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/commands.py ADDED
@@ -0,0 +1,394 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import random
7
+ import re
8
+ import subprocess
9
+ import threading
10
+ import time
11
+ from collections import OrderedDict
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ from .cache import ProviderCooldownError, SQLiteResponseCache, is_rate_limit_error
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class CachedCommandResult:
21
+ args: tuple[str, ...]
22
+ returncode: int
23
+ stdout: str
24
+ stderr: str = ""
25
+ cache_hit: bool = False
26
+
27
+
28
+ class CachedReadCommand:
29
+ """Run allowlisted read commands through a shared SQLite response cache."""
30
+
31
+ def __init__(self, cache: SQLiteResponseCache, *, ttl: float = 15.0) -> None:
32
+ self.cache = cache
33
+ self.ttl = ttl
34
+ self.cooldown_seconds = 60.0
35
+
36
+ @staticmethod
37
+ def is_read(args: Sequence[str]) -> bool:
38
+ argv = tuple(args)
39
+ if not argv or Path(argv[0]).name != "gh":
40
+ return False
41
+ if "--web" in argv or "--watch" in argv:
42
+ return False
43
+ if len(argv) >= 3 and argv[1] == "search":
44
+ return argv[2] in {"prs", "issues", "repos", "commits", "code"}
45
+ if len(argv) >= 3 and argv[1] in {"pr", "issue", "repo"}:
46
+ return argv[2] in {"list", "view", "status", "checks"}
47
+ if len(argv) >= 2 and argv[1] == "api":
48
+ return _api_is_read(argv[2:])
49
+ return False
50
+
51
+ def run(self, args: Sequence[str], *, timeout: int | None = None, env: dict[str, str] | None = None) -> CachedCommandResult:
52
+ argv = tuple(str(item) for item in args)
53
+ if not self.is_read(argv):
54
+ return self._execute(argv, timeout=timeout, env=env)
55
+ effective_env = os.environ if env is None else env
56
+ # gh can keep its effective token in the system credential store,
57
+ # independently of hosts.yml. A username or unchanged config file is
58
+ # therefore not enough to identify that credential across requests.
59
+ if not _cacheable_credential(argv, effective_env):
60
+ return self._execute(argv, timeout=timeout, env=env)
61
+ scope = tuple(
62
+ (name, effective_env.get(name, ""))
63
+ for name in ("GH_HOST", "GH_REPO", "GH_CONFIG_DIR")
64
+ )
65
+ try:
66
+ identity = _credential_scope(effective_env)
67
+ except OSError:
68
+ # If identity cannot be established, execute once without sharing.
69
+ return self._execute(argv, timeout=timeout, env=env)
70
+ # With an explicit host and repository the working directory cannot
71
+ # change the result, so services in different directories share it.
72
+ # Other reads stay partitioned by the repository context of the cwd.
73
+ explicit = argv[1] != "api" and _explicit_host_repository_read(argv, effective_env, True, True)
74
+ context = "explicit-repository" if explicit else os.getcwd()
75
+ key = self.cache.key("command-v2", argv, "scope", scope, context, identity)
76
+ family = _api_family(argv)
77
+ cooldown_key = self.cache.key("provider-v3", effective_env.get("GH_HOST", "github.com"), identity, family)
78
+ def load() -> bytes:
79
+ result = self._execute(argv, timeout=timeout, env=env)
80
+ if result.returncode and is_rate_limit_error(RuntimeError(result.stderr)):
81
+ self.cache.cooldown(cooldown_key, ttl=self._cooldown_until_reset(family, env))
82
+ return json.dumps(
83
+ {"returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr},
84
+ separators=(",", ":"),
85
+ ).encode()
86
+
87
+ try:
88
+ value, hit = self.cache.get_or_set(
89
+ key,
90
+ load,
91
+ ttl=self.ttl,
92
+ should_cache=lambda payload: json.loads(payload)["returncode"] == 0,
93
+ cooldown_key=cooldown_key,
94
+ cooldown_seconds=self.cooldown_seconds,
95
+ is_rate_limit=is_rate_limit_error,
96
+ )
97
+ except ProviderCooldownError as exc:
98
+ return CachedCommandResult(argv, 75, "", str(exc))
99
+ result = json.loads(value)
100
+ return CachedCommandResult(
101
+ argv,
102
+ int(result["returncode"]),
103
+ result["stdout"],
104
+ result["stderr"],
105
+ cache_hit=hit,
106
+ )
107
+
108
+ def _cooldown_until_reset(self, family: str, env: dict[str, str] | None) -> float:
109
+ """Cool down until the exhausted resource resets (bounded, jittered); 60 s without evidence.
110
+
111
+ ``gh api rate_limit`` does not count against the primary rate limit. A
112
+ secondary limit leaves the resource with quota, so the default applies.
113
+ """
114
+ try:
115
+ observed = self._execute(("gh", "api", "rate_limit"), timeout=10, env=env)
116
+ resource = json.loads(observed.stdout)["resources"][family] if observed.returncode == 0 else None
117
+ except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError):
118
+ resource = None
119
+ if not isinstance(resource, dict) or resource.get("remaining") != 0:
120
+ return self.cooldown_seconds
121
+ reset = resource.get("reset")
122
+ if isinstance(reset, bool) or not isinstance(reset, (int, float)):
123
+ return self.cooldown_seconds
124
+ wait = float(reset) - time.time() + random.uniform(1.0, 15.0)
125
+ return min(MAX_COOLDOWN_SECONDS, max(self.cooldown_seconds, wait))
126
+
127
+ @staticmethod
128
+ def _execute(args: tuple[str, ...], *, timeout: int | None, env: dict[str, str] | None) -> CachedCommandResult:
129
+ proc = subprocess.run(args, check=False, timeout=timeout, env=env, capture_output=True, text=True)
130
+ return CachedCommandResult(args, proc.returncode, proc.stdout, proc.stderr)
131
+
132
+
133
+ _FINGERPRINT_LIMIT = 16
134
+ _TOKEN_ENVIRONMENT = ("GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN")
135
+ _API_VALUES = {"-X", "--method", "-f", "--raw-field", "-F", "--field",
136
+ "-H", "--header", "--hostname", "-q", "--jq", "-t", "--template", "-p", "--preview"}
137
+ _fingerprints: OrderedDict[Path, tuple[tuple[int, ...], str]] = OrderedDict()
138
+ _fingerprint_lock = threading.Lock()
139
+
140
+
141
+ def _file_identity(info: os.stat_result) -> tuple[int, ...]:
142
+ return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
143
+
144
+
145
+ def _github_config_fingerprint(path: Path) -> str:
146
+ """Reuse bounded hashes, never raw credentials, across stable file reads."""
147
+ path = path.absolute()
148
+ try:
149
+ identity = _file_identity(path.stat())
150
+ except FileNotFoundError:
151
+ with _fingerprint_lock:
152
+ _fingerprints.pop(path, None)
153
+ return hashlib.sha256(b"").hexdigest()
154
+ with _fingerprint_lock:
155
+ cached = _fingerprints.get(path)
156
+ if cached is not None and cached[0] == identity:
157
+ _fingerprints.move_to_end(path)
158
+ return cached[1]
159
+ with path.open("rb") as stream:
160
+ if _file_identity(os.fstat(stream.fileno())) != identity:
161
+ raise OSError("Credential configuration changed before read")
162
+ digest = hashlib.sha256()
163
+ for chunk in iter(lambda: stream.read(65536), b""):
164
+ digest.update(chunk)
165
+ fingerprint = digest.hexdigest()
166
+ if _file_identity(os.fstat(stream.fileno())) != identity:
167
+ raise OSError("Credential configuration changed during read")
168
+ if _file_identity(path.stat()) != identity:
169
+ raise OSError("Credential configuration replaced during read")
170
+ with _fingerprint_lock:
171
+ _fingerprints[path] = (identity, fingerprint)
172
+ _fingerprints.move_to_end(path)
173
+ while len(_fingerprints) > _FINGERPRINT_LIMIT:
174
+ _fingerprints.popitem(last=False)
175
+ return fingerprint
176
+
177
+
178
+ def _credential_scope(env: dict[str, str]) -> str:
179
+ """Hash identity inputs; credentials never become persisted cache metadata."""
180
+ tokens = tuple(env.get(name, "") for name in _TOKEN_ENVIRONMENT)
181
+ config = Path(env.get("GH_CONFIG_DIR") or
182
+ str(Path(env.get("XDG_CONFIG_HOME") or
183
+ str(Path(env.get("HOME") or str(Path.home())) / ".config")) / "gh"))
184
+ fingerprint = _github_config_fingerprint(config / "hosts.yml")
185
+ return SQLiteResponseCache.key("auth-v2", tokens, fingerprint)
186
+
187
+
188
+ def _cacheable_credential(argv: Sequence[str], env: dict[str, str]) -> bool:
189
+ public = bool(env.get("GH_TOKEN") or env.get("GITHUB_TOKEN"))
190
+ enterprise = bool(env.get("GH_ENTERPRISE_TOKEN") or env.get("GITHUB_ENTERPRISE_TOKEN"))
191
+ if public and enterprise:
192
+ return True
193
+ if not (public or enterprise) or len(argv) < 2:
194
+ return False
195
+ if argv[1] != "api":
196
+ return _explicit_host_repository_read(argv, env, public, enterprise)
197
+ # A host-qualified repository can affect host selection. Avoid guessing how
198
+ # it interacts with gh's repository context when only one token is known.
199
+ if str(env.get("GH_REPO", "")).count("/") >= 2:
200
+ return False
201
+ host = None
202
+ arguments = argv[2:]
203
+ index = 0
204
+ while index < len(arguments):
205
+ token = arguments[index]
206
+ option, separator, value = token.partition("=")
207
+ if not separator and len(token) > 2 and token[:2] in {"-X", "-f", "-F", "-H", "-q", "-t", "-p"}:
208
+ option, value, separator = token[:2], token[2:], "="
209
+ if option in _API_VALUES:
210
+ if not separator:
211
+ index += 1
212
+ if index >= len(arguments):
213
+ return False
214
+ value = arguments[index]
215
+ if option == "--hostname":
216
+ if host is not None:
217
+ return False
218
+ host = value
219
+ elif not token.startswith("-") and re.match(r"(?i)^https?://", token):
220
+ # A URL-shaped endpoint may select a host independently of flags.
221
+ return False
222
+ index += 1
223
+ # gh may choose its sole configured host as the default, so absence of an
224
+ # explicit hostname or GH_HOST is not proof that the target is github.com.
225
+ host = host or env.get("GH_HOST")
226
+ if not host:
227
+ return False
228
+ host = host.lower()
229
+ if not _valid_host(host):
230
+ return False
231
+ return public if _public_host(host) else enterprise
232
+
233
+
234
+ _HOST_PATTERN = re.compile(r"[a-z0-9][a-z0-9.-]*")
235
+ _REPOSITORY_PATTERN = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+")
236
+ _REPOSITORY_OPTIONS = {"--repo", "-R"}
237
+
238
+
239
+ def _valid_host(host: str) -> bool:
240
+ return bool(_HOST_PATTERN.fullmatch(host))
241
+
242
+
243
+ def _public_host(host: str) -> bool:
244
+ return (host in {"github.com", "github.localhost"}
245
+ or host.endswith((".github.com", ".github.localhost", ".ghe.com")))
246
+
247
+
248
+ def _explicit_host_repository_read(
249
+ argv: Sequence[str], env: dict[str, str], public: bool, enterprise: bool
250
+ ) -> bool:
251
+ """Admit non-API reads only when GH_HOST alone selects the host.
252
+
253
+ ``gh pr``/``gh issue`` resolve the host from the repository context, so the
254
+ repository must be explicit (``--repo``/``-R`` or ``GH_REPO``) and must not
255
+ carry a host or URL. ``gh search`` has no repository context and is only
256
+ admitted for github.com. Anything ambiguous keeps bypassing the cache.
257
+ """
258
+ host = str(env.get("GH_HOST", "")).lower()
259
+ if not host or not _valid_host(host):
260
+ return False
261
+ if any(re.match(r"(?i)^https?://", str(token)) for token in argv[2:]):
262
+ return False
263
+ env_repository = str(env.get("GH_REPO", ""))
264
+ if env_repository and not _REPOSITORY_PATTERN.fullmatch(env_repository):
265
+ return False
266
+ if argv[1] == "search":
267
+ if host != "github.com":
268
+ return False
269
+ elif argv[1] in {"pr", "issue"}:
270
+ repositories = []
271
+ arguments = list(argv[2:])
272
+ for index, token in enumerate(arguments):
273
+ if token in _REPOSITORY_OPTIONS:
274
+ if index + 1 >= len(arguments):
275
+ return False
276
+ repositories.append(arguments[index + 1])
277
+ elif token.startswith("--repo="):
278
+ repositories.append(token.partition("=")[2])
279
+ elif token.startswith("-R") and len(token) > 2:
280
+ repositories.append(token[2:])
281
+ if len(repositories) > 1:
282
+ return False
283
+ repository = repositories[0] if repositories else env_repository
284
+ if not repository or not _REPOSITORY_PATTERN.fullmatch(repository):
285
+ return False
286
+ else:
287
+ return False
288
+ return public if _public_host(host) else enterprise
289
+
290
+
291
+ def github_env(
292
+ host: str = "github.com",
293
+ env: dict[str, str] | None = None,
294
+ *,
295
+ runner=subprocess.run,
296
+ timeout: float = 10.0,
297
+ ) -> dict[str, str]:
298
+ """Return a child environment that makes the GitHub identity explicit.
299
+
300
+ GitHub CLI may keep its token in the system keyring, which procache cannot
301
+ fingerprint, so such reads are never shared. This helper pins ``GH_HOST``
302
+ and copies the token ``gh`` would use for that host into the returned
303
+ environment, read locally with ``gh auth token`` (no network request). The
304
+ token only lives in the returned mapping; the cache stores a hash of it.
305
+ If resolution fails the mapping carries no resolved token and
306
+ ``CachedReadCommand`` keeps bypassing the cache.
307
+ """
308
+ host = str(host).lower()
309
+ if not _valid_host(host):
310
+ raise ValueError("invalid GitHub host")
311
+ result = dict(os.environ if env is None else env)
312
+ result["GH_HOST"] = host
313
+ if _public_host(host):
314
+ variable, existing = "GH_TOKEN", ("GH_TOKEN", "GITHUB_TOKEN")
315
+ else:
316
+ variable, existing = "GH_ENTERPRISE_TOKEN", ("GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN")
317
+ if any(result.get(name) for name in existing):
318
+ return result
319
+ try:
320
+ completed = runner(
321
+ ["gh", "auth", "token", "--hostname", host],
322
+ capture_output=True, text=True, timeout=timeout, check=False, env=result,
323
+ )
324
+ except (OSError, subprocess.SubprocessError):
325
+ return result
326
+ token = (completed.stdout or "").strip() if completed.returncode == 0 else ""
327
+ if token and not any(character.isspace() for character in token):
328
+ result[variable] = token
329
+ return result
330
+
331
+
332
+ MAX_COOLDOWN_SECONDS = 3600.0
333
+ _REST_COMMANDS = frozenset({"run", "workflow", "release", "cache", "secret", "variable", "gist", "ruleset", "attestation"})
334
+
335
+
336
+ def _api_family(argv: Sequence[str]) -> str:
337
+ """GitHub rate-limit resource a gh read draws from: ``core``, ``graphql`` or ``search``."""
338
+ command = argv[1] if len(argv) > 1 else ""
339
+ if command == "search":
340
+ return "search"
341
+ if command == "api":
342
+ positional = [item for item in argv[2:] if not item.startswith("-")]
343
+ endpoint = next((item for item in positional if item not in {"GET", "HEAD"}), "")
344
+ if endpoint == "graphql":
345
+ return "graphql"
346
+ return "search" if endpoint.lstrip("/").startswith("search/") else "core"
347
+ return "core" if command in _REST_COMMANDS else "graphql"
348
+
349
+
350
+ def _api_is_read(arguments: Sequence[str]) -> bool:
351
+ """Recognize gh's effective method; ambiguous request bodies bypass caching."""
352
+ switches = {"--paginate", "--slurp", "-i", "--include", "--silent", "--verbose"}
353
+ endpoint = None
354
+ method = None
355
+ fields = []
356
+ index = 0
357
+ while index < len(arguments):
358
+ token = arguments[index]
359
+ option, separator, value = token.partition("=")
360
+ if not separator and len(token) > 2 and token[:2] in {"-X", "-f", "-F", "-H", "-q", "-t", "-p"}:
361
+ option, value, separator = token[:2], token[2:], "="
362
+ if option in _API_VALUES:
363
+ if not separator:
364
+ index += 1
365
+ if index >= len(arguments):
366
+ return False
367
+ value = arguments[index]
368
+ if option in {"-X", "--method"}:
369
+ if method is not None:
370
+ return False
371
+ method = value.upper()
372
+ elif option in {"-f", "--raw-field", "-F", "--field"}:
373
+ if "=" not in value or value.split("=", 1)[1].startswith("@"):
374
+ return False
375
+ fields.append(value)
376
+ elif token in switches:
377
+ pass
378
+ elif token.startswith("-") or endpoint is not None:
379
+ return False
380
+ else:
381
+ endpoint = token
382
+ index += 1
383
+ if not endpoint:
384
+ return False
385
+ effective_method = method or ("POST" if fields else "GET")
386
+ if endpoint != "graphql":
387
+ return effective_method == "GET"
388
+ queries = [value.split("=", 1)[1] for value in fields if value.startswith("query=")]
389
+ if effective_method not in {"GET", "POST"} or len(queries) != 1:
390
+ return False
391
+ # Strip strings before comments so a '#' in a string cannot hide a mutation.
392
+ document = re.sub(r'"(?:\\.|[^"\\])*"', '""', queries[0])
393
+ document = re.sub(r"#[^\r\n]*", "", document).lstrip("\ufeff \t\r\n,")
394
+ return bool(re.match(r"(?:query\b|\{)", document)) and not re.search(r"\b(?:mutation|subscription)\b", document)