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/session.py
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
"""명세 8절 — 라이선스 세션(실행 리스) 상태 기계. 참/거짓 하나로 이용 가능을 알리지 않는다."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import threading
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, ClassVar
|
|
10
|
+
|
|
11
|
+
from ._api import Api, Req
|
|
12
|
+
from ._generated import Codes, NeedsDecisionReason, Routes, Rules, SessionStateType
|
|
13
|
+
from ._support import jittered, parse_iso, seconds, sha256_hex
|
|
14
|
+
from ._tokens import TokenManager
|
|
15
|
+
from ._verifier import Expectation, Verifier
|
|
16
|
+
from .errors import BydevError, wrap
|
|
17
|
+
from .models import LicenseClaims, LicenseTokenInfo, SessionInfo, read_session_response
|
|
18
|
+
from .ports import Cancel
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class ErrorView:
|
|
23
|
+
"""상태에 싣는 에러다(값으로 비교한다)."""
|
|
24
|
+
|
|
25
|
+
code: str
|
|
26
|
+
message: str
|
|
27
|
+
http_status: int | None
|
|
28
|
+
correlation_id: str | None
|
|
29
|
+
retry_after_sec: int | None
|
|
30
|
+
details: dict[str, Any] | None
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def of(e: BydevError) -> ErrorView:
|
|
34
|
+
return ErrorView(e.code, e.message, e.http_status, e.correlation_id, e.retry_after_sec, e.details)
|
|
35
|
+
|
|
36
|
+
def to_dict(self) -> dict[str, Any]:
|
|
37
|
+
return {
|
|
38
|
+
"code": self.code,
|
|
39
|
+
"message": self.message,
|
|
40
|
+
"httpStatus": self.http_status,
|
|
41
|
+
"correlationId": self.correlation_id,
|
|
42
|
+
"retryAfterSec": self.retry_after_sec,
|
|
43
|
+
"details": self.details,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class ActiveSession:
|
|
49
|
+
"""지금 쓰는 다른 기기(인수 판단에 보인다)."""
|
|
50
|
+
|
|
51
|
+
device_id: str
|
|
52
|
+
device_name: str
|
|
53
|
+
last_seen_at: str
|
|
54
|
+
|
|
55
|
+
def to_dict(self) -> dict[str, Any]:
|
|
56
|
+
return {"deviceId": self.device_id, "deviceName": self.device_name, "lastSeenAt": self.last_seen_at}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _err(e: ErrorView | None) -> dict[str, Any] | None:
|
|
60
|
+
return e.to_dict() if e else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class Starting:
|
|
65
|
+
"""획득 중."""
|
|
66
|
+
|
|
67
|
+
TYPE: ClassVar[str] = SessionStateType.STARTING
|
|
68
|
+
attempt: int
|
|
69
|
+
last_error: ErrorView | None
|
|
70
|
+
|
|
71
|
+
def to_dict(self) -> dict[str, Any]:
|
|
72
|
+
return {"type": self.TYPE, "attempt": self.attempt, "lastError": _err(self.last_error)}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class Active:
|
|
77
|
+
"""리스를 쥔 상태 — 기능 코드는 `claims`(exp · sid)를 쓴다."""
|
|
78
|
+
|
|
79
|
+
TYPE: ClassVar[str] = SessionStateType.ACTIVE
|
|
80
|
+
session: SessionInfo
|
|
81
|
+
license_token: LicenseTokenInfo
|
|
82
|
+
claims: LicenseClaims
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict[str, Any]:
|
|
85
|
+
return {
|
|
86
|
+
"type": self.TYPE,
|
|
87
|
+
"session": self.session.to_dict(),
|
|
88
|
+
"licenseToken": self.license_token.to_dict(),
|
|
89
|
+
"claims": self.claims.to_dict(),
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class Degraded:
|
|
95
|
+
"""하트비트가 실패하는 중 — `offline_until`까지는 계속 쓸 수 있다."""
|
|
96
|
+
|
|
97
|
+
TYPE: ClassVar[str] = SessionStateType.DEGRADED
|
|
98
|
+
session: SessionInfo
|
|
99
|
+
license_token: LicenseTokenInfo
|
|
100
|
+
claims: LicenseClaims
|
|
101
|
+
consecutive_failures: int
|
|
102
|
+
offline_until: str
|
|
103
|
+
last_error: ErrorView | None
|
|
104
|
+
|
|
105
|
+
def to_dict(self) -> dict[str, Any]:
|
|
106
|
+
return {
|
|
107
|
+
"type": self.TYPE,
|
|
108
|
+
"session": self.session.to_dict(),
|
|
109
|
+
"licenseToken": self.license_token.to_dict(),
|
|
110
|
+
"claims": self.claims.to_dict(),
|
|
111
|
+
"consecutiveFailures": self.consecutive_failures,
|
|
112
|
+
"offlineUntil": self.offline_until,
|
|
113
|
+
"lastError": _err(self.last_error),
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class NeedsDecision:
|
|
119
|
+
"""사용자 판단이 필요하다 — `DEVICE_IN_USE` · `INSTANCE_ALREADY_RUNNING`은 `take_over()`, `DEVICE_LIMIT_EXCEEDED`는 기기 해제 뒤 `retry()`."""
|
|
120
|
+
|
|
121
|
+
TYPE: ClassVar[str] = SessionStateType.NEEDS_DECISION
|
|
122
|
+
reason: str
|
|
123
|
+
active_session: ActiveSession | None
|
|
124
|
+
max_devices: int | None
|
|
125
|
+
correlation_id: str | None
|
|
126
|
+
|
|
127
|
+
def to_dict(self) -> dict[str, Any]:
|
|
128
|
+
return {
|
|
129
|
+
"type": self.TYPE,
|
|
130
|
+
"reason": self.reason,
|
|
131
|
+
"activeSession": self.active_session.to_dict() if self.active_session else None,
|
|
132
|
+
"maxDevices": self.max_devices,
|
|
133
|
+
"correlationId": self.correlation_id,
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class Locked:
|
|
139
|
+
"""잠금 — 오류 화면에 `correlation_id`를 보인다. `retrying`이면 스스로 풀릴 수 있다(OFFLINE_EXPIRED)."""
|
|
140
|
+
|
|
141
|
+
TYPE: ClassVar[str] = SessionStateType.LOCKED
|
|
142
|
+
code: str
|
|
143
|
+
message: str
|
|
144
|
+
correlation_id: str | None
|
|
145
|
+
details: dict[str, Any] | None
|
|
146
|
+
retrying: bool
|
|
147
|
+
|
|
148
|
+
def to_dict(self) -> dict[str, Any]:
|
|
149
|
+
return {
|
|
150
|
+
"type": self.TYPE,
|
|
151
|
+
"code": self.code,
|
|
152
|
+
"message": self.message,
|
|
153
|
+
"correlationId": self.correlation_id,
|
|
154
|
+
"details": self.details,
|
|
155
|
+
"retrying": self.retrying,
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True)
|
|
160
|
+
class Stopped:
|
|
161
|
+
"""멈춤."""
|
|
162
|
+
|
|
163
|
+
TYPE: ClassVar[str] = SessionStateType.STOPPED
|
|
164
|
+
|
|
165
|
+
def to_dict(self) -> dict[str, Any]:
|
|
166
|
+
return {"type": self.TYPE}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
#: 세션 상태(판별 유니온, 명세 8.1절) — `match state: case Active(claims=c): …`
|
|
170
|
+
SessionState = Starting | Active | Degraded | NeedsDecision | Locked | Stopped
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass(frozen=True)
|
|
174
|
+
class DeviceInfo:
|
|
175
|
+
"""세션 획득 때 보내는 기기 정보다(`platform`은 `DevicePlatform`)."""
|
|
176
|
+
|
|
177
|
+
name: str
|
|
178
|
+
platform: str
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True)
|
|
182
|
+
class AppInfo:
|
|
183
|
+
"""실행 중인 앱이다(명세 1절 · ADR-0049) — 배포 대상(업데이트 확인의 `target`과 같은 값, `DistributionTarget`)과 콘솔에 업로드한 버전 문자열.
|
|
184
|
+
|
|
185
|
+
세션 획득에 싣는다. 업데이트 제공 기한이 있는 영구 이용권은 이 값이 없으면 획득이 `ENTITLEMENT_VERSION_NOT_COVERED`로 거절된다.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
target: str
|
|
189
|
+
version: str
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class Subscription:
|
|
193
|
+
"""구독 — `unsubscribe()`로 끊는다."""
|
|
194
|
+
|
|
195
|
+
def __init__(self, on_cancel: Callable[[], None]) -> None:
|
|
196
|
+
self._on_cancel = on_cancel
|
|
197
|
+
|
|
198
|
+
def unsubscribe(self) -> None:
|
|
199
|
+
self._on_cancel()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class LicenseSession:
|
|
203
|
+
"""라이선스 세션이다. `start` · `take_over` · `retry` · `stop`과 상태 구독. 구독 함수는 SDK의 스레드에서 불린다 — UI 스레드로 넘긴다."""
|
|
204
|
+
|
|
205
|
+
def __init__(
|
|
206
|
+
self,
|
|
207
|
+
api: Api,
|
|
208
|
+
tokens: TokenManager,
|
|
209
|
+
verifier: Verifier,
|
|
210
|
+
device: DeviceInfo,
|
|
211
|
+
app: AppInfo | None = None,
|
|
212
|
+
) -> None:
|
|
213
|
+
self._api = api
|
|
214
|
+
self._tokens = tokens
|
|
215
|
+
self._verifier = verifier
|
|
216
|
+
self._device = device
|
|
217
|
+
self._app = app
|
|
218
|
+
self._lock = threading.Lock()
|
|
219
|
+
self._current: SessionState = Stopped()
|
|
220
|
+
self._listeners: dict[int, Callable[[SessionState], None]] = {}
|
|
221
|
+
self._next_listener = 0
|
|
222
|
+
self._run = 0
|
|
223
|
+
self._instance = ""
|
|
224
|
+
self._held: Active | None = None
|
|
225
|
+
self._failures = 0
|
|
226
|
+
self._heartbeat: Cancel | None = None
|
|
227
|
+
self._offline: Cancel | None = None
|
|
228
|
+
self._fallback: str | None = None
|
|
229
|
+
# 처음 계산한 지문 해시 — 한 실행 동안 다시 쓴다(명세 10절). 획득마다 다시 읽으면 일시적인 읽기 실패 하나로 다른 기기가 된다
|
|
230
|
+
self._fingerprint: str | None = None
|
|
231
|
+
|
|
232
|
+
def _cancel_timers(self) -> None:
|
|
233
|
+
for timer in (self._heartbeat, self._offline):
|
|
234
|
+
if timer is not None:
|
|
235
|
+
timer.cancel()
|
|
236
|
+
self._heartbeat = self._offline = None
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def state(self) -> SessionState:
|
|
240
|
+
"""지금 상태다."""
|
|
241
|
+
with self._lock:
|
|
242
|
+
return self._current
|
|
243
|
+
|
|
244
|
+
def subscribe(self, listener: Callable[[SessionState], None]) -> Subscription:
|
|
245
|
+
"""상태가 바뀔 때마다 부른다."""
|
|
246
|
+
with self._lock:
|
|
247
|
+
key = self._next_listener
|
|
248
|
+
self._next_listener += 1
|
|
249
|
+
self._listeners[key] = listener
|
|
250
|
+
|
|
251
|
+
def cancel() -> None:
|
|
252
|
+
with self._lock:
|
|
253
|
+
self._listeners.pop(key, None)
|
|
254
|
+
|
|
255
|
+
return Subscription(cancel)
|
|
256
|
+
|
|
257
|
+
def start(self) -> None:
|
|
258
|
+
"""`Stopped`에서만 의미가 있다(8.2절)."""
|
|
259
|
+
with self._lock:
|
|
260
|
+
if not isinstance(self._current, Stopped):
|
|
261
|
+
return
|
|
262
|
+
self._run += 1
|
|
263
|
+
self._instance = self._api.ports.random.uuid()
|
|
264
|
+
self._begin_acquire(force=False, last_error=None)
|
|
265
|
+
|
|
266
|
+
def take_over(self) -> None:
|
|
267
|
+
"""`NeedsDecision`(다른 기기 · 같은 기기 실행 중) 또는 `Locked(SESSION_SUPERSEDED)`에서 인수한다 — 새 Idempotency-Key."""
|
|
268
|
+
s = self.state
|
|
269
|
+
allowed = (
|
|
270
|
+
isinstance(s, NeedsDecision) and s.reason != NeedsDecisionReason.DEVICE_LIMIT_EXCEEDED
|
|
271
|
+
) or (isinstance(s, Locked) and s.code == Codes.SESSION_SUPERSEDED)
|
|
272
|
+
if allowed:
|
|
273
|
+
with self._lock:
|
|
274
|
+
self._run += 1
|
|
275
|
+
self._begin_acquire(force=True, last_error=None)
|
|
276
|
+
|
|
277
|
+
def retry(self) -> None:
|
|
278
|
+
"""`NeedsDecision`(기기 수) 또는 스스로 풀리지 않는 `Locked`에서 다시 얻는다."""
|
|
279
|
+
s = self.state
|
|
280
|
+
allowed = (
|
|
281
|
+
isinstance(s, NeedsDecision) and s.reason == NeedsDecisionReason.DEVICE_LIMIT_EXCEEDED
|
|
282
|
+
) or (isinstance(s, Locked) and not s.retrying)
|
|
283
|
+
if allowed:
|
|
284
|
+
with self._lock:
|
|
285
|
+
self._run += 1
|
|
286
|
+
self._begin_acquire(force=False, last_error=None)
|
|
287
|
+
|
|
288
|
+
def stop(self) -> None:
|
|
289
|
+
"""예약을 모두 취소하고 반납을 한 번 보낸다(8.7절, 블로킹). 진행 중인 요청의 결과는 버린다."""
|
|
290
|
+
with self._lock:
|
|
291
|
+
if isinstance(self._current, Stopped):
|
|
292
|
+
return
|
|
293
|
+
self._run += 1
|
|
294
|
+
self._cancel_timers()
|
|
295
|
+
self._instance = ""
|
|
296
|
+
sid = self._held.session.id if self._held else None
|
|
297
|
+
self._held = None
|
|
298
|
+
if sid is not None:
|
|
299
|
+
url = self._api.url(Routes.RELEASE_SESSION.path, {"sid": sid})
|
|
300
|
+
try:
|
|
301
|
+
self._tokens.authed(lambda bearer: self._api.send(Req("DELETE", url, bearer=bearer)))
|
|
302
|
+
except BydevError:
|
|
303
|
+
self._api.ports.logger.debug("세션 반납을 보내지 못했다 — 리스가 저절로 빈다")
|
|
304
|
+
self._set_state(Stopped())
|
|
305
|
+
|
|
306
|
+
def note_lease(self, value: str | None) -> None:
|
|
307
|
+
"""8.5절 — 다른 인증 응답의 `X-Lease-Expires-At`."""
|
|
308
|
+
if not value:
|
|
309
|
+
return
|
|
310
|
+
with self._lock:
|
|
311
|
+
held, current = self._held, self._current
|
|
312
|
+
if held is None or not isinstance(current, Active | Degraded):
|
|
313
|
+
return
|
|
314
|
+
if current.session.lease_expires_at == value:
|
|
315
|
+
return
|
|
316
|
+
session = dataclasses.replace(current.session, lease_expires_at=value)
|
|
317
|
+
nxt: SessionState = dataclasses.replace(current, session=session)
|
|
318
|
+
self._held = dataclasses.replace(
|
|
319
|
+
held, session=dataclasses.replace(held.session, lease_expires_at=value)
|
|
320
|
+
)
|
|
321
|
+
self._set_state(nxt)
|
|
322
|
+
|
|
323
|
+
# ── 안 ──────────────────────────────────────────────────────
|
|
324
|
+
|
|
325
|
+
def _set_state(self, nxt: SessionState) -> None:
|
|
326
|
+
with self._lock:
|
|
327
|
+
if self._current == nxt:
|
|
328
|
+
return
|
|
329
|
+
self._current = nxt
|
|
330
|
+
targets = list(self._listeners.values())
|
|
331
|
+
for listener in targets:
|
|
332
|
+
listener(nxt)
|
|
333
|
+
|
|
334
|
+
def _live(self, run: int) -> bool:
|
|
335
|
+
with self._lock:
|
|
336
|
+
return self._run == run
|
|
337
|
+
|
|
338
|
+
def _after(self, delay_ms: int, task: Callable[[], None]) -> None:
|
|
339
|
+
handle = self._api.ports.scheduler.after(delay_ms, task)
|
|
340
|
+
with self._lock:
|
|
341
|
+
old, self._heartbeat = self._heartbeat, handle
|
|
342
|
+
if old is not None:
|
|
343
|
+
old.cancel()
|
|
344
|
+
|
|
345
|
+
def _begin_acquire(self, *, force: bool, last_error: BydevError | None) -> None:
|
|
346
|
+
with self._lock:
|
|
347
|
+
self._cancel_timers()
|
|
348
|
+
self._held = None
|
|
349
|
+
self._failures = 0
|
|
350
|
+
run = self._run
|
|
351
|
+
self._set_state(Starting(0, ErrorView.of(last_error) if last_error else None))
|
|
352
|
+
key = self._api.ports.random.uuid()
|
|
353
|
+
self._after(0, lambda: self._acquire(run, force, key, 0))
|
|
354
|
+
|
|
355
|
+
def _fingerprint_hash(self) -> str:
|
|
356
|
+
with self._lock:
|
|
357
|
+
if self._fingerprint is not None:
|
|
358
|
+
return self._fingerprint
|
|
359
|
+
computed = self._compute_fingerprint_hash()
|
|
360
|
+
with self._lock:
|
|
361
|
+
if self._fingerprint is None: # 동시에 계산했으면 먼저 정한 값
|
|
362
|
+
self._fingerprint = computed
|
|
363
|
+
return self._fingerprint
|
|
364
|
+
|
|
365
|
+
def _compute_fingerprint_hash(self) -> str:
|
|
366
|
+
ports = self._api.ports
|
|
367
|
+
try:
|
|
368
|
+
source = ports.fingerprint.read()
|
|
369
|
+
except Exception:
|
|
370
|
+
source = None
|
|
371
|
+
value = (source or "").strip()
|
|
372
|
+
if not value:
|
|
373
|
+
with self._lock:
|
|
374
|
+
if self._fallback is None:
|
|
375
|
+
ports.logger.warn(
|
|
376
|
+
"기기 지문 출처를 읽지 못해 이번 실행 동안만 쓰는 ID를 쓴다 — 출처 포트를 준다(명세 10절)"
|
|
377
|
+
)
|
|
378
|
+
self._fallback = ports.random.uuid()
|
|
379
|
+
value = self._fallback
|
|
380
|
+
return sha256_hex((value + Rules.FINGERPRINT_SALT).encode())
|
|
381
|
+
|
|
382
|
+
def _acquire(self, run: int, force: bool, key: str, attempt: int) -> None:
|
|
383
|
+
"""8.2절. 일시적 실패의 재시도는 같은 키."""
|
|
384
|
+
if not self._live(run):
|
|
385
|
+
return
|
|
386
|
+
with self._lock:
|
|
387
|
+
instance = self._instance
|
|
388
|
+
body: dict[str, Any] = {
|
|
389
|
+
"device": {
|
|
390
|
+
"fingerprintHash": self._fingerprint_hash(),
|
|
391
|
+
"name": self._device.name,
|
|
392
|
+
"platform": self._device.platform,
|
|
393
|
+
},
|
|
394
|
+
"instanceId": instance,
|
|
395
|
+
"force": force,
|
|
396
|
+
}
|
|
397
|
+
if self._app is not None:
|
|
398
|
+
body["app"] = {"target": self._app.target, "version": self._app.version}
|
|
399
|
+
url = self._api.url(Routes.ACQUIRE_SESSION.path)
|
|
400
|
+
try:
|
|
401
|
+
res = self._tokens.authed(
|
|
402
|
+
lambda bearer: self._api.send(Req("POST", url, body, bearer=bearer, idempotency_key=key))
|
|
403
|
+
)
|
|
404
|
+
if not self._live(run):
|
|
405
|
+
return
|
|
406
|
+
self._adopt(run, res.json)
|
|
407
|
+
return
|
|
408
|
+
except Exception as e:
|
|
409
|
+
if not self._live(run):
|
|
410
|
+
return
|
|
411
|
+
error = wrap(e, Codes.PROTOCOL_ERROR, "세션 응답을 읽지 못했다")
|
|
412
|
+
if error.is_transient:
|
|
413
|
+
delays = Rules.SESSION_START_RETRY_DELAYS_SEC
|
|
414
|
+
base = delays[min(attempt, len(delays) - 1)]
|
|
415
|
+
self._set_state(Starting(attempt + 1, ErrorView.of(error)))
|
|
416
|
+
delay = jittered(
|
|
417
|
+
self._api.ports.random,
|
|
418
|
+
seconds(base),
|
|
419
|
+
Rules.SESSION_HEARTBEAT_JITTER_MIN,
|
|
420
|
+
Rules.SESSION_HEARTBEAT_JITTER_MAX,
|
|
421
|
+
)
|
|
422
|
+
self._after(delay, lambda: self._acquire(run, force, key, attempt + 1))
|
|
423
|
+
elif error.code in Rules.NEEDS_DECISION_REASONS:
|
|
424
|
+
details = error.details or {}
|
|
425
|
+
raw = details.get("activeSession")
|
|
426
|
+
active_session = (
|
|
427
|
+
ActiveSession(
|
|
428
|
+
str(raw.get("deviceId", "")),
|
|
429
|
+
str(raw.get("deviceName", "")),
|
|
430
|
+
str(raw.get("lastSeenAt", "")),
|
|
431
|
+
)
|
|
432
|
+
if isinstance(raw, dict)
|
|
433
|
+
else None
|
|
434
|
+
)
|
|
435
|
+
max_devices = details.get("maxDevices")
|
|
436
|
+
self._set_state(
|
|
437
|
+
NeedsDecision(
|
|
438
|
+
error.code,
|
|
439
|
+
active_session,
|
|
440
|
+
int(max_devices) if isinstance(max_devices, int | float) else None,
|
|
441
|
+
error.correlation_id,
|
|
442
|
+
)
|
|
443
|
+
)
|
|
444
|
+
else:
|
|
445
|
+
self._lock_with(error, retrying=False)
|
|
446
|
+
|
|
447
|
+
def _adopt(self, run: int, json: Any) -> None:
|
|
448
|
+
"""200 응답 → 검증(9절) → Active → 다음 하트비트."""
|
|
449
|
+
session, token = read_session_response(json)
|
|
450
|
+
claims = self._verifier.verify_license(
|
|
451
|
+
token.token, Expectation(session.id, session.device_id, session.generation), 0
|
|
452
|
+
)
|
|
453
|
+
if not self._live(run):
|
|
454
|
+
return
|
|
455
|
+
active = Active(session, token, claims)
|
|
456
|
+
with self._lock:
|
|
457
|
+
self._held = active
|
|
458
|
+
self._failures = 0
|
|
459
|
+
offline, self._offline = self._offline, None
|
|
460
|
+
if offline is not None:
|
|
461
|
+
offline.cancel()
|
|
462
|
+
self._set_state(active)
|
|
463
|
+
self._schedule_heartbeat(run, session.heartbeat_sec, 0)
|
|
464
|
+
|
|
465
|
+
def _schedule_heartbeat(self, run: int, heartbeat_sec: int, retry_after_sec: int) -> None:
|
|
466
|
+
delay = max(
|
|
467
|
+
jittered(
|
|
468
|
+
self._api.ports.random,
|
|
469
|
+
max(0, heartbeat_sec) * 1000,
|
|
470
|
+
Rules.SESSION_HEARTBEAT_JITTER_MIN,
|
|
471
|
+
Rules.SESSION_HEARTBEAT_JITTER_MAX,
|
|
472
|
+
),
|
|
473
|
+
retry_after_sec * 1000,
|
|
474
|
+
)
|
|
475
|
+
self._after(delay, lambda: self._beat(run))
|
|
476
|
+
|
|
477
|
+
def _beat(self, run: int) -> None:
|
|
478
|
+
"""8.3절 하트비트."""
|
|
479
|
+
with self._lock:
|
|
480
|
+
held = self._held if self._run == run else None
|
|
481
|
+
if held is None:
|
|
482
|
+
return
|
|
483
|
+
url = self._api.url(Routes.HEARTBEAT_SESSION.path, {"sid": held.session.id})
|
|
484
|
+
body = {"generation": held.session.generation}
|
|
485
|
+
try:
|
|
486
|
+
res = self._tokens.authed(lambda bearer: self._api.send(Req("POST", url, body, bearer=bearer)))
|
|
487
|
+
if not self._live(run):
|
|
488
|
+
return
|
|
489
|
+
self._adopt(run, res.json)
|
|
490
|
+
return
|
|
491
|
+
except Exception as e:
|
|
492
|
+
if not self._live(run):
|
|
493
|
+
return
|
|
494
|
+
error = wrap(e, Codes.PROTOCOL_ERROR, "세션 응답을 읽지 못했다")
|
|
495
|
+
if error.is_transient:
|
|
496
|
+
with self._lock:
|
|
497
|
+
self._failures += 1
|
|
498
|
+
failures = self._failures
|
|
499
|
+
holding = isinstance(self._current, Active | Degraded)
|
|
500
|
+
if holding:
|
|
501
|
+
offline_until = held.license_token.expires_at
|
|
502
|
+
self._set_state(
|
|
503
|
+
Degraded(
|
|
504
|
+
held.session,
|
|
505
|
+
held.license_token,
|
|
506
|
+
held.claims,
|
|
507
|
+
failures,
|
|
508
|
+
offline_until,
|
|
509
|
+
ErrorView.of(error),
|
|
510
|
+
)
|
|
511
|
+
)
|
|
512
|
+
self._arm_offline_expiry(run, offline_until)
|
|
513
|
+
retry = (
|
|
514
|
+
error.retry_after_sec or 0
|
|
515
|
+
if error.code == Codes.RATE_LIMITED or error.http_status == 429
|
|
516
|
+
else 0
|
|
517
|
+
)
|
|
518
|
+
self._schedule_heartbeat(run, held.session.heartbeat_sec, retry)
|
|
519
|
+
elif error.code == Codes.SESSION_REVOKED:
|
|
520
|
+
# 리스가 끝났을 때도 이 코드다 — 한 번 다시 얻는다(같은 instanceId, 새 키)
|
|
521
|
+
self._begin_acquire(force=False, last_error=error)
|
|
522
|
+
else:
|
|
523
|
+
self._lock_with(error, retrying=False)
|
|
524
|
+
|
|
525
|
+
def _arm_offline_expiry(self, run: int, offline_until: str) -> None:
|
|
526
|
+
"""8.4절 — `offline_until`이 지나도록 성공하지 못하면 잠근다. 재시도는 그대로."""
|
|
527
|
+
with self._lock:
|
|
528
|
+
if self._offline is not None:
|
|
529
|
+
return
|
|
530
|
+
now = self._api.ports.clock.now_ms()
|
|
531
|
+
until = parse_iso(offline_until)
|
|
532
|
+
delay = max(0, until - now) if until is not None else 0
|
|
533
|
+
|
|
534
|
+
def expire() -> None:
|
|
535
|
+
with self._lock:
|
|
536
|
+
self._offline = None
|
|
537
|
+
ok = self._run == run and isinstance(self._current, Degraded)
|
|
538
|
+
if ok:
|
|
539
|
+
self._set_state(
|
|
540
|
+
Locked(
|
|
541
|
+
Codes.OFFLINE_EXPIRED,
|
|
542
|
+
"하트비트에 성공하지 못한 채 licenseToken이 만료됐다",
|
|
543
|
+
None,
|
|
544
|
+
None,
|
|
545
|
+
True,
|
|
546
|
+
)
|
|
547
|
+
)
|
|
548
|
+
|
|
549
|
+
handle = self._api.ports.scheduler.after(delay, expire)
|
|
550
|
+
with self._lock:
|
|
551
|
+
self._offline = handle
|
|
552
|
+
|
|
553
|
+
def _lock_with(self, error: BydevError, *, retrying: bool) -> None:
|
|
554
|
+
with self._lock:
|
|
555
|
+
self._cancel_timers()
|
|
556
|
+
self._set_state(Locked(error.code, error.message, error.correlation_id, error.details, retrying))
|