ai-devlease-client 0.1.1__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.
- ai_devlease_client/__init__.py +69 -0
- ai_devlease_client/_version.py +3 -0
- ai_devlease_client/client.py +333 -0
- ai_devlease_client/config.py +111 -0
- ai_devlease_client/errors.py +247 -0
- ai_devlease_client/lease.py +157 -0
- ai_devlease_client/models.py +360 -0
- ai_devlease_client/py.typed +0 -0
- ai_devlease_client/validation.py +38 -0
- ai_devlease_client-0.1.1.dist-info/METADATA +25 -0
- ai_devlease_client-0.1.1.dist-info/RECORD +13 -0
- ai_devlease_client-0.1.1.dist-info/WHEEL +5 -0
- ai_devlease_client-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Client of the ai-devlease lease manager (import name `ai_devlease_client`)."""
|
|
2
|
+
|
|
3
|
+
from ._version import __version__
|
|
4
|
+
from .client import AiDevleaseClient
|
|
5
|
+
from .config import ConfigError
|
|
6
|
+
from .errors import (
|
|
7
|
+
AiDevleaseError,
|
|
8
|
+
DomainError,
|
|
9
|
+
ExclusiveLockActiveError,
|
|
10
|
+
ExclusiveLockHeldError,
|
|
11
|
+
ExclusiveLockNotHeldError,
|
|
12
|
+
HolderFormatError,
|
|
13
|
+
LeaseNotFoundError,
|
|
14
|
+
QueueJobError,
|
|
15
|
+
QueueJobFailedError,
|
|
16
|
+
QueueJobTimeoutError,
|
|
17
|
+
ResultContractError,
|
|
18
|
+
RestartRequiredError,
|
|
19
|
+
ServiceNotInCatalogError,
|
|
20
|
+
StartTimeoutError,
|
|
21
|
+
StorageError,
|
|
22
|
+
TransportError,
|
|
23
|
+
UnitStartFailedError,
|
|
24
|
+
ValidationError,
|
|
25
|
+
)
|
|
26
|
+
from .lease import LeaseHandle
|
|
27
|
+
from .models import (
|
|
28
|
+
AcquireResult,
|
|
29
|
+
CatalogEntry,
|
|
30
|
+
CatalogResult,
|
|
31
|
+
LockResult,
|
|
32
|
+
ReleaseResult,
|
|
33
|
+
RenewResult,
|
|
34
|
+
StatusResult,
|
|
35
|
+
UnlockResult,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"__version__",
|
|
40
|
+
"AiDevleaseClient",
|
|
41
|
+
"ConfigError",
|
|
42
|
+
"LeaseHandle",
|
|
43
|
+
"AcquireResult",
|
|
44
|
+
"RenewResult",
|
|
45
|
+
"ReleaseResult",
|
|
46
|
+
"StatusResult",
|
|
47
|
+
"LockResult",
|
|
48
|
+
"UnlockResult",
|
|
49
|
+
"CatalogEntry",
|
|
50
|
+
"CatalogResult",
|
|
51
|
+
"AiDevleaseError",
|
|
52
|
+
"TransportError",
|
|
53
|
+
"ResultContractError",
|
|
54
|
+
"QueueJobError",
|
|
55
|
+
"QueueJobFailedError",
|
|
56
|
+
"QueueJobTimeoutError",
|
|
57
|
+
"RestartRequiredError",
|
|
58
|
+
"ValidationError",
|
|
59
|
+
"HolderFormatError",
|
|
60
|
+
"DomainError",
|
|
61
|
+
"ServiceNotInCatalogError",
|
|
62
|
+
"StartTimeoutError",
|
|
63
|
+
"UnitStartFailedError",
|
|
64
|
+
"ExclusiveLockActiveError",
|
|
65
|
+
"ExclusiveLockHeldError",
|
|
66
|
+
"ExclusiveLockNotHeldError",
|
|
67
|
+
"LeaseNotFoundError",
|
|
68
|
+
"StorageError",
|
|
69
|
+
]
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Client of the ai-devlease lease manager.
|
|
3
|
+
|
|
4
|
+
The client holds the framework's JsonRpcClient privately and reaches the service
|
|
5
|
+
through one seam, `_run`. No transport concept (address, status code, envelope)
|
|
6
|
+
appears in a signature or a return value; every failure is an AiDevleaseError.
|
|
7
|
+
|
|
8
|
+
ACQUIRE goes through the adapter queue (decision Q3): the command is submitted,
|
|
9
|
+
the job id is kept and the job is polled with `queue_get_job_status` until it ends;
|
|
10
|
+
the client never waits synchronously on the connection. Every other command is
|
|
11
|
+
synchronous and direct.
|
|
12
|
+
|
|
13
|
+
`call_raw` is the bounded validation invocation: it sends a raw parameter map with no
|
|
14
|
+
client-side validation so negative cases reach the service, and returns the unparsed
|
|
15
|
+
`data` of the answer; errors are mapped exactly as for the typed methods.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import json
|
|
22
|
+
import time
|
|
23
|
+
from collections.abc import Mapping, Sequence
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any, Final
|
|
26
|
+
|
|
27
|
+
from mcp_proxy_adapter.client.jsonrpc_client import JsonRpcClient
|
|
28
|
+
from mcp_proxy_adapter.client.jsonrpc_client.exceptions import (
|
|
29
|
+
ClientError,
|
|
30
|
+
ClientRemoteResponseError,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
from .config import (
|
|
34
|
+
SECTION_NAME,
|
|
35
|
+
ConfigError,
|
|
36
|
+
load_acquire_wait,
|
|
37
|
+
load_client_kwargs,
|
|
38
|
+
)
|
|
39
|
+
from .errors import (
|
|
40
|
+
DOMAIN_ERRORS,
|
|
41
|
+
VALIDATION_CODE,
|
|
42
|
+
AiDevleaseError,
|
|
43
|
+
QueueJobFailedError,
|
|
44
|
+
QueueJobTimeoutError,
|
|
45
|
+
ResultContractError,
|
|
46
|
+
TransportError,
|
|
47
|
+
error_from_payload,
|
|
48
|
+
)
|
|
49
|
+
from .lease import LeaseHandle
|
|
50
|
+
from .models import (
|
|
51
|
+
AcquireResult,
|
|
52
|
+
CatalogResult,
|
|
53
|
+
LockResult,
|
|
54
|
+
ReleaseResult,
|
|
55
|
+
RenewResult,
|
|
56
|
+
StatusResult,
|
|
57
|
+
UnlockResult,
|
|
58
|
+
)
|
|
59
|
+
from .validation import validate_holder
|
|
60
|
+
|
|
61
|
+
__all__ = ["AiDevleaseClient", "ACQUIRE_COMMAND"]
|
|
62
|
+
|
|
63
|
+
ACQUIRE_COMMAND: Final[str] = "acquire"
|
|
64
|
+
|
|
65
|
+
#: Job states of the adapter queue that end a job.
|
|
66
|
+
_TERMINAL_JOB_STATES: Final[frozenset[str]] = frozenset(
|
|
67
|
+
{"completed", "failed", "error", "stopped", "cancelled", "timeout"}
|
|
68
|
+
)
|
|
69
|
+
_JOB_POLL_SECONDS: Final[float] = 1.0
|
|
70
|
+
|
|
71
|
+
_DOMAIN_CODES: Final[frozenset[int]] = frozenset(DOMAIN_ERRORS) | {VALIDATION_CODE}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _error_of(answer: Mapping[str, Any]) -> AiDevleaseError | None:
|
|
75
|
+
"""The typed error an answer carries, or None when the answer is not an error."""
|
|
76
|
+
err = answer.get("error")
|
|
77
|
+
if answer.get("success") is False:
|
|
78
|
+
if isinstance(err, Mapping):
|
|
79
|
+
data = err.get("data") if isinstance(err.get("data"), Mapping) else err
|
|
80
|
+
mapped = error_from_payload(err.get("code"), err.get("message"), data)
|
|
81
|
+
if mapped is not None:
|
|
82
|
+
return mapped
|
|
83
|
+
data = answer.get("data")
|
|
84
|
+
mapped = error_from_payload(
|
|
85
|
+
answer.get("code"),
|
|
86
|
+
err if isinstance(err, str) else answer.get("message"),
|
|
87
|
+
data if isinstance(data, Mapping) else answer,
|
|
88
|
+
)
|
|
89
|
+
if mapped is not None:
|
|
90
|
+
return mapped
|
|
91
|
+
return TransportError(f"service refused the call: {json.dumps(answer, default=str)[:500]}")
|
|
92
|
+
# Bare domain payload {code, message, details} (the envelope was already unwrapped).
|
|
93
|
+
code = answer.get("code")
|
|
94
|
+
if isinstance(code, int) and code in _DOMAIN_CODES and "message" in answer:
|
|
95
|
+
return error_from_payload(code, answer.get("message"), answer)
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _data_of(answer: Any) -> Any:
|
|
100
|
+
"""Peel the framework and command envelopes; raise the typed error of a refusal."""
|
|
101
|
+
for _ in range(6):
|
|
102
|
+
if not isinstance(answer, Mapping):
|
|
103
|
+
return answer
|
|
104
|
+
error = _error_of(answer)
|
|
105
|
+
if error is not None:
|
|
106
|
+
raise error
|
|
107
|
+
if answer.get("success") is True and "data" in answer:
|
|
108
|
+
answer = answer["data"]
|
|
109
|
+
elif "mode" in answer and "result" in answer:
|
|
110
|
+
answer = answer["result"]
|
|
111
|
+
else:
|
|
112
|
+
return answer
|
|
113
|
+
raise ResultContractError("answer nests envelopes deeper than the contract allows")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _translate(exc: ClientError) -> AiDevleaseError:
|
|
117
|
+
"""Map a framework ClientError to the client's vocabulary."""
|
|
118
|
+
if isinstance(exc, ClientRemoteResponseError):
|
|
119
|
+
details = exc.details if isinstance(exc.details, Mapping) else {}
|
|
120
|
+
data = details.get("data") if isinstance(details.get("data"), Mapping) else None
|
|
121
|
+
mapped = error_from_payload(details.get("code"), str(exc), data)
|
|
122
|
+
if mapped is not None:
|
|
123
|
+
mapped.__cause__ = exc
|
|
124
|
+
return mapped
|
|
125
|
+
out = TransportError(f"{type(exc).__name__}: {exc}")
|
|
126
|
+
out.__cause__ = exc
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class AiDevleaseClient:
|
|
131
|
+
"""Typed client of the ai-devlease command surface."""
|
|
132
|
+
|
|
133
|
+
def __init__(
|
|
134
|
+
self,
|
|
135
|
+
section: Mapping[str, Any],
|
|
136
|
+
base_dir: str | None = None,
|
|
137
|
+
*,
|
|
138
|
+
job_poll_seconds: float = _JOB_POLL_SECONDS,
|
|
139
|
+
) -> None:
|
|
140
|
+
"""
|
|
141
|
+
Build the client from its configuration section (see `config`).
|
|
142
|
+
|
|
143
|
+
Raises ConfigError when the section is malformed.
|
|
144
|
+
"""
|
|
145
|
+
if isinstance(job_poll_seconds, bool) or job_poll_seconds <= 0:
|
|
146
|
+
raise ConfigError("job_poll_seconds must be greater than zero")
|
|
147
|
+
kwargs = load_client_kwargs(section, base_dir)
|
|
148
|
+
self._acquire_wait: float = load_acquire_wait(section)
|
|
149
|
+
self._job_poll: float = float(job_poll_seconds)
|
|
150
|
+
self._client: JsonRpcClient = JsonRpcClient(**kwargs)
|
|
151
|
+
|
|
152
|
+
@classmethod
|
|
153
|
+
def from_document_path(
|
|
154
|
+
cls, path: str | Path, section_name: str = SECTION_NAME
|
|
155
|
+
) -> AiDevleaseClient:
|
|
156
|
+
"""Build the client from the named section of a JSON configuration document."""
|
|
157
|
+
path_obj = Path(path).resolve()
|
|
158
|
+
with open(path_obj) as handle:
|
|
159
|
+
document = json.load(handle)
|
|
160
|
+
section = document.get(section_name) if isinstance(document, Mapping) else None
|
|
161
|
+
if not isinstance(section, Mapping):
|
|
162
|
+
raise ConfigError(f"configuration document carries no '{section_name}' section")
|
|
163
|
+
return cls(section, base_dir=str(path_obj.parent))
|
|
164
|
+
|
|
165
|
+
# -- lifecycle ---------------------------------------------------------
|
|
166
|
+
|
|
167
|
+
async def close(self) -> None:
|
|
168
|
+
"""Release the transport; closing twice is harmless."""
|
|
169
|
+
await self._client.close()
|
|
170
|
+
|
|
171
|
+
async def __aenter__(self) -> AiDevleaseClient:
|
|
172
|
+
return self
|
|
173
|
+
|
|
174
|
+
async def __aexit__(self, *exc_info: object) -> None:
|
|
175
|
+
await self.close()
|
|
176
|
+
|
|
177
|
+
def __repr__(self) -> str:
|
|
178
|
+
return f"{self.__class__.__name__}()"
|
|
179
|
+
|
|
180
|
+
# -- the one seam ------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
async def _direct(self, command: str, params: Mapping[str, Any]) -> Any:
|
|
183
|
+
try:
|
|
184
|
+
answer = await self._client.execute_command_unified(
|
|
185
|
+
command, dict(params), expect_queue=False
|
|
186
|
+
)
|
|
187
|
+
except ClientError as exc:
|
|
188
|
+
raise _translate(exc) from exc
|
|
189
|
+
return _data_of(answer)
|
|
190
|
+
|
|
191
|
+
async def _queued(self, command: str, params: Mapping[str, Any]) -> Any:
|
|
192
|
+
"""Submit `command` to the adapter queue, keep the job id and poll it to its end."""
|
|
193
|
+
deadline = time.monotonic() + self._acquire_wait
|
|
194
|
+
try:
|
|
195
|
+
envelope = await self._client.execute_command_unified(
|
|
196
|
+
command, dict(params), auto_poll=False
|
|
197
|
+
)
|
|
198
|
+
except ClientError as exc:
|
|
199
|
+
raise _translate(exc) from exc
|
|
200
|
+
if not isinstance(envelope, Mapping):
|
|
201
|
+
raise ResultContractError(f"{command}: submit answer is not an object")
|
|
202
|
+
job_id = envelope.get("job_id")
|
|
203
|
+
if envelope.get("mode") != "queued" or not isinstance(job_id, str) or not job_id:
|
|
204
|
+
# The service answered inline; the answer is the result.
|
|
205
|
+
return _data_of(envelope)
|
|
206
|
+
while True:
|
|
207
|
+
try:
|
|
208
|
+
status = await self._client.queue_get_job_status(job_id)
|
|
209
|
+
except ClientError as exc:
|
|
210
|
+
raise _translate(exc) from exc
|
|
211
|
+
data = status.get("data") if isinstance(status, Mapping) else None
|
|
212
|
+
body = data if isinstance(data, Mapping) else status
|
|
213
|
+
state = str(body.get("status", "")).lower() if isinstance(body, Mapping) else ""
|
|
214
|
+
if state in _TERMINAL_JOB_STATES:
|
|
215
|
+
break
|
|
216
|
+
if time.monotonic() >= deadline:
|
|
217
|
+
raise QueueJobTimeoutError(
|
|
218
|
+
f"{command}: job {job_id} still '{state or 'unknown'}' after "
|
|
219
|
+
f"{self._acquire_wait:g} s; the job keeps running",
|
|
220
|
+
job_id,
|
|
221
|
+
)
|
|
222
|
+
await asyncio.sleep(self._job_poll)
|
|
223
|
+
assert isinstance(body, Mapping)
|
|
224
|
+
if state == "completed":
|
|
225
|
+
return _data_of(body.get("result"))
|
|
226
|
+
for candidate in (body.get("result"), body.get("error")):
|
|
227
|
+
if isinstance(candidate, Mapping):
|
|
228
|
+
_data_of(candidate) # raises the typed domain error when it carries one
|
|
229
|
+
raise QueueJobFailedError(
|
|
230
|
+
f"{command}: job {job_id} ended '{state}': {body.get('error') or body.get('message') or ''}".strip(),
|
|
231
|
+
job_id,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
async def _run(self, command: str, params: Mapping[str, Any]) -> Any:
|
|
235
|
+
if command == ACQUIRE_COMMAND:
|
|
236
|
+
return await self._queued(command, params)
|
|
237
|
+
return await self._direct(command, params)
|
|
238
|
+
|
|
239
|
+
async def call_raw(self, command: str, params: Mapping[str, Any] | None = None) -> Any:
|
|
240
|
+
"""
|
|
241
|
+
Bounded validation invocation: send a raw parameter map, no client-side validation.
|
|
242
|
+
|
|
243
|
+
Returns the unparsed `data` of the answer. Errors are mapped like the typed methods:
|
|
244
|
+
-32602 raises ValidationError, -32010..-32017 the typed domain error. `acquire` goes
|
|
245
|
+
through the queue like the typed method.
|
|
246
|
+
"""
|
|
247
|
+
return await self._run(command, dict(params or {}))
|
|
248
|
+
|
|
249
|
+
# -- commands ----------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
async def acquire(self, holder: str, service: str) -> AcquireResult:
|
|
252
|
+
"""Take a lease on `service` (and its dependencies); returns when everything is ready."""
|
|
253
|
+
validate_holder(holder)
|
|
254
|
+
return AcquireResult.from_payload(
|
|
255
|
+
await self._run(ACQUIRE_COMMAND, {"holder": holder, "service": service})
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
async def renew(self, holder: str) -> RenewResult:
|
|
259
|
+
"""Renew every lease and exclusive lock of `holder`. Raises LeaseNotFoundError (E7)."""
|
|
260
|
+
validate_holder(holder)
|
|
261
|
+
return RenewResult.from_payload(await self._run("renew", {"holder": holder}))
|
|
262
|
+
|
|
263
|
+
async def release(self, holder: str, service: str | None = None) -> ReleaseResult:
|
|
264
|
+
"""Release `service` of `holder`, or every lease of `holder` when `service` is None."""
|
|
265
|
+
validate_holder(holder)
|
|
266
|
+
params: dict[str, Any] = {"holder": holder}
|
|
267
|
+
if service is not None:
|
|
268
|
+
params["service"] = service
|
|
269
|
+
return ReleaseResult.from_payload(await self._run("release", params))
|
|
270
|
+
|
|
271
|
+
async def status(self, service: str | None = None) -> StatusResult:
|
|
272
|
+
"""Read the state of every service, or of one (exact name)."""
|
|
273
|
+
params = {} if service is None else {"service": service}
|
|
274
|
+
return StatusResult.from_payload(await self._run("status", params))
|
|
275
|
+
|
|
276
|
+
async def lock_exclusive(self, holder: str, service: str) -> LockResult:
|
|
277
|
+
"""Take the exclusive lock of `service`."""
|
|
278
|
+
validate_holder(holder)
|
|
279
|
+
return LockResult.from_payload(
|
|
280
|
+
await self._run("lock_exclusive", {"holder": holder, "service": service})
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
async def unlock_exclusive(self, holder: str, service: str) -> UnlockResult:
|
|
284
|
+
"""Drop the exclusive lock of `service`; only its owner can."""
|
|
285
|
+
validate_holder(holder)
|
|
286
|
+
return UnlockResult.from_payload(
|
|
287
|
+
await self._run("unlock_exclusive", {"holder": holder, "service": service})
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
async def catalog(self, service: str | None = None) -> CatalogResult:
|
|
291
|
+
"""Read the service catalog, or one entry (exact name)."""
|
|
292
|
+
params = {} if service is None else {"service": service}
|
|
293
|
+
return CatalogResult.from_payload(await self._run("catalog", params))
|
|
294
|
+
|
|
295
|
+
async def help(
|
|
296
|
+
self,
|
|
297
|
+
cmdname: str | None = None,
|
|
298
|
+
limit: int | None = None,
|
|
299
|
+
offset: int | None = None,
|
|
300
|
+
) -> Any:
|
|
301
|
+
"""Standard help of the installed adapter version (result passed through)."""
|
|
302
|
+
params = {
|
|
303
|
+
k: v
|
|
304
|
+
for k, v in (("cmdname", cmdname), ("limit", limit), ("offset", offset))
|
|
305
|
+
if v is not None
|
|
306
|
+
}
|
|
307
|
+
return await self._run("help", params)
|
|
308
|
+
|
|
309
|
+
async def health(self) -> Any:
|
|
310
|
+
"""Standard health of the installed adapter version (result passed through)."""
|
|
311
|
+
return await self._run("health", {})
|
|
312
|
+
|
|
313
|
+
# -- helper ------------------------------------------------------------
|
|
314
|
+
|
|
315
|
+
def lease(
|
|
316
|
+
self,
|
|
317
|
+
holder: str,
|
|
318
|
+
services: str | Sequence[str],
|
|
319
|
+
*,
|
|
320
|
+
renew_interval: float = 60.0,
|
|
321
|
+
on_restart_required: Any = None,
|
|
322
|
+
) -> LeaseHandle:
|
|
323
|
+
"""
|
|
324
|
+
Context manager: acquire the services, renew every `renew_interval` seconds
|
|
325
|
+
(60 s) in the background, surface `restart_required`, release on exit.
|
|
326
|
+
"""
|
|
327
|
+
return LeaseHandle(
|
|
328
|
+
self,
|
|
329
|
+
holder,
|
|
330
|
+
services,
|
|
331
|
+
renew_interval=renew_interval,
|
|
332
|
+
on_restart_required=on_restart_required,
|
|
333
|
+
)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration of the ai-devlease client.
|
|
3
|
+
|
|
4
|
+
The client is built from its own section ("ai_devlease_client") of the consuming
|
|
5
|
+
process's configuration document, in the sectioned fleet shape: a top-level
|
|
6
|
+
``protocol`` (http, https, mtls), a ``server`` sub-section with ``host`` and ``port``,
|
|
7
|
+
optional ``client`` and ``ssl`` sub-sections with ``cert``, ``key``, ``ca``,
|
|
8
|
+
``check_hostname``, ``timeout``, and an optional ``auth`` sub-section with ``token`` and
|
|
9
|
+
``token_header``. This module produces the keyword arguments of the framework's
|
|
10
|
+
JsonRpcClient and reads nothing else.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Final
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"ConfigError",
|
|
21
|
+
"SECTION_NAME",
|
|
22
|
+
"ACQUIRE_WAIT_SECONDS",
|
|
23
|
+
"load_client_kwargs",
|
|
24
|
+
"load_acquire_wait",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
SECTION_NAME: Final[str] = "ai_devlease_client"
|
|
28
|
+
|
|
29
|
+
#: Longest the client follows an acquire job: exclusive wait 300 s plus start timeout 300 s
|
|
30
|
+
#: of a real service, plus headroom.
|
|
31
|
+
ACQUIRE_WAIT_SECONDS: Final[float] = 660.0
|
|
32
|
+
|
|
33
|
+
_PROTOCOLS = frozenset({"http", "https", "mtls"})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ConfigError(Exception):
|
|
37
|
+
"""The configuration section is missing or malformed."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _mapping(node: Any, name: str) -> Mapping[str, Any]:
|
|
41
|
+
if node is None:
|
|
42
|
+
return {}
|
|
43
|
+
if not isinstance(node, Mapping):
|
|
44
|
+
raise ConfigError(f"'{name}' must be an object")
|
|
45
|
+
return node
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _path(value: Any, name: str, base_dir: str | None) -> str | None:
|
|
49
|
+
if value is None:
|
|
50
|
+
return None
|
|
51
|
+
if not isinstance(value, str) or not value:
|
|
52
|
+
raise ConfigError(f"'{name}' must be a non-empty string path")
|
|
53
|
+
path = Path(value)
|
|
54
|
+
if not path.is_absolute() and base_dir is not None:
|
|
55
|
+
path = Path(base_dir) / path
|
|
56
|
+
return str(path.resolve())
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load_client_kwargs(section: Mapping[str, Any], base_dir: str | None = None) -> dict[str, Any]:
|
|
60
|
+
"""Translate the section into JsonRpcClient constructor keyword arguments."""
|
|
61
|
+
if not isinstance(section, Mapping):
|
|
62
|
+
raise ConfigError("client section must be an object")
|
|
63
|
+
protocol = section.get("protocol")
|
|
64
|
+
if protocol not in _PROTOCOLS:
|
|
65
|
+
raise ConfigError(f"'protocol' must be one of {sorted(_PROTOCOLS)}")
|
|
66
|
+
server = _mapping(section.get("server"), "server")
|
|
67
|
+
host, port = server.get("host"), server.get("port")
|
|
68
|
+
if not isinstance(host, str) or not host:
|
|
69
|
+
raise ConfigError("'server.host' must be a non-empty string")
|
|
70
|
+
if isinstance(port, bool) or not isinstance(port, int) or not 0 < port < 65536:
|
|
71
|
+
raise ConfigError("'server.port' must be an integer in 1..65535")
|
|
72
|
+
client = _mapping(section.get("client"), "client")
|
|
73
|
+
ssl = _mapping(section.get("ssl"), "ssl")
|
|
74
|
+
auth = _mapping(section.get("auth"), "auth")
|
|
75
|
+
|
|
76
|
+
def pick(key: str) -> Any:
|
|
77
|
+
return client.get(key, ssl.get(key))
|
|
78
|
+
|
|
79
|
+
timeout = client.get("timeout")
|
|
80
|
+
if timeout is not None and (
|
|
81
|
+
isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0
|
|
82
|
+
):
|
|
83
|
+
raise ConfigError("'client.timeout' must be a number greater than zero")
|
|
84
|
+
check_hostname = pick("check_hostname")
|
|
85
|
+
if check_hostname is not None and not isinstance(check_hostname, bool):
|
|
86
|
+
raise ConfigError("'check_hostname' must be a boolean")
|
|
87
|
+
token, token_header = auth.get("token"), auth.get("token_header")
|
|
88
|
+
for name, value in (("auth.token", token), ("auth.token_header", token_header)):
|
|
89
|
+
if value is not None and not isinstance(value, str):
|
|
90
|
+
raise ConfigError(f"'{name}' must be a string")
|
|
91
|
+
return {
|
|
92
|
+
"protocol": protocol,
|
|
93
|
+
"host": host,
|
|
94
|
+
"port": port,
|
|
95
|
+
"token_header": token_header,
|
|
96
|
+
"token": token,
|
|
97
|
+
"cert": _path(pick("cert"), "cert", base_dir),
|
|
98
|
+
"key": _path(pick("key"), "key", base_dir),
|
|
99
|
+
"ca": _path(pick("ca"), "ca", base_dir),
|
|
100
|
+
"check_hostname": check_hostname,
|
|
101
|
+
"timeout": float(timeout) if timeout is not None else None,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def load_acquire_wait(section: Mapping[str, Any]) -> float:
|
|
106
|
+
"""`client.acquire_wait_seconds`: how long an acquire job is followed."""
|
|
107
|
+
client = _mapping(section.get("client"), "client")
|
|
108
|
+
value = client.get("acquire_wait_seconds", ACQUIRE_WAIT_SECONDS)
|
|
109
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
|
|
110
|
+
raise ConfigError("'client.acquire_wait_seconds' must be a number greater than zero")
|
|
111
|
+
return float(value)
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Typed errors of the ai-devlease client.
|
|
3
|
+
|
|
4
|
+
Every failure the caller can see is an AiDevleaseError. The service contract
|
|
5
|
+
(matrix TODO 44ee0365, table D):
|
|
6
|
+
|
|
7
|
+
- -32602 -> ValidationError (violation unknown | missing | type | value)
|
|
8
|
+
- -32010 E1 -> ServiceNotInCatalogError -32014 E5 -> ExclusiveLockHeldError
|
|
9
|
+
- -32011 E2 -> StartTimeoutError -32015 E6 -> ExclusiveLockNotHeldError
|
|
10
|
+
- -32012 E3 -> UnitStartFailedError -32016 E7 -> LeaseNotFoundError
|
|
11
|
+
- -32013 E4 -> ExclusiveLockActiveError -32017 E8 -> StorageError
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Mapping
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"AiDevleaseError",
|
|
21
|
+
"TransportError",
|
|
22
|
+
"ResultContractError",
|
|
23
|
+
"QueueJobError",
|
|
24
|
+
"QueueJobFailedError",
|
|
25
|
+
"QueueJobTimeoutError",
|
|
26
|
+
"RestartRequiredError",
|
|
27
|
+
"ValidationError",
|
|
28
|
+
"HolderFormatError",
|
|
29
|
+
"DomainError",
|
|
30
|
+
"ServiceNotInCatalogError",
|
|
31
|
+
"StartTimeoutError",
|
|
32
|
+
"UnitStartFailedError",
|
|
33
|
+
"ExclusiveLockActiveError",
|
|
34
|
+
"ExclusiveLockHeldError",
|
|
35
|
+
"ExclusiveLockNotHeldError",
|
|
36
|
+
"LeaseNotFoundError",
|
|
37
|
+
"StorageError",
|
|
38
|
+
"VALIDATION_CODE",
|
|
39
|
+
"DOMAIN_ERRORS",
|
|
40
|
+
"error_from_payload",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
VALIDATION_CODE = -32602
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AiDevleaseError(Exception):
|
|
47
|
+
"""Base of every error raised by this client."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class TransportError(AiDevleaseError):
|
|
51
|
+
"""The service could not be reached or answered outside its contract."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ResultContractError(AiDevleaseError):
|
|
55
|
+
"""A successful answer does not have the shape the contract promises."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class QueueJobError(AiDevleaseError):
|
|
59
|
+
"""The queued acquire job did not finish with a result."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, message: str, job_id: str | None = None) -> None:
|
|
62
|
+
super().__init__(message)
|
|
63
|
+
self.job_id = job_id
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class QueueJobFailedError(QueueJobError):
|
|
67
|
+
"""The job ended in a failed, stopped or cancelled state without a domain error."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class QueueJobTimeoutError(QueueJobError):
|
|
71
|
+
"""The client stopped waiting for the job; the job itself keeps running."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class RestartRequiredError(AiDevleaseError):
|
|
75
|
+
"""A renew reported that units of the held services were restarted (reconnect)."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, services: tuple[str, ...]) -> None:
|
|
78
|
+
super().__init__("restart_required: " + ", ".join(services))
|
|
79
|
+
self.services = services
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class ValidationError(AiDevleaseError):
|
|
83
|
+
"""Parameter refusal, code -32602 (error.data.violation)."""
|
|
84
|
+
|
|
85
|
+
code = VALIDATION_CODE
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
message: str,
|
|
90
|
+
*,
|
|
91
|
+
violation: str | None = None,
|
|
92
|
+
field: str | None = None,
|
|
93
|
+
parameters: list[str] | None = None,
|
|
94
|
+
expected: Any = None,
|
|
95
|
+
got: Any = None,
|
|
96
|
+
data: Mapping[str, Any] | None = None,
|
|
97
|
+
) -> None:
|
|
98
|
+
super().__init__(message)
|
|
99
|
+
self.violation = violation
|
|
100
|
+
self.field = field
|
|
101
|
+
self.parameters = parameters
|
|
102
|
+
self.expected = expected
|
|
103
|
+
self.got = got
|
|
104
|
+
self.data = dict(data) if data else {}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class HolderFormatError(ValidationError):
|
|
108
|
+
"""Client-side refusal of a holder that is not `<project>/<run_id>`."""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class DomainError(AiDevleaseError):
|
|
112
|
+
"""Domain error E1..E8 with the payload {code, message, details}."""
|
|
113
|
+
|
|
114
|
+
code: int = 0
|
|
115
|
+
name: str = ""
|
|
116
|
+
|
|
117
|
+
def __init__(self, message: str, details: Mapping[str, Any] | None = None) -> None:
|
|
118
|
+
super().__init__(message)
|
|
119
|
+
self.message = message
|
|
120
|
+
self.details = dict(details) if details else {}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class ServiceNotInCatalogError(DomainError):
|
|
124
|
+
"""E1: the service is not in the catalog."""
|
|
125
|
+
|
|
126
|
+
code = -32010
|
|
127
|
+
name = "SERVICE_NOT_IN_CATALOG"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class StartTimeoutError(DomainError):
|
|
131
|
+
"""E2: health, version and registration were not reached in time; no lease exists."""
|
|
132
|
+
|
|
133
|
+
code = -32011
|
|
134
|
+
name = "START_TIMEOUT"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class UnitStartFailedError(DomainError):
|
|
138
|
+
"""E3: systemctl start of the unit was refused or failed."""
|
|
139
|
+
|
|
140
|
+
code = -32012
|
|
141
|
+
name = "UNIT_START_FAILED"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class ExclusiveLockActiveError(DomainError):
|
|
145
|
+
"""E4: acquire waited more than 300 s on a foreign exclusive lock."""
|
|
146
|
+
|
|
147
|
+
code = -32013
|
|
148
|
+
name = "EXCLUSIVE_LOCK_ACTIVE"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class ExclusiveLockHeldError(DomainError):
|
|
152
|
+
"""E5: lock_exclusive found another holder's lock."""
|
|
153
|
+
|
|
154
|
+
code = -32014
|
|
155
|
+
name = "EXCLUSIVE_LOCK_HELD"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class ExclusiveLockNotHeldError(DomainError):
|
|
159
|
+
"""E6: unlock_exclusive found no lock, or a foreign one."""
|
|
160
|
+
|
|
161
|
+
code = -32015
|
|
162
|
+
name = "EXCLUSIVE_LOCK_NOT_HELD"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class LeaseNotFoundError(DomainError):
|
|
166
|
+
"""E7: renew found no lease of the holder (the client acquires again)."""
|
|
167
|
+
|
|
168
|
+
code = -32016
|
|
169
|
+
name = "LEASE_NOT_FOUND"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class StorageError(DomainError):
|
|
173
|
+
"""E8: the SQLite storage failed."""
|
|
174
|
+
|
|
175
|
+
code = -32017
|
|
176
|
+
name = "STORAGE_ERROR"
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
DOMAIN_ERRORS: dict[int, type[DomainError]] = {
|
|
180
|
+
cls.code: cls
|
|
181
|
+
for cls in (
|
|
182
|
+
ServiceNotInCatalogError,
|
|
183
|
+
StartTimeoutError,
|
|
184
|
+
UnitStartFailedError,
|
|
185
|
+
ExclusiveLockActiveError,
|
|
186
|
+
ExclusiveLockHeldError,
|
|
187
|
+
ExclusiveLockNotHeldError,
|
|
188
|
+
LeaseNotFoundError,
|
|
189
|
+
StorageError,
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
_BY_NAME = {cls.name: cls for cls in DOMAIN_ERRORS.values()}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _find(source: Mapping[str, Any] | None, key: str) -> Any:
|
|
196
|
+
"""Read `key` from `source` or from its nested `details` / `data` mapping."""
|
|
197
|
+
if not isinstance(source, Mapping):
|
|
198
|
+
return None
|
|
199
|
+
if key in source:
|
|
200
|
+
return source[key]
|
|
201
|
+
for nested in ("details", "data"):
|
|
202
|
+
inner = source.get(nested)
|
|
203
|
+
if isinstance(inner, Mapping) and key in inner:
|
|
204
|
+
return inner[key]
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def error_from_payload(
|
|
209
|
+
code: Any,
|
|
210
|
+
message: Any,
|
|
211
|
+
data: Mapping[str, Any] | None,
|
|
212
|
+
) -> AiDevleaseError | None:
|
|
213
|
+
"""
|
|
214
|
+
Map an error payload (adapter error.code / error.message / error.data or the
|
|
215
|
+
domain payload {code, message, details}) to a typed exception.
|
|
216
|
+
|
|
217
|
+
Returns None when the payload is neither -32602 nor one of -32010..-32017
|
|
218
|
+
(or their symbolic names), so the caller reports it as a transport failure.
|
|
219
|
+
"""
|
|
220
|
+
text = message if isinstance(message, str) else str(message or "")
|
|
221
|
+
if isinstance(code, str):
|
|
222
|
+
by_name = _BY_NAME.get(code)
|
|
223
|
+
if by_name is not None:
|
|
224
|
+
code = by_name.code
|
|
225
|
+
else:
|
|
226
|
+
try:
|
|
227
|
+
code = int(code)
|
|
228
|
+
except ValueError:
|
|
229
|
+
return None
|
|
230
|
+
if code == VALIDATION_CODE:
|
|
231
|
+
parameters = _find(data, "parameters")
|
|
232
|
+
return ValidationError(
|
|
233
|
+
text,
|
|
234
|
+
violation=_find(data, "violation"),
|
|
235
|
+
field=_find(data, "field") or _find(data, "parameter"),
|
|
236
|
+
parameters=list(parameters) if isinstance(parameters, (list, tuple)) else None,
|
|
237
|
+
expected=_find(data, "expected"),
|
|
238
|
+
got=_find(data, "got"),
|
|
239
|
+
data=data,
|
|
240
|
+
)
|
|
241
|
+
cls = DOMAIN_ERRORS.get(code) if isinstance(code, int) else None
|
|
242
|
+
if cls is None:
|
|
243
|
+
return None
|
|
244
|
+
details = data.get("details") if isinstance(data, Mapping) else None
|
|
245
|
+
if not isinstance(details, Mapping):
|
|
246
|
+
details = data
|
|
247
|
+
return cls(text, details)
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Lease helper: acquire, renew in the background every 60 s, release on exit.
|
|
3
|
+
|
|
4
|
+
async with client.lease("proj/run1", "fake-a") as lease:
|
|
5
|
+
...
|
|
6
|
+
lease.raise_if_restart_required()
|
|
7
|
+
|
|
8
|
+
BEHAVIOUR
|
|
9
|
+
- enter: acquires the services in the given order (the service takes its dependencies);
|
|
10
|
+
when one acquire fails, the ones already taken are released and the error propagates.
|
|
11
|
+
- while held: one background task calls `renew` every `renew_interval` seconds (60 s;
|
|
12
|
+
the TTL of a real service is 300 s). `renew` also extends the exclusive locks of
|
|
13
|
+
the holder.
|
|
14
|
+
- restart_required (Q6): when a renew lists services, they are recorded in
|
|
15
|
+
`restart_required`, `restart_event` is set, `on_restart_required(services)` is called
|
|
16
|
+
(sync or async) and `raise_if_restart_required()` raises RestartRequiredError.
|
|
17
|
+
- E7 LEASE_NOT_FOUND on a renew (the lease expired): the helper acquires the services
|
|
18
|
+
again (Q5) and counts it in `reacquired`.
|
|
19
|
+
- any other renew failure is stored in `last_error`, counted in `renew_failures` and
|
|
20
|
+
`failed_event` is set; the loop keeps trying on the next tick.
|
|
21
|
+
- exit: stops the loop, then releases every service in reverse order. A release error is
|
|
22
|
+
raised unless the body already raised.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import contextlib
|
|
29
|
+
import inspect
|
|
30
|
+
from collections.abc import Callable, Sequence
|
|
31
|
+
from typing import TYPE_CHECKING, Any, Final
|
|
32
|
+
|
|
33
|
+
from .errors import AiDevleaseError, LeaseNotFoundError, RestartRequiredError
|
|
34
|
+
from .validation import validate_holder
|
|
35
|
+
|
|
36
|
+
if TYPE_CHECKING:
|
|
37
|
+
from .client import AiDevleaseClient
|
|
38
|
+
from .models import AcquireResult, RenewResult
|
|
39
|
+
|
|
40
|
+
__all__ = ["LeaseHandle", "RENEW_INTERVAL_SECONDS"]
|
|
41
|
+
|
|
42
|
+
RENEW_INTERVAL_SECONDS: Final[float] = 60.0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class LeaseHandle:
|
|
46
|
+
"""Async context manager returned by `AiDevleaseClient.lease`."""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
client: AiDevleaseClient,
|
|
51
|
+
holder: str,
|
|
52
|
+
services: str | Sequence[str],
|
|
53
|
+
*,
|
|
54
|
+
renew_interval: float = RENEW_INTERVAL_SECONDS,
|
|
55
|
+
on_restart_required: Callable[[tuple[str, ...]], Any] | None = None,
|
|
56
|
+
) -> None:
|
|
57
|
+
validate_holder(holder)
|
|
58
|
+
names = [services] if isinstance(services, str) else list(services)
|
|
59
|
+
if not names or not all(isinstance(n, str) and n for n in names):
|
|
60
|
+
raise ValueError("services must be a non-empty name or a sequence of non-empty names")
|
|
61
|
+
if isinstance(renew_interval, bool) or renew_interval <= 0:
|
|
62
|
+
raise ValueError("renew_interval must be greater than zero")
|
|
63
|
+
self._client = client
|
|
64
|
+
self.holder = holder
|
|
65
|
+
self.services: tuple[str, ...] = tuple(names)
|
|
66
|
+
self.renew_interval = float(renew_interval)
|
|
67
|
+
self._callback = on_restart_required
|
|
68
|
+
self._task: asyncio.Task[None] | None = None
|
|
69
|
+
self._taken: list[str] = []
|
|
70
|
+
self.acquired: dict[str, AcquireResult] = {}
|
|
71
|
+
self.last_renew: RenewResult | None = None
|
|
72
|
+
self.renew_count = 0
|
|
73
|
+
self.reacquired = 0
|
|
74
|
+
self.renew_failures = 0
|
|
75
|
+
self.last_error: AiDevleaseError | None = None
|
|
76
|
+
self.failed_event = asyncio.Event()
|
|
77
|
+
self.restart_required: tuple[str, ...] = ()
|
|
78
|
+
self.restart_event = asyncio.Event()
|
|
79
|
+
|
|
80
|
+
def raise_if_restart_required(self) -> None:
|
|
81
|
+
"""Raise RestartRequiredError when a renew reported restarted services."""
|
|
82
|
+
if self.restart_required:
|
|
83
|
+
raise RestartRequiredError(self.restart_required)
|
|
84
|
+
|
|
85
|
+
async def __aenter__(self) -> LeaseHandle:
|
|
86
|
+
try:
|
|
87
|
+
for name in self.services:
|
|
88
|
+
self.acquired[name] = await self._client.acquire(self.holder, name)
|
|
89
|
+
self._taken.append(name)
|
|
90
|
+
except BaseException:
|
|
91
|
+
await self._release_all(suppress=True)
|
|
92
|
+
raise
|
|
93
|
+
self._task = asyncio.create_task(self._renew_loop(), name=f"ai-devlease-renew-{self.holder}")
|
|
94
|
+
return self
|
|
95
|
+
|
|
96
|
+
async def __aexit__(self, exc_type: type[BaseException] | None, *rest: object) -> None:
|
|
97
|
+
await self._stop()
|
|
98
|
+
await self._release_all(suppress=exc_type is not None)
|
|
99
|
+
|
|
100
|
+
async def _stop(self) -> None:
|
|
101
|
+
task, self._task = self._task, None
|
|
102
|
+
if task is not None:
|
|
103
|
+
task.cancel()
|
|
104
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
105
|
+
await task
|
|
106
|
+
|
|
107
|
+
async def _release_all(self, *, suppress: bool) -> None:
|
|
108
|
+
first: BaseException | None = None
|
|
109
|
+
for name in reversed(self._taken):
|
|
110
|
+
try:
|
|
111
|
+
await self._client.release(self.holder, name)
|
|
112
|
+
except Exception as exc: # noqa: BLE001 - the remaining leases are still released
|
|
113
|
+
first = first or exc
|
|
114
|
+
self._taken.clear()
|
|
115
|
+
if first is not None and not suppress:
|
|
116
|
+
raise first
|
|
117
|
+
|
|
118
|
+
async def _renew_loop(self) -> None:
|
|
119
|
+
while True:
|
|
120
|
+
await asyncio.sleep(self.renew_interval)
|
|
121
|
+
try:
|
|
122
|
+
result = await self._client.renew(self.holder)
|
|
123
|
+
except LeaseNotFoundError:
|
|
124
|
+
await self._reacquire()
|
|
125
|
+
continue
|
|
126
|
+
except AiDevleaseError as exc:
|
|
127
|
+
self._fail(exc)
|
|
128
|
+
continue
|
|
129
|
+
self.last_renew = result
|
|
130
|
+
self.renew_count += 1
|
|
131
|
+
if result.restart_required:
|
|
132
|
+
self.restart_required = tuple(dict.fromkeys((*self.restart_required, *result.restart_required)))
|
|
133
|
+
self.restart_event.set()
|
|
134
|
+
await self._notify(result.restart_required)
|
|
135
|
+
|
|
136
|
+
async def _reacquire(self) -> None:
|
|
137
|
+
try:
|
|
138
|
+
for name in self.services:
|
|
139
|
+
self.acquired[name] = await self._client.acquire(self.holder, name)
|
|
140
|
+
self.reacquired += 1
|
|
141
|
+
except AiDevleaseError as exc:
|
|
142
|
+
self._fail(exc)
|
|
143
|
+
|
|
144
|
+
def _fail(self, exc: AiDevleaseError) -> None:
|
|
145
|
+
self.last_error = exc
|
|
146
|
+
self.renew_failures += 1
|
|
147
|
+
self.failed_event.set()
|
|
148
|
+
|
|
149
|
+
async def _notify(self, services: tuple[str, ...]) -> None:
|
|
150
|
+
if self._callback is None:
|
|
151
|
+
return
|
|
152
|
+
try:
|
|
153
|
+
outcome = self._callback(services)
|
|
154
|
+
if inspect.isawaitable(outcome):
|
|
155
|
+
await outcome
|
|
156
|
+
except Exception as exc: # noqa: BLE001 - a faulty callback must not stop renewing
|
|
157
|
+
self._fail(AiDevleaseError(f"on_restart_required callback failed: {exc!r}"))
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Result types of the ai-devlease commands (matrix tables C-acq .. C-cat).
|
|
3
|
+
|
|
4
|
+
Each `from_payload` checks the contract shape and raises ResultContractError on any
|
|
5
|
+
missing field or wrong type, so a contract drift surfaces as an error and never as a
|
|
6
|
+
silently wrong value.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Mapping, Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .errors import ResultContractError
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"LeaseInfo",
|
|
20
|
+
"ReadyService",
|
|
21
|
+
"AcquireResult",
|
|
22
|
+
"RenewedLease",
|
|
23
|
+
"RenewResult",
|
|
24
|
+
"ReleasedLease",
|
|
25
|
+
"ReleaseResult",
|
|
26
|
+
"StatusHolder",
|
|
27
|
+
"ExclusiveInfo",
|
|
28
|
+
"ServiceStatus",
|
|
29
|
+
"StatusResult",
|
|
30
|
+
"LockResult",
|
|
31
|
+
"UnlockResult",
|
|
32
|
+
"CatalogEntry",
|
|
33
|
+
"CatalogResult",
|
|
34
|
+
"SERVICE_STATES",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
#: Vocabulary of `state` in status (decision Q7).
|
|
38
|
+
SERVICE_STATES = frozenset({"stopped", "starting", "ready", "idle", "stopping", "failed"})
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _obj(value: Any, where: str) -> Mapping[str, Any]:
|
|
42
|
+
if not isinstance(value, Mapping):
|
|
43
|
+
raise ResultContractError(f"{where}: expected an object, got {type(value).__name__}")
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _field(src: Mapping[str, Any], key: str, kind: type | tuple[type, ...], where: str) -> Any:
|
|
48
|
+
if key not in src:
|
|
49
|
+
raise ResultContractError(f"{where}: missing field '{key}'")
|
|
50
|
+
value = src[key]
|
|
51
|
+
kinds = kind if isinstance(kind, tuple) else (kind,)
|
|
52
|
+
if isinstance(value, bool) and bool not in kinds:
|
|
53
|
+
raise ResultContractError(f"{where}.{key}: expected {kinds}, got bool")
|
|
54
|
+
if not isinstance(value, kinds):
|
|
55
|
+
raise ResultContractError(f"{where}.{key}: expected {kinds}, got {type(value).__name__}")
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _ts(src: Mapping[str, Any], key: str, where: str, *, nullable: bool = False) -> datetime | None:
|
|
60
|
+
if nullable and key in src and src[key] is None:
|
|
61
|
+
return None
|
|
62
|
+
text = _field(src, key, str, where)
|
|
63
|
+
try:
|
|
64
|
+
moment = datetime.fromisoformat(text)
|
|
65
|
+
except ValueError as exc:
|
|
66
|
+
raise ResultContractError(f"{where}.{key}: not an ISO-8601 timestamp: {text!r}") from exc
|
|
67
|
+
if moment.tzinfo is None:
|
|
68
|
+
raise ResultContractError(f"{where}.{key}: timestamp without a zone: {text!r}")
|
|
69
|
+
return moment
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _list(src: Mapping[str, Any], key: str, where: str) -> Sequence[Any]:
|
|
73
|
+
return _field(src, key, list, where)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _strs(src: Mapping[str, Any], key: str, where: str) -> tuple[str, ...]:
|
|
77
|
+
items = _list(src, key, where)
|
|
78
|
+
if not all(isinstance(i, str) for i in items):
|
|
79
|
+
raise ResultContractError(f"{where}.{key}: expected a list of strings")
|
|
80
|
+
return tuple(items)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class LeaseInfo:
|
|
85
|
+
expires_at: datetime
|
|
86
|
+
ttl_seconds: int
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class ReadyService:
|
|
91
|
+
service: str
|
|
92
|
+
state: str
|
|
93
|
+
version: str
|
|
94
|
+
registered: bool
|
|
95
|
+
explicit_registration: bool
|
|
96
|
+
started_by_call: bool
|
|
97
|
+
lease_expires_at: datetime
|
|
98
|
+
|
|
99
|
+
@classmethod
|
|
100
|
+
def from_payload(cls, raw: Any) -> ReadyService:
|
|
101
|
+
w = "acquire.services[]"
|
|
102
|
+
src = _obj(raw, w)
|
|
103
|
+
return cls(
|
|
104
|
+
service=_field(src, "service", str, w),
|
|
105
|
+
state=_field(src, "state", str, w),
|
|
106
|
+
version=_field(src, "version", str, w),
|
|
107
|
+
registered=_field(src, "registered", bool, w),
|
|
108
|
+
explicit_registration=_field(src, "explicit_registration", bool, w),
|
|
109
|
+
started_by_call=_field(src, "started_by_call", bool, w),
|
|
110
|
+
lease_expires_at=_ts(src, "lease_expires_at", w), # type: ignore[arg-type]
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass(frozen=True)
|
|
115
|
+
class AcquireResult:
|
|
116
|
+
ready: bool
|
|
117
|
+
holder: str
|
|
118
|
+
service: str
|
|
119
|
+
reacquired: bool
|
|
120
|
+
lease: LeaseInfo
|
|
121
|
+
services: tuple[ReadyService, ...]
|
|
122
|
+
|
|
123
|
+
@classmethod
|
|
124
|
+
def from_payload(cls, raw: Any) -> AcquireResult:
|
|
125
|
+
w = "acquire"
|
|
126
|
+
src = _obj(raw, w)
|
|
127
|
+
lease = _obj(_field(src, "lease", Mapping, w), "acquire.lease")
|
|
128
|
+
return cls(
|
|
129
|
+
ready=_field(src, "ready", bool, w),
|
|
130
|
+
holder=_field(src, "holder", str, w),
|
|
131
|
+
service=_field(src, "service", str, w),
|
|
132
|
+
reacquired=_field(src, "reacquired", bool, w),
|
|
133
|
+
lease=LeaseInfo(
|
|
134
|
+
expires_at=_ts(lease, "expires_at", "acquire.lease"), # type: ignore[arg-type]
|
|
135
|
+
ttl_seconds=_field(lease, "ttl_seconds", int, "acquire.lease"),
|
|
136
|
+
),
|
|
137
|
+
services=tuple(ReadyService.from_payload(i) for i in _list(src, "services", w)),
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass(frozen=True)
|
|
142
|
+
class RenewedLease:
|
|
143
|
+
service: str
|
|
144
|
+
expires_at: datetime
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True)
|
|
148
|
+
class RenewResult:
|
|
149
|
+
holder: str
|
|
150
|
+
ttl_seconds: int
|
|
151
|
+
renewed: tuple[RenewedLease, ...]
|
|
152
|
+
#: Services whose unit was restarted under an exclusive lock: the holder reconnects (Q6).
|
|
153
|
+
restart_required: tuple[str, ...]
|
|
154
|
+
|
|
155
|
+
@classmethod
|
|
156
|
+
def from_payload(cls, raw: Any) -> RenewResult:
|
|
157
|
+
w = "renew"
|
|
158
|
+
src = _obj(raw, w)
|
|
159
|
+
renewed = []
|
|
160
|
+
for item in _list(src, "renewed", w):
|
|
161
|
+
i = _obj(item, "renew.renewed[]")
|
|
162
|
+
renewed.append(
|
|
163
|
+
RenewedLease(
|
|
164
|
+
service=_field(i, "service", str, "renew.renewed[]"),
|
|
165
|
+
expires_at=_ts(i, "expires_at", "renew.renewed[]"), # type: ignore[arg-type]
|
|
166
|
+
)
|
|
167
|
+
)
|
|
168
|
+
return cls(
|
|
169
|
+
holder=_field(src, "holder", str, w),
|
|
170
|
+
ttl_seconds=_field(src, "ttl_seconds", int, w),
|
|
171
|
+
renewed=tuple(renewed),
|
|
172
|
+
restart_required=_strs(src, "restart_required", w),
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass(frozen=True)
|
|
177
|
+
class ReleasedLease:
|
|
178
|
+
service: str
|
|
179
|
+
leases_left: int
|
|
180
|
+
idle_stop_at: datetime | None
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass(frozen=True)
|
|
184
|
+
class ReleaseResult:
|
|
185
|
+
holder: str
|
|
186
|
+
released: tuple[ReleasedLease, ...]
|
|
187
|
+
|
|
188
|
+
@classmethod
|
|
189
|
+
def from_payload(cls, raw: Any) -> ReleaseResult:
|
|
190
|
+
w = "release"
|
|
191
|
+
src = _obj(raw, w)
|
|
192
|
+
released = []
|
|
193
|
+
for item in _list(src, "released", w):
|
|
194
|
+
i = _obj(item, "release.released[]")
|
|
195
|
+
left = _field(i, "leases_left", int, "release.released[]")
|
|
196
|
+
if left < 0:
|
|
197
|
+
raise ResultContractError("release.released[].leases_left: negative")
|
|
198
|
+
released.append(
|
|
199
|
+
ReleasedLease(
|
|
200
|
+
service=_field(i, "service", str, "release.released[]"),
|
|
201
|
+
leases_left=left,
|
|
202
|
+
idle_stop_at=_ts(i, "idle_stop_at", "release.released[]", nullable=True),
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
return cls(holder=_field(src, "holder", str, w), released=tuple(released))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@dataclass(frozen=True)
|
|
209
|
+
class StatusHolder:
|
|
210
|
+
holder: str
|
|
211
|
+
expires_at: datetime
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@dataclass(frozen=True)
|
|
215
|
+
class ExclusiveInfo:
|
|
216
|
+
holder: str
|
|
217
|
+
locked_at: datetime
|
|
218
|
+
expires_at: datetime
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass(frozen=True)
|
|
222
|
+
class ServiceStatus:
|
|
223
|
+
service: str
|
|
224
|
+
state: str
|
|
225
|
+
version: str | None
|
|
226
|
+
holders: tuple[StatusHolder, ...]
|
|
227
|
+
idle_stop_at: datetime | None
|
|
228
|
+
exclusive: ExclusiveInfo | None
|
|
229
|
+
|
|
230
|
+
@classmethod
|
|
231
|
+
def from_payload(cls, raw: Any) -> ServiceStatus:
|
|
232
|
+
w = "status.services[]"
|
|
233
|
+
src = _obj(raw, w)
|
|
234
|
+
state = _field(src, "state", str, w)
|
|
235
|
+
if state not in SERVICE_STATES:
|
|
236
|
+
raise ResultContractError(f"{w}.state: {state!r} is outside {sorted(SERVICE_STATES)}")
|
|
237
|
+
version = src.get("version")
|
|
238
|
+
if "version" not in src or not (version is None or isinstance(version, str)):
|
|
239
|
+
raise ResultContractError(f"{w}.version: expected a string or null")
|
|
240
|
+
holders = []
|
|
241
|
+
for item in _list(src, "holders", w):
|
|
242
|
+
h = _obj(item, f"{w}.holders[]")
|
|
243
|
+
holders.append(
|
|
244
|
+
StatusHolder(
|
|
245
|
+
holder=_field(h, "holder", str, f"{w}.holders[]"),
|
|
246
|
+
expires_at=_ts(h, "expires_at", f"{w}.holders[]"), # type: ignore[arg-type]
|
|
247
|
+
)
|
|
248
|
+
)
|
|
249
|
+
if "exclusive" not in src:
|
|
250
|
+
raise ResultContractError(f"{w}: missing field 'exclusive'")
|
|
251
|
+
exclusive = None
|
|
252
|
+
if src["exclusive"] is not None:
|
|
253
|
+
e = _obj(src["exclusive"], f"{w}.exclusive")
|
|
254
|
+
exclusive = ExclusiveInfo(
|
|
255
|
+
holder=_field(e, "holder", str, f"{w}.exclusive"),
|
|
256
|
+
locked_at=_ts(e, "locked_at", f"{w}.exclusive"), # type: ignore[arg-type]
|
|
257
|
+
expires_at=_ts(e, "expires_at", f"{w}.exclusive"), # type: ignore[arg-type]
|
|
258
|
+
)
|
|
259
|
+
return cls(
|
|
260
|
+
service=_field(src, "service", str, w),
|
|
261
|
+
state=state,
|
|
262
|
+
version=version,
|
|
263
|
+
holders=tuple(holders),
|
|
264
|
+
idle_stop_at=_ts(src, "idle_stop_at", w, nullable=True),
|
|
265
|
+
exclusive=exclusive,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
@dataclass(frozen=True)
|
|
270
|
+
class StatusResult:
|
|
271
|
+
generated_at: datetime
|
|
272
|
+
services: tuple[ServiceStatus, ...]
|
|
273
|
+
|
|
274
|
+
@classmethod
|
|
275
|
+
def from_payload(cls, raw: Any) -> StatusResult:
|
|
276
|
+
w = "status"
|
|
277
|
+
src = _obj(raw, w)
|
|
278
|
+
return cls(
|
|
279
|
+
generated_at=_ts(src, "generated_at", w), # type: ignore[arg-type]
|
|
280
|
+
services=tuple(ServiceStatus.from_payload(i) for i in _list(src, "services", w)),
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
@dataclass(frozen=True)
|
|
285
|
+
class LockResult:
|
|
286
|
+
service: str
|
|
287
|
+
holder: str
|
|
288
|
+
locked_at: datetime
|
|
289
|
+
expires_at: datetime
|
|
290
|
+
|
|
291
|
+
@classmethod
|
|
292
|
+
def from_payload(cls, raw: Any) -> LockResult:
|
|
293
|
+
w = "lock_exclusive"
|
|
294
|
+
src = _obj(raw, w)
|
|
295
|
+
return cls(
|
|
296
|
+
service=_field(src, "service", str, w),
|
|
297
|
+
holder=_field(src, "holder", str, w),
|
|
298
|
+
locked_at=_ts(src, "locked_at", w), # type: ignore[arg-type]
|
|
299
|
+
expires_at=_ts(src, "expires_at", w), # type: ignore[arg-type]
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@dataclass(frozen=True)
|
|
304
|
+
class UnlockResult:
|
|
305
|
+
service: str
|
|
306
|
+
holder: str
|
|
307
|
+
unlocked: bool
|
|
308
|
+
|
|
309
|
+
@classmethod
|
|
310
|
+
def from_payload(cls, raw: Any) -> UnlockResult:
|
|
311
|
+
w = "unlock_exclusive"
|
|
312
|
+
src = _obj(raw, w)
|
|
313
|
+
return cls(
|
|
314
|
+
service=_field(src, "service", str, w),
|
|
315
|
+
holder=_field(src, "holder", str, w),
|
|
316
|
+
unlocked=_field(src, "unlocked", bool, w),
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
@dataclass(frozen=True)
|
|
321
|
+
class CatalogEntry:
|
|
322
|
+
service: str
|
|
323
|
+
unit: str
|
|
324
|
+
containers: tuple[str, ...]
|
|
325
|
+
proxy_id: str
|
|
326
|
+
health: str
|
|
327
|
+
version_source: str
|
|
328
|
+
dependencies: tuple[str, ...]
|
|
329
|
+
lease_ttl_seconds: int
|
|
330
|
+
idle_stop_seconds: int
|
|
331
|
+
start_timeout_seconds: int
|
|
332
|
+
sweeper_interval_seconds: int
|
|
333
|
+
|
|
334
|
+
@classmethod
|
|
335
|
+
def from_payload(cls, raw: Any) -> CatalogEntry:
|
|
336
|
+
w = "catalog.services[]"
|
|
337
|
+
src = _obj(raw, w)
|
|
338
|
+
return cls(
|
|
339
|
+
service=_field(src, "service", str, w),
|
|
340
|
+
unit=_field(src, "unit", str, w),
|
|
341
|
+
containers=_strs(src, "containers", w),
|
|
342
|
+
proxy_id=_field(src, "proxy_id", str, w),
|
|
343
|
+
health=_field(src, "health", str, w),
|
|
344
|
+
version_source=_field(src, "version_source", str, w),
|
|
345
|
+
dependencies=_strs(src, "dependencies", w),
|
|
346
|
+
lease_ttl_seconds=_field(src, "lease_ttl_seconds", int, w),
|
|
347
|
+
idle_stop_seconds=_field(src, "idle_stop_seconds", int, w),
|
|
348
|
+
start_timeout_seconds=_field(src, "start_timeout_seconds", int, w),
|
|
349
|
+
sweeper_interval_seconds=_field(src, "sweeper_interval_seconds", int, w),
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
@dataclass(frozen=True)
|
|
354
|
+
class CatalogResult:
|
|
355
|
+
services: tuple[CatalogEntry, ...]
|
|
356
|
+
|
|
357
|
+
@classmethod
|
|
358
|
+
def from_payload(cls, raw: Any) -> CatalogResult:
|
|
359
|
+
src = _obj(raw, "catalog")
|
|
360
|
+
return cls(services=tuple(CatalogEntry.from_payload(i) for i in _list(src, "services", "catalog")))
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Client-side validation of the holder (decision Q1)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any, Final
|
|
7
|
+
|
|
8
|
+
from .errors import HolderFormatError
|
|
9
|
+
|
|
10
|
+
__all__ = ["HOLDER_PATTERN", "validate_holder"]
|
|
11
|
+
|
|
12
|
+
#: `<project>/<run_id>`: exactly one "/", each segment 1..64 characters of [a-z0-9._-].
|
|
13
|
+
HOLDER_PATTERN: Final[re.Pattern[str]] = re.compile(r"[a-z0-9._-]{1,64}/[a-z0-9._-]{1,64}")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def validate_holder(holder: Any) -> str:
|
|
17
|
+
"""
|
|
18
|
+
Return `holder` when it matches the contract format, else raise HolderFormatError
|
|
19
|
+
with the same violation the server would report: `type` for a non-string,
|
|
20
|
+
`value` for any format violation.
|
|
21
|
+
"""
|
|
22
|
+
if not isinstance(holder, str):
|
|
23
|
+
raise HolderFormatError(
|
|
24
|
+
"holder must be a string",
|
|
25
|
+
violation="type",
|
|
26
|
+
field="holder",
|
|
27
|
+
expected="str",
|
|
28
|
+
got=type(holder).__name__,
|
|
29
|
+
)
|
|
30
|
+
if HOLDER_PATTERN.fullmatch(holder) is None:
|
|
31
|
+
raise HolderFormatError(
|
|
32
|
+
"holder must be '<project>/<run_id>': one '/', each segment 1..64 of [a-z0-9._-]",
|
|
33
|
+
violation="value",
|
|
34
|
+
field="holder",
|
|
35
|
+
expected="<project>/<run_id>",
|
|
36
|
+
got=holder,
|
|
37
|
+
)
|
|
38
|
+
return holder
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ai-devlease-client
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Typed client of the ai-devlease lease manager - a wrapper over the mcp-proxy-adapter framework client
|
|
5
|
+
Author-email: Vasiliy Zdanovskiy <vasilyvz@gmail.com>
|
|
6
|
+
License: Proprietary
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: mcp-proxy-adapter>=8.11.3
|
|
10
|
+
|
|
11
|
+
# ai-devlease-client
|
|
12
|
+
|
|
13
|
+
Typed async client of the ai-devlease lease manager (import `ai_devlease_client`).
|
|
14
|
+
|
|
15
|
+
Commands: `acquire` (adapter queue: submit, then poll the job), `renew` (holder only),
|
|
16
|
+
`release`, `status`, `lock_exclusive`, `unlock_exclusive`, `catalog`, `help`, `health`.
|
|
17
|
+
Holder format is `<project>/<run_id>` (one `/`, each segment 1..64 of `[a-z0-9._-]`) and is
|
|
18
|
+
validated before the call. Errors map to typed exceptions: `-32602` to `ValidationError`
|
|
19
|
+
and `-32010..-32017` to `ServiceNotInCatalogError` .. `StorageError`.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
async with AiDevleaseClient.from_document_path("config.json") as client:
|
|
23
|
+
async with client.lease("proj/run1", "fake-a") as lease:
|
|
24
|
+
... # renewed every 60 s; lease.restart_required lists services to reconnect to
|
|
25
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
ai_devlease_client/__init__.py,sha256=tAlHmfw3izT_So67S8AExA_Zpwii5msOKNh34UtSYhw,1567
|
|
2
|
+
ai_devlease_client/_version.py,sha256=JYVj9pwmXg8ZaCaNyUjOUo7hq2WTNXDrUMcBVGa4cdM,78
|
|
3
|
+
ai_devlease_client/client.py,sha256=SFrRqN0g816a0uE95lAjBs_dPHit4D-YmtrJBrngBOo,13264
|
|
4
|
+
ai_devlease_client/config.py,sha256=FQjWgEC2FkBVhPhQ_7NvaBHKXT-uivzcoOORV8Acrhs,4440
|
|
5
|
+
ai_devlease_client/errors.py,sha256=at_juk3GnBV9Rzvd19htNlUxPZdvein45qnP-TZFJN8,7094
|
|
6
|
+
ai_devlease_client/lease.py,sha256=Dk4avmSQxcPNaDhz1nI7cMhvfnBNKXhpydwyjQrsxiQ,6339
|
|
7
|
+
ai_devlease_client/models.py,sha256=nQ0t0SUfRTI5xik-VO_2GgUbHQFXf8ylWrgUFVfbv54,11529
|
|
8
|
+
ai_devlease_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
ai_devlease_client/validation.py,sha256=ld-YK_qDvhr0K7fyEeeoiBpWXaIfQ4t7l8HuxOsDKMY,1239
|
|
10
|
+
ai_devlease_client-0.1.1.dist-info/METADATA,sha256=bcv0gRHAHUrolZPwFm3WQIKPJTp3deRDwM-BoZdwEOw,1124
|
|
11
|
+
ai_devlease_client-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
ai_devlease_client-0.1.1.dist-info/top_level.txt,sha256=Xp-JO47zHyRILY4KsRUhweYEczidmIS3kViwW1BAytw,19
|
|
13
|
+
ai_devlease_client-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ai_devlease_client
|