fs.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /**
  2. * Behavioural check of this package's `node:fs` bridge over a real MemoryVfs:
  3. * encoding branches, Dirent, file descriptors, FileHandle append/replace semantics,
  4. * and Node's error codes.
  5. *
  6. * Every import resolves through `src/` so the harness and bridge share the same
  7. * module-level VFS slot. Mixing the bare package's built entry with `/src/*`
  8. * imports can create two slots, leaving the bridge with no mounted filesystem.
  9. */
  10. import { expect, test } from 'vitest'
  11. import { MemoryVfs } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/memory.ts'
  12. import { setActiveVfs } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/active.ts'
  13. import * as fs from '@deepseek-ai/dsh-experimental-webworker-runtime/src/node/builtin_modules/implemented/fs.ts'
  14. import * as fsp from '@deepseek-ai/dsh-experimental-webworker-runtime/src/node/builtin_modules/implemented/fs/promises.ts'
  15. import type { VfsBigIntStats, VfsMutationSink, VfsStats } from '@deepseek-ai/dsh-experimental-webworker-runtime/src/storage/types.ts'
  16. let flushes = 0
  17. const sink: VfsMutationSink = {
  18. record: () => {},
  19. flush: () => {
  20. flushes += 1
  21. return Promise.resolve()
  22. },
  23. }
  24. const vfs = new MemoryVfs({ sink })
  25. setActiveVfs(vfs)
  26. // Identity precondition: the bridge must read this exact mounted VFS; successful
  27. // calls alone could come from another mounted instance.
  28. fs.mkdirSync('/dsh/.probe', { recursive: true })
  29. fs.writeFileSync('/dsh/.probe/instance', 'x')
  30. if (!vfs.existsSync('/dsh/.probe/instance')) {
  31. throw new Error('fs-check: the fs bridge is not reading the VFS this harness mounted '
  32. + '(two module instances — check that every import resolves through src/)')
  33. }
  34. vfs.rmSync('/dsh/.probe', { recursive: true })
  35. const check = (label: string, actual: unknown, expected: unknown): void => {
  36. const [seen, wanted] = [JSON.stringify(actual), JSON.stringify(expected)]
  37. test(label, () => { expect(seen).toBe(wanted) })
  38. }
  39. const throws = (label: string, run: () => unknown, code: string): void => {
  40. let outcome: string
  41. try {
  42. run()
  43. outcome = 'did not throw'
  44. } catch (error) {
  45. outcome = (error as { code?: string }).code ?? (error as Error).message
  46. }
  47. test(label, () => { expect(outcome).toContain(code) })
  48. }
  49. fs.mkdirSync('/dsh/config', { recursive: true })
  50. fs.writeFileSync('/dsh/config/cordis.yml', '- id: timer\n')
  51. check('readFileSync utf8', fs.readFileSync('/dsh/config/cordis.yml', 'utf8'), '- id: timer\n')
  52. check('readFileSync options object', fs.readFileSync('/dsh/config/cordis.yml', { encoding: 'utf8' }), '- id: timer\n')
  53. check('readFileSync bytes length', (fs.readFileSync('/dsh/config/cordis.yml') as Uint8Array).byteLength, 12)
  54. check('readFileSync is Buffer', Buffer.isBuffer(fs.readFileSync('/dsh/config/cordis.yml')), true)
  55. check('existsSync true', fs.existsSync('/dsh/config/cordis.yml'), true)
  56. check('existsSync false', fs.existsSync('/dsh/nope'), false)
  57. check('statSync isFile', fs.statSync('/dsh/config/cordis.yml').isFile(), true)
  58. check('statSync size', fs.statSync('/dsh/config/cordis.yml').size, 12)
  59. check('statSync dir', fs.statSync('/dsh/config').isDirectory(), true)
  60. check('realpathSync', fs.realpathSync('/dsh/config/../config/cordis.yml'), '/dsh/config/cordis.yml')
  61. fs.appendFileSync('/dsh/config/cordis.yml', '- id: llm\n')
  62. check('appendFileSync', fs.readFileSync('/dsh/config/cordis.yml', 'utf8'), '- id: timer\n- id: llm\n')
  63. fs.mkdirSync('/dsh/config/agent-presets/standard', { recursive: true })
  64. fs.writeFileSync('/dsh/config/agent-presets/standard/SKILL.md', '# skill\n')
  65. check('readdirSync names', fs.readdirSync('/dsh/config'), ['agent-presets', 'cordis.yml'])
  66. const entries = fs.readdirSync('/dsh/config', { withFileTypes: true }) as fs.Dirent[]
  67. check('readdirSync withFileTypes', entries.map(entry => [entry.name, entry.isFile(), entry.isDirectory()]), [
  68. ['agent-presets', false, true],
  69. ['cordis.yml', true, false],
  70. ])
  71. check('Dirent parentPath', entries[0]!.parentPath, '/dsh/config')
  72. const temporary = fs.mkdtempSync('/dsh/tmp/run-')
  73. check('mkdtempSync creates directory', fs.statSync(temporary).isDirectory(), true)
  74. check('mkdtempSync unique', fs.mkdtempSync('/dsh/tmp/run-') === temporary, false)
  75. throws('readFileSync missing', () => fs.readFileSync('/dsh/missing'), 'ENOENT')
  76. throws('statSync missing', () => fs.statSync('/dsh/missing'), 'ENOENT')
  77. throws('accessSync missing', () =>{ fs.accessSync('/dsh/missing') }, 'ENOENT')
  78. throws('readdirSync missing', () => fs.readdirSync('/dsh/missing'), 'ENOENT')
  79. const appendFd = fs.openSync('/dsh/log.jsonl', 'a')
  80. fs.writeSync(appendFd, '{"a":1}\n')
  81. fs.writeSync(appendFd, '{"a":2}\n')
  82. fs.closeSync(appendFd)
  83. check('append fd writes', fs.readFileSync('/dsh/log.jsonl', 'utf8'), '{"a":1}\n{"a":2}\n')
  84. const readFd = fs.openSync('/dsh/log.jsonl', 'r')
  85. const target = new Uint8Array(8)
  86. check('readSync count', fs.readSync(readFd, target, 0, 8), 8)
  87. check('readSync bytes', new TextDecoder().decode(target), '{"a":1}\n')
  88. check('readSync continues', fs.readSync(readFd, target, 0, 8), 8)
  89. check('readSync second line', new TextDecoder().decode(target), '{"a":2}\n')
  90. check('readSync at eof', fs.readSync(readFd, target, 0, 8), 0)
  91. fs.closeSync(readFd)
  92. throws('closed fd', () => fs.readSync(readFd, target, 0, 8), 'EBADF')
  93. const writeFd = fs.openSync('/dsh/truncated.txt', 'w')
  94. fs.writeSync(writeFd, 'abc')
  95. fs.closeSync(writeFd)
  96. check('write fd truncates', fs.readFileSync('/dsh/truncated.txt', 'utf8'), 'abc')
  97. fs.renameSync('/dsh/truncated.txt', '/dsh/renamed.txt')
  98. check('renameSync moves', [fs.existsSync('/dsh/truncated.txt'), fs.readFileSync('/dsh/renamed.txt', 'utf8')], [false, 'abc'])
  99. fs.rmSync('/dsh/renamed.txt')
  100. check('rmSync removes', fs.existsSync('/dsh/renamed.txt'), false)
  101. // A FileHandle opened for appending must append, not replace: the JSONL session
  102. // log writes its header frame first and every batch after it through this path.
  103. fs.writeFileSync('/dsh/log-handle.jsonl', 'header\n')
  104. const appendHandle = await fsp.open('/dsh/log-handle.jsonl', 'a')
  105. check('append handle sees the existing size', (await appendHandle.stat()).size, 7)
  106. await appendHandle.writeFile('batch-1\n')
  107. await appendHandle.sync()
  108. check('handle.sync flushes the active VFS', flushes, 1)
  109. await appendHandle.close()
  110. const secondHandle = await fsp.open('/dsh/log-handle.jsonl', 'a')
  111. await secondHandle.writeFile('batch-2\n')
  112. await secondHandle.close()
  113. check('handle.writeFile appends in append mode', fs.readFileSync('/dsh/log-handle.jsonl', 'utf8'), 'header\nbatch-1\nbatch-2\n')
  114. const replaceHandle = await fsp.open('/dsh/log-handle.jsonl', 'w')
  115. await replaceHandle.writeFile('replaced\n')
  116. await replaceHandle.close()
  117. check('handle.writeFile replaces without append mode', fs.readFileSync('/dsh/log-handle.jsonl', 'utf8'), 'replaced\n')
  118. const truncHandle = await fsp.open('/dsh/log-handle.jsonl', 'r+')
  119. await truncHandle.truncate(4)
  120. await truncHandle.close()
  121. check('handle.truncate cuts the tail', fs.readFileSync('/dsh/log-handle.jsonl', 'utf8'), 'repl')
  122. check('promises.readFile', await fsp.readFile('/dsh/config/cordis.yml', 'utf8'), '- id: timer\n- id: llm\n')
  123. await fsp.writeFile('/dsh/promise.txt', 'p')
  124. check('promises.writeFile', fs.readFileSync('/dsh/promise.txt', 'utf8'), 'p')
  125. check('promises.stat', (await fsp.stat('/dsh/promise.txt')).isFile(), true)
  126. await fsp.cp('/dsh/config', '/dsh/config-copy')
  127. check('promises.cp tree', await fsp.readFile('/dsh/config-copy/agent-presets/standard/SKILL.md', 'utf8'), '# skill\n')
  128. await fsp.rm('/dsh/config-copy', { recursive: true })
  129. check('promises.rm recursive', fs.existsSync('/dsh/config-copy'), false)
  130. // ---------------------------------------------------------------------------
  131. // The `{ bigint: true }` stats the filesystem service reads.
  132. //
  133. // `dsh-fs-local` stats EVERY target this way before it lists or reads: it masks
  134. // `mode` with a BigInt literal and builds its version token from
  135. // `dev:ino:size:mtimeNs:ctimeNs`. A number-valued `mode` here made that mask
  136. // throw `Cannot mix BigInt and other types`, which the service reported as
  137. // FS_IO_ERROR and skill discovery swallowed as "empty directory" — the worker
  138. // booted with an empty skill catalog and no error anywhere.
  139. // ---------------------------------------------------------------------------
  140. const bigStats = (path: string): VfsBigIntStats => fs.statSync(path, { bigint: true }) as VfsBigIntStats
  141. fs.writeFileSync('/dsh/versioned.txt', 'one')
  142. {
  143. const stats = bigStats('/dsh/versioned.txt')
  144. check('bigint stat reports mode as a BigInt', typeof stats.mode, 'bigint')
  145. check('bigint mode masks to the creation-default file permission', Number(stats.mode & 0o777n), 0o644)
  146. check('bigint stat reports the identity fields the version token needs', [
  147. typeof stats.dev, typeof stats.ino, typeof stats.size, typeof stats.mtimeNs, typeof stats.ctimeNs,
  148. ], ['bigint', 'bigint', 'bigint', 'bigint', 'bigint'])
  149. check('bigint nanosecond time scales the millisecond time', stats.mtimeNs === stats.mtimeMs * 1_000_000n, true)
  150. check('bigint stat still answers the type predicates', [stats.isFile(), stats.isDirectory()], [true, false])
  151. check('plain stat keeps its number shape', typeof fs.statSync('/dsh/versioned.txt').mode, 'number')
  152. }
  153. {
  154. // Two writes inside one millisecond must not produce one version: the service's
  155. // stale-write guard compares these tokens.
  156. const token = (path: string): string => {
  157. const stats = bigStats(path)
  158. return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`
  159. }
  160. const before = token('/dsh/versioned.txt')
  161. fs.writeFileSync('/dsh/versioned.txt', 'two')
  162. check('a rewrite changes the version token', token('/dsh/versioned.txt') !== before, true)
  163. check('an unchanged file keeps its version token', token('/dsh/versioned.txt'), token('/dsh/versioned.txt'))
  164. }
  165. {
  166. const first = bigStats('/dsh/versioned.txt').ino
  167. fs.writeFileSync('/dsh/versioned.txt', 'three')
  168. check('identity survives a write to the same path', String(bigStats('/dsh/versioned.txt').ino), String(first))
  169. fs.rmSync('/dsh/versioned.txt')
  170. fs.writeFileSync('/dsh/versioned.txt', 'four')
  171. check('a removed and recreated path reports a new identity', bigStats('/dsh/versioned.txt').ino !== first, true)
  172. }
  173. check('a directory reports the creation-default mode in the bigint shape', Number(bigStats('/dsh/config').mode & 0o777n), 0o755)
  174. // ---------------------------------------------------------------------------
  175. // Permission bits round-trip: creation takes the caller's mode, chmod changes
  176. // it, stat reads back the stored value. dsh-credentials-local's owner-only
  177. // check reads exactly this (writeFileAtomic writes `wx` + mode 600, renames
  178. // into place, then the provider stats the result).
  179. // ---------------------------------------------------------------------------
  180. const plainMode = (path: string): number => (fs.statSync(path) as VfsStats).mode & 0o777
  181. fs.writeFileSync('/dsh/secrets.tmp', 'k: v\n', { mode: 0o600, flag: 'wx' })
  182. fs.renameSync('/dsh/secrets.tmp', '/dsh/secrets.yaml')
  183. check('a wx write with mode 600 stats as 600 after rename', plainMode('/dsh/secrets.yaml'), 0o600)
  184. fs.writeFileSync('/dsh/secrets.yaml', 'k: w\n')
  185. check('a rewrite keeps the creation bits', plainMode('/dsh/secrets.yaml'), 0o600)
  186. fs.chmodSync('/dsh/secrets.yaml', 0o640)
  187. check('chmod reads back exactly what was set', plainMode('/dsh/secrets.yaml'), 0o640)
  188. await fsp.chmod('/dsh/secrets.yaml', 0o600)
  189. check('promises.chmod reads back through the bigint shape', Number(bigStats('/dsh/secrets.yaml').mode & 0o777n), 0o600)
  190. fs.mkdirSync('/dsh/vault', { mode: 0o700 })
  191. check('mkdir honours its mode option', plainMode('/dsh/vault'), 0o700)
  192. check('promises.stat forwards the bigint option', typeof (await fsp.stat('/dsh/config', { bigint: true })).mode, 'bigint')