|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 2 | +import { promises as fs } from 'node:fs'; |
| 3 | +import os from 'node:os'; |
| 4 | +import path from 'node:path'; |
| 5 | +import { setTimeout as sleep } from 'node:timers/promises'; |
| 6 | +import { withDirectoryLock } from '../file-lock.js'; |
| 7 | + |
| 8 | +let directory: string; |
| 9 | +let file: string; |
| 10 | + |
| 11 | +beforeEach(async () => { |
| 12 | + directory = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-memory-lease-')); |
| 13 | + file = path.join(directory, 'memory.jsonl'); |
| 14 | +}); |
| 15 | + |
| 16 | +afterEach(async () => { |
| 17 | + vi.restoreAllMocks(); |
| 18 | + await fs.rm(directory, { recursive: true, force: true }); |
| 19 | +}); |
| 20 | + |
| 21 | +// Obtain the fixture through the public lease API so it follows the on-disk |
| 22 | +// protocol, then model a holder that disappeared without releasing it. The |
| 23 | +// operation itself resolves (it parks the lease); the loss surfaces only at |
| 24 | +// release, where a resolved operation is final and the lease stays parked. |
| 25 | +async function abandonLease(): Promise<void> { |
| 26 | + const lockPath = `${file}.lock`; |
| 27 | + const parked = `${file}.abandoned`; |
| 28 | + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 29 | + await withDirectoryLock(file, () => fs.rename(lockPath, parked), { timeoutMs: 1000 }); |
| 30 | + errors.mockRestore(); |
| 31 | + await fs.rename(parked, lockPath); |
| 32 | + const old = new Date(Date.now() - 10000); |
| 33 | + await fs.utimes(lockPath, old, old); |
| 34 | + for (const entry of await fs.readdir(lockPath)) { |
| 35 | + await fs.utimes(path.join(lockPath, entry), old, old); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +describe('memory directory leases', () => { |
| 40 | + it('does not let a delayed stale remover delete a newly acquired lease', async () => { |
| 41 | + await abandonLease(); |
| 42 | + const lockPath = `${file}.lock`; |
| 43 | + const rmdir = fs.rmdir; |
| 44 | + const timing = { staleMs: 500, updateMs: 50, timeoutMs: 2000 }; |
| 45 | + let replacement: Promise<void> | undefined; |
| 46 | + let entered!: () => void; |
| 47 | + const ready = new Promise<void>(resolve => { entered = resolve; }); |
| 48 | + let intercepted = false; |
| 49 | + let active = false; |
| 50 | + let overlapped = false; |
| 51 | + |
| 52 | + vi.spyOn(fs, 'rmdir').mockImplementation(async (target, options) => { |
| 53 | + if (String(target) === lockPath && !intercepted) { |
| 54 | + intercepted = true; |
| 55 | + // A peer removes the old generation and acquires a replacement before |
| 56 | + // this contender's already-authorized rmdir reaches the filesystem. |
| 57 | + await rmdir(target, options); |
| 58 | + replacement = withDirectoryLock(file, async () => { |
| 59 | + active = true; |
| 60 | + entered(); |
| 61 | + await sleep(150); |
| 62 | + active = false; |
| 63 | + }, timing); |
| 64 | + await ready; |
| 65 | + } |
| 66 | + return rmdir(target, options); |
| 67 | + }); |
| 68 | + |
| 69 | + const first = await Promise.allSettled([ |
| 70 | + withDirectoryLock(file, async () => { overlapped = active; }, timing), |
| 71 | + ]); |
| 72 | + const second = await Promise.allSettled([replacement]); |
| 73 | + expect(intercepted).toBe(true); |
| 74 | + expect(overlapped).toBe(false); |
| 75 | + expect(first[0].status).toBe('fulfilled'); |
| 76 | + expect(second[0].status).toBe('fulfilled'); |
| 77 | + }); |
| 78 | + |
| 79 | + it('does not adopt a replacement installed before acquisition finishes', async () => { |
| 80 | + const lockPath = `${file}.lock`; |
| 81 | + const mkdir = fs.mkdir; |
| 82 | + const rename = fs.rename; |
| 83 | + let replaced = false; |
| 84 | + let entered = false; |
| 85 | + const replace = async () => { |
| 86 | + replaced = true; |
| 87 | + await fs.rm(lockPath, { recursive: true }); |
| 88 | + await mkdir(lockPath); |
| 89 | + }; |
| 90 | + vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => { |
| 91 | + await rename(from, to); |
| 92 | + if (String(to) === lockPath && !replaced) await replace(); |
| 93 | + }); |
| 94 | + await expect(withDirectoryLock(file, async () => { entered = true; }, { timeoutMs: 1000 })) |
| 95 | + .rejects.toThrow('Memory file lock lost'); |
| 96 | + expect(entered).toBe(false); |
| 97 | + expect((await fs.stat(lockPath)).isDirectory()).toBe(true); |
| 98 | + }); |
| 99 | + |
| 100 | + it('times out without entering another holder\'s critical section', async () => { |
| 101 | + const timing = { staleMs: 1000, updateMs: 100, timeoutMs: 1000 }; |
| 102 | + await withDirectoryLock(file, async () => { |
| 103 | + await expect(withDirectoryLock(file, () => fs.writeFile(file, 'must not be written'), { |
| 104 | + ...timing, |
| 105 | + timeoutMs: 25, |
| 106 | + })).rejects.toThrow('Timed out waiting'); |
| 107 | + await expect(fs.stat(file)).rejects.toMatchObject({ code: 'ENOENT' }); |
| 108 | + expect((await fs.stat(`${file}.lock`)).isDirectory()).toBe(true); |
| 109 | + }, timing); |
| 110 | + }); |
| 111 | + |
| 112 | + it('accepts the timestamp precision actually stored by the filesystem', async () => { |
| 113 | + const utimes = fs.utimes; |
| 114 | + let holding = false; |
| 115 | + let updated!: () => void; |
| 116 | + const heartbeat = new Promise<void>(resolve => { updated = resolve; }); |
| 117 | + vi.spyOn(fs, 'utimes').mockImplementation(async (target, atime, mtime) => { |
| 118 | + const seconds = mtime instanceof Date ? mtime.getTime() / 1000 : Number(mtime); |
| 119 | + await utimes(target, atime, Math.floor(seconds)); |
| 120 | + if (holding) updated(); |
| 121 | + }); |
| 122 | + await expect(withDirectoryLock(file, async assertOwned => { |
| 123 | + holding = true; |
| 124 | + await heartbeat; |
| 125 | + await assertOwned(); |
| 126 | + return 'still owned'; |
| 127 | + }, { staleMs: 3000, updateMs: 20, timeoutMs: 100 })).resolves.toBe('still owned'); |
| 128 | + }); |
| 129 | + |
| 130 | + it('stops renewing and leaves a replacement lease untouched', async () => { |
| 131 | + let replacementMtime = 0; |
| 132 | + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 133 | + await expect(withDirectoryLock(file, async () => { |
| 134 | + await fs.rm(`${file}.lock`, { recursive: true }); |
| 135 | + await fs.mkdir(`${file}.lock`); |
| 136 | + const replacementTime = new Date(Date.now() + 10000); |
| 137 | + await fs.utimes(`${file}.lock`, replacementTime, replacementTime); |
| 138 | + replacementMtime = (await fs.stat(`${file}.lock`)).mtimeMs; |
| 139 | + await sleep(80); |
| 140 | + }, { staleMs: 1000, updateMs: 20, timeoutMs: 100 })).resolves.toBeUndefined(); |
| 141 | + errors.mockRestore(); |
| 142 | + expect((await fs.stat(`${file}.lock`)).mtimeMs).toBe(replacementMtime); |
| 143 | + }); |
| 144 | + |
| 145 | + it('does not mask an operation error when releasing its directory also fails', async () => { |
| 146 | + const failure = new Error('operation failed'); |
| 147 | + vi.spyOn(fs, 'rmdir').mockRejectedValueOnce(new Error('release failed')); |
| 148 | + vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 149 | + await expect(withDirectoryLock(file, async () => { throw failure; }, { timeoutMs: 1000 })).rejects.toBe(failure); |
| 150 | + }); |
| 151 | + |
| 152 | + it('keeps a live holder exclusive for longer than the stale interval', async () => { |
| 153 | + let entered!: () => void; |
| 154 | + const ready = new Promise<void>(resolve => { entered = resolve; }); |
| 155 | + const timing = { staleMs: 100, updateMs: 20, timeoutMs: 1000 }; |
| 156 | + let active = false; |
| 157 | + let overlapped = false; |
| 158 | + const first = withDirectoryLock(file, async () => { |
| 159 | + active = true; |
| 160 | + entered(); |
| 161 | + await sleep(350); |
| 162 | + active = false; |
| 163 | + }, timing); |
| 164 | + await ready; |
| 165 | + const second = withDirectoryLock(file, async () => { overlapped = active; }, timing); |
| 166 | + await Promise.all([first, second]); |
| 167 | + expect(overlapped).toBe(false); |
| 168 | + }); |
| 169 | + |
| 170 | + it('recovers an abandoned lease without requiring the data file to exist', async () => { |
| 171 | + await abandonLease(); |
| 172 | + |
| 173 | + await expect(withDirectoryLock(file, async () => 'recovered', { |
| 174 | + staleMs: 500, |
| 175 | + updateMs: 50, |
| 176 | + timeoutMs: 100, |
| 177 | + })).resolves.toBe('recovered'); |
| 178 | + await expect(fs.stat(`${file}.lock`)).rejects.toMatchObject({ code: 'ENOENT' }); |
| 179 | + }); |
| 180 | +}); |
0 commit comments