subactor-procache 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.
procache/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """Small, provider-neutral cache for safe read-side API calls."""
2
+
3
+ from .cache import CacheEntry, ProCache, ProviderCooldownError, SQLiteResponseCache, is_rate_limit_error
4
+ from .commands import CachedCommandResult, CachedReadCommand, github_env
5
+ from .pygithub import CachedPyGithubRequester
6
+
7
+ __all__ = [
8
+ "CacheEntry",
9
+ "CachedCommandResult",
10
+ "CachedPyGithubRequester",
11
+ "CachedReadCommand",
12
+ "ProCache",
13
+ "ProviderCooldownError",
14
+ "SQLiteResponseCache",
15
+ "github_env",
16
+ "is_rate_limit_error",
17
+ ]
procache/cache.py ADDED
@@ -0,0 +1,494 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import random
7
+ import re
8
+ import sqlite3
9
+ import threading
10
+ import time
11
+ import uuid
12
+ from collections.abc import Callable
13
+ from contextlib import closing
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import ClassVar, TypeVar
17
+ from weakref import WeakValueDictionary
18
+
19
+ T = TypeVar("T")
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class CacheEntry:
24
+ key: str
25
+ value: bytes
26
+ expires_at: float
27
+ etag: str | None = None
28
+
29
+
30
+ class ProviderCooldownError(RuntimeError):
31
+ """Raised while a provider rate-limit cooldown is active."""
32
+
33
+ def __init__(self, provider: str, remaining: float) -> None:
34
+ self.provider = provider
35
+ self.remaining = max(0.0, remaining)
36
+ super().__init__(f"provider {provider!r} is cooling down for {self.remaining:.1f}s")
37
+
38
+
39
+ def is_rate_limit_error(error: Exception) -> bool:
40
+ """Recognize common 429/secondary-limit provider errors without dependencies."""
41
+ status = getattr(error, "status_code", None)
42
+ if status is None:
43
+ status = getattr(error, "status", None)
44
+ if status is None:
45
+ status = getattr(error, "code", None)
46
+ message = str(error).lower()
47
+ if status == 429 or re.search(r"\bhttp(?:/\d(?:\.\d)?)?[ :]+429\b", message):
48
+ return True
49
+ headers = getattr(error, "headers", None)
50
+ headers = {str(k).lower(): str(v) for k, v in headers.items()} if isinstance(headers, dict) else {}
51
+ if status == 403 and (headers.get("x-ratelimit-remaining") == "0" or "retry-after" in headers):
52
+ return True
53
+ # CLI stderr can contain branch names, paths and URLs. Those identifiers
54
+ # are not provider evidence, even when named rate-limit or similar.
55
+ message = re.sub(r"(['\"`])(?:\.{0,2}/|[\w.-]+/|https?://)[^\r\n]*?\1", " ", message)
56
+ message = re.sub(r"(?<!\w)(?:https?://|(?:[\w.-]+/)+)\S+", " ", message)
57
+ diagnostics = (
58
+ r"\brate[ -]limits?\s+(?:exceeded|exhausted|reached)\b",
59
+ r"\b(?:exceeded|hit|reached|triggered)\s+(?:(?:an?|the|your|api|secondary)\s+){0,4}rate[ -]limits?\b",
60
+ r"\bsecondary[ -](?:rate[ -])?limit\b",
61
+ r"\babuse detection mechanism\b",
62
+ r"\brate-limited\b|\btoo many requests\b",
63
+ r"^\s*(?:error[: ]+)?(?:api )?rate[ -]limit[.!]?\s*$",
64
+ )
65
+ return any(re.search(pattern, message) for pattern in diagnostics)
66
+
67
+
68
+ class SQLiteResponseCache:
69
+ """A bounded persistent cache for provider reads.
70
+
71
+ The cache is deliberately blind to provider payloads. Callers choose the
72
+ stable key and TTL, while mutations never enter this class. SQLite WAL and
73
+ a per-key process lock make concurrent agent processes converge on one
74
+ value instead of issuing a request storm.
75
+ """
76
+
77
+ # The first write of each instance and every PRUNE_EVERY-th after it
78
+ # retires up to PRUNE_BATCH expired rows: on average four per write, which
79
+ # outpaces insertion so the file stops growing, while the write lock and
80
+ # the per-write cost stay small.
81
+ PRUNE_BATCH = 64
82
+ PRUNE_EVERY = 16
83
+ # Longest pause between checks while another process loads the same key.
84
+ MAX_WAIT_INTERVAL = 0.5
85
+ SQLITE_TIMEOUT = 30.0
86
+ MAX_RETRY_INTERVAL = 0.05
87
+ _LOCKED_ERRORS = frozenset({
88
+ "database is locked",
89
+ "database table is locked",
90
+ "database schema is locked",
91
+ })
92
+
93
+ _locks: ClassVar[WeakValueDictionary[str, threading.Lock]] = WeakValueDictionary()
94
+ _locks_guard = threading.Lock()
95
+ _write_locks: ClassVar[WeakValueDictionary[str, threading.Lock]] = WeakValueDictionary()
96
+ _write_locks_guard = threading.Lock()
97
+
98
+ def __init__(
99
+ self,
100
+ path: str | Path,
101
+ *,
102
+ namespace: str = "default",
103
+ clock: Callable[[], float] | None = None,
104
+ ) -> None:
105
+ self.path = Path(path)
106
+ self.namespace = namespace
107
+ self._clock = time.time if clock is None else clock
108
+ self._writes = 0
109
+ self._local = threading.local()
110
+ self.path.parent.mkdir(parents=True, exist_ok=True)
111
+ self._resolved_path = str(self.path.resolve())
112
+ self._cached_write_lock: threading.Lock | None = None
113
+ self._write_lock_pid: int | None = None
114
+ self._run_write(self._ensure_schema)
115
+
116
+ @staticmethod
117
+ def _ensure_schema(db: sqlite3.Connection) -> None:
118
+ for statement in (
119
+ """
120
+ CREATE TABLE IF NOT EXISTS responses (
121
+ namespace TEXT NOT NULL,
122
+ cache_key TEXT NOT NULL,
123
+ value BLOB NOT NULL,
124
+ expires_at REAL NOT NULL,
125
+ etag TEXT,
126
+ updated_at REAL NOT NULL,
127
+ PRIMARY KEY (namespace, cache_key)
128
+ )
129
+ """,
130
+ "CREATE INDEX IF NOT EXISTS responses_expiry ON responses(expires_at)",
131
+ """
132
+ CREATE TABLE IF NOT EXISTS flights (
133
+ namespace TEXT NOT NULL,
134
+ cache_key TEXT NOT NULL,
135
+ owner TEXT NOT NULL,
136
+ expires_at REAL NOT NULL,
137
+ PRIMARY KEY (namespace, cache_key)
138
+ )
139
+ """,
140
+ """
141
+ CREATE TABLE IF NOT EXISTS cooldowns (
142
+ namespace TEXT NOT NULL,
143
+ cooldown_key TEXT NOT NULL,
144
+ until_at REAL NOT NULL,
145
+ updated_at REAL NOT NULL,
146
+ PRIMARY KEY (namespace, cooldown_key)
147
+ )
148
+ """,
149
+ ):
150
+ with closing(db.execute(statement)):
151
+ pass
152
+
153
+ @classmethod
154
+ def _is_locked_error(cls, error: sqlite3.OperationalError) -> bool:
155
+ return str(error).strip().lower() in cls._LOCKED_ERRORS
156
+
157
+ @classmethod
158
+ def _retry_locked(
159
+ cls,
160
+ operation: Callable[[], T],
161
+ *,
162
+ timeout: float | None = None,
163
+ max_interval: float | None = None,
164
+ ) -> T:
165
+ limit = cls.SQLITE_TIMEOUT if timeout is None else timeout
166
+ cap = cls.MAX_RETRY_INTERVAL if max_interval is None else max_interval
167
+ deadline = time.monotonic() + limit
168
+ delay = 0.005
169
+ while True:
170
+ try:
171
+ return operation()
172
+ except sqlite3.OperationalError as error:
173
+ remaining = deadline - time.monotonic()
174
+ if not cls._is_locked_error(error) or remaining <= 0:
175
+ raise
176
+ # Jittered backoff spreads waking callers after WAL or busy-lock contention.
177
+ step = min(delay, remaining)
178
+ time.sleep(step * (0.5 + 0.5 * random.random()))
179
+ delay = min(delay * 1.5, cap)
180
+
181
+ def _connect(self) -> sqlite3.Connection:
182
+ pid = os.getpid()
183
+ db = getattr(self._local, "connection", None)
184
+ if db is None or getattr(self._local, "pid", None) != pid:
185
+ timeout = self.SQLITE_TIMEOUT
186
+ db = sqlite3.connect(self.path, timeout=timeout, isolation_level="IMMEDIATE")
187
+ try:
188
+ db.execute(f"PRAGMA busy_timeout={int(timeout * 1000)}")
189
+ self._enable_wal(db, timeout=timeout)
190
+ except BaseException:
191
+ db.close()
192
+ raise
193
+ self._local.connection = db
194
+ self._local.pid = pid
195
+ return db
196
+
197
+ @classmethod
198
+ def _enable_wal(cls, db: sqlite3.Connection, *, timeout: float | None = None) -> None:
199
+ # Concurrent first open can return SQLITE_BUSY from the mode change
200
+ # without honoring busy_timeout. Keep retries within the same bound.
201
+ cls._retry_locked(lambda: db.execute("PRAGMA journal_mode=WAL"), timeout=timeout)
202
+
203
+ def close(self) -> None:
204
+ """Close this instance's connection in the current thread only."""
205
+ db = getattr(self._local, "connection", None)
206
+ self._local.connection = None
207
+ self._local.pid = None
208
+ if db is not None:
209
+ db.close()
210
+
211
+ def __enter__(self):
212
+ return self
213
+
214
+ def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
215
+ self.close()
216
+
217
+ @staticmethod
218
+ def _named_lock(
219
+ pool: WeakValueDictionary[str, threading.Lock],
220
+ guard: threading.Lock,
221
+ key: str,
222
+ ) -> threading.Lock:
223
+ with guard:
224
+ return pool.setdefault(key, threading.Lock())
225
+
226
+ @classmethod
227
+ def _lock_for(cls, key: str) -> threading.Lock:
228
+ # Holders and waiters retain strong references. Completed one-use keys
229
+ # disappear once nobody can still acquire that lock.
230
+ return cls._named_lock(cls._locks, cls._locks_guard, key)
231
+
232
+ def _write_lock(self) -> threading.Lock:
233
+ pid = os.getpid()
234
+ lock = self._cached_write_lock
235
+ if lock is None or self._write_lock_pid != pid:
236
+ lock = self._named_lock(
237
+ self._write_locks,
238
+ self._write_locks_guard,
239
+ f"{pid}:{self._resolved_path}",
240
+ )
241
+ self._cached_write_lock = lock
242
+ self._write_lock_pid = pid
243
+ return lock
244
+
245
+ def _execute_in_db(self, action: Callable[[sqlite3.Connection], T]) -> T:
246
+ with self._connect() as db:
247
+ return action(db)
248
+
249
+ def _run_read(self, action: Callable[[sqlite3.Connection], T]) -> T:
250
+ return self._retry_locked(
251
+ lambda: self._execute_in_db(action),
252
+ timeout=self.SQLITE_TIMEOUT,
253
+ max_interval=self.MAX_RETRY_INTERVAL,
254
+ )
255
+
256
+ def _run_write(
257
+ self,
258
+ action: Callable[[sqlite3.Connection], T],
259
+ *,
260
+ on_commit: Callable[[], None] | None = None,
261
+ ) -> T:
262
+ with self._write_lock():
263
+ result = self._retry_locked(
264
+ lambda: self._execute_in_db(action),
265
+ timeout=self.SQLITE_TIMEOUT,
266
+ max_interval=self.MAX_RETRY_INTERVAL,
267
+ )
268
+ if on_commit is not None:
269
+ on_commit()
270
+ return result
271
+
272
+ @staticmethod
273
+ def _fetchone(
274
+ db: sqlite3.Connection,
275
+ sql: str,
276
+ params: tuple[object, ...],
277
+ ) -> tuple[object, ...] | None:
278
+ with closing(db.execute(sql, params)) as cursor:
279
+ return cursor.fetchone()
280
+
281
+ @staticmethod
282
+ def _execute(
283
+ db: sqlite3.Connection,
284
+ sql: str,
285
+ params: tuple[object, ...],
286
+ ) -> int:
287
+ with closing(db.execute(sql, params)) as cursor:
288
+ return int(cursor.rowcount)
289
+
290
+ @staticmethod
291
+ def key(*parts: object) -> str:
292
+ encoded = json.dumps(parts, sort_keys=True, separators=(",", ":"), default=str)
293
+ return hashlib.sha256(encoded.encode()).hexdigest()
294
+
295
+ def get(self, key: str, *, now: float | None = None) -> CacheEntry | None:
296
+ moment = self._clock() if now is None else now
297
+ row = self._run_read(
298
+ lambda db: self._fetchone(
299
+ db,
300
+ "SELECT cache_key, value, expires_at, etag FROM responses "
301
+ "WHERE namespace=? AND cache_key=? AND expires_at>?",
302
+ (self.namespace, key, moment),
303
+ )
304
+ )
305
+ if row is None:
306
+ return None
307
+ return CacheEntry(key=str(row[0]), value=bytes(row[1]), expires_at=float(row[2]), etag=row[3])
308
+
309
+ def put(self, key: str, value: bytes, *, ttl: float, etag: str | None = None) -> CacheEntry:
310
+ if ttl <= 0:
311
+ raise ValueError("cache TTL must be positive")
312
+ now = self._clock()
313
+ expires_at = now + ttl
314
+
315
+ def write(db: sqlite3.Connection) -> None:
316
+ self._execute(
317
+ db,
318
+ "INSERT OR REPLACE INTO responses(namespace,cache_key,value,expires_at,etag,updated_at) "
319
+ "VALUES(?,?,?,?,?,?)",
320
+ (self.namespace, key, sqlite3.Binary(value), expires_at, etag, now),
321
+ )
322
+ # Nothing else removes expired reads, so writes retire a bounded
323
+ # batch inside the transaction they already hold.
324
+ if self._writes % self.PRUNE_EVERY == 0:
325
+ self._execute(
326
+ db,
327
+ "DELETE FROM responses WHERE rowid IN (SELECT rowid FROM responses "
328
+ "WHERE namespace=? AND expires_at<=? LIMIT ?)",
329
+ (self.namespace, now, self.PRUNE_BATCH),
330
+ )
331
+ self._execute(db, "DELETE FROM flights WHERE namespace=? AND expires_at<=?", (self.namespace, now))
332
+
333
+ def advance_writes() -> None:
334
+ self._writes += 1
335
+
336
+ self._run_write(write, on_commit=advance_writes)
337
+ return CacheEntry(key=key, value=value, expires_at=expires_at, etag=etag)
338
+
339
+ def get_or_set(
340
+ self,
341
+ key: str,
342
+ loader: Callable[[], bytes],
343
+ *,
344
+ ttl: float,
345
+ etag: str | None = None,
346
+ should_cache: Callable[[bytes], bool] | None = None,
347
+ cooldown_key: str | None = None,
348
+ cooldown_seconds: float = 60.0,
349
+ is_rate_limit: Callable[[Exception], bool] | None = None,
350
+ ) -> tuple[bytes, bool]:
351
+ """Return ``(value, hit)`` while coalescing callers across processes."""
352
+ if cooldown_key is not None:
353
+ self.raise_if_cooling_down(cooldown_key)
354
+ cached = self.get(key)
355
+ if cached is not None:
356
+ return cached.value, True
357
+ lock_key = SQLiteResponseCache.key("singleflight", str(self.path.resolve()), self.namespace, key)
358
+ with self._lock_for(lock_key):
359
+ owner = uuid.uuid4().hex
360
+ interval = 0.05
361
+ while True:
362
+ if cooldown_key is not None:
363
+ self.raise_if_cooling_down(cooldown_key)
364
+ cached = self.get(key)
365
+ if cached is not None:
366
+ return cached.value, True
367
+ # Waiters only read while another process holds the flight;
368
+ # claiming takes the database write lock.
369
+ if not self._flight_active(key) and self._claim_flight(key, owner):
370
+ break
371
+ time.sleep(interval)
372
+ interval = min(interval * 2, self.MAX_WAIT_INTERVAL)
373
+ try:
374
+ # A previous flight may have completed between the cache check
375
+ # and the claim if it was released just before our transaction.
376
+ cached = self.get(key)
377
+ if cached is not None:
378
+ return cached.value, True
379
+ try:
380
+ value = loader()
381
+ except Exception as exc:
382
+ if cooldown_key is not None and is_rate_limit is not None and is_rate_limit(exc):
383
+ self.cooldown(cooldown_key, ttl=cooldown_seconds)
384
+ raise
385
+ if should_cache is None or should_cache(value):
386
+ self.put(key, value, ttl=ttl, etag=etag)
387
+ return value, False
388
+ finally:
389
+ self._release_flight(key, owner)
390
+
391
+ def _flight_active(self, key: str) -> bool:
392
+ row = self._run_read(
393
+ lambda db: self._fetchone(
394
+ db,
395
+ "SELECT 1 FROM flights WHERE namespace=? AND cache_key=? AND expires_at>?",
396
+ (self.namespace, key, self._clock()),
397
+ )
398
+ )
399
+ return row is not None
400
+
401
+ def _claim_flight(self, key: str, owner: str, *, ttl: float = 120.0) -> bool:
402
+ now = self._clock()
403
+
404
+ def claim(db: sqlite3.Connection) -> bool:
405
+ self._execute(
406
+ db,
407
+ "DELETE FROM flights WHERE namespace=? AND cache_key=? AND expires_at<=?",
408
+ (self.namespace, key, now),
409
+ )
410
+ return (
411
+ self._execute(
412
+ db,
413
+ "INSERT OR IGNORE INTO flights(namespace,cache_key,owner,expires_at) VALUES(?,?,?,?)",
414
+ (self.namespace, key, owner, now + ttl),
415
+ )
416
+ == 1
417
+ )
418
+
419
+ return self._run_write(claim)
420
+
421
+ def _release_flight(self, key: str, owner: str) -> None:
422
+ self._run_write(
423
+ lambda db: self._execute(
424
+ db,
425
+ "DELETE FROM flights WHERE namespace=? AND cache_key=? AND owner=?",
426
+ (self.namespace, key, owner),
427
+ )
428
+ )
429
+
430
+ def cooldown(self, key: str, *, ttl: float) -> float:
431
+ if ttl <= 0:
432
+ raise ValueError("cooldown TTL must be positive")
433
+ now = self._clock()
434
+ until = now + ttl
435
+ self._run_write(
436
+ lambda db: self._execute(
437
+ db,
438
+ "INSERT OR REPLACE INTO cooldowns(namespace,cooldown_key,until_at,updated_at) "
439
+ "VALUES(?,?,?,?)",
440
+ (self.namespace, key, until, now),
441
+ )
442
+ )
443
+ return until
444
+
445
+ def cooldown_remaining(self, key: str, *, now: float | None = None) -> float:
446
+ moment = self._clock() if now is None else now
447
+ row = self._run_read(
448
+ lambda db: self._fetchone(
449
+ db,
450
+ "SELECT until_at FROM cooldowns WHERE namespace=? AND cooldown_key=?",
451
+ (self.namespace, key),
452
+ )
453
+ )
454
+ if row is None:
455
+ return 0.0
456
+ remaining = float(row[0]) - moment
457
+ if remaining <= 0:
458
+ self._run_write(
459
+ lambda db: self._execute(
460
+ db,
461
+ "DELETE FROM cooldowns WHERE namespace=? AND cooldown_key=? AND until_at<=?",
462
+ (self.namespace, key, moment),
463
+ )
464
+ )
465
+ return 0.0
466
+ return remaining
467
+
468
+ def raise_if_cooling_down(self, key: str) -> None:
469
+ remaining = self.cooldown_remaining(key)
470
+ if remaining > 0:
471
+ raise ProviderCooldownError(self.namespace, remaining)
472
+
473
+ def prune(self, *, now: float | None = None) -> int:
474
+ moment = self._clock() if now is None else now
475
+ return self._run_write(
476
+ lambda db: self._execute(
477
+ db,
478
+ "DELETE FROM responses WHERE namespace=? AND expires_at<=?",
479
+ (self.namespace, moment),
480
+ )
481
+ )
482
+
483
+ def clear(self) -> None:
484
+ """Drop cached reads and cooldowns for this provider namespace."""
485
+
486
+ def drop(db: sqlite3.Connection) -> None:
487
+ self._execute(db, "DELETE FROM responses WHERE namespace=?", (self.namespace,))
488
+ self._execute(db, "DELETE FROM cooldowns WHERE namespace=?", (self.namespace,))
489
+ self._execute(db, "DELETE FROM flights WHERE namespace=?", (self.namespace,))
490
+
491
+ self._run_write(drop)
492
+
493
+
494
+ ProCache = SQLiteResponseCache