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 +17 -0
- procache/cache.py +494 -0
- procache/commands.py +394 -0
- procache/http.py +323 -0
- procache/pygithub.py +126 -0
- procache/urtlog_bridge.py +129 -0
- subactor_procache-0.1.0.dist-info/METADATA +8 -0
- subactor_procache-0.1.0.dist-info/RECORD +10 -0
- subactor_procache-0.1.0.dist-info/WHEEL +5 -0
- subactor_procache-0.1.0.dist-info/top_level.txt +1 -0
procache/http.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""Opt-in HTTP read caching independent of a provider or HTTP SDK.
|
|
2
|
+
|
|
3
|
+
The caller supplies the actual transport and a credential/principal scope.
|
|
4
|
+
Only explicitly eligible GET/HEAD and validated GraphQL queries are stored. Authorization,
|
|
5
|
+
publication and health observations should use ``fresh=True``. Secrets in
|
|
6
|
+
request identity are hashed; response bodies still belong in a private cache.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import base64
|
|
12
|
+
import json
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import stat
|
|
17
|
+
import uuid
|
|
18
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
19
|
+
from dataclasses import dataclass, replace
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
from urllib.parse import urlsplit
|
|
23
|
+
|
|
24
|
+
from .cache import SQLiteResponseCache
|
|
25
|
+
from .commands import CachedReadCommand
|
|
26
|
+
from .urtlog_bridge import maybe_emit_http_read
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class HTTPResponse:
|
|
31
|
+
status: int
|
|
32
|
+
headers: Mapping[str, str]
|
|
33
|
+
body: bytes
|
|
34
|
+
cache_hit: bool = False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class CachedHTTPReads:
|
|
38
|
+
"""Coalesce successful metadata reads across processes using Procache.
|
|
39
|
+
|
|
40
|
+
``scope`` must identify the transport's current credentials and tenant,
|
|
41
|
+
including authentication hidden inside an SDK session. Unknown scopes
|
|
42
|
+
bypass caching. Headers and parameters distinguish representations.
|
|
43
|
+
Mutations invalidate that origin/scope even when transport failure leaves
|
|
44
|
+
the remote outcome unknown. Generation keys fence older in-flight reads.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
MAX_BODY_BYTES = 4 * 1024 * 1024
|
|
48
|
+
EPOCH_TTL = 86400
|
|
49
|
+
REVALIDATION_TTL = 3600
|
|
50
|
+
|
|
51
|
+
def __init__(self, cache: SQLiteResponseCache, *, ttl: float = 15.0) -> None:
|
|
52
|
+
if not math.isfinite(ttl) or not 0 < ttl <= 3600:
|
|
53
|
+
raise ValueError("HTTP cache TTL must be finite and between 0 and 3600 seconds")
|
|
54
|
+
self.cache = cache
|
|
55
|
+
# The validated lifetime is part of the shared identity. Equivalent
|
|
56
|
+
# int/float arguments must not partition records across API clients.
|
|
57
|
+
self.ttl = float(ttl)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def shared(cls, *, path: str | Path | None = None, ttl: float = 15.0) -> CachedHTTPReads:
|
|
61
|
+
"""Use the common cross-application HTTP namespace and private store."""
|
|
62
|
+
root = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
|
|
63
|
+
location = Path(path or os.environ.get("SUBACTOR_PROCACHE_PATH") or root / "subactor" / "provider-http.sqlite3").absolute()
|
|
64
|
+
if ".." in location.parts:
|
|
65
|
+
raise ValueError("HTTP cache path must not contain parent traversal")
|
|
66
|
+
cls._private_directory(location.parent, require_exists=False)
|
|
67
|
+
location.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
68
|
+
cls._private_directory(location.parent, require_exists=True)
|
|
69
|
+
if location.is_symlink():
|
|
70
|
+
raise ValueError("HTTP cache must be a regular private file")
|
|
71
|
+
descriptor = os.open(location, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
|
|
72
|
+
try:
|
|
73
|
+
info = os.fstat(descriptor)
|
|
74
|
+
if not stat.S_ISREG(info.st_mode) or (hasattr(os, "geteuid") and info.st_uid != os.geteuid()):
|
|
75
|
+
raise ValueError("HTTP cache must be an owned regular file")
|
|
76
|
+
if hasattr(os, "fchmod"):
|
|
77
|
+
os.fchmod(descriptor, 0o600)
|
|
78
|
+
else:
|
|
79
|
+
location.chmod(0o600)
|
|
80
|
+
finally:
|
|
81
|
+
os.close(descriptor)
|
|
82
|
+
return cls(SQLiteResponseCache(location, namespace="provider-http-v1"), ttl=ttl)
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def _private_directory(directory: Path, *, require_exists: bool) -> None:
|
|
86
|
+
# SQLite reopens the filename for each connection. Its parent must
|
|
87
|
+
# therefore remain private, rather than just validating the first fd.
|
|
88
|
+
# A sticky ancestor such as /tmp protects an owned child from other
|
|
89
|
+
# users; ordinary writable ancestors and symlinks do not.
|
|
90
|
+
uid = os.geteuid() if hasattr(os, "geteuid") else None
|
|
91
|
+
for parent in (*reversed(directory.parents), directory):
|
|
92
|
+
try:
|
|
93
|
+
info = parent.lstat()
|
|
94
|
+
except FileNotFoundError:
|
|
95
|
+
if require_exists:
|
|
96
|
+
raise ValueError("HTTP cache directory must exist") from None
|
|
97
|
+
continue
|
|
98
|
+
if not stat.S_ISDIR(info.st_mode):
|
|
99
|
+
raise ValueError("HTTP cache directory chain must not contain symlinks")
|
|
100
|
+
if uid is not None and info.st_uid not in {0, uid}:
|
|
101
|
+
raise ValueError("HTTP cache directory chain must be trusted")
|
|
102
|
+
if parent == directory:
|
|
103
|
+
if (uid is not None and info.st_uid != uid) or info.st_mode & 0o077:
|
|
104
|
+
raise ValueError("HTTP cache directory must be owned and private")
|
|
105
|
+
elif info.st_mode & 0o022 and not info.st_mode & stat.S_ISVTX:
|
|
106
|
+
raise ValueError("HTTP cache directory ancestor must not be writable by other users")
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def credential_scope(*credentials: object) -> str | None:
|
|
110
|
+
"""Hash a known identity; missing inputs retain the uncached path.
|
|
111
|
+
|
|
112
|
+
Public callers can explicitly use an ``"anonymous"`` identity.
|
|
113
|
+
"""
|
|
114
|
+
if not credentials or any(value is None or value == "" or value == b"" for value in credentials):
|
|
115
|
+
return None
|
|
116
|
+
return SQLiteResponseCache.key("http-principal-v1", credentials)
|
|
117
|
+
|
|
118
|
+
def _authority(self, url: str, scope: str) -> str:
|
|
119
|
+
parsed = urlsplit(url)
|
|
120
|
+
return self.cache.key("http-authority-v1", parsed.scheme.lower(), parsed.netloc.lower(), scope)
|
|
121
|
+
|
|
122
|
+
def invalidate(self, url: str, *, scope: str) -> None:
|
|
123
|
+
"""Invalidate every representation for one origin and principal."""
|
|
124
|
+
self.cache.put(self._authority(url, scope), uuid.uuid4().hex.encode(), ttl=self.EPOCH_TTL)
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def _headers(headers: Mapping[str, str]) -> dict[str, str]:
|
|
128
|
+
return {str(k).lower(): str(v) for k, v in headers.items()}
|
|
129
|
+
|
|
130
|
+
def _ttl(self, response: HTTPResponse) -> float:
|
|
131
|
+
if not 200 <= response.status < 300 or len(response.body) > self.MAX_BODY_BYTES:
|
|
132
|
+
return 0
|
|
133
|
+
headers = self._headers(response.headers)
|
|
134
|
+
policy = headers.get("cache-control", "").lower()
|
|
135
|
+
directives = {part.strip().split("=", 1)[0] for part in policy.split(",")}
|
|
136
|
+
if directives & {"no-store", "no-cache"} or ("set-cookie" in headers and "public" not in directives):
|
|
137
|
+
return 0
|
|
138
|
+
if "*" in {value.strip() for value in headers.get("vary", "").split(",")}:
|
|
139
|
+
return 0
|
|
140
|
+
ttl = self.ttl
|
|
141
|
+
match = re.search(r'(?:^|,)\s*max-age\s*=\s*"?(\d+)"?\s*(?:,|$)', policy)
|
|
142
|
+
if match:
|
|
143
|
+
try:
|
|
144
|
+
age = max(0, int(headers.get("age", "0")))
|
|
145
|
+
except ValueError:
|
|
146
|
+
return 0
|
|
147
|
+
ttl = min(ttl, max(0, int(match[1]) - age))
|
|
148
|
+
return ttl
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def _graphql_read(body: bytes | None) -> bool:
|
|
152
|
+
if body is None or len(body) > CachedHTTPReads.MAX_BODY_BYTES:
|
|
153
|
+
return False
|
|
154
|
+
def unique(pairs):
|
|
155
|
+
result = {}
|
|
156
|
+
for key, value in pairs:
|
|
157
|
+
if key in result:
|
|
158
|
+
raise ValueError("ambiguous GraphQL envelope")
|
|
159
|
+
result[key] = value
|
|
160
|
+
return result
|
|
161
|
+
try:
|
|
162
|
+
document = json.loads(body, object_pairs_hook=unique)
|
|
163
|
+
except (UnicodeError, ValueError):
|
|
164
|
+
return False
|
|
165
|
+
if not isinstance(document, dict) or not isinstance(document.get("query"), str):
|
|
166
|
+
return False
|
|
167
|
+
return CachedReadCommand.is_read(["gh", "api", "graphql", "-f", "query=" + document["query"]])
|
|
168
|
+
|
|
169
|
+
@staticmethod
|
|
170
|
+
def _encode(response: HTTPResponse) -> bytes:
|
|
171
|
+
return json.dumps([response.status, dict(response.headers),
|
|
172
|
+
base64.b64encode(response.body).decode("ascii")],
|
|
173
|
+
separators=(",", ":")).encode()
|
|
174
|
+
|
|
175
|
+
@staticmethod
|
|
176
|
+
def _decode(payload: bytes, hit: bool) -> HTTPResponse:
|
|
177
|
+
status, headers, body = json.loads(payload)
|
|
178
|
+
return HTTPResponse(status, headers, base64.b64decode(body), cache_hit=hit)
|
|
179
|
+
|
|
180
|
+
@staticmethod
|
|
181
|
+
def _etag(headers: Mapping[str, str]) -> str | None:
|
|
182
|
+
tag = CachedHTTPReads._headers(headers).get("etag", "")
|
|
183
|
+
return tag if re.fullmatch(r'(?:W/)?"[\x21\x23-\x7e\x80-\xff]*"', tag) else None
|
|
184
|
+
|
|
185
|
+
def request(
|
|
186
|
+
self,
|
|
187
|
+
method: str,
|
|
188
|
+
url: str,
|
|
189
|
+
loader: Callable[[], HTTPResponse],
|
|
190
|
+
*,
|
|
191
|
+
scope: str | None = None,
|
|
192
|
+
headers: Mapping[str, str] | None = None,
|
|
193
|
+
parameters: object = None,
|
|
194
|
+
body: bytes | None = None,
|
|
195
|
+
cacheable: bool = False,
|
|
196
|
+
fresh: bool = False,
|
|
197
|
+
stream: bool = False,
|
|
198
|
+
graphql: bool = False,
|
|
199
|
+
revalidate: Callable[[str], HTTPResponse] | None = None,
|
|
200
|
+
) -> HTTPResponse:
|
|
201
|
+
"""Optionally revalidate an expired full GET with a scoped ETag.
|
|
202
|
+
|
|
203
|
+
The callback sends an authenticated If-None-Match request using the
|
|
204
|
+
supplied tag. The former body is returned only when the provider
|
|
205
|
+
confirms it with 304. Such a response has cache_hit=False.
|
|
206
|
+
"""
|
|
207
|
+
method = method.upper()
|
|
208
|
+
graphql_read = graphql and method == "POST" and self._graphql_read(body)
|
|
209
|
+
if method not in {"GET", "HEAD"} and not graphql_read:
|
|
210
|
+
try:
|
|
211
|
+
return replace(loader(), cache_hit=False)
|
|
212
|
+
finally:
|
|
213
|
+
if scope:
|
|
214
|
+
self.invalidate(url, scope=scope)
|
|
215
|
+
request_headers = self._headers(headers or {})
|
|
216
|
+
policy = request_headers.get("cache-control", "").lower()
|
|
217
|
+
directives = {part.strip().split("=", 1)[0] for part in policy.split(",")}
|
|
218
|
+
request_fresh = bool(directives & {"no-store", "no-cache"}) or bool(
|
|
219
|
+
re.search(r'(?:^|,)\s*max-age\s*=\s*"?0"?\s*(?:,|$)', policy)
|
|
220
|
+
) or "no-cache" in {value.strip().lower() for value in request_headers.get("pragma", "").split(",")}
|
|
221
|
+
if not scope or not cacheable or fresh or request_fresh or stream or (body is not None and not graphql_read):
|
|
222
|
+
return replace(loader(), cache_hit=False)
|
|
223
|
+
|
|
224
|
+
authority = self._authority(url, scope)
|
|
225
|
+
epoch = self.cache.get(authority)
|
|
226
|
+
key = self.cache.key("http-read-v1", authority, epoch.value.hex() if epoch else "initial",
|
|
227
|
+
method, url, request_headers, parameters, body, self.ttl)
|
|
228
|
+
cached = self.cache.get(key)
|
|
229
|
+
if cached is not None:
|
|
230
|
+
response = self._decode(cached.value, True)
|
|
231
|
+
if os.environ.get("URTLOG_STATE_DIR"):
|
|
232
|
+
maybe_emit_http_read(method, url, response.status, cache_hit=True)
|
|
233
|
+
return response
|
|
234
|
+
|
|
235
|
+
explicit_conditions = {"range", "if-range", "if-match", "if-none-match",
|
|
236
|
+
"if-modified-since", "if-unmodified-since"}
|
|
237
|
+
revalidation_key = (
|
|
238
|
+
self.cache.key("http-etag-v1", key)
|
|
239
|
+
if revalidate is not None and method == "GET" and not explicit_conditions.intersection(request_headers)
|
|
240
|
+
else None
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
def load() -> bytes:
|
|
244
|
+
previous = self.cache.get(revalidation_key) if revalidation_key else None
|
|
245
|
+
if revalidate is not None and previous is not None and previous.etag is not None:
|
|
246
|
+
response = revalidate(previous.etag)
|
|
247
|
+
if response.status == 304:
|
|
248
|
+
returned_tag = self._headers(response.headers).get("etag")
|
|
249
|
+
if returned_tag is None or returned_tag.removeprefix("W/") == previous.etag.removeprefix("W/"):
|
|
250
|
+
old = self._decode(previous.value, False)
|
|
251
|
+
headers = self._headers(old.headers) | self._headers(response.headers)
|
|
252
|
+
response = replace(old, headers=headers)
|
|
253
|
+
else:
|
|
254
|
+
response = loader()
|
|
255
|
+
else:
|
|
256
|
+
response = loader()
|
|
257
|
+
value = self._encode(response)
|
|
258
|
+
ttl = self._ttl(response)
|
|
259
|
+
if graphql_read:
|
|
260
|
+
try:
|
|
261
|
+
payload = json.loads(response.body)
|
|
262
|
+
if not isinstance(payload, dict) or payload.get("errors") or "data" not in payload:
|
|
263
|
+
ttl = 0
|
|
264
|
+
except (UnicodeError, ValueError):
|
|
265
|
+
ttl = 0
|
|
266
|
+
if response.status == 429:
|
|
267
|
+
try:
|
|
268
|
+
retry_after = float(self._headers(response.headers).get("retry-after", "60"))
|
|
269
|
+
except ValueError:
|
|
270
|
+
retry_after = 60
|
|
271
|
+
if not math.isfinite(retry_after):
|
|
272
|
+
retry_after = 60
|
|
273
|
+
self.cache.cooldown(authority, ttl=min(3600, max(1, retry_after)))
|
|
274
|
+
if ttl > 0:
|
|
275
|
+
# This loader owns the backend's single flight. Store with the
|
|
276
|
+
# response's effective lifetime; get_or_set must not reinsert
|
|
277
|
+
# it with the caller's longer default TTL.
|
|
278
|
+
# Explicitly public metadata may accompany edge cookies.
|
|
279
|
+
# Preserve them on the live response, never persist or replay
|
|
280
|
+
# them when serving the cached representation.
|
|
281
|
+
stored = replace(response, headers={k: v for k, v in response.headers.items()
|
|
282
|
+
if k.lower() != "set-cookie"})
|
|
283
|
+
stored_value = self._encode(stored)
|
|
284
|
+
self.cache.put(key, stored_value, ttl=ttl)
|
|
285
|
+
if revalidation_key and response.status == 200 and (tag := self._etag(stored.headers)):
|
|
286
|
+
self.cache.put(revalidation_key, stored_value, ttl=self.REVALIDATION_TTL, etag=tag)
|
|
287
|
+
return value
|
|
288
|
+
if revalidation_key and previous is not None and previous.etag is not None:
|
|
289
|
+
# Replace a validator after a response that cannot be retained.
|
|
290
|
+
self.cache.put(revalidation_key, b"", ttl=self.ttl)
|
|
291
|
+
return value
|
|
292
|
+
|
|
293
|
+
value, hit = self.cache.get_or_set(
|
|
294
|
+
key, load, ttl=self.ttl, should_cache=lambda _: False, cooldown_key=authority,
|
|
295
|
+
)
|
|
296
|
+
response = self._decode(value, hit)
|
|
297
|
+
if os.environ.get("URTLOG_STATE_DIR"):
|
|
298
|
+
maybe_emit_http_read(method, url, response.status, cache_hit=hit)
|
|
299
|
+
return response
|
|
300
|
+
|
|
301
|
+
async def arequest(
|
|
302
|
+
self, method: str, url: str, loader: Callable[[], Awaitable[HTTPResponse]], *,
|
|
303
|
+
revalidate: Callable[[str], Awaitable[HTTPResponse]] | None = None, **kwargs: Any,
|
|
304
|
+
) -> HTTPResponse:
|
|
305
|
+
"""Run async SDK transport on its own loop without blocking that loop.
|
|
306
|
+
|
|
307
|
+
SQLite and cross-process waiting run in the executor. A cancelled
|
|
308
|
+
waiter leaves a shared fetch available to the other readers; the
|
|
309
|
+
transport retains responsibility for its network timeout.
|
|
310
|
+
"""
|
|
311
|
+
loop = asyncio.get_running_loop()
|
|
312
|
+
async def call_loader() -> HTTPResponse:
|
|
313
|
+
return await loader()
|
|
314
|
+
def load() -> HTTPResponse:
|
|
315
|
+
return asyncio.run_coroutine_threadsafe(call_loader(), loop).result()
|
|
316
|
+
async def call_revalidator(tag: str) -> HTTPResponse:
|
|
317
|
+
assert revalidate is not None
|
|
318
|
+
return await revalidate(tag)
|
|
319
|
+
def refresh(tag: str) -> HTTPResponse:
|
|
320
|
+
return asyncio.run_coroutine_threadsafe(call_revalidator(tag), loop).result()
|
|
321
|
+
return await asyncio.to_thread(
|
|
322
|
+
self.request, method, url, load, revalidate=refresh if revalidate is not None else None, **kwargs,
|
|
323
|
+
)
|
procache/pygithub.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .cache import SQLiteResponseCache, is_rate_limit_error
|
|
7
|
+
|
|
8
|
+
REVALIDATION_TTL = 86400.0
|
|
9
|
+
_CONDITIONAL_HEADERS = frozenset({
|
|
10
|
+
"if-none-match", "if-modified-since", "if-match", "if-unmodified-since", "if-range", "range",
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _etag(headers: Any) -> str | None:
|
|
15
|
+
if not isinstance(headers, dict):
|
|
16
|
+
return None
|
|
17
|
+
tag = next((str(value) for name, value in headers.items() if str(name).lower() == "etag"), "")
|
|
18
|
+
return tag or None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _same_tag(left: str, right: str) -> bool:
|
|
22
|
+
return left.removeprefix("W/") == right.removeprefix("W/")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CachedPyGithubRequester:
|
|
26
|
+
"""Read-through adapter for PyGithub's JSON requester.
|
|
27
|
+
|
|
28
|
+
Only GET responses with a known authentication context are cached.
|
|
29
|
+
Response headers and request representation are preserved. All writes go
|
|
30
|
+
directly through the delegated requester; rate-limit exceptions open the
|
|
31
|
+
shared provider cooldown in ``SQLiteResponseCache``.
|
|
32
|
+
|
|
33
|
+
After the short TTL an expired read is revalidated with the stored ETag.
|
|
34
|
+
PyGithub returns a 304 as headers with no payload; the former payload is
|
|
35
|
+
reused only then and when the provider confirms the same tag. GitHub does
|
|
36
|
+
not count such a 304 against the primary rate limit.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, delegate: Any, cache: SQLiteResponseCache, *, ttl: float = 15.0) -> None:
|
|
40
|
+
self._delegate = delegate
|
|
41
|
+
self._cache = cache
|
|
42
|
+
self._ttl = ttl
|
|
43
|
+
|
|
44
|
+
def __getattr__(self, name: str) -> Any:
|
|
45
|
+
return getattr(self._delegate, name)
|
|
46
|
+
|
|
47
|
+
def requestJsonAndCheck(
|
|
48
|
+
self,
|
|
49
|
+
verb: str,
|
|
50
|
+
url: str,
|
|
51
|
+
parameters: dict[str, Any] | None = None,
|
|
52
|
+
headers: dict[str, str] | None = None,
|
|
53
|
+
input: Any | None = None,
|
|
54
|
+
follow_302_redirect: bool = False,
|
|
55
|
+
) -> tuple[dict[str, Any], Any]:
|
|
56
|
+
identity = self._identity() if verb.upper() == "GET" else None
|
|
57
|
+
if identity is None:
|
|
58
|
+
return self._delegate.requestJsonAndCheck(
|
|
59
|
+
verb, url, parameters, headers, input, follow_302_redirect
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
key = self._cache.key(
|
|
63
|
+
"pygithub-v2", identity, verb.upper(), url, parameters, headers,
|
|
64
|
+
input, follow_302_redirect,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
explicit = {str(name).lower() for name in (headers or {})} & _CONDITIONAL_HEADERS
|
|
68
|
+
revalidation_key = None if explicit else self._cache.key("pygithub-etag-v1", key)
|
|
69
|
+
|
|
70
|
+
def encode(response_headers: Any, payload: Any) -> bytes:
|
|
71
|
+
return json.dumps(
|
|
72
|
+
[dict(response_headers), payload], separators=(",", ":"), default=str
|
|
73
|
+
).encode("utf-8")
|
|
74
|
+
|
|
75
|
+
def load() -> bytes:
|
|
76
|
+
previous = self._cache.get(revalidation_key) if revalidation_key else None
|
|
77
|
+
if previous is not None and previous.etag:
|
|
78
|
+
conditional = {**(headers or {}), "If-None-Match": previous.etag}
|
|
79
|
+
response_headers, payload = self._delegate.requestJsonAndCheck(
|
|
80
|
+
verb, url, parameters, conditional, input, follow_302_redirect
|
|
81
|
+
)
|
|
82
|
+
returned = _etag(response_headers)
|
|
83
|
+
if payload is None and (returned is None or _same_tag(returned, previous.etag)):
|
|
84
|
+
old_headers, old_payload = json.loads(previous.value)
|
|
85
|
+
value = encode({**old_headers, **dict(response_headers)}, old_payload)
|
|
86
|
+
self._cache.put(revalidation_key, value, ttl=REVALIDATION_TTL, etag=previous.etag)
|
|
87
|
+
return value
|
|
88
|
+
if payload is None:
|
|
89
|
+
response_headers, payload = self._delegate.requestJsonAndCheck(
|
|
90
|
+
verb, url, parameters, headers, input, follow_302_redirect
|
|
91
|
+
)
|
|
92
|
+
else:
|
|
93
|
+
response_headers, payload = self._delegate.requestJsonAndCheck(
|
|
94
|
+
verb, url, parameters, headers, input, follow_302_redirect
|
|
95
|
+
)
|
|
96
|
+
value = encode(response_headers, payload)
|
|
97
|
+
tag = _etag(response_headers)
|
|
98
|
+
if revalidation_key and tag and payload is not None:
|
|
99
|
+
self._cache.put(revalidation_key, value, ttl=REVALIDATION_TTL, etag=tag)
|
|
100
|
+
return value
|
|
101
|
+
|
|
102
|
+
value, _ = self._cache.get_or_set(
|
|
103
|
+
key,
|
|
104
|
+
load,
|
|
105
|
+
ttl=self._ttl,
|
|
106
|
+
cooldown_key=self._cache.key("pygithub-provider-v2", identity),
|
|
107
|
+
cooldown_seconds=60,
|
|
108
|
+
is_rate_limit=is_rate_limit_error,
|
|
109
|
+
)
|
|
110
|
+
response_headers, payload = json.loads(value)
|
|
111
|
+
return response_headers, payload
|
|
112
|
+
|
|
113
|
+
def _identity(self) -> str | None:
|
|
114
|
+
"""Hash PyGithub's public auth context; unknown delegates bypass sharing."""
|
|
115
|
+
try:
|
|
116
|
+
auth = self._delegate.auth
|
|
117
|
+
base_url = self._delegate.base_url
|
|
118
|
+
token = auth.token if auth is not None else None
|
|
119
|
+
token_type = auth.token_type if auth is not None else "anonymous"
|
|
120
|
+
except AttributeError:
|
|
121
|
+
return None
|
|
122
|
+
if not isinstance(base_url, str) or not base_url:
|
|
123
|
+
return None
|
|
124
|
+
if auth is not None and (not isinstance(token, str) or not token):
|
|
125
|
+
return None
|
|
126
|
+
return self._cache.key("pygithub-auth-v1", base_url, token_type, token)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Opt-in, zero-mandatory-dependency bridge projecting Procache HTTP reads into uritime-urtlog.
|
|
2
|
+
|
|
3
|
+
Activated strictly when ``URTLOG_STATE_DIR`` (or an explicit ``state_dir``) is
|
|
4
|
+
provided and ``urtlog`` is importable. Strips URL userinfo, query strings, and
|
|
5
|
+
fragments before recording so tokens or sensitive parameters never enter logs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
import hashlib
|
|
12
|
+
import importlib
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import urlsplit
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def resolve_state_dir(explicit: Path | str | None = None) -> Path | None:
|
|
20
|
+
"""Return configured urtlog state directory, or None when opt-in is inactive."""
|
|
21
|
+
raw = str(explicit).strip() if explicit is not None else os.environ.get("URTLOG_STATE_DIR", "").strip()
|
|
22
|
+
if not raw:
|
|
23
|
+
return None
|
|
24
|
+
return Path(raw).expanduser().resolve()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def sanitize_url(url: str) -> str:
|
|
28
|
+
"""Strip credentials, query parameters, and fragments from a URL."""
|
|
29
|
+
parsed = urlsplit(url.strip())
|
|
30
|
+
scheme = (parsed.scheme or "https").lower()
|
|
31
|
+
host = (parsed.hostname or "unknown").lower()
|
|
32
|
+
port = f":{parsed.port}" if parsed.port else ""
|
|
33
|
+
path = parsed.path or "/"
|
|
34
|
+
return f"{scheme}://{host}{port}{path}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _slug(value: str, fallback: str = "unknown") -> str:
|
|
38
|
+
cleaned = "".join(ch if ch.isalnum() or ch in "._-" else "-" for ch in value.strip().lower()).strip("-")
|
|
39
|
+
return cleaned or fallback
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def maybe_emit_http_read(
|
|
43
|
+
method: str,
|
|
44
|
+
url: str,
|
|
45
|
+
status_code: int,
|
|
46
|
+
*,
|
|
47
|
+
cache_hit: bool,
|
|
48
|
+
state_dir: Path | str | None = None,
|
|
49
|
+
repository: str = "dockuri/procache",
|
|
50
|
+
sensitivity: str = "internal",
|
|
51
|
+
) -> dict[str, Any]:
|
|
52
|
+
"""Emit a sanitized Procache HTTP read observation into uritime-urtlog fail-open."""
|
|
53
|
+
try:
|
|
54
|
+
target_dir = resolve_state_dir(state_dir)
|
|
55
|
+
if target_dir is None:
|
|
56
|
+
return {"emitted": False, "reason": "disabled"}
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
urtlog_mod = importlib.import_module("urtlog")
|
|
60
|
+
except (ImportError, OSError, AttributeError, RuntimeError):
|
|
61
|
+
return {"emitted": False, "reason": "urtlog_not_installed"}
|
|
62
|
+
|
|
63
|
+
safe_url = sanitize_url(url)
|
|
64
|
+
parsed = urlsplit(safe_url)
|
|
65
|
+
host_slug = _slug(parsed.hostname or "unknown", "unknown")
|
|
66
|
+
method_slug = _slug(method, "get")
|
|
67
|
+
outcome_slug = "hit" if cache_hit else "miss"
|
|
68
|
+
now_us = int(datetime.now(timezone.utc).timestamp() * 1_000_000)
|
|
69
|
+
url_hash = hashlib.sha256(safe_url.encode("utf-8")).hexdigest()[:14]
|
|
70
|
+
eid = "prc-" + hashlib.sha256(
|
|
71
|
+
f"{now_us}|{method_slug}|{safe_url}|{status_code}|{outcome_slug}".encode("utf-8")
|
|
72
|
+
).hexdigest()[:16]
|
|
73
|
+
status = "succeeded" if 200 <= int(status_code) < 400 else "failed"
|
|
74
|
+
|
|
75
|
+
with urtlog_mod.UrtClient(target_dir, source="procache", repository=repository) as client:
|
|
76
|
+
record = urtlog_mod.UrtEventRecord(
|
|
77
|
+
event_id=eid,
|
|
78
|
+
kind="log",
|
|
79
|
+
source="procache",
|
|
80
|
+
urt=urtlog_mod.UrtTime(at_us=now_us),
|
|
81
|
+
uri=urtlog_mod.OperationUri.parse(f"procache://http/{host_slug}/{method_slug}_{outcome_slug}"),
|
|
82
|
+
inputs=(
|
|
83
|
+
urtlog_mod.DataRef(
|
|
84
|
+
urn=f"urn:uritime:procache:url:{host_slug}:{url_hash}",
|
|
85
|
+
role="http_request",
|
|
86
|
+
sensitivity=sensitivity,
|
|
87
|
+
),
|
|
88
|
+
),
|
|
89
|
+
outputs=(
|
|
90
|
+
urtlog_mod.DataRef(
|
|
91
|
+
urn=f"urn:uritime:procache:response:{eid}",
|
|
92
|
+
role="http_response",
|
|
93
|
+
sensitivity=sensitivity,
|
|
94
|
+
),
|
|
95
|
+
),
|
|
96
|
+
status=status,
|
|
97
|
+
repository=repository,
|
|
98
|
+
actor="dockuri/procache",
|
|
99
|
+
sensitivity=sensitivity,
|
|
100
|
+
owner_principal="dockuri/procache",
|
|
101
|
+
run_id=eid,
|
|
102
|
+
stage="completed",
|
|
103
|
+
log_type="summary" if status == "succeeded" else "warning",
|
|
104
|
+
summary=f"{method.upper()} {safe_url} -> {status_code} ({outcome_slug})",
|
|
105
|
+
metadata={
|
|
106
|
+
"method": method.upper(),
|
|
107
|
+
"sanitized_url": safe_url,
|
|
108
|
+
"status_code": int(status_code),
|
|
109
|
+
"cache_hit": bool(cache_hit),
|
|
110
|
+
},
|
|
111
|
+
custody=urtlog_mod.Custody(
|
|
112
|
+
commissioned_by="dockuri/procache",
|
|
113
|
+
executed_by="dockuri/procache",
|
|
114
|
+
recipients=("group:ops", "heyasa"),
|
|
115
|
+
),
|
|
116
|
+
)
|
|
117
|
+
client.store.append(record)
|
|
118
|
+
client.registry.register_url(
|
|
119
|
+
safe_url,
|
|
120
|
+
owner=repository,
|
|
121
|
+
system="procache",
|
|
122
|
+
description=f"Observed cached HTTP endpoint ({method.upper()})",
|
|
123
|
+
effects=("network", "read"),
|
|
124
|
+
available=status == "succeeded",
|
|
125
|
+
revision="observed",
|
|
126
|
+
)
|
|
127
|
+
return {"emitted": True, "event_id": eid, "sanitized_url": safe_url, "cache_hit": bool(cache_hit)}
|
|
128
|
+
except (OSError, ValueError, TypeError, AttributeError, RuntimeError, KeyError):
|
|
129
|
+
return {"emitted": False, "reason": "emit_failed"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: subactor-procache
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Process-safe TTL caching and request coalescing for provider read APIs.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Provides-Extra: urtlog
|
|
8
|
+
Requires-Dist: uritime-urtlog>=0.3.0; extra == "urtlog"
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
procache/__init__.py,sha256=7cMbpLGk22d-Wf4_kMzAJRyAoLebsgqE95ZDqayUaJE,524
|
|
2
|
+
procache/cache.py,sha256=JsuxNRJsaWH6GCK_0K6cOeh21L4Q392yz0zC0sSCe5A,18655
|
|
3
|
+
procache/commands.py,sha256=g52p3-AgPTEL0eZvznA_NZ3R-Wgv6cbHYz9dTKq-_Bo,16993
|
|
4
|
+
procache/http.py,sha256=DNZVwWUCCfF8svCddvRXC83-E0Kldb4FUPkJrzedttM,15478
|
|
5
|
+
procache/pygithub.py,sha256=XeFuu5Vugc6AeX02A_yxBXreCKE7QTB5JI8EYxoKKLA,5291
|
|
6
|
+
procache/urtlog_bridge.py,sha256=iAcEUO0_3LtNU0M34H78sQtq3Ke1GAWmfrKQTncU-MU,5311
|
|
7
|
+
subactor_procache-0.1.0.dist-info/METADATA,sha256=cHlgmxOa5vngRxL_OqnVmNd55n78uAcC6zNxIhdPPYI,265
|
|
8
|
+
subactor_procache-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
subactor_procache-0.1.0.dist-info/top_level.txt,sha256=cv3wWIdUPs2v8nkm9lDEeMME93kFdVl_92oM9Uy3PVU,9
|
|
10
|
+
subactor_procache-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
procache
|