transaction.spec.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import { afterAll, describe, expect, it } from 'vitest'
  2. import * as fs from 'node:fs'
  3. import * as path from 'node:path'
  4. import * as os from 'node:os'
  5. import { createHash } from 'node:crypto'
  6. import { recoverTransactions, runTransaction, withBookLock, writeBatchAtomic } from '../src'
  7. const roots: string[] = []
  8. function mkRoot(): string {
  9. const root = fs.mkdtempSync(path.join(os.tmpdir(), 'webnovel-txn-'))
  10. roots.push(root)
  11. return root
  12. }
  13. afterAll(() => { for (const root of roots) { try { fs.rmSync(root, { recursive: true, force: true }) } catch { /* temp cleanup */ } } })
  14. describe('书仓写入锁', () => {
  15. it('同一进程嵌套可重入,退出后锁清理', () => {
  16. const root = mkRoot()
  17. const seen: string[] = []
  18. withBookLock(root, () => {
  19. seen.push('outer')
  20. withBookLock(root, () => { seen.push('inner') })
  21. })
  22. expect(seen).toEqual(['outer', 'inner'])
  23. expect(fs.existsSync(path.join(root, '.webnovel', 'book.lock'))).toBe(false)
  24. })
  25. it('活跃锁拒绝第二个写入者,不会盲删锁', () => {
  26. const root = mkRoot()
  27. fs.mkdirSync(path.join(root, '.webnovel'), { recursive: true })
  28. fs.writeFileSync(path.join(root, '.webnovel', 'book.lock'), JSON.stringify({ pid: process.pid }) + '\n', 'utf-8')
  29. expect(() => withBookLock(root, () => undefined)).toThrow(/写入锁定中/)
  30. expect(fs.existsSync(path.join(root, '.webnovel', 'book.lock'))).toBe(true)
  31. })
  32. })
  33. describe('多文件事务恢复', () => {
  34. it('中断批次恢复既有目标并删除新目标与同目录临时文件', () => {
  35. const root = mkRoot()
  36. const id = 'crashed'
  37. const tx = path.join(root, '.webnovel', 'transactions', id)
  38. fs.mkdirSync(path.join(tx, 'backups'), { recursive: true })
  39. fs.mkdirSync(path.join(root, '正文'), { recursive: true })
  40. fs.writeFileSync(path.join(root, '正文', '旧.md'), '新内容\n', 'utf-8')
  41. fs.writeFileSync(path.join(tx, 'backups', '0.bak'), '旧内容\n', 'utf-8')
  42. fs.writeFileSync(path.join(root, '正文', '.webnovel-txn-crashed-1.tmp'), '临时\n', 'utf-8')
  43. fs.writeFileSync(path.join(root, '正文', '新.md'), '新目标\n', 'utf-8')
  44. const hash = createHash('sha256').update('新内容\n').digest('hex')
  45. fs.writeFileSync(path.join(tx, 'manifest.json'), JSON.stringify({
  46. schemaVersion: 1,
  47. id,
  48. createdAt: new Date().toISOString(),
  49. phase: 'applying',
  50. entries: [
  51. { relPath: '正文/旧.md', tmpRel: `正文/.webnovel-txn-${id}-0.tmp`, backupRel: `.webnovel/transactions/${id}/backups/0.bak`, originalHash: createHash('sha256').update('旧内容\n').digest('hex'), hadOriginal: true, backupRecorded: true, applied: true, contentHash: hash },
  52. { relPath: '正文/新.md', tmpRel: `正文/.webnovel-txn-${id}-1.tmp`, backupRel: `.webnovel/transactions/${id}/backups/1.bak`, originalHash: null, hadOriginal: false, backupRecorded: true, applied: true, contentHash: createHash('sha256').update('新目标\n').digest('hex') },
  53. ],
  54. }), 'utf-8')
  55. recoverTransactions(root)
  56. expect(fs.readFileSync(path.join(root, '正文', '旧.md'), 'utf-8')).toBe('旧内容\n')
  57. expect(fs.existsSync(path.join(root, '正文', '新.md'))).toBe(false)
  58. expect(fs.existsSync(path.join(root, '正文', '.webnovel-txn-crashed-1.tmp'))).toBe(false)
  59. expect(fs.existsSync(tx)).toBe(false)
  60. })
  61. it('manifest 在 rename 后尚未标记 applied 时按内容指纹恢复', () => {
  62. const root = mkRoot()
  63. const id = 'crashed-after-rename'
  64. const tx = path.join(root, '.webnovel', 'transactions', id)
  65. fs.mkdirSync(path.join(tx, 'backups'), { recursive: true })
  66. fs.mkdirSync(path.join(root, '正文'), { recursive: true })
  67. fs.writeFileSync(path.join(root, '正文', '章.md'), '新\n', 'utf-8')
  68. fs.writeFileSync(path.join(tx, 'backups', '0.bak'), '旧\n', 'utf-8')
  69. fs.writeFileSync(path.join(tx, 'manifest.json'), JSON.stringify({
  70. schemaVersion: 1, id, createdAt: new Date().toISOString(), phase: 'applying',
  71. entries: [{ relPath: '正文/章.md', tmpRel: `正文/.webnovel-txn-${id}-0.tmp`, backupRel: `.webnovel/transactions/${id}/backups/0.bak`, originalHash: createHash('sha256').update('旧\n').digest('hex'), hadOriginal: true, backupRecorded: true, applied: false, contentHash: createHash('sha256').update('新\n').digest('hex') }],
  72. }), 'utf-8')
  73. recoverTransactions(root)
  74. expect(fs.readFileSync(path.join(root, '正文', '章.md'), 'utf-8')).toBe('旧\n')
  75. expect(fs.existsSync(tx)).toBe(false)
  76. })
  77. it('作者在中断后改过目标时不被恢复批次覆盖', () => {
  78. const root = mkRoot()
  79. const id = 'author-edited-after-crash'
  80. const tx = path.join(root, '.webnovel', 'transactions', id)
  81. fs.mkdirSync(path.join(tx, 'backups'), { recursive: true })
  82. fs.mkdirSync(path.join(root, '正文'), { recursive: true })
  83. fs.writeFileSync(path.join(root, '正文', '章.md'), '作者后来修改\n', 'utf-8')
  84. fs.writeFileSync(path.join(tx, 'backups', '0.bak'), '旧\n', 'utf-8')
  85. fs.writeFileSync(path.join(tx, 'manifest.json'), JSON.stringify({
  86. schemaVersion: 1, id, createdAt: new Date().toISOString(), phase: 'applying',
  87. entries: [{ relPath: '正文/章.md', tmpRel: `正文/.webnovel-txn-${id}-0.tmp`, backupRel: `.webnovel/transactions/${id}/backups/0.bak`, originalHash: createHash('sha256').update('旧\n').digest('hex'), hadOriginal: true, backupRecorded: true, applied: true, contentHash: createHash('sha256').update('新\n').digest('hex') }],
  88. }), 'utf-8')
  89. expect(() => recoverTransactions(root)).toThrow(/恢复冲突/)
  90. expect(fs.readFileSync(path.join(root, '正文', '章.md'), 'utf-8')).toBe('作者后来修改\n')
  91. expect(fs.existsSync(tx)).toBe(true)
  92. })
  93. it('正常批次完成后不残留事务目录', () => {
  94. const root = mkRoot()
  95. runTransaction(root, [{ relPath: '正文/章.md', content: '正文\n' }])
  96. expect(fs.readFileSync(path.join(root, '正文', '章.md'), 'utf-8')).toBe('正文\n')
  97. expect(fs.readdirSync(path.join(root, '.webnovel', 'transactions'))).toEqual([])
  98. })
  99. it('传入 provenance 时保留可读的操作审计', () => {
  100. const root = mkRoot()
  101. writeBatchAtomic(root, [{ relPath: '正文/章.md', content: '正文\n' }], {
  102. provenance: {
  103. operationId: 'op-test-001',
  104. sessionId: 'session-test',
  105. agentId: 'agent-test',
  106. toolName: 'novel_import_draft',
  107. callId: 'call-test',
  108. },
  109. })
  110. const audit = JSON.parse(fs.readFileSync(path.join(root, '.webnovel', 'operations', 'op-test-001.json'), 'utf-8')) as Record<string, unknown>
  111. expect(audit.status).toBe('completed')
  112. expect(audit.operationId).toBe('op-test-001')
  113. expect(audit.sessionId).toBe('session-test')
  114. expect(audit.agentId).toBe('agent-test')
  115. expect(audit.toolName).toBe('novel_import_draft')
  116. expect(audit.callId).toBe('call-test')
  117. expect(audit.targets).toEqual(['正文/章.md'])
  118. })
  119. it('事务失败也记录 failed 阶段而不是伪造成功', () => {
  120. const root = mkRoot()
  121. fs.mkdirSync(path.join(root, '占位目录'), { recursive: true })
  122. expect(() => writeBatchAtomic(root, [{ relPath: '占位目录', content: '不能覆盖目录' }], {
  123. provenance: { operationId: 'op-test-failed', toolName: 'test' },
  124. })).toThrow(/B1/)
  125. const audit = JSON.parse(fs.readFileSync(path.join(root, '.webnovel', 'operations', 'op-test-failed.json'), 'utf-8')) as Record<string, unknown>
  126. expect(audit.status).toBe('failed')
  127. expect(String(audit.error)).toMatch(/事务|EPERM|目录/)
  128. })
  129. })