watcher.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { credentialRef } from '@deepseek-ai/dsh-credentials'
  7. import { LocalCredentialProvider } from '../src/index.ts'
  8. const fsHarness = vi.hoisted(() => ({
  9. nextReadError: undefined as NodeJS.ErrnoException | undefined,
  10. }))
  11. vi.mock('node:fs/promises', async (importOriginal) => {
  12. const actual = await importOriginal<typeof import('node:fs/promises')>()
  13. return {
  14. ...actual,
  15. readFile: (async (path: unknown, ...rest: never[]) => {
  16. const error = fsHarness.nextReadError
  17. if (error !== undefined) {
  18. fsHarness.nextReadError = undefined
  19. throw error
  20. }
  21. return (actual.readFile as (path: unknown, ...args: never[]) => Promise<unknown>)(path, ...rest)
  22. }) as typeof actual.readFile,
  23. }
  24. })
  25. function writeCredentials(file: string, text: string): Promise<void> {
  26. return writeFile(file, text, { mode: 0o600 })
  27. }
  28. // chokidar is the nondeterministic OS boundary: faking it lets these tests
  29. // drive the event pipeline (error events, races with unreadable files)
  30. // deterministically. Real end-to-end watching stays covered by local.spec.ts.
  31. vi.mock('chokidar', async () => {
  32. const { EventEmitter } = await import('node:events')
  33. class FakeWatcher extends EventEmitter {
  34. close = vi.fn(() => Promise.resolve())
  35. }
  36. const instances: Array<{ path: string; options: unknown; watcher: InstanceType<typeof FakeWatcher> }> = []
  37. return {
  38. watch: vi.fn((path: string, options: unknown) => {
  39. const watcher = new FakeWatcher()
  40. instances.push({ path, options, watcher })
  41. return watcher
  42. }),
  43. __instances: instances,
  44. }
  45. })
  46. interface FakeChokidar {
  47. __instances: Array<{
  48. path: string
  49. options: { awaitWriteFinish: { stabilityThreshold: number; pollInterval: number } }
  50. watcher: import('node:events').EventEmitter
  51. }>
  52. }
  53. async function fakeInstances(): Promise<FakeChokidar['__instances']> {
  54. const chokidar = await import('chokidar') as unknown as FakeChokidar
  55. return chokidar.__instances
  56. }
  57. const KEY = credentialRef('DSH_CRED_PIPE')
  58. const cleanups: Array<() => Promise<void>> = []
  59. afterEach(async () => {
  60. fsHarness.nextReadError = undefined
  61. while (cleanups.length > 0) await cleanups.pop()!()
  62. ;(await fakeInstances()).length = 0
  63. })
  64. async function tempDir(): Promise<string> {
  65. const dir = await mkdtemp(join(tmpdir(), 'dsh-credentials-watch-'))
  66. cleanups.push(() => rm(dir, { recursive: true, force: true }))
  67. return dir
  68. }
  69. async function boot(config: ConstructorParameters<typeof LocalCredentialProvider>[1]): Promise<Context> {
  70. const ctx = new Context()
  71. const fiber = ctx.plugin(LocalCredentialProvider, config)
  72. cleanups.push(async () => {
  73. await fiber.dispose()
  74. })
  75. await fiber
  76. return ctx
  77. }
  78. describe('watcher pipeline', () => {
  79. it('clamps the write-settle poll interval for a zero debounce', async () => {
  80. const dir = await tempDir()
  81. await boot({ path: join(dir, '.credentials.yaml'), debounceMs: 0 })
  82. const [instance] = await fakeInstances()
  83. expect(instance!.options.awaitWriteFinish).toEqual({ stabilityThreshold: 0, pollInterval: 1 })
  84. })
  85. it('survives a watcher error and keeps publishing later edits', async () => {
  86. const dir = await tempDir()
  87. const path = join(dir, '.credentials.yaml')
  88. const ctx = await boot({ path, debounceMs: 5 })
  89. const [instance] = await fakeInstances()
  90. instance!.watcher.emit('error', new Error('watch backend failure'))
  91. expect(await ctx.credentials.resolve(KEY)).toBeUndefined()
  92. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: arrived\n')
  93. instance!.watcher.emit('all', 'change', path)
  94. await vi.waitFor(async () => {
  95. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'arrived', source: 'file' })
  96. })
  97. })
  98. it('keeps the last good snapshot when the file turns unreadable at runtime', async () => {
  99. const dir = await tempDir()
  100. const path = join(dir, '.credentials.yaml')
  101. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: good\n')
  102. const ctx = await boot({ path, debounceMs: 5 })
  103. await chmod(path, 0o000)
  104. cleanups.push(() => chmod(path, 0o600))
  105. const [instance] = await fakeInstances()
  106. instance!.watcher.emit('all', 'change', path)
  107. // The warn-and-keep path is asynchronous; give the serialized refresh a turn.
  108. await new Promise(resolve => setTimeout(resolve, 50))
  109. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'good', source: 'file' })
  110. })
  111. it('keeps the last good snapshot when the read fails after its permission check', async () => {
  112. const dir = await tempDir()
  113. const path = join(dir, '.credentials.yaml')
  114. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: good\n')
  115. const ctx = await boot({ path, debounceMs: 5 })
  116. fsHarness.nextReadError = Object.assign(new Error('version: 1\nrefs:\n EACCES: injected read failure\n'), { code: 'EACCES' })
  117. const [instance] = await fakeInstances()
  118. instance!.watcher.emit('all', 'change', path)
  119. await vi.waitFor(() => {
  120. expect(fsHarness.nextReadError).toBeUndefined()
  121. })
  122. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'good', source: 'file' })
  123. })
  124. it('keeps the reload queue alive after an invariant violation escapes the fan-out', async () => {
  125. const dir = await tempDir()
  126. const path = join(dir, '.credentials.yaml')
  127. const ctx = await boot({ path, debounceMs: 5 })
  128. let arm = true
  129. ctx.on('credentials/reference-updated', () => {
  130. if (!arm) return
  131. throw Object.assign(new Error('forged relation'), { code: 'INVARIANT' })
  132. })
  133. const [instance] = await fakeInstances()
  134. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: first\n')
  135. instance!.watcher.emit('all', 'change', path)
  136. // The snapshot commits before the fan-out, so the value lands even though
  137. // the listener threw out of the refresh.
  138. await vi.waitFor(async () => {
  139. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'first', source: 'file' })
  140. })
  141. arm = false
  142. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: second\n')
  143. instance!.watcher.emit('all', 'change', path)
  144. await vi.waitFor(async () => {
  145. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'second', source: 'file' })
  146. })
  147. })
  148. it('quiesces the refresh pipeline before dispose completes', async () => {
  149. const dir = await tempDir()
  150. const path = join(dir, '.credentials.yaml')
  151. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: initial\n')
  152. const ctx = new Context()
  153. const fiber = ctx.plugin(LocalCredentialProvider, { path, debounceMs: 5 })
  154. await fiber
  155. let disposed = false
  156. let postDisposeCommits = 0
  157. ctx.on('credentials/reference-updated', () => {
  158. if (disposed) postDisposeCommits += 1
  159. })
  160. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: changed\n')
  161. const [instance] = await fakeInstances()
  162. // Two queued refreshes: dispose interrupts one mid-flight and the other
  163. // before it starts, so both closed guards must hold.
  164. instance!.watcher.emit('all', 'change', path)
  165. instance!.watcher.emit('all', 'change', path)
  166. await fiber.dispose()
  167. disposed = true
  168. instance!.watcher.emit('all', 'change', path)
  169. instance!.watcher.emit('ready')
  170. await new Promise(resolve => setTimeout(resolve, 100))
  171. expect(postDisposeCommits).toBe(0)
  172. })
  173. it('empties the snapshot when the document is deleted and emits the removals', async () => {
  174. const dir = await tempDir()
  175. const path = join(dir, '.credentials.yaml')
  176. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: doomed\n')
  177. const ctx = await boot({ path, debounceMs: 5 })
  178. const seen: string[] = []
  179. ctx.on('credentials/reference-updated', (ref) => {
  180. seen.push(ref)
  181. })
  182. await rm(path)
  183. const [instance] = await fakeInstances()
  184. instance!.watcher.emit('all', 'unlink', path)
  185. await vi.waitFor(async () => {
  186. expect(await ctx.credentials.resolve(KEY)).toBeUndefined()
  187. })
  188. expect(seen).toEqual([KEY])
  189. })
  190. it('keeps the last good snapshot when an external edit makes the document invalid', async () => {
  191. const dir = await tempDir()
  192. const path = join(dir, '.credentials.yaml')
  193. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: a\n')
  194. const ctx = await boot({ path, debounceMs: 5 })
  195. const seen: string[] = []
  196. ctx.on('credentials/reference-updated', (ref) => {
  197. seen.push(ref)
  198. })
  199. // A key the seam cannot address is a rejection, not preserved content:
  200. // this document holds nothing but credentials. A live reload must warn
  201. // and keep serving the last good snapshot rather than take the process
  202. // down or silently drop the entry it could not validate.
  203. await writeCredentials(path, 'version: 1\nrefs:\n BAD-KEY: 2\n DSH_CRED_PIPE: b\n')
  204. const [instance] = await fakeInstances()
  205. instance!.watcher.emit('all', 'change', path)
  206. await new Promise(resolve => setTimeout(resolve, 50))
  207. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'a', source: 'file' })
  208. expect(seen).toEqual([])
  209. // Repairing the document resumes publishing.
  210. await writeCredentials(path, 'version: 1\nrefs:\n DSH_CRED_PIPE: b\n')
  211. instance!.watcher.emit('all', 'change', path)
  212. await vi.waitFor(async () => {
  213. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'b', source: 'file' })
  214. })
  215. expect(seen).toEqual([KEY])
  216. })
  217. it('treats an event for a still-absent file as a no-op', async () => {
  218. const dir = await tempDir()
  219. const path = join(dir, '.credentials.yaml')
  220. const ctx = await boot({ path, debounceMs: 5 })
  221. const [instance] = await fakeInstances()
  222. instance!.watcher.emit('all', 'add', path)
  223. await new Promise(resolve => setTimeout(resolve, 50))
  224. expect(await ctx.credentials.resolve(KEY)).toBeUndefined()
  225. })
  226. it('reconciles at watcher ready so a change during setup is not missed', async () => {
  227. const dir = await tempDir()
  228. const path = join(dir, '.credentials.yaml')
  229. await writeCredentials(path, `version: 1\nrefs:\n ${KEY}: a\n`)
  230. const ctx = await boot({ path, debounceMs: 5 })
  231. // Written after the initial load but before the watcher became active:
  232. // no 'all' event will ever fire for it.
  233. await writeCredentials(path, `version: 1\nrefs:\n ${KEY}: written-before-ready\n`)
  234. const [instance] = await fakeInstances()
  235. instance!.watcher.emit('ready')
  236. await vi.waitFor(async () => {
  237. expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'written-before-ready', source: 'file' })
  238. })
  239. })
  240. })