import test from 'node:test' import assert from 'node:assert/strict' import {mkdtemp, chmod, readdir, writeFile, readFile, unlink, rm} from 'node:fs/promises' import {tmpdir} from 'node:os' import path from 'node:path' import {withJournalLease} from './operator-files.mjs' const posix = process.platform !== 'win32' async function owned(work) { const directory = await mkdtemp(path.join(tmpdir(), 'mm-operator-lease-')) try { await chmod(directory, 0o700); await work(directory) } finally { await rm(directory, {recursive: true, force: true}) } } test('Windows refuses before callback or lease creation', {skip: posix}, async () => { await owned(async directory => { let called = false await assert.rejects(withJournalLease(directory, async () => { called = true }), /Windows ACL/) assert.equal(called, false) assert.deepEqual(await readdir(directory), []) }) }) test('POSIX cooperative exclusion spans the entire callback and cleanup', {skip: !posix}, async () => { await owned(async directory => { let entered, release const ready = new Promise(resolve => { entered = resolve }) const held = new Promise(resolve => { release = resolve }) const first = withJournalLease(directory, async () => { entered(); await held; return 'first' }) await ready try { let secondCalled = false await assert.rejects(withJournalLease(directory, async () => { secondCalled = true }), {code: 'EEXIST'}) assert.equal(secondCalled, false) assert.deepEqual(await readdir(directory), ['publisher-lease.lock']) } finally { release(); await first } assert.deepEqual(await readdir(directory), []) assert.equal(await withJournalLease(directory, async () => 'next'), 'next') }) }) test('POSIX unknown work retains its pending cursor and original error', {skip: !posix}, async () => { await owned(async directory => { const pending = path.join(directory, 'pending-publication.json'), failure = new Error('unknown publication') await assert.rejects(withJournalLease(directory, async () => { await writeFile(pending, 'pending', {flag: 'wx', mode: 0o600}) throw failure }), error => error === failure) assert.equal(await readFile(pending, 'utf8'), 'pending') assert.deepEqual(await readdir(directory), ['pending-publication.json']) }) }) test('POSIX foreign replacement remains and known COMMIT survives cleanup refusal', {skip: !posix}, async () => { await owned(async directory => { const lease = path.join(directory, 'publisher-lease.lock') const result = await withJournalLease(directory, async () => { await unlink(lease) await writeFile(lease, 'foreign lease', {flag: 'wx', mode: 0o600}) return {outcome: 'committed', epoch: '9', headSha256: 'a'.repeat(64)} }) assert.equal(result.outcome, 'committed') assert.equal(result.epoch, '9') assert.equal(result.journalUnconfirmed, true) assert.equal(await readFile(lease, 'utf8'), 'foreign lease') await assert.rejects(withJournalLease(directory, async () => assert.fail('foreign lease was adopted')), {code: 'EEXIST'}) }) })