import * as path from "path" import * as os from "os" import * as fs from "fs/promises" import { safeWriteJson } from "../safeWriteJson" import { deleteJsonFile } from "../jsonFileRecovery" import { resolveLockKey } from "../../services/file-safety/safeWriteText" // The defect this file pins is about an alias: the caller hands in a path that runs through a // link, and the publish is promised to land on the file the link refers to - the location the // advisory lock was taken for and the location confineTo measured. The EPERM fallback named the // alias instead, which moves the alias itself and leaves the referent holding the text no // preview touched. // A file symlink is not available on the Windows lane: `fs.symlink` on a file answers EPERM // there (no privilege, no Developer Mode), which is the same reason jsonFileRecovery.test.ts: // 257-262 gates its alias rows on the POSIX lanes. Rows E1 to E4 therefore model the alias at // the fs/promises seam - the link is held in a map and follows POSIX rename/unlink semantics, // where renaming a link path moves the link and renaming onto a link path replaces the link - // while every byte lives on the real filesystem in the one real directory the alias sits in. // Row E5 repeats the publish claim against a real link on the lanes that can make one. interface Seam { // Alias path -> referent path. Only these paths are modelled; everything else is the real // filesystem. links: Map // Every rename the writer asked for, in order, as [source, destination]. renames: [string, string][] // Which rename numbers must fail, in order, with the code the writer is meant to see. failRenames: { at: number; code: string | null; message: string }[] } const seam = vi.hoisted((): Seam => ({ links: new Map(), renames: [] as [string, string][], failRenames: [] as { at: number; code: string | null; message: string }[], })) const enoent = (target: string): Error => Object.assign(new Error(`ENOENT: no such file or directory, ${target}`), { code: "ENOENT" }) vi.mock("fs/promises", async () => { const actual = await vi.importActual("fs/promises") const asPath = (target: string | Buffer | URL): string => String(target) const referentOf = (target: string): string | undefined => seam.links.get(target) // A modelled link resolves to its referent, and reports what the referent reports: absent // referent means the link is dangling, which is the ENOENT the writer's own resolution // already treats as "not there yet" rather than as an answer about the link. const modelledRealpath = async (target: string): Promise => { const referent = referentOf(target) if (referent === undefined) { return actual.realpath(target) } try { await actual.stat(referent) } catch { throw enoent(target) } return referent } const modelledStat = async (target: string, options?: { bigint?: boolean }) => { const referent = referentOf(target) return referent === undefined ? actual.stat(target, options) : actual.stat(referent, options) } // The sequence of renames this writer issues is fixed: 1 commits, 2 renames the target aside // in the fallback, 3 puts the replacement in place, 4 is the rollback. Injecting by position // aims at the same step whatever spelling the step happens to use, which is the point of the // rows below. const injectedFailure = (index: number): void => { const hit = seam.failRenames.find((failure) => failure.at === index) if (hit === undefined || index !== seam.renames.length) { return } seam.failRenames = seam.failRenames.filter((failure) => failure !== hit) throw Object.assign(new Error(hit.message), hit.code === null ? {} : { code: hit.code }) } const mockedFs = { ...actual, realpath: vi.fn(async (target: string | Buffer | URL) => modelledRealpath(asPath(target))), stat: vi.fn(async (target: string | Buffer | URL, options?: { bigint?: boolean }) => modelledStat(asPath(target), options), ), readFile: vi.fn(async (target: string | Buffer | URL, options?: unknown) => { const referent = referentOf(asPath(target)) return actual.readFile(referent ?? (target as string | Buffer | URL), options as BufferEncoding | undefined) }), lstat: vi.fn(async (target: string | Buffer | URL) => { const pathText = asPath(target) if (seam.links.has(pathText)) { return { isSymbolicLink: () => true, isFile: () => false } as Awaited> } return actual.lstat(pathText) }), readlink: vi.fn(async (target: string | Buffer | URL) => { const referent = referentOf(asPath(target)) if (referent !== undefined) { return referent } return actual.readlink(asPath(target)) }), rename: vi.fn(async (source: string | Buffer | URL, destination: string | Buffer | URL) => { const from = asPath(source) const to = asPath(destination) seam.renames.push([from, to]) injectedFailure(seam.renames.length) const linkHere = seam.links.get(from) if (linkHere !== undefined) { // POSIX rename does not follow the link on either side: renaming a link path moves // the link, and the file it refers to keeps its own name and its own bytes. seam.links.delete(from) seam.links.set(to, linkHere) return } if (seam.links.has(to)) { // Renaming onto a link path replaces the link with the source file. seam.links.delete(to) } await actual.rename(from, to) }), unlink: vi.fn(async (target: string | Buffer | URL) => { const pathText = asPath(target) if (seam.links.has(pathText)) { seam.links.delete(pathText) return } await actual.unlink(pathText) }), } return mockedFs }) describe("safeWriteJson - the EPERM fallback against an alias target", () => { let dir = "" let referent = "" let alias = "" beforeEach(async () => { seam.links = new Map() seam.renames = [] seam.failRenames = [] dir = await fs.mkdtemp(path.join(os.tmpdir(), "safe-write-alias-")) referent = path.join(dir, "target.json") alias = path.join(dir, "alias.json") }) afterEach(async () => { seam.links = new Map() seam.failRenames = [] await fs.rm(dir, { recursive: true, force: true }) }) const stageAliasFixture = async (committed: unknown): Promise => { await fs.writeFile(referent, JSON.stringify(committed), "utf8") seam.links.set(alias, referent) } // The renames that name the file being published: the commit destination, the text the // fallback renames aside, the replacement destination, and the rollback destination. Read // together they say which file this writer believed it was publishing - the promise the lock // key and confineTo both make. const namesAskedOfTheTarget = (): string[] => seam.renames.flatMap(([from, to], index) => index === 1 ? [from] : index === 0 || index === 2 || index === 3 ? [to] : [], ) const leftoverNames = async (): Promise => (await fs.readdir(dir)).filter((entry) => entry.includes(".bak_") || entry.includes(".new_")) it("publishes an alias write onto the file the alias refers to when the commit rename is refused", async () => { // The Windows condition: a reader holds the target open, so the single commit rename // answers EPERM and the writer falls back to renaming the target aside and moving the // replacement in. Both of those steps have to name the referent - the file the advisory // lock was taken for and the file confineTo measured - because renaming an alias path // moves the alias, not the file. const committed = { message: "committed before the fallback" } const replacement = { message: "published through the alias" } await stageAliasFixture(committed) seam.failRenames = [{ at: 1, code: "EPERM", message: "EPERM: operation not permitted" }] await safeWriteJson(alias, replacement) expect(JSON.parse(await fs.readFile(referent, "utf8"))).toEqual(replacement) expect(seam.links.get(alias)).toBe(referent) expect((await fs.lstat(alias)).isSymbolicLink()).toBe(true) expect(JSON.parse(await fs.readFile(alias, "utf8"))).toEqual(replacement) expect(namesAskedOfTheTarget()).toEqual([referent, referent, referent]) const backup = seam.renames[1][1] expect(path.dirname(backup)).toBe(dir) expect(path.basename(backup).startsWith("." + path.basename(referent) + ".bak_")).toBe(true) expect(await leftoverNames()).toEqual([]) expect([...seam.links.keys()]).toEqual([alias]) }) it("commits an alias write on the referent when no rename is refused", async () => { // The control for the row above, same fixture without the injected EPERM: the fast commit // already names the referent, so the alias keeps pointing where it always pointed and no // second copy of the file is created anywhere. Without this row the refusal above could // quietly become "alias writes never land". const committed = { message: "committed before the fast commit" } const replacement = { message: "published by the single rename" } await stageAliasFixture(committed) await safeWriteJson(alias, replacement) expect(JSON.parse(await fs.readFile(referent, "utf8"))).toEqual(replacement) expect(seam.links.get(alias)).toBe(referent) expect((await fs.lstat(alias)).isSymbolicLink()).toBe(true) expect(seam.renames).toHaveLength(1) expect(namesAskedOfTheTarget()).toEqual([referent]) expect(await leftoverNames()).toEqual([]) }) it("rolls the referent back when the fallback replacement rename fails", async () => { // The failure the fallback's own rollback exists for. The rollback has to restore the same // file the fallback renamed aside: restoring the alias instead would put the old text // behind the alias name and leave the referent holding whatever it held before. const committed = { message: "committed, to be restored" } const replacement = { message: "never published" } await stageAliasFixture(committed) seam.failRenames = [ { at: 1, code: "EPERM", message: "EPERM: operation not permitted" }, { at: 3, code: null, message: "fallback replacement refused" }, ] await expect(safeWriteJson(alias, replacement)).rejects.toThrow("fallback replacement refused") expect(namesAskedOfTheTarget()).toEqual([referent, referent, referent, referent]) expect(JSON.parse(await fs.readFile(referent, "utf8"))).toEqual(committed) expect(seam.links.get(alias)).toBe(referent) expect((await fs.lstat(alias)).isSymbolicLink()).toBe(true) expect(await leftoverNames()).toEqual([]) }) it("finds the renamed-aside text on the next round through the same alias", async () => { // The crash window between the two renames, forced by failing the rollback too so the // state survives: the file the fallback renamed aside sits in the referent's directory // under the referent's name, and the alias has nothing to publish onto. The next round // asks for the alias, so its recovery pass has to look where the previous round wrote - // the same resolved path the lock key was taken from - or the committed text is left // behind as garbage and the alias is left with no link at all. const committed = { message: "committed before the crash" } const interrupted = { message: "interrupted write" } const recovered = { message: "written after the crash" } await stageAliasFixture(committed) seam.failRenames = [ { at: 1, code: "EPERM", message: "EPERM: operation not permitted" }, { at: 3, code: null, message: "fallback replacement refused" }, { at: 4, code: null, message: "rollback refused" }, ] // The rollback failure is logged rather than rethrown, so the caller sees the rename that // failed first. Failing the rollback too is only there to keep the crash state standing. await expect(safeWriteJson(alias, interrupted)).rejects.toThrow("fallback replacement refused") // The text the previous round renamed aside sits in the directory of the file it renamed, // under that file's name - which is also the name the recovery pass looks for, and the name // jsonFileRecovery.ts:93-94 promises for a backup of a file reached through an alias. const aside = seam.renames[1][1] expect(path.dirname(aside)).toBe(dir) expect(path.basename(aside).startsWith("." + path.basename(referent) + ".bak_")).toBe(true) // The alias has nothing to publish onto: the referent it names is the path under another // name. The next round asks for the alias, so recovery has to reach the aside text. let seenByMerge: unknown = "unset" await safeWriteJson(alias, recovered, { merge: (existing: unknown) => { seenByMerge = existing return recovered }, }) // The previous round's text came back to the writer before the new one was composed. expect(seenByMerge).toEqual(committed) expect(JSON.parse(await fs.readFile(referent, "utf8"))).toEqual(recovered) expect(seam.links.get(alias)).toBe(referent) expect((await fs.lstat(alias)).isSymbolicLink()).toBe(true) expect(await leftoverNames()).toEqual([]) }) // Row E5 is the same claim against a real link. It runs on the lanes that can create one // for the reason jsonFileRecovery.test.ts:257-262 gives: fs.symlink on a file answers EPERM // on the Windows lane, which has neither privilege nor Developer Mode. The four rows above // run everywhere, including here, which is why they model the alias at the seam. const itPosix = it.runIf(process.platform !== "win32") itPosix("publishes a real alias write onto the referent when the commit rename is refused", async () => { const committed = { message: "committed before a real fallback" } const replacement = { message: "published through a real link" } await fs.writeFile(referent, JSON.stringify(committed), "utf8") await fs.symlink(referent, alias) vi.mocked(fs.rename).mockImplementationOnce(async () => { throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }) }) await safeWriteJson(alias, replacement) expect(JSON.parse(await fs.readFile(referent, "utf8"))).toEqual(replacement) expect((await fs.lstat(alias)).isSymbolicLink()).toBe(true) expect(await fs.readlink(alias)).toBe(referent) expect(JSON.parse(await fs.readFile(alias, "utf8"))).toEqual(replacement) expect(await leftoverNames()).toEqual([]) }) const errorLetter = (error: unknown): string => error && typeof error === "object" && "code" in error ? String((error as { code: unknown }).code) : String(error) // Rows E6 and E7 verify the window CodeRabbit #4507851718 asked to have verified: a delete that // starts while this writer is inside the EPERM fallback. Everything is measured through the key the // delete asks for, because the alignment rests on that key. Between the second rename and the third // the canonical path is absent - the fallback has just renamed it aside - so the alias is a dangling // link, which is the moment at which a delete could have resolved the alias to some other name, // contended with nobody, and removed the staging file and the renamed-aside text under the writer. const deleteDuringFallback = async (kind: "modelled" | "real"): Promise => { const committed = { message: "committed before the fallback" } const replacement = { message: "published through the fallback" } if (kind === "real") { await fs.writeFile(referent, JSON.stringify(committed), "utf8") await fs.symlink(referent, alias) } else { await stageAliasFixture(committed) } const actual = await vi.importActual("fs/promises") const seamRename = vi.mocked(fs.rename).getMockImplementation() if (seamRename === undefined) { throw new Error("the seam must expose its rename implementation before a row replaces it") } const facts: { keyAlias?: string keyReferent?: string outcome?: string duringWindow?: string[] } = {} try { vi.mocked(fs.rename).mockImplementation( async (source: string | Buffer | URL, destination: string | Buffer | URL) => { const from = String(source) const to = String(destination) seam.renames.push([from, to]) if (seam.renames.length === 1) { // The Windows condition the fallback exists for: a reader holds the target open. throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }) } if (seam.renames.length === 3) { facts.keyAlias = await resolveLockKey(alias).catch((e: unknown) => "ERR-" + errorLetter(e)) facts.keyReferent = await resolveLockKey(referent).catch( (e: unknown) => "ERR-" + errorLetter(e), ) facts.duringWindow = await leftoverNames() facts.outcome = await deleteJsonFile(alias).then( () => "DELETED", (e: unknown) => "THREW-" + errorLetter(e), ) } // Same alias semantics the seam uses: POSIX rename moves the link, and renaming onto a // link path replaces the link. Bytes stay on the real filesystem either way. const linkHere = seam.links.get(from) if (linkHere !== undefined) { seam.links.delete(from) seam.links.set(to, linkHere) return } if (seam.links.has(to)) { seam.links.delete(to) return } await actual.rename(from, to) }, ) await safeWriteJson(alias, replacement) } finally { vi.mocked(fs.rename).mockImplementation(seamRename) } // The delete asked for the same key the writer holds, so it never got past acquisition. expect(facts.keyAlias, "the alias must still resolve to the key the writer holds").toBe(facts.keyReferent) expect(facts.outcome, "an alias-side delete must contend, not delete").toBe("THREW-ELOCKED") // ... and contending is what saved them: the staging file and the renamed-aside text were both // present inside the window and are gone only because the writer itself finished the job. expect(facts.duringWindow).toHaveLength(2) expect(facts.duringWindow).toEqual( expect.arrayContaining([expect.stringContaining(".new_"), expect.stringContaining(".bak_")]), ) expect(JSON.parse(await fs.readFile(referent, "utf8"))).toEqual(replacement) expect((await fs.lstat(alias)).isSymbolicLink()).toBe(true) if (kind === "real") { expect(await fs.readlink(alias)).toBe(referent) } else { expect(seam.links.get(alias)).toBe(referent) } expect(await leftoverNames()).toEqual([]) } it("keeps the staging file and the renamed-aside text out of an alias-side delete during the fallback", async () => { await deleteDuringFallback("modelled") }) // Row E7 is the same claim against a real link, for the reason the block comment above E5 gives: // the bot asked for a synchronized symlink write/delete test, and only the lanes that can create a // file symlink can run it. The row above is the one the Windows lane executes. itPosix("keeps a real alias write and an alias-side delete on one lock through the fallback", async () => { await deleteDuringFallback("real") }) })