-
Notifications
You must be signed in to change notification settings - Fork 44
feat: forward user signals to builds/runs #1088
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,7 +7,8 @@ import { ACTOR_JOB_STATUSES } from '@apify/consts'; | |
|
|
||
| import { Flags } from '../command-framework/flags.js'; | ||
| import { CommandExitCodes } from '../consts.js'; | ||
| import { error, run as runLog, success, warning } from '../outputs.js'; | ||
| import { useSignalHandler } from '../hooks/useSignalHandler.js'; | ||
| import { error, info, run as runLog, success, warning } from '../outputs.js'; | ||
| import { outputJobLog } from '../utils.js'; | ||
| import { resolveInput } from './resolve-input.js'; | ||
|
|
||
|
|
@@ -90,6 +91,63 @@ export async function* runActorOrTaskOnCloud(apifyClient: ApifyClient, options: | |
| throw err; | ||
| } | ||
|
|
||
| // From this point on the run exists on the platform. Forward interrupt | ||
| // signals to a platform-side abort so the run does not keep burning | ||
| // compute units after the user gives up waiting locally (Ctrl+C, SIGTERM | ||
| // from a parent process, SIGHUP from a closing terminal). The `using` | ||
| // binding removes the listener when this generator finishes or is | ||
| // terminated by the consumer (e.g. `break` out of `for await`). | ||
| // | ||
| // `once: false` keeps the listener registered across repeated signals so | ||
| // the default Node behavior (terminate the process) is suppressed while | ||
| // the abort is in flight. We escalate across attempts: | ||
| // 1st signal → graceful abort, with a hint the user can press again | ||
| // 2nd signal → immediate abort | ||
| // 3rd+ → silent no-op, so frantic Ctrl+C doesn't kill the CLI | ||
| // before the abort request finishes. | ||
| let abortAttempt = 0; | ||
|
|
||
| using _signalHandler = useSignalHandler({ | ||
| signals: ['SIGINT', 'SIGTERM', 'SIGHUP'], | ||
| once: false, | ||
| handler: async (signal) => { | ||
| abortAttempt += 1; | ||
|
|
||
| if (abortAttempt > 2) { | ||
| return; | ||
| } | ||
|
Comment on lines
+116
to
+118
|
||
|
|
||
| const gracefully = abortAttempt === 1; | ||
|
|
||
| if (!silent) { | ||
| if (gracefully) { | ||
| info({ | ||
| message: chalk.gray( | ||
| `Received ${chalk.yellow(signal)}, gracefully aborting ${type.toLowerCase()} run "${chalk.yellow(run.id)}" on the Apify platform... ${chalk.dim('(press Ctrl+C again to abort immediately)')}`, | ||
| ), | ||
| stdout: true, | ||
| }); | ||
| } else { | ||
| info({ | ||
| message: chalk.gray( | ||
| `Received ${chalk.yellow(signal)} again, aborting ${type.toLowerCase()} run "${chalk.yellow(run.id)}" immediately...`, | ||
| ), | ||
| stdout: true, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| try { | ||
| await apifyClient.run(run.id).abort({ gracefully }); | ||
| } catch (abortErr) { | ||
| error({ | ||
| message: `Failed to abort run "${run.id}": ${(abortErr as Error).message}`, | ||
| stdout: true, | ||
| }); | ||
| } | ||
| }, | ||
| }); | ||
|
|
||
| // Return the started run right away | ||
| yield run; | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -5,10 +5,25 @@ import { normalizeExecutablePath } from './hooks/runtimes/utils.js'; | |||||
| import { error, run } from './outputs.js'; | ||||||
| import { cliDebugPrint } from './utils/cliDebugPrint.js'; | ||||||
|
|
||||||
| const spawnPromised = async (cmd: string, args: string[], opts: Options) => { | ||||||
| interface SpawnPromisedInternalOptions { | ||||||
| /** | ||||||
| * Signals that should be forwarded from the parent process to the spawned | ||||||
| * child. When the CLI receives one of these signals it is re-sent to the | ||||||
| * child so it can shut down cleanly instead of being orphaned when the CLI | ||||||
| * exits. | ||||||
| */ | ||||||
| forwardSignals?: NodeJS.Signals[]; | ||||||
| } | ||||||
|
|
||||||
| const spawnPromised = async ( | ||||||
| cmd: string, | ||||||
| args: string[], | ||||||
| opts: Options, | ||||||
| { forwardSignals }: SpawnPromisedInternalOptions = {}, | ||||||
| ) => { | ||||||
| const escapedCommand = normalizeExecutablePath(cmd); | ||||||
|
|
||||||
| cliDebugPrint('spawnPromised', { escapedCommand, args, opts }); | ||||||
| cliDebugPrint('spawnPromised', { escapedCommand, args, opts, forwardSignals }); | ||||||
|
|
||||||
| const childProcess = execa(escapedCommand, args, { | ||||||
| shell: true, | ||||||
|
|
@@ -21,23 +36,58 @@ const spawnPromised = async (cmd: string, args: string[], opts: Options) => { | |||||
| verbose: process.env.APIFY_CLI_DEBUG ? 'full' : undefined, | ||||||
| }); | ||||||
|
|
||||||
| return Result.fromAsync( | ||||||
| childProcess.catch((execaError: ExecaError) => { | ||||||
| throw new Error(`${cmd} exited with code ${execaError.exitCode}`, { cause: execaError }); | ||||||
| }), | ||||||
| ) as Promise<Result<Awaited<typeof childProcess>, Error & { cause: ExecaError }>>; | ||||||
| const cleanupSignalHandlers: (() => void)[] = []; | ||||||
|
|
||||||
| if (forwardSignals?.length) { | ||||||
| for (const signal of forwardSignals) { | ||||||
| const handler = () => { | ||||||
| childProcess.kill(signal); | ||||||
| }; | ||||||
|
|
||||||
| process.on(signal, handler); | ||||||
|
||||||
| process.on(signal, handler); | |
| process.once(signal, handler); |
Copilot
AI
Apr 19, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
New forwardSignals behavior isn’t covered by tests. There are existing Vitest tests for execWithLog, so it would be good to add a test that simulates a signal and asserts the child receives it (and that handlers are cleaned up).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
After the first abort attempt, subsequent signals are ignored (
abortAttempt > 1returns) whileonce: falsekeeps intercepting them. This can leave users unable to force-terminate the CLI if aborting/streaming hangs. Consider removing/disposing the signal handler (or letting later signals fall through) after sending the abort request.