main
ply4 git calls231 ms50 KiB2 cachedprotocol v2
840 lines35 KiBRaw
1// Content-addressed Workers Caching graph (never caches.default).
2//
3// Layers (all keyed by ctx.props.scope + path under /v${CACHE_VERSION}/):
4// RefCache — ref → commit oid (ONLY mutable; short TTL + purge-on-write)
5// CommitCache — commit oid → parsed commit (immutable)
6// TreeCache — tree oid → listing (immutable)
7// ResolvePathCache— (commit oid, path) → {blob,mode} via Commit+Tree (immutable)
8// ObjectCache — blob oid → verified inflated bytes (immutable)
9//
10// Auth stays on the default entrypoint. Named entrypoints are not internet-routable.
11// Docs: developers.cloudflare.com/workers/cache/ examples + cache-keys (ctx.props isolation).
12import {
13 BLOB_CACHE_HEADER,
14 BLOB_CACHE_MAX_AGE_SECONDS,
15 BLOB_CACHE_MAX_BYTES,
16 BLOB_OID_HEADER,
17 TYPE,
18 commitView,
19 createTransport,
20 fetchObject,
21 lsRefs,
22 openBlob,
23 parseTree,
24 readBlob,
25 refCandidates,
26 validatePath,
27} from 'ply';
28import { captureGroup, chainGet, dig, header } from './absent.ts';
29import { CACHE_VERSION } from './cache-version.ts';
30import { API_LIMITS } from './limits.ts';
31import { unwrapOr } from './option.ts';
32import { withPublicReadCredential, type TokenSource } from './public.ts';
33import { quirksFor } from './quirks.ts';
34import {
35 applyUpstreamHeaders,
36 createRayLog,
37 observeUpstream,
38 RAY_HEADER,
39 type RayLog,
40} from './rays.ts';
41import { checkRemote, createGuardedFetch, redirectOptions } from './remote.ts';
43export { BLOB_CACHE_HEADER, BLOB_CACHE_MAX_AGE_SECONDS, BLOB_CACHE_MAX_BYTES, BLOB_OID_HEADER };
45/** Dated 2026-11-08: object/tree/commit/resolve TTL (REPORT-blob-cache / REPORT-workers-cache). */
46export const CAS_IMMUTABLE = `public, max-age=${BLOB_CACHE_MAX_AGE_SECONDS}, immutable`;
47/**
48 * Ref layer: max-age=0 must-revalidate (2026-11-08).
49 * SWR previously served pre-write tips after a missed purge (CD commit-fresh).
50 * Concurrent misses still collapse; every response revalidates through RefCache.
51 * purgeEverything on write remains the primary invalidation.
52 */
53export const REF_SWR_S = 0;
54export const REF_CACHE_CONTROL = 'public, max-age=0, must-revalidate';
55export const NO_STORE = 'no-store';
57/** Upstream Authorization value; must NOT be named Authorization (triggers BYPASS). */
58export const CAS_AUTH_HEADER = 'x-ply-cas-authorization';
59export const CAS_ORIGIN = 'https://cas.internal';
61export type CasProps = { readonly scope: string };
63/** ctx.exports.<Entrypoint> is callable with { props } then .fetch (LoopbackServiceStub). */
64export type CasBinding = {
65 (opts: { readonly props: CasProps }): { fetch(input: RequestInfo | URL): Promise<Response> };
66};
68export type CasLayer = 'ref' | 'commit' | 'tree' | 'resolve' | 'object';
70const OID_RE = /^[0-9a-f]{40}$/;
72export function layerHeader(layer: CasLayer): string {
73 return `x-ply-cache-${layer}`;
76export function casPath(layer: CasLayer, rest: string, version: number = CACHE_VERSION): string {
77 return `/v${version}/${layer}/${rest}`;
80function plain(status: number, text: string): Response {
81 return new Response(text, {
82 status,
83 headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': NO_STORE },
84 });
87/** Map ply fetch errors: not_found and upload-pack not_our_ref → 404; else 502. */
88function upstreamStatus(error: unknown): number {
89 const code = chainGet(error, 'code');
90 if (code.tag === 'some' && code.value === 'not_found') return 404;
91 if (code.tag === 'some' && code.value === 'remote_error') {
92 const reason = chainGet(error, 'reason');
93 if (reason.tag === 'some' && reason.value === 'not_our_ref') return 404;
94 }
95 if (code.tag === 'some' && code.value === 'http') {
96 const status = chainGet(error, 'status');
97 if (status.tag === 'some' && status.value === 404) return 404;
98 }
99 return 502;
102function ifNoneMatchHits(inm: string | null, etag: string): boolean {
103 if (inm === null || etag === '') return false;
104 if (inm.trim() === '*') return false;
105 const want = etag.startsWith('"') ? etag : `"${etag}"`;
106 for (const part of inm.split(',')) {
107 const raw = part.trim();
108 if (raw === '') continue;
109 const tag = raw.startsWith('W/') ? raw.slice(2).trim() : raw;
110 if (tag === want) return true;
111 }
112 return false;
116function jsonOk(body: unknown, cacheControl: string, etag: string | null, layer: CasLayer, extra: HeadersInit = {}): Response {
117 const headers = new Headers({
118 'content-type': 'application/json; charset=utf-8',
119 'cache-control': cacheControl,
120 ...Object.fromEntries(new Headers(extra)),
121 });
122 if (etag !== null) headers.set('etag', `"${etag}"`);
123 headers.set('cache-tag', `ply-cas-v${CACHE_VERSION},ply-cas-${layer}${etag ? `,ply-cas-${layer}-${etag}` : ''}`);
124 return new Response(JSON.stringify(body), { status: 200, headers });
127export function parseScope(props: CasProps): { readonly scope: string } | Response {
128 const scope = typeof props.scope === 'string' ? props.scope : '';
129 if (scope === '') return plain(400, 'missing scope');
130 let url: URL;
131 try {
132 url = new URL(scope);
133 } catch {
134 return plain(400, 'bad scope');
135 }
136 if (url.username || url.password) return plain(400, 'scope must be credential-free');
137 return { scope };
140function authorizationFrom(req: Request): { readonly header: string } | null {
141 const raw = req.headers.get(CAS_AUTH_HEADER);
142 if (raw === null || raw === '') return null;
143 if (!/^[\t\x20-\x7e]+$/.test(raw)) return null;
144 return { header: raw };
147export function gitAuthorizationValue(auth: unknown): string | null {
148 if (auth === null || typeof auth !== 'object') return null;
149 const headerField = chainGet(auth, 'header');
150 if (headerField.tag === 'some' && typeof headerField.value === 'string' && headerField.value !== '') return headerField.value;
151 const bearer = chainGet(auth, 'bearer');
152 if (bearer.tag === 'some' && typeof bearer.value === 'string' && bearer.value !== '') return `Bearer ${bearer.value}`;
153 const token = chainGet(auth, 'token');
154 const user = chainGet(auth, 'user');
155 if (token.tag === 'some' && typeof token.value === 'string' && token.value !== '') {
156 if (user.tag === 'some' && typeof user.value === 'string' && user.value !== '') {
157 return `Basic ${btoa(`${user.value}:${token.value}`)}`;
158 }
159 return `Bearer ${token.value}`;
160 }
161 return null;
164type PlyTransport = ReturnType<typeof createTransport> extends { ok: true; value: infer T } | { ok: false } ? T : never;
165export type TransportResult =
166 | { readonly ok: true; readonly value: PlyTransport; readonly rays: RayLog; readonly started: number }
167 | { readonly ok: false; readonly response: Response };
169export function allowOriginsFromEnv(env: object): readonly string[] {
170 const field = chainGet(env, 'ALLOW_REMOTE_ORIGINS');
171 const raw = field.tag === 'some' && typeof field.value === 'string' ? field.value : '';
172 return raw.split(',').map(s => s.trim()).filter(Boolean);
175/**
176 * Merge `x-artifacts-ray` values from CAS layer responses (fill rays).
177 * On a Workers Cache HIT the entrypoint does not run; the stored fill rays ride on the cached response.
178 */
179export function mergeRayHeaderValues(...values: Array<string | null>): string {
180 const parts: string[] = [];
181 for (const value of values) {
182 if (value === null || value === '') continue;
183 for (const part of value.split(', ')) {
184 if (part !== '') parts.push(part);
185 }
186 }
187 return parts.join(', ');
190function stampFillRays(res: Response, rays: RayLog, started: number): Response {
191 applyUpstreamHeaders(res.headers, rays.report(), Date.now() - started);
192 return res;
195export function transportFor(req: Request, scope: string, tokens: TokenSource | null, allow: readonly string[] = []): TransportResult {
196 const auth = authorizationFrom(req);
197 let remote;
198 try {
199 remote = checkRemote(scope, allow);
200 } catch (e) {
201 const msg = e instanceof Error ? e.message : String(e);
202 return { ok: false, response: plain(400, msg) };
203 }
204 const rays = createRayLog();
205 const direct = withPublicReadCredential(globalThis.fetch.bind(globalThis), tokens);
206 const fetchImpl = observeUpstream(createGuardedFetch(direct, remote, allow), rays);
207 const transport = createTransport(remote.href, {
208 ...(auth === null ? {} : { auth }),
209 fetchImpl,
210 limits: API_LIMITS,
211 quirks: quirksFor(remote.origin),
212 ...redirectOptions(remote, allow),
213 });
214 if (!transport.ok) return { ok: false, response: plain(400, transport.error.message) };
215 return { ok: true, value: transport.value, rays, started: Date.now() };
218/** Stamp Cf-Cache-Status onto x-ply-cache-<layer> for the front door / spans. */
219export async function viaCas(
220 binding: CasBinding,
221 layer: CasLayer,
222 pathRest: string,
223 scope: string,
224 gitAuthorization: string | null,
225 init: RequestInit = {},
226): Promise<Response> {
227 const headers = new Headers(init.headers);
228 headers.delete('authorization');
229 headers.delete('Authorization');
230 if (gitAuthorization !== null && gitAuthorization !== '') headers.set(CAS_AUTH_HEADER, gitAuthorization);
231 // LoopbackServiceStub: binding({ props }).fetch(req) — props land on the callee's ctx.props (cache key).
232 const res = await binding({ props: { scope } }).fetch(
233 new Request(`${CAS_ORIGIN}${casPath(layer, pathRest)}`, { ...init, headers, redirect: 'manual' }),
234 );
235 const out = new Headers(res.headers);
236 out.set(layerHeader(layer), unwrapOr(header(res.headers, 'cf-cache-status'), unwrapOr(header(res.headers, layerHeader(layer)), 'NONE')));
237 out.delete('cf-cache-status');
238 return new Response(res.body, { status: res.status, statusText: res.statusText, headers: out });
241export function splitFilePath(path: string): { readonly parent: string; readonly name: string } | null {
242 if (typeof path !== 'string' || path === '' || path === '/' || path.includes('\0')) return null;
243 const trimmed = path.replace(/^\/+/, '').replace(/\/+$/, '');
244 if (trimmed === '') return null;
245 const slash = trimmed.lastIndexOf('/');
246 if (slash === -1) return { parent: '', name: trimmed };
247 return { parent: trimmed.slice(0, slash), name: trimmed.slice(slash + 1) };
250export function isBlobEntry(entry: { readonly type: string }): boolean {
251 return entry.type === 'blob';
254// ── path parsers ────────────────────────────────────────────────────────────
256export function parseObjectPath(pathname: string): string | null {
257 const m = /^\/v(\d+)\/object\/([0-9a-f]{40})$/.exec(pathname);
258 const version = captureGroup(m, 1);
259 const oid = captureGroup(m, 2);
260 if (version.tag === 'none' || oid.tag === 'none' || Number(version.value) !== CACHE_VERSION) return null;
261 return oid.value;
264export function parseTreePath(pathname: string): string | null {
265 const m = /^\/v(\d+)\/tree\/([0-9a-f]{40})$/.exec(pathname);
266 const version = captureGroup(m, 1);
267 const oid = captureGroup(m, 2);
268 if (version.tag === 'none' || oid.tag === 'none' || Number(version.value) !== CACHE_VERSION) return null;
269 return oid.value;
272export function parseCommitPath(pathname: string): string | null {
273 const m = /^\/v(\d+)\/commit\/([0-9a-f]{40})$/.exec(pathname);
274 const version = captureGroup(m, 1);
275 const oid = captureGroup(m, 2);
276 if (version.tag === 'none' || oid.tag === 'none' || Number(version.value) !== CACHE_VERSION) return null;
277 return oid.value;
280export function parseResolvePath(pathname: string): { readonly commit: string; readonly path: string } | null {
281 const m = /^\/v(\d+)\/resolve\/([0-9a-f]{40})(\/(.*))?$/.exec(pathname);
282 const version = captureGroup(m, 1);
283 const commit = captureGroup(m, 2);
284 if (version.tag === 'none' || commit.tag === 'none' || Number(version.value) !== CACHE_VERSION) return null;
285 const rest = captureGroup(m, 4);
286 let path = '';
287 if (rest.tag === 'some') {
288 try {
289 path = decodeURIComponent(rest.value);
290 } catch {
291 return null;
292 }
293 }
294 return { commit: commit.value, path };
297export function parseRefPath(pathname: string): string | null {
298 const m = /^\/v(\d+)\/ref\/(.+)$/.exec(pathname);
299 const version = captureGroup(m, 1);
300 const ref = captureGroup(m, 2);
301 if (version.tag === 'none' || ref.tag === 'none' || Number(version.value) !== CACHE_VERSION) return null;
302 try {
303 return decodeURIComponent(ref.value);
304 } catch {
305 return null;
306 }
309export function encodeRefPath(ref: string): string {
310 return encodeURIComponent(ref);
313export function encodeResolveRest(commit: string, path: string): string {
314 const trimmed = path.replace(/^\/+/, '').replace(/\/+$/, '');
315 if (trimmed === '') return commit;
316 return `${commit}/${trimmed.split('/').map(encodeURIComponent).join('/')}`;
319// ── serve layers ────────────────────────────────────────────────────────────
321export async function serveObject(req: Request, props: CasProps, tokens: TokenSource | null, allow: readonly string[] = []): Promise<Response> {
322 if (req.method !== 'GET' && req.method !== 'HEAD') return plain(405, 'method not allowed');
323 const oid = parseObjectPath(new URL(req.url).pathname);
324 if (oid === null) return plain(404, 'not an object key');
325 const scoped = parseScope(props);
326 if (scoped instanceof Response) return scoped;
327 const t = transportFor(req, scoped.scope, tokens, allow);
328 if (!t.ok) return t.response;
330 const buffered = await readBlob(t.value, oid, { maxBytes: BLOB_CACHE_MAX_BYTES });
331 if (!buffered.ok) {
332 return stampFillRays(plain(upstreamStatus(buffered.error), buffered.error.message), t.rays, t.started);
333 }
334 if (buffered.value.kind === 'too_big') {
335 const opened = await openBlob(t.value, oid);
336 if (!opened.ok) return stampFillRays(plain(502, opened.error.message), t.rays, t.started);
337 if (opened.value.kind !== 'stream') return stampFillRays(plain(502, 'unexpected blob kind'), t.rays, t.started);
338 const headers = new Headers({
339 'content-type': 'application/octet-stream',
340 'cache-control': NO_STORE,
341 'content-length': String(opened.value.size),
342 'x-ply-size': String(opened.value.size),
343 [BLOB_OID_HEADER]: oid,
344 etag: `"${oid}"`,
345 [BLOB_CACHE_HEADER]: 'BYPASS',
346 [layerHeader('object')]: 'BYPASS',
347 });
348 return stampFillRays(new Response(opened.value.stream, { status: 200, headers }), t.rays, t.started);
349 }
350 const data = buffered.value.data;
351 const headers = new Headers({
352 'content-type': 'application/octet-stream',
353 'cache-control': CAS_IMMUTABLE,
354 'content-length': String(data.byteLength),
355 'x-ply-size': String(data.byteLength),
356 [BLOB_OID_HEADER]: oid,
357 etag: `"${oid}"`,
358 'cache-tag': `ply-cas-v${CACHE_VERSION},ply-cas-object,ply-cas-object-${oid}`,
359 });
360 if (ifNoneMatchHits(req.headers.get('if-none-match'), `"${oid}"`)) {
361 headers.delete('content-length');
362 return stampFillRays(new Response(null, { status: 304, headers }), t.rays, t.started);
363 }
364 return stampFillRays(new Response(data, { status: 200, headers }), t.rays, t.started);
367export async function serveTree(req: Request, props: CasProps, tokens: TokenSource | null, allow: readonly string[] = []): Promise<Response> {
368 if (req.method !== 'GET' && req.method !== 'HEAD') return plain(405, 'method not allowed');
369 const oid = parseTreePath(new URL(req.url).pathname);
370 if (oid === null) return plain(404, 'not a tree key');
371 const scoped = parseScope(props);
372 if (scoped instanceof Response) return scoped;
373 const t = transportFor(req, scoped.scope, tokens, allow);
374 if (!t.ok) return t.response;
376 const fetched = await fetchObject(t.value, { oid, expectType: TYPE.TREE });
377 if (!fetched.ok) {
378 return stampFillRays(plain(upstreamStatus(fetched.error), fetched.error.message), t.rays, t.started);
379 }
380 if (fetched.value.type !== TYPE.TREE) return stampFillRays(plain(502, 'not a tree'), t.rays, t.started);
381 const parsed = parseTree(fetched.value.data);
382 if (!parsed.ok) return stampFillRays(plain(502, parsed.error.message), t.rays, t.started);
383 const entries = parsed.value.map(e => ({
384 name: e.name,
385 mode: e.mode.padStart(6, '0'),
386 oid: e.oid,
387 type: e.mode === '40000' ? 'tree' : e.mode === '160000' ? 'commit' : 'blob',
388 }));
389 return stampFillRays(jsonOk({ tree: oid, entries }, CAS_IMMUTABLE, oid, 'tree'), t.rays, t.started);
392export async function serveCommit(req: Request, props: CasProps, tokens: TokenSource | null, allow: readonly string[] = []): Promise<Response> {
393 if (req.method !== 'GET' && req.method !== 'HEAD') return plain(405, 'method not allowed');
394 const oid = parseCommitPath(new URL(req.url).pathname);
395 if (oid === null) return plain(404, 'not a commit key');
396 const scoped = parseScope(props);
397 if (scoped instanceof Response) return scoped;
398 const t = transportFor(req, scoped.scope, tokens, allow);
399 if (!t.ok) return t.response;
401 const fetched = await fetchObject(t.value, { oid, expectType: TYPE.COMMIT });
402 if (!fetched.ok) {
403 return stampFillRays(plain(upstreamStatus(fetched.error), fetched.error.message), t.rays, t.started);
404 }
405 if (fetched.value.type !== TYPE.COMMIT) return stampFillRays(plain(404, `${oid} is not a commit`), t.rays, t.started);
406 const viewed = commitView(fetched.value.data);
407 if (!viewed.ok) return stampFillRays(plain(502, viewed.error.message), t.rays, t.started);
408 const view = viewed.value;
409 return stampFillRays(
410 jsonOk(
411 {
412 oid,
413 tree: view.tree,
414 parents: view.parents,
415 author: view.author,
416 committer: view.committer,
417 message: view.message,
418 signed: view.signed,
419 },
420 CAS_IMMUTABLE,
421 oid,
422 'commit',
423 ),
424 t.rays,
425 t.started,
426 );
429export type TreeLoopback = (treeOid: string, scope: string, auth: string | null) => Promise<Response>;
430export type CommitLoopback = (commitOid: string, scope: string, auth: string | null) => Promise<Response>;
432/**
433 * Resolve (commit, path) → blob|tree entry by walking TreeCache per segment so shared prefixes hit.
434 */
435function withMergedRays(res: Response, rayParts: string[]): Response {
436 const merged = mergeRayHeaderValues(...rayParts);
437 if (merged !== '') res.headers.set(RAY_HEADER, merged);
438 return res;
441export async function serveResolve(
442 req: Request,
443 props: CasProps,
444 _tokens: TokenSource | null,
445 loop: { readonly tree: TreeLoopback; readonly commit: CommitLoopback },
446 _allow: readonly string[] = [],
447): Promise<Response> {
448 if (req.method !== 'GET' && req.method !== 'HEAD') return plain(405, 'method not allowed');
449 const parsed = parseResolvePath(new URL(req.url).pathname);
450 if (parsed === null) return plain(404, 'not a resolve key');
451 const scoped = parseScope(props);
452 if (scoped instanceof Response) return scoped;
453 const auth = req.headers.get(CAS_AUTH_HEADER);
454 const rayParts: string[] = [];
456 const commitRes = await loop.commit(parsed.commit, scoped.scope, auth);
457 rayParts.push(unwrapOr(header(commitRes.headers, RAY_HEADER), ''));
458 if (commitRes.status !== 200) {
459 const text = await commitRes.text().catch(() => '');
460 return withMergedRays(plain(commitRes.status, text || 'commit resolve failed'), rayParts);
461 }
462 const commitRaw = await commitRes.json();
463 const treeField = chainGet(commitRaw, 'tree');
464 if (treeField.tag === 'none' || typeof treeField.value !== 'string' || !OID_RE.test(treeField.value)) {
465 return withMergedRays(plain(502, 'commit missing tree'), rayParts);
466 }
467 const commitTree = treeField.value;
469 const segments = parsed.path === '' ? [] : parsed.path.split('/').filter(s => s.length > 0);
470 let treeOid = commitTree;
471 let mode = '040000';
472 let oid = treeOid;
473 let type: 'tree' | 'blob' | 'commit' = 'tree';
475 for (let i = 0; i < segments.length; i++) {
476 const treeRes = await loop.tree(treeOid, scoped.scope, auth);
477 rayParts.push(unwrapOr(header(treeRes.headers, RAY_HEADER), ''));
478 if (treeRes.status !== 200) {
479 const text = await treeRes.text().catch(() => '');
480 return withMergedRays(plain(treeRes.status, text || 'tree resolve failed'), rayParts);
481 }
482 const listingRaw = await treeRes.json();
483 const entriesField = chainGet(listingRaw, 'entries');
484 const entries = entriesField.tag === 'some' && Array.isArray(entriesField.value) ? entriesField.value : [];
485 const entry = entries.find((e: { name: string }) => e.name === segments[i]) as { name: string; mode: string; oid: string; type: string } | null;
486 if (entry === null || entry === void 0) {
487 return withMergedRays(plain(404, `${segments.slice(0, i + 1).join('/')} not found`), rayParts);
488 }
489 oid = entry.oid;
490 mode = entry.mode;
491 type = entry.type === 'tree' ? 'tree' : entry.type === 'commit' ? 'commit' : 'blob';
492 if (i < segments.length - 1) {
493 if (type !== 'tree') {
494 return withMergedRays(plain(404, `${segments.slice(0, i + 1).join('/')} is not a tree`), rayParts);
495 }
496 treeOid = oid;
497 }
498 }
500 return withMergedRays(
501 jsonOk(
502 { commit: parsed.commit, path: parsed.path, oid, mode, type, tree: commitTree },
503 CAS_IMMUTABLE,
504 `${parsed.commit}:${parsed.path}`,
505 'resolve',
506 ),
507 rayParts,
508 );
511export async function serveRef(req: Request, props: CasProps, tokens: TokenSource | null, allow: readonly string[] = []): Promise<Response> {
512 if (req.method !== 'GET' && req.method !== 'HEAD') return plain(405, 'method not allowed');
513 const ref = parseRefPath(new URL(req.url).pathname);
514 if (ref === null) return plain(404, 'not a ref key');
515 const scoped = parseScope(props);
516 if (scoped instanceof Response) return scoped;
517 const t = transportFor(req, scoped.scope, tokens, allow);
518 if (!t.ok) return t.response;
520 // Full oid: immutable tip; still cache briefly under the ref key (caller may also skip RefCache).
521 if (OID_RE.test(ref)) {
522 return stampFillRays(
523 jsonOk({ ref, commit: ref, unborn: false }, REF_CACHE_CONTROL, ref, 'ref', {
524 'cache-tag': `ply-cas-v${CACHE_VERSION},ply-cas-ref,ply-cas-ref-${ref.slice(0, 12)}`,
525 }),
526 t.rays,
527 t.started,
528 );
529 }
530 const cands = refCandidates(ref === '' ? null : ref);
531 if (!cands.ok) return stampFillRays(plain(400, cands.error.message), t.rays, t.started);
532 const prefixes = cands.value.length > 0 ? [...cands.value, 'HEAD'] : ['HEAD'];
533 const listed = await lsRefs(t.value, prefixes, { unborn: true });
534 if (!listed.ok) return stampFillRays(plain(upstreamStatus(listed.error), listed.error.message), t.rays, t.started);
535 const refs = listed.value.refs;
536 const unborn = listed.value.unborn;
538 // Unborn HEAD / default branch: empty-repo body.
539 if (unborn !== null) {
540 const target = unborn.target;
541 const askingUnborn =
542 cands.value.includes('HEAD') ||
543 cands.value.includes(target) ||
544 ref === 'HEAD' ||
545 ref === '' ||
546 ref === target ||
547 (target.startsWith('refs/heads/') && (ref === target.slice('refs/heads/'.length) || ref === 'main'));
548 if (askingUnborn) {
549 // Never cache unborn: the next write births the ref; a HIT would 404 tree/read until TTL.
550 return stampFillRays(jsonOk({ ref: target, commit: null, unborn: true }, NO_STORE, null, 'ref'), t.rays, t.started);
551 }
552 }
554 // First candidate that ls-refs returned wins (tags before branches, matching git / refCandidates order).
555 let hitName: string | null = null;
556 let hitOid: string | null = null;
557 for (const name of cands.value) {
558 const entry = refs.get(name);
559 if (entry === void 0) continue;
560 hitName = name;
561 hitOid = entry.peeled !== null ? entry.peeled : entry.oid;
562 break;
563 }
564 if (hitName === null && cands.value.includes('HEAD')) {
565 const headName = listed.value.head;
566 if (headName !== null && refs.has(headName)) {
567 const entry = refs.get(headName);
568 if (entry !== void 0) {
569 hitName = headName;
570 hitOid = entry.peeled !== null ? entry.peeled : entry.oid;
571 }
572 }
573 const headEntry = refs.get('HEAD');
574 if (hitName === null && headEntry !== void 0) {
575 hitName = headName !== null ? headName : 'HEAD';
576 hitOid = headEntry.peeled !== null ? headEntry.peeled : headEntry.oid;
577 }
578 }
579 if (hitName === null || hitOid === null) return stampFillRays(plain(404, `ref ${ref} not found`), t.rays, t.started);
580 if (!OID_RE.test(hitOid)) return stampFillRays(plain(502, 'bad commit oid from ls-refs'), t.rays, t.started);
581 // Present the symref target when the caller asked for HEAD (matches readCommit).
582 const presented = hitName === 'HEAD' && listed.value.head !== null ? listed.value.head : hitName;
583 return stampFillRays(
584 jsonOk({ ref: presented, commit: hitOid, unborn: false }, REF_CACHE_CONTROL, hitOid, 'ref', {
585 'cache-tag': `ply-cas-v${CACHE_VERSION},ply-cas-ref,ply-cas-ref-${hitOid.slice(0, 12)}`,
586 }),
587 t.rays,
588 t.started,
589 );
592/**
593 * Purge every RefCache entry after a write. RefCache stores only mutable tips; purgeEverything
594 * is scoped to this entrypoint (docs), so it clears all scopes' ref tips without touching
595 * Object/Tree/Commit. Tags + pathPrefixes alone still left stale HIT+SWR tips in CD (74c7519).
596 */
597export const REF_PATH_PREFIX = `/v${CACHE_VERSION}/ref/`;
598export async function purgeRefTags(ctx: object, _tags: string[]): Promise<{ ok: boolean; ms: number; error: string }> {
599 const t0 = Date.now();
600 const cacheField = dig(ctx, ['cache']);
601 if (cacheField.tag === 'none' || cacheField.value === null) return { ok: false, ms: 0, error: 'no ctx.cache' };
602 // Must call as a method: extracting purge and invoking unbound throws
603 // "Illegal invocation" on Workers Cache (CD 2026-11-08 root-create 503).
604 const cache = cacheField.value as { purge(opts: { purgeEverything: true }): Promise<unknown> };
605 const purgeField = chainGet(cache, 'purge');
606 if (purgeField.tag === 'none' || typeof purgeField.value !== 'function') return { ok: false, ms: 0, error: 'no purge' };
607 try {
608 // Method call keeps `this` = cache (unbound extract → Illegal invocation on Workers Cache).
609 const result = await cache.purge({ purgeEverything: true });
610 const success = chainGet(result, 'success');
611 if (success.tag === 'some' && success.value === false) {
612 const errors = chainGet(result, 'errors');
613 return { ok: false, ms: Date.now() - t0, error: JSON.stringify(errors.tag === 'some' ? errors.value : null).slice(0, 200) };
614 }
615 return { ok: true, ms: Date.now() - t0, error: '' };
616 } catch (e) {
617 return { ok: false, ms: Date.now() - t0, error: e instanceof Error ? e.message : String(e) };
618 }
621export type CasExports = {
622 readonly RefCache: CasBinding | null;
623 readonly CommitCache: CasBinding | null;
624 readonly TreeCache: CasBinding | null;
625 readonly ResolvePathCache: CasBinding | null;
626 readonly ObjectCache: CasBinding | null;
627};
629/** Minimal ply Tracer surface used for per-layer cache-status spans. */
630export type CasSpan = { set(attrs: Record<string, string | number | boolean>): unknown; ok(): unknown };
631export type CasTracer = {
632 span<T>(name: string, opts: { attrs: Record<string, string | number | boolean> }, fn: (s: CasSpan) => T | PromiseLike<T>): Promise<T>;
633};
635export type ComposeWant = 'blob' | 'tree' | 'commit';
637export type ComposeInput = {
638 readonly remote: string;
639 readonly ref: string | null;
640 readonly path: string | null;
641 readonly authHeader: string | null;
642 readonly exports: CasExports;
643 readonly want: ComposeWant;
644 /** When true, skip Workers Cache and return null so the caller uses direct ply. */
645 readonly bypass: boolean;
646 readonly tracer: CasTracer | null;
647};
649async function viaCasSpan(
650 tracer: CasTracer | null,
651 binding: CasBinding,
652 layer: CasLayer,
653 pathRest: string,
654 scope: string,
655 auth: string | null,
656): Promise<Response> {
657 const run = () => viaCas(binding, layer, pathRest, scope, auth);
658 if (tracer === null) return run();
659 return tracer.span(`ply.cas.${layer}`, { attrs: { 'ply.cas.layer': layer } }, async span => {
660 const res = await run();
661 const status = unwrapOr(header(res.headers, layerHeader(layer)), 'NONE');
662 span.set({ 'ply.cas.cache': status, 'http.status_code': res.status });
663 if (res.status >= 400) span.set({ 'ply.cas.error': true });
664 else span.ok();
665 return res;
666 });
669/**
670 * Auth already ran. Compose Ref → (Commit | Resolve → Object/Tree).
671 * Returns layer cache statuses for telemetry.
672 */
673export async function composeCasGraph(input: ComposeInput): Promise<
674 | {
675 readonly ok: true;
676 readonly kind: 'blob';
677 readonly stream: ReadableStream<Uint8Array>;
678 readonly size: number;
679 readonly meta: { ref: string; commit: string; blob: string; mode: string; etag: string };
680 readonly cache: Record<string, string>;
681 }
682 | {
683 readonly ok: true;
684 readonly kind: 'tree';
685 readonly body: { ref: string; commit: string; tree: string; entries: unknown };
686 readonly cache: Record<string, string>;
687 }
688 | {
689 readonly ok: true;
690 readonly kind: 'commit';
691 readonly body: Record<string, unknown>;
692 readonly cache: Record<string, string>;
693 }
694 | { readonly ok: false; readonly status: number; readonly code: string; readonly message: string; readonly cache: Record<string, string> }
695> {
696 const cache: Record<string, string> = {};
697 const rayParts: string[] = [];
698 const takeRays = (res: Response) => {
699 rayParts.push(unwrapOr(header(res.headers, RAY_HEADER), ''));
700 };
701 const withRays = <T extends { readonly cache: Record<string, string> }>(out: T): T => {
702 const merged = mergeRayHeaderValues(...rayParts);
703 if (merged !== '') out.cache[RAY_HEADER] = merged;
704 return out;
705 };
706 const fail = (status: number, code: string, message: string) =>
707 withRays({ ok: false as const, status, code, message, cache });
708 if (input.bypass || input.exports.RefCache === null) {
709 return fail(501, 'bad_request', 'cas bypass');
710 }
711 const refName = input.ref === null || input.ref === '' ? 'HEAD' : input.ref;
712 let commitOid: string;
713 let presentedRef: string;
714 if (OID_RE.test(refName)) {
715 // Content-addressed tip: skip mutable RefCache.
716 cache[layerHeader('ref')] = 'BYPASS';
717 commitOid = refName;
718 presentedRef = refName;
719 } else {
720 const refRes = await viaCasSpan(input.tracer, input.exports.RefCache, 'ref', encodeRefPath(refName), input.remote, input.authHeader);
721 cache[layerHeader('ref')] = unwrapOr(header(refRes.headers, layerHeader('ref')), 'NONE');
722 takeRays(refRes);
723 if (refRes.status !== 200) {
724 const text = await refRes.text().catch(() => '');
725 if (refRes.status === 404) return fail(404, 'not_found', text || 'ref resolve failed');
726 if (refRes.status === 400) return fail(400, 'bad_request', text || 'bad ref');
727 return fail(502, 'upstream_5xx', text || 'ref resolve failed');
728 }
729 const refRaw = await refRes.json();
730 const unbornField = chainGet(refRaw, 'unborn');
731 const commitField = chainGet(refRaw, 'commit');
732 const refField = chainGet(refRaw, 'ref');
733 const unborn = unbornField.tag === 'some' && unbornField.value === true;
734 const commitOidVal = commitField.tag === 'some' && typeof commitField.value === 'string' ? commitField.value : null;
735 const refVal = refField.tag === 'some' && typeof refField.value === 'string' ? refField.value : refName;
736 if (unborn || commitOidVal === null) {
737 if (input.want === 'commit') {
738 return withRays({
739 ok: true as const,
740 kind: 'commit' as const,
741 body: { empty: true, ref: refVal === '' ? 'refs/heads/main' : refVal, oid: null, tree: null, parents: [], author: null, committer: null, message: null, signed: false },
742 cache,
743 });
744 }
745 return fail(404, 'not_found', 'empty repository');
746 }
747 commitOid = commitOidVal;
748 presentedRef = refVal;
749 }
751 if (input.want === 'commit') {
752 if (input.exports.CommitCache === null) return fail(501, 'bad_request', 'no CommitCache');
753 const cRes = await viaCasSpan(input.tracer, input.exports.CommitCache, 'commit', commitOid, input.remote, input.authHeader);
754 cache[layerHeader('commit')] = unwrapOr(header(cRes.headers, layerHeader('commit')), 'NONE');
755 takeRays(cRes);
756 if (cRes.status !== 200) {
757 const text = await cRes.text().catch(() => '');
758 const code = cRes.status === 404 ? 'not_found' : cRes.status === 400 ? 'bad_request' : 'upstream_5xx';
759 return fail(cRes.status === 404 || cRes.status === 400 ? cRes.status : 502, code, text || 'commit cache failed');
760 }
761 const body = (await cRes.json()) as Record<string, unknown>;
762 return withRays({ ok: true as const, kind: 'commit' as const, body: { ...body, ref: presentedRef }, cache });
763 }
765 if (input.exports.ResolvePathCache === null) return fail(501, 'bad_request', 'no ResolvePathCache');
766 const path = input.path === null ? '' : input.path;
767 if (path !== '') {
768 const checked = validatePath(path);
769 if (!checked.ok) return fail(400, 'bad_request', checked.error.message);
770 }
771 const resolveRes = await viaCasSpan(
772 input.tracer,
773 input.exports.ResolvePathCache,
774 'resolve',
775 encodeResolveRest(commitOid, path),
776 input.remote,
777 input.authHeader,
778 );
779 cache[layerHeader('resolve')] = unwrapOr(header(resolveRes.headers, layerHeader('resolve')), 'NONE');
780 takeRays(resolveRes);
781 // Nested commit/tree statuses are not automatically visible; resolve span covers the walk.
782 if (resolveRes.status !== 200) {
783 const text = await resolveRes.text().catch(() => '');
784 const code = resolveRes.status === 404 ? 'not_found' : 'upstream_5xx';
785 return fail(resolveRes.status, code, text || 'path resolve failed');
786 }
787 const resolved = (await resolveRes.json()) as { oid: string; mode: string; type: string; tree: string; path: string };
789 if (input.want === 'tree') {
790 if (resolved.type !== 'tree' && path !== '') {
791 return fail(400, 'bad_request', `${path} is not a directory`);
792 }
793 const treeOid = path === '' ? resolved.tree : resolved.oid;
794 if (input.exports.TreeCache === null) return fail(501, 'bad_request', 'no TreeCache');
795 const tRes = await viaCasSpan(input.tracer, input.exports.TreeCache, 'tree', treeOid, input.remote, input.authHeader);
796 cache[layerHeader('tree')] = unwrapOr(header(tRes.headers, layerHeader('tree')), 'NONE');
797 takeRays(tRes);
798 if (tRes.status !== 200) {
799 const text = await tRes.text().catch(() => '');
800 return fail(tRes.status, 'upstream_5xx', text || 'tree cache failed');
801 }
802 const listing = (await tRes.json()) as { tree: string; entries: unknown };
803 return withRays({
804 ok: true as const,
805 kind: 'tree' as const,
806 body: { ref: presentedRef, commit: commitOid, tree: listing.tree, entries: listing.entries },
807 cache,
808 });
809 }
811 // blob
812 if (resolved.type === 'tree') {
813 return fail(400, 'bad_request', `${path} is a directory`);
814 }
815 if (resolved.type === 'commit') {
816 return fail(404, 'not_found', `${path} is a submodule (commit ${resolved.oid})`);
817 }
818 if (input.exports.ObjectCache === null) return fail(501, 'bad_request', 'no ObjectCache');
819 const oRes = await viaCasSpan(input.tracer, input.exports.ObjectCache, 'object', resolved.oid, input.remote, input.authHeader);
820 const objectStatus = unwrapOr(header(oRes.headers, layerHeader('object')), 'NONE');
821 cache[layerHeader('object')] = objectStatus;
822 cache[BLOB_CACHE_HEADER] = objectStatus;
823 takeRays(oRes);
824 if (oRes.status !== 200 || oRes.body === null) {
825 const text = await oRes.text().catch(() => '');
826 return fail(oRes.status === 404 ? 404 : 502, oRes.status === 404 ? 'not_found' : 'upstream_5xx', text || 'object cache failed');
827 }
828 const size = Number(unwrapOr(header(oRes.headers, 'x-ply-size'), '0'));
829 if (!Number.isInteger(size) || size < 0) {
830 return fail(502, 'pack_corrupt', 'object cache missing x-ply-size');
831 }
832 return withRays({
833 ok: true as const,
834 kind: 'blob' as const,
835 stream: oRes.body,
836 size,
837 meta: { ref: presentedRef, commit: commitOid, blob: resolved.oid, mode: resolved.mode, etag: `"${resolved.oid}"` },
838 cache,
839 });
Diagnostics4 git calls · 231 ms
CallStatusSizeTime0231 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=145
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=145
git.pkt.payload.max=76
git.ls_refs.count=2
git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020040 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=41349
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=526b305930b8ef382f2d7a1f9c0238730a585921
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=6
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=41349
git.pkt.payload.max=41254
git.sideband.band1.bytes=41253
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=61
git.pack.bytes=41253
git.pack.ofs_delta=0
git.pack.ref_delta=0
git.pack.chain.max=0
git.pack.trailer=ab60efef4b7243678c75de64a4386986ee885c1c
git.pack.full=61
Open pack map
fetch2009.3 KiB226 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=226
git.response.bytes=9476
git.response.cache=MISS
git.response.duration_ms=226
git.fetch.wants=3477be7f02f9652a9c6e99556425b2112c7bccde
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=9476
git.pkt.payload.max=9455
git.sideband.band1.bytes=9454
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply-web.git
Ref
refs/heads/main
Commit
526b305930b8ef382f2d7a1f9c0238730a585921
cf-ray
a5e2d66beee4689d
Request
de48046e…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format