mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
Merge fix/session-owned-ipc-relay: make the IPC relay part of the session it serves (#14)
The session supervisor opens and owns each session's IPC relay; every exit path stops the relay task, removes its socket and unregisters its sender. A session ends when its IPC connection closes. IPC_FORWARD never waits on a component and reports an error for a missing relay or a full queue. appd's runtime directory is created mode 0700 and the relay socket 0600.
This commit is contained in:
commit
8214c12d7e
3 changed files with 342 additions and 55 deletions
|
|
@ -190,7 +190,7 @@ async fn run() -> anyhow::Result<()> {
|
||||||
let socket_path = appd_socket_path()?;
|
let socket_path = appd_socket_path()?;
|
||||||
|
|
||||||
if let Some(parent) = socket_path.parent() {
|
if let Some(parent) = socket_path.parent() {
|
||||||
std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
|
private_dir(parent).with_context(|| format!("create {}", parent.display()))?;
|
||||||
}
|
}
|
||||||
let _ = std::fs::remove_file(&socket_path);
|
let _ = std::fs::remove_file(&socket_path);
|
||||||
|
|
||||||
|
|
@ -366,7 +366,7 @@ fn system_token_path() -> std::io::Result<PathBuf> {
|
||||||
.map_err(|_| std::io::Error::other("XDG_RUNTIME_DIR not set"))?,
|
.map_err(|_| std::io::Error::other("XDG_RUNTIME_DIR not set"))?,
|
||||||
)
|
)
|
||||||
.join("weft");
|
.join("weft");
|
||||||
std::fs::create_dir_all(&dir)?;
|
private_dir(&dir)?;
|
||||||
Ok(dir.join("appd.systoken"))
|
Ok(dir.join("appd.systoken"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -375,7 +375,7 @@ fn write_ws_port(port: u16) -> anyhow::Result<()> {
|
||||||
let runtime_dir = std::env::var("XDG_RUNTIME_DIR").context("XDG_RUNTIME_DIR not set")?;
|
let runtime_dir = std::env::var("XDG_RUNTIME_DIR").context("XDG_RUNTIME_DIR not set")?;
|
||||||
let path = PathBuf::from(runtime_dir).join("weft/appd.wsport");
|
let path = PathBuf::from(runtime_dir).join("weft/appd.wsport");
|
||||||
if let Some(parent) = path.parent() {
|
if let Some(parent) = path.parent() {
|
||||||
std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
|
private_dir(parent).with_context(|| format!("create {}", parent.display()))?;
|
||||||
}
|
}
|
||||||
std::fs::write(&path, port.to_string()).with_context(|| format!("write {}", path.display()))?;
|
std::fs::write(&path, port.to_string()).with_context(|| format!("write {}", path.display()))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
@ -415,10 +415,27 @@ async fn handle_connection(
|
||||||
pub(crate) fn session_ipc_socket_path(session_id: u64) -> Option<PathBuf> {
|
pub(crate) fn session_ipc_socket_path(session_id: u64) -> Option<PathBuf> {
|
||||||
let runtime_dir = std::env::var("XDG_RUNTIME_DIR").ok()?;
|
let runtime_dir = std::env::var("XDG_RUNTIME_DIR").ok()?;
|
||||||
let dir = PathBuf::from(runtime_dir).join("weft");
|
let dir = PathBuf::from(runtime_dir).join("weft");
|
||||||
std::fs::create_dir_all(&dir).ok()?;
|
private_dir(&dir).ok()?;
|
||||||
Some(dir.join(format!("ipc-{session_id}.sock")))
|
Some(dir.join(format!("ipc-{session_id}.sock")))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates appd's runtime directory (`$XDG_RUNTIME_DIR/weft`) or another of
|
||||||
|
/// its directories, accessible to the user only whatever the umask, also
|
||||||
|
/// when it already existed.
|
||||||
|
pub(crate) fn private_dir(dir: &std::path::Path) -> std::io::Result<()> {
|
||||||
|
let mut builder = std::fs::DirBuilder::new();
|
||||||
|
builder.recursive(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||||
|
builder.create(dir)?;
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
||||||
match req {
|
match req {
|
||||||
Request::LaunchApp {
|
Request::LaunchApp {
|
||||||
|
|
@ -468,27 +485,11 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
||||||
});
|
});
|
||||||
return Response::LaunchAck { session_id, app_id };
|
return Response::LaunchAck { session_id, app_id };
|
||||||
}
|
}
|
||||||
let ipc_socket = session_ipc_socket_path(session_id);
|
|
||||||
let broadcast = registry.lock().await.broadcast().clone();
|
|
||||||
if let Some(ref sock_path) = ipc_socket
|
|
||||||
&& let Some(tx) =
|
|
||||||
runtime::spawn_ipc_relay(session_id, sock_path.clone(), broadcast).await
|
|
||||||
{
|
|
||||||
registry.lock().await.register_ipc_sender(session_id, tx);
|
|
||||||
}
|
|
||||||
let reg = Arc::clone(registry);
|
let reg = Arc::clone(registry);
|
||||||
let aid = app_id.clone();
|
let aid = app_id.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) = runtime::supervise(
|
if let Err(e) =
|
||||||
session_id,
|
runtime::supervise(session_id, &aid, grants, reg, abort_rx, compositor_tx).await
|
||||||
&aid,
|
|
||||||
grants,
|
|
||||||
reg,
|
|
||||||
abort_rx,
|
|
||||||
compositor_tx,
|
|
||||||
ipc_socket,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
{
|
||||||
tracing::warn!(session_id, error = %e, "runtime supervisor error");
|
tracing::warn!(session_id, error = %e, "runtime supervisor error");
|
||||||
}
|
}
|
||||||
|
|
@ -530,15 +531,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"),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
match tx.try_send(payload) {
|
||||||
|
Ok(()) => Response::AppState {
|
||||||
session_id,
|
session_id,
|
||||||
state: ipc::AppStateKind::Running,
|
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 {
|
||||||
|
|
@ -634,6 +651,31 @@ mod tests {
|
||||||
|
|
||||||
static ENV_LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
|
static ENV_LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
|
||||||
|
|
||||||
|
/// Points XDG_RUNTIME_DIR at a directory private to this test process,
|
||||||
|
/// since session sockets are named by session ID and every test registry
|
||||||
|
/// starts at 1. Directories of test processes that have ended are
|
||||||
|
/// removed. Callers hold env_lock.
|
||||||
|
fn use_test_runtime_dir() {
|
||||||
|
let base = std::env::temp_dir().join("weft-appd-tests");
|
||||||
|
if let Ok(entries) = std::fs::read_dir(&base) {
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let alive = entry
|
||||||
|
.file_name()
|
||||||
|
.to_str()
|
||||||
|
.and_then(|pid| pid.parse::<u32>().ok())
|
||||||
|
.is_some_and(|pid| std::path::Path::new(&format!("/proc/{pid}")).exists());
|
||||||
|
if !alive {
|
||||||
|
let _ = std::fs::remove_dir_all(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let dir = base.join(std::process::id().to_string());
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
// 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) };
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn env_lock() -> &'static tokio::sync::Mutex<()> {
|
pub(crate) fn env_lock() -> &'static tokio::sync::Mutex<()> {
|
||||||
ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
|
ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
|
||||||
}
|
}
|
||||||
|
|
@ -1003,6 +1045,187 @@ 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), ®istry).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), ®istry).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), ®istry),
|
||||||
|
)
|
||||||
|
.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();
|
||||||
|
// Both children report ready and keep running; the test plays the
|
||||||
|
// component, connecting to the session's IPC socket and closing it.
|
||||||
|
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 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", &child);
|
||||||
|
std::env::set_var("WEFT_APP_SHELL_BIN", &child);
|
||||||
|
std::env::set_var("WEFT_DISABLE_CGROUP", "1");
|
||||||
|
}
|
||||||
|
|
||||||
|
let registry = make_registry();
|
||||||
|
let mut rx = registry.lock().await.subscribe();
|
||||||
|
let session_id = registry.lock().await.launch("test.app");
|
||||||
|
let abort_rx = registry.lock().await.register_abort(session_id);
|
||||||
|
let socket = session_ipc_socket_path(session_id).unwrap();
|
||||||
|
let component = async {
|
||||||
|
// Connect once the session is running, then close the connection.
|
||||||
|
loop {
|
||||||
|
if let Ok(Response::AppReady { session_id: id, .. }) = rx.recv().await
|
||||||
|
&& id == session_id
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
drop(tokio::net::UnixStream::connect(&socket).await.unwrap());
|
||||||
|
};
|
||||||
|
let supervised = runtime::supervise(
|
||||||
|
session_id,
|
||||||
|
"test.app",
|
||||||
|
grants::SessionGrants::default(),
|
||||||
|
Arc::clone(®istry),
|
||||||
|
abort_rx,
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
let finished = tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||||
|
tokio::join!(supervised, component)
|
||||||
|
})
|
||||||
|
.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")]
|
||||||
|
async fn a_stopped_session_releases_its_ipc_relay() {
|
||||||
|
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_relay_{}", std::process::id()));
|
||||||
|
let app = dir.join("store/org.example.relay");
|
||||||
|
std::fs::create_dir_all(&app).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
app.join("wapp.toml"),
|
||||||
|
"[package]\nid = \"org.example.relay\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
// The runtime reports ready and exits without connecting to the relay.
|
||||||
|
let child = dir.join("child.sh");
|
||||||
|
std::fs::write(
|
||||||
|
&child,
|
||||||
|
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\nexec sleep 1\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 mut rx = registry.lock().await.subscribe();
|
||||||
|
let ack = dispatch(
|
||||||
|
Request::LaunchApp {
|
||||||
|
app_id: "org.example.relay".into(),
|
||||||
|
surface_id: 0,
|
||||||
|
},
|
||||||
|
®istry,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let Response::LaunchAck { session_id, .. } = ack else {
|
||||||
|
panic!("expected LaunchAck, got {ack:?}");
|
||||||
|
};
|
||||||
|
let stopped = tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||||
|
loop {
|
||||||
|
if let Ok(Response::AppState {
|
||||||
|
session_id: id,
|
||||||
|
state: AppStateKind::Stopped,
|
||||||
|
}) = rx.recv().await
|
||||||
|
&& id == session_id
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.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!(stopped.is_ok(), "session did not stop");
|
||||||
|
assert!(registry.lock().await.ipc_sender_for(session_id).is_none());
|
||||||
|
assert!(!session_ipc_socket_path(session_id).unwrap().exists());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test(flavor = "current_thread")]
|
#[tokio::test(flavor = "current_thread")]
|
||||||
async fn supervisor_transitions_through_ready_to_stopped() {
|
async fn supervisor_transitions_through_ready_to_stopped() {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
@ -1040,6 +1263,8 @@ mod tests {
|
||||||
let session_id = registry.lock().await.launch("test.app");
|
let session_id = registry.lock().await.launch("test.app");
|
||||||
let abort_rx = registry.lock().await.register_abort(session_id);
|
let abort_rx = registry.lock().await.register_abort(session_id);
|
||||||
|
|
||||||
|
use_test_runtime_dir();
|
||||||
|
|
||||||
runtime::supervise(
|
runtime::supervise(
|
||||||
session_id,
|
session_id,
|
||||||
"test.app",
|
"test.app",
|
||||||
|
|
@ -1047,7 +1272,6 @@ mod tests {
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
None,
|
None,
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
@ -1056,6 +1280,10 @@ mod tests {
|
||||||
registry.lock().await.state(session_id),
|
registry.lock().await.state(session_id),
|
||||||
AppStateKind::Stopped
|
AppStateKind::Stopped
|
||||||
));
|
));
|
||||||
|
// The session's IPC relay ends with it, although the test runtime
|
||||||
|
// never connected to it.
|
||||||
|
assert!(registry.lock().await.ipc_sender_for(session_id).is_none());
|
||||||
|
assert!(!session_ipc_socket_path(session_id).unwrap().exists());
|
||||||
|
|
||||||
let notification =
|
let notification =
|
||||||
tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await;
|
tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await;
|
||||||
|
|
@ -1110,6 +1338,8 @@ mod tests {
|
||||||
|
|
||||||
registry.lock().await.terminate(session_id);
|
registry.lock().await.terminate(session_id);
|
||||||
|
|
||||||
|
use_test_runtime_dir();
|
||||||
|
|
||||||
runtime::supervise(
|
runtime::supervise(
|
||||||
session_id,
|
session_id,
|
||||||
"test.abort.startup",
|
"test.abort.startup",
|
||||||
|
|
@ -1117,7 +1347,6 @@ mod tests {
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
None,
|
None,
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
@ -1159,6 +1388,8 @@ mod tests {
|
||||||
let session_id = registry.lock().await.launch("test.spawn.fail");
|
let session_id = registry.lock().await.launch("test.spawn.fail");
|
||||||
let abort_rx = registry.lock().await.register_abort(session_id);
|
let abort_rx = registry.lock().await.register_abort(session_id);
|
||||||
|
|
||||||
|
use_test_runtime_dir();
|
||||||
|
|
||||||
runtime::supervise(
|
runtime::supervise(
|
||||||
session_id,
|
session_id,
|
||||||
"test.spawn.fail",
|
"test.spawn.fail",
|
||||||
|
|
@ -1166,7 +1397,6 @@ mod tests {
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
None,
|
None,
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
@ -1316,6 +1546,7 @@ mod tests {
|
||||||
let session_id = registry.lock().await.launch("test.app");
|
let session_id = registry.lock().await.launch("test.app");
|
||||||
let abort_rx = registry.lock().await.register_abort(session_id);
|
let abort_rx = registry.lock().await.register_abort(session_id);
|
||||||
let started = std::time::Instant::now();
|
let started = std::time::Instant::now();
|
||||||
|
use_test_runtime_dir();
|
||||||
tokio::time::timeout(
|
tokio::time::timeout(
|
||||||
std::time::Duration::from_secs(20),
|
std::time::Duration::from_secs(20),
|
||||||
runtime::supervise(
|
runtime::supervise(
|
||||||
|
|
@ -1325,7 +1556,6 @@ mod tests {
|
||||||
Arc::clone(®istry),
|
Arc::clone(®istry),
|
||||||
abort_rx,
|
abort_rx,
|
||||||
None,
|
None,
|
||||||
None,
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
|
|
|
||||||
|
|
@ -8,21 +8,57 @@ use crate::Registry;
|
||||||
use crate::compositor_client::CompositorSender;
|
use crate::compositor_client::CompositorSender;
|
||||||
use crate::ipc::{AppStateKind, Response};
|
use crate::ipc::{AppStateKind, Response};
|
||||||
|
|
||||||
|
/// The per-session relay between the component's IPC socket and the app
|
||||||
|
/// bridge. It belongs to the session: closing it stops the relay task and
|
||||||
|
/// removes the socket, whether or not the component ever connected.
|
||||||
|
pub(crate) struct IpcRelay {
|
||||||
|
task: tokio::task::JoinHandle<()>,
|
||||||
|
socket_path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IpcRelay {
|
||||||
|
/// 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();
|
||||||
|
let _ = std::fs::remove_file(&self.socket_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Listens on `socket_path` for the session's component and relays
|
||||||
|
/// newline-delimited messages between it and the returned sender (towards
|
||||||
|
/// the component) and the broadcast channel (from the component).
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
pub(crate) async fn spawn_ipc_relay(
|
pub(crate) fn spawn_ipc_relay(
|
||||||
session_id: u64,
|
session_id: u64,
|
||||||
socket_path: PathBuf,
|
socket_path: PathBuf,
|
||||||
broadcast: tokio::sync::broadcast::Sender<Response>,
|
broadcast: tokio::sync::broadcast::Sender<Response>,
|
||||||
) -> Option<tokio::sync::mpsc::Sender<String>> {
|
) -> 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).ok()?;
|
let listener = tokio::net::UnixListener::bind(&socket_path)?;
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
if let Err(e) =
|
||||||
|
std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600))
|
||||||
|
{
|
||||||
|
let _ = std::fs::remove_file(&socket_path);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
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);
|
||||||
tokio::spawn(async move {
|
let task = tokio::spawn(async move {
|
||||||
let Ok((stream, _)) = listener.accept().await else {
|
let Ok((stream, _)) = listener.accept().await else {
|
||||||
tracing::warn!(session_id, "IPC relay: failed to accept connection");
|
tracing::warn!(session_id, "IPC relay: failed to accept connection");
|
||||||
let _ = std::fs::remove_file(&socket_path);
|
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
// One component per session: no further connections are accepted.
|
||||||
|
drop(listener);
|
||||||
tracing::debug!(session_id, "IPC relay: component connected");
|
tracing::debug!(session_id, "IPC relay: component connected");
|
||||||
let (reader, writer) = tokio::io::split(stream);
|
let (reader, writer) = tokio::io::split(stream);
|
||||||
let mut reader = BufReader::new(reader);
|
let mut reader = BufReader::new(reader);
|
||||||
|
|
@ -55,18 +91,17 @@ pub(crate) async fn spawn_ipc_relay(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let _ = std::fs::remove_file(&socket_path);
|
|
||||||
});
|
});
|
||||||
Some(html_to_wasm_tx)
|
Ok((html_to_wasm_tx, IpcRelay { task, socket_path }))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(unix))]
|
#[cfg(not(unix))]
|
||||||
pub(crate) async fn spawn_ipc_relay(
|
pub(crate) fn spawn_ipc_relay(
|
||||||
_session_id: u64,
|
_session_id: u64,
|
||||||
_socket_path: PathBuf,
|
_socket_path: PathBuf,
|
||||||
_broadcast: tokio::sync::broadcast::Sender<Response>,
|
_broadcast: tokio::sync::broadcast::Sender<Response>,
|
||||||
) -> Option<tokio::sync::mpsc::Sender<String>> {
|
) -> std::io::Result<(tokio::sync::mpsc::Sender<String>, IpcRelay)> {
|
||||||
None
|
Err(std::io::ErrorKind::Unsupported.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
const READY_TIMEOUT: Duration = Duration::from_secs(30);
|
const READY_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
|
|
@ -177,7 +212,7 @@ fn spawn_app_shell(
|
||||||
fn portal_socket_path(session_id: u64) -> Option<PathBuf> {
|
fn portal_socket_path(session_id: u64) -> Option<PathBuf> {
|
||||||
let runtime_dir = std::env::var("XDG_RUNTIME_DIR").ok()?;
|
let runtime_dir = std::env::var("XDG_RUNTIME_DIR").ok()?;
|
||||||
let dir = PathBuf::from(runtime_dir).join("weft");
|
let dir = PathBuf::from(runtime_dir).join("weft");
|
||||||
std::fs::create_dir_all(&dir).ok()?;
|
crate::private_dir(&dir).ok()?;
|
||||||
Some(dir.join(format!("portal-{session_id}.sock")))
|
Some(dir.join(format!("portal-{session_id}.sock")))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -211,7 +246,6 @@ pub(crate) async fn supervise(
|
||||||
registry: Registry,
|
registry: Registry,
|
||||||
abort_rx: tokio::sync::oneshot::Receiver<()>,
|
abort_rx: tokio::sync::oneshot::Receiver<()>,
|
||||||
compositor_tx: Option<CompositorSender>,
|
compositor_tx: Option<CompositorSender>,
|
||||||
ipc_socket_path: Option<std::path::PathBuf>,
|
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let mut abort_rx = abort_rx;
|
let mut abort_rx = abort_rx;
|
||||||
let bin = match std::env::var("WEFT_RUNTIME_BIN") {
|
let bin = match std::env::var("WEFT_RUNTIME_BIN") {
|
||||||
|
|
@ -234,6 +268,22 @@ pub(crate) async fn supervise(
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let Some(ipc_socket_path) = crate::session_ipc_socket_path(session_id) else {
|
||||||
|
tracing::warn!(session_id, %app_id, "no runtime directory for the IPC socket");
|
||||||
|
return stop_unstarted(®istry, session_id).await;
|
||||||
|
};
|
||||||
|
let broadcast = registry.lock().await.broadcast().clone();
|
||||||
|
let relay = match spawn_ipc_relay(session_id, ipc_socket_path.clone(), broadcast) {
|
||||||
|
Ok((tx, relay)) => {
|
||||||
|
registry.lock().await.register_ipc_sender(session_id, tx);
|
||||||
|
relay
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(session_id, %app_id, error = %e, "cannot open the IPC socket");
|
||||||
|
return stop_unstarted(®istry, session_id).await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let (mount_orch, store_override) =
|
let (mount_orch, store_override) =
|
||||||
crate::mount::MountOrchestrator::mount_if_needed(app_id, session_id);
|
crate::mount::MountOrchestrator::mount_if_needed(app_id, session_id);
|
||||||
|
|
||||||
|
|
@ -254,9 +304,7 @@ pub(crate) async fn supervise(
|
||||||
.env(READY_TOKEN_ENV, &token)
|
.env(READY_TOKEN_ENV, &token)
|
||||||
.kill_on_drop(true);
|
.kill_on_drop(true);
|
||||||
|
|
||||||
if let Some(ref sock) = ipc_socket_path {
|
cmd.arg("--ipc-socket").arg(&ipc_socket_path);
|
||||||
cmd.arg("--ipc-socket").arg(sock);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(ref root) = store_override {
|
if let Some(ref root) = store_override {
|
||||||
cmd.env("WEFT_APP_STORE", root);
|
cmd.env("WEFT_APP_STORE", root);
|
||||||
|
|
@ -278,6 +326,7 @@ pub(crate) async fn supervise(
|
||||||
runtime: None,
|
runtime: None,
|
||||||
app_shell: None,
|
app_shell: None,
|
||||||
portal,
|
portal,
|
||||||
|
relay: Some(relay),
|
||||||
mount: mount_orch,
|
mount: mount_orch,
|
||||||
compositor_tx,
|
compositor_tx,
|
||||||
surface_announced: false,
|
surface_announced: false,
|
||||||
|
|
@ -353,6 +402,9 @@ pub(crate) async fn supervise(
|
||||||
status = session.runtime.as_mut().expect("runtime spawned").wait() => {
|
status = session.runtime.as_mut().expect("runtime spawned").wait() => {
|
||||||
Err(format!("runtime exited before the app shell was ready ({status:?})"))
|
Err(format!("runtime exited before the app shell was ready ({status:?})"))
|
||||||
}
|
}
|
||||||
|
_ = session.relay.as_mut().expect("relay opened").ended() => {
|
||||||
|
Err("component closed its IPC connection before the session was ready".to_owned())
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let shell_stdout = match shell_stdout {
|
let shell_stdout = match shell_stdout {
|
||||||
Ok(reader) => reader,
|
Ok(reader) => reader,
|
||||||
|
|
@ -378,6 +430,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(®istry, &reason).await
|
session.settle(®istry, &reason).await
|
||||||
}
|
}
|
||||||
|
|
@ -394,15 +449,15 @@ async fn stop_unstarted(registry: &Registry, session_id: u64) -> anyhow::Result<
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The processes, portal, compositor association and image mount a session
|
/// The processes, IPC relay, portal, compositor association and image mount
|
||||||
/// owns. `settle` releases all of them on every exit path: spawn failure,
|
/// a session owns. `settle` releases all of them on every exit path: spawn
|
||||||
/// readiness failure, timeout, abort and child exit. The IPC relay is not yet
|
/// failure, readiness failure, timeout, abort and child exit.
|
||||||
/// owned here.
|
|
||||||
struct OwnedSession {
|
struct OwnedSession {
|
||||||
session_id: u64,
|
session_id: u64,
|
||||||
runtime: Option<tokio::process::Child>,
|
runtime: Option<tokio::process::Child>,
|
||||||
app_shell: Option<tokio::process::Child>,
|
app_shell: Option<tokio::process::Child>,
|
||||||
portal: Option<(PathBuf, tokio::process::Child)>,
|
portal: Option<(PathBuf, tokio::process::Child)>,
|
||||||
|
relay: Option<IpcRelay>,
|
||||||
mount: crate::mount::MountOrchestrator,
|
mount: crate::mount::MountOrchestrator,
|
||||||
compositor_tx: Option<CompositorSender>,
|
compositor_tx: Option<CompositorSender>,
|
||||||
surface_announced: bool,
|
surface_announced: bool,
|
||||||
|
|
@ -427,7 +482,9 @@ impl OwnedSession {
|
||||||
}
|
}
|
||||||
self.mount.umount();
|
self.mount.umount();
|
||||||
kill_portal(self.portal).await;
|
kill_portal(self.portal).await;
|
||||||
|
drop(self.relay);
|
||||||
let mut reg = registry.lock().await;
|
let mut reg = registry.lock().await;
|
||||||
|
reg.remove_ipc_sender(session_id);
|
||||||
reg.set_state(session_id, AppStateKind::Stopped);
|
reg.set_state(session_id, AppStateKind::Stopped);
|
||||||
reg.remove_abort_sender(session_id);
|
reg.remove_abort_sender(session_id);
|
||||||
let _ = reg.broadcast().send(Response::AppState {
|
let _ = reg.broadcast().send(Response::AppState {
|
||||||
|
|
|
||||||
|
|
@ -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 file portal, the compositor association and any image mount are released. Manages the per-session IPC relay and 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
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue