gateway.ts
This file
Path
packages/git/src/gateway.ts
372 lines · 10.1 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/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 1–2why, one step back1import type { RepoName } from "@repo/artifacts/repo-host";2import { repoNameOfAddress } from "@repo/protocol/ids";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 3–22why, one step back3import type { CommitSha } from "@repo/protocol/ids";4import { RepoBusy, StaleBase } from "@repo/protocol/refusal";5import { headline } from "@repo/protocol/render";6import { Array, Effect, Equal, Match, Option } from "effect";78import { Custody } from "./custody.ts";9import type { Command } from "./custody.ts";10import {11 drain,12 readAdvertisement,13 readOpening,14 readReport,15 refuseAll,16 resume,17 writeReport,18} from "./receive-pack.ts";19import type { Opening, RefStatus } from "./receive-pack.ts";20import { Exchange, Upstream, UpstreamFailure } from "./upstream.ts";21import type { Service } from "./upstream.ts";22Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 23–25why, one step back23// A repo's address: one to three segments (`datekit`, `oscabriel/datekit`,24// `github.com/pallets/click`, each with a fork's `--` parts on the last), with25// or without `.git`, then the endpoint.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
line 26why, one step back26const ROUTE =Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 27why, one step back27 /^\/(?<name>[A-Za-z0-9._-]+?(?:\/[A-Za-z0-9._-]+?){0,2})(?:\.git)?\/(?<endpoint>info\/refs|git-upload-pack|git-receive-pack)$/u;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 28–30why, one step back2829export type GitEndpoint = "info/refs" | "git-upload-pack" | "git-receive-pack";30Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 31–46why, one step back31export interface GitRoute {32 readonly endpoint: GitEndpoint;33 readonly name: string;34 readonly repo: Option.Option<RepoName>;35}3637export const gitRoute = (pathname: string): Option.Option<GitRoute> =>38 Option.flatMap(39 Option.fromNullishOr(ROUTE.exec(pathname)?.groups),40 ({ endpoint, name }) =>41 name === undefined ||42 (endpoint !== "info/refs" &&43 endpoint !== "git-upload-pack" &&44 endpoint !== "git-receive-pack")45 ? Option.none()46 : Option.some({ endpoint, name, repo: repoNameOfAddress(name) })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 47–74why, one step back47 );4849const isService = (service: string | null): service is Service =>50 service === "git-upload-pack" || service === "git-receive-pack";5152// What the upstream needs of the client's headers. Credentials are never on53// the list: the upstream sees only the platform's.54const FORWARDED = [55 "accept",56 "content-encoding",57 "content-type",58 "git-protocol",59];6061const forwarded = (headers: Headers) => {62 const picked = new Headers();6364 for (const name of FORWARDED) {65 const value = headers.get(name);6667 if (value !== null) {68 picked.set(name, value);69 }70 }7172 return picked;73};74Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 75why, one step back75/** The Workers types leave a request body's chunk type open. */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 76–121why, one step back76const bytes = () =>77 new TransformStream<unknown, Uint8Array>({78 transform: (chunk, controller) => {79 if (chunk instanceof Uint8Array) {80 controller.enqueue(chunk);81 } else {82 controller.error(83 new TypeError("a request body held something other than bytes")84 );85 }86 },87 });8889const bodyOf = (request: Request) =>90 request.method === "POST" && request.body !== null91 ? Option.some(request.body.pipeThrough(bytes()))92 : Option.none();9394export const plain = (95 status: number,96 text: string,97 headers: Readonly<Record<string, string>> = {}98) =>99 new Response(`${text}\n`, {100 headers: { "content-type": "text/plain; charset=utf-8", ...headers },101 status,102 });103104const relay = (response: Response) =>105 new Response(response.body, {106 headers: {107 "cache-control": "no-cache",108 "content-type":109 response.headers.get("content-type") ?? "application/octet-stream",110 },111 status: response.status,112 });113114const result = (report: Uint8Array) =>115 new Response(report, {116 headers: {117 "cache-control": "no-cache",118 "content-type": "application/x-git-receive-pack-result",119 },120 });121Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6
line 122why, one step back122// What an upstream says when a ref moved under a push: Artifacts, thenMerge 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 123–126why, one step back123// git's own receive-pack (2.56).124const MOVED = new Set(["stale ref", "incorrect old value provided"]);125126// Artifacts' whole reply to a push it is too busy for: one fatal side-bandDrop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6
line 127why, one step back127// message and no report.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 128–317why, one step back128const BUSY = "artifacts_git_receive_pack_busy";129130const busy = (messages: readonly Uint8Array[]) =>131 messages.some((message) => new TextDecoder().decode(message).includes(BUSY));132133const tipsOf = (repo: RepoName) =>134 Effect.gen(function* () {135 const response = yield* (yield* Upstream).exchange(136 repo,137 Exchange.Advertise({138 headers: new Headers(),139 service: "git-receive-pack",140 })141 );142143 const advertisement = yield* Effect.tryPromise(() =>144 response.arrayBuffer()145 );146147 return yield* Effect.try(() =>148 readAdvertisement(new Uint8Array(advertisement))149 );150 }).pipe(Effect.orElseSucceed(() => new Map<string, CommitSha>()));151152const translate = (153 repo: RepoName,154 commands: readonly Command[],155 refs: readonly RefStatus[]156) =>157 Effect.gen(function* () {158 const moved = refs.filter(({ ng }) =>159 Option.exists(ng, (reason) => MOVED.has(reason))160 );161162 if (moved.length === 0) {163 return new Map<string, StaleBase>();164 }165166 const tips = yield* tipsOf(repo);167168 return new Map(169 moved.flatMap(({ ref }) => {170 const base = commands.find((command) => command.ref === ref)?.from;171 const tip = tips.get(ref);172173 return base === undefined || Option.isNone(base) || tip === undefined174 ? []175 : [176 [177 ref,178 new StaleBase({ base: base.value, conflicts: [], main: tip }),179 ] as const,180 ];181 })182 );183 });184185const answer = (186 repo: RepoName,187 opening: Opening,188 commands: Array.NonEmptyReadonlyArray<Command>,189 response: Response190) =>191 Effect.gen(function* () {192 if (response.status !== 200) {193 return relay(response);194 }195196 const reply = new Uint8Array(197 yield* Effect.tryPromise({198 catch: () =>199 new UpstreamFailure({200 reason: "the push's report was cut off",201 repo,202 }),203 try: () => response.arrayBuffer(),204 })205 );206207 const report = Effect.try(() => readReport(opening.capabilities, reply));208 const read = yield* Effect.option(report);209210 if (Option.isNone(read)) {211 return result(reply);212 }213214 const { messages, refs, unpack } = read.value;215216 if (busy(messages)) {217 const refusals = [new RepoBusy()] as const;218219 return result(220 writeReport(221 opening.capabilities,222 [],223 refusals,224 refuseAll(commands, refusals)225 )226 );227 }228229 const translated = yield* translate(repo, commands, refs);230231 if (translated.size > 0) {232 return result(233 writeReport(234 opening.capabilities,235 messages,236 [...translated.values()],237 refs.map((status) => {238 const refusal = translated.get(status.ref);239240 return refusal === undefined241 ? status242 : { ng: Option.some(headline([refusal])), ref: status.ref };243 })244 )245 );246 }247248 const landed =249 Equal.equals(unpack, Option.some("ok")) &&250 refs.length === commands.length &&251 refs.every(({ ng }) => Option.isNone(ng));252253 if (!landed) {254 return result(reply);255 }256257 const refused = yield* (yield* Custody).review(repo, commands);258259 return Array.isReadonlyArrayNonEmpty(refused)260 ? result(261 writeReport(262 opening.capabilities,263 messages,264 refused,265 refuseAll(commands, refused)266 )267 )268 : result(reply);269 });270271const push = (272 repo: RepoName,273 headers: Headers,274 body: ReadableStream<Uint8Array>275) =>276 Effect.gen(function* () {277 const custody = yield* Custody;278 const upstream = yield* Upstream;279 const opening = yield* readOpening(body);280281 const forward = upstream.exchange(282 repo,283 Exchange.Call({284 body: resume(opening.read, body),285 headers,286 service: "git-receive-pack",287 })288 );289290 // git's probe before a large push names no refs; nothing to judge.291 if (!Array.isReadonlyArrayNonEmpty(opening.commands)) {292 return relay(yield* forward);293 }294295 const { commands } = opening;296 const refused = yield* custody.admit(repo, commands);297298 if (Array.isReadonlyArrayNonEmpty(refused)) {299 yield* drain(body);300301 return result(302 writeReport(303 opening.capabilities,304 [],305 refused,306 refuseAll(commands, refused)307 )308 );309 }310311 return yield* answer(repo, opening, commands, yield* forward);312 }).pipe(313 Effect.catchTag("Malformed", ({ reason }) =>314 Effect.succeed(plain(400, reason))315 )316 );317Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 318why, one step back318/** Packs stream through and are never held whole. */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 319–331why, one step back319export const gateway = (320 request: Request321): Effect.Effect<Response, never, Upstream | Custody> =>322 Effect.gen(function* () {323 const url = new URL(request.url);324 const found = gitRoute(url.pathname);325326 if (Option.isNone(found)) {327 return plain(404, "not a git endpoint");328 }329330 const route = found.value;331 const upstream = yield* Upstream;Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 332–337why, one step back332333 if (Option.isNone(route.repo)) {334 return plain(404, `no repo ${route.name}`);335 }336337 const repo = route.repo.value;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 338–372why, one step back338 const headers = forwarded(request.headers);339340 return yield* Match.value(route.endpoint).pipe(341 Match.when("info/refs", () => {342 const service = url.searchParams.get("service");343344 return request.method === "GET" && isService(service)345 ? upstream346 .exchange(repo, Exchange.Advertise({ headers, service }))347 .pipe(Effect.map(relay))348 : Effect.succeed(plain(403, "this gateway speaks smart HTTP only"));349 }),350 Match.when("git-upload-pack", (service) =>351 Option.match(bodyOf(request), {352 onNone: () => Effect.succeed(plain(405, "POST a git request")),353 onSome: (body) =>354 upstream355 .exchange(repo, Exchange.Call({ body, headers, service }))356 .pipe(Effect.map(relay)),357 })358 ),359 Match.when("git-receive-pack", () =>360 Option.match(bodyOf(request), {361 onNone: () => Effect.succeed(plain(405, "POST a git request")),362 onSome: (body) => push(repo, headers, body),363 })364 ),365 Match.orElse(() => Effect.succeed(plain(404, "not a git endpoint")))366 );367 }).pipe(368 Effect.catchTags({369 RepoNotFound: ({ name }) => Effect.succeed(plain(404, `no repo ${name}`)),370 UpstreamFailure: ({ reason }) => Effect.succeed(plain(502, reason)),371 })372 );