bydev 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bydev/__init__.py +168 -0
- bydev/_api.py +157 -0
- bydev/_generated.py +271 -0
- bydev/_support.py +195 -0
- bydev/_tokens.py +131 -0
- bydev/_verifier.py +165 -0
- bydev/aio.py +55 -0
- bydev/client.py +160 -0
- bydev/defaults.py +117 -0
- bydev/errors.py +78 -0
- bydev/login.py +140 -0
- bydev/models.py +660 -0
- bydev/platform.py +403 -0
- bydev/ports.py +182 -0
- bydev/py.typed +0 -0
- bydev/server.py +90 -0
- bydev/session.py +556 -0
- bydev-0.1.0.dist-info/METADATA +185 -0
- bydev-0.1.0.dist-info/RECORD +22 -0
- bydev-0.1.0.dist-info/WHEEL +4 -0
- bydev-0.1.0.dist-info/licenses/LICENSE-APACHE +202 -0
- bydev-0.1.0.dist-info/licenses/LICENSE-MIT +21 -0
bydev/client.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""데브 라이선스 API 클라이언트(명세 1 · 5 · 7절)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from ._api import Api, ApiResponse, Req
|
|
11
|
+
from ._generated import Codes, Routes
|
|
12
|
+
from ._support import sha256_hex
|
|
13
|
+
from ._tokens import TokenManager
|
|
14
|
+
from ._verifier import Verifier
|
|
15
|
+
from .errors import BydevError
|
|
16
|
+
from .login import LoginAttempt
|
|
17
|
+
from .models import DeviceCode, DevicePage, DeviceRelease, Entitlement, LicenseClaims, Profile, UpdateCheck
|
|
18
|
+
from .ports import Ports, resolve
|
|
19
|
+
from .session import AppInfo, DeviceInfo, LicenseSession
|
|
20
|
+
|
|
21
|
+
SDK_VERSION = "0.1.0"
|
|
22
|
+
USER_AGENT = f"bydev-python/{SDK_VERSION}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Config:
|
|
27
|
+
"""명세 1절의 설정이다."""
|
|
28
|
+
|
|
29
|
+
base_url: str
|
|
30
|
+
client_id: str
|
|
31
|
+
product_id: str
|
|
32
|
+
scopes: Sequence[str]
|
|
33
|
+
#: 세션을 쓰면 필요하다(`bydev.platform.system_device_info()`).
|
|
34
|
+
device: DeviceInfo | None = None
|
|
35
|
+
ports: Ports = field(default_factory=Ports)
|
|
36
|
+
#: 실행 중인 앱의 배포 대상 · 버전이다 — 세션을 쓰면 넣는다(명세 1절 · ADR-0049). 위치 인수 순서를 지키려고 맨 뒤에 둔다.
|
|
37
|
+
app: AppInfo | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class LicenseClient:
|
|
41
|
+
"""데브 라이선스 API 클라이언트다. 서버 응답 하나의 참/거짓으로 기능을 열지 않는다 — `session()`의 상태와 검증된 토큰의 클레임을 쓴다.
|
|
42
|
+
|
|
43
|
+
**블로킹 API**다(asyncio는 `bydev.aio.AsyncLicenseClient`). 스레드 사이에 나눠 쓴다.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, config: Config) -> None:
|
|
47
|
+
if not config.scopes:
|
|
48
|
+
raise BydevError(Codes.CONFIGURATION, "scopes가 비었다")
|
|
49
|
+
self._config = config
|
|
50
|
+
self._api = Api(config.base_url, resolve(config.ports), USER_AGENT)
|
|
51
|
+
self._tokens = TokenManager(self._api, config.client_id)
|
|
52
|
+
self._verifier = Verifier(self._api, config.client_id, track_generations=True)
|
|
53
|
+
self._lock = threading.Lock()
|
|
54
|
+
self._login: LoginAttempt | None = None
|
|
55
|
+
self._session: LicenseSession | None = None
|
|
56
|
+
|
|
57
|
+
def start_login(self) -> LoginAttempt:
|
|
58
|
+
"""디바이스 로그인을 시작한다(명세 5절). 진행 중인 로그인은 취소한다."""
|
|
59
|
+
with self._lock:
|
|
60
|
+
previous, self._login = self._login, None
|
|
61
|
+
if previous is not None:
|
|
62
|
+
previous.cancel()
|
|
63
|
+
doc = self._api.discovery()
|
|
64
|
+
body = {"client_id": self._config.client_id, "scope": " ".join(self._config.scopes)}
|
|
65
|
+
res = self._api.send(Req("POST", doc.device_authorization_endpoint, body))
|
|
66
|
+
attempt = LoginAttempt(DeviceCode.read(res.json), self._config.client_id, self._api, self._tokens)
|
|
67
|
+
attempt.schedule_poll()
|
|
68
|
+
with self._lock:
|
|
69
|
+
self._login = attempt
|
|
70
|
+
return attempt
|
|
71
|
+
|
|
72
|
+
def has_credentials(self) -> bool:
|
|
73
|
+
"""저장된 로그인이 있는지다 — 이용 가능 여부가 아니다."""
|
|
74
|
+
return self._tokens.load() is not None
|
|
75
|
+
|
|
76
|
+
def _get(
|
|
77
|
+
self, path: str, params: dict[str, str] | None = None, query: Sequence[tuple[str, str]] = ()
|
|
78
|
+
) -> Any:
|
|
79
|
+
url = self._api.url(path, params, query)
|
|
80
|
+
res = self._tokens.authed(lambda bearer: self._api.send(Req("GET", url, bearer=bearer)))
|
|
81
|
+
self._note_lease(res)
|
|
82
|
+
return res.json
|
|
83
|
+
|
|
84
|
+
def _note_lease(self, res: ApiResponse) -> None:
|
|
85
|
+
with self._lock:
|
|
86
|
+
session = self._session
|
|
87
|
+
if session is not None:
|
|
88
|
+
session.note_lease(res.headers.get("x-lease-expires-at"))
|
|
89
|
+
|
|
90
|
+
def entitlement(self) -> Entitlement:
|
|
91
|
+
"""이 제품의 이용권이다."""
|
|
92
|
+
return Entitlement.read(self._get(Routes.GET_MY_ENTITLEMENT.path))
|
|
93
|
+
|
|
94
|
+
def devices(self, cursor: str | None = None, limit: int | None = None) -> DevicePage:
|
|
95
|
+
"""등록된 기기 한 쪽이다. 다음 쪽을 저절로 따라가지 않는다."""
|
|
96
|
+
query = []
|
|
97
|
+
if cursor:
|
|
98
|
+
query.append(("cursor", cursor))
|
|
99
|
+
if limit is not None and limit > 0:
|
|
100
|
+
query.append(("limit", str(limit)))
|
|
101
|
+
return DevicePage.read(self._get(Routes.LIST_DEVICES.path, query=query))
|
|
102
|
+
|
|
103
|
+
def release_device(self, device_id: str) -> DeviceRelease:
|
|
104
|
+
"""기기를 해제한다(월 횟수 제한)."""
|
|
105
|
+
key = self._api.ports.random.uuid()
|
|
106
|
+
url = self._api.url(Routes.RELEASE_DEVICE.path, {"deviceId": device_id})
|
|
107
|
+
res = self._tokens.authed(
|
|
108
|
+
lambda bearer: self._api.send(Req("DELETE", url, bearer=bearer, idempotency_key=key))
|
|
109
|
+
)
|
|
110
|
+
self._note_lease(res)
|
|
111
|
+
return DeviceRelease.read(res.json)
|
|
112
|
+
|
|
113
|
+
def profile(self) -> Profile:
|
|
114
|
+
"""닉네임과 가명 식별자다."""
|
|
115
|
+
return Profile.read(self._get(Routes.GET_PROFILE.path))
|
|
116
|
+
|
|
117
|
+
def check_for_update(self, target: str, current_version: str) -> UpdateCheck:
|
|
118
|
+
"""업데이트 확인이다. `update_status`가 `REQUIRED`면 업데이트 전까지 실행을 막는다. 받은 파일은 설치 전에 `verify_download`.
|
|
119
|
+
|
|
120
|
+
`entitled`가 있으면(업데이트 제공 기한이 있는 구매자) 최상위 대신 `entitled.release`를 따른다 — 범위 밖 버전을 설치하면 세션 획득이
|
|
121
|
+
거절된다.
|
|
122
|
+
"""
|
|
123
|
+
return UpdateCheck.read(
|
|
124
|
+
self._get(
|
|
125
|
+
Routes.GET_PRODUCT_UPDATES.path,
|
|
126
|
+
{"id": self._config.product_id},
|
|
127
|
+
[("target", target), ("currentVersion", current_version)],
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
def verify_download(self, data: bytes, sha256: str) -> None:
|
|
132
|
+
"""내려받은 파일의 SHA-256을 확인한다 — 다르면 `DOWNLOAD_INTEGRITY`."""
|
|
133
|
+
if sha256_hex(data) != sha256.lower():
|
|
134
|
+
raise BydevError(Codes.DOWNLOAD_INTEGRITY, "내려받은 파일의 SHA-256이 다르다 — 설치하지 않는다")
|
|
135
|
+
|
|
136
|
+
def verify_token(self, token: str) -> LicenseClaims:
|
|
137
|
+
"""licenseToken을 검증한다(명세 9절) — 앱이 기능 코드 여러 곳에서 다시 검증할 때."""
|
|
138
|
+
return self._verifier.verify_license(token, None, 0)
|
|
139
|
+
|
|
140
|
+
def logout(self) -> bool:
|
|
141
|
+
"""세션을 멈추고 폐기 요청을 한 번 보낸 뒤 기록을 지운다. 서버 폐기에 성공했는지를 돌려준다."""
|
|
142
|
+
with self._lock:
|
|
143
|
+
login, self._login = self._login, None
|
|
144
|
+
session = self._session
|
|
145
|
+
if login is not None:
|
|
146
|
+
login.cancel()
|
|
147
|
+
if session is not None:
|
|
148
|
+
session.stop()
|
|
149
|
+
return self._tokens.logout()
|
|
150
|
+
|
|
151
|
+
def session(self) -> LicenseSession:
|
|
152
|
+
"""이 클라이언트의 세션이다(하나뿐)."""
|
|
153
|
+
with self._lock:
|
|
154
|
+
if self._session is None:
|
|
155
|
+
if self._config.device is None:
|
|
156
|
+
raise BydevError(Codes.CONFIGURATION, "세션을 쓰려면 device(name, platform)를 준다")
|
|
157
|
+
self._session = LicenseSession(
|
|
158
|
+
self._api, self._tokens, self._verifier, self._config.device, self._config.app
|
|
159
|
+
)
|
|
160
|
+
return self._session
|
bydev/defaults.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""명세 2절 — 기본 구현. 운영체제 저장소 · 지문 출처는 앱이 고른다(`bydev.platform`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import secrets
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
import uuid as _uuid
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ._generated import Codes, Rules
|
|
15
|
+
from .errors import BydevError
|
|
16
|
+
from .ports import Cancel, CredentialRecord, HttpRequest, HttpResponse, Signal
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SystemClock:
|
|
20
|
+
"""시스템 시계 — SDK에서 시계를 직접 읽는 유일한 곳."""
|
|
21
|
+
|
|
22
|
+
def now_ms(self) -> int:
|
|
23
|
+
return time.time_ns() // 1_000_000
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ThreadScheduler:
|
|
27
|
+
"""데몬 스레드 스케줄러 — 예약마다 타이머 스레드 하나."""
|
|
28
|
+
|
|
29
|
+
def after(self, delay_ms: int, task: Callable[[], None]) -> Cancel:
|
|
30
|
+
timer = threading.Timer(max(0, delay_ms) / 1000, task)
|
|
31
|
+
timer.daemon = True
|
|
32
|
+
timer.start()
|
|
33
|
+
return Cancel(timer.cancel)
|
|
34
|
+
|
|
35
|
+
def sleep(self, ms: int) -> None:
|
|
36
|
+
time.sleep(max(0, ms) / 1000)
|
|
37
|
+
|
|
38
|
+
def wait(self, signal: Signal) -> None:
|
|
39
|
+
signal.block()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SecureRandom:
|
|
43
|
+
"""운영체제 난수(`secrets`)."""
|
|
44
|
+
|
|
45
|
+
def random(self) -> float:
|
|
46
|
+
return secrets.randbits(53) / (1 << 53)
|
|
47
|
+
|
|
48
|
+
def uuid(self) -> str:
|
|
49
|
+
return str(_uuid.uuid4())
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
53
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class UrllibTransport:
|
|
58
|
+
"""표준 `urllib` 전송 — 시간 초과 `Rules.HTTP_TIMEOUT_SEC`, 리다이렉트를 따라가지 않는다(3xx는 그대로 돌려준다)."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, timeout_sec: float = Rules.HTTP_TIMEOUT_SEC) -> None:
|
|
61
|
+
self._timeout = timeout_sec
|
|
62
|
+
self._opener = urllib.request.build_opener(_NoRedirect)
|
|
63
|
+
|
|
64
|
+
def send(self, request: HttpRequest) -> HttpResponse:
|
|
65
|
+
req = urllib.request.Request(
|
|
66
|
+
request.url, data=request.body, method=request.method, headers=request.headers
|
|
67
|
+
)
|
|
68
|
+
try:
|
|
69
|
+
with self._opener.open(req, timeout=self._timeout) as res:
|
|
70
|
+
return HttpResponse(res.status, {k.lower(): v for k, v in res.headers.items()}, res.read())
|
|
71
|
+
except urllib.error.HTTPError as e:
|
|
72
|
+
# 2xx가 아닌 응답(3xx 포함)도 응답이다
|
|
73
|
+
with e:
|
|
74
|
+
return HttpResponse(e.code, {k.lower(): v for k, v in e.headers.items()}, e.read())
|
|
75
|
+
except (urllib.error.URLError, OSError) as e:
|
|
76
|
+
error = BydevError(Codes.NETWORK_ERROR, "API에 연결하지 못했다")
|
|
77
|
+
raise error from e
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class MemoryCredentialStore:
|
|
81
|
+
"""메모리 저장소 — 앱을 끄면 로그인이 사라진다. 클라이언트의 기본값이다(운영체제 저장소는 `bydev.platform`에서 고른다)."""
|
|
82
|
+
|
|
83
|
+
def __init__(self, initial: CredentialRecord | None = None) -> None:
|
|
84
|
+
self._record = initial
|
|
85
|
+
self._lock = threading.Lock()
|
|
86
|
+
|
|
87
|
+
def load(self) -> CredentialRecord | None:
|
|
88
|
+
with self._lock:
|
|
89
|
+
return self._record
|
|
90
|
+
|
|
91
|
+
def save(self, record: CredentialRecord) -> None:
|
|
92
|
+
with self._lock:
|
|
93
|
+
self._record = record
|
|
94
|
+
|
|
95
|
+
def clear(self) -> None:
|
|
96
|
+
with self._lock:
|
|
97
|
+
self._record = None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class NoFingerprint:
|
|
101
|
+
"""지문 출처 없음 — SDK가 수명 동안의 난수 ID로 물러난다(경고 로그)."""
|
|
102
|
+
|
|
103
|
+
def read(self) -> str | None:
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class SilentLog:
|
|
108
|
+
"""아무것도 하지 않는 로그."""
|
|
109
|
+
|
|
110
|
+
def debug(self, message: str) -> None:
|
|
111
|
+
pass
|
|
112
|
+
|
|
113
|
+
def info(self, message: str) -> None:
|
|
114
|
+
pass
|
|
115
|
+
|
|
116
|
+
def warn(self, message: str) -> None:
|
|
117
|
+
pass
|
bydev/errors.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""SDK의 에러 하나(명세 3.3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from ._generated import Codes, Rules
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BydevError(Exception):
|
|
11
|
+
"""`code`로 분기하고(생성된 `Codes`) `message`는 보여 주기만 한다. 앱의 오류 화면에 `correlation_id`를 보이면 문의를 바로 찾는다."""
|
|
12
|
+
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
code: str,
|
|
16
|
+
message: str,
|
|
17
|
+
*,
|
|
18
|
+
http_status: int | None = None,
|
|
19
|
+
correlation_id: str | None = None,
|
|
20
|
+
retry_after_sec: int | None = None,
|
|
21
|
+
details: dict[str, Any] | None = None,
|
|
22
|
+
) -> None:
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.code = code
|
|
25
|
+
self.message = message
|
|
26
|
+
self.http_status = http_status
|
|
27
|
+
self.correlation_id = correlation_id
|
|
28
|
+
self.retry_after_sec = retry_after_sec
|
|
29
|
+
self.details = details
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def is_transient(self) -> bool:
|
|
33
|
+
"""일시적 실패인지다(명세 3.4). 아는 코드는 그 뜻대로 — 429인 한도 초과 코드는 끝난 실패 — 모르는 코드만 HTTP 상태로 나눈다."""
|
|
34
|
+
if self.code in Rules.TRANSIENT_CODES:
|
|
35
|
+
return True
|
|
36
|
+
if self.code in Codes.API_HTTP_STATUS or self.code in Codes.SDK:
|
|
37
|
+
return False
|
|
38
|
+
status = self.http_status
|
|
39
|
+
if status is None:
|
|
40
|
+
return False
|
|
41
|
+
return status in Rules.TRANSIENT_UNKNOWN_CODE_STATUSES or any(
|
|
42
|
+
lo <= status <= hi for lo, hi in Rules.TRANSIENT_UNKNOWN_CODE_STATUS_RANGES
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def to_dict(self) -> dict[str, Any]:
|
|
46
|
+
"""`{"code","message","httpStatus","correlationId","retryAfterSec","details"}` — 키는 언제나 다 있다(없는 값은 None)."""
|
|
47
|
+
return {
|
|
48
|
+
"code": self.code,
|
|
49
|
+
"message": self.message,
|
|
50
|
+
"httpStatus": self.http_status,
|
|
51
|
+
"correlationId": self.correlation_id,
|
|
52
|
+
"retryAfterSec": self.retry_after_sec,
|
|
53
|
+
"details": self.details,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
def __str__(self) -> str:
|
|
57
|
+
return f"{self.code}: {self.message}"
|
|
58
|
+
|
|
59
|
+
def __repr__(self) -> str:
|
|
60
|
+
return f"BydevError({self.code!r}, {self.message!r})"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def wrap(error: BaseException, code: str, message: str) -> BydevError:
|
|
64
|
+
"""포트가 던진 에러를 `code`로 감싼다 — 이미 `BydevError`면 그대로."""
|
|
65
|
+
if isinstance(error, BydevError):
|
|
66
|
+
return error
|
|
67
|
+
wrapped = BydevError(code, message)
|
|
68
|
+
wrapped.__cause__ = error
|
|
69
|
+
return wrapped
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def storage(error: BaseException, message: str) -> BydevError:
|
|
73
|
+
"""저장소 실패는 언제나 `STORAGE_FAILED`(명세 2절)."""
|
|
74
|
+
if isinstance(error, BydevError) and error.code == Codes.STORAGE_FAILED:
|
|
75
|
+
return error
|
|
76
|
+
wrapped = BydevError(Codes.STORAGE_FAILED, message)
|
|
77
|
+
wrapped.__cause__ = error
|
|
78
|
+
return wrapped
|
bydev/login.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""명세 5절 — 디바이스 로그인. 코드를 받은 순간부터 폴링하고 `wait()`는 그 결과를 기다린다."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ._api import Api, ApiResponse, Req
|
|
10
|
+
from ._generated import Codes, Rules, Spec
|
|
11
|
+
from ._support import format_iso, jittered
|
|
12
|
+
from ._tokens import TokenManager
|
|
13
|
+
from .errors import BydevError, wrap
|
|
14
|
+
from .models import DeviceCode, TokenSet
|
|
15
|
+
from .ports import Cancel, Signal
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class LoginResult:
|
|
20
|
+
"""로그인이 끝났을 때 받은 스코프다."""
|
|
21
|
+
|
|
22
|
+
scope: str
|
|
23
|
+
|
|
24
|
+
def to_dict(self) -> dict[str, Any]:
|
|
25
|
+
return {"scope": self.scope}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class LoginAttempt:
|
|
29
|
+
"""디바이스 플로우 하나다. 화면에 `user_code` · `verification_uri_complete`(QR)를 보이고 `wait()`로 기다린다."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, code: DeviceCode, client_id: str, api: Api, tokens: TokenManager) -> None:
|
|
32
|
+
self._expires_at_ms = api.ports.clock.now_ms() + code.expires_in * 1000
|
|
33
|
+
self.user_code = code.user_code
|
|
34
|
+
self.verification_uri = code.verification_uri
|
|
35
|
+
self.verification_uri_complete = code.verification_uri_complete
|
|
36
|
+
#: 코드가 만료되는 시각(ISO 8601).
|
|
37
|
+
self.expires_at = format_iso(self._expires_at_ms)
|
|
38
|
+
self._device_code = code.device_code
|
|
39
|
+
self._client_id = client_id
|
|
40
|
+
self._api = api
|
|
41
|
+
self._tokens = tokens
|
|
42
|
+
self._done = Signal()
|
|
43
|
+
self._lock = threading.Lock()
|
|
44
|
+
self._interval = code.interval
|
|
45
|
+
self._settled = False
|
|
46
|
+
self._handle: Cancel | None = None
|
|
47
|
+
self._result: LoginResult | BydevError | None = None
|
|
48
|
+
|
|
49
|
+
def wait(self) -> LoginResult:
|
|
50
|
+
"""로그인이 끝나기를 기다린다(블로킹). 실패는 `BydevError`(`EXPIRED_TOKEN` · `INVALID_GRANT` · `LOGIN_CANCELLED` · `STORAGE_FAILED` …)."""
|
|
51
|
+
self._api.ports.scheduler.wait(self._done)
|
|
52
|
+
with self._lock:
|
|
53
|
+
result = self._result
|
|
54
|
+
if isinstance(result, LoginResult):
|
|
55
|
+
return result
|
|
56
|
+
raise result or BydevError(Codes.LOGIN_CANCELLED, "로그인을 취소했다")
|
|
57
|
+
|
|
58
|
+
def cancel(self) -> None:
|
|
59
|
+
"""로그인을 취소한다 — `wait()`는 `LOGIN_CANCELLED`로 끝난다."""
|
|
60
|
+
self._finish(BydevError(Codes.LOGIN_CANCELLED, "로그인을 취소했다"))
|
|
61
|
+
|
|
62
|
+
def _finish(self, result: LoginResult | BydevError) -> None:
|
|
63
|
+
with self._lock:
|
|
64
|
+
if self._settled:
|
|
65
|
+
return
|
|
66
|
+
self._settled = True
|
|
67
|
+
self._result = result
|
|
68
|
+
handle, self._handle = self._handle, None
|
|
69
|
+
if handle is not None:
|
|
70
|
+
handle.cancel()
|
|
71
|
+
self._done.fire()
|
|
72
|
+
|
|
73
|
+
def _is_settled(self) -> bool:
|
|
74
|
+
with self._lock:
|
|
75
|
+
return self._settled
|
|
76
|
+
|
|
77
|
+
def schedule_poll(self, retry_after_sec: int = 0) -> None:
|
|
78
|
+
"""폴링 지터는 위로만(interval보다 이르면 SLOW_DOWN이다). 429면 retry_after_sec보다 이르게 묻지 않는다(명세 5절)."""
|
|
79
|
+
ports = self._api.ports
|
|
80
|
+
with self._lock:
|
|
81
|
+
interval = self._interval
|
|
82
|
+
delay = max(
|
|
83
|
+
jittered(
|
|
84
|
+
ports.random,
|
|
85
|
+
max(0, interval) * 1000,
|
|
86
|
+
Rules.LOGIN_POLL_JITTER_MIN,
|
|
87
|
+
Rules.LOGIN_POLL_JITTER_MAX,
|
|
88
|
+
),
|
|
89
|
+
retry_after_sec * 1000,
|
|
90
|
+
)
|
|
91
|
+
if ports.clock.now_ms() + delay > self._expires_at_ms:
|
|
92
|
+
self._finish(BydevError(Codes.EXPIRED_TOKEN, "로그인 코드가 만료됐다 — 처음부터 다시"))
|
|
93
|
+
return
|
|
94
|
+
handle = ports.scheduler.after(delay, self._poll)
|
|
95
|
+
with self._lock:
|
|
96
|
+
late = self._settled
|
|
97
|
+
if not late:
|
|
98
|
+
self._handle = handle
|
|
99
|
+
if late:
|
|
100
|
+
handle.cancel()
|
|
101
|
+
|
|
102
|
+
def _poll(self) -> None:
|
|
103
|
+
if self._is_settled():
|
|
104
|
+
return
|
|
105
|
+
outcome: ApiResponse | BydevError
|
|
106
|
+
try:
|
|
107
|
+
doc = self._api.discovery()
|
|
108
|
+
body = {
|
|
109
|
+
"grant_type": Spec.DEVICE_CODE_GRANT_TYPE,
|
|
110
|
+
"client_id": self._client_id,
|
|
111
|
+
"device_code": self._device_code,
|
|
112
|
+
}
|
|
113
|
+
outcome = self._api.send(Req("POST", doc.token_endpoint, body))
|
|
114
|
+
except Exception as e:
|
|
115
|
+
outcome = wrap(e, Codes.NETWORK_ERROR, "API에 연결하지 못했다")
|
|
116
|
+
if self._is_settled():
|
|
117
|
+
return
|
|
118
|
+
if isinstance(outcome, ApiResponse):
|
|
119
|
+
try:
|
|
120
|
+
tokens = TokenSet.read(outcome.json)
|
|
121
|
+
self._tokens.adopt(tokens)
|
|
122
|
+
self._finish(LoginResult(tokens.scope))
|
|
123
|
+
except BydevError as e:
|
|
124
|
+
self._finish(e)
|
|
125
|
+
return
|
|
126
|
+
error = outcome
|
|
127
|
+
if error.code == Codes.AUTHORIZATION_PENDING:
|
|
128
|
+
self.schedule_poll()
|
|
129
|
+
elif error.is_transient:
|
|
130
|
+
limited = error.code == Codes.RATE_LIMITED or error.http_status == 429
|
|
131
|
+
self.schedule_poll((error.retry_after_sec or 0) if limited else 0)
|
|
132
|
+
elif error.code == Codes.SLOW_DOWN:
|
|
133
|
+
with self._lock:
|
|
134
|
+
n = error.retry_after_sec
|
|
135
|
+
self._interval = (
|
|
136
|
+
n if n is not None and n > 0 else self._interval + Rules.LOGIN_SLOW_DOWN_INCREMENT_SEC
|
|
137
|
+
)
|
|
138
|
+
self.schedule_poll()
|
|
139
|
+
else:
|
|
140
|
+
self._finish(error)
|