watcher.spec.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import z from '@deepseek-ai/schemastery'
  4. import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import { FileSettingsProvider } from '../src/index.ts'
  8. // chokidar is the nondeterministic OS boundary: faking it lets these tests
  9. // drive the event pipeline (error events, races with unreadable files)
  10. // deterministically. Real end-to-end watching stays covered by local.spec.ts.
  11. vi.mock('chokidar', async () => {
  12. const { EventEmitter } = await import('node:events')
  13. class FakeWatcher extends EventEmitter {
  14. close = vi.fn(() => Promise.resolve())
  15. }
  16. const instances: Array<{ path: string; options: unknown; watcher: InstanceType<typeof FakeWatcher> }> = []
  17. return {
  18. watch: vi.fn((path: string, options: unknown) => {
  19. const watcher = new FakeWatcher()
  20. instances.push({ path, options, watcher })
  21. return watcher
  22. }),
  23. __instances: instances,
  24. }
  25. })
  26. interface FakeChokidar {
  27. __instances: Array<{
  28. path: string
  29. options: { awaitWriteFinish: { stabilityThreshold: number; pollInterval: number } }
  30. watcher: import('node:events').EventEmitter
  31. }>
  32. }
  33. async function fakeInstances(): Promise<FakeChokidar['__instances']> {
  34. const chokidar = await import('chokidar') as unknown as FakeChokidar
  35. return chokidar.__instances
  36. }
  37. const ThemeSchema: z<{ theme: string }> = z.object({
  38. theme: z.string().default('dark'),
  39. })
  40. const cleanups: Array<() => Promise<void>> = []
  41. afterEach(async () => {
  42. while (cleanups.length > 0) await cleanups.pop()!()
  43. ;(await fakeInstances()).length = 0
  44. })
  45. async function tempDir(): Promise<string> {
  46. const dir = await mkdtemp(join(tmpdir(), 'dsh-settings-watch-'))
  47. cleanups.push(() => rm(dir, { recursive: true, force: true }))
  48. return dir
  49. }
  50. async function boot(config: ConstructorParameters<typeof FileSettingsProvider>[1]): Promise<Context> {
  51. const ctx = new Context()
  52. const fiber = ctx.plugin(FileSettingsProvider, config)
  53. cleanups.push(async () => { await fiber.dispose() })
  54. await fiber
  55. return ctx
  56. }
  57. describe('watcher pipeline', () => {
  58. it('clamps the write-settle poll interval for a zero debounce', async () => {
  59. const dir = await tempDir()
  60. await boot({ path: join(dir, 'settings.yaml'), debounceMs: 0 })
  61. const [instance] = await fakeInstances()
  62. expect(instance!.options.awaitWriteFinish).toEqual({ stabilityThreshold: 0, pollInterval: 1 })
  63. })
  64. it('survives a watcher error and keeps publishing later edits', async () => {
  65. const dir = await tempDir()
  66. const path = join(dir, 'settings.yaml')
  67. const ctx = await boot({ path, debounceMs: 5 })
  68. const scope = ctx.settings.register('ui-theme', ThemeSchema)
  69. const [instance] = await fakeInstances()
  70. instance!.watcher.emit('error', new Error('watch backend failure'))
  71. expect(scope.get()).toEqual({ theme: 'dark' })
  72. await writeFile(path, 'ui-theme:\n theme: light\n')
  73. instance!.watcher.emit('all', 'change', path)
  74. await vi.waitFor(() => {
  75. expect(scope.get()).toEqual({ theme: 'light' })
  76. })
  77. })
  78. it('keeps the last good document when the file turns unreadable at runtime', async () => {
  79. const dir = await tempDir()
  80. const path = join(dir, 'settings.yaml')
  81. await writeFile(path, 'ui-theme:\n theme: light\n')
  82. const ctx = await boot({ path, debounceMs: 5 })
  83. const scope = ctx.settings.register('ui-theme', ThemeSchema)
  84. await chmod(path, 0o000)
  85. cleanups.push(() => chmod(path, 0o600))
  86. const [instance] = await fakeInstances()
  87. instance!.watcher.emit('all', 'change', path)
  88. // The warn-and-keep path is asynchronous; give the serialized refresh a turn.
  89. await new Promise(resolve => setTimeout(resolve, 50))
  90. expect(scope.get()).toEqual({ theme: 'light' })
  91. })
  92. it('keeps the reload queue alive after an invariant violation escapes a commit', async () => {
  93. const dir = await tempDir()
  94. const path = join(dir, 'settings.yaml')
  95. await writeFile(path, 'ui-theme:\n theme: light\n')
  96. const ctx = await boot({ path, debounceMs: 5 })
  97. const scope = ctx.settings.register('ui-theme', ThemeSchema)
  98. let arm = true
  99. ctx.on('settings/updated', () => {
  100. if (!arm) return
  101. throw Object.assign(new Error('forged relation'), { code: 'INVARIANT' })
  102. })
  103. const [instance] = await fakeInstances()
  104. await writeFile(path, 'ui-theme:\n theme: broken-commit\n')
  105. instance!.watcher.emit('all', 'change', path)
  106. await vi.waitFor(() => {
  107. expect(scope.get().theme).toBe('broken-commit')
  108. })
  109. arm = false
  110. await writeFile(path, 'ui-theme:\n theme: recovered\n')
  111. instance!.watcher.emit('all', 'change', path)
  112. await vi.waitFor(() => {
  113. expect(scope.get().theme).toBe('recovered')
  114. })
  115. })
  116. it('quiesces the refresh pipeline before dispose completes', async () => {
  117. const dir = await tempDir()
  118. const path = join(dir, 'settings.yaml')
  119. await writeFile(path, 'ui-theme:\n theme: light\n')
  120. const ctx = new Context()
  121. const fiber = ctx.plugin(FileSettingsProvider, { path, debounceMs: 5 })
  122. await fiber
  123. ctx.settings.register('ui-theme', ThemeSchema)
  124. let disposed = false
  125. let postDisposeCommits = 0
  126. ctx.on('settings/updated', () => {
  127. if (disposed) postDisposeCommits += 1
  128. })
  129. await writeFile(path, 'ui-theme:\n theme: darker\n')
  130. const [instance] = await fakeInstances()
  131. // Two queued refreshes: dispose interrupts one mid-flight and the other
  132. // before it starts, so both closed guards must hold.
  133. instance!.watcher.emit('all', 'change', path)
  134. instance!.watcher.emit('all', 'change', path)
  135. await fiber.dispose()
  136. disposed = true
  137. instance!.watcher.emit('all', 'change', path)
  138. instance!.watcher.emit('ready')
  139. await new Promise(resolve => setTimeout(resolve, 100))
  140. expect(postDisposeCommits).toBe(0)
  141. })
  142. it('treats an event for a still-absent file as a no-op', async () => {
  143. const dir = await tempDir()
  144. const path = join(dir, 'settings.yaml')
  145. const ctx = await boot({ path, debounceMs: 5 })
  146. const scope = ctx.settings.register('ui-theme', ThemeSchema)
  147. const [instance] = await fakeInstances()
  148. instance!.watcher.emit('all', 'add', path)
  149. await new Promise(resolve => setTimeout(resolve, 50))
  150. expect(scope.get()).toEqual({ theme: 'dark' })
  151. })
  152. it('folds an unobserved external edit into a write instead of overwriting it', async () => {
  153. const dir = await tempDir()
  154. const path = join(dir, 'settings.yaml')
  155. await writeFile(path, 'ui-theme:\n theme: light\n')
  156. const ctx = await boot({ path, debounceMs: 5 })
  157. const theme = ctx.settings.register('ui-theme', ThemeSchema)
  158. const editor = ctx.settings.register('editor', z.object({
  159. tabWidth: z.number().default(2),
  160. }))
  161. // The external edit has landed on disk but its watcher event has not
  162. // fired yet (a debounce window, or a missed event): the write must fold
  163. // it in, not resurrect the stale document.
  164. await writeFile(path, 'ui-theme:\n theme: light\neditor:\n tabWidth: 8\n')
  165. await theme.update({ theme: 'darker' })
  166. const text = await readFile(path, 'utf8')
  167. expect(text).toContain('tabWidth: 8')
  168. expect(text).toContain('theme: darker')
  169. // The fold published the unobserved section before the write committed.
  170. expect(editor.get()).toEqual({ tabWidth: 8 })
  171. })
  172. it('reconciles at watcher ready so a change during setup is not missed', async () => {
  173. const dir = await tempDir()
  174. const path = join(dir, 'settings.yaml')
  175. await writeFile(path, 'ui-theme:\n theme: light\n')
  176. const ctx = await boot({ path, debounceMs: 5 })
  177. const scope = ctx.settings.register('ui-theme', ThemeSchema)
  178. // Written after the initial load but before the watcher became active:
  179. // no 'all' event will ever fire for it.
  180. await writeFile(path, 'ui-theme:\n theme: written-before-ready\n')
  181. const [instance] = await fakeInstances()
  182. instance!.watcher.emit('ready')
  183. await vi.waitFor(() => {
  184. expect(scope.get().theme).toBe('written-before-ready')
  185. })
  186. })
  187. it('fails a write loud when the on-disk document turned invalid unobserved', async () => {
  188. const dir = await tempDir()
  189. const path = join(dir, 'settings.yaml')
  190. await writeFile(path, 'ui-theme:\n theme: light\n')
  191. const ctx = await boot({ path, debounceMs: 5 })
  192. const scope = ctx.settings.register('ui-theme', ThemeSchema)
  193. const broken = 'ui-theme: [unclosed\n flow: {\n'
  194. await writeFile(path, broken)
  195. await expect(scope.update({ theme: 'darker' })).rejects.toThrow(/invalid document/)
  196. // The user's manual edit stays on disk untouched and the cache keeps the
  197. // last good value.
  198. expect(await readFile(path, 'utf8')).toBe(broken)
  199. expect(scope.get()).toEqual({ theme: 'light' })
  200. })
  201. })