fix(appd): end sessions whose IPC connection closes and never block on it

IPC_FORWARD held the registry lock while awaiting a send to the
component; with a full queue it stalled appd, and once the relay was
closed it locked the registry again and deadlocked. It now sends without
waiting and reports an error when the session has no relay or its queue
is full.

A relay whose component disconnected left the session running with no
way to exchange messages. The session now stops when its IPC connection
closes. The relay releases its task and socket when dropped, so a
cancelled supervisor leaks neither, and the socket is created with mode
0600.

New tests fail against the previous code: IPC_FORWARD against a missing
relay and a full queue must answer at once, and a runtime that closes
its IPC connection while still running must end its session. The test
runtime directory lives under target/ instead of one directory per run.
This commit is contained in:
Marco Allegretti 2026-10-09 09:18:39 +00:00
parent d9d9d24205
commit 26bd5b5079
No known key found for this signature in database
3 changed files with 150 additions and 20 deletions

View file

@ -514,15 +514,31 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
session_id, session_id,
payload, payload,
} => { } => {
if let Some(tx) = registry.lock().await.ipc_sender_for(session_id) // The registry lock is released before sending; a component that
&& tx.send(payload).await.is_err() // stops reading must not stall appd.
{ let sender = registry.lock().await.ipc_sender_for(session_id);
tracing::warn!(session_id, "IPC relay sender closed"); let Some(tx) = sender else {
registry.lock().await.remove_ipc_sender(session_id); return Response::Error {
} code: 1,
Response::AppState { message: format!("session {session_id} has no IPC relay"),
session_id, };
state: ipc::AppStateKind::Running, };
match tx.try_send(payload) {
Ok(()) => Response::AppState {
session_id,
state: ipc::AppStateKind::Running,
},
Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => Response::Error {
code: 1,
message: format!("session {session_id} is not reading messages"),
},
Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
registry.lock().await.remove_ipc_sender(session_id);
Response::Error {
code: 1,
message: format!("session {session_id} has no IPC relay"),
}
}
} }
} }
Request::PanelGesture { Request::PanelGesture {
@ -622,9 +638,10 @@ mod tests {
/// socket. Callers hold env_lock. /// socket. Callers hold env_lock.
fn use_test_runtime_dir() { fn use_test_runtime_dir() {
let dir = let dir =
std::env::temp_dir().join(format!("weft_test_runtime_dir_{}", std::process::id())); std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-runtime-dir");
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
// SAFETY: callers hold env_lock on a current_thread runtime. // SAFETY: env_lock serialises the tests that change the environment,
// and std serialises the environment accesses themselves.
unsafe { std::env::set_var("XDG_RUNTIME_DIR", &dir) }; unsafe { std::env::set_var("XDG_RUNTIME_DIR", &dir) };
} }
@ -997,6 +1014,106 @@ mod tests {
} }
#[cfg(unix)] #[cfg(unix)]
#[tokio::test]
async fn ipc_forward_never_waits_on_a_component() {
let registry = make_registry();
let forward = |session_id| Request::IpcForward {
session_id,
payload: "x".into(),
};
let reply = dispatch(forward(7), &registry).await;
assert!(matches!(reply, Response::Error { .. }), "{reply:?}");
let (tx, _rx) = tokio::sync::mpsc::channel(1);
registry.lock().await.register_ipc_sender(7, tx);
assert!(matches!(
dispatch(forward(7), &registry).await,
Response::AppState { .. }
));
// The queue is full and nothing reads it: the reply comes at once.
let reply = tokio::time::timeout(
std::time::Duration::from_secs(1),
dispatch(forward(7), &registry),
)
.await
.expect("IPC_FORWARD blocked");
assert!(matches!(reply, Response::Error { .. }), "{reply:?}");
}
#[tokio::test(flavor = "current_thread")]
async fn a_closed_ipc_connection_ends_the_session() {
use std::os::unix::fs::PermissionsExt;
let _env = env_lock().lock().await;
use_test_runtime_dir();
let dir = std::env::temp_dir().join(format!("weft_test_ipc_close_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// The runtime connects to its IPC socket ($4), closes the connection
// and keeps running; the app shell just reports ready.
let runtime = dir.join("runtime.sh");
std::fs::write(
&runtime,
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\n\
python3 -c 'import socket,sys; s=socket.socket(socket.AF_UNIX); \
s.connect(sys.argv[1]); s.close()' \"$4\"\nexec sleep 30\n",
)
.unwrap();
let shell = dir.join("shell.sh");
std::fs::write(
&shell,
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\nexec sleep 30\n",
)
.unwrap();
for script in [&runtime, &shell] {
std::fs::set_permissions(script, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let prior: Vec<_> = [
"WEFT_RUNTIME_BIN",
"WEFT_APP_SHELL_BIN",
"WEFT_DISABLE_CGROUP",
]
.iter()
.map(|k| (*k, std::env::var_os(k)))
.collect();
// SAFETY: env_lock serialises the tests that change the environment.
unsafe {
std::env::set_var("WEFT_RUNTIME_BIN", &runtime);
std::env::set_var("WEFT_APP_SHELL_BIN", &shell);
std::env::set_var("WEFT_DISABLE_CGROUP", "1");
}
let registry = make_registry();
let session_id = registry.lock().await.launch("test.app");
let abort_rx = registry.lock().await.register_abort(session_id);
let finished = tokio::time::timeout(
std::time::Duration::from_secs(15),
runtime::supervise(
session_id,
"test.app",
grants::SessionGrants::default(),
Arc::clone(&registry),
abort_rx,
None,
),
)
.await;
for (key, value) in prior {
// SAFETY: as above.
unsafe {
match value {
Some(v) => std::env::set_var(key, v),
None => std::env::remove_var(key),
}
}
}
let _ = std::fs::remove_dir_all(&dir);
assert!(finished.is_ok(), "the session outlived its IPC connection");
assert!(matches!(
registry.lock().await.state(session_id),
AppStateKind::Stopped
));
}
#[tokio::test(flavor = "current_thread")] #[tokio::test(flavor = "current_thread")]
async fn a_stopped_session_releases_its_ipc_relay() { async fn a_stopped_session_releases_its_ipc_relay() {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
@ -1019,10 +1136,10 @@ mod tests {
.unwrap(); .unwrap();
std::fs::set_permissions(&child, std::fs::Permissions::from_mode(0o755)).unwrap(); std::fs::set_permissions(&child, std::fs::Permissions::from_mode(0o755)).unwrap();
let vars = [ let vars = [
("WEFT_RUNTIME_BIN", child.as_os_str()), ("WEFT_RUNTIME_BIN", child.clone().into_os_string()),
("WEFT_APP_SHELL_BIN", child.as_os_str()), ("WEFT_APP_SHELL_BIN", child.clone().into_os_string()),
("WEFT_DISABLE_CGROUP", std::ffi::OsStr::new("1")), ("WEFT_DISABLE_CGROUP", "1".into()),
("WEFT_APP_STORE", dir.join("store").into_os_string().leak()), ("WEFT_APP_STORE", dir.join("store").into_os_string()),
]; ];
let prior: Vec<_> = vars let prior: Vec<_> = vars
.iter() .iter()

View file

@ -17,7 +17,15 @@ pub(crate) struct IpcRelay {
} }
impl IpcRelay { impl IpcRelay {
fn close(self) { /// Completes when the relay stops: the component closed its connection
/// or the listener failed.
async fn ended(&mut self) {
let _ = (&mut self.task).await;
}
}
impl Drop for IpcRelay {
fn drop(&mut self) {
self.task.abort(); self.task.abort();
let _ = std::fs::remove_file(&self.socket_path); let _ = std::fs::remove_file(&self.socket_path);
} }
@ -34,6 +42,10 @@ pub(crate) fn spawn_ipc_relay(
) -> std::io::Result<(tokio::sync::mpsc::Sender<String>, IpcRelay)> { ) -> std::io::Result<(tokio::sync::mpsc::Sender<String>, IpcRelay)> {
let _ = std::fs::remove_file(&socket_path); let _ = std::fs::remove_file(&socket_path);
let listener = tokio::net::UnixListener::bind(&socket_path)?; let listener = tokio::net::UnixListener::bind(&socket_path)?;
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600))?;
}
let (html_to_wasm_tx, mut html_to_wasm_rx) = tokio::sync::mpsc::channel::<String>(64); let (html_to_wasm_tx, mut html_to_wasm_rx) = tokio::sync::mpsc::channel::<String>(64);
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
let Ok((stream, _)) = listener.accept().await else { let Ok((stream, _)) = listener.accept().await else {
@ -410,6 +422,9 @@ pub(crate) async fn supervise(
format!("app shell exited ({status:?})") format!("app shell exited ({status:?})")
} }
_ = &mut abort_rx => "terminate requested".to_owned(), _ = &mut abort_rx => "terminate requested".to_owned(),
_ = session.relay.as_mut().expect("relay opened").ended() => {
"component closed its IPC connection".to_owned()
}
}; };
session.settle(&registry, &reason).await session.settle(&registry, &reason).await
} }
@ -459,9 +474,7 @@ impl OwnedSession {
} }
self.mount.umount(); self.mount.umount();
kill_portal(self.portal).await; kill_portal(self.portal).await;
if let Some(relay) = self.relay { drop(self.relay);
relay.close();
}
let mut reg = registry.lock().await; let mut reg = registry.lock().await;
reg.remove_ipc_sender(session_id); reg.remove_ipc_sender(session_id);
reg.set_state(session_id, AppStateKind::Stopped); reg.set_state(session_id, AppStateKind::Stopped);

View file

@ -20,7 +20,7 @@ Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signal
### weft-appd ### weft-appd
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. Each wait times out after 30 seconds. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session and accepts one connection, from the session's runtime. appd applies cgroup resource limits to the runtime via systemd-run when available. Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. Each wait times out after 30 seconds. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available.
### weft-runtime ### weft-runtime