Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,20 @@ import { join } from 'node:path';
import { createInterface } from 'node:readline';

const workerMode = process.argv[2] === '--worker';
// The global vp runs `dist/bin.js`, which keeps Vite in a child process.
const globalMode = process.argv[2] === '--global';
const localMode = !workerMode && !globalMode;

async function listenerInfo(stdout, launchPid) {
let listener;
for await (const line of createInterface({ input: stdout })) {
const match = /^listening (\d+) (\d+)$/.exec(line);
if (match) {
listener = { port: Number(match[1]), pid: Number(match[2]) };
if (globalMode) {
assert.notEqual(listener.pid, launchPid, 'Vite runs below the global vp process');
return listener;
}
if (!workerMode) {
assert.equal(listener.pid, launchPid);
return listener;
Expand All @@ -32,7 +39,7 @@ const cache = mkdtempSync(join(tmpdir(), 'vp-dev-cache-'));
const cacheProof = join(cache, 'cache-before-vite');
const env = { ...process.env, NODE_COMPILE_CACHE: cache };
delete env.NODE_DISABLE_COMPILE_CACHE;
if (!workerMode) {
if (localMode) {
env.NODE_OPTIONS = ['--require=./check-launcher-cache.cjs', env.NODE_OPTIONS]
.filter(Boolean)
.join(' ');
Expand All @@ -57,15 +64,15 @@ try {
console.log('Vite served the project with the client under /probe/');
if (workerMode) {
console.log('The Worker host stayed alive while Vite ran as a child');
} else {
} else if (localMode) {
assert.ok(
existsSync(cacheProof),
'Vite startup checked the launcher cache before loading its entry point',
);
console.log('vp saved its compile cache before starting Vite');
}

process.kill(pid, 'SIGTERM');
process.kill(globalMode ? child.pid : pid, 'SIGTERM');
const [code, signal] = await once(child, 'exit', { signal: AbortSignal.timeout(5_000) });
const socket = connect(port, '127.0.0.1');
try {
Expand All @@ -76,7 +83,7 @@ try {
socket.destroy();
}
assert.deepEqual([code, signal], [143, null]);
const target = workerMode ? 'Vite child' : 'launch PID';
const target = workerMode ? 'Vite child' : globalMode ? 'global vp PID' : 'launch PID';
console.log(`SIGTERM to the ${target} closed the port with exit code 143`);
} catch (error) {
console.error(error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,10 @@ vp = "local"
skip-platforms = ["windows"]
comment = "A Node Worker runs project-local vp dev without replacing its host process."
steps = [{ argv = ["node", "probe.mjs", "--worker"], tty = false, timeout = 25000 }]

[[case]]
name = "command_dev_global_signal"
vp = "global"
Comment thread
fengmk2 marked this conversation as resolved.
Resolved
skip-platforms = ["windows"]
comment = "SIGTERM sent to the global vp dev PID passes through each wrapper and stops the listening Vite server."
steps = [{ argv = ["node", "probe.mjs", "--global"], tty = false, timeout = 25000 }]
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# command_dev_global_signal

SIGTERM sent to the global vp dev PID passes through each wrapper and stops the listening Vite server.

## `node probe.mjs --global`

```
Vite served the project with the client under /probe/
SIGTERM to the global vp PID closed the port with exit code 143
```
7 changes: 6 additions & 1 deletion crates/vp_command/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ use vt_path::{AbsolutePath, AbsolutePathBuf, RelativePathBuf};

mod external_tool;
mod ps1_shim;
#[cfg(unix)]
mod signal_forward;

pub use external_tool::{
ExternalToolQuery, FirstPathMatch, classify_first_path_match, find_external_tool,
Expand Down Expand Up @@ -141,7 +143,8 @@ pub fn exec_node_command(mut cmd: Command) -> Error {
/// is interrupted (e.g., via Ctrl+C) while the terminal is in a non-standard state.
///
/// On Unix, saves the terminal state before spawning the child process and restores
/// it after the child exits, and ignores SIGINT meanwhile. On Windows, Ctrl+C is ignored
/// it after the child exits, and ignores SIGINT meanwhile. It also forwards SIGTERM and
/// SIGHUP to the child (`SignalForwardGuard`). On Windows, Ctrl+C is ignored
/// meanwhile (`ConsoleCtrlGuard`), so this process waits for the child's own cleanup.
pub async fn execute_with_terminal_guard(mut cmd: Command) -> Result<ExitStatus, Error> {
// Save terminal state and ignore SIGINT (Unix) or Ctrl+C (Windows) until the child exits.
Expand All @@ -151,6 +154,8 @@ pub async fn execute_with_terminal_guard(mut cmd: Command) -> Result<ExitStatus,
let _guard = ConsoleCtrlGuard::install();

let mut child = cmd.spawn().map_err(|e| Error::Anyhow(e.into()))?;
#[cfg(unix)]
let _forward = child.id().and_then(signal_forward::SignalForwardGuard::install);
Comment thread
fengmk2 marked this conversation as resolved.
Resolved
child.wait().await.map_err(|e| Error::Anyhow(e.into()))
}

Expand Down
73 changes: 73 additions & 0 deletions crates/vp_command/src/signal_forward.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
//! Forward termination signals from a wrapper process to the child it waits for.

use std::{
mem::MaybeUninit,
sync::atomic::{AtomicI32, Ordering},
};

use nix::{
libc,
sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction},
};

/// The child that receives forwarded signals, or 0 when no guard is alive.
static FORWARD_PID: AtomicI32 = AtomicI32::new(0);

/// While alive, sends SIGTERM and SIGHUP that reach this process on to the child.
///
/// A process manager or `kill <pid>` signals only this process. Without this
/// guard, this process exits and the child keeps running. SIGINT is not
/// forwarded, because the terminal sends Ctrl+C to the whole process group.
pub(crate) struct SignalForwardGuard {
previous: Vec<(Signal, SigAction)>,
}

impl SignalForwardGuard {
/// Returns `None` when another guard already forwards to a child.
pub(crate) fn install(pid: u32) -> Option<Self> {
let pid = i32::try_from(pid).ok()?;
FORWARD_PID.compare_exchange(0, pid, Ordering::SeqCst, Ordering::SeqCst).ok()?;
let action =
SigAction::new(SigHandler::Handler(forward), SaFlags::SA_RESTART, SigSet::empty());
let previous = [Signal::SIGTERM, Signal::SIGHUP]
.into_iter()
// Keep a signal that the caller ignores, such as SIGHUP under `nohup`.
.filter(|&signal| !is_ignored(signal))
.filter_map(|signal| {
// SAFETY: `forward` only calls async-signal-safe functions.
let previous = unsafe { sigaction(signal, &action) }.ok()?;
Comment thread
fengmk2 marked this conversation as resolved.
Resolved
Some((signal, previous))
})
.collect();
Some(Self { previous })
}
}

impl Drop for SignalForwardGuard {
fn drop(&mut self) {
// The child has exited. Stop forwarding before its PID can be reused.
FORWARD_PID.store(0, Ordering::SeqCst);
for (signal, previous) in self.previous.drain(..) {
// SAFETY: reinstalls the disposition captured by `install`.
let _ = unsafe { sigaction(signal, &previous) };
}
}
}

/// Reads the disposition without replacing it.
fn is_ignored(signal: Signal) -> bool {
let mut current = MaybeUninit::<libc::sigaction>::uninit();
// SAFETY: a null action only writes the current disposition to `current`.
unsafe {
libc::sigaction(signal as libc::c_int, std::ptr::null(), current.as_mut_ptr()) == 0
&& current.assume_init().sa_sigaction == libc::SIG_IGN
}
}

extern "C" fn forward(signal: libc::c_int) {
let pid = FORWARD_PID.load(Ordering::SeqCst);
if pid > 0 {
// SAFETY: `kill` is async-signal-safe.
unsafe { libc::kill(pid, signal) };
Comment thread
fengmk2 marked this conversation as resolved.
Resolved
}
}
Loading