import { deepStrictEqual, strictEqual, throws } from 'node:assert'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { workspaceNativeRunClaim } from '@stim-cli/core/state'; import { requestNativeRunCancel } from '../engine/native-run.ts'; import { readClaimSet } from '../ownership-claim.ts'; import { runPluginIosBuild } from '../integrations/plugin-ios.ts'; import { createNdjsonWriter } from '../ndjson.ts'; let root: string; beforeEach(() => { root = realpathSync(mkdtempSync(join(tmpdir(), 'stim-plugin-compile-'))); vi.stubEnv('STIM_HOME', join(root, 'home')); }); afterEach(() => { vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true }); }); test.each(['relative', 'absolute'])('uses the project bundle with the %s compiler result', async (kind) => { const appPath = join(root, 'build', 'Fixture.app'); mkdirSync(appPath, { recursive: true }); writeFileSync( join(appPath, 'Info.plist'), 'CFBundleIdentifierdev.stim.fixture', ); const app = kind === 'relative' ? 'build/Fixture.app' : appPath; const log = createNdjsonWriter(join(root, 'build.ndjson')); onTestFinished(() => { log.close(); }); const built = await runPluginIosBuild( { id: 'fixture', ios: { build: () => ({ argv: [process.execPath, '-e', 'console.log(process.argv[1])', app], env: process.env }), result: ({ lines }) => ({ app: lines.at(-1) ?? null, diagnostics: [] }), }, }, { root, configuration: null, simulator: null, env: process.env, logWriter: log, onHeartbeat() {}, estimateMs: null, }, ); expect(built).toMatchObject({ ok: true, appPath, bundleId: 'dev.stim.fixture' }); }); describe.skipIf(process.platform === 'win32')('compiler process group', () => { test.each([ ['SIGTERM', 'verified', 143], ['SIGTERM', 'unverified', 2], ['SIGINT', 'verified', 130], ['two interrupts', 'verified', 130], ['stop', 'verified', 1], ] as const)( '%s stops the compiler group and handles %s cleanup', async (trigger, cleanup, expectedExit) => { const ready = join(root, 'compiler-pid'); const terminated = join(root, 'compiler-terminated'); const descendant = join(root, 'descendant-pid'); const slotMarker = join(root, 'build-slot-path'); const compiler = ` const fs = require('node:fs'); const { spawn } = require('node:child_process'); spawn(process.execPath, ['-e', "process.on('SIGINT', () => {}); require('node:fs').writeFileSync(process.argv[1], String(process.pid)); setTimeout(() => {}, 60000)", process.argv[3], ], { stdio: ['ignore', 1, 2] }); for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => fs.appendFileSync(process.argv[2], signal)); process.stdout.write('compiler stdout\\n'); process.stderr.write('compiler stderr\\n'); fs.writeFileSync(process.argv[1], String(process.pid)); setInterval(() => {}, 1000); `; const script = ` import { readFileSync, writeFileSync } from 'node:fs'; import { runProcessOperation } from '../cli-operation.ts'; import { tryAcquireBuildSlot, releaseBuildSlot } from '../engine/build-slots.ts'; import { withNativeBuildRun } from '../engine/native-run.ts'; import { withIosOperationScope } from '../integrations/ios-operation-scope.ts'; import { runPluginIosBuild } from '../integrations/plugin-ios.ts'; const [root, ready, terminated, descendant, slotMarker, cleanup] = process.argv.slice(1); if (cleanup === 'unverified') { const kill = process.kill; process.kill = (pid, signal) => { if (signal === 'SIGKILL' && pid < 0 && pid === -Number(readFileSync(ready, 'utf8'))) throw Object.assign(new Error('Compiler group signal denied'), { code: 'EPERM' }); return kill(pid, signal); }; } const source = { id: 'fixture', ios: { build: () => ({ argv: [process.execPath, '-e', ${JSON.stringify(compiler)}, ready, terminated, descendant], env: process.env }), result: ({ lines }) => { if (!lines.includes('compiler stdout') || !lines.includes('compiler stderr')) throw new Error('Missing compiler output: ' + JSON.stringify(lines)); return { app: null, diagnostics: [] }; }, }, }; try { const { interrupted } = await runProcessOperation(root, (context) => withNativeBuildRun(context, root, { command: 'ios', platform: 'ios', slot: 'default' }, async () => { const slot = tryAcquireBuildSlot({ max: 1, root, context }); if (!slot || slot.unlimited) throw new Error('Could not claim a build slot'); writeFileSync(slotMarker, slot.path); let retain = false; try { return await withIosOperationScope(context, (scope) => { scope.own(async () => {}); return runPluginIosBuild(source, { root, configuration: null, simulator: null, env: process.env, logWriter: {}, onHeartbeat() {}, estimateMs: null, scope, }); }); } catch (error) { retain = error.claims?.includes(slot.claim) === true; throw error; } finally { releaseBuildSlot(slot, retain); } }, { write() {} }), ); process.exitCode = interrupted ?? 1; } catch (error) { console.error(error.code ?? error); process.exitCode = error.code === 'STIM_CLAIM_UNAVAILABLE' ? 2 : 1; } `; const runner = spawn( process.execPath, [ '--experimental-strip-types', '--input-type=module', '-e', script, '--', root, ready, terminated, descendant, slotMarker, cleanup, ], { cwd: import.meta.dirname, stdio: ['ignore', 'ignore', 'pipe'], }, ); let stderr = ''; runner.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; }); const closed = once(runner, 'close'); const claim = workspaceNativeRunClaim(root); let compilerExited = false; try { await vi.waitFor( () => { if (!existsSync(ready) || !existsSync(descendant)) throw new Error(stderr || 'Compiler group has not started'); }, { timeout: 5000 }, ); expect(existsSync(claim)).toBe(true); const pid = Number(readFileSync(ready, 'utf8')); const descendantPid = Number(readFileSync(descendant, 'utf8')); const slotPath = readFileSync(slotMarker, 'utf8'); expect(process.kill(descendantPid, 0)).toBe(true); const interrupt = trigger === 'two interrupts' ? 'SIGINT' : trigger; if (interrupt === 'stop') { const [holder] = readClaimSet(claim).live; if (!holder) throw new Error('Native-run holder is missing'); requestNativeRunCancel(root, holder.claimId); } else { strictEqual(runner.kill(interrupt), true); } await vi.waitFor(() => expect(existsSync(terminated)).toBe(true), { timeout: 3000 }); if (trigger === 'SIGTERM') strictEqual(process.kill(descendantPid, 0), true); expect(existsSync(claim)).toBe(true); expect(existsSync(slotPath)).toBe(true); if (trigger === 'two interrupts') { strictEqual(runner.kill('SIGINT'), true); await vi.waitFor( () => { throws(() => process.kill(pid, 0), { code: 'ESRCH' }); throws(() => process.kill(descendantPid, 0), { code: 'ESRCH' }); }, { timeout: 1500 }, ); } const exit = await Promise.race([ closed, new Promise((resolve) => { const timeout = setTimeout(() => resolve('timed out'), 22000); timeout.unref(); }), ]); deepStrictEqual(exit, [expectedExit, null], stderr || `Expected the CLI to exit after ${trigger}`); expect(stderr.includes('STIM_CLAIM_UNAVAILABLE')).toBe(cleanup === 'unverified'); expect(readFileSync(terminated, 'utf8')).toBe(interrupt === 'stop' ? 'SIGINT' : interrupt); expect(() => process.kill(pid, 0)).toThrow(/ESRCH/); if (cleanup === 'verified') throws(() => process.kill(descendantPid, 0), { code: 'ESRCH' }); else strictEqual(process.kill(descendantPid, 0), true); compilerExited = true; expect(existsSync(claim)).toBe(cleanup === 'unverified'); expect(existsSync(slotPath)).toBe(cleanup === 'unverified'); } finally { for (const marker of [...(compilerExited ? [] : [ready]), descendant]) { if (existsSync(marker)) { const pid = Number(readFileSync(marker, 'utf8')); try { process.kill(pid, 'SIGKILL'); } catch {} } } runner.kill('SIGKILL'); await closed; } }, 30000, ); });