mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
fix(appd): close a running session as a user close would before terminating it
TERMINATE_APP, which the taskbar sends, killed the session's processes at once, so an application had no chance to finish, for example to save. A running session is now asked to close through the compositor (AppCloseRequest, which sends xdg_toplevel close to its windows) and the app shell is given five seconds to exit by itself before what remains is terminated. The stop reason records whether the app closed or was terminated after the timeout. TERMINATE_APP replies stopping and the session stays registered until it settles; a starting session is stopped at once, and appd shutting down terminates sessions without a close. check_counter.py requires the compositor to ask the session's window to close and the app shell to exit with status 0 on the close; a unit test requires an app that ignores the close to be terminated after the timeout and not before.
This commit is contained in:
parent
102c20d2b4
commit
80d7451abf
7 changed files with 196 additions and 14 deletions
|
|
@ -86,10 +86,19 @@ impl SessionRegistry {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asks a session to stop: a running session is closed as a user close
|
||||||
|
/// would close it, a starting one is stopped at once. The session stays
|
||||||
|
/// registered, Stopping, until its supervisor settles it.
|
||||||
fn terminate(&mut self, session_id: u64) -> bool {
|
fn terminate(&mut self, session_id: u64) -> bool {
|
||||||
let found = self.sessions.remove(&session_id).is_some();
|
match self.abort_senders.remove(&session_id) {
|
||||||
self.abort_senders.remove(&session_id);
|
Some(sender) => {
|
||||||
found
|
let _ = sender.send(());
|
||||||
|
self.set_state(session_id, AppStateKind::Stopping);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
// A session no supervisor runs has nothing to settle.
|
||||||
|
None => self.sessions.remove(&session_id).is_some(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn register_abort(&mut self, session_id: u64) -> tokio::sync::oneshot::Receiver<()> {
|
pub(crate) fn register_abort(&mut self, session_id: u64) -> tokio::sync::oneshot::Receiver<()> {
|
||||||
|
|
@ -532,10 +541,10 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
||||||
Request::TerminateApp { session_id } => {
|
Request::TerminateApp { session_id } => {
|
||||||
let found = registry.lock().await.terminate(session_id);
|
let found = registry.lock().await.terminate(session_id);
|
||||||
if found {
|
if found {
|
||||||
tracing::info!(session_id, "terminated");
|
tracing::info!(session_id, "stop requested");
|
||||||
Response::AppState {
|
Response::AppState {
|
||||||
session_id,
|
session_id,
|
||||||
state: AppStateKind::Stopped,
|
state: AppStateKind::Stopping,
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Response::Error {
|
Response::Error {
|
||||||
|
|
@ -915,7 +924,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn dispatch_terminate_known_returns_stopped() {
|
async fn dispatch_terminate_known_returns_stopping() {
|
||||||
let _env = env_lock().lock().await;
|
let _env = env_lock().lock().await;
|
||||||
let reg = make_registry();
|
let reg = make_registry();
|
||||||
let ack = dispatch(
|
let ack = dispatch(
|
||||||
|
|
@ -930,11 +939,13 @@ mod tests {
|
||||||
Response::LaunchAck { session_id, .. } => session_id,
|
Response::LaunchAck { session_id, .. } => session_id,
|
||||||
_ => panic!("expected LaunchAck"),
|
_ => panic!("expected LaunchAck"),
|
||||||
};
|
};
|
||||||
|
// The reply says the session is stopping; Stopped is broadcast once
|
||||||
|
// its supervisor has settled it.
|
||||||
let resp = dispatch(Request::TerminateApp { session_id }, ®).await;
|
let resp = dispatch(Request::TerminateApp { session_id }, ®).await;
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
resp,
|
resp,
|
||||||
Response::AppState {
|
Response::AppState {
|
||||||
state: AppStateKind::Stopped,
|
state: AppStateKind::Stopping,
|
||||||
..
|
..
|
||||||
}
|
}
|
||||||
));
|
));
|
||||||
|
|
@ -1349,6 +1360,115 @@ mod tests {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "current_thread")]
|
||||||
|
async fn an_app_that_ignores_a_close_is_terminated_after_the_timeout() {
|
||||||
|
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_close_{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let app = dir.join("store/org.example.close");
|
||||||
|
write_test_package(&app, "org.example.close", "");
|
||||||
|
// Both children report ready and then ignore everything.
|
||||||
|
let child = dir.join("child.sh");
|
||||||
|
std::fs::write(
|
||||||
|
&child,
|
||||||
|
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\nexec sleep 30\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::set_permissions(&child, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
let vars = [
|
||||||
|
("WEFT_RUNTIME_BIN", child.clone().into_os_string()),
|
||||||
|
("WEFT_APP_SHELL_BIN", child.clone().into_os_string()),
|
||||||
|
("WEFT_DISABLE_CGROUP", "1".into()),
|
||||||
|
("WEFT_APP_STORE", dir.join("store").into_os_string()),
|
||||||
|
];
|
||||||
|
let prior: Vec<_> = vars
|
||||||
|
.iter()
|
||||||
|
.map(|(k, _)| (*k, std::env::var_os(k)))
|
||||||
|
.collect();
|
||||||
|
for (key, value) in &vars {
|
||||||
|
// SAFETY: env_lock is held on a current_thread runtime.
|
||||||
|
unsafe { std::env::set_var(key, value) };
|
||||||
|
}
|
||||||
|
|
||||||
|
let registry = make_registry();
|
||||||
|
let (tx, mut compositor) = tokio::sync::mpsc::channel(8);
|
||||||
|
registry.lock().await.compositor_tx = Some(compositor_client::CompositorSender::new(
|
||||||
|
tx,
|
||||||
|
std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
|
||||||
|
));
|
||||||
|
let mut rx = registry.lock().await.subscribe();
|
||||||
|
let ack = dispatch(
|
||||||
|
Request::LaunchApp {
|
||||||
|
app_id: "org.example.close".into(),
|
||||||
|
surface_id: 0,
|
||||||
|
},
|
||||||
|
®istry,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let Response::LaunchAck { session_id, .. } = ack else {
|
||||||
|
panic!("{ack:?}");
|
||||||
|
};
|
||||||
|
let ready = tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||||
|
while !matches!(rx.recv().await, Ok(Response::AppReady { .. })) {}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let reply = dispatch(Request::TerminateApp { session_id }, ®istry).await;
|
||||||
|
let stopped = tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||||
|
while !matches!(
|
||||||
|
rx.recv().await,
|
||||||
|
Ok(Response::AppState {
|
||||||
|
state: AppStateKind::Stopped,
|
||||||
|
..
|
||||||
|
})
|
||||||
|
) {}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let elapsed = started.elapsed();
|
||||||
|
let mut sent = Vec::new();
|
||||||
|
while let Ok(out) = compositor.try_recv() {
|
||||||
|
sent.push(out.msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
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!(ready.is_ok(), "the session did not become ready");
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
reply,
|
||||||
|
Response::AppState {
|
||||||
|
state: AppStateKind::Stopping,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
),
|
||||||
|
"{reply:?}"
|
||||||
|
);
|
||||||
|
assert!(stopped.is_ok(), "the session did not stop");
|
||||||
|
// The app was asked to close, given the timeout, then terminated.
|
||||||
|
assert!(
|
||||||
|
sent.iter().any(|m| matches!(
|
||||||
|
m,
|
||||||
|
weft_ipc_types::AppdToCompositor::AppCloseRequest { session_id: s } if *s == session_id
|
||||||
|
)),
|
||||||
|
"{sent:?}"
|
||||||
|
);
|
||||||
|
assert!(elapsed >= runtime::CLOSE_TIMEOUT, "{elapsed:?}");
|
||||||
|
assert!(
|
||||||
|
elapsed < runtime::CLOSE_TIMEOUT + std::time::Duration::from_secs(5),
|
||||||
|
"{elapsed:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test(flavor = "current_thread")]
|
#[tokio::test(flavor = "current_thread")]
|
||||||
async fn without_a_connected_compositor_nothing_is_started() {
|
async fn without_a_connected_compositor_nothing_is_started() {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
@ -1746,9 +1866,10 @@ mod tests {
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
// The session stays registered until it settles, then is Stopped.
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
registry.lock().await.state(session_id),
|
registry.lock().await.state(session_id),
|
||||||
AppStateKind::NotFound
|
AppStateKind::Stopped
|
||||||
));
|
));
|
||||||
|
|
||||||
let broadcast = rx.try_recv();
|
let broadcast = rx.try_recv();
|
||||||
|
|
|
||||||
|
|
@ -449,7 +449,11 @@ pub(crate) async fn supervise(
|
||||||
status = session.app_shell.as_mut().expect("app shell spawned").wait() => {
|
status = session.app_shell.as_mut().expect("app shell spawned").wait() => {
|
||||||
format!("app shell exited ({status:?})")
|
format!("app shell exited ({status:?})")
|
||||||
}
|
}
|
||||||
_ = &mut abort_rx => "terminate requested".to_owned(),
|
requested = &mut abort_rx => match requested {
|
||||||
|
Ok(()) => session.close(session_id).await,
|
||||||
|
// The sender is dropped only when appd shuts down.
|
||||||
|
Err(_) => "appd is shutting down".to_owned(),
|
||||||
|
},
|
||||||
_ = session.relay.as_mut().expect("relay opened").ended() => {
|
_ = session.relay.as_mut().expect("relay opened").ended() => {
|
||||||
"component closed its IPC connection".to_owned()
|
"component closed its IPC connection".to_owned()
|
||||||
}
|
}
|
||||||
|
|
@ -457,6 +461,10 @@ pub(crate) async fn supervise(
|
||||||
session.settle(®istry, &reason).await
|
session.settle(®istry, &reason).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How long an application may take to close after being asked, for
|
||||||
|
/// example to save, before its processes are terminated.
|
||||||
|
pub(crate) const CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||||
|
|
||||||
/// Creates the session's Wayland connection and queues the compositor's end
|
/// Creates the session's Wayland connection and queues the compositor's end
|
||||||
/// for the compositor, returning the app shell's end.
|
/// for the compositor, returning the app shell's end.
|
||||||
fn attach_client(
|
fn attach_client(
|
||||||
|
|
@ -514,6 +522,33 @@ struct OwnedSession {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl OwnedSession {
|
impl OwnedSession {
|
||||||
|
/// Closes a running session as a user close would: the compositor asks
|
||||||
|
/// its windows to close and the app shell gets `CLOSE_TIMEOUT` to exit by
|
||||||
|
/// itself. Returns the terminal reason; settling terminates whatever is
|
||||||
|
/// still running.
|
||||||
|
async fn close(&mut self, session_id: u64) -> String {
|
||||||
|
let asked = self.client_attached
|
||||||
|
&& self.compositor_tx.as_ref().is_some_and(|tx| {
|
||||||
|
tx.is_connected()
|
||||||
|
&& tx
|
||||||
|
.try_send(AppdToCompositor::AppCloseRequest { session_id }.into())
|
||||||
|
.is_ok()
|
||||||
|
});
|
||||||
|
if !asked {
|
||||||
|
return "terminate requested; the compositor could not ask the app to close".to_owned();
|
||||||
|
}
|
||||||
|
let Some(app_shell) = self.app_shell.as_mut() else {
|
||||||
|
return "terminate requested".to_owned();
|
||||||
|
};
|
||||||
|
match tokio::time::timeout(CLOSE_TIMEOUT, app_shell.wait()).await {
|
||||||
|
Ok(status) => format!("closed on request; app shell exited ({status:?})"),
|
||||||
|
Err(_) => format!(
|
||||||
|
"close requested; the app shell did not exit within {} s and was terminated",
|
||||||
|
CLOSE_TIMEOUT.as_secs()
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn settle(self, registry: &Registry, reason: &str) -> anyhow::Result<()> {
|
async fn settle(self, registry: &Registry, reason: &str) -> anyhow::Result<()> {
|
||||||
let session_id = self.session_id;
|
let session_id = self.session_id;
|
||||||
tracing::info!(session_id, reason, "stopping session");
|
tracing::info!(session_id, reason, "stopping session");
|
||||||
|
|
|
||||||
|
|
@ -285,6 +285,10 @@ fn handle_message(state: &mut WeftCompositorState, msg: AppdToCompositor) {
|
||||||
.kill_client(client, DisconnectReason::ConnectionClosed);
|
.kill_client(client, DisconnectReason::ConnectionClosed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
AppdToCompositor::AppCloseRequest { session_id } => {
|
||||||
|
let closed = state.close_session_windows(session_id);
|
||||||
|
tracing::info!(session_id, windows = closed, "session asked to close");
|
||||||
|
}
|
||||||
AppdToCompositor::AppFocusRequest { session_id } => {
|
AppdToCompositor::AppFocusRequest { session_id } => {
|
||||||
if state.activate_session(session_id) {
|
if state.activate_session(session_id) {
|
||||||
tracing::info!(session_id, "session activated");
|
tracing::info!(session_id, "session activated");
|
||||||
|
|
|
||||||
|
|
@ -83,6 +83,20 @@ impl WeftCompositorState {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asks every window of `session_id` to close; returns how many.
|
||||||
|
pub fn close_session_windows(&mut self, session_id: u64) -> usize {
|
||||||
|
let mut closed = 0;
|
||||||
|
for window in self.space.elements() {
|
||||||
|
if window_session(window) == Some(session_id)
|
||||||
|
&& let Some(toplevel) = window.toplevel()
|
||||||
|
{
|
||||||
|
toplevel.send_close();
|
||||||
|
closed += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
closed
|
||||||
|
}
|
||||||
|
|
||||||
/// Activates the topmost window of `session_id`; returns whether the
|
/// Activates the topmost window of `session_id`; returns whether the
|
||||||
/// session has one.
|
/// session has one.
|
||||||
pub fn activate_session(&mut self, session_id: u64) -> bool {
|
pub fn activate_session(&mut self, session_id: u64) -> bool {
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,10 @@ pub enum AppdToCompositor {
|
||||||
AppFocusRequest {
|
AppFocusRequest {
|
||||||
session_id: u64,
|
session_id: u64,
|
||||||
},
|
},
|
||||||
|
/// Asks the session's windows to close, as a user close would.
|
||||||
|
AppCloseRequest {
|
||||||
|
session_id: u64,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Messages sent from weft-compositor to weft-appd.
|
/// Messages sent from weft-compositor to weft-appd.
|
||||||
|
|
|
||||||
|
|
@ -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). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. 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.
|
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. 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. `TERMINATE_APP` on a running session closes it as a user close would: appd replies `stopping`, asks the compositor to close the session's windows, and gives the app shell 5 seconds to exit by itself, for example after saving, before terminating it; the stop reason records which happened, and `stopped` is broadcast once the session has settled. A session still starting is stopped at once, and when appd itself shuts down its sessions are terminated without a close. 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
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -220,13 +220,17 @@ def run(args, desktop, xdotool):
|
||||||
if states[3] != states[1]:
|
if states[3] != states[1]:
|
||||||
raise AssertionError("count after ArrowDown does not match the count after one ArrowUp")
|
raise AssertionError("count after ArrowDown does not match the count after one ArrowUp")
|
||||||
|
|
||||||
# Ending the session closes its client in the compositor.
|
# Ending the session closes the app as a user close would: the
|
||||||
|
# compositor asks its window to close and the app shell exits by itself.
|
||||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||||
deadline = time.monotonic() + 15
|
deadline = time.monotonic() + 15
|
||||||
closed = f"closing the client of an ended session session_id={session_id}"
|
asked = f"session asked to close session_id={session_id} windows=1"
|
||||||
while closed not in desktop.log_text("compositor"):
|
closed = (f'stopping session session_id={session_id} reason="closed on request; '
|
||||||
|
'app shell exited (Ok(ExitStatus(unix_wait_status(0))))"')
|
||||||
|
while asked not in desktop.log_text("compositor") or closed not in desktop.log_text("appd"):
|
||||||
if time.monotonic() > deadline:
|
if time.monotonic() > deadline:
|
||||||
raise AssertionError(f"the compositor did not close the session's client: {closed!r}")
|
raise AssertionError("the session did not close on request; see compositor.log "
|
||||||
|
"and appd.log")
|
||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue