ai-devlease-client 0.1.1__tar.gz

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.
@@ -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,15 @@
1
+ # ai-devlease-client
2
+
3
+ Typed async client of the ai-devlease lease manager (import `ai_devlease_client`).
4
+
5
+ Commands: `acquire` (adapter queue: submit, then poll the job), `renew` (holder only),
6
+ `release`, `status`, `lock_exclusive`, `unlock_exclusive`, `catalog`, `help`, `health`.
7
+ Holder format is `<project>/<run_id>` (one `/`, each segment 1..64 of `[a-z0-9._-]`) and is
8
+ validated before the call. Errors map to typed exceptions: `-32602` to `ValidationError`
9
+ and `-32010..-32017` to `ServiceNotInCatalogError` .. `StorageError`.
10
+
11
+ ```python
12
+ async with AiDevleaseClient.from_document_path("config.json") as client:
13
+ async with client.lease("proj/run1", "fake-a") as lease:
14
+ ... # renewed every 60 s; lease.restart_required lists services to reconnect to
15
+ ```
@@ -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,3 @@
1
+ """Single version source of the ai-devlease client."""
2
+
3
+ __version__ = "0.1.1"
@@ -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)