diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 78a436a1424e4..78383768a73e0 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- skipIf needs to know synchronously whether git-lfs is installed. +import * as NodeChildProcess from "node:child_process"; import * as NodeNet from "node:net"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; @@ -14,6 +16,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as PlatformError from "effect/PlatformError"; import { ChildProcessSpawner } from "effect/process"; import * as Metric from "effect/Metric"; @@ -369,6 +372,134 @@ it.effect.each(["interrupt", "timeout", "success"] as const)( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +const gitLfsAvailable = NodeChildProcess.spawnSync("git", ["lfs", "version"]).status === 0; + +// git-lfs runs extension commands without a shell, so it needs git-lfs and POSIX paths. +for (const stop of ["interrupt", "timeout"] as const) + it.effect.skipIf(!gitLfsAvailable || HostProcess.Platform.defaultValue() === "win32")( + `checkpoint staging stopped by ${stop} strands no Git LFS temp file and spares another writer's`, + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + // Windows hosts without symlink rights must get the same isolation. + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + symlink: () => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "symlink", + }), + ), + }), + ); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-lfs-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* git(["lfs", "install", "--local"]); + const lfsDir = path.join(cwd, ".git/lfs"); + yield* fs.makeDirectory(path.join(lfsDir, "objects"), { recursive: true }); + + // git-lfs creates its temp file before it starts an extension, so an extension that waits + // on this socket holds the clean filter mid-file until the socket ends or it is killed. + const barriers = yield* Queue.unbounded(); + const server = yield* Effect.acquireRelease( + Effect.sync(() => + NodeNet.createServer((socket) => { + socket.resume(); + Queue.offerUnsafe(barriers, socket); + }), + ), + (server) => Effect.sync(() => server.close()), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }), + ); + const address = server.address(); + if (address === null || typeof address === "string") return yield* Effect.die("no port"); + const extension = path.join(sandbox, "barrier.cjs"); + yield* fs.writeFileString( + extension, + `const s = require('node:net').connect(${address.port}, '127.0.0.1'); +s.resume(); +s.on('end', () => process.stdin.pipe(process.stdout));`, + ); + yield* git([ + "config", + "lfs.extension.barrier.clean", + `${process.execPath} ${extension} %f`, + ]); + yield* git(["config", "lfs.extension.barrier.smudge", "cat"]); + yield* git(["config", "lfs.extension.barrier.priority", "0"]); + yield* fs.writeFileString( + path.join(cwd, ".gitattributes"), + "*.bin filter=lfs diff=lfs merge=lfs -text\n", + ); + yield* fs.writeFileString(path.join(cwd, "asset.bin"), "untracked asset\n"); + yield* fs.writeFileString(path.join(cwd, "external.bin"), "another writer's asset\n"); + + const fiber = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Queue.take(barriers).pipe( + Effect.raceFirst( + Fiber.join(fiber).pipe( + Effect.andThen(Effect.die("capture ended before the LFS extension started")), + ), + ), + ); + // A git-lfs writer outside T3 holds its own temp file in the shared lfs/tmp meanwhile. + const external = NodeChildProcess.spawn("git", ["add", "external.bin"], { + cwd, + stdio: "ignore", + }); + const externalExit = new Promise((resolve) => + external.once("exit", resolve), + ); + const externalBarrier = yield* Queue.take(barriers); + if (stop === "interrupt") yield* Fiber.interrupt(fiber); + else yield* TestClock.adjust("30 seconds"); + const result = yield* Fiber.await(fiber); + if (stop === "interrupt") + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + else { + const error = + Exit.isSuccess(result) && Exit.isFailure(result.value) + ? Cause.findErrorOption(result.value.cause) + : Option.none(); + assert.isTrue(Option.isSome(error) && error.value._tag === "VcsProcessTimeoutError"); + } + const lfsEntries = Effect.all([ + Effect.map(fs.readDirectory(lfsDir), (names) => names.toSorted()), + Effect.map(fs.readDirectory(path.join(lfsDir, "tmp")), (names) => names.length), + ]); + assert.deepEqual(yield* lfsEntries, [["objects", "tmp"], 1]); + + // The other writer stays stalled through a later capture, however long it waits. + yield* git(["config", "lfs.extension.barrier.clean", "cat"]); + yield* TestClock.adjust("1 hour"); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + assert.deepEqual(yield* lfsEntries, [["objects", "tmp"], 1]); + externalBarrier.end(); + assert.strictEqual(yield* Effect.promise(() => externalExit), 0); + assert.deepEqual(yield* lfsEntries, [["objects", "tmp"], 0]); + const pointer = (yield* git(["show", `${checkpointRef}:asset.bin`])).stdout; + const oid = /oid sha256:([0-9a-f]{64})/.exec(pointer)?.[1]; + if (oid === undefined) return assert.fail(`not an LFS pointer: ${pointer}`); + assert.isTrue( + yield* fs.exists(path.join(lfsDir, "objects", oid.slice(0, 2), oid.slice(2, 4), oid)), + ); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), + ); + it.effect.each(["failure", "interrupt"] as const)( "checkpoint publication $0 preserves existing refs and permits retry", (stop) => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 56b4b44d0156e..382eee566061f 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -666,6 +666,9 @@ const gitSupportsRemergeDiff = (versionOutput: string): boolean => { return major > 2 || (major === 2 && Number(match[2]) >= 36); }; +// git-lfs stores each object at objects///. +const LFS_OBJECT_PATH = /^[0-9a-f]{2}[\\/][0-9a-f]{2}[\\/][0-9a-f]{64}$/; + export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -1259,6 +1262,56 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ), ), ); + // A stopped add strands git-lfs's copy in lfs/tmp, which other git-lfs writers share, so this + // capture gives git-lfs its own storage and moves the objects it wrote out once staging succeeds. + const lfsObjects = path.join(gitCommonDir, "lfs", "objects"); + const privateLfsStorage = yield* Effect.gen(function* () { + if (!(yield* fileSystem.exists(lfsObjects))) return undefined; + const configuredStorage = yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--get", "lfs.storage"], + allowNonZeroExit: true, + }); + if (configuredStorage.stdout.trim() !== "") return undefined; + const directory = yield* Effect.acquireRelease( + fileSystem.makeTempDirectory({ + directory: path.dirname(lfsObjects), + prefix: "t3-checkpoint-", + }), + (directory) => + fileSystem.remove(directory, { recursive: true, force: true }).pipe( + Effect.catch((cause) => + Effect.logWarning("Could not remove private checkpoint LFS storage", { + reason: cause.reason._tag, + }), + ), + ), + ); + return directory; + }).pipe(Effect.orElseSucceed(() => undefined)); + const publishLfsObjects = Effect.fn("GitVcsDriver.publishLfsObjects")( + function* (storage: string) { + const objects = path.join(storage, "objects"); + const entries = yield* fileSystem.readDirectory(objects, { recursive: true }).pipe( + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + (): Effect.Effect> => Effect.succeed([]), + ), + ); + for (const entry of entries) { + if (!LFS_OBJECT_PATH.test(entry)) continue; + const target = path.join(lfsObjects, entry); + if (yield* fileSystem.exists(target)) continue; + yield* fileSystem.makeDirectory(path.dirname(target), { recursive: true }); + yield* fileSystem.rename(path.join(objects, entry), target); + } + }, + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ operation, cwd: input.cwd, stage: "publish", cause }), + ), + ); const commitEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: tempIndexPath, GIT_OBJECT_DIRECTORY: privateObjects, @@ -1538,6 +1591,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( // safecrlf=true refuses LF files under CRLF conversion; capture them as Git's default does. "-c", "core.safecrlf=false", + ...(privateLfsStorage === undefined + ? [] + : ["-c", `lfs.storage=${privateLfsStorage}`]), "add", // Unreadable files keep their indexed version and unreadable new files are left out. ...(ignoreErrors ? ["--ignore-errors"] : []), @@ -1616,6 +1672,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }), ); + if (privateLfsStorage !== undefined) yield* publishLfsObjects(privateLfsStorage); + const stagingMs = (yield* Clock.currentTimeMillis) - stagingAt; const writeTreeResult = yield* execute({