|
| 1 | +import { describe, expect, test } from "bun:test" |
| 2 | +import { dlopen, FFIType, ptr } from "bun:ffi" |
| 3 | +import path from "path" |
| 4 | +import { mkdtemp, readdir, readFile, rename, rm, writeFile } from "fs/promises" |
| 5 | +import { tmpdir } from "os" |
| 6 | +import { readJson, renameWithRetry, writeJsonAtomic, writeJsonAtomicDetached } from "../../src/util/persistence" |
| 7 | + |
| 8 | +const root = () => mkdtemp(path.join(tmpdir(), "opencode-tui-lock-")) |
| 9 | + |
| 10 | +function lockError(code: string) { |
| 11 | + return Object.assign(new Error(`${code}: operation not permitted, rename`), { code }) |
| 12 | +} |
| 13 | + |
| 14 | +/** |
| 15 | + * A rename seam that fails with each code in `codes`, in order, and then runs `land`. Counts the |
| 16 | + * attempts and the waits the retry asked for, which is what these tests assert instead of sleeping. |
| 17 | + */ |
| 18 | +function failing(codes: string[], land?: (from: string, to: string) => Promise<void>) { |
| 19 | + const calls = { attempts: 0, waits: [] as number[] } |
| 20 | + return { |
| 21 | + calls, |
| 22 | + rename: async (from: string, to: string) => { |
| 23 | + const code = codes[calls.attempts] |
| 24 | + calls.attempts++ |
| 25 | + if (code !== undefined) throw lockError(code) |
| 26 | + await land?.(from, to) |
| 27 | + }, |
| 28 | + wait: async (ms: number) => { |
| 29 | + calls.waits.push(ms) |
| 30 | + }, |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +async function failure(promise: Promise<void>) { |
| 35 | + return promise.then( |
| 36 | + () => undefined, |
| 37 | + (error: unknown) => error, |
| 38 | + ) |
| 39 | +} |
| 40 | + |
| 41 | +async function leftovers(directory: string) { |
| 42 | + return (await readdir(directory)).filter((entry) => entry.endsWith(".tmp")) |
| 43 | +} |
| 44 | + |
| 45 | +describe("writeJsonAtomic rename retry", () => { |
| 46 | + test("lands the rename on the second attempt after waiting 50ms", async () => { |
| 47 | + const directory = await root() |
| 48 | + try { |
| 49 | + const target = path.join(directory, "session.json") |
| 50 | + const temporary = path.join(directory, "session.json.new") |
| 51 | + await writeFile(target, '{"pinned":["old"]}') |
| 52 | + await writeFile(temporary, '{"pinned":["new"]}') |
| 53 | + const lock = failing(["EPERM"], rename) |
| 54 | + |
| 55 | + await renameWithRetry(temporary, target, lock) |
| 56 | + |
| 57 | + expect(lock.calls.attempts).toBe(2) |
| 58 | + expect(lock.calls.waits).toEqual([50]) |
| 59 | + expect(await readFile(target, "utf8")).toBe('{"pinned":["new"]}') |
| 60 | + expect(await leftovers(directory)).toEqual([]) |
| 61 | + } finally { |
| 62 | + await rm(directory, { recursive: true, force: true }) |
| 63 | + } |
| 64 | + }) |
| 65 | + |
| 66 | + test("rethrows the last lock error after the first attempt plus 50, 150 and 450ms retries", async () => { |
| 67 | + const directory = await root() |
| 68 | + try { |
| 69 | + const target = path.join(directory, "session.json") |
| 70 | + await writeFile(target, '{"pinned":["old"]}') |
| 71 | + const lock = failing(["EPERM", "EBUSY", "EPERM", "EBUSY"]) |
| 72 | + |
| 73 | + const caught = await failure(writeJsonAtomic(target, { pinned: ["new"] }, lock)) |
| 74 | + |
| 75 | + expect(caught).toBeInstanceOf(Error) |
| 76 | + expect(lock.calls.attempts).toBe(4) |
| 77 | + expect(lock.calls.waits).toEqual([50, 150, 450]) |
| 78 | + // Only a rename that succeeded replaces the destination, so the old file is still whole, and |
| 79 | + // the staging file is removed rather than left for a reader to mistake for state. |
| 80 | + expect(await readJson(target)).toEqual({ pinned: ["old"] }) |
| 81 | + expect(await leftovers(directory)).toEqual([]) |
| 82 | + } finally { |
| 83 | + await rm(directory, { recursive: true, force: true }) |
| 84 | + } |
| 85 | + }) |
| 86 | + |
| 87 | + const other = [ |
| 88 | + { name: "EACCES", code: "EACCES" }, |
| 89 | + { name: "ENOENT", code: "ENOENT" }, |
| 90 | + { name: "no error code", code: "" }, |
| 91 | + ] |
| 92 | + |
| 93 | + for (const item of other) { |
| 94 | + test(`does not retry a rename that failed with ${item.name}`, async () => { |
| 95 | + const directory = await root() |
| 96 | + try { |
| 97 | + const target = path.join(directory, "session.json") |
| 98 | + await writeFile(target, '{"pinned":["old"]}') |
| 99 | + const cause = item.code ? lockError(item.code) : new Error("rename failed") |
| 100 | + const waits: number[] = [] |
| 101 | + let attempts = 0 |
| 102 | + |
| 103 | + const caught = await failure( |
| 104 | + writeJsonAtomic( |
| 105 | + target, |
| 106 | + { pinned: ["new"] }, |
| 107 | + { |
| 108 | + rename: async () => { |
| 109 | + attempts++ |
| 110 | + throw cause |
| 111 | + }, |
| 112 | + wait: async (ms: number) => { |
| 113 | + waits.push(ms) |
| 114 | + }, |
| 115 | + }, |
| 116 | + ), |
| 117 | + ) |
| 118 | + |
| 119 | + expect(caught).toBe(cause) |
| 120 | + expect(attempts).toBe(1) |
| 121 | + expect(waits).toEqual([]) |
| 122 | + expect(await readJson(target)).toEqual({ pinned: ["old"] }) |
| 123 | + expect(await leftovers(directory)).toEqual([]) |
| 124 | + } finally { |
| 125 | + await rm(directory, { recursive: true, force: true }) |
| 126 | + } |
| 127 | + }) |
| 128 | + } |
| 129 | + |
| 130 | + // The lock this retry exists for only happens on Windows: every handle node:fs opens grants |
| 131 | + // FILE_SHARE_READ|WRITE|DELETE, so two node:fs handles never contend and a rename always wins. |
| 132 | + // Asking for a narrower dwShareMode needs Win32, and bun:ffi reaches it without a native build. |
| 133 | + // A scanner such as antivirus or the search indexer holds a state file with FILE_SHARE_READ|WRITE, |
| 134 | + // which permits writing through the open handle but not replacing the file. |
| 135 | + function holdOpen(file: string) { |
| 136 | + const GENERIC_READ = 0x80000000 |
| 137 | + const FILE_SHARE_READ = 0x00000001 |
| 138 | + const FILE_SHARE_WRITE = 0x00000002 |
| 139 | + const OPEN_EXISTING = 3 |
| 140 | + const kernel32 = dlopen("kernel32.dll", { |
| 141 | + CreateFileW: { |
| 142 | + args: [FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.ptr], |
| 143 | + returns: FFIType.ptr, |
| 144 | + }, |
| 145 | + CloseHandle: { args: [FFIType.ptr], returns: FFIType.i32 }, |
| 146 | + }) |
| 147 | + const wide = Buffer.from(`${file}\0`, "utf16le") |
| 148 | + const handle = kernel32.symbols.CreateFileW( |
| 149 | + ptr(wide), |
| 150 | + GENERIC_READ, |
| 151 | + FILE_SHARE_READ | FILE_SHARE_WRITE, |
| 152 | + null, |
| 153 | + OPEN_EXISTING, |
| 154 | + 0, |
| 155 | + null, |
| 156 | + ) |
| 157 | + if (handle === null) throw new Error(`could not open a handle on ${file}`) |
| 158 | + return { release: () => kernel32.symbols.CloseHandle(handle) } |
| 159 | + } |
| 160 | + |
| 161 | + const windowsTest = test.skipIf(process.platform !== "win32") |
| 162 | + |
| 163 | + windowsTest("retries a destination a real Windows handle holds, then reports the lock", async () => { |
| 164 | + const directory = await root() |
| 165 | + const target = path.join(directory, "session.json") |
| 166 | + await writeFile(target, '{"pinned":["old"]}') |
| 167 | + const holder = holdOpen(target) |
| 168 | + const waits: number[] = [] |
| 169 | + |
| 170 | + let caught: unknown |
| 171 | + try { |
| 172 | + caught = await failure( |
| 173 | + writeJsonAtomic( |
| 174 | + target, |
| 175 | + { pinned: ["new"] }, |
| 176 | + { |
| 177 | + wait: async (ms: number) => { |
| 178 | + waits.push(ms) |
| 179 | + }, |
| 180 | + }, |
| 181 | + ), |
| 182 | + ) |
| 183 | + } finally { |
| 184 | + holder.release() |
| 185 | + } |
| 186 | + |
| 187 | + // The real rename is the one under test here, so the lock is whatever Windows reports for it. |
| 188 | + expect(caught).toBeInstanceOf(Error) |
| 189 | + expect((caught as Error).message).toMatch(/EPERM|EBUSY/) |
| 190 | + expect(waits).toEqual([50, 150, 450]) |
| 191 | + expect(await readJson(target)).toEqual({ pinned: ["old"] }) |
| 192 | + expect(await leftovers(directory)).toEqual([]) |
| 193 | + }) |
| 194 | + |
| 195 | + test("a detached write reports its failure and the returned promise never rejects", async () => { |
| 196 | + const directory = await root() |
| 197 | + try { |
| 198 | + const target = path.join(directory, "session.json") |
| 199 | + await writeFile(target, '{"pinned":["old"]}') |
| 200 | + const cause = lockError("EPERM") |
| 201 | + const reported: unknown[] = [] |
| 202 | + |
| 203 | + const landed = await writeJsonAtomicDetached( |
| 204 | + target, |
| 205 | + { pinned: ["new"] }, |
| 206 | + (error) => { |
| 207 | + reported.push(error) |
| 208 | + }, |
| 209 | + { |
| 210 | + rename: async () => { |
| 211 | + throw cause |
| 212 | + }, |
| 213 | + wait: async () => undefined, |
| 214 | + }, |
| 215 | + ) |
| 216 | + |
| 217 | + expect(landed).toBeUndefined() |
| 218 | + expect(reported).toEqual([cause]) |
| 219 | + expect(await readJson(target)).toEqual({ pinned: ["old"] }) |
| 220 | + expect(await leftovers(directory)).toEqual([]) |
| 221 | + } finally { |
| 222 | + await rm(directory, { recursive: true, force: true }) |
| 223 | + } |
| 224 | + }) |
| 225 | +}) |
0 commit comments