GitHubivarvong

ply

main
ply6 git calls95 ms34 KiB3 cachedprotocol v2
713 lines47 KiBRaw
1// Read one file or one directory listing from a remote, without a clone: ls-refs → the commit (tree:0, deepen 1) → one
2// tree per path level → the blob, STREAMED (inflate, then the caller). The latest chunk is held until the object
3// hash and the pack trailer verify; a failure errors the stream without releasing it. Built from the same
4// primitives as edit.js; carries no push, merge or pack-building code (asserted by test/bundle.test.js).
5//
6// readFile(url, { ref, path }, opts) → { ref, commit, blob, mode, size, stream } stream: ReadableStream<Uint8Array>
7// listTree(url, { ref, path }, opts) → { ref, commit, tree, entries: [{ name, mode, oid, type }] }
8// readCommit(url, { ref }, opts) → { ref, oid, tree, parents, author, committer, message, signed } (no trees fetched
9// unless the server refuses tree:0; then the blob:none fallback applies)
10// an unborn HEAD, or that branch by name, is { empty: true, ref } — a state, not not_found
11// walkPath(transport, treeOid, comps, { cache }) → Result<{ tree, entry }, PlyError> one tree per component, from a tree
12// the caller already has. not_found carries miss (ref, path, directory, submodule, …).
13// walkCommit(transport, commitOid, comps, { cache, levels }) → Result<{ commit, data, tree, entry }, PlyError> the
14// commit and the path's trees, the first levels in the commit's own fetch where taken.
15//
16// `ref`: null/'HEAD' (the remote's HEAD), a full ref name, a short name resolved the way `git rev-parse` does it for a
17// remote's refs (refs/<n>, refs/tags/<n>, refs/heads/<n> — tags win over branches, as in git), or a 40-hex commit oid.
18// `{ abbrev: 'advertised' }` also accepts a 4–39 character lowercase hex prefix, unique among the tips that one ls-refs
19// lists (HEAD, branches, tags, and peeled targets). A ref name wins over a prefix, as in git. The default `'off'`
20// leaves a short hex string as a ref name. That answer is weaker than `git rev-parse`: an interior object is not a
21// candidate. Annotated tags are peeled. `size` is known before the first content byte (the pack object header carries it), so a
22// caller can send Content-Length. The stream errors (never ends cleanly) if the content does not hash to the blob's oid
23// or the server sends a different number of bytes than it declared, and the chunk that would have completed the body
24// stays held: a consumer that received every byte, or saw `done`, saw the right bytes.
25// openBlob(transport, oid, { maxBytes, follows }) → Result<{ kind:'stream', size, stream } | { kind:'too_big', size }, PlyError>
26// readBlob(transport, oid, { maxBytes, follows }) → Result<{ kind:'bytes', data } | { kind:'too_big', size }, PlyError>
27// `too_big` is decided from the pack object header. The fetch is cancelled and no body byte is delivered.
28//
29// Errors are values: every function here returns a Result (docs/STACK.md "Public API policy"). The blob stream errors
30// as a stream does: its pull, transform and flush raise the PlyError the consumer reads.
31/* oxlint-disable import/max-dependencies -- an entry composes the protocol from one import per module, so its bundle carries nothing else */
32import { fail, isPlyCode, isPlyError, plyError } from './errors.js';
33import type { ErrorOf, Miss, PlyError } from './errors.js';
34import { assertNever, err, getOrElse, isSome, map, mapOption, none, ok, some } from './result.js';
35import type { Err, Option, Result } from './result.js';
36import { operation } from './operation.js';
37import { lsRefs, parseUnbornLine, type LsRefsResult } from './lsrefs.js';
38import { discover } from './discover.js';
39import { packStream, objectAt, objectId, spInit, spStep, spFinish, treeEntries } from './fetch.js';
40import { parseCommit, parseIdent, parseTree, objectHeader, TYPE, TYPE_NAME } from './objects.js';
41import { streamingSha1 } from './sha1.js';
42import { bufferSource, concat } from './bytes.js';
43import { KIND, spanOn } from './otel.js';
44import type { Span } from './otel.js';
45import { DEFAULT_LIMITS, limitsOf } from './limits.js';
46import type { CheckedLimits, LimitsInput } from './limits.js';
47import { validateRef, validatePath } from './validate.js';
48import type { SpState, SpStepped } from './fetch.js';
49import type { Transport } from './transport.js';
50import { raised } from './transport.js';
51import type { TreeEntry } from './objects.js';
52import { isPlyThrown, thrownCodeOr, thrownText } from './boundary.js';
53import { commitById } from './commit.js';
54import { commitForWalk } from './pathtrees.js';
55import { parseOid, type Oid } from './oid.js';
56import type { EntryOptions, TypeNames } from './boundary.js';
57import { at, fromNullable, fromNullish, mapGet, readKey, withDefaults } from './absent.js';
58import type { Input } from './absent.js';
60/* oxlint-disable no-await-in-loop -- a stream is consumed in order: each write waits for the inflate side (back-pressure) */
61/* oxlint-disable require-await -- the entry points are async: a refused argument is an Err in a promise, like every other answer */
62/* oxlint-disable unicorn/explicit-length-check, require-unicode-regexp, typescript/prefer-includes -- bundle budget: the JS's truthy length checks and non-unicode regexes, byte for byte (no behaviour change); RegExp#test, not includes: a thrown value's message may be no string at run time */
64const OID = /^[0-9a-f]{40}$/;
65// null or the platform's missing value: what a caller's `ref` or `path` left out.
66const isNothing = (v: unknown): boolean => fromNullish(v).tag === 'none';
68// Pure: what to ask ls-refs for, and which answer wins. git's ref_rev_parse_rules minus the remote-tracking forms.
69// `ref` is the caller's, checked here: anything but null, the missing value or a string is bad_request.
70export function refCandidates(ref: unknown): Result<string[], PlyError> {
71 if (isNothing(ref) || ref === '' || ref === 'HEAD') return ok(['HEAD']);
72 if (typeof ref !== 'string') return fail('bad_request', 'ref must be a string');
73 if (OID.test(ref)) return ok([]);
74 const names = ref.startsWith('refs/') ? [ref] : [`refs/${ref}`, `refs/tags/${ref}`, `refs/heads/${ref}`];
75 const out: string[] = [];
76 for (const name of names) {
77 const valid = validateRef(name);
78 if (!valid.ok) return valid;
79 out.push(valid.value);
80 }
81 return ok(out);
84// git ls-tree's object types.
85export type EntryType = 'tree' | 'commit' | 'blob';
86// Pure: git ls-tree's type for a tree entry mode.
87export const entryType = (mode: string): EntryType => {
88 if (mode === '40000') return 'tree';
89 return mode === '160000' ? 'commit' : 'blob';
90};
91// Pure: git ls-tree prints modes as %06o (trees as 040000); the tree object stores them without the leading zero.
92export const lsMode = (mode: string): string => mode.padStart(6, '0');
94// The caller's name and the unborn target name the same branch: HEAD, the full ref, or the short branch name.
95const sameBranch = (requested: unknown, full: string): boolean => {
96 const name = isNothing(requested) || requested === '' ? 'HEAD' : requested;
97 return typeof name === 'string' && (name === full || name === 'HEAD' || (!name.startsWith('refs/') && full === `refs/heads/${name}`));
98};
100// Effect: the unborn HEAD's target, or None when the server does not advertise ls-refs=unborn or lists no unborn line
101// (a deleted branch, a born HEAD). discover runs only on a ref miss; the happy path never asks.
102async function unbornTarget(t: Transport): Promise<Result<Option<string>, PlyError>> {
103 const info = await discover(t);
104 if (!info.ok) return info;
105 if (!info.value.lsRefsUnborn) return ok(none);
106 const listed = await lsRefs(t, ['HEAD'], { unborn: parseUnbornLine });
107 if (!listed.ok) return listed;
108 const target = mapOption(fromNullish(listed.value.unborn), u => u.target);
109 return ok(getOrElse(target, '') === '' ? none : target);
112// A ref as the caller names it: null or 'HEAD' for the remote's HEAD (as is '' or leaving it out), a name, or a 40-hex oid.
113export type RefSpec = string | null;
114export type Resolved = { readonly name: string; readonly commit: Oid };
115// How far a short hex string is an object id. `'off'` (the default): it is a ref name. `'advertised'`: after the name
116// misses, it is a prefix of an advertised tip.
117export type AbbrevMode = 'advertised' | 'off';
118const ABBREV = /^[0-9a-f]{4,39}$/;
119// Pure, over one ls-refs answer. `unique_among_advertised` is one oid (the ref names are every listing that carried it,
120// as the oid or as a peeled target). `none`: no advertised oid starts with the prefix. `ambiguous`: more than one oid does.
121// A bad prefix (not 4..39 lowercase hex) is `bad_request`, not a kind.
122export type AbbrevResolution =
123 | { readonly kind: 'unique_among_advertised'; readonly oid: Oid; readonly refs: readonly string[] }
124 | { readonly kind: 'none' }
125 | { readonly kind: 'ambiguous'; readonly oids: readonly Oid[] };
126export function resolveAbbrev(prefix: string, listed: LsRefsResult): Result<AbbrevResolution, PlyError> {
127 if (!ABBREV.test(prefix)) return fail('bad_request', 'abbreviated oid must be 4..39 lowercase hex', { what: 'ref' });
128 const byOid = new Map<Oid, string[]>();
129 for (const rec of listed.refs.values()) {
130 const peeled = fromNullish(rec.peeled);
131 const hits: ReadonlyArray<readonly [Oid, string]> = peeled.tag === 'none' ? [[rec.oid, rec.name]] : [[rec.oid, rec.name], [peeled.value, rec.name]];
132 for (const [oid, name] of hits) {
133 if (!oid.startsWith(prefix)) continue;
134 const names = mapGet(byOid, oid);
135 if (names.tag === 'none') byOid.set(oid, [name]);
136 else if (!names.value.includes(name)) names.value.push(name);
137 }
138 }
139 const oids = [...byOid.keys()].toSorted();
140 const oid = at(oids, 0);
141 if (oid.tag === 'none') return ok({ kind: 'none' });
142 if (oids.length > 1) return ok({ kind: 'ambiguous', oids });
143 return ok({ kind: 'unique_among_advertised', oid: oid.value, refs: getOrElse(mapGet(byOid, oid.value), []) });
145// The name missed. A unique advertised oid is that commit; more than one is bad_request; none leaves the caller to
146// report not_found. The prefix already matched ABBREV, so resolveAbbrev's own bad_request does not run.
147function advertisedCommit(prefix: string, listed: LsRefsResult): Result<Option<Resolved>, PlyError> {
148 const resolved = resolveAbbrev(prefix, listed);
149 if (!resolved.ok) return resolved;
150 const found = resolved.value;
151 switch (found.kind) {
152 case 'unique_among_advertised': return ok(some({ name: found.oid, commit: found.oid }));
153 case 'ambiguous': return fail('bad_request', `abbreviated oid ${prefix} matches ${found.oids.length} advertised objects`, { what: 'ref', got: found.oids });
154 case 'none': return ok(none);
155 }
156 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
157 return assertNever(found);
159// One ls-refs. `hit` is the ref name, a bare oid, or a unique advertised prefix. `miss` is the name not listed and the
160// prefix not unique. The abbrev refusal lives here so resolveCommit's only fail() is not_found.
161type Lookup = { readonly kind: 'hit'; readonly resolved: Resolved } | { readonly kind: 'miss'; readonly candidates: readonly string[] };
162async function lookupRef(t: Transport, ref: unknown, abbrev: AbbrevMode): Promise<Result<Lookup, PlyError>> {
163 if (abbrev !== 'off' && abbrev !== 'advertised') return fail('bad_request', 'abbrev must be "advertised" or "off"', { what: 'abbrev' });
164 // a 40-hex oid is taken as given, parsed once here (refCandidates answers no name for one)
165 const id = parseOid(ref);
166 if (id.ok) return ok({ kind: 'hit', resolved: { name: id.value, commit: id.value } });
167 const named = refCandidates(ref);
168 if (!named.ok) return named;
169 const cands = named.value;
170 // null: this call is a name. A string: the prefix, and the listing is wide enough to answer it.
171 const prefix = abbrev === 'advertised' && typeof ref === 'string' && ABBREV.test(ref) ? ref : null;
172 const listing = await lsRefs(t, prefix === null ? cands : [...cands, 'HEAD', 'refs/heads/', 'refs/tags/']);
173 if (!listing.ok) return listing;
174 const listed = listing.value;
175 for (const name of cands) {
176 const r = mapGet(listed.refs, name);
177 if (r.tag === 'some') return ok({ kind: 'hit', resolved: { name: name === 'HEAD' ? getOrElse(fromNullish(listed.head), 'HEAD') : name, commit: getOrElse(fromNullish(r.value.peeled), r.value.oid) } });
178 }
179 if (prefix !== null) {
180 const found = advertisedCommit(prefix, listed);
181 if (!found.ok) return found;
182 if (found.value.tag === 'some') return ok({ kind: 'hit', resolved: found.value.value });
183 }
184 return ok({ kind: 'miss', candidates: cands });
187export type ResolveConfig = { readonly abbrev: AbbrevMode };
188export type ResolveOptions = Input<ResolveConfig>;
189// Effect: ref → { name, commit } (annotated tags peeled; a bare oid is taken as given and checked by the commit fetch).
190// `abbrev: 'advertised'` asks once for the name's candidates plus HEAD, branches and tags, tries the name first, then
191// the prefix. `'off'` is the candidates alone. A miss is not_found, and an unborn HEAD the caller named is head_unborn.
192export async function resolveCommit(t: Transport, ref: unknown, options: ResolveOptions = {}): Promise<Result<Resolved, PlyError>> {
193 const { abbrev } = withDefaults<ResolveConfig>(options, { abbrev: 'off' });
194 const looked = await lookupRef(t, ref, abbrev);
195 if (!looked.ok) return looked;
196 if (looked.value.kind === 'hit') return ok(looked.value.resolved);
197 const { candidates } = looked.value;
198 const head = getOrElse(at(candidates, 0), '') === 'HEAD';
199 // The unborn question is a second ls-refs, and only after a miss: the advertisement is read then, and `unborn` is
200 // sent only when the server lists ls-refs=unborn. A path miss never reaches here.
201 const unborn = await unbornTarget(t);
202 if (!unborn.ok) return unborn;
203 // refCandidates refused a non-string, and a HEAD miss does not read this. The false arm stays so the type is a string.
204 const asked = typeof ref === 'string' ? ref : '';
205 const target = unborn.value;
206 let miss: Miss;
207 if (target.tag === 'some' && sameBranch(ref, target.value)) miss = { kind: 'head_unborn', target: target.value };
208 else if (head) miss = { kind: 'head_absent' };
209 else miss = { kind: 'ref', ref: asked, candidates };
210 return fail('not_found', head ? 'remote HEAD is unborn or absent (some hosts point HEAD at a deleted branch); pass ref explicitly' : `ref ${asked} not found`, { miss });
213export { fetchCommit, type FetchedCommit, type CommitMiss } from './commit.js';
215// An ident for JSON. `time` is ISO-8601 UTC, `epoch` the raw seconds, `tz` the offset as written (+0530).
216export type IdentView = { readonly name: string; readonly email: string; readonly time: string | null; readonly epoch: number | null; readonly tz: string };
217// Pure: an ident line's view (null for a line parseIdent cannot read).
218const identView = (line: unknown): IdentView | null => {
219 const p = parseIdent(line);
220 if (!p) return null;
221 const epoch = p.time === null ? null : Number(p.time);
222 const d = epoch === null ? null : new Date(epoch * 1000);
223 return { name: p.name, email: p.email, time: d && !Number.isNaN(d.getTime()) ? d.toISOString().replace('.000Z', 'Z') : null, epoch, tz: p.tz };
224};
226// The JSON view of a commit object. `signed` is whether it carries a gpgsig/gpgsig-sha256 header (any format:
227// OpenPGP, SSH, X.509); it says nothing about whether the signature verifies. The message is the raw body, UTF-8.
228export type CommitView = {
229 readonly tree: string;
230 readonly parents: readonly string[];
231 readonly author: IdentView | null;
232 readonly committer: IdentView | null;
233 readonly message: string;
234 readonly signed: boolean;
235};
236// Pure: a commit object's view. A malformed commit is parseCommit's (objects.ts) Err.
237export function commitView(data: Uint8Array, limits: LimitsInput = DEFAULT_LIMITS): Result<CommitView, PlyError> {
238 const parsed = parseCommit(data, limits);
239 if (!parsed.ok) return parsed;
240 const c: { readonly tree: string; readonly parents: readonly string[]; readonly author: string; readonly committer: string; readonly message: string | null; readonly extra: readonly string[] } = parsed.value;
241 return ok({ tree: c.tree, parents: c.parents, author: identView(c.author), committer: identView(c.committer), message: c.message === null ? '' : c.message, signed: c.extra.some(l => /^gpgsig(-sha256)? /.test(l)) });
244// The options operation() reads pass through (tracer, auth, fetchImpl, limits, transport, …).
245export type ReadOptions = EntryOptions;
246// Trees by oid, kept by the caller across reads (immutable: an oid names its bytes).
247export type TreeCache = Map<string, Uint8Array>;
248export type CommitResult = CommitView & { readonly ref: string; readonly oid: string };
249// An unborn HEAD (or that branch by name): git log's "does not have any commits yet". Not a not_found.
250export type EmptyCommit = { readonly empty: true; readonly ref: string };
252// What readCommit, listTree and readFile take as their second argument. `ref: null` is the remote's HEAD.
253export type RefConfig = { readonly ref: RefSpec };
254export type ReadCommitSpec = Input<RefConfig>;
255// An unborn HEAD the caller named is a state (EmptyCommit), not a failure. Every other answer is the resolution's own.
256const unbornState = (r: Result<Resolved, PlyError>): Option<EmptyCommit> => {
257 // Only ply's own error is believed: a transport that raises a look-alike object is not the server saying HEAD is unborn.
258 if (r.ok || !isPlyError(r.error) || r.error.code !== 'not_found' || r.error.miss.kind !== 'head_unborn') return none;
259 return some({ empty: true, ref: r.error.miss.target });
260};
261export async function readCommit(url: string, spec: ReadCommitSpec = {}, opts: ReadOptions = {}): Promise<Result<CommitResult | EmptyCommit, PlyError>> {
262 const { ref } = withDefaults<RefConfig>(spec, { ref: null });
263 return operation<EmptyCommit | CommitResult>('read_commit', url, { ...opts, attrs: { 'git.read_commit.ref': ref === null ? 'HEAD' : ref } }, async ({ t, outcome }) => {
264 const resolved = await resolveCommit(t, ref);
265 const empty = unbornState(resolved);
266 if (empty.tag === 'some') return outcome('ok', empty.value);
267 if (!resolved.ok) return resolved;
268 const { name, commit } = resolved.value;
269 const fetched = await commitById(t, commit);
270 if (!fetched.ok) return fetched;
271 const viewed = commitView(fetched.value.data, t.limits);
272 if (!viewed.ok) return viewed;
273 const view = viewed.value;
274 return outcome('ok', { ref: name, oid: commit, ...view }, { 'git.read_commit.oid': commit, 'git.read_commit.parents': view.parents.length, 'git.read_commit.signed': view.signed });
275 });
278// Effect: a tree's entries, from its bytes in the caller's cache (parsed here) or by one tree:0 fetch whose bytes the
279// cache keeps (the fetch's own check parsed them: treeEntries, #208).
280async function treeAt(t: Transport, cache: TreeCache, oid: Oid, limits: CheckedLimits): Promise<Result<TreeEntry[], PlyError>> {
281 const cached = mapGet(cache, oid);
282 if (cached.tag === 'some') return parseTree(cached.value, limits);
283 const fetched = await objectAt(t, oid, { filter: 'tree:0', expectType: TYPE.TREE });
284 if (!fetched.ok) return fetched;
285 cache.set(oid, fetched.value.data);
286 return treeEntries(fetched.value, limits);
288// A failure inside a span: recorded on it (the span's own end follows), and passed on.
289const spanErr = <E>(span: Span, r: Err<E>): Err<E> => { span.error(r.error); return r; };
291export type Walked = { readonly tree: Oid; readonly entry: TreeEntry | null };
292export type WalkConfig = { readonly cache: TreeCache };
293export type WalkOptions = Input<WalkConfig>;
294// Effect: walk `comps` from a tree the caller already has. `tree` is that starting oid; `entry` is the last component
295// (null when comps is empty). A missing component or a non-directory along the way is not_found with its miss. Each
296// level is a `git.read.tree` span under the transport's parent, so a readFile/listTree walk stays on that trace.
297// walkPath from a parsed tree id: readFile, listTree and ply's other walks start here.
298async function walkFrom(t: Transport, treeOid: Oid, comps: readonly string[], options: WalkOptions = {}): Promise<Result<Walked, PlyError>> {
299 const { cache } = withDefaults<WalkConfig>(options, { cache: new Map<string, Uint8Array>() });
300 let here = treeOid;
301 let entry: TreeEntry | null = null;
302 for (const [depth, name] of comps.entries()) {
303 // oxlint-disable-next-line no-loop-func -- the span runs to completion inside this iteration (awaited)
304 const level = await spanOn(t.tracer, 'git.read.tree', { parent: t.parent, attrs: { 'git.read.tree.depth': depth, 'git.read.tree.oid': here, 'git.read.tree.lookup': name } }, async (span): Promise<Result<TreeEntry, PlyError>> => {
305 span.set({ 'git.read.tree.cache_hit': isSome(mapGet(cache, here)) });
306 const entries = await treeAt(t, cache, here, t.limits);
307 if (!entries.ok) return spanErr(span, entries);
308 const found = fromNullable(entries.value.find(x => x.name === name));
309 span.set({ 'git.read.tree.entries': entries.value.length, 'git.read.tree.entry.found': found.tag === 'some', 'git.read.tree.entry.mode': getOrElse(mapOption(found, f => f.mode), '') });
310 if (found.tag === 'none') return spanErr(span, fail('not_found', `path component ${name} not found`, { miss: { kind: 'path', missing: name, existingPath: comps.slice(0, depth).join('/') } }));
311 if (depth < comps.length - 1 && found.value.mode !== '40000') return spanErr(span, fail('not_found', `${name} is not a directory`, { miss: { kind: 'not_directory', path: comps.slice(0, depth + 1).join('/'), mode: found.value.mode } }));
312 return ok(found.value);
313 });
314 if (!level.ok) return level;
315 entry = level.value;
316 here = entry.oid;
317 }
318 return ok({ tree: treeOid, entry });
320// The caller's tree id is parsed once, before the walk (fetchObject's refusal, as a first fetch of it would give).
321export async function walkPath(t: Transport, treeOid: string, comps: readonly string[], options: WalkOptions = {}): Promise<Result<Walked, PlyError>> {
322 const start = objectId(treeOid);
323 return start.ok ? walkFrom(t, start.value, comps, options) : start;
326// A commit-rooted walk: the commit's bytes (as fetched, hash-checked), its root tree, and the walk's last entry.
327export type CommitWalked = Walked & { readonly commit: Oid; readonly data: Uint8Array };
328export type CommitWalkConfig = WalkConfig & { readonly levels: number };
329export type CommitWalkOptions = Input<CommitWalkConfig>;
330// Effect: walk `comps` from the commit's root tree. `tree` is that root (walkPath's tree is the tree it started from).
331// `levels` is how many tree levels the caller reads from the root: the path's directories, and the listed directory
332// itself for listTree. The commit fetch brings the first of them where the server takes it (pathtrees.ts, #218).
333// `root`, when given, is the operation's span: it carries the commit and its root tree before the walk starts.
334async function walkFromCommit(t: Transport, commit: Oid, comps: readonly string[], { levels, cache }: CommitWalkConfig, root: Span | null): Promise<Result<CommitWalked, PlyError>> {
335 const fetched = await commitForWalk(t, commit, levels);
336 if (!fetched.ok) return fetched;
337 const { data } = fetched.value;
338 const info = parseCommit(data, t.limits);
339 if (!info.ok) return info;
340 if (root !== null) root.set({ 'git.read.commit': commit, 'git.read.tree.root': info.value.tree });
341 const walked = await walkFrom(t, info.value.tree, comps, { cache });
342 if (!walked.ok) return walked;
343 return ok({ commit, data, tree: info.value.tree, entry: walked.value.entry });
345// walkCommit(transport, commitOid, comps, { cache, levels }): the commit and its path in as few round trips as the server
346// allows (#222). A server known to take `combine:blob:none+tree:K` answers the commit and its first min(levels, 2) tree
347// levels in one fetch (pathtrees.ts); elsewhere it is the commit (tree:0, deepen 1), then one tree per level, as readFile
348// reads it. Every tree the walk reads lands in `cache`; a tree the commit's fetch brought and the walk did not read (the
349// listed directory, a sibling) is answered by fetchObject without another request. `levels` defaults to comps.length + 1
350// (the path's directories and the listed one); 0 fetches the commit alone. Not a commit (or an oid that is not 40 hex,
351// or levels that is not a non-negative integer) is that refusal; a missing component is walkPath's not_found.
352export async function walkCommit(t: Transport, commit: string, comps: readonly string[], options: CommitWalkOptions = {}): Promise<Result<CommitWalked, PlyError>> {
353 const id = objectId(commit);
354 if (!id.ok) return id;
355 const config = withDefaults<CommitWalkConfig>(options, { cache: new Map<string, Uint8Array>(), levels: comps.length + 1 });
356 if (!Number.isSafeInteger(config.levels) || config.levels < 0) return fail('bad_request', `walkCommit: levels must be a non-negative integer, got ${String(config.levels)}`);
357 return walkFromCommit(t, id.value, comps, config, null);
360// A path as the entries take it: validated components. With `allowRoot` (a tree path), a missing, null, empty or '/'
361// path is the root and one trailing '/' is dropped (git: `HEAD:dir/` is the tree). Without it (a file path), a trailing
362// '/' names a directory and is refused, as git refuses `HEAD:file/` for a blob (#300-8).
363export const pathComps = (path: unknown, limits: CheckedLimits, { allowRoot }: { readonly allowRoot: boolean }): Result<string[], PlyError> => {
364 if (allowRoot && (isNothing(path) || path === '' || path === '/')) return ok([]);
365 const valid = validatePath(allowRoot && typeof path === 'string' ? path.replace(/\/$/, '') : path, limits);
366 return valid.ok ? ok(valid.value.components) : valid;
367};
369// What listTree and readFile take as their second argument. `path: null` is the root for listTree, and refused by readFile.
370export type PathConfig = RefConfig & { readonly path: string | null };
371export type PathSpec = Input<PathConfig>;
372// The options of listTree and readFile: operation()'s, plus the caller's tree cache.
373export type TreeReadConfig = { readonly cache: TreeCache; readonly limits: LimitsInput };
374export type TreeReadOptions = ReadOptions & Input<TreeReadConfig>;
375// A null or missing limits record is the default, as the nullish read had it, and the record is parsed once, here; the
376// cache is fresh per call.
377const treeReadConfig = (options: TreeReadOptions): Result<{ readonly cache: TreeCache; readonly limits: CheckedLimits }, ErrorOf<'bad_request'>> =>
378 map(limitsOf(options), limits => ({ cache: getOrElse(readKey(options, 'cache'), new Map<string, Uint8Array>()), limits }));
380export type ListEntry = { readonly name: string; readonly mode: string; readonly oid: string; readonly type: EntryType };
381export type ListResult = { readonly ref: string; readonly commit: string; readonly tree: string; readonly entries: readonly ListEntry[] };
382// The listed directory: the walk's last entry when it is a tree, the root when the path was. not_found otherwise.
383function listedDir(walked: Walked, comps: readonly string[]): Result<Oid, PlyError> {
384 const { entry } = walked;
385 if (entry === null) return ok(walked.tree);
386 if (entry.mode !== '40000') return fail('not_found', `${comps.join('/')} is not a directory (mode ${entry.mode})`, { miss: { kind: 'not_directory', path: comps.join('/'), mode: entry.mode } });
387 return ok(entry.oid);
389export async function listTree(url: string, spec: PathSpec = {}, options: TreeReadOptions = {}): Promise<Result<ListResult, PlyError>> {
390 const { ref, path } = withDefaults<PathConfig>(spec, { ref: null, path: '' });
391 const config = treeReadConfig(options);
392 if (!config.ok) return config;
393 const { cache, limits } = config.value;
394 const checked = pathComps(path, limits, { allowRoot: true });
395 if (!checked.ok) return checked;
396 const comps = checked.value;
397 return operation('ls_tree', url, { ...options, limits, attrs: { 'git.ls_tree.ref': ref === null ? 'HEAD' : ref, 'git.ls_tree.path': comps.join('/'), 'git.ls_tree.path.depth': comps.length } }, async ({ t, root, outcome }) => {
398 const resolved = await resolveCommit(t, ref);
399 if (!resolved.ok) return resolved;
400 const { name, commit } = resolved.value;
401 // the tracer operation() started the root span on (opts.tracer)
402 const walked = await walkFromCommit(t, commit, comps, { levels: comps.length + 1, cache }, root);
403 if (!walked.ok) return walked;
404 const dir = listedDir(walked.value, comps);
405 if (!dir.ok) return dir;
406 const oid = dir.value;
407 const parsed = await treeAt(t, cache, oid, limits);
408 if (!parsed.ok) return parsed;
409 const entries: readonly TreeEntry[] = parsed.value;
410 return outcome('ok', { ref: name, commit, tree: oid, entries: entries.map(e => ({ name: e.name, mode: lsMode(e.mode), oid: e.oid, type: entryType(e.mode) })) }, { 'git.ls_tree.tree': oid, 'git.ls_tree.entries': entries.length });
411 });
414export type FileResult = {
415 readonly ref: string;
416 readonly commit: string;
417 readonly blob: string;
418 readonly mode: string;
419 readonly size: number;
420 readonly stream: ReadableStream<Uint8Array>;
421};
422// The file's entry: a symlink's blob is its target (what `git show <ref>:<path>` prints); a directory has no blob, and a
423// gitlink has none in this repository.
424function fileEntry(entry: TreeEntry, comps: readonly string[]): Result<TreeEntry, PlyError> {
425 if (entry.mode === '40000') return fail('not_found', `${comps.join('/')} is a directory`, { miss: { kind: 'is_directory', path: comps.join('/'), tree: entry.oid } });
426 if (entry.mode === '160000') return fail('not_found', `${comps.join('/')} is a submodule (commit ${entry.oid})`, { miss: { kind: 'submodule', path: comps.join('/'), commit: entry.oid } });
427 return ok(entry);
429// The root span ends when the stream is open (size known); the content's own span, `git.read.blob`, ends when the
430// stream does, with the bytes delivered and whether the oid verified. It outlives the root, so it is not the root's child
431// but the root of its own trace, linked both ways (follows_from / followed_by): README "Span lifetimes".
432export async function readFile(url: string, spec: PathSpec = {}, options: TreeReadOptions = {}): Promise<Result<FileResult, PlyError>> {
433 const { ref, path } = withDefaults<PathConfig>(spec, { ref: null, path: null });
434 const config = treeReadConfig(options);
435 if (!config.ok) return config;
436 const { cache, limits } = config.value;
437 const checked = pathComps(path, limits, { allowRoot: false });
438 if (!checked.ok) return checked;
439 const comps = checked.value;
440 return operation('read', url, { ...options, limits, attrs: { 'git.read.ref': ref === null ? 'HEAD' : ref, 'git.read.path': comps.join('/'), 'git.read.path.depth': comps.length } }, async ({ t, root, outcome }) => {
441 const resolved = await resolveCommit(t, ref);
442 if (!resolved.ok) return resolved;
443 const { name, commit } = resolved.value;
444 const walked = await walkFromCommit(t, commit, comps, { levels: comps.length, cache }, root);
445 if (!walked.ok) return walked;
446 // comps is non-empty (validatePath refuses an empty path), so the walk ends at an entry
447 // oxlint-disable-next-line typescript/no-unsafe-type-assertion, typescript/non-nullable-type-assertion-style -- see above (and no `!`: docs/STACK.md)
448 const file = fileEntry(walked.value.entry as TreeEntry, comps);
449 if (!file.ok) return file;
450 const entry = file.value;
451 // oxlint-disable-next-line no-use-before-define -- the JS's order (readFile, then openBlob): a function declaration, hoisted; the bundle's gzip budget
452 const opened = await openBlob(t, entry.oid, { follows: root });
453 if (!opened.ok) return opened;
454 const { size, stream } = opened.value;
455 return outcome('ok', { ref: name, commit, blob: entry.oid, mode: lsMode(entry.mode), size, stream }, { 'git.read.blob': entry.oid, 'git.read.blob.size': size, 'git.read.blob.mode': entry.mode });
456 });
459export type BlobStream = { readonly kind: 'stream'; readonly size: number; readonly stream: ReadableStream<Uint8Array> };
460export type BlobTooBig = { readonly kind: 'too_big'; readonly size: number };
461export type OpenedBlob = BlobStream | BlobTooBig;
462// `maxBytes`: the declared size above which the blob is too_big (left out: no cap). `follows`: the span the stream
463// follows (null: none).
464export type BlobConfig = { readonly maxBytes: number; readonly follows: Span | null };
465export type BlobOpts = Input<BlobConfig>;
466// The options without a cap: the answer is always a stream.
467export type FollowOpts = Input<Pick<BlobConfig, 'follows'>>;
468export type CappedOpts = Pick<BlobConfig, 'maxBytes'> & FollowOpts;
470// The fail-site recorder (test/space/failsite-hook.mjs) installs this only when PLY_FAILSITES is set. A guard, not a
471// cast: under the hook the value is a function and the property is absent otherwise, so the call is a no-op in a bundle.
472const FAIL_SITE = Symbol.for('ply.failsite');
473// Isolate age: Workers may freeze Date.now() at 0 during module evaluation (prod 8e7f5e26 stamped
474// ply.isolate_age_ms ≈ epoch). performance.now() starts at 0 with the isolate and advances; the delta
475// from module init is the age. Stamped on large-read spans (variance diagnosis).
476const ISOLATE_BORN_PERF = performance.now();
477const nowMs = (): number => performance.now();
478const isolateAgeMs = (): number => Math.round(nowMs() - ISOLATE_BORN_PERF);
479const isFailSiteRecorder = (v: unknown): v is (holder: (e: unknown) => unknown) => void => typeof v === 'function';
480type BodyState = Extract<SpState, { readonly phase: 'body' }>;
481// A pull of the pack stream, or a parser step, as a value: what it threw is the failure (failHere classifies it).
482const nextChunk = async (it: AsyncIterator<Uint8Array>): Promise<Result<IteratorResult<Uint8Array>, unknown>> => {
483 try { return ok(await it.next()); } catch (e) { return err(e); }
484};
485const stepHeader = (sp: SpState, chunk: Uint8Array): ReturnType<typeof spStep> => spStep(sp, chunk);
486// Effect: pull until the object header is read (→ type and size). The zlib bytes after it go to `early`.
487async function blobHeader(it: AsyncIterator<Uint8Array>, early: Uint8Array[]): Promise<Result<BodyState, unknown>> {
488 let sp: SpState = spInit();
489 while (sp.phase !== 'body') {
490 const next = await nextChunk(it);
491 if (!next.ok) return next;
492 if (next.value.done === true) return err(plyError('pack_corrupt', 'pack ended before the object header'));
493 const r = stepHeader(sp, next.value.value);
494 if (!r.ok) return r;
495 sp = r.value.state;
496 early.push(...r.value.zlib);
497 }
498 if (sp.type !== TYPE.BLOB) return err(plyError('pack_corrupt', `expected blob, got ${getOrElse<string | number>(fromNullish((TYPE_NAME as TypeNames)[sp.type]), sp.type)}`));
499 return ok(sp);
501// Effect: one blob on the caller's transport. Reads the pack until the object header (→ size). A declared size above
502// `maxBytes` is `{ kind: 'too_big' }`: the fetch is cancelled and no body byte is delivered (`git.read.blob.header_only`).
503// Otherwise the zlib bytes go through DecompressionStream and a verifying transform. The transform releases every chunk
504// but the latest as it arrives, and releases the latest only after the pack trailer and the object hash verify. A failure
505// errors the stream with that chunk still held, so the body never completes on unverified bytes. Back-pressure: the pump
506// awaits each write, so at most one network chunk and one inflate chunk are in flight beyond the chunk being held.
507// `follows` is the span the stream follows (the read root, or git.checkout.blobs): the consumer reads after it returns.
508// The tracer is the transport's. Header and cap failures are a Result; a bad `maxBytes` is too. Without `maxBytes` the
509// result is a stream (a cap is the only way the header refuses the blob).
510export function openBlob(t: Transport, oid: string, ...opts: [] | [FollowOpts]): Promise<Result<BlobStream, PlyError>>;
511export function openBlob(t: Transport, oid: string, opts: CappedOpts): Promise<Result<OpenedBlob, PlyError>>;
512export function openBlob(t: Transport, oid: string, opts: BlobOpts): Promise<Result<OpenedBlob, PlyError>>;
513export async function openBlob(t: Transport, oid: string, opts: BlobOpts = {}): Promise<Result<OpenedBlob, PlyError>> {
514 // A given maxBytes is checked, null included (a cap the caller passed); only leaving it out is no cap.
515 const cap = readKey(opts, 'maxBytes');
516 if (cap.tag === 'some' && (!Number.isInteger(cap.value) || cap.value < 0)) return fail('bad_request', 'maxBytes must be an integer >= 0', { what: 'maxBytes' });
517 const maxBytes = getOrElse(cap, Number.POSITIVE_INFINITY);
518 const { follows } = withDefaults<Pick<BlobConfig, 'follows'>>(opts, { follows: null });
519 const span = t.tracer.start('git.read.blob', { ...(follows === null ? {} : { follows }), attrs: { 'git.read.blob.oid': oid } });
520 // Inflated-blob caching lives in ply-web's Workers Cache BlobCache entrypoint (never caches.default).
521 const fetchSpan = t.tracer.start('git.upload-pack fetch', { parent: span, kind: KIND.CLIENT });
522 // Inflate+verify wall clock (overlaps the upload-pack body). Opened once the object header has passed the size cap.
523 let inflateSpan: { ended: boolean; set(a: Record<string, unknown>): { end(): void }; end(): void; error(e: unknown): { end(): void } } | null = null;
524 let hashMs = 0;
525 const endInflate = (attrs: Record<string, unknown> = {}): void => {
526 if (inflateSpan === null || inflateSpan.ended) return;
527 inflateSpan.set(attrs).end();
528 };
529 const it: AsyncIterator<Uint8Array> = packStream(t, { wants: [oid] }, fetchSpan)[Symbol.asyncIterator]();
530 // Close the pack stream: the read failed, was cancelled, or the cap ended it. Its own failure then is not the outcome.
531 const close = async (): Promise<void> => { if (typeof it.return === 'function') await it.return().catch(() => { /* the outcome is already decided */ }); };
532 // the first of failure, cancellation and verified end records the outcome; whatever follows (a cancel aborting the
533 // pump) leaves the ended spans alone
534 const failHere = (e: unknown): unknown => {
535 // A ply error built before this call has a stack that does not name the call, so the fail-site recorder
536 // (installed only under PLY_FAILSITES) would not see it. Absent the hook there is no function to call.
537 const record: unknown = (globalThis as Record<symbol, unknown>)[FAIL_SITE];
538 if (isFailSiteRecorder(record)) record(failHere);
539 const code = thrownCodeOr(e, null);
540 if (isPlyCode(code)) {
541 if (!span.ended) { fetchSpan.error(e).end(); endInflate({ 'git.blob.inflate.outcome': code }); span.error(e).set({ 'git.read.blob.outcome': code }).end(); }
542 return e;
543 }
544 const wrapped = plyError('pack_corrupt', `blob stream: ${thrownText(e)}`, { cause: e });
545 if (!span.ended) { fetchSpan.error(wrapped).end(); endInflate({ 'git.blob.inflate.outcome': wrapped.code }); span.error(wrapped).set({ 'git.read.blob.outcome': wrapped.code }).end(); }
546 return wrapped;
547 };
548 const early: Uint8Array[] = [];
549 const header = await blobHeader(it, early);
550 if (!header.ok) {
551 await close();
552 return err(raised('pack_corrupt', failHere(header.error)));
553 }
554 let sp: SpState = header.value;
555 const size = header.value.size;
556 span.set({ 'git.read.blob.size': size });
557 // The cap is the declared size. Bytes already in the packet that completed the header stay unread by the consumer;
558 // the iterator is closed so nothing further is pulled.
559 if (size > maxBytes) {
560 span.set({ 'git.read.blob.header_only': true, 'git.read.blob.outcome': 'too_big' }).end();
561 fetchSpan.end();
562 await close();
563 return ok({ kind: 'too_big', size });
564 }
565 inflateSpan = t.tracer.start('git.blob.inflate', { parent: span, attrs: { 'git.read.blob.oid': oid, 'git.read.blob.size': size } });
566 const ds = new DecompressionStream('deflate');
567 const writer = ds.writable.getWriter();
568 // a pump failure (network, framing, trailer) aborts the inflate side, which errors the stream the consumer reads. The
569 // verify transform's flush never runs then (its catch is unreachable), so the failure is recorded here.
570 // The abort's reason is the failure: workerd's DecompressionStream errors its readable with a reason of its own (the
571 // message without the code), node's with the one given, so the reader is handed the failure kept here (#144).
572 let aborted: { readonly e: unknown } | null = null;
573 const readFailure = (e: unknown): unknown => {
574 // Stryker disable next-line ConditionalExpression: node's DecompressionStream keeps the abort reason, so only workerd (test/workerd.test.js) tells the two apart
575 if (aborted !== null) return aborted.e;
576 return isPlyThrown(e) ? e : failHere(e);
577 };
578 const abortWith = async (e: unknown): Promise<void> => { const failed = failHere(e); if (aborted === null) aborted = { e: failed }; await writer.abort(failed).catch(() => { /* already failing */ }); await close(); };
579 const pump = (async (): Promise<void> => {
580 for (const z of early) await writer.write(bufferSource(z));
581 for (;;) {
582 const step = await it.next();
583 // oxlint-disable-next-line typescript/strict-boolean-expressions -- bundle budget: the JS's own truthy test (an iterator's done is true, false or absent)
584 if (step.done) break;
585 const stepped = spStep(sp, step.value);
586 if (!stepped.ok) { await abortWith(stepped.error); return; }
587 const r: SpStepped = stepped.value; sp = r.state;
588 for (const z of r.zlib) await writer.write(bufferSource(z));
589 }
590 const finished = spFinish(sp); // pack trailer checksum
591 if (!finished.ok) { await abortWith(finished.error); return; }
592 sp = finished.value;
593 fetchSpan.end();
594 await writer.close();
595 })();
596 pump.catch(abortWith);
597 const sha = streamingSha1();
598 // hash_await_ms: wall time spent awaiting hasher update/hex only. DigestStream hashes in the host while
599 // write() resolves on accept, so this is often ~0 on Workers; the CPU shows up in GET cpu_time_ms overlapping
600 // inflate — not a free hash. Renamed from hash_ms (loop 2026-11-08) so the metric does not claim CPU self-time.
601 // Coalescing into HASH_BUF_BYTES cuts one await per inflate chunk.
602 const HASH_BUF_BYTES = 65_536;
603 const hashBuf = new Uint8Array(HASH_BUF_BYTES);
604 let hashBufLen = 0;
605 const hashFlush = async (): Promise<void> => {
606 if (hashBufLen === 0) return;
607 const h0 = nowMs();
608 await sha.update(hashBufLen === HASH_BUF_BYTES ? hashBuf : hashBuf.subarray(0, hashBufLen));
609 hashMs += nowMs() - h0;
610 hashBufLen = 0;
611 };
612 const hashPush = async (chunk: Uint8Array): Promise<void> => {
613 let off = 0;
614 while (off < chunk.byteLength) {
615 const n = Math.min(HASH_BUF_BYTES - hashBufLen, chunk.byteLength - off);
616 hashBuf.set(chunk.subarray(off, off + n), hashBufLen);
617 hashBufLen += n;
618 off += n;
619 if (hashBufLen === HASH_BUF_BYTES) await hashFlush();
620 }
621 };
622 {
623 const h0 = nowMs();
624 await sha.update(objectHeader('blob', size));
625 hashMs += nowMs() - h0;
626 }
627 let seen = 0;
628 const inflateStarted = nowMs();
629 // The latest inflate chunk. An empty chunk is not a chunk: releasing the real tail because a zero-length piece
630 // arrived would finish the body before the hash and the trailer were checked.
631 let held: Uint8Array | null = null;
632 // The stream edge: a transform or flush that throws errors the stream, which is how the consumer is told.
633 const verify = new TransformStream<Uint8Array, Uint8Array>({
634 async transform(chunk, ctl) {
635 if (chunk.byteLength === 0) return;
636 seen += chunk.length;
637 if (seen > size) throw failHere(plyError('pack_corrupt', `server streamed more than the ${size} bytes it declared`));
638 await hashPush(chunk);
639 if (held) ctl.enqueue(held);
640 held = chunk;
641 },
642 async flush(ctl) {
643 try { await pump; } catch (e) { throw failHere(e); }
644 if (seen !== size) throw failHere(plyError('pack_corrupt', `inflated ${seen} != declared ${size}`));
645 await hashFlush();
646 const h1 = nowMs();
647 const got = await sha.hex();
648 hashMs += nowMs() - h1;
649 if (got !== oid) throw failHere(plyError('pack_corrupt', `blob content hashes to ${got}, not ${oid}`));
650 if (held) ctl.enqueue(held);
651 held = null;
652 const inflateMs = Math.max(0, nowMs() - inflateStarted);
653 const bytesPerSec = inflateMs > 0 ? Math.round(seen / (inflateMs / 1000)) : 0;
654 endInflate({
655 'git.blob.inflate.outcome': 'ok',
656 'git.read.blob.hash_await_ms': Math.round(hashMs * 1000) / 1000,
657 'git.blob.inflate.bytes_per_sec': bytesPerSec,
658 'ply.isolate_age_ms': isolateAgeMs(),
659 });
660 span.set({
661 'git.read.blob.bytes': seen,
662 'git.read.blob.verified': true,
663 'git.read.blob.hasher': sha.kind,
664 'git.read.blob.hash_await_ms': Math.round(hashMs * 1000) / 1000,
665 'git.blob.inflate.bytes_per_sec': bytesPerSec,
666 'ply.isolate_age_ms': isolateAgeMs(),
667 'git.read.blob.outcome': 'ok',
668 }).end();
669 },
670 });
671 // DecompressionStream's own refusals (trailing junk after the deflate end, a bad block) are platform errors with no ply
672 // code; the consumer sees them as pack_corrupt like every other refusal on this path (I1: a code from the fixed set).
673 // The consumer's cancel() is an outcome of its own ('cancelled', not an error): without the cancel hook a cancel after the
674 // pump has written its last chunk would leave both spans open forever, and one before it would read as pack_corrupt.
675 const inner = ds.readable.pipeThrough(verify).getReader();
676 const stream = new ReadableStream<Uint8Array>({
677 async pull(c) {
678 let r: ReadableStreamReadResult<Uint8Array>;
679 try { r = await inner.read(); } catch (e) { throw readFailure(e); }
680 if (r.done) c.close(); else c.enqueue(r.value);
681 },
682 async cancel(reason) {
683 if (!span.ended) { fetchSpan.end(); endInflate({ 'git.blob.inflate.outcome': 'cancelled' }); span.set({ 'git.read.blob.bytes': seen, 'git.read.blob.hash_await_ms': Math.round(hashMs * 1000) / 1000, 'git.read.blob.outcome': 'cancelled' }).end(); }
684 await inner.cancel(reason).catch(() => { /* cancelling: the outcome is recorded */ });
685 await close();
686 },
687 }, { highWaterMark: 0 });
688 return ok({ kind: 'stream', size, stream });
691export type BlobData = { readonly kind: 'bytes'; readonly data: Uint8Array<ArrayBuffer> };
692// Effect: openBlob, then the whole verified stream. A stream that errors is that error; `too_big` is not read.
693export function readBlob(t: Transport, oid: string, ...opts: [] | [FollowOpts]): Promise<Result<BlobData, PlyError>>;
694export function readBlob(t: Transport, oid: string, opts: CappedOpts): Promise<Result<BlobData | BlobTooBig, PlyError>>;
695export function readBlob(t: Transport, oid: string, opts: BlobOpts): Promise<Result<BlobData | BlobTooBig, PlyError>>;
696export async function readBlob(t: Transport, oid: string, opts: BlobOpts = {}): Promise<Result<BlobData | BlobTooBig, PlyError>> {
697 // The general overload: a caller's options may or may not carry a cap.
698 const open: (t: Transport, oid: string, opts: BlobOpts) => Promise<Result<OpenedBlob, PlyError>> = openBlob;
699 const opened = await open(t, oid, opts);
700 if (!opened.ok) return opened;
701 switch (opened.value.kind) {
702 case 'too_big': return ok(opened.value);
703 case 'stream': {
704 const parts: Uint8Array[] = [];
705 try { for await (const chunk of opened.value.stream) parts.push(chunk); }
706 // the stream's error, as the consumer of readFile's stream sees it; a value that is not ply's is coded here
707 catch (e) { return err(raised('pack_corrupt', e)); }
708 return ok({ kind: 'bytes', data: concat(parts) });
709 }
710 }
711 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
712 return assertNever(opened.value);
Diagnostics6 git calls · 95 ms
CallStatusSizeTime095 ms
discover200191 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=191
git.server.agent=git/github-9922ec520325-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=191
git.pkt.payload.max=36
ls-refs20012 KiB2 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=11990
git.response.cache=UPDATING
git.response.duration_ms=2
git.protocol.version=2
git.pkt.frames=152
git.pkt.data=151
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=11990
git.pkt.payload.max=122
git.ls_refs.count=151
git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 102004.2 KiB · hit3 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=4347
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4
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=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4347
git.pkt.payload.max=4247
git.sideband.band1.bytes=4247
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=10
git.pack.bytes=4247
git.pack.ofs_delta=0
git.pack.ref_delta=0
git.pack.chain.max=0
git.pack.trailer=a6caf8e129bea82c9bae4cbc7c130c9205add400
git.pack.full=10
Open pack map
fetchtree:0200919 B · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=919
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=800d30ba8923860bfc460ca884b7f9ba22083588
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=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=919
git.pkt.payload.max=892
git.sideband.band1.bytes=892
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=892
git.pack.trailer=5323b9266eea5ded637285d1c5320699f12be76e
Open pack map
fetchtree:02002.4 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=85
git.response.bytes=2507
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=8f720d29ff85ce682ffdad9c393b04a3834c3203
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=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=2507
git.pkt.payload.max=2480
git.sideband.band1.bytes=2480
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=2480
git.pack.trailer=723b6bf1d4d6021fe5eb940c622b9ff00ee4a381
Open pack map
fetch20015 KiB85 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=15223
git.response.cache=MISS
git.response.duration_ms=85
git.fetch.wants=43b30913d380c01c446d02fd20e8f6bfd1a7e72c
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=5
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=15223
git.pkt.payload.max=8192
git.sideband.band1.bytes=15191
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://github.com/ivarvong/ply
Ref
refs/heads/main
Commit
19912563f540228593df0c489082e5e2508e21e4
cf-ray
a5e0fc5ab86e332c
Request
0bd8e01a…
Protocol
v2 · sha1
Agent
git/github-9922ec520325-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format