json-backend.spec.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { afterAll, describe, expect, it } from 'vitest'
  5. import { Context } from 'cordis'
  6. import Storage, { storageBackendServiceKey } from '@deepseek-ai/dsh-storage'
  7. import InvariantService from '@deepseek-ai/dsh-invariants'
  8. import { runKvBackendContract } from '../../storage/tests/contract.ts'
  9. import { Config, JsonStorageBackend, apply } from '../src/index.ts'
  10. import * as InvariantCompanion from '../src/invariant.ts'
  11. const roots: string[] = []
  12. async function freshRoot(): Promise<string> {
  13. const root = await mkdtemp(join(tmpdir(), 'dsh-storage-json-'))
  14. roots.push(root)
  15. return root
  16. }
  17. afterAll(async () => {
  18. for (const root of roots) await rm(root, { recursive: true, force: true })
  19. })
  20. runKvBackendContract('json', async () => {
  21. const root = await freshRoot()
  22. return {
  23. backend: new JsonStorageBackend(root),
  24. reopen: async () => new JsonStorageBackend(root),
  25. }
  26. })
  27. describe('json backend specifics', () => {
  28. const descriptor = { name: 'shape', version: 1, tables: ['t'], hasGlobal: true }
  29. it('publishes a human-readable pretty-printed file', async () => {
  30. const root = await freshRoot()
  31. const backend = new JsonStorageBackend(root)
  32. const unit = await backend.kv.open(descriptor)
  33. await unit.putRecord('t', 'k', { hello: 'world' })
  34. const text = await readFile(join(root, 'shape.json'), 'utf8')
  35. expect(text).toBe(`${JSON.stringify(
  36. { unit: { name: 'shape', version: 1 }, global: null, tables: { t: { k: { hello: 'world' } } } },
  37. null,
  38. 2,
  39. )}\n`)
  40. await backend.close()
  41. })
  42. it('defers materialization until the first write', async () => {
  43. const root = await freshRoot()
  44. const backend = new JsonStorageBackend(root)
  45. await backend.kv.open(descriptor)
  46. await expect(readFile(join(root, 'shape.json'), 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
  47. await backend.close()
  48. })
  49. it('rejects a malformed medium', async () => {
  50. const root = await freshRoot()
  51. await writeFile(join(root, 'shape.json'), 'not json at all', 'utf8')
  52. const backend = new JsonStorageBackend(root)
  53. await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' })
  54. await backend.close()
  55. })
  56. it('rejects a foreign unit header', async () => {
  57. const root = await freshRoot()
  58. await writeFile(
  59. join(root, 'shape.json'),
  60. JSON.stringify({ unit: { name: 'other', version: 1 }, global: null, tables: {} }),
  61. 'utf8',
  62. )
  63. const backend = new JsonStorageBackend(root)
  64. await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' })
  65. await backend.close()
  66. })
  67. it('rejects double-open of one unit as a plain caller error', async () => {
  68. const root = await freshRoot()
  69. const backend = new JsonStorageBackend(root)
  70. await backend.kv.open(descriptor)
  71. await expect(backend.kv.open(descriptor)).rejects.toThrow(/already open/)
  72. await backend.close()
  73. })
  74. it('rolls back memory when a publish fails', async () => {
  75. const root = await freshRoot()
  76. const backend = new JsonStorageBackend(root)
  77. const unit = await backend.kv.open(descriptor)
  78. await unit.putRecord('t', 'k', { v: 'committed' })
  79. await unit.setGlobal({ g: 'committed' })
  80. // Make every publish fail: revoke write permission on the root.
  81. await chmod(root, 0o500)
  82. await expect(unit.putRecord('t', 'k', { v: 'rejected' })).rejects.toThrow()
  83. await expect(unit.putRecord('t', 'k2', { v: 'also rejected' })).rejects.toThrow()
  84. await expect(unit.deleteRecord('t', 'k')).rejects.toThrow()
  85. await expect(unit.setGlobal({ g: 'rejected' })).rejects.toThrow()
  86. await chmod(root, 0o700)
  87. const snapshot = await unit.loadAll()
  88. expect(snapshot.tables['t']).toEqual({ k: { v: 'committed' } })
  89. expect(snapshot.global).toEqual({ g: 'committed' })
  90. // The next successful publish must not carry rejected writes to disk.
  91. await unit.putRecord('t', 'k3', { v: 'later' })
  92. const text = await readFile(join(root, 'shape.json'), 'utf8')
  93. expect(text).not.toContain('rejected')
  94. await backend.close()
  95. })
  96. it('rejects undeclared table and global access as caller errors', async () => {
  97. const root = await freshRoot()
  98. const backend = new JsonStorageBackend(root)
  99. const unit = await backend.kv.open({ name: 'shape', version: 1, tables: ['t'], hasGlobal: false })
  100. await expect(unit.putRecord('undeclared', 'k', {})).rejects.toThrow(/does not declare table/)
  101. await expect(unit.setGlobal({})).rejects.toThrow(/does not declare a global slot/)
  102. await backend.close()
  103. })
  104. it('rejects invalid unit and table names', async () => {
  105. const root = await freshRoot()
  106. const backend = new JsonStorageBackend(root)
  107. await expect(backend.kv.open({ ...descriptor, name: 'Bad-Name' })).rejects.toMatchObject({
  108. name: 'StorageError',
  109. code: 'malformed-medium',
  110. })
  111. await expect(backend.kv.open({ ...descriptor, tables: ['ok', 'not ok'] })).rejects.toMatchObject({
  112. name: 'StorageError',
  113. code: 'malformed-medium',
  114. })
  115. await backend.close()
  116. await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'closed' })
  117. })
  118. it('opens a file missing a declared table as that table empty', async () => {
  119. const root = await freshRoot()
  120. await writeFile(
  121. join(root, 'contract_unit.json'),
  122. JSON.stringify({ unit: { name: 'contract_unit', version: 3 }, global: null, tables: { alpha: { k: 1 } } }),
  123. 'utf8',
  124. )
  125. const backend = new JsonStorageBackend(root)
  126. const unit = await backend.kv.open({ name: 'contract_unit', version: 3, tables: ['alpha', 'beta'], hasGlobal: true })
  127. const snapshot = await unit.loadAll()
  128. expect(snapshot.tables['alpha']).toEqual({ k: 1 })
  129. expect(snapshot.tables['beta']).toEqual({})
  130. await backend.close()
  131. })
  132. it('propagates non-ENOENT read failures', async () => {
  133. const root = await freshRoot()
  134. const { mkdir } = await import('node:fs/promises')
  135. // A directory where the unit file should be: readFile fails with EISDIR.
  136. await mkdir(join(root, 'shape.json'))
  137. const backend = new JsonStorageBackend(root)
  138. await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'EISDIR' })
  139. await backend.close()
  140. })
  141. it('rejects malformed table shapes and foreign versions distinctly', async () => {
  142. const root = await freshRoot()
  143. await writeFile(
  144. join(root, 'shape.json'),
  145. JSON.stringify({ unit: { name: 'shape', version: 1 }, global: null, tables: { t: ['not', 'an', 'object'] } }),
  146. 'utf8',
  147. )
  148. const backend = new JsonStorageBackend(root)
  149. await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' })
  150. await writeFile(
  151. join(root, 'shape.json'),
  152. JSON.stringify({ unit: { name: 'shape', version: 9 }, global: null, tables: {} }),
  153. 'utf8',
  154. )
  155. await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'version-mismatch' })
  156. await writeFile(join(root, 'shape.json'), JSON.stringify({ unit: { name: 'shape', version: 1 }, global: null }), 'utf8')
  157. await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' })
  158. await writeFile(join(root, 'shape.json'), JSON.stringify('just a string'), 'utf8')
  159. await expect(backend.kv.open(descriptor)).rejects.toMatchObject({ code: 'malformed-medium' })
  160. await backend.close()
  161. })
  162. it('registers on the hub via apply and closes on dispose', async () => {
  163. const root = await freshRoot()
  164. const ctx = new Context()
  165. await ctx.plugin(Storage)
  166. const fiber = await ctx.plugin({ apply, Config, inject: ['storage'] }, { root })
  167. const backend = ctx.storage.backend.get('json')
  168. expect(ctx.get(storageBackendServiceKey('json'))).toBe(backend)
  169. const unit = await backend.kv!.open(descriptor)
  170. await unit.putRecord('t', 'k', { v: 1 })
  171. await fiber.dispose()
  172. expect(() => ctx.storage.backend.get('json')).toThrow()
  173. expect(ctx.get(storageBackendServiceKey('json'))).toBeUndefined()
  174. await expect(unit.putRecord('t', 'x', {})).rejects.toMatchObject({ code: 'closed' })
  175. })
  176. it('registers the invariant companion and disposes cleanly', async () => {
  177. const ctx = new Context()
  178. await ctx.plugin(InvariantService)
  179. const fiber = await ctx.plugin(InvariantCompanion)
  180. // Disposal releases the reservation: a fresh mount succeeds.
  181. await fiber.dispose()
  182. await ctx.plugin(InvariantCompanion)
  183. })
  184. it('close drains in-flight writes and blocks in-flight opens', async () => {
  185. const root = await freshRoot()
  186. const backend = new JsonStorageBackend(root)
  187. const unit = await backend.kv.open(descriptor)
  188. const bigWrite = unit.putRecord('t', 'big', { blob: 'x'.repeat(4 * 1024 * 1024) })
  189. await unit.close()
  190. await expect(bigWrite).resolves.toBeUndefined()
  191. const onDisk = JSON.parse(await readFile(join(root, 'shape.json'), 'utf8')) as {
  192. tables: Record<string, Record<string, unknown>>
  193. }
  194. expect(onDisk.tables['t']?.['big']).toBeDefined()
  195. const backend2 = new JsonStorageBackend(root)
  196. const opening = backend2.kv.open(descriptor)
  197. const closing = backend2.close()
  198. await expect(opening.then(u => u.putRecord('t', 'x', {}))).rejects.toMatchObject({ code: 'closed' })
  199. await closing
  200. })
  201. })