test-invariants.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /**
  2. * Vitest-wide invariant host. Ordinary Cordis roots receive the invariant
  3. * service with global enablement plus the current test package's companion,
  4. * when it publishes one.
  5. * One topology test mounts every companion; focused invariant tests own their
  6. * service topology explicitly.
  7. */
  8. import { expect } from 'vitest'
  9. import { FiberState, Inject, RegistryService, ValidationError } from '@deepseek-ai/cordis'
  10. import type { Context, Plugin } from '@deepseek-ai/cordis'
  11. import InvariantRegistry from '@deepseek-ai/dsh-invariants'
  12. declare global {
  13. interface ImportMeta {
  14. /** Lazy Vite module-glob expansion used by the Vitest setup file. */
  15. glob<TModule>(pattern: string): Record<string, () => Promise<TModule>>
  16. }
  17. }
  18. /** Loader-safe exports shared by every package invariant companion. */
  19. export interface TestInvariantCompanion {
  20. readonly name: string
  21. readonly inject: readonly string[]
  22. readonly default?: unknown
  23. apply(ctx: Context): Promise<() => void>
  24. }
  25. /** Private service dependency that holds ordinary root plugins until invariant startup completes. */
  26. export const TEST_INVARIANT_READY_SERVICE = 'testInvariantReady'
  27. /**
  28. * Every published package companion as a lazy loader keyed by glob path. Ordinary tests
  29. * load only their owner's module; the exhaustive topology test loads and
  30. * executes all of them, so aggregated coverage still observes every
  31. * registration while per-file setup avoids importing unrelated companions and their
  32. * transitive package sources.
  33. */
  34. export const testInvariantCompanions: Readonly<Record<string, () => Promise<TestInvariantCompanion>>> =
  35. import.meta.glob<TestInvariantCompanion>('../packages/*/*/src/invariant.ts')
  36. /** Manual-topology suites whose names cannot follow the focused invariant convention. */
  37. const MANUAL_INVARIANT_TEST_EXCEPTIONS = [
  38. '/packages/runtime-diagnostics/invariants/tests/service.spec.ts',
  39. ] as const
  40. interface InvariantHost {
  41. readonly byCallback: ReadonlyMap<unknown, PluginFiber>
  42. readonly barrierOwners: WeakSet<Context['fiber']>
  43. readonly ready: Promise<void>
  44. }
  45. type PluginFiber = ReturnType<RegistryService['plugin']>
  46. type PluginCallback = Plugin.Function | Plugin.Constructor
  47. const hosts = new WeakMap<Context, InvariantHost>()
  48. // oxlint-disable-next-line typescript/unbound-method -- every call below supplies its RegistryService receiver explicitly.
  49. const originalPlugin = RegistryService.prototype.plugin
  50. RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, getOuterStack?: () => string[]) {
  51. const testPath = expect.getState().testPath ?? ''
  52. if (usesManualInvariantTree(testPath)) return originalPlugin.call(this, plugin, config, getOuterStack)
  53. const root = this.ctx.root
  54. const host = hosts.get(root) ?? startInvariantHost(root)
  55. const callback = this.resolve(plugin)
  56. const existing = callback === undefined ? undefined : host.byCallback.get(callback)
  57. if (existing !== undefined) {
  58. return hasBarrierOwner(host, this.ctx) ? existing : joinInvariantStartup(existing, host.ready)
  59. }
  60. // Causal descendants of a gated target have already crossed the barrier.
  61. // Host service and companion descendants also bypass it so their own startup
  62. // cannot depend on the readiness they are responsible for providing.
  63. if (hasBarrierOwner(host, this.ctx)) {
  64. return originalPlugin.call(this, plugin, config, getOuterStack)
  65. }
  66. if (callback === undefined) {
  67. return originalPlugin.call(this, plugin, config, getOuterStack)
  68. }
  69. const fiber = originalPlugin.call(
  70. this,
  71. withInvariantReadiness(plugin, callback as PluginCallback),
  72. config,
  73. getOuterStack,
  74. )
  75. const initiallyPending = fiber.ctx.fiber.state === FiberState.PENDING
  76. host.barrierOwners.add(fiber.ctx.fiber)
  77. return joinInvariantStartup(fiber, host.ready, initiallyPending)
  78. }
  79. /**
  80. * Detect focused suites that construct service selection or companion lifecycle explicitly.
  81. * @param testPath - absolute or repo-relative Vitest file path.
  82. * @returns whether the global invariant host must leave the root untouched.
  83. */
  84. export function usesManualInvariantTree(testPath: string): boolean {
  85. const normalized = testPath.replaceAll('\\', '/')
  86. if (/\/packages\/[^/]+\/[^/]+\/tests\/[^/]*invariant[^/]*\.spec\.ts$/.test(normalized)) return true
  87. return MANUAL_INVARIANT_TEST_EXCEPTIONS.some(path => normalized.endsWith(path))
  88. }
  89. const ALL_COMPANION_TESTS = ['/scripts/test-invariants.spec.ts'] as const
  90. /**
  91. * Select the package companions that an ordinary test root must register.
  92. * Package tests receive their owner's checks; the dedicated topology test
  93. * receives every companion owner so coverage and runtime registration remain
  94. * independently enforced.
  95. * @param testPath - absolute or repo-relative normalized Vitest file path.
  96. * @returns sorted `import.meta.glob` keys for companions to mount.
  97. */
  98. export function testInvariantCompanionPaths(testPath: string): string[] {
  99. const normalized = testPath.replaceAll('\\', '/')
  100. const allPaths = Object.keys(testInvariantCompanions).sort()
  101. if (ALL_COMPANION_TESTS.some(path => normalized.endsWith(path))) return allPaths
  102. const owner = normalized.match(/\/packages\/([^/]+)\/([^/]+)\/tests\//)
  103. if (owner === null) return []
  104. const companionPath = `../packages/${owner[1]}/${owner[2]}/src/invariant.ts`
  105. return testInvariantCompanions[companionPath] === undefined ? [] : [companionPath]
  106. }
  107. function startInvariantHost(root: Context): InvariantHost {
  108. const byCallback = new Map<unknown, PluginFiber>()
  109. const barrierOwners = new WeakSet<Context['fiber']>()
  110. const mount = (plugin: Plugin, config?: unknown): PluginFiber => {
  111. const fiber = originalPlugin.call(root.registry, plugin, config)
  112. const callback = root.registry.resolve(plugin)
  113. if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
  114. byCallback.set(callback, fiber)
  115. barrierOwners.add(fiber.ctx.fiber)
  116. return fiber
  117. }
  118. // The service mounts synchronously so the intercepted registration that
  119. // started this host immediately finds its own fiber in byCallback.
  120. // Companions load and mount inside the ready chain (after the service is
  121. // active, so their startup is directly joinable); every joined root plugin
  122. // awaits ready, so none starts ahead of its package checks. Tests plugging
  123. // a companion directly must await an earlier root plugin first — the
  124. // duplicate-mount failure otherwise is loud (owner name already reserved).
  125. const serviceFiber = mount(InvariantRegistry, { enabled: true })
  126. const testPath = expect.getState().testPath ?? ''
  127. const companionPaths = testInvariantCompanionPaths(testPath)
  128. const ready = requireActive(serviceFiber, 'invariant service').then(async () => {
  129. const companions = await Promise.all(companionPaths.map(async (path) => {
  130. const load = testInvariantCompanions[path]
  131. if (load === undefined) {
  132. throw new Error(`test invariants: selected companion vanished at ${path}`)
  133. }
  134. const companion = await load()
  135. if (!companion.inject.includes('invariants')) {
  136. throw new Error(`test invariants: ${path} must inject the invariant service`)
  137. }
  138. return { companion, path }
  139. }))
  140. const companionFibers = companions.map(({ companion, path }) => ({
  141. fiber: mount(companion),
  142. path,
  143. }))
  144. await Promise.all(companionFibers.map(({ fiber, path }) => requireActive(fiber, path)))
  145. root.provide(TEST_INVARIANT_READY_SERVICE, true)
  146. })
  147. const host = { byCallback, barrierOwners, ready }
  148. hosts.set(root, host)
  149. return host
  150. }
  151. function hasBarrierOwner(host: InvariantHost, ctx: Context): boolean {
  152. let fiber = ctx.fiber
  153. while (true) {
  154. if (
  155. host.barrierOwners.has(fiber)
  156. && (fiber.state === FiberState.LOADING || fiber.state === FiberState.ACTIVE)
  157. ) {
  158. return true
  159. }
  160. const parent = fiber.parent.fiber
  161. if (parent === fiber) return false
  162. fiber = parent
  163. }
  164. }
  165. async function requireActive(fiber: PluginFiber, label: string): Promise<void> {
  166. await fiber.await()
  167. if (fiber.state !== FiberState.ACTIVE) {
  168. throw new Error(`test invariants: ${label} settled without becoming active`)
  169. }
  170. }
  171. function withInvariantReadiness(plugin: Plugin, callback: PluginCallback): Plugin.Object {
  172. return {
  173. apply: callback as Plugin.Function,
  174. inject: {
  175. ...Inject.resolve(plugin.inject),
  176. [TEST_INVARIANT_READY_SERVICE]: null,
  177. },
  178. ...(plugin.name === undefined ? {} : { name: plugin.name }),
  179. ...(plugin.Config === undefined ? {} : { Config: plugin.Config }),
  180. ...(plugin.provide === undefined ? {} : { provide: plugin.provide }),
  181. ...(plugin.intercept === undefined ? {} : { intercept: plugin.intercept }),
  182. }
  183. }
  184. function joinInvariantStartup(
  185. fiber: PluginFiber,
  186. invariantReady: Promise<void>,
  187. disposePendingValidationFailure = false,
  188. ): PluginFiber {
  189. // RegistryService returns a thenable wrapper whose context still points to
  190. // the raw Fiber. Calling inherited await() on the wrapper would return and
  191. // assimilate that thenable, accidentally following later plugin startup.
  192. const rawFiber = fiber.ctx.fiber
  193. const readiness = invariantReady.then(async () => {
  194. try {
  195. return await rawFiber.await()
  196. } catch (error) {
  197. // Config resolves only after the readiness injection activates. Dispose
  198. // validation failures owned by an initially pending target; ordinary
  199. // callback failures remain inspectable.
  200. if (disposePendingValidationFailure && error instanceof ValidationError) {
  201. await rawFiber.dispose()
  202. }
  203. throw error
  204. }
  205. })
  206. const joined = Object.create(fiber) as PluginFiber
  207. joined.then = readiness.then.bind(readiness)
  208. return joined
  209. }