main
ply4 git calls30 ms43 KiB3 cachedprotocol v2
183 lines9.7 KiBRaw
1// The /v1 write handlers. Parsing that can fail with bad_request happens before a transport is opened, and throws
2// (index.js answers it). Every ply call's failure is its Err, returned to index.js as this handler's Result.
3// An unborn HEAD is read only when a call needs the default branch or a not_found might be that empty ref.
4import { plyError, mergeBranch, operation, parseCommitId, readCommit, rebaseBranch } from 'ply'
5import { type PlyError } from '../ply-result.ts'
6import { fromNullable, recordGet } from '../absent.ts'
7import { err, ok, type Result } from '../http/machine.ts'
8import { type CallOpts } from './call.ts'
9import { type WorkerError } from './errors.ts'
10import { createBranch, deleteRef } from './branch.ts'
11import { commitEdit } from './commit.ts'
12import { noteUnbornAdvertised, readHead, type HeadState } from './head.ts'
13import { nowSeconds, plyStamp, stamp } from './identity.ts'
14import { pick } from './pick.ts'
15import { asBody, branchRef, parseDeleteOid, parseEdit, refOrCommit, sameBranch } from './request.ts'
16import { unifyPly, type WriteOutcome } from './result.ts'
17import { createTag, removeTag } from './tag.ts'
19async function readHeadState(remote: string, opts: CallOpts, op: string): Promise<Result<HeadState, PlyError>> {
20 return operation(op, remote, opts, async ({ t, outcome }) => outcome('ok', await readHead(t)))
23async function bornRef(remote: string, opts: CallOpts, field: string): Promise<Result<string, PlyError>> {
24 const read = await readHeadState(remote, opts, 'head')
25 if (!read.ok) return read
26 const head = read.value
27 if (head.kind === 'born') return ok(head.ref)
28 if (head.kind === 'unborn') return err(plyError('bad_request', `${field} is required when the remote HEAD is unborn (${head.ref})`))
29 if (head.kind === 'detached') return err(plyError('bad_request', `${field} is required when the remote HEAD is detached`))
30 return err(plyError('bad_request', `${field} is required when the remote HEAD is absent`))
33async function requireRef(remote: string, opts: CallOpts, given: unknown, field: string, parse: (value: unknown, name: string) => string = branchRef): Promise<Result<string, PlyError>> {
34 const present = fromNullable(given)
35 if (present.tag === 'some' && present.value !== '') return ok(parse(present.value, field))
36 return bornRef(remote, opts, field)
39/** A not_found on an unborn HEAD's own ref says so. A failed HEAD read keeps the original not_found. */
40async function clarifyUnborn(remote: string, opts: CallOpts, error: PlyError, verb: string): Promise<PlyError> {
41 if (error.code !== 'not_found') return error
42 const read = await readHeadState(remote, opts, 'head')
43 if (read.ok && read.value.kind === 'unborn' && error.message.includes(read.value.ref)) {
44 return plyError('not_found', `ref ${read.value.ref} is unborn; create a commit before ${verb}`, { miss: { kind: 'head_unborn', target: read.value.ref } })
45 }
46 return error
49function textOr(value: unknown, field: string): string | null {
50 const found = fromNullable(value)
51 if (found.tag === 'none') return null
52 if (typeof found.value !== 'string') throw plyError('bad_request', `${field} must be a string`)
53 return found.value
56function optionalStamp(raw: Record<string, unknown>, key: string, field: string, now: ReturnType<typeof nowSeconds>) {
57 const found = recordGet(raw, key)
58 if (found.tag === 'none') return null
59 return stamp(found.value, field, now)
62type Reply = { readonly body: Record<string, unknown> } | { readonly status: number; readonly body: Record<string, unknown> }
63type Handled = Promise<Result<Reply, PlyError | WorkerError>>
65const replied = (r: Result<Record<string, unknown>, PlyError | WorkerError>, status: number | null = null): Result<Reply, PlyError | WorkerError> =>
66 r.ok ? ok(status === null ? { body: r.value } : { status, body: r.value }) : r
68export async function handleEdit(remote: string, body: unknown, opts: CallOpts): Handled {
69 return replied(await commitEdit(remote, parseEdit(asBody(body), nowSeconds()), opts))
72export async function handleBranchCreate(remote: string, body: unknown, opts: CallOpts): Handled {
73 const raw = asBody(body)
74 return replied(await createBranch(remote, raw.ref, raw.from, opts), 201)
77export async function handleBranchDelete(remote: string, body: unknown, opts: CallOpts): Handled {
78 const raw = asBody(body)
79 return replied(await deleteRef(remote, branchRef(raw.ref, 'ref'), parseDeleteOid(raw.oid), opts, 'branch_delete'))
82export async function handleMerge(remote: string, body: unknown, opts: CallOpts): Handled {
83 const raw = asBody(body)
84 const required = await requireRef(remote, opts, raw.ref, 'ref')
85 if (!required.ok) return required
86 const ref = required.value
87 const from = refOrCommit(raw.from, 'from')
88 const now = nowSeconds()
89 const author = optionalStamp(raw, 'author', 'author', now)
90 const committer = optionalStamp(raw, 'committer', 'committer', now)
91 const message = textOr(raw.message, 'message')
92 const merged = await mergeBranch(remote, {
93 ref,
94 from,
95 ...(author === null ? {} : { author: plyStamp(author) }),
96 ...(committer === null ? {} : { committer: plyStamp(committer) }),
97 message,
98 fastForwardOnly: !!raw.fastForwardOnly,
99 noFastForward: !!raw.noFastForward,
100 }, opts)
101 if (!merged.ok) return err(await clarifyUnborn(remote, opts, merged.error, 'merging'))
102 const result = merged.value as Record<string, unknown>
103 const outcome = (typeof result.outcome === 'string' ? result.outcome : 'merge') as WriteOutcome
104 return ok({ body: unifyPly(result, outcome, ref) })
107export async function handleRebase(remote: string, body: unknown, opts: CallOpts): Handled {
108 const raw = asBody(body)
109 const ref = branchRef(raw.ref, 'ref')
110 const required = await requireRef(remote, opts, raw.onto, 'onto', refOrCommit)
111 if (!required.ok) return required
112 const onto = required.value
113 const now = nowSeconds()
114 const committer = stamp(raw.committer, 'committer', now)
115 const author = optionalStamp(raw, 'author', 'author', now)
116 const message = textOr(raw.message, 'message')
117 const rebased = await rebaseBranch(remote, {
118 ref,
119 onto,
120 committer: plyStamp(committer),
121 ...(author === null ? {} : { author: plyStamp(author) }),
122 squash: !!raw.squash,
123 message,
124 }, opts)
125 if (!rebased.ok) return err(await clarifyUnborn(remote, opts, rebased.error, 'rebasing'))
126 const result = rebased.value as Record<string, unknown>
127 const outcome = (typeof result.outcome === 'string' ? result.outcome : 'rebase') as WriteOutcome
128 return ok({ body: unifyPly(result, outcome, ref) })
131async function handlePick(remote: string, body: unknown, opts: CallOpts, revert: boolean): Handled {
132 const raw = asBody(body)
133 const required = await requireRef(remote, opts, raw.ref, 'ref')
134 if (!required.ok) return required
135 const ref = required.value
136 const parsed = parseCommitId(raw.commit)
137 if (!parsed.ok) throw parsed.error
138 const commit = parsed.value
139 const committer = stamp(raw.committer, 'committer', nowSeconds())
140 const allowEmpty = recordGet(raw, 'allowEmpty')
141 if (allowEmpty.tag === 'some' && typeof allowEmpty.value !== 'boolean') throw plyError('bad_request', 'allowEmpty must be true or false')
142 const message = textOr(raw.message, 'message')
143 const picked = await pick(remote, opts, { ref, commit, committer, message, allowEmpty: allowEmpty.tag === 'some' && allowEmpty.value === true, revert })
144 if (!picked.ok) return err(await clarifyUnborn(remote, opts, picked.error, revert ? 'reverting' : 'cherry-picking'))
145 return ok({ body: picked.value })
148export const handleCherryPick = (remote: string, body: unknown, opts: CallOpts) => handlePick(remote, body, opts, false)
149export const handleRevert = (remote: string, body: unknown, opts: CallOpts) => handlePick(remote, body, opts, true)
151export const handleTagCreate = async (remote: string, body: unknown, opts: CallOpts): Handled => replied(await createTag(remote, body, opts), 201)
152export const handleTagDelete = async (remote: string, body: unknown, opts: CallOpts): Handled => replied(await removeTag(remote, body, opts))
154const EMPTY_COMMIT = { empty: true, oid: null, tree: null, parents: [], author: null, committer: null, message: null, signed: false }
156/** A born commit is ply's readCommit body, unchanged. An unborn HEAD (or that same branch by name) is the empty-repo body. */
157export async function readCommitOrEmpty(remote: string, ref: string | null, opts: CallOpts): Promise<Result<Record<string, unknown>, PlyError>> {
158 // A branch name or oid is what readCommit resolves. Omitting ref is ply's default.
159 // ply returns `{ empty: true, ref }` for an unborn HEAD. The documented body also carries the null commit fields.
160 const read = await readCommit(remote, { ref }, opts as Parameters<typeof readCommit>[2])
161 if (read.ok) {
162 if ('empty' in read.value) {
163 noteUnbornAdvertised(remote)
164 return ok({ ...EMPTY_COMMIT, ref: read.value.ref })
165 }
166 return ok(read.value)
167 }
168 if (read.error.code !== 'not_found') return read
169 // A failed HEAD read (a missing repository) keeps the original not_found.
170 const head = await readHeadState(remote, opts, 'read_commit')
171 const wanted = ref === null ? '' : ref
172 if (head.ok && head.value.kind === 'unborn' && (wanted === '' || wanted === 'HEAD' || sameBranch(wanted, head.value.ref))) return ok({ ...EMPTY_COMMIT, ref: head.value.ref })
173 return read
176/** Extra fields for GET /v1/refs when ply's ls-refs could not see an unborn HEAD. Born repositories are unchanged. */
177export async function unbornFields(remote: string, opts: CallOpts, head: string | null): Promise<Record<string, unknown>> {
178 if (head) return {}
179 // A failed HEAD read changes nothing: the ref list itself succeeded, and head stays null.
180 const state = await readHeadState(remote, opts, 'head')
181 if (state.ok && state.value.kind === 'unborn') return { empty: true, unborn: state.value.ref }
182 return {}
Diagnostics4 git calls · 30 ms
CallStatusSizeTime030 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=145
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=145
git.pkt.payload.max=76
git.ls_refs.count=2
git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020040 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=41349
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=526b305930b8ef382f2d7a1f9c0238730a585921
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=6
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=41349
git.pkt.payload.max=41254
git.sideband.band1.bytes=41253
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=61
git.pack.bytes=41253
git.pack.ofs_delta=0
git.pack.ref_delta=0
git.pack.chain.max=0
git.pack.trailer=ab60efef4b7243678c75de64a4386986ee885c1c
git.pack.full=61
Open pack map
fetch2002.7 KiB · hit25 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=25
git.response.bytes=2785
git.response.cache=HIT
git.response.duration_ms=25
git.fetch.wants=d43914a381177ec16627e76c827223ef641bf0a2
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=2785
git.pkt.payload.max=2764
git.sideband.band1.bytes=2763
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

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

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