diff --git a/packages/studio-server/src/history/blobStore.test.ts b/packages/studio-server/src/history/blobStore.test.ts index 707dfe716b..30007b15e5 100644 --- a/packages/studio-server/src/history/blobStore.test.ts +++ b/packages/studio-server/src/history/blobStore.test.ts @@ -21,6 +21,7 @@ vi.mock("node:fs/promises", async (importOriginal) => { rename: vi.fn(actual.rename), copyFile: vi.fn(actual.copyFile), open: vi.fn(actual.open), + rm: vi.fn(actual.rm), }; }); @@ -33,6 +34,7 @@ const { rename: realRename, copyFile: realCopyFile, open: realOpen, + rm: realRm, } = await vi.importActual("node:fs/promises"); const busy = () => Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }); const platform = process.platform; @@ -225,6 +227,115 @@ describe("the history store's count of what it holds", () => { }); }); +describe("a pinned copy", () => { + it("survives every prune from the moment it is filed until it is unpinned", async () => { + const root = mkdtempSync(join(tmpdir(), "hf-blob-pin-")); + try { + const small = join(root, "small.txt"); + const large = join(root, "large.txt"); + writeFileSync(small, "pinned bytes"); + writeFileSync(large, "y".repeat(200 * 1024)); + const store = await openBlobStore(join(root, "history", "blobs")); + const hashes = [await store.put(small, true), await store.put(large, true)]; + await store.prune(new Set()); + for (const hash of hashes) expect(store.has(hash!)).toBe(true); + for (const hash of hashes) store.unpin(hash!); + await store.prune(new Set()); + for (const hash of hashes) expect(store.has(hash!)).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("pins a copy whose bytes the store already holds, and keeps it until each pin is let go", async () => { + const root = mkdtempSync(join(tmpdir(), "hf-blob-pin-")); + try { + const file = join(root, "same.txt"); + writeFileSync(file, "same bytes"); + const store = await openBlobStore(join(root, "history", "blobs")); + const hash = (await store.put(file))!; + await store.put(file, true); + await store.put(file, true); + store.unpin(hash); + await store.prune(new Set()); + expect(store.has(hash)).toBe(true); + store.unpin(hash); + await store.prune(new Set()); + expect(store.has(hash)).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); + +describe("a pinned copy filed while its hash is pruned", () => { + afterEach(() => { + vi.mocked(fsp.rm).mockImplementation(realRm); + vi.mocked(fsp.open).mockImplementation(realOpen); + }); + + it("is filed again after the delete, never deleted after it is pinned", async () => { + const root = mkdtempSync(join(tmpdir(), "hf-blob-pin-")); + try { + const file = join(root, "same.txt"); + writeFileSync(file, "same bytes"); + const blobs = join(root, "history", "blobs"); + const store = await openBlobStore(blobs); + const hash = (await store.put(file))!; + let release = () => {}; + const held = new Promise((resolve) => (release = resolve)); + let deleting = 0; + vi.mocked(fsp.rm).mockImplementation(async (...args: Parameters) => { + if (String(args[0]).endsWith(hash)) { + deleting += 1; + await held; + } + return realRm(...args); + }); + let read = false; + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + const handle = await realOpen(...args); + if (String(args[0]) !== file) return handle; + const close = handle.close.bind(handle); + handle.close = async () => { + await close(); + read = true; + }; + return handle; + }); + const pruned = store.prune(new Set()); + await vi.waitFor(() => expect(deleting).toBe(1)); + const pinned = store.put(file, true); + // The put has read its bytes and come to the store while the delete is still under way. + await vi.waitFor(() => expect(read).toBe(true)); + release(); + await Promise.all([pruned, pinned]); + expect(store.has(hash)).toBe(true); + await expect(readBlob(blobs, hash)).resolves.toEqual(Buffer.from("same bytes")); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("takes no pin when the duplicate it staged cannot be removed", async () => { + const root = mkdtempSync(join(tmpdir(), "hf-blob-pin-")); + try { + const large = join(root, "large.txt"); + writeFileSync(large, "z".repeat(200 * 1024)); + const store = await openBlobStore(join(root, "history", "blobs")); + await store.put(large); + vi.mocked(fsp.rm).mockImplementation(async (...args: Parameters) => { + if (String(args[0]).includes("incoming-")) throw busy(); + return realRm(...args); + }); + await expect(store.put(large, true)).rejects.toThrow("EPERM"); + expect([...store.pinned()]).toEqual([]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); + describe("a file written to while the history reads it", () => { let root: string; beforeEach(() => { diff --git a/packages/studio-server/src/history/blobStore.ts b/packages/studio-server/src/history/blobStore.ts index 48189fae6f..51098b73fd 100644 --- a/packages/studio-server/src/history/blobStore.ts +++ b/packages/studio-server/src/history/blobStore.ts @@ -22,7 +22,9 @@ import { assertLandedIn, assertStillWithin, folderWithin } from "./containedPath /** File contents stored once by sha256, text and binary alike. */ export interface BlobStore { /** Copies the file in (cloned where it can) and returns its hash; null while it keeps changing. */ - put(absPath: string): Promise; + put(absPath: string, pin?: boolean, onRead?: () => void): Promise; + unpin(hash: string): void; + pinned(): Iterable; reference(absPath: string): Promise; has(hash: string): boolean; read(hash: string): Promise; @@ -75,13 +77,17 @@ export async function hashFile(path: string): Promise { async function readIfSmall( path: string, + onRead: () => void, ): Promise<{ bytes: Buffer; mode: number; moved: boolean } | null> { const handle = await open(path, "r"); try { const before = await handle.stat(); if (before.size > READ_ONCE_AT_MOST_BYTES) return null; const bytes = await handle.readFile(); - return { bytes, mode: before.mode, moved: !unchanged(before, await handle.stat()) }; + const moved = !unchanged(before, await handle.stat()); + // At the read itself, not after the close, which a slow drive can hold. + if (!moved) onRead(); + return { bytes, mode: before.mode, moved }; } finally { await handle.close(); } @@ -194,11 +200,23 @@ export async function openBlobStore(dir: string): Promise { for (const hash of asideSizes.keys()) holds.set(hash, new Set(["*"])); const pathOf = (hash: string) => blobPath(sizes.has(hash) ? dir : asideDir, hash); let total = [...sizes.values()].reduce((sum, size) => sum + size, 0); - const forget = async (hash: string) => { - await rm(blobPath(dir, hash), { force: true }); - total -= sizes.get(hash) ?? 0; - sizes.delete(hash); + const pins = new Map(); + const pin = (hash: string) => pins.set(hash, (pins.get(hash) ?? 0) + 1); + const turns = new Map>(); + const inTurn = (hash: string, step: () => Promise): Promise => { + const done = (turns.get(hash) ?? Promise.resolve()).then(step, step); + const tail = done.catch(() => {}); + turns.set(hash, tail); + void tail.then(() => turns.get(hash) === tail && turns.delete(hash)); + return done; }; + const forget = (hash: string) => + inTurn(hash, async () => { + if (pins.has(hash) || !sizes.has(hash)) return; + await rm(blobPath(dir, hash), { force: true }); + total -= sizes.get(hash) ?? 0; + sizes.delete(hash); + }); const forgetAside = async (hash: string) => { await rm(blobPath(asideDir, hash), { force: true }); asideSizes.delete(hash); @@ -216,9 +234,12 @@ export async function openBlobStore(dir: string): Promise { await write(); }); // The bytes hashed are the bytes filed, so a write racing the read can never file bytes under the wrong hash. - const putBytes = async (bytes: Buffer, mode: number) => { + const putBytes = async (bytes: Buffer, mode: number, pinned: boolean) => { const hash = sha256(bytes); - if (sizes.has(hash)) return hash; + return inTurn(hash, () => filedBytes(hash, bytes, mode, pinned)); + }; + const filedBytes = async (hash: string, bytes: Buffer, mode: number, pinned: boolean) => { + if (sizes.has(hash)) return pinned ? (pin(hash), hash) : hash; const temp = join(dir, `incoming-${randomUUID()}`); try { await withFolderMadeIfMissing(dir, () => writeFile(temp, bytes, { mode })); @@ -231,12 +252,18 @@ export async function openBlobStore(dir: string): Promise { throw error; } file(hash, bytes.length); + if (pinned) pin(hash); return hash; }; - const putIfUnchanged = async (absPath: string): Promise => { - const small = await readIfSmall(absPath); - if (small) return small.moved ? null : putBytes(small.bytes, small.mode); + const putIfUnchanged = async ( + absPath: string, + pinned: boolean, + onRead: () => void, + ): Promise => { + const small = await readIfSmall(absPath, onRead); + if (small?.moved) return null; + if (small) return putBytes(small.bytes, small.mode, pinned); // Hash the copy, not the source, so a write racing the copy can never file bytes under the wrong hash. const temp = join(dir, `incoming-${randomUUID()}`); // Recreated if removed while open, so a missing folder is never mistaken for a deleted project file. @@ -252,22 +279,27 @@ export async function openBlobStore(dir: string): Promise { await rm(temp, { force: true }); return null; } + onRead(); const hash = await hashFile(temp); - if (sizes.has(hash)) { - await rm(temp, { force: true }); + return inTurn(hash, async () => { + if (sizes.has(hash)) { + await rm(temp, { force: true }); + if (pinned) pin(hash); + return hash; + } + await mkdir(dirname(blobPath(dir, hash)), { recursive: true }); + const size = (await stat(temp)).size; + await renameWithRetryAsync(temp, blobPath(dir, hash)); + file(hash, size); + if (pinned) pin(hash); return hash; - } - await mkdir(dirname(blobPath(dir, hash)), { recursive: true }); - const size = (await stat(temp)).size; - await renameWithRetryAsync(temp, blobPath(dir, hash)); - file(hash, size); - return hash; + }); }; return { - async put(absPath) { + async put(absPath, pinned = false, onRead = () => {}) { for (let read = 0; read < READS_BEFORE_LEAVING_IT; read += 1) { - const hash = await putIfUnchanged(absPath); + const hash = await putIfUnchanged(absPath, pinned, onRead); if (hash !== null) return hash; } return null; @@ -314,6 +346,12 @@ export async function openBlobStore(dir: string): Promise { async drop(hashes) { for (const hash of hashes) if (sizes.has(hash)) await forget(hash); }, + unpin(hash) { + const left = (pins.get(hash) ?? 0) - 1; + if (left > 0) pins.set(hash, left); + else pins.delete(hash); + }, + pinned: () => pins.keys(), async prune(keep) { for (const hash of [...sizes.keys()]) if (!keep.has(hash)) await forget(hash); for (const hash of [...asideSizes.keys()]) if (!keep.has(hash)) await forgetAside(hash); diff --git a/packages/studio-server/src/history/firstCopy.test.ts b/packages/studio-server/src/history/firstCopy.test.ts index 89e11e166d..b985128913 100644 --- a/packages/studio-server/src/history/firstCopy.test.ts +++ b/packages/studio-server/src/history/firstCopy.test.ts @@ -10,23 +10,26 @@ import { readFileSync, rmSync, statSync, + appendFileSync, + truncateSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, sep } from "node:path"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; vi.mock("node:fs/promises", async (importOriginal) => { const actual = await importOriginal(); - return { ...actual, writeFile: vi.fn(actual.writeFile) }; + return { ...actual, writeFile: vi.fn(actual.writeFile), open: vi.fn(actual.open) }; }); import * as fsp from "node:fs/promises"; +import { fileContentVersion, recordFileWriteReceipt } from "../helpers/fileVersion.js"; import { blobPath } from "./blobStore.js"; import { START } from "./historyLog.js"; import { openProjectHistory } from "./projectHistory.js"; -const { writeFile: realWriteFile } = +const { writeFile: realWriteFile, open: realOpen } = await vi.importActual("node:fs/promises"); const sha256 = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex"); const temps: string[] = []; @@ -39,6 +42,7 @@ const closes: (() => Promise)[] = []; afterEach(async () => { vi.mocked(fsp.writeFile).mockImplementation(realWriteFile); + vi.mocked(fsp.open).mockImplementation(realOpen); for (const close of closes.splice(0)) await close(); for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }); }); @@ -73,6 +77,39 @@ function expectAllKept( expect(readFileSync(blobPath(blobs, sha256(bytes))).equals(bytes)).toBe(true); } } +/** The first filing of `bytes` into the blob store waits until released. */ +function holdFiling(bytes: Buffer): { release: () => void; reached: Promise } { + const releases: (() => void)[] = []; + let reach = () => {}; + const reached = new Promise((held) => (reach = held)); + vi.mocked(fsp.writeFile).mockImplementation(async (...args: Parameters) => { + const [to, written] = args; + if (!releases.length && String(to).includes("incoming-") && bytes.equals(written as Buffer)) { + const wait = new Promise((answer) => releases.push(answer)); + reach(); + await wait; + } + return realWriteFile(...args); + }); + const release = () => releases.forEach((answer) => answer()); + closes.push(async () => release()); + return { release, reached }; +} + +const saveReceipt = (absPath: string, bytes: string, overwrote: string) => + recordFileWriteReceipt(absPath, { + path: "parts/p0.js", + version: fileContentVersion(bytes), + writeToken: "studio", + overwrote, + }); + +/** Every first copy is recorded: nothing is named as still being adopted. */ +const adopted = (historyRoot: string) => + vi.waitFor(() => expect(existsSync(join(homeIn(historyRoot), "adopting.json"))).toBe(false), { + timeout: 10_000, + }); + const pathsOf = (count: number) => [ "index.html", ...Array.from({ length: count }, (_, i) => `parts/p${i}.js`), @@ -145,4 +182,436 @@ describe("a project's first history copy", () => { expect(most).toBeGreaterThan(1); expect(most).toBeLessThanOrEqual(4); }); + + // fails without the fix: a file whose read never answered held the first copy, so the project never opened. + it("leaves a file whose read never answers owed past its deadline, and the open finishes", async () => { + const projectDir = projectOf(6, "stuck"); + const stuck = join(projectDir, "parts", "p1.js"); + const releases: (() => void)[] = []; + let stuckReads = 0; + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + if (String(args[0]) === stuck) { + stuckReads += 1; + await new Promise((answer) => releases.push(answer)); + } + return realOpen(...args); + }); + const historyRoot = tempDir("hf-first-copy-root-"); + try { + const history = await openProjectHistory({ projectDir, historyRoot, firstCopyFileMs: 100 }); + closes.push(() => history.close()); + expect(stuckReads).toBe(1); + const owed = JSON.parse(readFileSync(join(homeIn(historyRoot), "adopting.json"), "utf8")); + expect(owed).toContain("parts/p1.js"); + } finally { + for (const answer of releases) answer(); + } + }); + + it("gives a queued first copy its deadline from when its read starts", async () => { + // Nine reads of 150 ms through four slots: the last round ends at 450 ms, each read well within 400 ms. + const projectDir = projectOf(9, "queued"); + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + if (String(args[0]).startsWith(projectDir)) + await new Promise((later) => setTimeout(later, 150)); + return realOpen(...args); + }); + const historyRoot = tempDir("hf-first-copy-root-"); + const history = await openProjectHistory({ projectDir, historyRoot, firstCopyFileMs: 400 }); + closes.push(() => history.close()); + expect(Object.keys(history.peek(START) ?? {}).sort()).toEqual(pathsOf(9).sort()); + expect(existsSync(join(homeIn(historyRoot), "adopting.json"))).toBe(false); + }); + + it("does not stretch a stalled read's deadline while other first copies finish", async () => { + const projectDir = projectOf(1, "stretch"); + const stuck = join(projectDir, "parts", "p0.js"); + const releases: (() => void)[] = []; + closes.push(async () => releases.forEach((answer) => answer())); + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + if (String(args[0]) === stuck) await new Promise((answer) => releases.push(answer)); + if (String(args[0]) === join(projectDir, "index.html")) + await new Promise((later) => setTimeout(later, 800)); + return realOpen(...args); + }); + const historyRoot = tempDir("hf-first-copy-root-"); + const openedAt = Date.now(); + const history = await openProjectHistory({ projectDir, historyRoot, firstCopyFileMs: 1000 }); + closes.push(() => history.close()); + expect(Date.now() - openedAt).toBeLessThan(1500); + expect(JSON.parse(readFileSync(join(homeIn(historyRoot), "adopting.json"), "utf8"))).toEqual([ + "parts/p0.js", + ]); + }); + + it("keeps the original as the start of a late copy when a save writes it back over a later change", async () => { + const projectDir = projectOf(1, "late"); + const p0 = join(projectDir, "parts", "p0.js"); + const original = readFileSync(p0); + const filing = holdFiling(original); + const historyRoot = tempDir("hf-first-copy-root-"); + const history = await openProjectHistory({ projectDir, historyRoot, firstCopyFileMs: 100 }); + closes.push(() => history.close()); + await filing.reached; + writeFileSync(p0, "// B\n"); + writeFileSync(p0, original); + saveReceipt(p0, original.toString(), "// B\n"); + filing.release(); + await adopted(historyRoot); + expect(history.peek(START)!["parts/p0.js"]).toBe(sha256(original)); + }); + + it("keeps the original an early save's receipt names through a prune before its late copy is filed", async () => { + const projectDir = projectOf(1, "prune"); + const p0 = join(projectDir, "parts", "p0.js"); + const original = readFileSync(p0); + const releases: (() => void)[] = []; + closes.push(async () => releases.forEach((answer) => answer())); + let stalled = false; + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + if (String(args[0]) === p0 && !stalled) { + stalled = true; + await new Promise((answer) => releases.push(answer)); + } + return realOpen(...args); + }); + const filing = holdFiling(Buffer.from("// B\n")); + const historyRoot = tempDir("hf-first-copy-root-"); + // The claim's prune and fold leave only what history still needs. + const history = await openProjectHistory({ + projectDir, + historyRoot, + firstCopyFileMs: 100, + budgetBytes: 16, + quietMs: 30, + }); + closes.push(() => history.close()); + writeFileSync(p0, "// B\n"); + saveReceipt(p0, "// B\n", original.toString()); + releases.forEach((answer) => answer()); + await filing.reached; + // A later receipt that starts a new chain: the live receipts no longer name the original. + saveReceipt(p0, "// C\n", "// unrelated\n"); + writeFileSync(join(projectDir, "index.html"), "person"); + await history.claim({ kind: "person", name: "You" }, "Edit", ["index.html"]); + filing.release(); + await adopted(historyRoot); + expect(history.peek(START)!["parts/p0.js"]).toBe(sha256(original)); + }); + + it("keeps a first copy that lands past its deadline as the file's start, and an edit since as a change", async () => { + const projectDir = projectOf(4, "late"); + const late = join(projectDir, "parts", "p1.js"); + const original = readFileSync(late); + let release = () => {}; + const held = new Promise((resolve) => (release = resolve)); + let heldWrites = 0; + vi.mocked(fsp.writeFile).mockImplementation( + async (...args: Parameters) => { + const [path, bytes] = args; + if ( + String(path).includes("incoming-") && + Buffer.isBuffer(bytes) && + bytes.equals(original) + ) { + heldWrites += 1; + await held; + } + return realWriteFile(...args); + }, + ); + const historyRoot = tempDir("hf-first-copy-root-"); + const history = await openProjectHistory({ + projectDir, + historyRoot, + firstCopyFileMs: 50, + quietMs: 30, + }); + closes.push(() => history.close()); + expect(heldWrites).toBe(1); + // An editor saves the file after the open, while its first copy is still being written. + writeFileSync(late, "// saved after the open\n"); + release(); + await vi.waitFor(() => expect(history.peek(START)).toHaveProperty(["parts/p1.js"]), { + timeout: 10_000, + }); + expect(history.peek(START)!["parts/p1.js"]).toBe(sha256(original)); + await vi.waitFor( + () => + expect(history.list().flatMap((entry) => entry.files.map((file) => file.path))).toContain( + "parts/p1.js", + ), + { timeout: 10_000 }, + ); + }); + + it("keeps a late first copy through a prune while another file's read is still stalled", async () => { + const projectDir = projectOf(4, "late-two"); + const stalled = join(projectDir, "parts", "p0.js"); + const late = join(projectDir, "parts", "p2.js"); + const original = readFileSync(late); + const edited = Buffer.from("edited"); + const saved = Buffer.from("// saved after the open\n"); + const stalls: (() => void)[] = []; + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + if (String(args[0]) === stalled) await new Promise((answer) => stalls.push(answer)); + return realOpen(...args); + }); + const holds = new Map void; gate: Promise }>(); + for (const bytes of [original, edited, saved]) { + let release = () => {}; + const gate = new Promise((resolve) => (release = resolve)); + holds.set(bytes, { held: 0, release, gate }); + } + vi.mocked(fsp.writeFile).mockImplementation( + async (...args: Parameters) => { + const [path, bytes] = args; + const hold = [...holds].find( + ([held]) => + String(path).includes("incoming-") && Buffer.isBuffer(bytes) && bytes.equals(held), + )?.[1]; + if (hold) { + hold.held += 1; + await hold.gate; + } + return realWriteFile(...args); + }, + ); + const historyRoot = tempDir("hf-first-copy-root-"); + try { + const history = await openProjectHistory({ + projectDir, + historyRoot, + firstCopyFileMs: 50, + quietMs: 30, + budgetBytes: 1, + }); + closes.push(() => history.close()); + // A sweep holds the history's queue while it stores the edited index; the late copy lands meanwhile. + writeFileSync(join(projectDir, "index.html"), edited); + const sweep = history.checkpoint(); + await vi.waitFor(() => expect(holds.get(edited)!.held).toBe(1)); + writeFileSync(late, saved); + holds.get(original)!.release(); + const home = homeIn(historyRoot); + await vi.waitFor(() => + expect(existsSync(blobPath(join(home, "blobs"), sha256(original)))).toBe(true), + ); + const claimed = history.claim({ kind: "person", name: "You" }, "Typed", ["parts/p2.js"]); + // The sweep's record prunes everything past the 1-byte budget that history does not still need. + holds.get(edited)!.release(); + await sweep; + // Read the start before the sweep that takes in the edit: a 1-byte budget folds that change into it. + await vi.waitFor(() => expect(history.peek(START)).toHaveProperty(["parts/p2.js"]), { + timeout: 10_000, + }); + expect(history.peek(START)!["parts/p2.js"]).toBe(sha256(original)); + expect(stalls).toHaveLength(1); + holds.get(saved)!.release(); + await claimed; + } finally { + for (const answer of stalls) answer(); + } + }); + + it("keeps an in-budget edit while a late first copy waits to be adopted", async () => { + const projectDir = projectOf(2, "budget"); + const late = join(projectDir, "parts", "p1.js"); + writeFileSync(late, "x".repeat(768)); + const original = readFileSync(late); + const edited = Buffer.from("budget edited"); + const holds = new Map void; gate: Promise }>(); + for (const bytes of [original, edited]) { + let release = () => {}; + const gate = new Promise((resolve) => (release = resolve)); + holds.set(bytes, { held: 0, release, gate }); + } + vi.mocked(fsp.writeFile).mockImplementation( + async (...args: Parameters) => { + const [path, bytes] = args; + const hold = [...holds].find( + ([held]) => + String(path).includes("incoming-") && Buffer.isBuffer(bytes) && bytes.equals(held), + )?.[1]; + if (hold) { + hold.held += 1; + await hold.gate; + } + return realWriteFile(...args); + }, + ); + const historyRoot = tempDir("hf-first-copy-root-"); + const history = await openProjectHistory({ + projectDir, + historyRoot, + firstCopyFileMs: 50, + quietMs: 30, + budgetBytes: 128, + }); + closes.push(() => history.close()); + writeFileSync(join(projectDir, "index.html"), edited); + const sweep = history.checkpoint(); + await vi.waitFor(() => expect(holds.get(edited)!.held).toBe(1)); + holds.get(original)!.release(); + const blobs = join(homeIn(historyRoot), "blobs"); + await vi.waitFor(() => expect(existsSync(blobPath(blobs, sha256(original)))).toBe(true)); + holds.get(edited)!.release(); + await sweep; + await vi.waitFor(() => expect(history.peek(START)).toHaveProperty(["parts/p1.js"]), { + timeout: 10_000, + }); + expect(history.list().flatMap((entry) => entry.files.map((file) => file.path))).toContain( + "index.html", + ); + }); + + // Each of the first `changing` reads of a file sees it change under it; every read after that is a fresh one. + async function freshReadsAtOnce(changing: number) { + const projectDir = projectOf(12, "fan"); + const parts = join(projectDir, "parts") + sep; + const opens = new Map(); + let waiting = 0; + let most = 0; + let release = () => {}; + const gate = new Promise((resolve) => (release = resolve)); + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + const path = String(args[0]); + if (!path.startsWith(parts)) return realOpen(...args); + const count = (opens.get(path) ?? 0) + 1; + opens.set(path, count); + if (count > changing) { + most = Math.max(most, ++waiting); + await gate; + waiting -= 1; + return realOpen(...args); + } + const handle = await realOpen(...args); + const readFile = handle.readFile.bind(handle); + handle.readFile = (async (...options: Parameters) => { + const bytes = await readFile(...options); + appendFileSync(path, "// saved while read\n"); + return bytes; + }) as typeof handle.readFile; + return handle; + }); + try { + const history = await open(projectDir, tempDir("hf-first-copy-root-")); + await vi.waitFor(() => expect(waiting).toBe(4), { timeout: 10_000 }); + release(); + await vi.waitFor( + () => + expect( + Object.keys(history.peek(START) ?? {}).filter((path) => path.startsWith("parts/")), + ).toHaveLength(12), + { timeout: 20_000 }, + ); + return most; + } finally { + release(); + } + } + + it("reads files whose first copy kept changing a few at a time", async () => { + expect(await freshReadsAtOnce(3)).toBe(4); + }); + + it("keeps later rereads of those files a few at a time too", async () => { + expect(await freshReadsAtOnce(6)).toBe(4); + }, 30_000); + + it("keeps a reread copy from pruning while it waits to be adopted", async () => { + const projectDir = projectOf(2, "reread"); + const late = join(projectDir, "parts", "p1.js"); + const edited = Buffer.from("reread edited"); + const saved = Buffer.from("// saved after the reread\n"); + let reads = 0; + let letReread = () => {}; + const rereadGate = new Promise((resolve) => (letReread = resolve)); + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + const path = String(args[0]); + if (path === late && ++reads === 4) await rereadGate; + const handle = await realOpen(...args); + if (path !== late || reads > 3) return handle; + const readFile = handle.readFile.bind(handle); + handle.readFile = (async (...options: Parameters) => { + const bytes = await readFile(...options); + appendFileSync(path, "// saved while read\n"); + return bytes; + }) as typeof handle.readFile; + return handle; + }); + const holds = new Map void; gate: Promise }>(); + for (const bytes of [edited, saved]) { + let release = () => {}; + const gate = new Promise((resolve) => (release = resolve)); + holds.set(bytes, { held: 0, release, gate }); + } + vi.mocked(fsp.writeFile).mockImplementation( + async (...args: Parameters) => { + const [path, bytes] = args; + const hold = [...holds].find( + ([held]) => + String(path).includes("incoming-") && Buffer.isBuffer(bytes) && bytes.equals(held), + )?.[1]; + if (hold) { + hold.held += 1; + await hold.gate; + } + return realWriteFile(...args); + }, + ); + const historyRoot = tempDir("hf-first-copy-root-"); + try { + const history = await openProjectHistory({ + projectDir, + historyRoot, + quietMs: 30, + budgetBytes: 1, + }); + closes.push(() => history.close()); + // A sweep holds the history's queue while it stores the edited index; the reread lands meanwhile. + writeFileSync(join(projectDir, "index.html"), edited); + const sweep = history.checkpoint(); + await vi.waitFor(() => expect(holds.get(edited)!.held).toBe(1)); + const reread = readFileSync(late); + letReread(); + const blobs = join(homeIn(historyRoot), "blobs"); + await vi.waitFor(() => expect(existsSync(blobPath(blobs, sha256(reread)))).toBe(true), { + timeout: 10_000, + }); + writeFileSync(late, saved); + holds.get(edited)!.release(); + await sweep; + // Read the start before the sweep that takes in the edit: a 1-byte budget folds that change into it. + await vi.waitFor(() => expect(history.peek(START)).toHaveProperty(["parts/p1.js"]), { + timeout: 10_000, + }); + expect(history.peek(START)!["parts/p1.js"]).toBe(sha256(reread)); + } finally { + letReread(); + for (const { release } of holds.values()) release(); + } + }); + + it("adopts a file that grew past the copy limit before its reread, by reference", async () => { + const projectDir = projectOf(2, "grew"); + const grows = join(projectDir, "parts", "p1.js"); + let reads = 0; + vi.mocked(fsp.open).mockImplementation(async (...args: Parameters) => { + const handle = await realOpen(...args); + if (String(args[0]) !== grows || ++reads > 3) return handle; + const readFile = handle.readFile.bind(handle); + handle.readFile = (async (...options: Parameters) => { + const bytes = await readFile(...options); + if (reads < 3) appendFileSync(grows, "// saved while read\n"); + else truncateSync(grows, 65 * 1024 ** 2); + return bytes; + }) as typeof handle.readFile; + return handle; + }); + const history = await open(projectDir, tempDir("hf-first-copy-root-")); + await vi.waitFor(() => expect(history.peek(START)).toHaveProperty(["parts/p1.js"]), { + timeout: 10_000, + }); + }); }); diff --git a/packages/studio-server/src/history/projectHistory.saving.test.ts b/packages/studio-server/src/history/projectHistory.saving.test.ts index d187734b1e..d7f451085c 100644 --- a/packages/studio-server/src/history/projectHistory.saving.test.ts +++ b/packages/studio-server/src/history/projectHistory.saving.test.ts @@ -17,9 +17,9 @@ vi.mock("./blobStore", async (importOriginal) => { ...real, openBlobStore: async (dir: string) => { const store = await real.openBlobStore(dir); - const put = async (path: string) => { + const put: typeof store.put = async (path, ...rest) => { const left = changing.get(basename(path)) ?? 0; - if (left === 0) return store.put(path); + if (left === 0) return store.put(path, ...rest); changing.set(basename(path), left - 1); return null; }; diff --git a/packages/studio-server/src/history/projectHistory.swap.test.ts b/packages/studio-server/src/history/projectHistory.swap.test.ts index 41bbd9b419..b5c42c1703 100644 --- a/packages/studio-server/src/history/projectHistory.swap.test.ts +++ b/packages/studio-server/src/history/projectHistory.swap.test.ts @@ -44,10 +44,10 @@ vi.mock("./blobStore", async (importOriginal) => { const store = await original.openBlobStore(dir); return { ...store, - put: async (path: string) => { + put: (async (path, ...rest) => { hooks.beforePut?.(); - return store.put(path); - }, + return store.put(path, ...rest); + }) satisfies typeof store.put, writeTo: async (hash: string, root: string, path: string, beforeReplace?: () => void) => { hooks.beforeWrite?.(); await store.writeTo(hash, root, path, beforeReplace); diff --git a/packages/studio-server/src/history/projectHistory.test.ts b/packages/studio-server/src/history/projectHistory.test.ts index ea52e7824d..1aa2ca75d8 100644 --- a/packages/studio-server/src/history/projectHistory.test.ts +++ b/packages/studio-server/src/history/projectHistory.test.ts @@ -56,17 +56,18 @@ vi.mock("./blobStore", async (importOriginal) => { const store = await real.openBlobStore(dir); return { ...store, - put: async (path: string) => { + put: (async (path, _pin, onRead) => { if (path.endsWith(".bin")) { mediaCopy.entered?.(); await mediaCopy.held; mediaCopy.copies.push(basename(path)); if (mediaCopy.fails?.(mediaCopy.copies.length)) throw new Error("The disk is full."); } - const hash = await store.put(path); + // These cases count media copies unpinned; pinning has its own cases in firstCopy.test.ts. + const hash = await store.put(path, false, onRead); if (path.endsWith(".bin")) await mediaCopy.stored?.(); return hash; - }, + }) satisfies typeof store.put, }; }, }; diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.ts index 88267f1c2d..da5f20cb52 100644 --- a/packages/studio-server/src/history/projectHistory.ts +++ b/packages/studio-server/src/history/projectHistory.ts @@ -95,6 +95,8 @@ export interface ProjectHistoryOptions { onError?: (error: unknown) => void; /** How long an open waits for another process to close the same history (default 5 s). */ ownerWaitMs?: number; + /** How long the first copy waits on one file before leaving it owed (default 10 s). */ + firstCopyFileMs?: number; ownerUrl?: string; /** A CLI turn's window from an earlier open: writes since, within its idle limit, become the entry with its id. */ closedWindow?: ClosedWindow; @@ -231,7 +233,19 @@ interface WrittenAt { fileTime?: number; } -type Copied = { hash: string } | "gone" | "changing"; +type Copied = + | { + hash: string; + referenced?: true; + release?: () => void; + /** Save receipts heard by the moment of the read: after hash to the hash it replaced. */ + heardAtRead?: Map; + } + | "gone" + | "changing"; + +const FIRST_COPY_FILE_MS = 10_000; + const ADOPT_RETRY_AT_MOST_MS = 30_000; /** Owed until a whole copy is recorded, the file is gone or history closes; retryNow waits for a fresh try. */ @@ -245,6 +259,8 @@ const FIRST_COPY_SLOTS_IN_PROCESS = 4; let firstCopiesRunning = 0; const firstCopiesWaiting: (() => void)[] = []; +const firstCopyProgress = new Set<() => void>(); + async function inFirstCopySlot(copy: () => Promise): Promise { if (firstCopiesRunning < FIRST_COPY_SLOTS_IN_PROCESS) firstCopiesRunning += 1; else await new Promise((yours) => firstCopiesWaiting.push(yours)); @@ -254,9 +270,33 @@ async function inFirstCopySlot(copy: () => Promise): Promise { const next = firstCopiesWaiting.shift(); if (next) next(); else firstCopiesRunning -= 1; + for (const restart of firstCopyProgress) restart(); } } +/** Owed `ms` after its read starts; while queued, `ms` after the last first copy that finished. */ +function firstCopyOrOwed(copy: () => Promise, ms: number) { + let timer: NodeJS.Timeout | undefined; + let owe = () => {}; + const owed = new Promise<"changing">((resolve) => (owe = () => resolve("changing"))); + const restart = () => { + clearTimeout(timer); + timer = setTimeout(owe, ms); + }; + firstCopyProgress.add(restart); + restart(); + const work = inFirstCopySlot(() => { + firstCopyProgress.delete(restart); + restart(); + return copy(); + }); + const result = Promise.race([work, owed]).finally(() => { + clearTimeout(timer); + firstCopyProgress.delete(restart); + }); + return { work, result }; +} + const MEDIA_LEDGER = ".media/manifest.jsonl"; const KEPT_HIDDEN_PATHS = new Set([...STUDIO_SIGNATURE_MANIFEST_PATHS, MEDIA_LEDGER]); @@ -491,6 +531,9 @@ class Engine { /** A coalescing claim, open until another key, its idle timer, an operation, a window, or another write. */ claimed: { group: Group; key: string; timer?: NodeJS.Timeout } | null = null; adopting = new Map(); + reading = new Map>(); + /** Bytes a save replaced in a file history holds no copy of yet: its pending first copy may start there. */ + heardBeforeCopy = new Map>(); /** Per path and hash an API write left, the hash of the bytes it replaced, until walked or written past. */ overwritten = new Map>(); stopHearing: (() => void) | undefined; @@ -682,6 +725,8 @@ class Engine { path, chainBackFrom(this.overwritten.get(path), replaced).set(after, replaced), ); + if (this.adopting.has(path)) + this.heardBeforeCopy.set(path, (this.heardBeforeCopy.get(path) ?? new Set()).add(replaced)); this.queue(async () => { if (!this.blobs.has(replaced) && !isUncopied(path, bytes.length)) await this.storeBytes(bytes); @@ -744,18 +789,26 @@ class Engine { const sweptAt = this.now(); const files = await this.historyFiles(); const copied = files.filter((file) => file.size <= COPY_LATER_ABOVE_BYTES); - const hashes = await Promise.allSettled( - copied.map((file) => inFirstCopySlot(() => this.storeIfPresent(file.path))), + const waitMs = this.options.firstCopyFileMs ?? FIRST_COPY_FILE_MS; + const copies = copied.map((file) => + firstCopyOrOwed(() => this.storeIfPresent(file.path, true), waitMs), ); + const hashes = await Promise.allSettled(copies.map((copy) => copy.result)); + const late = new Map>(); // Nothing names these copies until the log below is written, so one look at the end covers the whole copy. if (this.whereFolder() !== "here") throw this.replaced(); const owed: ListedFile[] = []; copied.forEach((file, i) => { const result = hashes[i]!; if (result.status === "rejected") throw result.reason; - if (result.value === "changing") owed.push(file); - else if (result.value !== "gone") + if (result.value === "changing") { + owed.push(file); + late.set(file.path, copies[i]!.work); + } else if (result.value !== "gone") { this.tracked.set(file.path, { hash: result.value.hash, stat: this.statKey(file, sweptAt) }); + this.heardBeforeCopy.delete(file.path); + result.value.release?.(); + } }); this.log.baseline = this.manifest(); this.log.keepsLedger = true; @@ -764,6 +817,7 @@ class Engine { this.adoptMediaInBackground( [...owed, ...files.filter((file) => file.size > COPY_LATER_ABOVE_BYTES)], sweptAt, + late, ); } @@ -771,11 +825,16 @@ class Engine { await Promise.all([...this.adopting.values()].map((adoption) => adoption.firstTry)); } - adoptMediaInBackground(files: ListedFile[], sweptAt: number): void { + adoptMediaInBackground( + files: ListedFile[], + sweptAt: number, + lateFirstCopies = new Map>(), + ): void { let turn: Promise = Promise.resolve(); for (const file of files) { - const adoption = this.adopt(file, sweptAt, turn); - turn = adoption.firstTry; + const late = lateFirstCopies.get(file.path); + const adoption = this.adopt(file, sweptAt, turn, late); + if (!late) turn = adoption.firstTry; this.adopting.set(file.path, adoption); } this.saveAdopting(); @@ -789,13 +848,20 @@ class Engine { } /** A file still changing stays named until a whole copy of it lands; the next open retries it. */ - adopt(file: ListedFile, sweptAt: number, turn: Promise): Adoption { + adopt( + file: ListedFile, + sweptAt: number, + turn: Promise, + late?: Promise, + ): Adoption { let asked: Array<() => void> = []; let wake = () => {}; + const owedFromOpen = late !== undefined; const tryOnce = async () => { const served = asked; asked = []; - const tried = await this.tryAdopting(file, sweptAt); + const tried = await this.tryAdopting(file, sweptAt, late, owedFromOpen); + late = undefined; for (const answer of served) answer(); return tried === "over"; }; @@ -823,17 +889,29 @@ class Engine { return { firstTry, ended, retryNow }; } - async tryAdopting(file: ListedFile, sweptAt: number): Promise<"over" | "changing"> { + async tryAdopting( + file: ListedFile, + sweptAt: number, + late?: Promise, + owedFromOpen = false, + ): Promise<"over" | "changing"> { try { if (this.whereFolder() !== "here") return "over"; - const copied = await this.storeIfPresent(file.path); - return await this.queue(async () => { + const first = await late?.catch(() => undefined); + const fromOpen = typeof first === "object"; + const read = () => this.storeIfPresent(file.path, true); + const copied = fromOpen ? first : await (owedFromOpen ? inFirstCopySlot(read) : read()); + const record = this.queue(async () => { // Still named for the next open until recorded, so a failed record is never logged as added. if ((await this.recordAdopted(file, sweptAt, copied)) === "changing") return "changing"; this.adopting.delete(file.path); + this.heardBeforeCopy.delete(file.path); this.saveAdopting(); + // The sweeps since open passed this file by: one more takes in any edit since the bytes were read. + if (fromOpen) this.sweepIn(0); return "over"; }); + return await record.finally(() => typeof copied === "object" && copied.release?.()); } catch (error) { if (!(error instanceof HistoryClosedError)) this.options.onError?.(error); return "over"; @@ -842,13 +920,13 @@ class Engine { async recordAdopted(file: ListedFile, sweptAt: number, first: Copied): Promise { if (typeof first === "string" || this.whereFolder() !== "here") return first; - // A prune that ran while this copy waited for the queue may have taken its bytes. - const kept = this.blobs.has(first.hash) || isUncopied(file.path, file.size); - const copied = kept ? first : await this.storeIfPresent(file.path); - if (typeof copied === "string") return copied; + // Bytes gone from the store are read again on the next try, outside the history queue. + if (!first.referenced && !this.blobs.has(first.hash)) return "changing"; + const copied = first; const { hash } = copied; const change = { path: file.path, before: null, after: hash }; - const found = this.overwrittenBy(change, undefined, new Set()); + const heard = copied.heardAtRead ?? new Map(); + const found = this.overwrittenBy(change, undefined, new Set(), heard); const start = found && this.blobs.has(found) ? found : hash; this.tracked.set(file.path, { hash, stat: this.statKey(file, sweptAt) }); this.log.baseline.set(file.path, start); @@ -969,13 +1047,30 @@ class Engine { } /** The file's hash once copied in, or why there is none: gone, or still changing through every read. */ - async storeIfPresent(path: string): Promise { + storeIfPresent(path: string, pin = false): Promise { + const before = this.reading.get(path) ?? Promise.resolve(); + const read = before.catch(() => {}).then(() => this.storeNow(path, pin)); + const turn = read.catch(() => {}); + this.reading.set(path, turn); + void turn.then(() => this.reading.get(path) === turn && this.reading.delete(path)); + return read; + } + + async storeNow(path: string, pin = false): Promise { try { const abs = join(this.dir, path); const { size } = await stat(abs); - if (isUncopied(path, size)) return { hash: await this.blobs.reference(abs) }; - const hash = await this.blobs.put(abs); - return hash === null ? "changing" : { hash }; + let heardAtRead: Map | undefined; + const read = () => (heardAtRead = new Map(this.overwritten.get(path))); + if (isUncopied(path, size)) { + const hash = await this.blobs.reference(abs); + read(); + return { hash, referenced: true, heardAtRead }; + } + const hash = await this.blobs.put(abs, pin, read); + if (hash === null) return "changing"; + const release = pin ? { release: () => this.blobs.unpin(hash) } : {}; + return { hash, ...release, heardAtRead }; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "gone"; throw error; @@ -1113,13 +1208,18 @@ class Engine { } /** Walks the server's writes back from `change.after` to the stored bytes they replaced. */ - overwrittenBy(change: HistoryFileChange, told: string | undefined, seen: Set) { + overwrittenBy( + change: HistoryFileChange, + told: string | undefined, + seen: Set, + heard = this.overwritten.get(change.path), + ) { let found: string | undefined; for (let hash = change.after; hash; ) { // A loop (X, Y, back to X) says nothing about what was there first: the client's word stands. if (seen.has(hash)) return undefined; seen.add(hash); - const replaced = this.overwritten.get(change.path)?.get(hash); + const replaced = heard?.get(hash); if (replaced === undefined) break; found = hash = replaced; if (hash === change.before || hash === told) return hash; @@ -1236,7 +1336,9 @@ class Engine { /** Stored bytes beyond what the current files need: a project larger than the budget still keeps its history. */ historyBytes(): number { let current = 0; - for (const hash of new Set([...this.tracked.values()].map((file) => file.hash))) + const baseline = [...this.tracked.values()].map((file) => file.hash); + const owedStarts = [...this.heardBeforeCopy.values()].flatMap((replaced) => [...replaced]); + for (const hash of new Set([...baseline, ...this.blobs.pinned(), ...owedStarts])) current += this.blobs.size(hash); return this.blobs.bytes() - current; } @@ -1250,6 +1352,7 @@ class Engine { ...referencedHashes(this.log, this.manifest()), ...this.pendingHashes(), ...[...this.overwritten.values()].flatMap((byAfter) => [...byAfter.values()]), + ...[...this.heardBeforeCopy.values()].flatMap((replaced) => [...replaced]), ]), ); if (this.historyBytes() <= budget || !foldOldest(this.log)) break; diff --git a/packages/studio-server/src/routes/history.test.ts b/packages/studio-server/src/routes/history.test.ts index 656a0dfa4f..8bc9b07827 100644 --- a/packages/studio-server/src/routes/history.test.ts +++ b/packages/studio-server/src/routes/history.test.ts @@ -32,10 +32,10 @@ vi.mock("../history/blobStore", async (importOriginal) => { const store = await real.openBlobStore(dir); return { ...store, - put: async (path: string) => { + put: (async (path, ...rest) => { if (path.endsWith(".bin")) await mediaCopy.held; - return store.put(path); - }, + return store.put(path, ...rest); + }) satisfies typeof store.put, }; }, }; diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index 51e7d556ab..655126dc60 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -56,7 +56,7 @@ "unpacked": 26703858 }, "@hyperframes/studio-server": { - "packed": 188871, + "packed": 201161, "unpacked": 732018 } }