Artifactspublic-v0

ply

main
ply4 git calls364 ms42 KiB2 cachedprotocol v2
143 lines12 KiBRaw
1// What every operation (edit, merge, rebase, pick) has in common, written once: a root span named `git.<op>` with the
2// operation's attributes, a transport (built for the url, or the caller's — re-parented under the root for its spans),
3// the outcome attribute on success or failure, and the one rule about confirmation: after a push is acknowledged, any
4// failure to read the ref back as expected is `ambiguous`.
5//
6// operation('merge', url, opts, async ({ t, root, outcome }) => { …; return outcome('merge', result, attrs); })
7//
8// The body returns a Result. Ok comes from `outcome(name, result, attrs)`, which stamps `git.<op>.outcome`, ends the
9// span and returns ok(result). An Err stamps the error's code as the outcome, is recorded on the root, carries the root
10// as `span` (a caller links a retry to it) and is returned. operation() itself returns the Result; it never throws.
11import type { ErrorOf, Extra, PlyError } from './errors.js';
12import type { CheckedLimits, LimitsInput } from './limits.js';
13import type { Span } from './otel.js';
14import { Tracer, guardTelemetry } from './otel.js';
15import type { Attrs, Frame, Hints, Quirks, RequestBody, Transport, TransportInput } from './transport.js';
16import type { FetchLike, HttpAuth } from './http.js';
17import { createTransport, redactUrl } from './http.js';
18import { plyMade, transportFrom, withParent } from './transport.js';
19import { lsRefs } from './lsrefs.js';
20import type { LsRefsResult } from './lsrefs.js';
21import { callbackFailed, describeThrown, fail, isPlyError, plyError } from './errors.js';
22import { DEFAULT_LIMITS, parseLimits } from './limits.js';
23import type { Input } from './absent.js';
24import { field, mapGet, withDefaults } from './absent.js';
25import type { Ok, Option, Result } from './result.js';
26import { err, flatMapOption, getOrElse, map, mapOption, ok } from './result.js';
27import { thrownCode, thrownMessage } from './boundary.js';
29// Everything an operation takes besides the url and the body, total. `null` is "none": no credential, no parent span,
30// no abort signal, no caller transport (build one for the url), no retry link, no finishing attributes.
31export type OperationConfig = {
32 readonly auth: HttpAuth | null;
33 readonly parent: Span | null;
34 readonly fetchImpl: FetchLike | null;
35 // any subset (a key left out is the default), parsed once before the transport is made
36 readonly limits: LimitsInput;
37 readonly signal: AbortSignal | null;
38 readonly quirks: Input<Quirks> | null;
39 readonly transport: TransportInput | null;
40 readonly attrs: Attrs;
41 readonly link: { readonly span: Span; readonly kind: string } | null;
42 readonly onFinish: (() => Attrs) | null;
43};
44// What callers pass: any of the config, and the tracer the root span starts on.
45export type OperationOpts = Input<OperationConfig & { readonly tracer: Tracer }>;
46const operationDefaults = (): { -readonly [K in keyof OperationConfig]: OperationConfig[K] } => ({
47 auth: null, parent: null, fetchImpl: null, limits: DEFAULT_LIMITS, signal: null, quirks: null, transport: null, attrs: {}, link: null, onFinish: null,
48});
49// The code an `ambiguous` replaced, when the thrown value had one (no key at all when it had none).
50const originalCode = (e: unknown): Pick<Extra, 'original'> => { const c = thrownCode(e); return c.tag === 'some' ? { original: c.value } : {}; };
51// What operation()'s catch needs of a thrown value, read without throwing: is it a PlyError, and the code it carries.
52// A value that cannot be read (a revoked Proxy, a `code` getter that throws) is not a PlyError and has no code.
53const readThrown = (e: unknown): { readonly known: PlyError | null; readonly original: Pick<Extra, 'original'> } => {
54 try { return { known: isPlyError(e) ? e : null, original: originalCode(e) }; } catch { return { known: null, original: {} }; }
55};
56// The service whose request only reads. The protocol has one other, the push service, and it is named only in the push
57// modules (a read-only bundle carries no push string: test/bundle.test.js). Once a request for any service but this
58// one is handed to a transport, a failure is no longer definite.
59const UPLOAD_PACK = 'git-upload-pack';
60// outcome(kind, result) or outcome(kind, result, attrs): the attributes stamped on the root beside the outcome; ok(result).
61export type Outcome = <R>(kind: string, result: R, ...extra: [] | [Attrs]) => Ok<R>;
62export type OperationBody<R> = (ctx: { readonly t: Transport; readonly root: Span; readonly outcome: Outcome; readonly limits: CheckedLimits }) => Promise<Result<R, PlyError>>;
64export async function operation<R>(op: string, url: string | URL, opts: OperationOpts, body: OperationBody<R>): Promise<Result<R, PlyError>> {
65 // `tracer` is optional (boundary.ts EntryOptions): a caller who passes none gets a Tracer with no exporter, whose spans
66 // are dropped. Anything given that is not a tracer (no start()) is that caller's bug, named in a bad_request.
67 const passed = field(opts, 'tracer');
68 const start = flatMapOption(passed, t => field(t, 'start'));
69 if (passed.tag === 'some' && typeof getOrElse(start, null) !== 'function') return fail('bad_request', `git.${op}: opts.tracer must be a Tracer (new Tracer() from ply)`, { what: 'tracer' });
70 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- checked just above: it has start()
71 const tracer: Tracer = passed.tag === 'some' ? (passed.value as Tracer) : new Tracer();
72 const { auth, parent, fetchImpl, limits, signal, quirks, transport, attrs, link, onFinish } = withDefaults(opts, operationDefaults());
73 const name = `git.${op}`;
74 const root = tracer.start(name, { parent, attrs: { [`${name}.url`]: transport === null ? redactUrl(url) : transport.url, ...attrs } });
75 if (link !== null) root.link(link.span, { 'ply.link': link.kind });
76 // onFinish only adds attributes: what it throws is telemetry's failure (reported to the tracer's onTelemetryError when
77 // it has one), never the operation's. The guard is ply's function, not a method of `tracer`: the check above
78 // guarantees start() and nothing else (a start/span wrapper, a Tracer from another copy of ply).
79 const finish = (extra: Attrs): Span => { if (onFinish !== null) guardTelemetry(tracer, 'onFinish', name, () => { root.set(onFinish()); }); root.set(extra); return root; };
80 const outcome: Outcome = (kind, result, ...extra) => { const [given = {}] = extra; finish({ ...given, [`${name}.outcome`]: kind }).end(); return ok(result); };
81 // An Err leaves through here: the outcome and error.type are its code (read before root.error scrubs it), the error is
82 // recorded on the root, and it carries the root span for a caller's retry link.
83 const failed = (e: PlyError): Result<R, PlyError> => {
84 finish({ [`${name}.outcome`]: e.code }).error(e, e.code).end();
85 Object.assign(e, { span: root });
86 return err(e);
87 };
88 let r: Result<R, PlyError>;
89 let pushHandedOver = false;
90 try {
91 // Inside the try: a transport that cannot be built (a bad URL, an unusable credential) ends the root with the
92 // error recorded, like any other failure, instead of leaving it open and missing from the trace.
93 // The limits, parsed once (#156): a bad one is refused here, before the transport exists or any request is sent.
94 const checked = parseLimits(limits);
95 if (!checked.ok) return failed(checked.error);
96 const made: Result<Transport, PlyError> = transport === null ? createTransport(url, { auth, tracer, parent: root, fetchImpl: fetchImpl === null ? globalThis.fetch : fetchImpl, limits: checked.value, signal, ...(quirks === null ? {} : { quirks }) }) : map(transportFrom(transport), given => withParent(given, root));
97 if (!made.ok) return failed(made.error);
98 // The one fact the catch below needs: was a push request handed to a transport? From that call on the request may
99 // be on the wire (a caller's transport may send before it yields a frame), so a throw is no longer a definite failure.
100 const given = made.value;
101 // frames() is called with the receiver it was called on, not `given`: ply hands each exchange a further view
102 // (withParent(t, span); merge lowers `limits` the same way), and a caller's frames() reads `this.parent` from it.
103 // plyMade: this frames() is ply's own over an already guarded `given`, so an operation handed `t` guards nothing again.
104 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Object.create returns any; a view of `given` (like withParent) whose frames() records the hand-over
105 const t = plyMade(Object.create(given, { frames: { enumerable: true, value: function frames(this: Transport, service: string, sent: RequestBody, span: Span, hints: Hints): AsyncIterable<Frame> {
106 if (service !== UPLOAD_PACK) pushHandedOver = true;
107 return given.frames.call(this, service, sent, span, hints);
108 } } }) as Transport);
109 // The root and every span under it redact the credential; root.error(e) below scrubs the error the caller gets.
110 if (t.scrub !== null) root.scrub = t.scrub;
111 r = await body({ t, root, outcome, limits: checked.value });
112 } catch (e) {
113 // Every ply failure is the body's Err. What still arrives as a throw is not ply's: the caller's own callback (a
114 // transport, a pack cache, any function it passed) raised it. operation() returns a Result all the same (README:
115 // never a throw), with one honest outcome. Once a push request was handed to a transport the ref may have moved:
116 // `ambiguous` (retry: read the ref back), carrying the thrown value as `cause`. Before that nothing was pushed: a
117 // thrown PlyError is that Err, and anything else is bad_request naming 'callback' with the thrown value as `cause`.
118 const { known, original } = readThrown(e);
119 if (pushHandedOver && !(known !== null && known.code === 'ambiguous')) return failed(plyError('ambiguous', `${name}: a caller-supplied callback threw after the push request was handed to the transport, push outcome unknown: ${describeThrown(e)}`, { what: 'callback', cause: e, ...original }));
120 return failed(known === null ? callbackFailed('callback', e) : known);
121 }
122 return r.ok ? r : failed(r.error);
125// After an acknowledged push: read `ref` back and require `expected`. A transport error here, or any other value, is
126// 'ambiguous' — the push may have landed. Records `<prefix>.verify.ref` on `root` (empty when the ref is absent).
127export async function verifyRef(t: Transport, root: Span, prefix: string, ref: string, expected: string): Promise<Result<string, ErrorOf<'ambiguous'>>> {
128 // An Err, or anything a broken transport throws: either is a failed read-back.
129 const read: Result<LsRefsResult, unknown> = await lsRefs(t, [ref]).then(r => r, (e: unknown) => err(e));
130 if (!read.ok) {
131 const e = read.error;
132 // A thrown null has no `.message`: any failure to read the ref back is `ambiguous` (I25), whatever was thrown.
133 const message = String(getOrElse<unknown>(thrownMessage(e), e));
134 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- expected is an ad-hoc error field (errors.ts Extra); A3 moves it into Detail
135 return fail('ambiguous', `push reported ok but the verification read-back failed: ${message}`, { cause: e, ...originalCode(e), expected } as Extra);
136 }
137 const seen: Option<string> = mapOption(mapGet(read.value.refs, ref), r => r.oid);
138 root.set({ [`${prefix}.verify.ref`]: getOrElse(seen, '') });
139 if (seen.tag === 'some' && seen.value === expected) return ok(seen.value);
140 // `seen` is null on the error when the ref is absent, as the wire says it.
141 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ad-hoc error fields (errors.ts Extra); A3 moves them into Detail
142 return fail('ambiguous', `push reported ok but ${ref} is ${getOrElse(seen, 'absent')}, not ${expected}`, { seen: getOrElse<string | null>(seen, null), expected } as Extra);
Diagnostics4 git calls · 364 ms
CallStatusSizeTime0364 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=145
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=145
git.pkt.payload.max=76
git.ls_refs.count=2
git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020038 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=38434
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=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
fetch2004.4 KiB359 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=359
git.response.bytes=4518
git.response.cache=MISS
git.response.duration_ms=359
git.fetch.wants=9a4940020ad54a3d0fad4f63ae0469a9df00cbe9
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=4518
git.pkt.payload.max=4497
git.sideband.band1.bytes=4496
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
a5e2c5403f5c4afc
Request
5ddcd770…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format