Artifactspublic-v0

ply

main
ply4 git calls40 ms42 KiB3 cachedprotocol v2
199 lines15 KiBRaw
1// Ref management by URL: create a branch at a commit, delete a branch, create a tag. Each is one operation (a
2// `git.<op>` root span, a transport built for the url) and one receive-pack command with no new objects, except an
3// annotated tag, whose one tag object is the pack.
4//
5// createBranch(url, { ref, from }, opts) → { ref, oid, pushBytes }
6// deleteBranch(url, { ref, expected? }, opts) → { ref, oid } oid: the tip it had
7// createTag(url, { name, target, message?, tagger? }, opts) → { ref, oid, commit, annotated, pushBytes }
8// deleteTag(url, { name, expected? }, opts) → { ref, oid } deleteBranch on refs/tags/<name>
9// listRefs(url, { prefixes? }, opts) → { head, refs: [{ name, oid, peeled }] }
10//
11// A ref that already exists is `cas_conflict` with `expected` the zero id and `actual` its tip, as a create in
12// editFile and commitChanges reports it (the zero old id is the compare-and-swap "must not exist"), whether ply saw it
13// in ls-refs or receive-pack refused the create. A delete compares against `expected` when given, else the tip ls-refs
14// reported; a stale one, or a push that loses the race to another writer, is `cas_conflict` with `actual` the tip
15// read back (null: deleted). What the server itself refuses (deleting the branch HEAD names, a hook) is its own
16// error, unchanged: `push_rejected` with git's reason.
17/* oxlint-disable require-await -- the entry points are async: a refused argument is an Err in a promise, like every other answer (read.ts) */
18/* oxlint-disable import/max-dependencies -- an operation over ls-refs, resolve, push and the tag codec: each module is one step */
19import type { PlyError } from './errors.js';
20import type { Result } from './result.js';
21import type { ReadOptions } from './read.js';
22import type { Input } from './absent.js';
23import type { OperationOpts } from './operation.js';
24import { fail } from './errors.js';
25import { ok } from './result.js';
26import { withDefaults } from './absent.js';
27import { lsRefs } from './lsrefs.js';
28import { push, ZERO_OID } from './push.js';
29import { parseOid } from './oid.js';
30import { operation, verifyRef } from './operation.js';
31import { encodeTag, hashObject, ident, TYPE } from './objects.js';
32import { validatePushRef, validateMessage } from './validate.js';
33import { resolveCommit } from './read.js';
34import { refOid, type Author, type OpContext, type PushObject } from './merge.js';
35import { assertCommit, isOid, stamp } from './mergeio.js';
37// What every ref operation takes besides the url and the spec: the entry options (auth, tracer, limits, …) and
38// `verify` (read the ref back after the push; an acknowledged push that does not read back is `ambiguous`).
39export type RefOpOptions = ReadOptions & Input<{ readonly verify: boolean }>;
41// The entry options as operation() takes them, with the operation's attributes.
42const opOpts = (options: RefOpOptions, attrs: Readonly<Record<string, unknown>>): OperationOpts => ({ ...options, attrs });
44// A ref the remote already has: the create's compare-and-swap (old id zero) cannot hold.
45const exists = (ref: string, tip: string): Result<never, PlyError> =>
46 fail('cas_conflict', `${ref} already exists at ${tip}`, { what: 'ref', expected: ZERO_OID, actual: tip });
48// Effect: the commit `from` names. A 40-hex id must be a commit the server has (fetched alone); a name is resolved as
49// readCommit resolves one (full ref, short name, HEAD; an annotated tag is peeled to its commit).
50async function commitOf(t: OpContext['t'], from: string, what: string): Promise<Result<string, PlyError>> {
51 // a 40-hex id is parsed once, here
52 const id = parseOid(from);
53 if (id.ok) {
54 if (id.value === ZERO_OID) return fail('bad_request', `${what} must not be the zero oid`, { what });
55 const c = await assertCommit(t, id.value, what);
56 return c.ok ? ok(id.value) : c;
57 }
58 const r = await resolveCommit(t, from);
59 return r.ok ? ok(r.value.commit) : r;
62// Effect: the create push (old id zero, nothing but `objects`). A refused create re-reads the ref: present, it is the
63// ref that already existed (cas_conflict naming its tip); absent, the server's own refusal stands.
64type Create = { readonly prefix: string; readonly ref: string; readonly newOid: string; readonly objects: readonly PushObject[]; readonly verify: boolean };
65async function createRef({ t, root }: Pick<OpContext, 't' | 'root'>, { prefix, ref, newOid, objects, verify }: Create): Promise<Result<number, PlyError>> {
66 const pushed = await push(t, { ref, oldOid: ZERO_OID, newOid, objects });
67 if (!pushed.ok) {
68 if (pushed.error.code !== 'cas_conflict') return pushed;
69 const now = await lsRefs(t, [ref]);
70 if (!now.ok) return now;
71 const tip = refOid(now.value.refs, ref);
72 return tip.tag === 'some' ? exists(ref, tip.value) : pushed;
73 }
74 if (verify) { const seen = await verifyRef(t, root, prefix, ref, newOid); if (!seen.ok) return seen; }
75 return ok(pushed.value.packBytes);
78export type CreateBranchSpec = { readonly ref: string; readonly from: string };
79export type CreateBranchResult = { readonly ref: string; readonly oid: string; readonly pushBytes: number };
80// A new branch at a commit: `from` is a ref name (full or short, as readCommit takes it) or a 40-hex commit id.
81export async function createBranch(url: string, spec: CreateBranchSpec, options: RefOpOptions = {}): Promise<Result<CreateBranchResult, PlyError>> {
82 const { ref, from } = spec;
83 const { verify } = withDefaults(options, { verify: false });
84 const named = validatePushRef(ref, false); if (!named.ok) return named;
85 if (typeof from !== 'string' || from === '') return fail('bad_request', 'from must be a ref name or a commit id', { what: 'from' });
86 return operation('branch_create', url, opOpts(options, { 'git.branch_create.ref': ref, 'git.branch_create.from': from }), async ({ t, root, outcome }: OpContext): Promise<Result<CreateBranchResult, PlyError>> => {
87 const listed = await lsRefs(t, [ref]); if (!listed.ok) return listed;
88 const present = refOid(listed.value.refs, ref);
89 if (present.tag === 'some') return exists(ref, present.value);
90 const commit = await commitOf(t, from, 'from'); if (!commit.ok) return commit;
91 root.set({ 'git.branch_create.oid': commit.value });
92 const pushed = await createRef({ t, root }, { prefix: 'git.branch_create', ref, newOid: commit.value, objects: [], verify });
93 if (!pushed.ok) return pushed;
94 return outcome('created', { ref, oid: commit.value, pushBytes: pushed.value });
95 });
98// Effect: a delete receive-pack refused as stale (the ref moved between ls-refs and the push). receive-pack does not
99// say where the ref went, so re-read it: present, cas_conflict with `actual` the winner's tip; absent, someone else
100// deleted it first and the push's own cas_conflict (actual null) stands.
101async function lostDelete(t: OpContext['t'], ref: string, tip: string, pushed: Result<never, PlyError>): Promise<Result<never, PlyError>> {
102 const now = await lsRefs(t, [ref]);
103 if (!now.ok) return now;
104 const moved = refOid(now.value.refs, ref);
105 return moved.tag === 'some' ? fail('cas_conflict', `${ref} moved from ${tip} to ${moved.value}`, { what: 'ref', expected: tip, actual: moved.value }) : pushed;
108export type DeleteBranchConfig = { readonly expected: string | null };
109export type DeleteBranchSpec = { readonly ref: string } & Input<DeleteBranchConfig>;
110export type DeleteBranchResult = { readonly ref: string; readonly oid: string };
111// Delete a branch (or any ref): against `expected` when given (the tip the caller last saw), else the tip ls-refs
112// reports now. An absent ref is not_found. receive-pack's report is the answer (push.ts: anything short of git's own
113// report is `ambiguous`), so there is no read-back.
114export async function deleteBranch(url: string, spec: DeleteBranchSpec, options: ReadOptions = {}): Promise<Result<DeleteBranchResult, PlyError>> {
115 const { ref } = spec;
116 const { expected } = withDefaults<DeleteBranchConfig>(spec, { expected: null });
117 const named = validatePushRef(ref, true); if (!named.ok) return named;
118 if (expected !== null && !isOid(expected)) return fail('bad_request', 'expected must be a 40-hex commit id', { what: 'expected' });
119 return operation('branch_delete', url, opOpts(options, { 'git.branch_delete.ref': ref, 'git.branch_delete.cas_from_caller': expected !== null }), async ({ t, root, outcome }: OpContext): Promise<Result<DeleteBranchResult, PlyError>> => {
120 const listed = await lsRefs(t, [ref]); if (!listed.ok) return listed;
121 const present = refOid(listed.value.refs, ref);
122 if (present.tag === 'none') return fail('not_found', `ref ${ref} not found`, { miss: { kind: 'ref', ref, candidates: [ref] } });
123 const tip = present.value;
124 if (expected !== null && expected !== tip) return fail('cas_conflict', `${ref} is at ${tip}, not ${expected}`, { what: 'ref', expected, actual: tip });
125 root.set({ 'git.branch_delete.oid': tip });
126 const pushed = await push(t, { ref, oldOid: tip, newOid: ZERO_OID, objects: [] });
127 if (!pushed.ok) return pushed.error.code === 'cas_conflict' ? lostDelete(t, ref, tip, pushed) : pushed;
128 return outcome('deleted', { ref, oid: tip });
129 });
132export type CreateTagConfig = { readonly message: string | null; readonly tagger: Author | null; readonly time: number };
133// `name` is the tag's name, `v1.0` or `refs/tags/v1.0`. A `message` makes an annotated tag (a tag object, as `git tag
134// -a`), which needs a `tagger`; without one the tag is lightweight (the ref names the commit, as `git tag`).
135export type CreateTagSpec = { readonly name: string; readonly target: string } & Input<CreateTagConfig>;
136export type CreateTagResult = { readonly ref: string; readonly oid: string; readonly commit: string; readonly annotated: boolean; readonly pushBytes: number };
137export async function createTag(url: string, spec: CreateTagSpec, options: RefOpOptions = {}): Promise<Result<CreateTagResult, PlyError>> {
138 const { name, target } = spec;
139 const { message, tagger, time } = withDefaults<CreateTagConfig>(spec, { message: null, tagger: null, time: Math.floor(Date.now() / 1000) });
140 const { verify } = withDefaults(options, { verify: false });
141 if (typeof name !== 'string' || name === '') return fail('bad_request', 'name must be a tag name', { what: 'tag' });
142 const ref = name.startsWith('refs/tags/') ? name : `refs/tags/${name}`;
143 const named = validatePushRef(ref, false); if (!named.ok) return named;
144 if (typeof target !== 'string' || target === '') return fail('bad_request', 'target must be a ref name or a commit id', { what: 'target' });
145 const annotated = message !== null;
146 if (annotated) { const m = validateMessage(message); if (!m.ok) return m; }
147 if (annotated && tagger === null) return fail('bad_request', 'an annotated tag (message) needs a tagger', { what: 'tagger' });
148 const who = tagger === null ? null : stamp(tagger, time);
149 if (who !== null && !who.ok) return who;
150 return operation('tag_create', url, opOpts(options, { 'git.tag_create.ref': ref, 'git.tag_create.target': target, 'git.tag_create.annotated': annotated }), async ({ t, root, outcome }: OpContext): Promise<Result<CreateTagResult, PlyError>> => {
151 const listed = await lsRefs(t, [ref]); if (!listed.ok) return listed;
152 const present = refOid(listed.value.refs, ref);
153 if (present.tag === 'some') return exists(ref, present.value);
154 const commit = await commitOf(t, target, 'target'); if (!commit.ok) return commit;
155 let oid = commit.value;
156 const objects: PushObject[] = [];
157 if (annotated && who !== null) {
158 const line = ident(who.value); if (!line.ok) return line;
159 const data = encodeTag({ object: commit.value, type: 'commit', tag: ref.slice('refs/tags/'.length), tagger: line.value, message: message.endsWith('\n') ? message : `${message}\n` });
160 if (!data.ok) return data;
161 oid = hashObject('tag', data.value);
162 objects.push({ type: TYPE.TAG, data: data.value });
163 }
164 root.set({ 'git.tag_create.commit': commit.value, 'git.tag_create.oid': oid });
165 const pushed = await createRef({ t, root }, { prefix: 'git.tag_create', ref, newOid: oid, objects, verify });
166 if (!pushed.ok) return pushed;
167 return outcome('created', { ref, oid, commit: commit.value, annotated, pushBytes: pushed.value });
168 });
171// A tag is a ref like a branch: deleting one is deleteBranch on refs/tags/<name> (the same CAS and errors).
172export type DeleteTagSpec = { readonly name: string } & Input<DeleteBranchConfig>;
173export async function deleteTag(url: string, spec: DeleteTagSpec, options: ReadOptions = {}): Promise<Result<DeleteBranchResult, PlyError>> {
174 const { name } = spec;
175 if (typeof name !== 'string' || name === '') return fail('bad_request', 'name must be a tag name', { what: 'tag' });
176 const { expected } = withDefaults<DeleteBranchConfig>(spec, { expected: null });
177 return deleteBranch(url, { ref: name.startsWith('refs/tags/') ? name : `refs/tags/${name}`, expected }, options);
180// The refs the remote advertises under `prefixes` (branches and tags by default), sorted by name, and the branch HEAD
181// names (null when HEAD is detached or absent). `peeled` is the commit an annotated tag points at, else null.
182export type ListRefsConfig = { readonly prefixes: readonly string[] };
183export type ListRefsSpec = Input<ListRefsConfig>;
184export type ListedRef = { readonly name: string; readonly oid: string; readonly peeled: string | null };
185export type ListRefsResult = { readonly head: string | null; readonly refs: readonly ListedRef[] };
186export async function listRefs(url: string, spec: ListRefsSpec = {}, options: ReadOptions = {}): Promise<Result<ListRefsResult, PlyError>> {
187 const { prefixes } = withDefaults<ListRefsConfig>(spec, { prefixes: ['refs/heads/', 'refs/tags/'] });
188 // A JS caller's value, checked as one: Array.isArray would narrow `prefixes` itself to any[].
189 const given: unknown = prefixes;
190 if (!Array.isArray(given) || !given.every(p => typeof p === 'string' && p !== '')) return fail('bad_request', 'prefixes must be non-empty strings', { what: 'prefixes' });
191 return operation('list_refs', url, opOpts(options, { 'git.list_refs.prefixes': prefixes.join(',') }), async ({ t, outcome }: OpContext): Promise<Result<ListRefsResult, PlyError>> => {
192 const listed = await lsRefs(t, [...prefixes, 'HEAD']); if (!listed.ok) return listed;
193 const refs: ListedRef[] = [];
194 for (const [name, r] of listed.value.refs) if (name !== 'HEAD' && prefixes.some(p => name.startsWith(p))) refs.push({ name, oid: r.oid, peeled: r.peeled });
195 // byte order, as git lists refs (names are unique, so never equal)
196 refs.sort((a, b) => (a.name < b.name ? -1 : 1));
197 return outcome('ok', { head: listed.value.head, refs }, { 'git.list_refs.count': refs.length });
198 });
Diagnostics4 git calls · 40 ms
CallStatusSizeTime040 ms
discover200152 B10 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
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 · hit6 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=24
git.response.bytes=38434
git.response.cache=HIT
git.response.duration_ms=6
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.3 KiB · hit24 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=4435
git.response.cache=HIT
git.response.duration_ms=24
git.fetch.wants=441b56934a608fa336d7c85ddf62b1db1852db0a
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=4435
git.pkt.payload.max=4414
git.sideband.band1.bytes=4413
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
a5e221d75930a87d
Request
df08d70e…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format