Artifactspublic-v0

ply

main
ply4 git calls336 ms60 KiB2 cachedprotocol v2
1027 lines71 KiBRaw
1// v0 receive-pack: commands + thin pack in, report-status out. Planning the request, reading the response stream,
2// classifying the report and deciding the outcome are pure; `push` is the one effect. Any failure after the body is on
3// the wire is 'ambiguous' (the ref may have moved).
4import { fail, ambiguousAfterPush, remoteText, REMOTE_TEXT_MAX } from './errors.js';
5import type { ErrorOf, PlyError } from './errors.js';
6import { ok, err, assertNever, flatMapOption, getOrElse, mapOption } from './result.js';
7import type { Err, Result } from './result.js';
8import { pkt, FLUSH, pktInit, pktStep } from './pktline.js';
9import { td, concat, decodeBytes, decodeChunk } from './bytes.js';
10import { SIDEBAND_PACK, SIDEBAND_PROGRESS, SIDEBAND_ERROR } from './format.js';
11import { ZERO_OID, parseOid } from './oid.js';
12import type { Oid } from './oid.js';
13import type { Refname } from './refname.js';
14import { measurePack, streamPack, streamSource } from './packwrite.js';
15import type { MeasuredPack, StreamedPack } from './packwrite.js';
16import { frames, coded, clientSpan, spanned, wrapNet, UA } from './transport.js';
17import { limitExceeded, parseLimits } from './limits.js';
18import type { LimitsInput } from './limits.js';
19// oxlint-disable-next-line import/max-dependencies -- the push path: framing, pack writer, transport, limits, validation, the parsed brands, Result
20import { validatePushRef, validateWire } from './validate.js';
21import type { WireField } from './validate.js';
23/* oxlint-disable no-magic-numbers -- span tails and the short-oid display width are diagnostics, not wire-format facts */
24const SHORT_OID = 8;
25const BAND_TAIL = 4096;
26const BAND_ATTR = 1024;
27const REPORT_KEEP = 64;
28/* oxlint-enable no-magic-numbers */
29const UNPACK = 'unpack ';
30const OK_REF = 'ok ';
31const NG_REF = 'ng ';
33export { ZERO_OID };
35// One ref update as a caller writes it. create: oldOid = zeros; delete: newOid = zeros. Plain strings in: planPush parses
36// every command (parseCommand) before anything is built or sent, and the plan carries only the parsed ones.
37export type Command = { readonly ref: string; readonly oldOid: string; readonly newOid: string };
38export type Commands = readonly [Command, ...Command[]];
39// A command parsed once: the ref is one receive-pack takes (validatePushRef), the oids are 40 lowercase hex (parseOid).
40export type PushCommand = { readonly ref: Refname; readonly oldOid: Oid; readonly newOid: Oid };
41// The parsed list: at least one PushCommand, made only by parseCommands / planPush (the brand is a type).
42declare const PARSED: unique symbol;
43export type ParsedCommands = readonly [PushCommand, ...PushCommand[]] & { readonly [PARSED]: true };
44// The guard is the whole check: every element is already a PushCommand (its type), so what is left is at least one.
45const isParsed = (cs: readonly PushCommand[]): cs is ParsedCommands => cs.length > 0;
46// A command from a typed caller, or an untyped one (or the single-ref form, whose fields may be missing).
47export type RawCommand = { readonly ref: unknown; readonly oldOid: unknown; readonly newOid: unknown };
48// @decoder parseCommand prefix=push-command
49export function parseCommand(c: RawCommand): Result<PushCommand, ErrorOf<'bad_request'>> {
50 const ref = validatePushRef(c.ref, c.newOid === ZERO_OID);
51 if (!ref.ok) return ref;
52 const oldOid = parseOid(c.oldOid);
53 const newOid = parseOid(c.newOid);
54 if (!oldOid.ok || !newOid.ok) return fail('bad_request', 'push: oids must be 40-hex');
55 return ok({ ref: ref.value, oldOid: oldOid.value, newOid: newOid.value });
57// The list's own check, after every command's: none at all is 'protocol' with nothing sent (push read the first command
58// for its span; an empty list was the TypeError that read raised, coded 'protocol', before any request or span).
59const nonEmpty = (cs: readonly PushCommand[]): Result<ParsedCommands, ErrorOf<'protocol'>> => (isParsed(cs) ? ok(cs) : fail('protocol', 'push: no commands'));
60const parseEach = (raw: readonly RawCommand[]): Result<PushCommand[], ErrorOf<'bad_request'>> => {
61 const parsed: PushCommand[] = [];
62 for (const c of raw) {
63 const one = parseCommand(c);
64 if (!one.ok) return one;
65 parsed.push(one.value);
66 }
67 return ok(parsed);
68};
69// The public list, parsed once. planPush runs the same two steps with its own checks between them.
70// @decoder parseCommands prefix=push-command
71export function parseCommands(raw: readonly RawCommand[]): Result<ParsedCommands, ErrorOf<'bad_request' | 'protocol'>> {
72 const each = parseEach(raw);
73 return each.ok ? nonEmpty(each.value) : each;
75// A pkt-line frame as pktStep and the transports' frames() yield it.
76export type { Frame } from './transport.js';
77import type { Frame, RequestBody, Scrub, SpanOpts, Transport } from './transport.js';
78import type { PktState } from './pktline.js';
79import type { PackInput, BuiltEntry } from './pack.js';
80import { WHOLE, inputBase, typeNameOf } from './pack.js';
81import { hashObject } from './objects.js';
82import type { Span } from './otel.js';
83import type { Input } from './absent.js';
84import { at, atOr, field, fromNullish, isMissing, mapGet, withDefaults } from './absent.js';
85import { lsRefs } from './lsrefs.js';
86import type { LsRefsResult } from './lsrefs.js';
88// local sideband parser to reduce dependencies
89const parseSideband = (payload: Uint8Array): { readonly band: number; readonly body: Uint8Array } => ({ band: atOr(payload, 0, 0), body: payload.subarray(1) });
92// What send-pack.c send_pack() checks against the advertisement before it sends a byte, as a value: the `atomic` and
93// `push-options` a push may ask for. receive-pack ignores an `atomic` it did not advertise (the refs land one by one)
94// and reads unadvertised option lines as the pack, so the request builder takes these only from a CheckedCaps, which
95// only receivecaps.ts checkPushCaps makes (from the server's advertisement). The brand is a type: nothing at run time.
96declare const CHECKED: unique symbol;
97export type CheckedCaps = { readonly atomic: boolean; readonly pushOptions: readonly string[]; readonly [CHECKED]: true };
99// Each line as a pkt-line, or the first one pkt() refuses (longer than a pkt-line holds).
100function pkts(lines: readonly string[]): Result<Uint8Array[], ErrorOf<'bad_request'>> {
101 const out: Uint8Array[] = [];
102 for (const l of lines) {
103 const p = pkt(l);
104 if (!p.ok) return p;
105 out.push(p.value);
106 }
107 return ok(out);
109// commands: [{ ref, oldOid, newOid }] (create: oldOid = zeros; delete: newOid = zeros). A push with only deletes sends no
110// pack. The wire encoder: `caps` is sent as given (push builds it with requestCaps). A line pkt() refuses is its Err.
111export const pushBody = ({ commands, caps = ['report-status', `agent=${UA.replace(/ .*/u, '')}`] }: { readonly commands: readonly Command[] } & Input<{ readonly caps: readonly string[] }>, pack: Uint8Array | null = null): Result<Uint8Array<ArrayBuffer>, ErrorOf<'bad_request'>> => {
112 const lines = commands.map((c, i) => `${c.oldOid} ${c.newOid} ${c.ref}${i === 0 ? `\0${caps.join(' ')}` : ''}\n`);
113 const framed = pkts(lines);
114 return framed.ok ? ok(concat([...framed.value, FLUSH, ...(pack ? [pack] : [])])) : framed;
115};
117// ---- the push outcome (pure): wire → stream shape → report shape → outcome → Result, each a tagged union ----
118// Principle (SAFETY.md I36): once the request body may have reached the server, ply says "landed" or "not landed" only on
119// a report exactly as git's receive-pack writes it (builtin/receive-pack.c report/report_v2, cmd_receive_pack); every
120// other post-send state is 'ambiguous'. Each step below is an allowlist: what it does not recognize falls to ambiguous.
121// The space of responses and the expected outcome of each cell: test/space/push-outcome.space.js and SPACE.md.
123// 1. The stream. A step machine over the outer pkt frames, ending in
124// { tag: 'report', lines } — the report's pkt payloads, framed as git frames them, nothing before or after — or
125// { tag: 'broken', why, remote } — anything else (band 3, an unknown band, a missing or extra flush, trailing data);
126// remote: band 3's message, or null
127// git's shapes: plain — report pkts, flush (= the report's flush), end; side-band-64k — band 2 (progress, hook stderr)
128// and empty band-1 keepalives, then the report pkts and their flush inside band 1, band 2 (post-receive), then the
129// outer flush (cmd_receive_pack: packet_flush(1) when use_sideband), end.
130export type Broken = { readonly tag: 'broken'; readonly why: string; readonly remote: string | null };
131export type Reading = {
132 readonly tag: 'reading';
133 readonly sideband: boolean;
134 readonly phase: 'report' | 'reported' | 'done';
135 readonly inner: PktState;
136 readonly lines: Uint8Array[];
137 readonly band2: string;
138 readonly band2Carry: Uint8Array;
139 readonly band2Frames: number;
140};
141export type StreamReport = { readonly tag: 'report'; readonly lines: readonly Uint8Array[] };
142export type StreamState = Reading | Broken | StreamReport;
143const broken = (why: string, remote: string | null = null): Broken => ({ tag: 'broken', why, remote });
144// `lines` grows in place (a report can hold limits.maxReportLines lines): a state is not reused once stepped.
145export const streamInit = (sideband: boolean): Reading => ({ tag: 'reading', sideband, phase: 'report', inner: pktInit(), lines: [], band2: '', band2Carry: new Uint8Array(0), band2Frames: 0 });
146// The band-1 pkt-lines that do not frame (pktStep's protocol error) are the Err: push reads it as a lost response.
147// @decoder streamStep prefix=stream
148// oxlint-disable-next-line complexity -- one step machine: each frame kind and band in the order git writes them
149export function streamStep(st: StreamState, f: Frame): Result<StreamState, ErrorOf<'protocol'>> {
150 // Stryker disable next-line ConditionalExpression: push stops stepping at the first non-reading state
151 if (st.tag !== 'reading') return ok(st);
152 if (st.phase === 'done') return ok(broken('data after the final flush'));
153 if (f.kind === 'flush') {
154 if (!st.sideband || (st.phase === 'reported' && st.inner.carry === null)) return ok({ ...st, phase: 'done' });
155 return ok(broken('flush before the report ended'));
156 }
157 // Stryker disable next-line ConditionalExpression: a delim/end frame has no payload, so read as data it still breaks the stream or the report
158 if (f.kind !== 'data') return ok(broken(`${f.kind} packet`));
159 if (!st.sideband) { st.lines.push(f.payload); return ok(st); }
160 const { band, body }: { readonly band: number; readonly body: Uint8Array } = parseSideband(f.payload);
161 // decodeChunk: a character cut by a frame boundary is held for the next frame instead of decoding as two U+FFFD (#43)
162 if (band === SIDEBAND_PROGRESS) { const d: { readonly text: string; readonly carry: Uint8Array } = decodeChunk(st.band2Carry, body); return ok({ ...st, band2: (st.band2 + d.text).slice(-BAND_TAIL), band2Carry: d.carry, band2Frames: st.band2Frames + 1 }); }
163 if (band === SIDEBAND_ERROR) return ok(broken('band 3', td.decode(body).trim()));
164 if (band !== SIDEBAND_PACK) return ok(broken(`bad sideband ${band}`));
165 // an empty band-1 packet is copy_to_sideband's keepalive: sent while hooks run, before the report and after it (post-receive)
166 if (body.length === 0) return ok(st);
167 // Stryker disable next-line ConditionalExpression: without it, band-1 bytes after the report's flush still break it (the loop below, or the carry at the outer flush)
168 if (st.phase !== 'report') return ok(broken('band 1 after the report'));
169 const r = pktStep(st.inner, body);
170 if (!r.ok) return r;
171 let phase: Reading['phase'] = st.phase;
172 for (const g of r.value.frames) {
173 if (phase !== 'report') return ok(broken('band 1 after the report'));
174 switch (g.kind) {
175 case 'flush': phase = 'reported'; continue;
176 case 'data': st.lines.push(g.payload); continue;
177 case 'delim':
178 case 'end': return ok(broken(`${g.kind} packet in the report`));
179 }
180 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
181 return assertNever(g);
182 }
183 return ok({ ...st, inner: r.value.state, phase });
185// Stryker disable next-line ConditionalExpression: a broken state has no phase, so it stays broken either way
186export const streamFinish = (st: StreamState): Broken | StreamReport => {
187 if (st.tag !== 'reading') return st;
188 return st.phase === 'done' ? { tag: 'report', lines: st.lines } : broken('no final flush');
189};
191// 2. The report. git's grammar, exactly: "unpack ok" or "unpack <one of unpack()'s failure strings>", then for each
192// commanded ref exactly one "ok <ref>" or "ng <ref> <reason>" (reason: printable ASCII), every line ending in LF, and
193// nothing else (report_v2's option lines come only from a proc-receive hook, which redirects the update: not modelled).
194// A step machine over the report's lines, one parser (send-pack.c receive_unpack_status, then receive_status):
195// { tag: 'unpack' } — before the first line: it must be git's unpack line
196// { tag: 'refs', unpack, want, seen } — after it: one well-formed status per commanded ref, each at most once
197// { tag: 'malformed', why } — anything else (absorbing)
198// and reportFinish's shapes:
199// { tag: 'statuses', refs } — unpack ok, one status per commanded ref
200// { tag: 'unpackFailed', status, refs } — unpack failed and every ref is "ng <ref> unpacker error" (git), or every
201// ref is "ng <ref> <status>", the unpack status echoed (a host: echoedFailure)
202// { tag: 'malformed', why }
203// execute_commands: an unpack failure marks every command "unpacker error", and nothing else does.
204export type RefStatus = { readonly ref: string; readonly ok: true; readonly reason: '' } | { readonly ref: string; readonly ok: false; readonly reason: string };
205export type Malformed = { readonly tag: 'malformed'; readonly why: string };
206export type ReportState =
207 | { readonly tag: 'unpack'; readonly want: ReadonlySet<string> }
208 | { readonly tag: 'refs'; readonly unpack: string; readonly want: ReadonlySet<string>; readonly seen: Map<string, RefStatus> }
209 | Malformed;
210export type ReportShape =
211 | { readonly tag: 'statuses'; readonly refs: readonly RefStatus[] }
212 | { readonly tag: 'unpackFailed'; readonly status: string; readonly refs: readonly RefStatus[] }
213 | Malformed;
214const GIT_UNPACK_ERROR_LIST = [
215 'eof before pack header was fully read', 'protocol error (pack signature mismatch detected)', 'protocol error (pack version unsupported)',
216 'unknown error in parse_pack_header', 'unable to create temporary object directory', 'unpack-objects abnormal exit', 'index-pack fork failed',
217 'index-pack abnormal exit',
218] as const;
219export type GitUnpackError = typeof GIT_UNPACK_ERROR_LIST[number];
220export const GIT_UNPACK_ERRORS: readonly GitUnpackError[] = Object.freeze(GIT_UNPACK_ERROR_LIST);
221const seenUnpack = (status: GitUnpackError): true => {
222 switch (status) {
223 case 'eof before pack header was fully read':
224 case 'protocol error (pack signature mismatch detected)':
225 case 'protocol error (pack version unsupported)':
226 case 'unknown error in parse_pack_header':
227 case 'unable to create temporary object directory':
228 case 'unpack-objects abnormal exit':
229 case 'index-pack fork failed':
230 case 'index-pack abnormal exit':
231 return true;
232 }
233 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
234 return assertNever(status);
235};
236const isGitUnpackError = (status: string): boolean => {
237 for (const item of GIT_UNPACK_ERRORS) if (item === status) return seenUnpack(item);
238 return false;
239};
240const UNPACKER_ERROR = 'unpacker error';
241const PRINTABLE = /^[ -~]+$/u;
242// A host's unpack failure (not git's grammar): every commanded ref is refused with the unpack status itself as its
243// reason, or with a documented alias of that status. Cloudflare Artifacts writes the exact echo ("unpack invalid pack
244// entry type 0", then "ng <ref> invalid pack entry type 0" for each ref; observed 2026-11-10, #246) and one alias
245// ("unpack reachable object is missing", then "ng <ref> missing object"; observed 2026-11-10, #266, ray
246// a589199bca2624ad-IAD). Positive evidence, not a guess: a landed or refused report is never one byte from an exact
247// echo, and the alias is a closed table (SPACE.md, judgment 3). Any other unmatched ng reason stays malformed.
248const HOST_UNPACK_ALIASES: ReadonlyArray<readonly [string, string]> = Object.freeze([
249 ['reachable object is missing', 'missing object'],
250]);
251const unpackReasonMatches = (status: string, reason: string): boolean => {
252 if (reason === status) return true;
253 for (const [s, r] of HOST_UNPACK_ALIASES) if (status === s && reason === r) return true;
254 return false;
255};
256const echoedFailure = (status: string, refs: readonly RefStatus[]): boolean => status !== 'ok' && refs.every(r => !r.ok && unpackReasonMatches(status, r.reason));
257// Artifacts' body cap, echoed on unpack and ng (observed 2026-11-10, #266, ray a58a707c0a76c98d-IAD):
258// artifacts_git_receive_pack_request_too_large: push is 286.3 MiB, limit is 64.0 MiB
259// A reason is host-written, up to a pkt-line long, so it is parsed by hand in time linear in its length: the literal
260// parts are compared in place, one indexOf finds the middle, and each figure is matched against MIB_FIGURE: two
261// anchored alternatives, every quantifier bounded, the two digit runs separated by a required '.', so a digit run
262// matches one way only and a long one is refused within 10 characters. (The pattern this replaces,
263// `[0-9]+[.]?[0-9]*` twice, split a digit run every possible way: 12.9 s for a 2,492-byte reason.) No length cap:
264// the grammar itself admits at most 105 characters, so a cap could not change a result.
265const TOO_LARGE_HEAD = 'artifacts_git_receive_pack_request_too_large: push is ';
266const TOO_LARGE_MID = ' MiB, limit is ';
267const TOO_LARGE_TAIL = ' MiB';
268// At most 9 integer digits and 6 decimals: under 10^9 MiB, about 2^50 bytes, so the byte count is always a safe
269// integer (999999999.999999 MiB = 1,048,575,999,999,999 bytes, under 2^53) and needs no check of its own.
270const MIB_FIGURE = /^[0-9]{1,9}$|^[0-9]{1,9}[.][0-9]{1,6}$/u;
271// oxlint-disable-next-line no-magic-numbers -- 2^10; MIB is 2^20, converting Artifacts' MiB figures to bytes
272const KIB = 1024;
273const MIB = KIB * KIB;
274// One figure in bytes, or null: not a decimal figure, or not a positive exact byte count.
275const mibBytes = (figure: string): number | null => {
276 if (!MIB_FIGURE.test(figure)) return null;
277 const bytes = Math.round(Number(figure) * MIB);
278 return bytes > 0 ? bytes : null;
279};
280// With no middle, indexOf is -1 and the first slice stops one short of the end: it is empty or ends in the tail's
281// 'i', never a figure, so that case needs no branch. The head holds no ' MiB', so the search starts at 0.
282export const parseReceivePackTooLarge = (reason: string): { readonly got: number; readonly max: number } | null => {
283 if (!reason.startsWith(TOO_LARGE_HEAD) || !reason.endsWith(TOO_LARGE_TAIL)) return null;
284 const mid = reason.indexOf(TOO_LARGE_MID);
285 const got = mibBytes(reason.slice(TOO_LARGE_HEAD.length, mid));
286 const max = mibBytes(reason.slice(mid + TOO_LARGE_MID.length, reason.length - TOO_LARGE_TAIL.length));
287 return got === null || max === null ? null : { got, max };
288};
289const malformed = (why: string): Malformed => ({ tag: 'malformed', why });
290// Stryker disable next-line ConditionalExpression,EqualityOperator,ArrayDeclaration: reportStep calls it on "ng <rest>" only; with no space or a leading one, every split names no commanded ref
291const splitOnce = (s: string, sep: string): readonly [string, string] => { const i = s.indexOf(sep); return i < 0 ? [s, ''] : [s.slice(0, i), s.slice(i + sep.length)]; };
292export const reportInit = (commands: ReadonlyArray<{ readonly ref: string }>): ReportState => ({ tag: 'unpack', want: new Set(commands.map(c => c.ref)) });
293// `seen` grows in place, as the stream's `lines` do: a state is not reused once stepped.
294// @decoder reportStep prefix=report
295export function reportStep(st: ReportState, payload: Uint8Array): ReportState {
296 if (st.tag === 'malformed') return st;
297 // A ref name is bytes (check_refname_format refuses only control bytes, space, ~ ^ : ? * [ and backslash, `..`, `@{` and the
298 // dot/slash/.lock rules; any byte >= 0x80 is legal), and receive-pack echoes it as it got it. decodeBytes maps it to
299 // the string the command was built from (encodeBytes is its inverse), so `ok <ref>` matches its command (#43).
300 const l: string = decodeBytes(payload);
301 const line = l.slice(0, l.length - 1);
302 if (!l.endsWith('\n') || line.includes('\n')) return malformed('a line is not one LF-terminated line');
303 switch (st.tag) {
304 case 'unpack': {
305 // '' (no unpack line) is neither "ok" nor a failure. A printable status that is neither "ok" nor one of git's
306 // failures may still be a host's echoed failure (reportFinish decides, from the ref lines).
307 const unpack = line.startsWith(UNPACK) ? line.slice(UNPACK.length) : '';
308 return unpack === 'ok' || isGitUnpackError(unpack) || PRINTABLE.test(unpack) ? { tag: 'refs', unpack, want: st.want, seen: new Map() } : malformed('no git unpack line first');
309 }
310 case 'refs': {
311 const isOk = line.startsWith(OK_REF);
312 if (!isOk && !line.startsWith(NG_REF)) return malformed('a line is not a ref status');
313 // validateRef forbids spaces in a ref, so the first space after "ng <ref>" ends the ref name
314 const rest = line.slice(OK_REF.length);
315 const [ref, reason] = isOk ? [rest, ''] : splitOnce(rest, ' ');
316 if (!st.want.has(ref)) return malformed('status for a ref not commanded');
317 if (st.seen.has(ref)) return malformed(`two statuses for ${ref}`);
318 if (isOk) st.seen.set(ref, { ref, ok: true, reason: '' });
319 else if (PRINTABLE.test(reason)) st.seen.set(ref, { ref, ok: false, reason });
320 else return malformed(`no readable reason for ${ref}`);
321 return st;
322 }
323 }
324 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
325 return assertNever(st);
327export function reportFinish(st: ReportState): ReportShape {
328 switch (st.tag) {
329 case 'malformed': return st;
330 case 'unpack': return malformed('no git unpack line first');
331 case 'refs': {
332 const complete = [...st.want].every(ref => st.seen.has(ref));
333 const refs = [...st.seen.values()];
334 // neither "ok" nor git's: definite only as a host's echoed failure over every commanded ref
335 if (st.unpack !== 'ok' && !isGitUnpackError(st.unpack)) return complete && echoedFailure(st.unpack, refs) ? { tag: 'unpackFailed', status: st.unpack, refs } : malformed('no git unpack line first');
336 for (const ref of st.want) if (!st.seen.has(ref)) return malformed(`no status for ${ref}`);
337 if (st.unpack !== 'ok') return refs.every(r => !r.ok && r.reason === UNPACKER_ERROR) || echoedFailure(st.unpack, refs) ? { tag: 'unpackFailed', status: st.unpack, refs } : malformed('unpack failed, a ref is not "unpacker error"');
338 if (refs.some(r => !r.ok && r.reason === UNPACKER_ERROR)) return malformed('"unpacker error" beside "unpack ok"');
339 return { tag: 'statuses', refs };
340 }
341 }
342 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
343 return assertNever(st);
345// The driver: the report's pkt payloads (StreamReport.lines) against the commands sent.
346// @decoder classifyReport prefix=report
347export function classifyReport(payloads: readonly Uint8Array[], commands: ReadonlyArray<{ readonly ref: string }>): ReportShape {
348 let st = reportInit(commands);
349 for (const p of payloads) st = reportStep(st, p);
350 return reportFinish(st);
353// The class of one ng reason. git v2.50.0 receive-pack's own reasons are a table, each justified by what a caller can
354// safely do next and judged by real git: test/space/push-ng.space.js (every reason × command × atomic × refs; SPACE.md).
355// cas the ref is not where the command said (stale old oid, create over an existing ref, a held lock): fresh retry
356// nff receive.denyNonFastForwards, and the new commit does not descend from the command's own old oid
357// ambiguous a proc-receive hook was handed the command and did not answer for it: it may have acted
358// innocent 'atomic push failure', an atomic push's other members: the culprit's class decides
359// rejected a refusal: resending the same request is refused again
360// git >= 2.51 reports a non-atomic ref's failed update by cause (refs.c ref_transaction_error_msg): a stale old oid, a
361// create over an existing ref and a ref deleted since the read are cas; 'refname conflict' (D/F) and the rest refuse.
362// Every other git reason is a refusal (push_rejected). A reason git does not write is another host's: 'stale ref' is
363// Cloudflare Artifacts' only ref-update rejection (stale old oid, create over an existing ref, stale delete, and the
364// innocent members of a multi-ref push, which it always treats as atomic; observed 2026-10-23, SAFETY.md I31).
365export type NgClass = 'cas' | 'nff' | 'innocent' | 'ambiguous' | 'rejected';
366const KNOWN_NG = [
367 'failed to update ref', 'atomic transaction failed', 'bad ref', 'incorrect old value provided', 'reference already exists', 'reference does not exist',
368 'non-fast-forward', 'atomic push failure', 'proc-receive failed to report status', 'fail to run proc-receive hook',
369] as const;
370type KnownNgReason = typeof KNOWN_NG[number];
371const knownNgClass = (reason: KnownNgReason): NgClass => {
372 switch (reason) {
373 case 'failed to update ref':
374 case 'atomic transaction failed':
375 case 'bad ref':
376 case 'incorrect old value provided':
377 case 'reference already exists':
378 case 'reference does not exist':
379 return 'cas';
380 case 'non-fast-forward': return 'nff';
381 case 'atomic push failure': return 'innocent';
382 case 'proc-receive failed to report status':
383 case 'fail to run proc-receive hook':
384 return 'ambiguous';
385 }
386 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
387 return assertNever(reason);
388};
389const HOST_CAS = /^(failed to lock|stale ref)$|fetch first|non-fast-forward|already exists/u;
390export const ngClass = (reason: string): NgClass => {
391 for (const known of KNOWN_NG) if (known === reason) return knownNgClass(known);
392 return HOST_CAS.test(reason) ? 'cas' : 'rejected';
393};
395// 3. The outcome. An exhaustive match on the report shape; 'ambiguous' is the only fallthrough. A refused ref carries
396// its reason and the reason's class. Every ref refused is a rejection whose code is the classes' verdict: a refusal
397// anywhere wins (push_rejected), then a non-fast-forward, then a lost compare-and-swap; 'innocent' members alone refuse.
398// { tag: 'landed' } | { tag: 'rejected', code, refs } | { tag: 'partial', landed, rejected } | { tag: 'ambiguous', why }
399export type Refused = { readonly ref: string; readonly reason: string; readonly cls: NgClass };
400export type RejectionCode = 'push_rejected' | 'not_fast_forward' | 'cas_conflict' | 'limit_exceeded';
401export type Outcome =
402 | { readonly tag: 'landed' }
403 | { readonly tag: 'rejected'; readonly code: RejectionCode; readonly refs: readonly Refused[] }
404 | { readonly tag: 'partial'; readonly landed: readonly string[]; readonly rejected: readonly Refused[] }
405 | { readonly tag: 'ambiguous'; readonly why: string };
406const refused = (refs: readonly RefStatus[]): Refused[] => refs.flatMap(r => (r.ok ? [] : [{ ref: r.ref, reason: r.reason, cls: ngClass(r.reason) }]));
407// every ref refused, none ambiguous: which rejection
408export const rejectionCode = (ng: readonly Refused[]): RejectionCode => {
409 if (ng.length > 0) {
410 let tooLarge = true;
411 for (const r of ng) if (parseReceivePackTooLarge(r.reason) === null) { tooLarge = false; break; }
412 if (tooLarge) return 'limit_exceeded';
413 }
414 const cls = new Set(ng.map(r => r.cls));
415 if (cls.has('rejected')) return 'push_rejected';
416 if (cls.has('nff')) return 'not_fast_forward';
417 return cls.has('cas') ? 'cas_conflict' : 'push_rejected';
418};
419// atomic: the push asked for all-or-nothing (default no); pack: a pack was sent (default yes)
420export type DecideOptions = Input<{ readonly atomic: boolean; readonly pack: boolean }>;
421export function decideOutcome(shape: ReportShape | Broken, { atomic = false, pack = true }: DecideOptions = {}): Outcome {
422 switch (shape.tag) {
423 // receive-pack writes an unpack failure only after reading a pack (delete_only() skips unpack)
424 case 'unpackFailed': {
425 if (!pack) return { tag: 'ambiguous', why: 'unpack failed but no pack was sent' };
426 const refs = refused(shape.refs);
427 // a host body-cap unpack is limit_exceeded; every other unpack failure stays push_rejected (the refs may
428 // carry an unrelated reason in a test shape; the unpack itself is the refusal)
429 let tooLarge = refs.length > 0;
430 for (const r of refs) if (parseReceivePackTooLarge(r.reason) === null) { tooLarge = false; break; }
431 return { tag: 'rejected', code: tooLarge ? 'limit_exceeded' : 'push_rejected', refs };
432 }
433 case 'statuses': {
434 const ng = refused(shape.refs);
435 if (ng.length === 0) return { tag: 'landed' };
436 // a proc-receive hook took the command and did not answer for it: it may have acted (test/space/push-ng.space.js)
437 const amb = fromNullish(ng.find(r => r.cls === 'ambiguous'));
438 if (amb.tag === 'some') return { tag: 'ambiguous', why: `proc-receive: ${amb.value.reason}` };
439 if (ng.length === shape.refs.length) return { tag: 'rejected', code: rejectionCode(ng), refs: ng };
440 // atomic: all or none. A split is git-shaped only for refs refused before the transaction (hidden refs, observed);
441 // ply does not claim a partial outcome for a push the caller made atomic (SPACE.md).
442 if (atomic) return { tag: 'ambiguous', why: 'atomic push split: some refs ok, some ng' };
443 return { tag: 'partial', landed: shape.refs.filter(r => r.ok).map(r => r.ref), rejected: ng };
444 }
445 case 'malformed':
446 case 'broken': return { tag: 'ambiguous', why: shape.why };
447 }
448 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
449 return assertNever(shape);
452// The report as classified (one parser: classifyReport), for the caller and the span: null when it was not git's.
453export type PushReport = Exclude<ReportShape, Malformed>;
455// 4. The Result. 'landed' is Ok; every other outcome is the PlyError a caller matches on, carrying the report and
456// band 2. A rejection's message names the first refused ref's reason (git's report order; an unpack failure's refs
457// are all "unpacker error", and there is at least one command).
458export type PushError = ErrorOf<RejectionCode | 'push_partial' | 'ambiguous'>;
459// remote: band 3's message when the stream broke on one, else null (a JS caller's missing value reads as null).
460export type OutcomeContext = { readonly report: PushReport | null; readonly hookOutput: string; readonly remote: string | null; readonly commands: readonly Command[] };
461// scrub: the transport's credential scrubber (or null), applied to band 3's text before it is cut (errors.ts remoteText).
462export function outcomeResult(o: Outcome, { report, hookOutput, remote, commands }: OutcomeContext, scrub: Scrub | null = null): Result<PushReport | null, PushError> {
463 const extra = { report, hookOutput };
464 switch (o.tag) {
465 case 'landed': return ok(report);
466 case 'rejected': {
467 const reason = getOrElse(mapOption(at(o.refs, 0), r => r.reason), '');
468 if (o.code === 'limit_exceeded') {
469 const sizes = parseReceivePackTooLarge(reason);
470 // rejectionCode only returns limit_exceeded when every ng reason parsed
471 const got = sizes === null ? 0 : sizes.got;
472 const max = sizes === null ? 0 : sizes.max;
473 return fail('limit_exceeded', `push is too large: ${remoteText(reason)}`, { ...extra, what: 'receive-pack request', got, max });
474 }
475 const message = `push rejected: ${reason}`;
476 if (o.code !== 'cas_conflict') return fail(o.code, message, extra);
477 // what the culprit's command said the ref was (null: absent); receive-pack does not say where it is (actual: null)
478 const culprit = fromNullish(o.refs.find(r => r.cls === 'cas'));
479 const old = flatMapOption(culprit, x => mapOption(fromNullish(commands.find(c => c.ref === x.ref)), c => c.oldOid));
480 return fail('cas_conflict', message, { ...extra, expected: old.tag === 'none' || old.value === ZERO_OID ? null : old.value, actual: null });
481 }
482 case 'partial': return fail('push_partial', `push partially applied: ${o.landed.join(', ')} updated; ${o.rejected.map(r => `${r.ref} (${r.reason})`).join(', ')} refused`, { ...extra, landed: o.landed, rejected: o.rejected });
483 case 'ambiguous': {
484 const said = fromNullish(remote);
485 return fail('ambiguous', `push outcome unknown: ${said.tag === 'none' ? '' : `remote: ${remoteText(said.value, REMOTE_TEXT_MAX, scrub)}: `}${o.why}`, said.tag === 'none' ? extra : { ...extra, original: 'remote_error' });
486 }
487 }
488 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
489 return assertNever(o);
491const bandLines = (text: string): string[] => text.split(/\r?\n|\r/u).map(l => l.trim()).filter(Boolean).slice(-REPORT_KEEP);
493// The transport surface push reads (http.ts and test doubles provide more).
494export type PushSpan = {
495 set(attrs: Readonly<Record<string, unknown>>): unknown;
496 event(name: string, attrs: Readonly<Record<string, unknown>>): unknown;
497};
498export type PushTransport = Transport;
499// One object for buildPack: { type, data, base } (pack.ts PackInput; a left-out base is none).
500export type PackObject = PackInput;
501export type PackEntry = BuiltEntry;
502// Single-ref form { ref, oldOid, newOid, objects } or multi-ref { commands: [...], objects }. Options:
503// sideband (default on): side-band-64k — the server's human-readable explanation of a rejection (hook stderr, GitHub's
504// GH006 text) arrives on band 2 and is recorded as git.push.remote.messages. Every receive-pack since 1.7 has it.
505// reportV2: report-status-v2 (per-ref option lines).
506// checked: atomic (all-or-nothing) and push options, as checked against the server's advertisement (receivecaps.ts
507// checkPushCaps; pushWithOptions and GitHttp.push do it).
508// commands null: the single-ref form, ref/oldOid/newOid (each refused by planPush when left out).
509export type PushConfig = {
510 readonly ref: string | null;
511 readonly oldOid: string;
512 readonly newOid: string;
513 readonly objects: readonly PackObject[];
514 readonly commands: Commands | null;
515 readonly sideband: boolean;
516 readonly reportV2: boolean;
517 readonly checked: CheckedCaps | null;
518};
519export type PushOptions = Input<PushConfig>;
520const pushDefaults = (): { -readonly [K in keyof PushConfig]: PushConfig[K] } => ({ ref: null, oldOid: '', newOid: '', objects: [], commands: null, sideband: true, reportV2: false, checked: null });
521export type PushResult = { readonly report: PushReport | null; readonly packBytes: number; readonly entries: readonly PackEntry[]; readonly hookOutput: string };
523// The request, planned before anything is built or sent (pure): every refusal here happens with nothing on the wire.
524export type PushPlan = { readonly commands: ParsedCommands; readonly caps: readonly string[]; readonly checked: CheckedCaps | null; readonly pushOptions: readonly WireField[]; readonly needPack: boolean; readonly maxReportLines: number; readonly maxReportReason: number; readonly maxReportProgress: number; readonly maxPack: number; readonly objects: readonly PackObject[]; readonly sideband: boolean };
525// The capabilities a push asks for; atomic and push-options only from a CheckedCaps.
526export type PushRequestCap = 'report-status' | 'report-status-v2' | 'side-band-64k' | 'atomic' | 'delete-refs' | 'push-options';
527const requestCap = (cap: PushRequestCap): PushRequestCap => {
528 switch (cap) {
529 case 'report-status':
530 case 'report-status-v2':
531 case 'side-band-64k':
532 case 'atomic':
533 case 'delete-refs':
534 case 'push-options':
535 return cap;
536 }
537 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
538 return assertNever(cap);
539};
540export const requestCaps = (commands: readonly Command[], { sideband = true, reportV2 = false }: Input<{ readonly sideband: boolean; readonly reportV2: boolean }>, checked: CheckedCaps | null = null): string[] =>
541 [reportV2 ? requestCap('report-status-v2') : requestCap('report-status'), ...(sideband ? [requestCap('side-band-64k')] : []), ...(checked !== null && checked.atomic ? [requestCap('atomic')] : []), ...(commands.some(c => c.newOid === ZERO_OID) ? [requestCap('delete-refs')] : []), ...(checked !== null && checked.pushOptions.length > 0 ? [requestCap('push-options')] : []), `agent=${UA.replace(/ .*/u, '')}`];
542// An untyped (JS) caller's atomic / pushOptions, which the type no longer has: refused rather than silently dropped.
543const unchecked = (o: unknown): boolean => {
544 const atomic = field(o, 'atomic');
545 const options = flatMapOption(field(o, 'pushOptions'), p => field(p, 'length'));
546 return (atomic.tag === 'some' && atomic.value === true) || (options.tag === 'some' && Number(options.value) > 0);
547};
548// Each object's base, checked before anything is built (pack.ts buildPack checks none): an OFS_DELTA's is an earlier
549// object of the same pack, a REF_DELTA's an object id. A JavaScript caller's base outside the three tags, or the flag
550// fields the tagged base replaced (baseIndex, baseOid), is refused rather than ignored: a delta sent as a whole object
551// would be a corrupt pack.
552function checkBases(objects: readonly PackObject[]): Result<null, ErrorOf<'bad_request'>> {
553 for (const [i, obj] of objects.entries()) {
554 const base = getOrElse<unknown>(field(obj, 'base'), WHOLE);
555 const tag = getOrElse<unknown>(field(base, 'tag'), null);
556 const flags = field(obj, 'baseIndex').tag === 'some' || field(obj, 'baseOid').tag === 'some';
557 if (flags || (tag !== 'none' && tag !== 'ofs' && tag !== 'ref')) return fail('bad_request', "push: an object's base is { tag: 'none' }, { tag: 'ofs', index } or { tag: 'ref', oid }", { what: 'base', got: flags ? 'baseIndex/baseOid' : tag });
558 const index = getOrElse<unknown>(field(base, 'index'), null);
559 if (tag === 'ofs' && !(typeof index === 'number' && Number.isInteger(index) && index >= 0 && index < i)) return fail('bad_request', 'push: an ofs base must name an earlier object', { what: 'base', got: index });
560 if (tag === 'ref' && !parseOid(getOrElse<unknown>(field(base, 'oid'), null)).ok) return fail('bad_request', 'push: a ref base must be an object id', { what: 'base', got: getOrElse<unknown>(field(base, 'oid'), null) });
561 }
562 return ok(null);
564// Each object once: the one place every producer's list passes (commitChanges, pushTree, merge, rebase, editFile, a
565// caller's own). A pack that holds one object twice is refused by a strict receiver: git index-pack --strict says
566// "The same object <oid> appears twice in the pack", unpack-objects --strict "tried to add buffer twice!", and
567// receive-pack reports either as "unpacker error" (git 2.50). Two whole objects are one object when type and bytes
568// are equal, so only objects that share a type, a length and a fingerprint (below) with another are hashed, each at
569// most once, and two are one object when their ids are equal; a list with no such pair costs a fingerprint (at most
570// 256 bytes read) and a map insert per object and no SHA-1. The first of a pair is kept, in its place, and an
571// ofs base index is renumbered to the kept list (a base that was a repeat becomes the kept copy, which is earlier).
572// A delta entry is kept as given: its object id is not known without applying it. Runs in send, on a list planPush
573// passed (checkBases), before the pack is measured.
574// FNV-1a (32 bits) over at most FINGERPRINT_RUNS runs of FINGERPRINT_RUN bytes, evenly spaced from the first run to
575// the last: every byte of an object no longer than that. Runs, not single bytes at a stride: data with a period (a
576// record layout, a generator's low byte) is the same at every stride and differs inside a run. Equal bytes give equal
577// fingerprints; it decides only which objects are hashed, never which are equal.
578const FINGERPRINT_RUNS = 32;
579const FINGERPRINT_RUN = 8;
580const FNV_OFFSET = 0x81_1c_9d_c5;
581const FNV_PRIME = 0x01_00_01_93;
582const fingerprint = (data: Uint8Array): number => {
583 const whole = data.length <= FINGERPRINT_RUNS * FINGERPRINT_RUN;
584 const runs = whole ? 1 : FINGERPRINT_RUNS;
585 const run = whole ? data.length : FINGERPRINT_RUN;
586 // the last run ends at the object's end
587 const spread = (data.length - run) / Math.max(1, runs - 1);
588 let h = FNV_OFFSET;
589 for (let r = 0; r < runs; r++) {
590 const start = Math.floor(r * spread);
591 // oxlint-disable-next-line typescript/no-unsafe-type-assertion, typescript/non-nullable-type-assertion-style -- start + run <= data.length: the read is in range (`as`, not the `!` src/ forbids)
592 for (let i = start; i < start + run; i++) h = Math.imul(h ^ (data[i] as number), FNV_PRIME);
593 }
594 return h >>> 0;
595};
596function oncePerObject(objects: readonly PackObject[]): readonly PackObject[] {
597 const buckets = new Map<string, { readonly first: number; byOid: Map<string, number> | null }>();
598 const out: PackObject[] = [];
599 const keptAt: number[] = [];
600 for (const [i, obj] of objects.entries()) {
601 const base = inputBase(obj);
602 const name = typeNameOf(obj.type);
603 if (base.tag !== 'none' || name === null || !(obj.data instanceof Uint8Array)) {
604 keptAt.push(out.length);
605 out.push(base.tag === 'ofs' && out.length !== i ? { ...obj, base: { tag: 'ofs', index: atOr(keptAt, base.index, base.index) } } : obj);
606 continue;
607 }
608 const key = `${obj.type}:${obj.data.length}:${fingerprint(obj.data)}`;
609 const bucket = mapGet(buckets, key);
610 if (bucket.tag === 'none') {
611 buckets.set(key, { first: out.length, byOid: null });
612 keptAt.push(out.length);
613 out.push(obj);
614 continue;
615 }
616 const held = bucket.value;
617 const firstObj = at(out, held.first);
618 const byOid = held.byOid === null ? new Map<string, number>(firstObj.tag === 'some' ? [[hashObject(name, firstObj.value.data), held.first]] : []) : held.byOid;
619 held.byOid = byOid;
620 const oid = hashObject(name, obj.data);
621 const seen = mapGet(byOid, oid);
622 if (seen.tag === 'some') { keptAt.push(seen.value); continue; }
623 byOid.set(oid, out.length);
624 keptAt.push(out.length);
625 out.push(obj);
626 }
627 return out.length === objects.length ? objects : out;
629// limits: the transport's (checked), or a caller's record (any subset, a key left out is the default; null is the defaults).
630export function planPush(o: PushOptions, limits: LimitsInput | null): Result<PushPlan, PlyError> {
631 const checkedLimits = parseLimits(limits);
632 if (!checkedLimits.ok) return checkedLimits;
633 const { maxRefs, maxReportLines, maxReportReasonBytes, maxReportProgressBytes, maxPackBytes } = checkedLimits.value;
634 const cfg = withDefaults(o, pushDefaults());
635 if (cfg.checked === null && unchecked(o)) return fail('bad_request', 'push: unchecked atomic or push options');
636 // the single-ref form's fields may be missing (null ref, '' oids): parseCommand refuses them as it refuses any other
637 const raw: readonly RawCommand[] = cfg.commands === null ? [{ ref: cfg.ref, oldOid: cfg.oldOid, newOid: cfg.newOid }] : cfg.commands;
638 if (raw.length > maxRefs) return err(limitExceeded('push commands', raw.length, maxRefs));
639 const parsed = parseEach(raw);
640 if (!parsed.ok) return parsed;
641 const bases = checkBases(cfg.objects);
642 if (!bases.ok) return bases;
643 // each option parsed once into the plan; the request body writes the parsed ones
644 const pushOptions: WireField[] = [];
645 for (const p of cfg.checked === null ? [] : cfg.checked.pushOptions) {
646 const option = validateWire(p, 'push option');
647 if (!option.ok) return option;
648 pushOptions.push(option.value);
649 }
650 // last, as before: every other refusal comes first for an empty list
651 const listed = nonEmpty(parsed.value);
652 if (!listed.ok) return listed;
653 const commands = listed.value;
654 return ok({ commands, caps: requestCaps(commands, cfg, cfg.checked), checked: cfg.checked, pushOptions, needPack: commands.some(c => c.newOid !== ZERO_OID), maxReportLines, maxReportReason: maxReportReasonBytes, maxReportProgress: maxReportProgressBytes, maxPack: maxPackBytes, objects: cfg.objects, sideband: cfg.sideband });
656// The request body: commands, flush, then (push-options) the options and another flush, then the pack.
657const requestBody = (plan: PushPlan, pack: Uint8Array | null): Result<Uint8Array<ArrayBuffer>, ErrorOf<'bad_request'>> => {
658 const options = plan.pushOptions;
659 if (options.length === 0) return pushBody(plan, pack);
660 const head = pushBody(plan);
661 if (!head.ok) return head;
662 const framed = pkts(options.map(p => `${p}\n`));
663 return framed.ok ? ok(concat([head.value, ...framed.value, FLUSH, ...(pack ? [pack] : [])])) : framed;
664};
666// The report's line cap: limits.maxReportLines, but never fewer lines than git sends for the commands pushed (one unpack
667// line, then one status per command; report-status-v2 adds up to four option lines a ref: refname, old-oid, new-oid,
668// forced-update), so a push maxRefs allows is never cut off by its own honest report (#144: maxRefs commands read
669// maxRefs + 1 lines). A larger cap is for a proc-receive hook that reports one command as several refs.
670export const REPORT_V2_OPTION_LINES = 4;
671const honestReportLines = (plan: Pick<PushPlan, 'commands' | 'caps'>): number => 1 + plan.commands.length * (plan.caps.includes('report-status-v2') ? 1 + REPORT_V2_OPTION_LINES : 1);
672export const reportLineCap = (plan: Pick<PushPlan, 'maxReportLines' | 'commands' | 'caps'>): number =>
673 Math.max(plan.maxReportLines, honestReportLines(plan));
674// The bytes kept of one reason: limits.maxReportReasonBytes, but never fewer than git's own longest status or reason, so
675// a reason git writes is never cut and its class (ngClass, isGitUnpackError) is read from the whole of it.
676const GIT_REASON_BYTES = Math.max(...[...GIT_UNPACK_ERROR_LIST, ...KNOWN_NG, UNPACKER_ERROR].map(s => s.length));
677export const reportReasonCap = (plan: Pick<PushPlan, 'maxReportReason'>): number => Math.max(plan.maxReportReason, GIT_REASON_BYTES);
678// One report line with its reason ("ng <ref> <reason>") or status ("unpack <status>") cut to its first `max` bytes. A cap
679// bounds what is kept, never the outcome: the line is cut only when it is one reportStep reads whole (it ends in LF and
680// the reason is printable ASCII to its end, so a character is a byte), and any other line is returned as it came, for
681// reportStep to refuse as it always did. The copy drops the frame the line arrived in.
682export const cutReportLine = (line: Uint8Array, max: number): Uint8Array => {
683 if (line.length - NG_REF.length - 1 <= max) return line;
684 const text = decodeBytes(line);
685 let start = 0;
686 if (text.startsWith(UNPACK)) start = UNPACK.length;
687 else if (text.startsWith(NG_REF)) start = text.indexOf(' ', NG_REF.length) + 1;
688 const reason = text.slice(start, text.length - 1);
689 if (start === 0 || reason.length <= max || !text.endsWith('\n') || !PRINTABLE.test(reason)) return line;
690 return concat([line.subarray(0, line.length - 1 - reason.length + max), line.subarray(line.length - 1)]);
691};
692// The reason of an "ng <ref> <reason>" line as it came, before any cut (reportStep's split: a ref holds no space).
693const wholeReason = (line: Uint8Array): string => {
694 const text = decodeBytes(line);
695 return text.slice(text.indexOf(' ', NG_REF.length) + 1, text.length - 1);
696};
697// The report as the read classifies it: reportStep's state, the unpack status whole (at most one pkt-line, held for this
698// read only), whether it was cut, and whether a line beside a cut is not that status repeated.
699type Classifying = { report: ReportState; status: string; statusCut: boolean; cutNoEcho: boolean };
700// Classifies lines[from..] once, where they lie: only a line over the cap is replaced, by its cut copy. The echo
701// (echoedFailure) is read from the whole lines, before the cut: where the unpack status or a ref's reason is cut,
702// anything but the status repeated whole is no unpack failure, however the kept parts compare.
703function classifyNew(c: Classifying, lines: Uint8Array[], from: number, max: number): void {
704 let { report } = c;
705 for (let i = from; i < lines.length; i += 1) {
706 const whole = lines[i];
707 // Stryker disable next-line ConditionalExpression: unreachable, i < lines.length
708 if (isMissing(whole)) break;
709 const line = cutReportLine(whole, max);
710 if (i === 0) {
711 const text = decodeBytes(whole);
712 c.status = text.slice(UNPACK.length, text.length - 1);
713 c.statusCut = line !== whole;
714 } else if ((c.statusCut || line !== whole) && wholeReason(whole) !== c.status) c.cutNoEcho = true;
715 if (line !== whole) lines[i] = line;
716 report = reportStep(report, line);
717 }
718 c.report = report;
720// An unpack failure read only because a cut made two different lines agree is none: whole, that report is not git's.
721const classified = (c: Classifying): ReportShape => {
722 const shape = reportFinish(c.report);
723 return c.cutNoEcho && shape.tag === 'unpackFailed' ? malformed('no git unpack line first') : shape;
724};
725// A band-2 frame past limits.maxReportProgressBytes, as the stream reads it: its place in the answer, none of its text.
726const PROGRESS_DROPPED: Frame = { kind: 'data', payload: Uint8Array.of(SIDEBAND_PROGRESS) };
728// The read, the platform edge: whatever the transport throws (network, HTTP status, framing) and our own limits on the
729// response end the read as `lost`; the stream otherwise ends as a report or broken. `reading` is the last reading state.
730// `answered`: a frame of receive-pack's answer was read before the failure (false: the exchange failed at its status line).
731// `shape`: the report as the read classified it, line by line (decide() does not classify it again).
732type Read = { readonly done: Broken | StreamReport; readonly shape: ReportShape | Broken; readonly reading: Reading } | { readonly cause: unknown; readonly answered: boolean };
733// An HTTP refusal of the receive-pack request itself (401/403: receive-pack disabled or not for this credential; 404: no
734// such repository), seen before any frame of its answer. git's http-backend decides that at the status line, before it
735// runs receive-pack (http.receivepack false is a 403), but the request body was sent, and a middlebox that forwarded
736// it and rewrote the status would look the same. So the refusal stands only when the service refuses its advertisement
737// (GET info/refs?service=git-receive-pack) with the same code: then receive-pack is not there for this caller and the
738// ref did not move, and the push is that error, not 'ambiguous' (#144). Anything else stays 'ambiguous'.
739const NOT_RUN: ReadonlySet<unknown> = new Set(['auth', 'not_found']);
740const codeOf = (e: unknown): unknown => getOrElse(field(e, 'code'), null);
741export const refusedBeforeReceivePack = (r: { readonly cause: unknown; readonly answered: boolean }): boolean => !r.answered && NOT_RUN.has(codeOf(r.cause));
742async function serviceRefused(t: PushTransport, span: Span, cause: unknown): Promise<boolean> {
743 try {
744 const ad = await t.advertise('git-receive-pack', span);
745 return !ad.ok && ad.error.code === codeOf(cause);
746 } catch { return false; } // a transport that cannot advertise confirms nothing
748async function readResponse(t: PushTransport, plan: PushPlan, body: RequestBody, span: Span, sideband: boolean): Promise<Read> {
749 let reportBytes = 0;
750 let reading = streamInit(sideband);
751 let st: StreamState = reading;
752 let lost: { readonly cause: unknown } | null = null;
753 let answered = false;
754 const maxLines = reportLineCap(plan);
755 // The answer is classified as its lines arrive: the read ends, and leaving the loop cancels the response body, the
756 // moment the report cannot be git's (its first line is not an unpack line, a status for a ref not commanded or
757 // already answered). So what is kept is at most one line a command, its reason cut at reportReasonCap, and band 2's
758 // tail; what is read is held to maxPackBytes (keepalives and band 2 with it) and the transport's timers. A limit here
759 // ends the read only when the report itself cannot be read inside it (report bytes, report lines).
760 const reasonCap = reportReasonCap(plan);
761 let progressBytes = 0;
762 const report: Classifying = { report: reportInit(plan.commands), status: '', statusCut: false, cutNoEcho: false };
763 let unreadable = false;
764 let fed = 0;
765 try {
766 for await (const f of frames(t, 'git-receive-pack', body, span)) {
767 answered = true;
768 const size = f.kind === 'data' ? f.payload.length : 0;
769 reportBytes += size;
770 if (reportBytes > plan.maxPack) { lost = { cause: limitExceeded('report bytes', reportBytes, plan.maxPack) }; break; }
771 let kept = f;
772 if (sideband && f.kind === 'data' && f.payload[0] === SIDEBAND_PROGRESS) {
773 progressBytes += size;
774 if (progressBytes > plan.maxReportProgress) kept = PROGRESS_DROPPED;
775 }
776 const stepped = streamStep(st, kept);
777 if (!stepped.ok) { lost = { cause: stepped.error }; break; }
778 st = stepped.value;
779 // Stryker disable next-line ConditionalExpression: a broken state has no lines, so reading on fails the read: ambiguous either way
780 if (st.tag !== 'reading') break;
781 reading = st;
782 const { lines } = st;
783 if (lines.length > maxLines) { lost = { cause: limitExceeded('report lines', lines.length, maxLines) }; break; }
784 classifyNew(report, lines, fed, reasonCap);
785 fed = lines.length;
786 unreadable = report.report.tag === 'malformed';
787 if (unreadable) break;
788 }
789 } catch (e) { lost = { cause: e }; }
790 if (lost !== null) return { ...lost, answered };
791 // a report that cannot be git's is that report, as far as it was read
792 const done: Broken | StreamReport = unreadable ? { tag: 'report', lines: reading.lines } : streamFinish(st);
793 return { done, shape: done.tag === 'report' ? classified(report) : done, reading };
796// The span's view of the outcome, from the classified report (no second parser).
797const unpackOf = (report: PushReport | null): string => {
798 if (report === null) return '';
799 return report.tag === 'statuses' ? 'ok' : report.status;
800};
801const outcomeAttrs = (done: Broken | StreamReport, report: PushReport | null, outcome: Outcome, band2Frames: number, band2: string): Record<string, unknown> => {
802 const refs = report === null ? [] : report.refs;
803 return {
804 'git.push.report.lines': done.tag === 'report' ? done.lines.slice(0, REPORT_KEEP).map(p => decodeBytes(p).replace(/\n$/u, '')) : [],
805 'git.push.unpack': unpackOf(report), 'git.push.ok': outcome.tag === 'landed', 'git.push.outcome': outcome.tag,
806 'git.push.ng.reason': getOrElse(mapOption(fromNullish(refs.find(x => !x.ok)), x => x.reason), ''), 'git.push.band2.frames': band2Frames, 'git.push.band2.tail': remoteText(band2.slice(-BAND_ATTR), BAND_ATTR),
807 'git.push.remote.messages': bandLines(band2), 'git.push.refs.ok': refs.filter(x => x.ok).length, 'git.push.refs.ng': refs.filter(x => !x.ok).length,
808 };
809};
811// git.object.type for a built entry: its name, or the type id in decimal for an id a caller passed that names no type
812// (pack.ts typeNameOf), so the attribute is never otel.ts's null-as-empty-string.
813const objectTypeAttr = (e: PackEntry): string => getOrElse(fromNullish(e.typeName), String(e.type));
814// The request body: the bytes (no pack, or a pack pass 1 kept), or the commands then pass 2 of the pack as a stream.
815type Body = { readonly body: RequestBody; readonly streamed: StreamedPack | null };
816const bodyOf = (plan: PushPlan, packed: MeasuredPack | null): Result<Body, ErrorOf<'bad_request'>> => {
817 const bytes = requestBody(plan, packed === null ? null : packed.held);
818 if (!bytes.ok || packed === null || packed.held !== null) return bytes.ok ? ok({ body: bytes.value, streamed: null }) : bytes;
819 const streamed = streamPack(packed, bytes.value);
820 return ok({ body: streamed, streamed });
821};
823// After a sideband band-3 report (often empty under Artifacts), a single-ref update can still be named: read the tip.
824// At our newOid → the push landed (report lost). Anywhere else → cas_conflict (lost the CAS / refused).
825// Multi-ref and deletes stay ambiguous: the tip alone does not name which command acted. Observed 2026-11-08 on
826// Cloudflare Artifacts under a same-ref race (phase6 F34): band 3 + empty report → was HTTP 502 `ambiguous`.
827// finishPush gates on isEmptyBand3Ambiguous so non-empty band 3 / cut / drop / verify stay ambiguous.
828async function resolveAmbiguousByTip(t: PushTransport, span: Span, plan: PushPlan, ambiguous: PlyError): Promise<Result<PushReport, PlyError> | null> {
829 if (plan.commands.length !== 1) return null;
830 const [cmd] = plan.commands;
831 if (cmd.newOid === ZERO_OID) return null;
832 const read: Result<LsRefsResult, unknown> = await lsRefs(t, [String(cmd.ref)]).then(r => r, (e: unknown) => err(e));
833 if (!read.ok) {
834 span.set({ 'git.push.ambiguous.resolved': 'unread' });
835 return null;
836 }
837 const tip = mapGet(read.value.refs, String(cmd.ref));
838 const seen = tip.tag === 'some' ? tip.value.oid : null;
839 const landed = seen === cmd.newOid;
840 span.set({ 'git.push.verify.ref': seen === null ? '' : seen, 'git.push.ambiguous.resolved': landed ? 'landed' : 'cas_conflict' });
841 if (landed) {
842 span.set({ 'git.push.ok': true, 'git.push.outcome': 'landed', 'git.push.ng.reason': '' });
843 return ok({ tag: 'statuses', refs: [{ ref: String(cmd.ref), ok: true as const, reason: '' as const }] });
844 }
845 span.set({ 'git.push.ok': false, 'git.push.outcome': 'rejected', 'git.push.ng.reason': 'stale ref' });
846 return fail('cas_conflict', 'push rejected: stale ref', { expected: cmd.oldOid === ZERO_OID ? null : cmd.oldOid, actual: seen, cause: ambiguous, original: 'ambiguous' });
849type FinishPush = {
850 readonly t: PushTransport;
851 readonly span: Span;
852 readonly plan: PushPlan;
853 readonly packBytes: number;
854 readonly entries: readonly PackEntry[];
855 readonly hookOutput: string;
856};
858// Tip read-back is only for empty sideband band 3 (Artifacts race: no report-status lines).
859// Band 3 with a remote message (credential echo, fatal text), cuts, drops, and forged-ok verify
860// stay ambiguous: cas_conflict would trigger edit's one retry and mis-name those outcomes.
861function isEmptyBand3Ambiguous(e: PlyError): boolean {
862 // outcomeResult embeds why as: `push outcome unknown: remote: ${remote}: band 3`
863 // empty remote (Artifacts) → trailing `remote: : band 3`.
864 return e.code === 'ambiguous' && e.message.endsWith('remote: : band 3');
867async function finishPush(ctx: FinishPush, res: Result<PushReport | null, PlyError>): Promise<Result<PushResult, PlyError>> {
868 const { t, span, plan, packBytes, entries, hookOutput } = ctx;
869 if (res.ok) return ok({ report: res.value, packBytes, entries, hookOutput });
870 if (!isEmptyBand3Ambiguous(res.error)) return res;
871 const resolved = await resolveAmbiguousByTip(t, span, plan, res.error);
872 if (resolved === null) return res;
873 if (resolved.ok) return ok({ report: resolved.value, packBytes, entries, hookOutput });
874 return resolved;
877// The answer to a request whose body went out: `cut` is the body's own failure, whatever the server said.
878async function decide(base: FinishPush, r: Read, cut: PlyError | null): Promise<Result<PushResult, PlyError>> {
879 const { t, span, plan } = base;
880 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ambiguousAfterPush of a PlyError is a PlyError
881 if (cut !== null) return finishPush(base, err(ambiguousAfterPush(cut) as PlyError));
882 if ('cause' in r) {
883 const notRun = refusedBeforeReceivePack(r) && await serviceRefused(t, span, r.cause);
884 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- refused: the cause carries one of ply's codes (a PlyError); else ambiguousAfterPush returns one (the cause itself when it already is an 'ambiguous' one)
885 if (notRun) return err(r.cause as PlyError);
886 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ambiguousAfterPush returns a PlyError
887 return finishPush(base, err(ambiguousAfterPush(r.cause) as PlyError));
888 }
889 const { done, shape, reading } = r;
890 const band2 = reading.band2Carry.length > 0 ? (reading.band2 + td.decode(reading.band2Carry)).slice(-BAND_TAIL) : reading.band2;
891 const outcome = decideOutcome(shape, { atomic: plan.checked !== null && plan.checked.atomic, pack: plan.needPack });
892 const report = shape.tag === 'malformed' || shape.tag === 'broken' ? null : shape;
893 span.set(outcomeAttrs(done, report, outcome, reading.band2Frames, band2));
894 if (outcome.tag === 'ambiguous') span.set({ 'git.push.ambiguous': outcome.why });
895 const res = outcomeResult(outcome, { report, hookOutput: band2, remote: shape.tag === 'broken' ? shape.remote : null, commands: plan.commands }, t.scrub);
896 return finishPush({ ...base, hookOutput: band2 }, res);
899// The send, inside the span: measure the pack, refuse an oversized one before the first byte, send, read, decide.
900async function send(t: PushTransport, plan: PushPlan, span: Span): Promise<Result<PushResult, PlyError>> {
901 // each object once (oncePerObject), here and not in planPush: under the span, where an entry that cannot be read is
902 // the push's 'protocol' error as it is when the pack writer reads it
903 const packed = plan.needPack ? await measurePack(oncePerObject(plan.objects)) : null;
904 const entries: readonly PackEntry[] = packed === null ? [] : packed.entries;
905 const packBytes = packed === null ? 0 : packed.bytes;
906 span.set({ 'git.push.pack.bytes': packBytes, 'git.push.pack.objects': entries.length, 'git.push.pack.thin': entries.some(e => Boolean(e.baseOid)), 'git.push.pack.compressed.bytes': entries.reduce((a, e) => a + e.compressed, 0), 'git.push.pack.raw.bytes': entries.reduce((a, e) => a + e.size, 0) });
907 for (const [i, e] of entries.entries()) span.event('git.push.object', { 'git.object.index': i, 'git.object.type': objectTypeAttr(e), 'git.object.size': e.size, 'git.object.compressed': e.compressed, 'git.object.base.oid': getOrElse(fromNullish(e.baseOid), ''), 'git.object.bytes': e.bytes });
908 // Refuse before the first byte is sent: a host with a push cap (Artifacts: 64 MiB of request body) would otherwise take the whole
909 // upload and answer 4xx. The measured size is the pack as pass 1 wrote it, so `got` is what the server would have
910 // received; pass 2 never sends more (packwrite.ts).
911 if (packBytes > plan.maxPack) return err(limitExceeded('push pack bytes', packBytes, plan.maxPack));
912 // The request body (commands + pack) is on the wire from here. Every failure — transport, HTTP status, framing,
913 // band 3, a limit — and every report that is not exactly git's is 'ambiguous': the ref may have moved. The one
914 // exception is the server refusing the service itself (refusedBeforeReceivePack, confirmed by its advertisement).
915 const body = bodyOf(plan, packed);
916 if (!body.ok) return body;
917 // The caller's signal had fired before the request: none is made, so this is the definite 'aborted' (or 'timeout',
918 // by the signal's reason), not 'ambiguous'.
919 const signal = getOrElse<unknown>(field(t, 'signal'), null);
920 if (signal instanceof AbortSignal && signal.aborted) return err(wrapNet(signal.reason, signal));
921 const r = await readResponse(t, plan, body.value.body, span, plan.sideband);
922 // The exchange failed with no answer and the transport never pulled the streamed body: the command list did not
923 // leave this process, so no ref can have moved, and the failure is its own cause, not 'ambiguous'. A body handed
924 // over as bytes cannot be seen leaving or not, so it stays under the rule above.
925 const { streamed } = body.value;
926 if ('cause' in r && !r.answered && streamed !== null && !streamed.pulled()) return err(wrapNet(r.cause, signal instanceof AbortSignal ? signal : null));
927 // pass 2 refused to finish the pack: whatever the server answered (workerd ends an errored body as if it were whole),
928 // it was not sent the pack that was measured
929 const cut = streamed === null ? null : streamed.failure();
930 return decide({ t, span, plan, packBytes, entries, hookOutput: '' }, r, cut);
933// The request under its span (push and pushPackChecked, below, are the entries).
934const receiveSpan = (t: PushTransport, { commands, caps }: PushPlan): SpanOpts => {
935 const [first] = commands;
936 return clientSpan(t, { 'git.command': 'receive-pack', 'git.protocol.version': 0, 'git.push.commands': commands.map(c => `${c.oldOid.slice(0, SHORT_OID)} ${c.newOid.slice(0, SHORT_OID)} ${c.ref}`), 'git.push.caps': caps, 'git.push.ref': first.ref, 'git.push.old': first.oldOid, 'git.push.new': first.newOid });
937};
938// oxlint-disable-next-line eslint/require-await -- async, as push was
939async function receivePack<T>(t: PushTransport, plan: PushPlan, run: (span: Span) => Promise<Result<T, PlyError>>): Promise<Result<T, PlyError>> {
940 // oxlint-disable-next-line typescript/promise-function-async -- the exchange's promise, passed through (an async wrapper adds bytes, not behaviour)
941 return coded('protocol', () => spanned(t, 'git.receive-pack', receiveSpan(t, plan), run));
944// The effect. A refusal before the request (planPush) is an Err with no span; everything after is under the span, whose
945// error is the PlyError the Result carries.
946// oxlint-disable-next-line typescript/promise-function-async -- receivePack's promise, returned as is
947export function push(t: PushTransport, opts: PushOptions): Promise<Result<PushResult, PlyError>> {
948 const plan = planPush(opts, t.limits);
949 if (!plan.ok) return Promise.resolve(plan);
950 // oxlint-disable-next-line typescript/promise-function-async -- send's promise, returned as is
951 return receivePack(t, plan.value, span => send(t, plan.value, span));
954// ---- a pack the caller already has (#234) ----
955// `pack` is a complete pack: header, entries, trailer. It is read once and never retried. A refusal here leaves it
956// unread and unlocked, and so does a request that failed before the transport pulled the body's first chunk (a signal
957// already fired, a connect or DNS failure): that is the failure itself, definite. From the first pull the pack is
958// spent, and every failure is 'ambiguous'.
959// `length` is the pack's own length, without the commands, when the caller knows it (default null). It is checked against
960// maxPackBytes before anything is sent and against the bytes as they go. The request is chunked either way.
961export type PackPushOptions = Input<Omit<PushConfig, 'objects'> & { readonly length: number | null }> & { readonly pack: ReadableStream<Uint8Array> };
962export type PackPushPlan = { readonly plan: PushPlan; readonly pack: ReadableStream<Uint8Array>; readonly length: number | null };
963const isPackLength = (n: unknown): n is number | null => n === null || (typeof n === 'number' && Number.isSafeInteger(n) && n >= 0);
964// Pure: every refusal happens with nothing read and nothing on the wire.
965export function planPackPush(o: PackPushOptions, limits: LimitsInput | null): Result<PackPushPlan, PlyError> {
966 if (field(o, 'objects').tag === 'some') return fail('bad_request', 'pushPack: takes a pack, not objects', { what: 'objects' });
967 const pack = getOrElse<unknown>(field(o, 'pack'), null);
968 if (!(pack instanceof ReadableStream) || pack.locked) return fail('bad_request', 'pushPack: pack must be an unlocked ReadableStream', { what: 'pack' });
969 const planned = planPush(o, limits);
970 if (!planned.ok) return planned;
971 if (!planned.value.needPack) return fail('bad_request', 'pushPack: a push of only deletes sends no pack', { what: 'pack' });
972 const length = getOrElse<unknown>(field(o, 'length'), null);
973 if (!isPackLength(length)) return fail('bad_request', 'pushPack: length must be a non-negative integer', { what: 'length', got: length });
974 if (length !== null && length > planned.value.maxPack) return err(limitExceeded('push pack bytes', length, planned.value.maxPack));
975 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the guard above checked the stream; its chunks are checked as they are read (packwrite.ts streamSource)
976 return ok({ plan: planned.value, pack: pack as ReadableStream<Uint8Array>, length });
978// Whether the push request left this process, beside what it came to (#272): the one fact a PushResult cannot carry.
979// `sent: 'no'` is a refusal before the request, or a request that failed before the transport pulled the body's first
980// chunk (a signal already fired, a connect or DNS failure, an HTTP answer with the body unpulled): receive-pack never
981// got the command list, so no ref can have moved. `sent: 'yes'` is the request and whatever it came to, 'ambiguous'
982// from the first pull. transfer.ts reads this, never the error's code.
983export type PackPushOutcome =
984 | { readonly sent: 'no'; readonly result: Err<PlyError> }
985 | { readonly sent: 'yes'; readonly result: Result<PushResult, PlyError> };
986const unsent = (result: Err<PlyError>): PackPushOutcome => ({ sent: 'no', result });
987async function sendSource(t: PushTransport, p: PackPushPlan, span: Span): Promise<PackPushOutcome> {
988 const { plan } = p;
989 const prefix = requestBody(plan, null);
990 if (!prefix.ok) return unsent(prefix);
991 // The caller's signal had fired before the send: no request is made and the pack is not locked, read or cancelled,
992 // so this is the definite 'aborted' (or 'timeout', by the signal's reason), not 'ambiguous'.
993 const signal = getOrElse<unknown>(field(t, 'signal'), null);
994 if (signal instanceof AbortSignal && signal.aborted) return unsent(err(wrapNet(signal.reason, signal)));
995 const body = streamSource(p.pack, prefix.value, p.length, plan.maxPack);
996 const r = await readResponse(t, plan, body, span, plan.sideband);
997 // The exchange failed with no answer and the transport never pulled the body: the command list did not leave this
998 // process, so no ref can have moved. The failure is its own cause (network, aborted, timeout, or the code of an HTTP
999 // answer that came with the body still unpulled: auth, not_found, rate_limited, upstream_5xx, http, not_git), not 'ambiguous', and
1000 // the pack goes back to the caller unread, unlocked and uncancelled. 'ambiguous' starts at the first pull.
1001 if ('cause' in r && !r.answered && !body.pulled()) {
1002 body.giveBack();
1003 return unsent(err(wrapNet(r.cause, signal instanceof AbortSignal ? signal : null)));
1005 // read before release: abandoning the rest of a pack the server already answered is not a failure of the pack
1006 const cut = body.failure();
1007 await body.release();
1008 const packBytes = body.sent();
1009 const requestBytes = prefix.value.length + packBytes;
1010 span.set({ 'git.push.pack.bytes': packBytes, 'git.request.bytes': requestBytes, 'http.request.body.size': requestBytes });
1011 return { sent: 'yes', result: await decide({ t, span, plan, packBytes, entries: [], hookOutput: '' }, r, cut) };
1013// The effect, for `checked` caps (pushPack in receivecaps.ts reads them from the advertisement), with whether the
1014// request was sent. The span is push's: its error is the Err the outcome carries; a raise (a transport the caller handed
1015// in) is 'protocol' and counts as sent, since nothing says the body was not pulled.
1016export async function pushPackChecked(t: PushTransport, opts: PackPushOptions): Promise<PackPushOutcome> {
1017 const p = planPackPush(opts, t.limits);
1018 if (!p.ok) return unsent(p);
1019 // the outcome's Err is the span's error; receivePack's Err (a raise) is recorded by the tracer
1020 const r = await receivePack(t, p.value.plan, async (span: Span): Promise<Result<PackPushOutcome, PlyError>> => {
1021 const o = await sendSource(t, p.value, span);
1022 if (!o.result.ok) span.error(o.result.error);
1023 return ok(o);
1024 });
1025 return r.ok ? r.value : { sent: 'yes', result: r };
Diagnostics4 git calls · 336 ms
CallStatusSizeTime0336 ms
discover200152 B3 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=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 1020038 KiB · hit7 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=326
git.response.bytes=38434
git.response.cache=HIT
git.response.duration_ms=7
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=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=6
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=38434
git.pkt.payload.max=38339
git.sideband.band1.bytes=38338
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=63
git.pack.bytes=38338
git.pack.ofs_delta=0
git.pack.ref_delta=8
git.pack.chain.max=8
git.pack.trailer=0bc36ab7adf82d3109177f11f1ea93f1ce071f77
git.pack.full=55
Open pack map
fetch20022 KiB326 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=22721
git.response.cache=MISS
git.response.duration_ms=326
git.fetch.wants=845473721407bf7863b2eeed831369d0048bfdc4
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=22721
git.pkt.payload.max=22700
git.sideband.band1.bytes=22699
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.git
Ref
refs/heads/main
Commit
19912563f540228593df0c489082e5e2508e21e4
cf-ray
a5e277144aafd806
Request
e9b1c01b…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format