1
0

node-half.client.spec.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /**
  2. * Node half of the HMR plugin: bundle watches follow the graph, stat changes
  3. * report through clientModuleHost.rebuilt, and everything dies with the fiber.
  4. */
  5. import { mkdtempSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
  6. import { tmpdir } from 'node:os'
  7. import { join } from 'node:path'
  8. import { Context } from '@deepseek-ai/cordis'
  9. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  10. import type { ClientArtifactBaseline, ClientModuleRegistry, WebBootGraph } from '@deepseek-ai/dsh-client-modules'
  11. import type { WebRoute, WebServer } from '@deepseek-ai/dsh-host-webserver'
  12. import { apply, Config, EVENTS_ENDPOINT, inject } from '../src/index.ts'
  13. const POLL_MS = 20
  14. let dir: string
  15. beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'dsh-hmr-')) })
  16. afterEach(() => { rmSync(dir, { recursive: true, force: true }) })
  17. /**
  18. * Controllable clientModuleHost fake over a mutable id → bundle-path table.
  19. * Structural (Pick+cast): the plugin only touches the read/notify surface;
  20. * the service class carries private scan state a literal need not reproduce.
  21. */
  22. type FakeHost = ClientModuleRegistry & { rebuiltCalls: string[]; fireGraphChanged(): void }
  23. interface FakeHostOptions {
  24. beforeGraphRead?: () => void
  25. rebuilt?: (id: string) => string | undefined
  26. }
  27. function artifactBaseline(path: string): ClientArtifactBaseline {
  28. const bundle = statSync(path)
  29. return { path, mtimeMs: bundle.mtimeMs, size: bundle.size }
  30. }
  31. function fakeClientModuleHost(rows: Map<string, string>, options: FakeHostOptions = {}): FakeHost {
  32. const graphListeners = new Set<() => void>()
  33. const rebuiltCalls: string[] = []
  34. const baselines = new Map([...rows].map(([id, path]) => [id, artifactBaseline(path)]))
  35. const fake: Pick<FakeHost, 'graph' | 'artifactBaseline' | 'rebuilt' | 'onRebuilt' | 'onGraphChanged' | 'rebuiltCalls' | 'fireGraphChanged'> = {
  36. rebuiltCalls,
  37. fireGraphChanged: () => { for (const l of graphListeners) l() },
  38. graph: (): WebBootGraph => {
  39. options.beforeGraphRead?.()
  40. return {
  41. rev: 'r',
  42. entries: [...rows.keys()].map(id => ({ id, url: `/plugins/??${id}/client.js&rev=r`, rev: 'r' })),
  43. batches: [],
  44. }
  45. },
  46. artifactBaseline: (id) => {
  47. const path = rows.get(id)
  48. if (path === undefined) return undefined
  49. let baseline = baselines.get(id)
  50. if (baseline?.path !== path) {
  51. baseline = artifactBaseline(path)
  52. baselines.set(id, baseline)
  53. }
  54. return { ...baseline }
  55. },
  56. rebuilt: (id) => {
  57. rebuiltCalls.push(id)
  58. return options.rebuilt?.(id) ?? 'r2'
  59. },
  60. onRebuilt: () => () => {},
  61. onGraphChanged: (listener) => {
  62. graphListeners.add(listener)
  63. return () => { graphListeners.delete(listener) }
  64. },
  65. }
  66. return fake as FakeHost
  67. }
  68. // Structural fake: the plugin only touches register(); the service class
  69. // carries private state a literal cannot (and need not) reproduce.
  70. function fakeHttpServer(routes: WebRoute[]): WebServer {
  71. const fake: Pick<WebServer, 'register' | 'tapIndex' | 'port'> = {
  72. register(route) {
  73. routes.push(route)
  74. return () => { routes.splice(routes.indexOf(route), 1) }
  75. },
  76. tapIndex: () => () => {},
  77. port: 0,
  78. }
  79. return fake as WebServer
  80. }
  81. async function mount(clientModuleHost: FakeHost, webServer: WebServer) {
  82. const ctx = new Context()
  83. ctx.provide('clientModules', clientModuleHost)
  84. ctx.provide('webServer', webServer)
  85. const fiber = ctx.plugin(
  86. { inject: [...inject], Config, apply },
  87. { pollIntervalMs: POLL_MS },
  88. )
  89. await fiber.await()
  90. return fiber
  91. }
  92. describe('hmr node half', () => {
  93. it('watches graph bundles, ignores map-only changes, and unwatches on dispose', async () => {
  94. const bundle = join(dir, 'a.js')
  95. writeFileSync(bundle, 'v1')
  96. const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]))
  97. const routes: WebRoute[] = []
  98. const fiber = await mount(clientModuleHost, fakeHttpServer(routes))
  99. expect(routes).toHaveLength(1)
  100. expect(routes[0]).toMatchObject({ kind: 'exact', path: EVENTS_ENDPOINT })
  101. expect(clientModuleHost.rebuiltCalls).toEqual([])
  102. // Nudge mtime past stat granularity so the poller sees a content signal.
  103. await new Promise(resolve => setTimeout(resolve, POLL_MS * 2))
  104. writeFileSync(bundle, 'v2-longer')
  105. await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toContain('pkg-a') }, { timeout: 3_000 })
  106. clientModuleHost.rebuiltCalls.length = 0
  107. await new Promise(resolve => setTimeout(resolve, POLL_MS * 2))
  108. writeFileSync(`${bundle}.map`, '{"version":3}')
  109. await new Promise(resolve => setTimeout(resolve, POLL_MS * 3))
  110. expect(clientModuleHost.rebuiltCalls).toEqual([])
  111. writeFileSync(bundle, 'v3-even-longer')
  112. await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toContain('pkg-a') }, { timeout: 3_000 })
  113. await fiber.dispose()
  114. expect(routes).toHaveLength(0)
  115. // Watcher gone: further file changes report nothing.
  116. clientModuleHost.rebuiltCalls.length = 0
  117. writeFileSync(bundle, 'v4-after-dispose')
  118. await new Promise(resolve => setTimeout(resolve, POLL_MS * 4))
  119. expect(clientModuleHost.rebuiltCalls).toHaveLength(0)
  120. })
  121. it('follows graph changes: rows added after activation get watched', async () => {
  122. const early = join(dir, 'early.js')
  123. const late = join(dir, 'late.js')
  124. writeFileSync(early, 'v1')
  125. const rows = new Map([['pkg-early', early]])
  126. const clientModuleHost = fakeClientModuleHost(rows)
  127. const fiber = await mount(clientModuleHost, fakeHttpServer([]))
  128. clientModuleHost.rebuiltCalls.length = 0
  129. writeFileSync(late, 'v1')
  130. rows.set('pkg-late', late)
  131. clientModuleHost.fireGraphChanged()
  132. expect(clientModuleHost.rebuiltCalls).toEqual([])
  133. await new Promise(resolve => setTimeout(resolve, POLL_MS * 2))
  134. writeFileSync(late, 'v2-longer')
  135. await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toContain('pkg-late') }, { timeout: 3_000 })
  136. rows.delete('pkg-late')
  137. clientModuleHost.fireGraphChanged()
  138. clientModuleHost.rebuiltCalls.length = 0
  139. writeFileSync(late, 'v3-even-longer')
  140. await new Promise(resolve => setTimeout(resolve, POLL_MS * 3))
  141. expect(clientModuleHost.rebuiltCalls).toHaveLength(0)
  142. await fiber.dispose()
  143. })
  144. it('rehashes only a row changed between its startup snapshot and watch installation', async () => {
  145. const bundle = join(dir, 'construction.js')
  146. writeFileSync(bundle, 'v1')
  147. let rewrite = true
  148. const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]), {
  149. beforeGraphRead: () => {
  150. if (!rewrite) return
  151. rewrite = false
  152. writeFileSync(bundle, 'v2-written-during-watch-construction')
  153. },
  154. })
  155. const fiber = await mount(clientModuleHost, fakeHttpServer([]))
  156. expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a'])
  157. clientModuleHost.rebuiltCalls.length = 0
  158. await new Promise(resolve => setTimeout(resolve, POLL_MS * 3))
  159. expect(clientModuleHost.rebuiltCalls).toHaveLength(0)
  160. await fiber.dispose()
  161. })
  162. it('marks a vanished bundle dirty so identical metadata still re-hashes after it reappears', async () => {
  163. const bundle = join(dir, 'replace.js')
  164. writeFileSync(bundle, 'seed')
  165. const fixedTime = new Date(1_600_000_000_000)
  166. utimesSync(bundle, fixedTime, fixedTime)
  167. const baseline = statSync(bundle)
  168. const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]))
  169. const fiber = await mount(clientModuleHost, fakeHttpServer([]))
  170. clientModuleHost.rebuiltCalls.length = 0
  171. unlinkSync(bundle)
  172. await new Promise(resolve => setTimeout(resolve, POLL_MS * 2))
  173. writeFileSync(bundle, 'x'.repeat(baseline.size))
  174. utimesSync(bundle, fixedTime, fixedTime)
  175. const restored = statSync(bundle)
  176. expect({ mtimeMs: restored.mtimeMs, size: restored.size }).toEqual({
  177. mtimeMs: baseline.mtimeMs,
  178. size: baseline.size,
  179. })
  180. await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a']) }, { timeout: 3_000 })
  181. await fiber.dispose()
  182. })
  183. it('retains a dirty baseline when a catch-up re-hash races a rename', async () => {
  184. const bundle = join(dir, 'rename.js')
  185. writeFileSync(bundle, 'v1')
  186. let first = true
  187. const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]), {
  188. beforeGraphRead: () => {
  189. if (!first) return
  190. writeFileSync(bundle, 'v2-written-during-watch-construction')
  191. },
  192. rebuilt: () => {
  193. if (!first) return 'r2'
  194. first = false
  195. throw Object.assign(new Error('bundle renamed'), { code: 'ENOENT' })
  196. },
  197. })
  198. const fiber = await mount(clientModuleHost, fakeHttpServer([]))
  199. await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a', 'pkg-a']) }, { timeout: 3_000 })
  200. await fiber.dispose()
  201. })
  202. })