coverage-partitions.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /** Coordinate single-worker Vitest coverage partitions and one merged report. */
  2. import { spawn } from 'node:child_process'
  3. import { lstat, mkdir, readdir, rm, unlink } from 'node:fs/promises'
  4. import { join, relative, sep } from 'node:path'
  5. /** Environment variable selecting the number of instrumented coverage processes. */
  6. export const COVERAGE_PARTITIONS_ENV = 'DSH_COVERAGE_PARTITIONS'
  7. /** Internal marker that suppresses reports and thresholds inside a partition process. */
  8. export const COVERAGE_PARTITION_MODE_ENV = 'DSH_COVERAGE_PARTITION_MODE'
  9. /** Environment variable overriding instrumented test and polling timeouts. */
  10. export const COVERAGE_TEST_TIMEOUT_ENV = 'DSH_COVERAGE_TEST_TIMEOUT_MS'
  11. /** One child command owned by the coverage coordinator. */
  12. export interface CoverageCommand {
  13. /** Diagnostic identity. */
  14. label: string
  15. /** Node arguments; the first argument is pnpm's JavaScript entrypoint. */
  16. args: string[]
  17. /** Environment additions for the child. */
  18. env: Record<string, string | undefined>
  19. /** Working directory for the child. */
  20. cwd: string
  21. /** Blob the partition must produce; absent for the merge command. */
  22. blobPath?: string
  23. }
  24. /** Observable child-process completion. */
  25. export interface CoverageCommandResult {
  26. /** Numeric process status, or `null` when a signal ended the child. */
  27. exitCode: number | null
  28. /** Terminating signal, or `null` after an ordinary exit. */
  29. signalCode: NodeJS.Signals | null
  30. /** Spawn failure recorded independently from process completion. */
  31. error?: string
  32. }
  33. /** Execute one coordinator command with inherited output. */
  34. export type CoverageCommandRunner = (command: CoverageCommand) => Promise<CoverageCommandResult>
  35. /** Construction inputs for {@link CoveragePartitionCoordinator}. */
  36. export interface CoveragePartitionCoordinatorOptions {
  37. /** Repository root that owns coverage output. */
  38. root: string
  39. /** Number of concurrent single-worker Vitest processes. */
  40. partitions: number
  41. /** pnpm JavaScript entrypoint from `npm_execpath`. */
  42. pnpmEntrypoint: string
  43. /** Additional arguments shared by every partition. */
  44. vitestArgs?: string[]
  45. /** Child executor, injectable for scheduler tests. */
  46. runCommand?: CoverageCommandRunner
  47. }
  48. /** Parse an optional coverage partition count. */
  49. export function parseCoveragePartitionCount(raw: string | undefined): number | undefined {
  50. if (raw === undefined || raw === '') return undefined
  51. const parsed = Number.parseInt(raw, 10)
  52. if (!Number.isSafeInteger(parsed) || parsed < 2 || String(parsed) !== raw) {
  53. throw new Error(`${COVERAGE_PARTITIONS_ENV} must be an integer greater than 1, got ${JSON.stringify(raw)}.`)
  54. }
  55. return parsed
  56. }
  57. /** Resolve the paired Vitest timeout arguments used by coverage partitions. */
  58. export function coverageTestTimeoutArgs(raw: string | undefined): string[] {
  59. if (raw === undefined || raw === '') return []
  60. const parsed = Number.parseInt(raw, 10)
  61. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  62. throw new Error(`${COVERAGE_TEST_TIMEOUT_ENV} must be a positive integer, got ${JSON.stringify(raw)}.`)
  63. }
  64. return [`--testTimeout=${raw}`, `--expect.poll.timeout=${raw}`]
  65. }
  66. /** Remove pnpm's package-script separator before forwarding Vitest arguments. */
  67. export function forwardedCoverageArgs(args: readonly string[]): string[] {
  68. return [...args.slice(args[0] === '--' ? 1 : 0)]
  69. }
  70. /** Run instrumented partitions, validate their blobs, and merge once. */
  71. export class CoveragePartitionCoordinator {
  72. private readonly root: string
  73. private readonly partitions: number
  74. private readonly pnpmEntrypoint: string
  75. private readonly vitestArgs: string[]
  76. private readonly runCommand: CoverageCommandRunner
  77. private readonly temporaryRoot: string
  78. private readonly blobsRoot: string
  79. /** Create a coordinator from validated process-independent inputs. */
  80. public constructor(options: CoveragePartitionCoordinatorOptions) {
  81. if (!Number.isSafeInteger(options.partitions) || options.partitions < 2) {
  82. throw new Error(`coverage partitions must be an integer greater than 1, got ${String(options.partitions)}.`)
  83. }
  84. this.root = options.root
  85. this.partitions = options.partitions
  86. this.pnpmEntrypoint = options.pnpmEntrypoint
  87. this.vitestArgs = options.vitestArgs ?? []
  88. this.runCommand = options.runCommand ?? runCoverageCommand
  89. this.temporaryRoot = join(this.root, 'coverage', '.partitioned')
  90. this.blobsRoot = join(this.temporaryRoot, 'blobs')
  91. }
  92. /**
  93. * Run every partition before one merged threshold check.
  94. * @returns zero only when every partition and the merge command succeed.
  95. */
  96. public async run(): Promise<number> {
  97. await removeOwnedTree(join(this.root, 'coverage'))
  98. await mkdir(this.blobsRoot, { recursive: true })
  99. try {
  100. const commands = Array.from(
  101. { length: this.partitions },
  102. (_, index) => this.partitionCommand(index + 1),
  103. )
  104. const results = await Promise.all(commands.map(async (command) => {
  105. console.log(`coverage-partitions: start ${command.label}`)
  106. const result = await this.runCommand(command)
  107. if (commandFailed(result)) {
  108. console.error(`coverage-partitions: FAIL ${command.label} (${commandFailureReason(result)})`)
  109. }
  110. return result
  111. }))
  112. await this.assertCompleteBlobSet(commands)
  113. const mergeCommand = this.mergeCommand()
  114. console.log(`coverage-partitions: start ${mergeCommand.label}`)
  115. const mergeResult = await this.runCommand(mergeCommand)
  116. return results.some(commandFailed) || commandFailed(mergeResult) ? 1 : 0
  117. } finally {
  118. await removeOwnedTree(this.temporaryRoot)
  119. }
  120. }
  121. private partitionCommand(index: number): CoverageCommand {
  122. const blobPath = join(this.blobsRoot, `partition-${index}.json`)
  123. const reportsDirectory = join(this.temporaryRoot, `coverage-${index}`)
  124. return {
  125. label: `partition ${index}/${this.partitions}`,
  126. args: [
  127. this.pnpmEntrypoint,
  128. 'exec',
  129. 'vitest',
  130. 'run',
  131. '--coverage',
  132. '--coverage.reportOnFailure',
  133. '--maxWorkers=1',
  134. `--shard=${index}/${this.partitions}`,
  135. '--reporter=default',
  136. '--reporter=blob',
  137. `--outputFile.blob=${this.relativePath(blobPath)}`,
  138. `--coverage.reportsDirectory=${this.relativePath(reportsDirectory)}`,
  139. ...this.vitestArgs,
  140. ],
  141. env: {
  142. [COVERAGE_PARTITIONS_ENV]: undefined,
  143. [COVERAGE_PARTITION_MODE_ENV]: '1',
  144. },
  145. cwd: this.root,
  146. blobPath,
  147. }
  148. }
  149. private mergeCommand(): CoverageCommand {
  150. return {
  151. label: 'merged coverage report',
  152. args: [
  153. this.pnpmEntrypoint,
  154. 'exec',
  155. 'vitest',
  156. `--merge-reports=${this.relativePath(this.blobsRoot)}`,
  157. '--coverage',
  158. ],
  159. env: {
  160. [COVERAGE_PARTITIONS_ENV]: undefined,
  161. [COVERAGE_PARTITION_MODE_ENV]: undefined,
  162. },
  163. cwd: this.root,
  164. }
  165. }
  166. private relativePath(path: string): string {
  167. return relative(this.root, path).split(sep).join('/')
  168. }
  169. private async assertCompleteBlobSet(commands: CoverageCommand[]): Promise<void> {
  170. const expected = commands.map((command) => {
  171. if (command.blobPath === undefined) throw new Error(`${command.label} has no blob path.`)
  172. return this.relativePath(command.blobPath)
  173. }).sort()
  174. const actual = (await readdir(this.blobsRoot))
  175. .map(name => this.relativePath(join(this.blobsRoot, name)))
  176. .sort()
  177. if (actual.length !== expected.length || actual.some((name, index) => name !== expected[index])) {
  178. throw new Error(`coverage partitions produced ${JSON.stringify(actual)}; expected ${JSON.stringify(expected)}.`)
  179. }
  180. }
  181. }
  182. /** Spawn one pnpm-backed command without a platform shell. */
  183. function runCoverageCommand(command: CoverageCommand): Promise<CoverageCommandResult> {
  184. return new Promise((resolveCommand) => {
  185. const env = { ...process.env }
  186. for (const [name, value] of Object.entries(command.env)) {
  187. if (value === undefined) Reflect.deleteProperty(env, name)
  188. else env[name] = value
  189. }
  190. const child = spawn(process.execPath, command.args, {
  191. cwd: command.cwd,
  192. env,
  193. stdio: 'inherit',
  194. })
  195. child.once('error', (error: Error) => {
  196. resolveCommand({ exitCode: null, signalCode: null, error: error.message })
  197. })
  198. child.once('exit', (exitCode, signalCode) => {
  199. resolveCommand({ exitCode, signalCode })
  200. })
  201. })
  202. }
  203. function commandFailed(result: CoverageCommandResult): boolean {
  204. return result.exitCode !== 0 || result.signalCode !== null || result.error !== undefined
  205. }
  206. function commandFailureReason(result: CoverageCommandResult): string {
  207. const facts = [
  208. result.error,
  209. result.exitCode === null ? undefined : `exit ${result.exitCode}`,
  210. result.signalCode === null ? undefined : `signal ${result.signalCode}`,
  211. ].filter((fact): fact is string => fact !== undefined)
  212. return facts.join(', ') || 'no exit code or signal'
  213. }
  214. async function removeOwnedTree(path: string): Promise<void> {
  215. const metadata = await lstat(path).catch((error: unknown) => {
  216. if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
  217. throw error
  218. })
  219. if (metadata === undefined) return
  220. if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
  221. await unlink(path)
  222. return
  223. }
  224. await rm(path, { recursive: true, force: true })
  225. }