receive-pack.ts
This file
Path
packages/git/src/receive-pack.ts
274 lines · 7.7 KiB · TypeScript
Last changed by
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–76why, one step back1import { RefName } from "@repo/artifacts/repo-host";2import { CommitSha } from "@repo/protocol/ids";3import type { Refusal } from "@repo/protocol/refusal";4import { explain, headline } from "@repo/protocol/render";5import { Array, Data, Effect, Option, Schema, Stream } from "effect";67import type { Command } from "./custody.ts";8import { FLUSH, concat, packetAt, packets, pkt, utf8 } from "./pkt-line.ts";910export class Malformed extends Data.TaggedError("Malformed")<{11 readonly reason: string;12}> {}1314const ZERO = "0".repeat(40);1516const COMMAND =17 /^(?<from>[0-9a-f]{40}) (?<to>[0-9a-f]{40}) (?<ref>[^\0\n ]+)(?:\0(?<capabilities>[^\n]*))?\n?$/u;1819const objectId = (hex: string) =>20 hex === ZERO ? Option.none() : Option.some(CommitSha.make(hex));2122const isRefName = Schema.is(RefName);2324export interface Opening {25 readonly commands: readonly Command[];26 readonly capabilities: ReadonlySet<string>;27 readonly read: Uint8Array;28}2930const parse = (lines: readonly string[]) =>31 Effect.gen(function* () {32 const commands: Command[] = [];33 let capabilities = new Set<string>();3435 // A shallow clone names its shallow commits before its commands.36 for (const line of lines.filter((text) => !text.startsWith("shallow "))) {37 const fields = COMMAND.exec(line)?.groups;3839 if (fields?.from === undefined || fields.to === undefined) {40 return yield* new Malformed({ reason: `not a push command: ${line}` });41 }4243 if (fields.ref === undefined || !isRefName(fields.ref)) {44 return yield* new Malformed({45 reason: `not a ref this gateway carries: ${fields.ref ?? ""}`,46 });47 }4849 if (commands.length === 0) {50 capabilities = new Set(51 (fields.capabilities ?? "").split(" ").filter((word) => word !== "")52 );53 }5455 commands.push({56 from: objectId(fields.from),57 ref: fields.ref,58 to: objectId(fields.to),59 });60 }6162 return { capabilities, commands };63 });6465const packetIn = (bytes: Uint8Array, at: number) =>66 Effect.try({67 catch: () => new Malformed({ reason: `bad pkt-line at byte ${at}` }),68 try: () => packetAt(bytes, at),69 });7071const chunkOf = (reader: ReadableStreamDefaultReader<Uint8Array>) =>72 Effect.tryPromise({73 catch: () => new Malformed({ reason: "the push could not be read" }),74 try: () => reader.read(),75 });76Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 77why, one step back77/** The pack that follows stays unread in the body. An empty list is git's probe before a large push. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 78–123why, one step back78export const readOpening = (body: ReadableStream<Uint8Array>) =>79 Effect.gen(function* () {80 const reader = body.getReader();81 const lines: string[] = [];82 let read = new Uint8Array(0);83 let at = 0;84 let flushed = false;8586 while (!flushed) {87 const next = yield* packetIn(read, at);8889 if (Option.isSome(next)) {90 const { packet } = next.value;9192 at = next.value.next;93 flushed = packet === "Flush";9495 if (packet !== "Flush") {96 lines.push(new TextDecoder().decode(packet));97 }98 } else {99 const chunk = yield* chunkOf(reader);100101 if (chunk.done) {102 return yield* new Malformed({103 reason: "the push ended inside its command list",104 });105 }106107 read = concat([read, chunk.value]);108 }109 }110111 reader.releaseLock();112113 const { capabilities, commands } = yield* parse(lines);114115 return { capabilities, commands, read } satisfies Opening;116 });117118const rest = (body: ReadableStream<Uint8Array>) =>119 Stream.fromReadableStream({120 evaluate: () => body,121 onError: () => new Malformed({ reason: "the push could not be read" }),122 });123Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 124why, one step back124/** So the client finishes sending. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 125–274why, one step back125export const drain = (body: ReadableStream<Uint8Array>) =>126 Stream.runDrain(rest(body)).pipe(Effect.ignore);127128export const resume = (read: Uint8Array, body: ReadableStream<Uint8Array>) =>129 Stream.toReadableStream(Stream.concat(Stream.succeed(read), rest(body)));130131// The largest payload a side-band packet carries, by the client's capability.132const bandLimit = (capabilities: ReadonlySet<string>) => {133 if (capabilities.has("side-band-64k")) {134 return Option.some(65_515);135 }136137 return capabilities.has("side-band") ? Option.some(995) : Option.none();138};139140const band = (channel: 1 | 2, payload: Uint8Array) =>141 pkt(concat([Uint8Array.of(channel), payload]));142143const chunks = (bytes: Uint8Array, limit: number) => {144 const parts: Uint8Array[] = [];145146 for (let at = 0; at < bytes.length; at += limit) {147 parts.push(bytes.subarray(at, at + limit));148 }149150 return parts;151};152153export interface RefStatus {154 readonly ref: string;155 readonly ng: Option.Option<string>;156}157158export interface UpstreamReport {159 readonly messages: readonly Uint8Array[];160 readonly unpack: Option.Option<string>;161 readonly refs: readonly RefStatus[];162}163164const text = (bytes: Uint8Array) =>165 new TextDecoder().decode(bytes).replace(/\n$/u, "");166167const STATUS = /^(?<verdict>ok|ng) (?<ref>\S+)(?: (?<reason>.*))?$/u;168169export const readReport = (170 capabilities: ReadonlySet<string>,171 reply: Uint8Array172): UpstreamReport => {173 const messages: Uint8Array[] = [];174 const status: Uint8Array[] = [];175176 if (Option.isSome(bandLimit(capabilities))) {177 for (const packet of packets(reply)) {178 if (packet !== "Flush") {179 // Band 1 carries the report, 2 progress, 3 a fatal error.180 (packet[0] === 1 ? status : messages).push(packet.subarray(1));181 }182 }183 } else {184 status.push(reply);185 }186187 const lines = packets(concat(status)).flatMap((packet) =>188 packet === "Flush" ? [] : [text(packet)]189 );190191 const unpack = Option.fromNullishOr(192 lines.find((line) => line.startsWith("unpack "))?.slice("unpack ".length)193 );194195 const refs = lines.flatMap((line): RefStatus[] => {196 const fields = STATUS.exec(line)?.groups;197198 return fields?.ref === undefined199 ? []200 : [201 {202 ng:203 fields.verdict === "ng"204 ? Option.some(fields.reason ?? "")205 : Option.none(),206 ref: fields.ref,207 },208 ];209 });210211 return { messages, refs, unpack };212};213214export const writeReport = (215 capabilities: ReadonlySet<string>,216 messages: readonly Uint8Array[],217 refusals: readonly Refusal[],218 refs: readonly RefStatus[]219) => {220 const reports =221 capabilities.has("report-status") || capabilities.has("report-status-v2");222223 const status = reports224 ? concat([225 pkt(utf8("unpack ok\n")),226 ...refs.map(({ ng, ref }) =>227 pkt(228 utf8(229 Option.match(ng, {230 onNone: () => `ok ${ref}\n`,231 onSome: (reason) => `ng ${ref} ${reason}\n`,232 })233 )234 )235 ),236 FLUSH,237 ])238 : new Uint8Array(0);239240 const explained = Array.isReadonlyArrayNonEmpty(refusals)241 ? explain(refusals)242 : [];243244 return Option.match(bandLimit(capabilities), {245 onNone: () => status,246 onSome: (limit) =>247 concat([248 ...messages.map((message) => band(2, message)),249 ...explained.map((line) => band(2, utf8(`${line}\n`))),250 ...chunks(status, limit).map((part) => band(1, part)),251 FLUSH,252 ]),253 });254};255256const ADVERTISED = /^(?<oid>[0-9a-f]{40}) (?<ref>[^\0\n ]+)/u;257258export const readAdvertisement = (advertisement: Uint8Array) =>259 new Map(260 packets(advertisement).flatMap((packet) => {261 const fields =262 packet === "Flush" ? undefined : ADVERTISED.exec(text(packet))?.groups;263264 return fields?.oid === undefined || fields.ref === undefined265 ? []266 : [[fields.ref, CommitSha.make(fields.oid)] as const];267 })268 );269270export const refuseAll = (271 commands: readonly Command[],272 refusals: Array.NonEmptyReadonlyArray<Refusal>273): RefStatus[] =>274 commands.map(({ ref }) => ({ ng: Option.some(headline(refusals)), ref }));