Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions packages/studio-server/src/history/blobStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
});

Expand All @@ -33,6 +34,7 @@ const {
rename: realRename,
copyFile: realCopyFile,
open: realOpen,
rm: realRm,
} = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
const busy = () => Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" });
const platform = process.platform;
Expand Down Expand Up @@ -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<void>((resolve) => (release = resolve));
let deleting = 0;
vi.mocked(fsp.rm).mockImplementation(async (...args: Parameters<typeof realRm>) => {
if (String(args[0]).endsWith(hash)) {
deleting += 1;
await held;
}
return realRm(...args);
});
let read = false;
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
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<typeof realRm>) => {
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(() => {
Expand Down
80 changes: 59 additions & 21 deletions packages/studio-server/src/history/blobStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null>;
put(absPath: string, pin?: boolean, onRead?: () => void): Promise<string | null>;
unpin(hash: string): void;
pinned(): Iterable<string>;
reference(absPath: string): Promise<string>;
has(hash: string): boolean;
read(hash: string): Promise<Buffer>;
Expand Down Expand Up @@ -75,13 +77,17 @@ export async function hashFile(path: string): Promise<string> {

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();
}
Expand Down Expand Up @@ -194,11 +200,23 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
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<string, number>();
const pin = (hash: string) => pins.set(hash, (pins.get(hash) ?? 0) + 1);
const turns = new Map<string, Promise<unknown>>();
const inTurn = <T>(hash: string, step: () => Promise<T>): Promise<T> => {
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);
Expand All @@ -216,9 +234,12 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
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 }));
Expand All @@ -231,12 +252,18 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
throw error;
}
file(hash, bytes.length);
if (pinned) pin(hash);
return hash;
};

const putIfUnchanged = async (absPath: string): Promise<string | null> => {
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<string | null> => {
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.
Expand All @@ -252,22 +279,27 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
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;
Expand Down Expand Up @@ -314,6 +346,12 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
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);
Expand Down
Loading
Loading