sub-pool-client 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.

Potentially problematic release.


This version of sub-pool-client might be problematic. Click here for more details.

@@ -0,0 +1,462 @@
1
+ """PooledClient — credential-broker mode with cross-process shared dir.
2
+
3
+ The pool is a credential broker, not a request proxy. This client:
4
+
5
+ 1. `__aenter__`:
6
+ - flocks a shared dir keyed by (pool_url, api_key, user_id, model)
7
+ - if nobody else holds a lease here: POST /credentials/lease,
8
+ write the full OAuth bundle to $SHARED/.credentials.json
9
+ - otherwise: just add our pid to the holders list and reuse the
10
+ already-present .credentials.json
11
+ - unlock
12
+ - spawn `ClaudeSDKClient` locally with env[CLAUDE_CONFIG_DIR]=$SHARED
13
+
14
+ 2. CLI runs: multiple concurrent CLI subprocesses (from parallel
15
+ PooledClient instances) share one .credentials.json. When the
16
+ access_token nears expiry, whichever CLI trips first refreshes via
17
+ Anthropic directly and writes back atomically; siblings pick up the
18
+ new bundle on their next 401 → reread → retry cycle. Same pattern
19
+ native CC uses for its own multi-process coordination.
20
+
21
+ 3. `__aexit__`:
22
+ - flocks + removes our pid from holders
23
+ - if holders now empty: read current .credentials.json (CLI may
24
+ have rotated refresh_token mid-run), DELETE lease to pool with
25
+ `updated_credentials=<bundle>` so the pool's refresh chain
26
+ stays continuous, then rmtree the shared dir.
27
+
28
+ The `CLAUDE_CODE_OAUTH_TOKEN` env-var approach is gone. `CLAUDE_CONFIG_DIR`
29
+ is what the CLI writes/reads, and that's what we share.
30
+
31
+ ## Cross-machine note
32
+
33
+ If two consumers on DIFFERENT machines try to hold leases for the same
34
+ account, the shared-dir mechanism can't coordinate — each host has its
35
+ own filesystem. Expect `invalid_grant` the moment one side refreshes.
36
+ Scale by adding accounts, not by cross-host sharing.
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import asyncio
41
+ import copy
42
+ import json
43
+ import logging
44
+ import os
45
+ import time
46
+ from pathlib import Path
47
+ from typing import Any
48
+
49
+ import httpx
50
+ from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient # type: ignore
51
+
52
+ from sub_pool_client._shared import (
53
+ cleanup_dir,
54
+ dir_key,
55
+ locked_meta,
56
+ shared_dir,
57
+ write_credentials,
58
+ )
59
+ from sub_pool_client.errors import (
60
+ PoolAuthError,
61
+ PoolConnectionError,
62
+ PoolUpstreamError,
63
+ )
64
+
65
+ log = logging.getLogger(__name__)
66
+
67
+
68
+ class PooledClient(ClaudeSDKClient):
69
+ """Drop-in replacement for `ClaudeSDKClient` that leases credentials
70
+ from a sub-pool instance before spawning the SDK subprocess."""
71
+
72
+ def __init__(
73
+ self,
74
+ options: ClaudeAgentOptions | None = None,
75
+ *,
76
+ pool_url: str | None = None,
77
+ api_key: str | None = None,
78
+ user_id: str | None = None,
79
+ request_id: str | None = None,
80
+ required_model: str | None = None,
81
+ required_features: list[str] | None = None,
82
+ http_client: httpx.AsyncClient | None = None,
83
+ ):
84
+ self._pool_url = (pool_url or os.environ.get("SUB_POOL_URL", "")).rstrip("/")
85
+ self._api_key = api_key or os.environ.get("SUB_POOL_KEY", "")
86
+ if not self._pool_url:
87
+ raise ValueError("pool_url required (set SUB_POOL_URL)")
88
+ if not self._api_key:
89
+ raise ValueError("api_key required (set SUB_POOL_KEY)")
90
+
91
+ self._user_id = user_id
92
+ self._request_id_req = request_id
93
+ self._required_model = required_model
94
+ self._required_features = list(required_features or [])
95
+
96
+ # Caller-supplied options are never mutated; we copy to attach env.
97
+ self._base_options = copy.copy(options) if options else ClaudeAgentOptions()
98
+ self._base_options.env = dict(self._base_options.env or {})
99
+
100
+ # HTTP client for lease + release
101
+ self._owned_http = http_client is None
102
+ self._http = http_client or httpx.AsyncClient(timeout=10.0)
103
+
104
+ # Populated on __aenter__
105
+ self._dir: Path | None = None # shared dir path
106
+ self._is_first_holder = False # we were the one who leased
107
+ self._is_poll_leader = False # we run the token poll task
108
+ self._lease_id: str | None = None
109
+ self._lease_account: str | None = None
110
+ self._lease_request_id: str | None = None
111
+ self._token_expires_at: float = 0.0
112
+ self._sdk_inited = False
113
+ self._poll_task: asyncio.Task | None = None
114
+ self._heartbeat_task: asyncio.Task | None = None
115
+
116
+ # ============================================================ lifecycle
117
+ async def __aenter__(self) -> "PooledClient":
118
+ key = dir_key(
119
+ pool_url=self._pool_url,
120
+ api_key=self._api_key,
121
+ provider="claude",
122
+ user_id=self._user_id,
123
+ required_model=self._required_model,
124
+ )
125
+ self._dir = shared_dir(key)
126
+
127
+ await self._join_or_acquire_lease()
128
+
129
+ # Tell the CLI where to find .credentials.json
130
+ self._base_options.env["CLAUDE_CONFIG_DIR"] = str(self._dir)
131
+ # Any stale override would shadow .credentials.json and defeat
132
+ # the whole shared-refresh model, so drop it explicitly.
133
+ self._base_options.env.pop("CLAUDE_CODE_OAUTH_TOKEN", None)
134
+
135
+ ClaudeSDKClient.__init__(self, options=self._base_options)
136
+ self._sdk_inited = True
137
+ await ClaudeSDKClient.__aenter__(self)
138
+
139
+ if self._is_poll_leader:
140
+ self._poll_task = asyncio.create_task(self._poll_loop())
141
+ # Every holder runs the heartbeat — cheap, and takes over
142
+ # leadership if the current leader crashed.
143
+ self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
144
+
145
+ return self
146
+
147
+ async def __aexit__(self, exc_type, exc, tb) -> None:
148
+ for attr in ("_poll_task", "_heartbeat_task"):
149
+ t = getattr(self, attr, None)
150
+ if t is not None:
151
+ t.cancel()
152
+ try:
153
+ await t
154
+ except (asyncio.CancelledError, Exception):
155
+ pass
156
+ setattr(self, attr, None)
157
+
158
+ if self._sdk_inited:
159
+ try:
160
+ await ClaudeSDKClient.__aexit__(self, exc_type, exc, tb)
161
+ except Exception:
162
+ log.exception("SDK __aexit__ failed")
163
+
164
+ await self._leave_lease(exc)
165
+
166
+ if self._owned_http:
167
+ await self._http.aclose()
168
+
169
+ # ============================================================ lease state
170
+ async def _join_or_acquire_lease(self) -> None:
171
+ assert self._dir is not None
172
+ my_pid = os.getpid()
173
+
174
+ async with locked_meta(self._dir) as meta:
175
+ if meta.lease_id and meta.holders:
176
+ # Active lease already present — reuse it.
177
+ self._lease_id = meta.lease_id
178
+ # Always append (one entry per __aenter__, not per pid)
179
+ # so N `async with` in the same pid are refcounted by
180
+ # N removes on exit.
181
+ meta.holders.append(my_pid)
182
+ # If no live leader, take the seat. locked_meta already
183
+ # cleared dead-pid leaders so poll_leader is either a
184
+ # live pid or None here.
185
+ if meta.poll_leader is None:
186
+ meta.poll_leader = my_pid
187
+ self._is_poll_leader = True
188
+ return
189
+
190
+ # No live holders → we're the first in. Acquire lease.
191
+ lease = await self._post_lease()
192
+ bundle = lease.get("credentials") or {}
193
+ if not bundle.get("access_token"):
194
+ raise PoolUpstreamError(
195
+ "MissingBundle",
196
+ "lease response did not include a credentials bundle",
197
+ )
198
+ write_credentials(self._dir, bundle)
199
+ self._lease_id = lease["lease_id"]
200
+ self._lease_account = lease.get("account")
201
+ self._lease_request_id = lease.get("request_id")
202
+ self._token_expires_at = float(
203
+ bundle.get("expires_at") or lease.get("token_expires_at") or 0.0
204
+ )
205
+ meta.lease_id = self._lease_id
206
+ meta.holders = [my_pid]
207
+ meta.poll_leader = my_pid
208
+ self._is_first_holder = True
209
+ self._is_poll_leader = True
210
+
211
+ async def _leave_lease(self, exc: BaseException | None) -> None:
212
+ if self._dir is None or self._lease_id is None:
213
+ return
214
+ my_pid = os.getpid()
215
+ last_out = False
216
+ lease_id_to_release: str | None = None
217
+
218
+ async with locked_meta(self._dir) as meta:
219
+ if meta.holders:
220
+ # Drop our pid. If this PooledClient instance was a
221
+ # repeat-in-same-process (same pid, multiple async with),
222
+ # we only remove one occurrence.
223
+ try:
224
+ meta.holders.remove(my_pid)
225
+ except ValueError:
226
+ pass
227
+ # If we were the poll leader, hand leadership off. The next
228
+ # heartbeat in a surviving holder will elect itself and start
229
+ # its own poll_loop.
230
+ if meta.poll_leader == my_pid:
231
+ meta.poll_leader = None
232
+ if not meta.holders:
233
+ lease_id_to_release = meta.lease_id
234
+ last_out = True
235
+
236
+ if last_out and lease_id_to_release is not None:
237
+ try:
238
+ await self._delete_lease(lease_id_to_release, exc)
239
+ except Exception:
240
+ log.exception("lease release failed (best-effort)")
241
+ cleanup_dir(self._dir)
242
+
243
+ # ============================================================ heartbeat
244
+ async def _heartbeat_loop(self, interval_s: float = 30.0) -> None:
245
+ """Periodically re-checks meta.json for liveness of the current
246
+ poll leader. If the leader is gone (crashed / exited) this
247
+ holder promotes itself and starts its own poll_loop.
248
+ """
249
+ try:
250
+ while True:
251
+ await asyncio.sleep(interval_s)
252
+ if self._is_poll_leader or self._dir is None:
253
+ continue
254
+
255
+ my_pid = os.getpid()
256
+ promoted = False
257
+ async with locked_meta(self._dir) as meta:
258
+ # locked_meta already cleared dead-leader pids.
259
+ if meta.poll_leader is None and my_pid in (meta.holders or []):
260
+ meta.poll_leader = my_pid
261
+ promoted = True
262
+ if promoted:
263
+ self._is_poll_leader = True
264
+ self._poll_task = asyncio.create_task(self._poll_loop())
265
+ log.info("heartbeat: promoted self to poll leader")
266
+ return # heartbeat's job done
267
+ except asyncio.CancelledError:
268
+ return
269
+
270
+ # ============================================================ poll
271
+ async def _poll_loop(self) -> None:
272
+ """Periodically ask the pool for a fresh access_token and rewrite
273
+ the shared .credentials.json in place. The CLI atomically picks
274
+ up the new access_token on its next read.
275
+
276
+ Poll schedule: wake up 10 min before current expiry (or 60s if
277
+ already in the window), hit the pool, rewrite file, repeat. We
278
+ do NOT rotate the refresh_token field on disk — the authoritative
279
+ refresh_token lives pool-side; the one in the file is a
280
+ best-effort fallback for when the pool can't be reached.
281
+ """
282
+ try:
283
+ while True:
284
+ remaining = self._token_expires_at - time.time()
285
+ # Wake up 10 min before expiry, minimum 60s sleep so we
286
+ # don't bash the pool during tiny-TTL tests.
287
+ sleep_s = max(60.0, remaining - 600.0)
288
+ await asyncio.sleep(sleep_s)
289
+
290
+ if self._dir is None or self._lease_id is None:
291
+ return
292
+
293
+ try:
294
+ new = await self._post_poll_token()
295
+ except Exception as e: # noqa: BLE001
296
+ log.warning("lease token poll failed: %s", e)
297
+ # Try again in 30s; a transient 5xx / network blip
298
+ # shouldn't tear down the agent.
299
+ self._token_expires_at = time.time() + 60.0
300
+ continue
301
+
302
+ new_access = new.get("access_token")
303
+ new_exp = float(new.get("token_expires_at") or 0.0)
304
+ if not new_access or not new_exp:
305
+ log.warning("lease token poll returned empty bundle: %s", new)
306
+ continue
307
+
308
+ # Rewrite shared .credentials.json with the new access_token
309
+ # (keep existing refresh_token + scopes + subscriptionType).
310
+ try:
311
+ _patch_access_token(self._dir, new_access, new_exp)
312
+ except OSError as e:
313
+ log.warning("failed to update .credentials.json: %s", e)
314
+ continue
315
+
316
+ self._token_expires_at = new_exp
317
+ log.debug(
318
+ "rotated access_token for lease %s (exp=%s)",
319
+ self._lease_id, new_exp,
320
+ )
321
+ except asyncio.CancelledError:
322
+ return
323
+
324
+ async def _post_poll_token(self) -> dict:
325
+ assert self._lease_id is not None
326
+ r = await self._http.post(
327
+ f"{self._pool_url}/credentials/lease/{self._lease_id}/token",
328
+ headers={"authorization": f"Bearer {self._api_key}"},
329
+ )
330
+ if r.status_code >= 400:
331
+ detail = _detail_or_text(r)
332
+ raise PoolUpstreamError(
333
+ str(detail.get("code") or f"HTTP{r.status_code}"),
334
+ str(detail.get("message") or r.text[:500]),
335
+ )
336
+ return r.json()
337
+
338
+ # ============================================================ HTTP
339
+ async def _post_lease(self) -> dict:
340
+ body: dict[str, Any] = {"provider": "claude"}
341
+ if self._user_id:
342
+ body["user_id"] = self._user_id
343
+ if self._request_id_req:
344
+ body["request_id"] = self._request_id_req
345
+ if self._required_model:
346
+ body["required_model"] = self._required_model
347
+ if self._required_features:
348
+ body["required_features"] = list(self._required_features)
349
+ try:
350
+ r = await self._http.post(
351
+ f"{self._pool_url}/credentials/lease",
352
+ headers={"authorization": f"Bearer {self._api_key}"},
353
+ json=body,
354
+ )
355
+ except (httpx.ConnectError, httpx.ReadTimeout) as e:
356
+ raise PoolConnectionError("ConnectError", str(e)) from e
357
+ except httpx.HTTPError as e:
358
+ raise PoolConnectionError("HTTPError", str(e)) from e
359
+
360
+ if r.status_code in (401, 403):
361
+ raise PoolAuthError(
362
+ f"HTTP{r.status_code}", r.text[:500] or "authorization failed",
363
+ )
364
+ if r.status_code >= 400:
365
+ detail = _detail_or_text(r)
366
+ raise PoolUpstreamError(
367
+ str(detail.get("code") or f"HTTP{r.status_code}"),
368
+ str(detail.get("message") or r.text[:500]),
369
+ )
370
+ return r.json()
371
+
372
+ async def _delete_lease(
373
+ self, lease_id: str, exc: BaseException | None,
374
+ ) -> None:
375
+ body: dict[str, Any] = {}
376
+ if exc is not None:
377
+ body["error_code"] = type(exc).__name__
378
+ body["error_message"] = str(exc)[:2000]
379
+ try:
380
+ await self._http.request(
381
+ "DELETE",
382
+ f"{self._pool_url}/credentials/lease/{lease_id}",
383
+ headers={"authorization": f"Bearer {self._api_key}"},
384
+ json=body,
385
+ )
386
+ except Exception as e: # noqa: BLE001
387
+ log.warning("DELETE lease %s failed (best-effort): %s", lease_id, e)
388
+
389
+ # ============================================================ error reporting
390
+ async def report_error(self, code: str, message: str) -> dict:
391
+ """Mid-lease: tell the pool about a backend error (429 rate
392
+ limit, quota exhausted, etc.) so it can mark the account COOLING
393
+ and route parallel leases elsewhere. The lease itself stays
394
+ alive — caller decides whether to keep using it or tear down
395
+ and re-lease on a different account.
396
+ """
397
+ if self._lease_id is None:
398
+ return {}
399
+ try:
400
+ r = await self._http.post(
401
+ f"{self._pool_url}/credentials/lease/{self._lease_id}/report-error",
402
+ headers={"authorization": f"Bearer {self._api_key}"},
403
+ json={"code": code, "message": message},
404
+ )
405
+ except Exception as e: # noqa: BLE001
406
+ log.warning("report_error HTTP failed: %s", e)
407
+ return {}
408
+ if r.status_code >= 400:
409
+ log.warning("report_error %s: %s", r.status_code, r.text[:200])
410
+ return {}
411
+ return r.json()
412
+
413
+ # ============================================================ introspection
414
+ @property
415
+ def account(self) -> str | None:
416
+ return self._lease_account
417
+
418
+ @property
419
+ def lease_id(self) -> str | None:
420
+ return self._lease_id
421
+
422
+ @property
423
+ def request_id(self) -> str | None:
424
+ return self._lease_request_id
425
+
426
+
427
+ def _patch_access_token(dir_: Path, new_access: str, new_expires_s: float) -> None:
428
+ """Rewrite dir/.credentials.json in CLI schema, overwriting only
429
+ accessToken + expiresAt. Other fields (refreshToken, scopes, ...)
430
+ preserved. Atomic rename, 0600 perms."""
431
+ p = dir_ / ".credentials.json"
432
+ try:
433
+ payload = json.loads(p.read_text()) if p.exists() else {}
434
+ except (OSError, ValueError):
435
+ payload = {}
436
+ nested = payload.setdefault("claudeAiOauth", {})
437
+ nested["accessToken"] = new_access
438
+ nested["expiresAt"] = int(new_expires_s * 1000)
439
+ tmp = p.with_suffix(p.suffix + ".tmp")
440
+ fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
441
+ try:
442
+ with os.fdopen(fd, "w") as f:
443
+ json.dump(payload, f, indent=2)
444
+ except BaseException:
445
+ try:
446
+ os.unlink(tmp)
447
+ except OSError:
448
+ pass
449
+ raise
450
+ os.replace(tmp, p)
451
+
452
+
453
+ def _detail_or_text(r: httpx.Response) -> dict:
454
+ try:
455
+ body = r.json()
456
+ except Exception:
457
+ return {}
458
+ if isinstance(body, dict):
459
+ detail = body.get("detail") or body.get("error")
460
+ if isinstance(detail, dict):
461
+ return detail
462
+ return {}