dsh-sansheng-liubu/sansheng/test/store.test.js

307 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import { SanshengStore } from '../src/store.js'
const project = {
id: 'prj-1',
name: '示例项目',
workspaceId: 'ws-1',
roomId: 'room-1',
bots: { lead: 'b-lead', shangshu: 'b-shang', gongbu: 'b-gong' },
models: {},
maxReworks: 3,
}
function review(overrides = {}) {
return {
id: 'rev-1',
projectId: 'prj-1',
goalId: 'goal-1',
goalRevision: 2,
kind: 'stage',
stageIndex: 1,
digest: 'abc',
verdict: 'pass',
reviewerRole: 'shangshu',
eventKey: 'same',
at: 1,
...overrides,
}
}
test('项目绑定与审查记录可持久化、可反查', async () => {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const file = join(dir, 'state.json')
const store = new SanshengStore(file)
await store.load()
await store.saveProject(project)
assert.equal(store.projectByRoom('room-1').id, 'prj-1')
assert.equal(store.projectByBot('b-gong').id, 'prj-1')
assert.equal(store.resolveProject('示例项目').id, 'prj-1')
const first = await store.addReview(review())
assert.equal(first.duplicate, false)
const second = await store.addReview(review({ id: 'rev-2' }))
assert.equal(second.duplicate, true)
assert.equal(store.peek().reviews.length, 1)
const reloaded = new SanshengStore(file)
await reloaded.load()
assert.equal(reloaded.peek().projects['prj-1'].name, '示例项目')
assert.equal(reloaded.peek().reviews.length, 1)
assert.equal(reloaded.reviewsFor({ projectId: 'prj-1' }).length, 1)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('v2 状态迁移到 v3:旧项目/审查保留,新字段补齐', async () => {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const file = join(dir, 'state.json')
const { writeFile } = await import('node:fs/promises')
await writeFile(file, JSON.stringify({
version: 2,
projects: { 'prj-old': { ...project, id: 'prj-old', roomId: 'room-old', bots: { lead: 'o-1', shangshu: 'o-2', gongbu: 'o-3' } } },
reviews: [{ id: 'rev-old', projectId: 'prj-old', kind: 'stage', verdict: 'pass', digest: 'x', at: 1 }],
dispatches: [],
reworks: [],
events: [],
}), 'utf8')
const store = new SanshengStore(file)
await store.load()
assert.equal(store.peek().version, 3)
assert.equal(store.projectById('prj-old').submissionSeq, 0)
assert.deepEqual(store.projectById('prj-old').delivery, { include: [], exclude: [] })
assert.equal(store.peek().reviews.length, 1)
assert.equal(typeof store.peek().artifacts, 'object')
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('commitArtifact 推进提交代次并保存快照', async () => {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const store = new SanshengStore(join(dir, 'state.json'))
await store.load()
await store.saveProject({ ...project })
const first = await store.commitArtifact('prj-1', { id: 'art-1', projectId: 'prj-1', digest: 'd1', createdAt: 1 })
assert.equal(first.submissionSeq, 1)
const second = await store.commitArtifact('prj-1', { id: 'art-2', projectId: 'prj-1', digest: 'd2', createdAt: 2 })
assert.equal(second.submissionSeq, 2)
assert.equal(store.projectById('prj-1').submissionSeq, 2)
assert.equal(store.artifactById('art-2').submissionSeq, 2)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('状态文件损坏时 load 明确报错而不是静默清空', async () => {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const file = join(dir, 'state.json')
const { writeFile } = await import('node:fs/promises')
await writeFile(file, '{not json', 'utf8')
const store = new SanshengStore(file)
await assert.rejects(() => store.load(), /读不了/)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('Q01:合法 JSON 的错误 schema 不被当成健康空状态,registry 不被覆盖', async () => {
const { readFile, writeFile } = await import('node:fs/promises')
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const file = join(dir, 'state.json')
const seed = new SanshengStore(file)
await seed.load()
await seed.saveProject({ ...project })
const registryBefore = await readFile(join(dir, 'registry.json'), 'utf8')
const payloads = [
'null',
'[]',
JSON.stringify({ version: 99, projects: {}, reviews: [], dispatches: [], reworks: [], events: [] }),
JSON.stringify({ version: 3, projects: [], reviews: [], dispatches: [], reworks: [], events: [] }),
JSON.stringify({ version: 3, projects: { 'prj-1': { ...project, bots: { lead: 'only-one' } } }, reviews: [], dispatches: [], reworks: [], events: [] }),
]
for (const payload of payloads) {
await writeFile(file, payload, 'utf8')
const store = new SanshengStore(file)
await assert.rejects(() => store.load(), /schema 非法/)
assert.equal(store.health().status, 'broken')
assert.equal(store.registryProjectForRoom('room-1'), 'prj-1', '错误 schema 不得覆盖既有 registry')
assert.equal(await readFile(join(dir, 'registry.json'), 'utf8'), registryBefore)
}
// 主状态为空但 registry 仍记录项目,也不能当作健康空状态。
await writeFile(file, JSON.stringify({ version: 3, seq: 0, projects: {}, reviews: [], dispatches: [], reworks: [], artifacts: {}, leases: {}, events: [] }), 'utf8')
const empty = new SanshengStore(file)
await assert.rejects(() => empty.load(), /registry 仍记录/)
assert.equal(empty.health().status, 'broken')
assert.equal(empty.registryProjectForBot('b-lead'), 'prj-1')
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('Q06:事务在落盘前对同步读取不可见', async () => {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const store = new SanshengStore(join(dir, 'state.json'))
await store.load()
await store.saveProject({ ...project })
let released
const gate = new Promise(resolve => { released = resolve })
const running = store.transact(async state => {
state.projects['prj-1'].name = '未提交草稿'
await gate
return 'ok'
})
await new Promise(resolve => setTimeout(resolve, 10))
assert.equal(store.projectById('prj-1').name, '示例项目', '事务中的草稿不应被读到')
released()
assert.equal(await running, 'ok')
assert.equal(store.projectById('prj-1').name, '未提交草稿')
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('Q09:核实派发必须校验 projectId,不能跨项目改状态', async () => {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const store = new SanshengStore(join(dir, 'state.json'))
await store.load()
await store.saveProject({ ...project })
await store.beginDispatch({ id: 'dsp-q09', projectId: 'prj-1', action: 'pass' })
await store.reconcileDispatches('boot-q09')
const wrong = await store.resolveDispatch('dsp-q09', 'done', 'user', 'prj-other')
assert.equal(wrong.wrongProject, true)
assert.equal(store.peek().dispatches.find(item => item.id === 'dsp-q09').status, 'unknown')
const right = await store.resolveDispatch('dsp-q09', 'done', 'user', 'prj-1', { withEvent: true })
assert.equal(right.changed, true)
assert.equal(right.record.status, 'confirmed')
const reconcileEvents = store.peek().events.filter(item => item.kind === 'reconcile')
assert.equal(reconcileEvents.length, 1, '核实事件与状态更新同一事务写入')
assert.equal(reconcileEvents[0].projectId, 'prj-1')
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('Q01b:主状态缺失但 registry 仍在时 health=missing 且保留治理身份', async () => {
const { rm } = await import('node:fs/promises')
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const file = join(dir, 'state.json')
const seed = new SanshengStore(file)
await seed.load()
await seed.saveProject({ ...project })
await rm(file)
const store = new SanshengStore(file)
await store.load()
assert.equal(store.health().status, 'missing')
assert.equal(store.health().registryStatus, 'ok')
assert.equal(store.health().writable, false)
assert.equal(store.registryProjectForRoom('room-1'), 'prj-1')
assert.equal(store.registryProjectForBot('b-lead'), 'prj-1')
await assert.rejects(() => store.reconcileDispatches('boot-missing'), /state-protected|写操作已停止/)
const after = new SanshengStore(file)
await after.load()
assert.equal(after.registryProjectForRoom('room-1'), 'prj-1', '启动对账不得覆盖 registry')
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('Q08:不同项目指向同一工作根也共享独占租约', async () => {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
try {
const store = new SanshengStore(join(dir, 'state.json'))
await store.load()
const first = await store.acquireRootLease('C:\\work\\shared', { holder: 'a', taskId: 't1' })
assert.equal(first.ok, true)
const second = await store.acquireRootLease('C:/work/shared/', { holder: 'b', taskId: 't2' })
assert.equal(second.ok, false)
assert.match(second.reason, /同一实际路径不能并发写/)
assert.equal((await store.releaseRootLease('C:\\work\\shared', 'a')).ok, true)
assert.equal(store.rootLeaseOf('C:/work/shared'), undefined)
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('Q08c:junction 别名解析到同一物理工作根', async () => {
if (process.platform !== 'win32') return
const { execFileSync } = await import('node:child_process')
const { mkdir } = await import('node:fs/promises')
const dir = await mkdtemp(join(tmpdir(), 'sansheng-alias-'))
const real = join(dir, 'real-root')
const alias = join(dir, 'alias-root')
try {
await mkdir(real)
execFileSync('cmd', ['/c', 'mklink', '/J', alias, real], { stdio: 'ignore' })
const store = new SanshengStore(join(dir, 'state.json'))
await store.load()
assert.equal((await store.acquireRootLease(real, { holder: 'a' })).ok, true)
const second = await store.acquireRootLease(alias, { holder: 'b' })
assert.equal(second.ok, false, 'junction 别名不能绕过根租约')
} finally {
try { execFileSync('cmd', ['/c', 'rmdir', alias], { stdio: 'ignore' }) } catch { /* not made */ }
await rm(dir, { recursive: true, force: true })
}
})
test('Q08d:崩溃遗留的根租约到期后可被新持有者接管', async () => {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-expire-'))
try {
const store = new SanshengStore(join(dir, 'state.json'))
await store.load()
assert.equal((await store.acquireRootLease(dir, { holder: 'crashed', ttlMs: 30 })).ok, true)
await new Promise(resolve => setTimeout(resolve, 60))
const next = await store.acquireRootLease(dir, { holder: 'next' })
assert.equal(next.ok, true)
assert.equal(store.rootLeaseOf(dir).holder, 'next')
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('R4-03:registry 的合法 JSON、错误 schema 不再当健康空登记', async () => {
const { readFile, writeFile } = await import('node:fs/promises')
const dir = await mkdtemp(join(tmpdir(), 'sansheng-registry-'))
try {
const file = join(dir, 'state.json')
const seed = new SanshengStore(file)
await seed.load()
await seed.saveProject({ ...project })
const registryBefore = await readFile(join(dir, 'registry.json'), 'utf8')
const bad = [
{ version: 1, rooms: [], bots: [] },
{ rooms: {}, bots: {} },
{ version: 99, rooms: {}, bots: {}, updatedAt: 1 },
{ version: 1, rooms: { 'room-1': 7 }, bots: {}, updatedAt: 1 },
{ version: 1, rooms: {}, bots: { 'b-lead': '' }, updatedAt: 1 },
{ version: 1, rooms: {}, bots: {}, updatedAt: 'now' },
]
for (const payload of bad) {
await writeFile(join(dir, 'registry.json'), JSON.stringify(payload), 'utf8')
const store = new SanshengStore(file)
await store.load()
assert.equal(store.health().status, 'broken', JSON.stringify(payload))
assert.equal(store.health().writable, false)
assert.equal(store.health().registryStatus, 'broken')
await assert.rejects(() => store.transact(() => {}), error => error.code === 'state-protected')
assert.equal(await readFile(join(dir, 'registry.json'), 'utf8'), JSON.stringify(payload), '不得覆盖坏 registry')
}
} finally {
await rm(dir, { recursive: true, force: true })
}
})