lander.ts
This file
Path
apps/web/src/dev/lander.ts
290 lines · 9.1 KiB · TypeScript
Last changed by
Merge build/502-web-dev-backend: the web runs locally over a seeded in-process worldoscabrielbefore adoption4aeb23e
History of this fileTake it
Merge build/502-web-dev-backend: the web runs locally over a seeded in-process worldoscabrielbefore adoption4aeb23e
lines 1–290why, one step back1/**2 * The dev world's Lander: what the trusted Lander does, over the memory3 * repo host, in a few lines a developer can read. It composes a decider's4 * files onto main for a check, merges an answer by laying the files it5 * changed over main (a path both main and the answer changed since the6 * answer's base is a conflict), lands a tree on main as the platform's7 * commit with a compare-and-swap push and then the mirror ref, and reads the8 * config folder at a commit. It writes no verdict notes: nothing in the9 * world reads them. The scripted `/memory` Lander answers in a fixed order,10 * which a world people click through can't follow, so this one does the11 * work, as `/isogit` does, through `git.ts`.12 */13import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";14import { Brand } from "@repo/brand";15import { composeRef, Lander, landedRef, Rebuild } from "@repo/project/lander";16import type { Change, LandJob } from "@repo/project/lander";17import type { CommitSha, RepoName } from "@repo/protocol/ids";18import { LandedSha, RepoPath, TreeSha } from "@repo/protocol/ids";19import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";20import { sdkVersion } from "@repo/rules/rules-evaluator";21import { Array, DateTime, Effect, Layer, Option, Ref } from "effect";2223import {24 filesAt,25 overlay,26 personIdentity,27 platformIdentity,28 scratch,29 textOf,30} from "./git.ts";31import type { Files, Snapshot } from "./git.ts";3233const mainRef = RefName.make("refs/heads/main");3435const blocked = () => new VerifierBlocked({});3637/** A commit's files, or `VerifierBlocked` when the repo doesn't hold it. */38const read = (repo: RepoName, commit: CommitSha) =>39 filesAt(repo, commit).pipe(40 Effect.flatMap(Effect.fromOption),41 Effect.mapError(blocked)42 );4344/** What `head` changed against `base`, path by path, in path order. */45const changesOf = (base: Snapshot, head: Snapshot): readonly Change[] =>46 Array.dedupe([...base.keys(), ...head.keys()])47 .toSorted()48 .flatMap((path): readonly Change[] => {49 const before = base.get(path);50 const after = head.get(path);51 const at = RepoPath.make(path);5253 if (before === undefined) {54 return after === undefined55 ? []56 : [{ after: after.blob, path: at, status: "added" }];57 }5859 if (after === undefined) {60 return [{ before: before.blob, path: at, status: "deleted" }];61 }6263 return before.blob === after.blob64 ? []65 : [66 {67 after: after.blob,68 before: before.blob,69 path: at,70 status: "modified",71 },72 ];73 });7475/** An answer's head merged onto main: main's files with what the answer changed laid over them. */76const merged = (input: {77 readonly repo: RepoName;78 readonly main: LandedSha;79 readonly fork: RepoName;80 readonly base: CommitSha;81 readonly head: CommitSha;82}) =>83 Effect.gen(function* () {84 const base = yield* read(input.fork, input.base);85 const head = yield* read(input.fork, input.head);86 const main = yield* read(input.repo, input.main);87 const changes = changesOf(base, head);8889 // Main moved this path since the answer's base, to something else.90 const conflicts = changes.flatMap(({ path }) =>91 main.get(path)?.blob !== base.get(path)?.blob &&92 main.get(path)?.blob !== head.get(path)?.blob93 ? [path]94 : []95 );9697 if (Array.isReadonlyArrayNonEmpty(conflicts)) {98 return yield* new StaleBase({99 base: input.base,100 conflicts,101 main: input.main,102 });103 }104105 // Main's files, with each path the answer changed as the answer left it.106 const files = new Map(textOf(main));107108 for (const { path } of changes) {109 const text = head.get(path)?.text;110111 if (text === undefined) {112 files.delete(path);113 } else {114 files.set(path, text);115 }116 }117118 return { changes, files: files satisfies Files };119 });120121/** The files a landing's tree is rebuilt from. */122const rebuilt = (job: LandJob) =>123 Rebuild.$match(job.rebuild, {124 Compose: ({ files }) =>125 Effect.map(read(job.repo, job.main), (main) =>126 overlay(127 textOf(main),128 files.map(({ content, path }) => [path, content] as const)129 )130 ),131 Existing: ({ commit }) => Effect.map(read(job.repo, commit), textOf),132 Merge: ({ base, fork, head }) =>133 Effect.map(134 merged({ base, fork, head, main: job.main, repo: job.repo }),135 ({ files }) => files136 ),137 });138139/** The commit an answer's landing was made on: its base; otherwise main. */140const baseOf = (job: LandJob) =>141 Rebuild.$is("Merge")(job.rebuild) ? job.rebuild.base : job.main;142143/** The Lander over the memory repo host, landing at the world's clock. */144export const DevLander: Layer.Layer<Lander, never, RepoHost> = Layer.effect(145 Lander,146 Effect.gen(function* () {147 const host = yield* RepoHost;148 const provided = Effect.provideService(RepoHost, host);149150 // A request landed before: its commit, so a second land returns it.151 const landedBy = yield* Ref.make<ReadonlyMap<string, LandedSha>>(new Map());152153 const tipOf = (repo: RepoName, ref: RefName) =>154 host.refs(repo).pipe(155 Effect.map((refs) => Option.fromNullishOr(refs.get(ref))),156 Effect.mapError(blocked)157 );158159 const land = (job: LandJob) =>160 Effect.gen(function* () {161 const before = (yield* Ref.get(landedBy)).get(job.requestId);162163 if (before !== undefined) {164 return { pending: [], sha: before };165 }166167 const tip = yield* tipOf(job.repo, mainRef);168169 if (!Option.contains(tip, job.main)) {170 return yield* new StaleBase({171 base: baseOf(job),172 conflicts: [],173 main: Option.getOrElse(tip, () => job.main),174 });175 }176177 const into = yield* scratch;178 const tree = yield* into.tree(yield* rebuilt(job));179180 if (TreeSha.make(tree) !== job.tree) {181 return yield* blocked();182 }183184 const commit = yield* into.commit({185 at: yield* DateTime.now,186 author: personIdentity(job.author),187 committer: platformIdentity,188 message: job.message,189 parents: [job.main],190 tree,191 });192193 // Never forced: if main moved since `job.main`, the push is refused.194 const [outcome] = yield* host195 .push(job.repo, into.source, [196 { from: Option.some(job.main), ref: mainRef, to: commit },197 ])198 .pipe(199 Effect.catchTags({200 HostBusy: () => Effect.fail(new RepoBusy({})),201 RepoNotFound: () => Effect.fail(blocked()),202 })203 );204205 if (outcome === undefined || !RefOutcome.$is("Updated")(outcome)) {206 return yield* new StaleBase({207 base: baseOf(job),208 conflicts: [],209 main: job.main,210 });211 }212213 const sha = LandedSha.make(commit);214215 yield* Ref.update(landedBy, (all) =>216 new Map(all).set(job.requestId, sha)217 );218219 // The mirror follows main in a push of its own (ADR 0005).220 const mirror = yield* tipOf(job.repo, landedRef);221222 yield* host223 .push(job.repo, into.source, [224 { from: mirror, ref: landedRef, to: commit },225 ])226 .pipe(Effect.ignore);227228 return { pending: [], sha };229 });230231 return Lander.of({232 bundleRules: ({ at, repo }) =>233 provided(234 Effect.map(read(repo, at), (files) => ({235 entry: `${Brand.configDir}/project.ts`,236 modules: Object.fromEntries(237 [...textOf(files)].filter(([path]) =>238 path.startsWith(`${Brand.configDir}/`)239 )240 ),241 sdkVersion,242 }))243 ),244 compose: ({ files, main, repo }) =>245 provided(246 Effect.gen(function* () {247 const onMain = yield* read(repo, main);248 const into = yield* scratch;249250 const tree = yield* into.tree(251 overlay(252 textOf(onMain),253 files.map(({ content, path }) => [path, content] as const)254 )255 );256257 const commit = yield* into.commit({258 at: yield* DateTime.now,259 author: platformIdentity,260 committer: platformIdentity,261 message: "Compose files onto main for a check",262 parents: [main],263 tree,264 });265266 const ref = composeRef(TreeSha.make(tree));267 const existing = yield* tipOf(repo, ref);268269 if (!Option.contains(existing, commit)) {270 yield* host271 .push(repo, into.source, [{ from: existing, ref, to: commit }])272 .pipe(Effect.mapError(blocked));273 }274275 return { commit, tree: TreeSha.make(tree) };276 })277 ),278 land: (job) => provided(land(job)),279 merge: (job) =>280 provided(281 Effect.gen(function* () {282 const { changes, files } = yield* merged(job);283 const into = yield* scratch;284285 return { changes, tree: TreeSha.make(yield* into.tree(files)) };286 })287 ),288 });289 })290);