coverage-partitions.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. /** Bounded combined stdout/stderr tail repeated when the command fails. */
  33. outputTail?: string
  34. }
  35. /** Execute one coordinator command with inherited output. */
  36. export type CoverageCommandRunner = (command: CoverageCommand) => Promise<CoverageCommandResult>
  37. /** Construction inputs for {@link CoveragePartitionCoordinator}. */
  38. export interface CoveragePartitionCoordinatorOptions {
  39. /** Repository root that owns coverage output. */
  40. root: string
  41. /** Number of concurrent single-worker Vitest processes. */
  42. partitions: number
  43. /** pnpm JavaScript entrypoint from `npm_execpath`. */
  44. pnpmEntrypoint: string
  45. /** Additional arguments shared by every partition. */
  46. vitestArgs?: string[]
  47. /** Child executor, injectable for scheduler tests. */
  48. runCommand?: CoverageCommandRunner
  49. }
  50. /** Parse an optional coverage partition count. */
  51. export function parseCoveragePartitionCount(raw: string | undefined): number | undefined {
  52. if (raw === undefined || raw === '') return undefined
  53. const parsed = Number.parseInt(raw, 10)
  54. if (!Number.isSafeInteger(parsed) || parsed < 2 || String(parsed) !== raw) {
  55. throw new Error(`${COVERAGE_PARTITIONS_ENV} must be an integer greater than 1, got ${JSON.stringify(raw)}.`)
  56. }
  57. return parsed
  58. }
  59. /** Resolve the paired Vitest timeout arguments used by coverage partitions. */
  60. export function coverageTestTimeoutArgs(raw: string | undefined): string[] {
  61. if (raw === undefined || raw === '') return []
  62. const parsed = Number.parseInt(raw, 10)
  63. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  64. throw new Error(`${COVERAGE_TEST_TIMEOUT_ENV} must be a positive integer, got ${JSON.stringify(raw)}.`)
  65. }
  66. return [`--testTimeout=${raw}`, `--expect.poll.timeout=${raw}`]
  67. }
  68. /** Remove pnpm's package-script separator before forwarding Vitest arguments. */
  69. export function forwardedCoverageArgs(args: readonly string[]): string[] {
  70. return [...args.slice(args[0] === '--' ? 1 : 0)]
  71. }
  72. /** Run instrumented partitions, validate their blobs, and merge once. */
  73. export class CoveragePartitionCoordinator {
  74. private readonly root: string
  75. private readonly partitions: number
  76. private readonly pnpmEntrypoint: string
  77. private readonly vitestArgs: string[]
  78. private readonly runCommand: CoverageCommandRunner
  79. private readonly temporaryRoot: string
  80. private readonly blobsRoot: string
  81. /** Create a coordinator from validated process-independent inputs. */
  82. public constructor(options: CoveragePartitionCoordinatorOptions) {
  83. if (!Number.isSafeInteger(options.partitions) || options.partitions < 2) {
  84. throw new Error(`coverage partitions must be an integer greater than 1, got ${String(options.partitions)}.`)
  85. }
  86. this.root = options.root
  87. this.partitions = options.partitions
  88. this.pnpmEntrypoint = options.pnpmEntrypoint
  89. this.vitestArgs = options.vitestArgs ?? []
  90. this.runCommand = options.runCommand ?? runCoverageCommand
  91. this.temporaryRoot = join(this.root, 'coverage', '.partitioned')
  92. this.blobsRoot = join(this.temporaryRoot, 'blobs')
  93. }
  94. /**
  95. * Run every partition before one merged threshold check.
  96. * @returns zero only when every partition and the merge command succeed.
  97. */
  98. public async run(): Promise<number> {
  99. await removeOwnedTree(join(this.root, 'coverage'))
  100. await mkdir(this.blobsRoot, { recursive: true })
  101. try {
  102. const commands = Array.from(
  103. { length: this.partitions },
  104. (_, index) => this.partitionCommand(index + 1),
  105. )
  106. const results = await Promise.all(commands.map(async (command) => {
  107. console.log(`coverage-partitions: start ${command.label}`)
  108. const result = await this.runCommand(command)
  109. if (commandFailed(result)) {
  110. console.error(`coverage-partitions: FAIL ${command.label} (${commandFailureReason(result)})`)
  111. if (result.outputTail !== undefined && result.outputTail !== '') {
  112. console.error(`coverage-partitions: output tail for ${command.label}:\n${result.outputTail}`)
  113. }
  114. }
  115. return result
  116. }))
  117. await this.assertCompleteBlobSet(commands)
  118. const mergeCommand = this.mergeCommand()
  119. console.log(`coverage-partitions: start ${mergeCommand.label}`)
  120. const mergeResult = await this.runCommand(mergeCommand)
  121. return results.some(commandFailed) || commandFailed(mergeResult) ? 1 : 0
  122. } finally {
  123. await removeOwnedTree(this.temporaryRoot)
  124. }
  125. }
  126. private partitionCommand(index: number): CoverageCommand {
  127. const blobPath = join(this.blobsRoot, `partition-${index}.json`)
  128. const reportsDirectory = join(this.temporaryRoot, `coverage-${index}`)
  129. return {
  130. label: `partition ${index}/${this.partitions}`,
  131. args: [
  132. this.pnpmEntrypoint,
  133. 'exec',
  134. 'vitest',
  135. 'run',
  136. '--coverage',
  137. '--coverage.reportOnFailure',
  138. '--maxWorkers=1',
  139. `--shard=${index}/${this.partitions}`,
  140. '--reporter=default',
  141. '--reporter=blob',
  142. `--outputFile.blob=${this.relativePath(blobPath)}`,
  143. `--coverage.reportsDirectory=${this.relativePath(reportsDirectory)}`,
  144. ...this.vitestArgs,
  145. ],
  146. env: {
  147. [COVERAGE_PARTITIONS_ENV]: undefined,
  148. [COVERAGE_PARTITION_MODE_ENV]: '1',
  149. },
  150. cwd: this.root,
  151. blobPath,
  152. }
  153. }
  154. private mergeCommand(): CoverageCommand {
  155. return {
  156. label: 'merged coverage report',
  157. args: [
  158. this.pnpmEntrypoint,
  159. 'exec',
  160. 'vitest',
  161. `--merge-reports=${this.relativePath(this.blobsRoot)}`,
  162. '--coverage',
  163. ],
  164. env: {
  165. [COVERAGE_PARTITIONS_ENV]: undefined,
  166. [COVERAGE_PARTITION_MODE_ENV]: undefined,
  167. },
  168. cwd: this.root,
  169. }
  170. }
  171. private relativePath(path: string): string {
  172. return relative(this.root, path).split(sep).join('/')
  173. }
  174. private async assertCompleteBlobSet(commands: CoverageCommand[]): Promise<void> {
  175. const expected = commands.map((command) => {
  176. if (command.blobPath === undefined) throw new Error(`${command.label} has no blob path.`)
  177. return this.relativePath(command.blobPath)
  178. }).sort()
  179. const actual = (await readdir(this.blobsRoot))
  180. .map(name => this.relativePath(join(this.blobsRoot, name)))
  181. .sort()
  182. if (actual.length !== expected.length || actual.some((name, index) => name !== expected[index])) {
  183. throw new Error(`coverage partitions produced ${JSON.stringify(actual)}; expected ${JSON.stringify(expected)}.`)
  184. }
  185. }
  186. }
  187. /** Spawn one pnpm-backed command without a platform shell. */
  188. function runCoverageCommand(command: CoverageCommand): Promise<CoverageCommandResult> {
  189. return new Promise((resolveCommand) => {
  190. let outputTail = ''
  191. const env = { ...process.env }
  192. for (const [name, value] of Object.entries(command.env)) {
  193. if (value === undefined) Reflect.deleteProperty(env, name)
  194. else env[name] = value
  195. }
  196. const child = spawn(process.execPath, command.args, {
  197. cwd: command.cwd,
  198. env,
  199. stdio: ['ignore', 'pipe', 'pipe'],
  200. })
  201. child.stdout.setEncoding('utf8')
  202. child.stderr.setEncoding('utf8')
  203. child.stdout.on('data', (chunk: string) => {
  204. process.stdout.write(chunk)
  205. outputTail = appendOutputTail(outputTail, chunk)
  206. })
  207. child.stderr.on('data', (chunk: string) => {
  208. process.stderr.write(chunk)
  209. outputTail = appendOutputTail(outputTail, chunk)
  210. })
  211. child.once('error', (error: Error) => {
  212. resolveCommand({ exitCode: null, signalCode: null, error: error.message, outputTail })
  213. })
  214. child.once('close', (exitCode, signalCode) => {
  215. resolveCommand({ exitCode, signalCode, outputTail })
  216. })
  217. })
  218. }
  219. function appendOutputTail(previous: string, chunk: string): string {
  220. const combined = previous + chunk
  221. return combined.length <= 65_536 ? combined : combined.slice(-65_536)
  222. }
  223. function commandFailed(result: CoverageCommandResult): boolean {
  224. return result.exitCode !== 0 || result.signalCode !== null || result.error !== undefined
  225. }
  226. function commandFailureReason(result: CoverageCommandResult): string {
  227. const facts = [
  228. result.error,
  229. result.exitCode === null ? undefined : `exit ${result.exitCode}`,
  230. result.signalCode === null ? undefined : `signal ${result.signalCode}`,
  231. ].filter((fact): fact is string => fact !== undefined)
  232. return facts.join(', ') || 'no exit code or signal'
  233. }
  234. async function removeOwnedTree(path: string): Promise<void> {
  235. const metadata = await lstat(path).catch((error: unknown) => {
  236. if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
  237. throw error
  238. })
  239. if (metadata === undefined) return
  240. if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
  241. await unlink(path)
  242. return
  243. }
  244. await rm(path, { recursive: true, force: true })
  245. }