diff --git a/packages/metro/src/DeltaBundler/Worker.flow.js b/packages/metro/src/DeltaBundler/Worker.flow.js index c26dbf155a..b6d1b869c0 100644 --- a/packages/metro/src/DeltaBundler/Worker.flow.js +++ b/packages/metro/src/DeltaBundler/Worker.flow.js @@ -20,6 +20,7 @@ import {traverse} from '@babel/core'; import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; +import {isMainThread} from 'node:worker_threads'; export type {JsTransformOptions as TransformOptions} from 'metro-transform-worker'; @@ -53,6 +54,15 @@ type Data = Readonly<{ // variable. delete process.env.JEST_WORKER_ID; +// Whether this module runs in a worker of its own. jest-worker calls `setup` +// in each worker process or thread it starts; with `maxWorkers` of 1, +// WorkerFarm loads this module into Metro's own process and never calls it. +let isInOwnWorker = false; + +export function setup(): void { + isInOwnWorker = true; +} + /** * When the `Buffer` is sent over the worker thread it gets serialized into a JSON object. * This helper method will deserialize it if needed. @@ -125,6 +135,8 @@ async function transformFile( start_timestamp: process.hrtime(), }; + const cpuUsageAtStart = getCpuUsage(); + const sha1 = crypto.createHash('sha1').update(data).digest('hex'); const result = await Transformer.transform( @@ -147,6 +159,7 @@ async function transformFile( const transformFileEndLogEntry = getEndLogEntry( transformFileStartLogEntry, projectRelativePath, + cpuUsageAtStart, ); return { @@ -157,15 +170,61 @@ async function transformFile( }; } -function getEndLogEntry(startLogEntry: LogEntry, filename: string): LogEntry { +type CpuUsage = Readonly<{user: number, system: number}>; + +// The CPU time of this worker, in microseconds. A child process worker runs one +// transform at a time, so its whole process is counted. Worker threads share a +// process, so a thread reads only its own time, where Node supports it +// (`process.threadCpuUsage`, added in Node 23.9). In Metro's own process, +// transforms interleave with each other and with the server's work, so none +// is measured there. +function getCpuUsage(): ?CpuUsage { + if (!isInOwnWorker) { + return null; + } + if (isMainThread) { + const {user, system} = process.cpuUsage(); + return {user, system}; + } + // Not in the Node library definitions yet. + const threadCpuUsage = Reflect.get(process, 'threadCpuUsage'); + if (typeof threadCpuUsage !== 'function') { + return null; + } + const usage: unknown = threadCpuUsage(); + if ( + usage != null && + typeof usage === 'object' && + typeof usage.user === 'number' && + typeof usage.system === 'number' + ) { + return {user: usage.user, system: usage.system}; + } + return null; +} + +function getEndLogEntry( + startLogEntry: LogEntry, + filename: string, + cpuUsageAtStart: ?CpuUsage, +): LogEntry { const timeDelta = process.hrtime(startLogEntry.start_timestamp); const duration_ms = Math.round((timeDelta[0] * 1e9 + timeDelta[1]) / 1e6); + const cpuUsageAtEnd = cpuUsageAtStart != null ? getCpuUsage() : null; return { action_name: 'Transforming file', action_phase: 'end', file_name: filename, duration_ms, + ...(cpuUsageAtStart != null && cpuUsageAtEnd != null + ? { + cpu_time_us: + cpuUsageAtEnd.user - + cpuUsageAtStart.user + + (cpuUsageAtEnd.system - cpuUsageAtStart.system), + } + : null), log_entry_label: 'Transforming file', }; } diff --git a/packages/metro/src/DeltaBundler/WorkerFarm.js b/packages/metro/src/DeltaBundler/WorkerFarm.js index 22d4b2a14a..5f66ff8e84 100644 --- a/packages/metro/src/DeltaBundler/WorkerFarm.js +++ b/packages/metro/src/DeltaBundler/WorkerFarm.js @@ -62,7 +62,8 @@ export default class WorkerFarm { this._worker = worker; } else { // eslint-disable-next-line import/no-commonjs - this._worker = require('./Worker') as Worker; + const {transform} = require('./Worker'); + this._worker = {transform}; } } diff --git a/packages/metro/src/DeltaBundler/__tests__/WorkerFarm-cpuTime-test.js b/packages/metro/src/DeltaBundler/__tests__/WorkerFarm-cpuTime-test.js new file mode 100644 index 0000000000..a2fc6baf7b --- /dev/null +++ b/packages/metro/src/DeltaBundler/__tests__/WorkerFarm-cpuTime-test.js @@ -0,0 +1,94 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * @oncall react_native + */ + +'use strict'; + +const WorkerFarm = require('../WorkerFarm').default; +const {getDefaultConfig} = require('metro-config'); +const {Logger} = require('metro-core'); + +jest.setTimeout(60 * 1000); +jest.useRealTimers(); + +const endEntries = []; +Logger.on('log', entry => { + if ( + entry.action_name === 'Transforming file' && + entry.action_phase === 'end' + ) { + endEntries.push(entry); + } +}); + +async function transformOneFile({maxWorkers, unstable_workerThreads}) { + const config = await getDefaultConfig(__dirname); + const farm = new WorkerFarm( + { + ...config, + maxWorkers, + projectRoot: __dirname, + transformer: {...config.transformer, unstable_workerThreads}, + }, + { + transformerPath: require.resolve('./cpuBusyTransformer'), + transformerConfig: {}, + }, + ); + try { + endEntries.length = 0; + await farm.transform('file.js', {}, Buffer.from('')); + return endEntries[0]; + } finally { + await farm.kill(); + } +} + +const threadCpuUsageSupported = + typeof Reflect.get(process, 'threadCpuUsage') === 'function'; + +test('a child process worker logs the CPU time of a transform', async () => { + const entry = await transformOneFile({ + maxWorkers: 2, + unstable_workerThreads: false, + }); + + // The transformer keeps the CPU busy for 200 ms. + expect(entry.cpu_time_us).toBeGreaterThan(100_000); + expect(entry.cpu_time_us).toBeLessThanOrEqual( + (entry.duration_ms + 50) * 1000, + ); +}); + +(threadCpuUsageSupported ? test : test.skip)( + 'a worker thread logs the CPU time of its own thread', + async () => { + const entry = await transformOneFile({ + maxWorkers: 2, + unstable_workerThreads: true, + }); + + expect(entry.cpu_time_us).toBeGreaterThan(100_000); + expect(entry.cpu_time_us).toBeLessThanOrEqual( + (entry.duration_ms + 50) * 1000, + ); + }, +); + +test('a transform in the server process logs no CPU time', async () => { + // With `maxWorkers` of 1, transforms run in the server process alongside + // each other, so process CPU time would include all of them. + const entry = await transformOneFile({ + maxWorkers: 1, + unstable_workerThreads: false, + }); + + expect(entry.duration_ms).toBeGreaterThan(100); + expect(entry).not.toHaveProperty('cpu_time_us'); +}); diff --git a/packages/metro/src/DeltaBundler/__tests__/cpuBusyTransformer.js b/packages/metro/src/DeltaBundler/__tests__/cpuBusyTransformer.js new file mode 100644 index 0000000000..076c119198 --- /dev/null +++ b/packages/metro/src/DeltaBundler/__tests__/cpuBusyTransformer.js @@ -0,0 +1,39 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * @oncall react_native + */ + +'use strict'; + +// A transformer that keeps the CPU busy for a while before returning an empty +// module. +const BUSY_MS = 200; + +module.exports = { + transform: async () => { + const until = Date.now() + BUSY_MS; + let x = 0; + while (Date.now() < until) { + x += Math.sqrt(x + 1); + } + return { + dependencies: [], + output: [ + { + type: 'js/module', + data: { + code: String(x > 0), + lineCount: 1, + map: [], + functionMap: null, + }, + }, + ], + }; + }, +};