Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HandoffGit.ts

449 lines17.3 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Path from "effect/Path";
6import * as Schema from "effect/Schema";
7import * as Semaphore from "effect/Semaphore";
8​
9import { branchNameFromHeadRef } from "../../vcs/gitRefs.ts";
10import * as VcsProcess from "../../vcs/VcsProcess.ts";
11​
12/** A bundle larger than one upload can carry is refused; push the branch first. */
13export const MAX_HANDOFF_BUNDLE_BYTES = 50 * 1024 * 1024;
14​
15/** The work a thread hands off: its branch tip and the working tree on top of it. */
16export interface HandoffPackage {
17 /** The git bundle: commits not on any remote, plus the snapshot commit. */
18 readonly bundlePath: string;
19 readonly bundleBytes: number;
20 /** The branch the work is on, or null for a detached checkout. */
21 readonly branch: string | null;
22 /** The branch tip. The thread's committed work ends here. */
23 readonly tip: string;
24 /** A commit on top of `tip` holding the working tree, untracked files included. */
25 readonly snapshot: string;
26 /** The remote commit the bundle builds on, for a peer to fetch when it lacks it. */
27 readonly baseRemoteUrl: string | null;
29​
30/** `cwd` has no commit to hand off. */
31export class HandoffNotARepositoryError extends Schema.TaggedError<HandoffNotARepositoryError>()(
32 "HandoffNotARepositoryError",
33 { cwd: Schema.String },
34) {
35 override get message(): string {
36 return `${this.cwd} is not a git checkout with a commit.`;
37 }
39​
40/** The unpushed work is more than one upload carries. */
41export class HandoffTooLargeError extends Schema.TaggedError<HandoffTooLargeError>()(
42 "HandoffTooLargeError",
43 { bundleBytes: Schema.Number },
44) {
45 override get message(): string {
46 return `The unpushed work is ${Math.ceil(this.bundleBytes / 1024 / 1024)} MiB, over the ${MAX_HANDOFF_BUNDLE_BYTES / 1024 / 1024} MiB a handoff carries. Push the branch, then hand off again.`;
47 }
49​
50/** The checkout here lacks the commits the bundle builds on, even after fetching. */
51export class HandoffMissingBaseError extends Schema.TaggedError<HandoffMissingBaseError>()(
52 "HandoffMissingBaseError",
53 {},
54) {
55 override get message(): string {
56 return "This checkout lacks the commits the handoff builds on, even after fetching. Push the branch where it came from, then hand off again.";
57 }
59​
60/** The branch is checked out in another worktree here, at another commit. */
61export class HandoffBranchCheckedOutError extends Schema.TaggedError<HandoffBranchCheckedOutError>()(
62 "HandoffBranchCheckedOutError",
63 { branch: Schema.String },
64) {
65 override get message(): string {
66 return `${this.branch} is checked out in another worktree here and differs. Switch that checkout off it, then hand off again.`;
67 }
69​
70/** The branch here has commits the handed-off work lacks. */
71export class HandoffBranchDivergedError extends Schema.TaggedError<HandoffBranchDivergedError>()(
72 "HandoffBranchDivergedError",
73 { branch: Schema.String },
74) {
75 override get message(): string {
76 return `${this.branch} here has commits the handed-off work lacks. Reconcile the branches, then hand off again.`;
77 }
79​
80/**
81 * A git step failed, or left something other than what the handoff needs.
82 * `step` says which; the git failure, when there is one, is the cause.
83 */
84export class HandoffGitStepError extends Schema.TaggedError<HandoffGitStepError>()(
85 "HandoffGitStepError",
86 {
87 step: Schema.String,
88 detail: Schema.optional(Schema.String),
89 cause: Schema.optional(Schema.Defect()),
90 },
91) {
92 override get message(): string {
93 return this.detail ?? `git ${this.step} failed.`;
94 }
96​
97export type HandoffGitError =
98 | HandoffNotARepositoryError
99 | HandoffTooLargeError
100 | HandoffMissingBaseError
101 | HandoffBranchCheckedOutError
102 | HandoffBranchDivergedError
103 | HandoffGitStepError;
104​
105/**
106 * Moves a thread's git work as one bundle: commits no remote has, plus a snapshot commit of
107 * the working tree. Applying it touches only the checkout it creates, moves an existing
108 * branch only forward, and undoes what it did when a step fails.
109 */
110export class HandoffGit extends Context.Service<
111 HandoffGit,
112 {
113 /** Packages `cwd`'s branch and working tree into a bundle in `outDir`. */
114 readonly pack: (input: {
115 readonly cwd: string;
116 readonly handoffId: string;
117 readonly outDir: string;
118 }) => Effect.Effect<HandoffPackage, HandoffGitError>;
119 /**
120 * Applies a package in `repoRoot`: a new worktree at `worktreePath` on its
121 * branch, with the working tree as it was. Nothing is left behind on failure.
122 */
123 readonly apply: (input: {
124 readonly repoRoot: string;
125 readonly worktreePath: string;
126 readonly handoffId: string;
127 readonly bundlePath: string;
128 readonly branch: string | null;
129 readonly tip: string;
130 readonly snapshot: string;
131 }) => Effect.Effect<
132 /** `undo` takes the checkout and the branch change back out, for a caller that fails later. */
133 { readonly branch: string | null; readonly undo: Effect.Effect<void> },
134 HandoffGitError
135 >;
136 }
137>()("t3/peer/handoff/HandoffGit") {}
138​
139const IDENTITY = {
140 GIT_AUTHOR_NAME: "T3 Code",
141 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
142 GIT_COMMITTER_NAME: "T3 Code",
143 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
144};
145​
146const handoffRef = (handoffId: string, name: string) => `refs/t3code/handoff/${handoffId}/${name}`;
147​
148/**
149 * The checkout holds what another machine sent, and a repository can keep its hooks in the
150 * working tree (a relative `core.hooksPath`), so no hook may run on it.
151 */
152const NO_HOOKS = ["-c", "core.hooksPath=/dev/null"];
153​
154const make = Effect.gen(function* () {
155 const processes = yield* VcsProcess.VcsProcess;
156 const fileSystem = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158​
159 const git = (
160 cwd: string,
161 args: ReadonlyArray<string>,
162 options: {
163 readonly env?: NodeJS.ProcessEnv;
164 readonly allowNonZeroExit?: boolean;
165 readonly onStdoutChunk?: (chunk: Uint8Array) => void;
166 } = {},
167 ) =>
168 processes
169 .run({
170 operation: "HandoffGit",
171 command: "git",
172 cwd,
173 args,
174 timeoutMs: 120_000,
175 ...(options.env === undefined ? {} : { env: options.env }),
176 ...(options.onStdoutChunk === undefined ? {} : { onStdoutChunk: options.onStdoutChunk }),
177 ...(options.allowNonZeroExit === undefined
178 ? {}
179 : { allowNonZeroExit: options.allowNonZeroExit }),
180 })
181 .pipe(
182 Effect.mapError(
183 (cause) =>
184 new HandoffGitStepError({
185 step: (args[0] === "-c" ? args[2] : args[0]) ?? "git",
186 cause,
187 }),
188 ),
189 // The caller sees only the step; git's own reason goes to the log.
190 Effect.tapError((error) =>
191 Effect.logWarning("handoff-git.step-failed", { step: error.step, cause: error.cause }),
192 ),
193 );
194​
195 const out = (cwd: string, args: ReadonlyArray<string>) =>
196 git(cwd, args).pipe(Effect.map((result) => result.stdout.trim()));
197​
198 const ok = (cwd: string, args: ReadonlyArray<string>) =>
199 git(cwd, args, { allowNonZeroExit: true }).pipe(Effect.map((result) => result.exitCode === 0));
200​
201 const requirePortableTree = Effect.fn("HandoffGit.requirePortableTree")(function* (
202 cwd: string,
203 tree: string,
204 ) {
205 let hasSubmodule = false;
206 let partial = "";
207 yield* git(cwd, ["ls-tree", "-r", "--format=%(objectmode)", tree], {
208 onStdoutChunk: (chunk) => {
209 if (hasSubmodule) return;
210 const modes = (partial + Buffer.from(chunk).toString("ascii")).split("\n");
211 partial = modes.pop() ?? "";
212 hasSubmodule = modes.includes("160000");
213 },
214 });
215 if (hasSubmodule) {
216 return yield* new HandoffGitStepError({
217 step: "ls-tree",
218 detail: "Thread moves do not support repositories with Git submodules.",
219 });
220 }
221 const lfs = yield* git(
222 cwd,
223 [
224 "grep",
225 "--quiet",
226 "--all-match",
227 "--extended-regexp",
228 "-e",
229 "^version https://(git-lfs[.]github[.]com|hawser[.]github[.]com)/spec/v1$",
230 "-e",
231 "^oid sha256:[0-9a-f]{64}$",
232 "-e",
233 "^size [0-9]+$",
234 tree,
235 "--",
236 ],
237 { allowNonZeroExit: true },
238 );
239 if (lfs.exitCode !== 1) {
240 return yield* new HandoffGitStepError({
241 step: "grep",
242 detail:
243 lfs.exitCode === 0
244 ? "Thread moves do not support repositories with Git LFS files."
245 : "The checkout could not be checked for Git LFS files.",
246 });
247 }
248 });
249​
250 const pack: HandoffGit["Service"]["pack"] = Effect.fn("HandoffGit.pack")(function* (input) {
251 if (!(yield* ok(input.cwd, ["rev-parse", "--verify", "HEAD"]))) {
252 return yield* new HandoffNotARepositoryError({ cwd: input.cwd });
253 }
254 const tip = yield* out(input.cwd, ["rev-parse", "HEAD"]);
255 yield* requirePortableTree(input.cwd, tip);
256 const branchName = yield* git(input.cwd, ["symbolic-ref", "--quiet", "HEAD"], {
257 allowNonZeroExit: true,
258 });
259 const branch = branchName.exitCode === 0 ? branchNameFromHeadRef(branchName.stdout) : null;
260 const gitDir = yield* out(input.cwd, ["rev-parse", "--path-format=absolute", "--git-dir"]);
261 const indexPath = path.join(gitDir, `t3-handoff-index-${input.handoffId}`);
262 // The working tree as a commit on top of the tip, in a private index so
263 // the user's staging is untouched. Ignored files stay behind.
264 const snapshot = yield* Effect.gen(function* () {
265 const env = { GIT_INDEX_FILE: indexPath, ...IDENTITY };
266 yield* git(input.cwd, ["read-tree", "HEAD"], { env });
267 // `:/` is the whole working tree, wherever in it the thread's checkout sits.
268 yield* git(input.cwd, ["add", "--all", "--", ":/"], { env });
269 const tree = (yield* git(input.cwd, ["write-tree"], { env })).stdout.trim();
270 yield* requirePortableTree(input.cwd, tree);
271 return (yield* git(
272 input.cwd,
273 ["commit-tree", tree, "-p", tip, "-m", `T3 Code handoff ${input.handoffId}`],
274 { env },
275 )).stdout.trim();
276 }).pipe(
277 Effect.ensuring(
278 Effect.forEach([indexPath, `${indexPath}.lock`], (file) =>
279 fileSystem.remove(file, { force: true }).pipe(Effect.ignore),
280 ),
281 ),
282 );
283 const snapshotRef = handoffRef(input.handoffId, "snapshot");
284 yield* git(input.cwd, ["update-ref", snapshotRef, snapshot]);
285 const bundlePath = path.join(input.outDir, `${input.handoffId}.bundle`);
286 // Only what `origin` lacks: that is the one remote the peer fetches the rest from.
287 yield* git(input.cwd, [
288 "bundle",
289 "create",
290 bundlePath,
291 snapshotRef,
292 "--not",
293 "--remotes=origin",
294 ]).pipe(Effect.ensuring(git(input.cwd, ["update-ref", "-d", snapshotRef]).pipe(Effect.ignore)));
295 const bundleBytes = Number(
296 (yield* fileSystem.stat(bundlePath).pipe(
297 Effect.mapError(
298 (cause) =>
299 new HandoffGitStepError({
300 step: "bundle",
301 detail: "The bundle was not written.",
302 cause,
303 }),
304 ),
305 )).size,
306 );
307 if (bundleBytes > MAX_HANDOFF_BUNDLE_BYTES) {
308 yield* fileSystem.remove(bundlePath, { force: true }).pipe(Effect.ignore);
309 return yield* new HandoffTooLargeError({ bundleBytes });
310 }
311 const remote = yield* git(input.cwd, ["remote", "get-url", "origin"], {
312 allowNonZeroExit: true,
313 });
314 return {
315 bundlePath,
316 bundleBytes,
317 branch,
318 tip,
319 snapshot,
320 baseRemoteUrl: remote.exitCode === 0 ? remote.stdout.trim() : null,
321 };
322 });
323​
324 // One apply at a time: two racing for a path would each see it free, and the loser's
325 // forced cleanup would take the winner's checkout.
326 const applying = yield* Semaphore.make(1);
327 const apply: HandoffGit["Service"]["apply"] = Effect.fn("HandoffGit.apply")(function* (input) {
328 const fetched = handoffRef(input.handoffId, "snapshot");
329 const undo: Array<Effect.Effect<void>> = [];
330 // Read when it runs: the steps are pushed as the apply goes.
331 const rollback = Effect.suspend(() =>
332 Effect.forEach(undo.toReversed(), (step) => step, { discard: true }),
333 );
334 return yield* Effect.gen(function* () {
335 // The bundle builds on commits the remote has; fetch them if missing.
336 if (!(yield* ok(input.repoRoot, ["bundle", "verify", input.bundlePath]))) {
337 yield* git(input.repoRoot, ["fetch", "--quiet", "origin"], { allowNonZeroExit: true });
338 if (!(yield* ok(input.repoRoot, ["bundle", "verify", input.bundlePath]))) {
339 return yield* new HandoffMissingBaseError();
340 }
341 }
342 yield* git(input.repoRoot, [
343 "fetch",
344 "--quiet",
345 "--no-tags",
346 input.bundlePath,
347 `${handoffRef(input.handoffId, "snapshot")}:${fetched}`,
348 ]);
349 undo.push(git(input.repoRoot, ["update-ref", "-d", fetched]).pipe(Effect.ignore));
350 if ((yield* out(input.repoRoot, ["rev-parse", fetched])) !== input.snapshot) {
351 return yield* new HandoffGitStepError({
352 step: "fetch",
353 detail: "The bundle does not hold the snapshot it was sent with.",
354 });
355 }
356 // The snapshot is the working tree on top of the tip, and of nothing else.
357 const lineage = yield* out(input.repoRoot, ["rev-list", "--parents", "-n", "1", fetched]);
358 if (lineage !== `${input.snapshot} ${input.tip}`) {
359 return yield* new HandoffGitStepError({
360 step: "fetch",
361 detail: "The snapshot was not made on the commit it was sent with.",
362 });
363 }
364 yield* requirePortableTree(input.repoRoot, input.snapshot);
365 // The branch here may only move forward to the tip, and only when no
366 // checkout has it, so nobody's work is overwritten.
367 let branch = input.branch;
368 if (branch !== null) {
369 const ref = `refs/heads/${branch}`;
370 const existing = yield* git(input.repoRoot, ["rev-parse", "--verify", "--quiet", ref], {
371 allowNonZeroExit: true,
372 });
373 if (existing.exitCode === 0) {
374 const current = existing.stdout.trim();
375 const worktrees = yield* git(input.repoRoot, ["worktree", "list", "--porcelain"]);
376 const checkedOut = worktrees.stdout.split("\n").some((line) => line === `branch ${ref}`);
377 if (checkedOut && current !== input.tip) {
378 return yield* new HandoffBranchCheckedOutError({ branch });
379 }
380 if (current !== input.tip) {
381 if (!(yield* ok(input.repoRoot, ["merge-base", "--is-ancestor", current, input.tip]))) {
382 return yield* new HandoffBranchDivergedError({ branch });
383 }
384 // Compare-and-swap: fails if the branch moved since it was read.
385 yield* git(input.repoRoot, ["update-ref", ref, input.tip, current]);
386 undo.push(
387 git(input.repoRoot, ["update-ref", ref, current, input.tip]).pipe(Effect.ignore),
388 );
389 }
390 if (checkedOut) branch = null;
391 } else {
392 yield* git(input.repoRoot, ["update-ref", ref, input.tip, ""]);
393 // Only while it is still the tip: a branch someone moved on since keeps their commits.
394 undo.push(git(input.repoRoot, ["update-ref", "-d", ref, input.tip]).pipe(Effect.ignore));
395 }
396 }
397 // The removal below is forced, so it must never meet a checkout that was already there.
398 if (yield* fileSystem.exists(input.worktreePath).pipe(Effect.orElseSucceed(() => true))) {
399 return yield* new HandoffGitStepError({
400 step: "worktree",
401 detail: "A checkout already sits where this one would go.",
402 });
403 }
404 // Registered first: a failing post-checkout hook leaves the worktree behind.
405 undo.push(
406 git(input.repoRoot, ["worktree", "remove", "--force", input.worktreePath]).pipe(
407 Effect.ignore,
408 ),
409 );
410 yield* git(input.repoRoot, [
411 ...NO_HOOKS,
412 ...(branch === null
413 ? ["worktree", "add", "--detach", input.worktreePath, input.tip]
414 : ["worktree", "add", input.worktreePath, branch]),
415 ]);
416 // The working tree as it was, untracked files included, then the
417 // index back on the tip so the changes show as uncommitted.
418 // The branch may have moved between the check above and the checkout.
419 if ((yield* out(input.worktreePath, ["rev-parse", "HEAD"])) !== input.tip) {
420 return yield* new HandoffGitStepError({
421 step: "worktree",
422 detail: "The branch moved while the handed-off work was being checked out.",
423 });
424 }
425 // A sparse checkout would otherwise leave out handed-off files outside its patterns.
426 yield* git(input.worktreePath, [
427 ...NO_HOOKS,
428 "checkout",
429 "--no-overlay",
430 "--ignore-skip-worktree-bits",
431 input.snapshot,
432 "--",
433 ".",
434 ]);
435 // By path, so the index is reset without writing the branch someone may have moved since.
436 yield* git(input.worktreePath, [...NO_HOOKS, "reset", "--quiet", input.tip, "--", "."]);
437 yield* git(input.repoRoot, ["update-ref", "-d", fetched]).pipe(Effect.ignore);
438 return { branch, undo: rollback };
439 // An interrupted apply is taken back like a failed one.
440 }).pipe(
441 Effect.onError(() => rollback),
442 applying.withPermits(1),
443 );
444 });
445​
446 return HandoffGit.of({ pack, apply });
447});
448​
449export const layer = Layer.effect(HandoffGit, make);