watcher.spec.ts 8.9 KB

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