From c1cb66d7d2644bacecc8a7551cb4444b5da695e1 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 22 Nov 2026 11:39:02 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(remote):=20=E9=87=8D=E8=BF=9E=E7=BB=AD?= =?UTF-8?q?=E4=BC=A0=E5=90=8E=E5=81=9C=E6=94=BE=E6=97=A7=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E7=9A=84=E8=BF=9B=E7=A8=8B=E4=BA=8B=E4=BB=B6=EF=BC=8Cremote.at?= =?UTF-8?q?tachProcess=20=E6=8E=A5=E5=9B=9E=E8=BF=90=E8=A1=8C=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=20(Refs=201lck/Lithe-IDEA#2231)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 客户端:连接可延后续传;park("process") 让上一个连接建立的进程(id 小于 hello 的 nextResourceId)的事件先停放,attach 时一次交出;每个进程最多 4 MiB、合计 16 MiB,超出时先丢最早的输出,退出事件不丢;连接关闭时还有 停放事件则记为已丢弃。attach 区分“已有请求在接收”和“没有可接回的事件”。 - workspace:连接常驻会话时延后续传、停放进程事件,从本进程记住的上一个 连接最后收到的事件 seq 续传(最多记 32 个会话,只存会话键和序号);记下 这次续传是否完整。 - 新命令 remote.attachProcess { sessionId, processId }:先发 process.attached { processId, truncated },再转发断线期间和之后的 process.output / process.exit,直到进程结束;请求拥有该进程,取消即结束。 新错误码 remote_process_gone、remote_process_attached。 - 顺手补齐 preferences.rs、programs.rs 缺的字段文档(注释检查原本不过)。 --- rust/contracts/application-boundary.md | 4 + rust/contracts/rust-core-api.md | 27 ++ rust/crates/core/src/protocol/command.rs | 5 + .../core/src/runtime/dispatcher/remote.rs | 12 + rust/crates/core/src/tests/mod.rs | 2 + rust/crates/core/src/tests/remote_attach.rs | 239 ++++++++++ rust/crates/protocol/src/error.rs | 8 + rust/crates/remote/src/client/mod.rs | 4 +- rust/crates/remote/src/client/preferences.rs | 5 + rust/crates/remote/src/client/routes.rs | 414 ++++++++++++++++++ rust/crates/remote/src/client/session.rs | 170 +++---- rust/crates/remote/tests/persistence.rs | 146 ++++++ rust/crates/workspace/src/host.rs | 126 +++++- rust/crates/workspace/src/lib.rs | 1 + rust/crates/workspace/src/programs.rs | 3 + rust/crates/workspace/src/resumption.rs | 118 +++++ rust/crates/workspace/src/sessions.rs | 57 ++- rust/crates/workspace/src/test_support.rs | 9 +- 18 files changed, 1230 insertions(+), 120 deletions(-) create mode 100644 rust/crates/core/src/tests/remote_attach.rs create mode 100644 rust/crates/remote/src/client/routes.rs create mode 100644 rust/crates/workspace/src/resumption.rs diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index df79b32e..c64cba64 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -418,6 +418,10 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported: be read or is not the build its SHA-256 names - `devcontainer_untrusted_folder`: the folder is not trusted, so its dev container was not built or started +- `remote_process_gone`: the remote process to attach to no longer runs and + its output is gone, or the reconnection started a new host session +- `remote_process_attached`: another request already receives the output of + the remote process to attach to - `unknown` GitHub authorization is independent of a Lithe account. Device Flow is the diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 1b56a893..b28ab211 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -810,6 +810,7 @@ or removing a command fails until the table changes in the same commit. | `remote.writeFile` | Save a file over an open remote connection | | `remote.hostRequest` | Perform a non-streaming operation on an existing workspace host | | `remote.runProcess` | Own a remote process and relays output until it exits or is cancelled | +| `remote.attachProcess` | Take over a process an earlier connection to the resumed host session started, relaying its missed and live output until it exits or is cancelled | | `remote.captureProcess` | Capture a short remote process with explicit time and output budgets | | `remote.runTerminal` | Own a remote PTY and relays output until it exits or is cancelled | | `remote.runWatch` | Own a host watch and relays changes until cancellation or root removal | @@ -6232,6 +6233,7 @@ gone. Requests over it take `sessionId`: | `remote.uploadFile` | `{ sessionId, sourcePath, path, sha256, mode }` | verified `{ size, sha256 }` | | `remote.runWatch` | `{ sessionId, params: { root, excludeNames? } }` | waits until root removal or cancellation; relays `watch.started`, `watch.changed`, `watch.error` | | `remote.runProcess` | `{ sessionId, params: { argv, cwd?, environment?, env?, pipeStdin?, label? } }` | leader exit; relays `process.started`, `process.output`, `process.exit` | +| `remote.attachProcess` | `{ sessionId, processId }` | leader exit; relays `process.attached` (`{ processId, truncated }`), `process.output`, `process.exit` | | `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, env?, columns, rows, label? } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` | | `remote.captureProcess` | `{ sessionId, params, timeoutMilliseconds, maxOutputBytes }` | base64 `stdout`, `stderr`, nullable `exitCode` and `signal` | | `remote.runningPrograms` | `{ sessionId }` | `{ programs: [{ kind, id, argv, label, runningMs }] }`, processes first; `kind` is `process` or `terminal`, `label` the one the program started with or `null` | @@ -6259,6 +6261,31 @@ published yet, the host records teardown against the pending resource ID and the creating worker cleans it after publication. A rejected or timed-out close worker cannot turn an already accepted cancellation into an orphaned resource. +`remote.connect` that resumes a persistent session (`resumed: true`) asks +the host once for the events after the last one this Core received over the +session, then keeps the output and exit of every process an earlier +connection started until a caller attaches to it. `remote.attachProcess` +takes those events, then relays the live ones; the request owns the process +from then on exactly like the `remote.runProcess` that started it, so +cancelling it ends the process. A run window that showed the process before +the connection dropped attaches with the `processId` from its +`process.started`; a kept program listed in `keptPrograms` or by +`remote.runningPrograms` attaches with its `id`. `process.attached` comes +first, and `truncated: true` means output between what the caller already +showed and the first relayed event may be missing: this Core was restarted +since, the host dropped events past its retention limit, or more than 4 MiB +of one process's output (16 MiB together) waited for an attach, in which +case the oldest output went first. Exit events are never dropped. A process +that exited while the connection was down ends the request at once with its +replayed output and exit. + +`remote.attachProcess` fails with `remote_process_gone` when the connection +did not resume a session, the process ended before the events this Core +received, or an earlier attach of it already ended; with +`remote_process_attached` when another request receives it, the +`remote.runProcess` that started it or an earlier `remote.attachProcess`. +Neither changes the process. Terminals and watches are not reattached. + Watch startup emits `watch.started` before buffered changes. The caller rescans on startup, `overflow`, or watch error; `ROOT_REMOVED` ends the call. Watch paths remain absolute host paths until the native adapter maps the owning workspace diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 80bd271e..34a8611e 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -995,6 +995,10 @@ pub enum RemoteCommand { HostRequest, /// Owns a remote process and relays output until it exits or is cancelled. RunProcess, + /// Takes over a process an earlier connection to the resumed host session + /// started and relays its output until it exits or is cancelled + /// (`remote.attachProcess`). + AttachProcess, /// Captures a short remote process with explicit time and output budgets. CaptureProcess, /// Owns a remote PTY and relays output until it exits or is cancelled. @@ -1635,6 +1639,7 @@ impl CoreCommand { "remote.writeFile" => Some(Self::Remote(RemoteCommand::WriteFile)), "remote.hostRequest" => Some(Self::Remote(RemoteCommand::HostRequest)), "remote.runProcess" => Some(Self::Remote(RemoteCommand::RunProcess)), + "remote.attachProcess" => Some(Self::Remote(RemoteCommand::AttachProcess)), "remote.captureProcess" => Some(Self::Remote(RemoteCommand::CaptureProcess)), "remote.runTerminal" => Some(Self::Remote(RemoteCommand::RunTerminal)), "remote.runWatch" => Some(Self::Remote(RemoteCommand::RunWatch)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index 42287f00..503bd625 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -93,6 +93,18 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu Err(error) => CoreResponse::failure(id, error), } } + RemoteCommand::AttachProcess => { + match serde_json::from_value(payload) + .map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid process attach request") + .with_details(error.to_string()) + }) + .and_then(lithe_workspace::host::attach_process) + { + Ok(value) => CoreResponse::success(id, value), + Err(error) => CoreResponse::failure(id, error), + } + } RemoteCommand::HostRequest | RemoteCommand::RunProcess | RemoteCommand::RunWatch diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index c1e02407..bfabf10b 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -64,6 +64,8 @@ mod protocol; mod published_build_plugins; mod rank_names; #[cfg(unix)] +mod remote_attach; +#[cfg(unix)] mod remote_sessions; mod request_events; mod row_selection; diff --git a/rust/crates/core/src/tests/remote_attach.rs b/rust/crates/core/src/tests/remote_attach.rs new file mode 100644 index 00000000..f2be3484 --- /dev/null +++ b/rust/crates/core/src/tests/remote_attach.rs @@ -0,0 +1,239 @@ +//! `remote.attachProcess` over a resumed persistent session: a scripted host +//! replays what its processes did while nobody was connected. + +use lithe_remote::client::session::{ConnectOptions, ResumeMode}; +use lithe_remote::client::RemoteSession; +use lithe_remote::protocol::frame::{read_frame, write_frame}; +use lithe_remote::protocol::{methods, Message, PREAMBLE}; +use lithe_workspace::sessions::History; +use lithe_workspace::test_support; +use serde_json::{json, Value}; +use std::io::Write; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; +use std::sync::{mpsc, Arc, Mutex}; +use std::time::Duration; + +const STEP: Duration = Duration::from_secs(10); + +/// Process 3 exited while the connection was down, 5 runs quietly and 6 +/// ended before the events this Core received. +fn scripted_host(mut server: UnixStream, done: mpsc::Sender<()>) { + let send = |server: &mut UnixStream, message: Message| { + write_frame(server, &serde_json::to_vec(&message).unwrap()).unwrap(); + server.flush().unwrap(); + }; + let event = |event: &str, params: Value, seq: u64| Message::Event { + event: event.into(), + params, + seq: Some(seq), + }; + let mut states = 0; + server.write_all(PREAMBLE).unwrap(); + while let Ok(Some(frame)) = read_frame(&mut server) { + let Message::Request { id, method, params } = serde_json::from_slice(&frame).unwrap() + else { + continue; + }; + let result = match method.as_str() { + methods::SERVER_HELLO => json!({ + "protocolVersion": 1, "serverVersion": "test", + "host": {"os": "linux", "arch": "x86_64", "hostName": "build.example", + "userName": "dev", "homeDirectory": "/home/dev", "defaultShell": "/bin/sh", + "pathSeparator": "/", "process": {"orphanProtection": "parentDeathSignal"}, + "watch": {"backend": "inotify", "directoryLimit": 128}, "features": []}, + "session": {"persistent": true, "resumed": true, "nextResourceId": 7, "lastEventSeq": 6} + }), + methods::SERVER_RESUME => { + assert_eq!(params["afterSeq"], 4); + let data = methods::encode_bytes(b"while away\n"); + send( + &mut server, + event( + methods::EVENT_PROCESS_OUTPUT, + json!({"processId": 3, "stream": "stdout", "data": data}), + 5, + ), + ); + send( + &mut server, + event( + methods::EVENT_PROCESS_EXIT, + json!({"processId": 3, "exitCode": 0, "signal": null}), + 6, + ), + ); + json!({"truncated": false}) + } + methods::SERVER_STATE => { + states += 1; + let processes = if states == 1 { + json!([{"processId": 5, "pid": 55, "argv": ["build"], "runningMs": 9, + "leaderExited": false}]) + } else { + json!([]) + }; + send( + &mut server, + Message::success( + id, + json!({"processes": processes, "terminals": [], "watches": []}), + ), + ); + if states == 1 { + // The quiet process speaks and exits only after the attach + // checked that it still runs. + let data = methods::encode_bytes(b"live\n"); + send( + &mut server, + event( + methods::EVENT_PROCESS_OUTPUT, + json!({"processId": 5, "stream": "stdout", "data": data}), + 7, + ), + ); + send( + &mut server, + event( + methods::EVENT_PROCESS_EXIT, + json!({"processId": 5, "exitCode": 2, "signal": null}), + 8, + ), + ); + } + continue; + } + // The attach owns the process: its end releases it as a run does. + methods::PROCESS_KILL => Value::Null, + methods::SERVER_SHUTDOWN => { + send(&mut server, Message::success(id, Value::Null)); + break; + } + other => panic!("unexpected method {other}"), + }; + send(&mut server, Message::success(id, result)); + } + let _ = done.send(()); +} + +/// Runs `remote.attachProcess` and returns its response with the remote +/// events it relayed. +fn attach(session_id: &str, process_id: u64) -> (Value, Vec) { + let relayed = Arc::new(Mutex::new(Vec::new())); + let records = Arc::clone(&relayed); + let response = crate::execute_json_with_events( + &json!({"id": test_support::unique_id(), "command": "remote.attachProcess", + "timeoutMilliseconds": 30_000, + "payload": {"sessionId": session_id, "processId": process_id}}) + .to_string(), + Arc::new(move |raw: &str| { + let event: Value = serde_json::from_str(raw).unwrap(); + if event["type"] == "remote" { + records.lock().unwrap().push(event); + } + }), + ); + let events = relayed.lock().unwrap().clone(); + (serde_json::from_str(&response).unwrap(), events) +} + +fn output(event: &Value) -> Vec { + methods::decode_bytes(event["params"]["data"].as_str().unwrap()).unwrap() +} + +#[test] +fn attaching_after_a_reconnection_relays_what_each_process_did_meanwhile() { + let (client, server) = UnixStream::pair().unwrap(); + server.set_read_timeout(Some(STEP)).unwrap(); + server.set_write_timeout(Some(STEP)).unwrap(); + let socket = client.try_clone().unwrap(); + let (done, finished) = mpsc::channel(); + let host = std::thread::spawn(move || scripted_host(server, done)); + let (session, events) = RemoteSession::from_streams( + client.try_clone().unwrap(), + client, + &ConnectOptions { + handshake_timeout: STEP, + resume: ResumeMode::Deferred, + ..ConnectOptions::default() + }, + ) + .unwrap(); + session.park("process"); + drop(events); + assert!(!session.resume(Some(4)).unwrap().truncated); + let id = test_support::register_in_process_with( + session, + History { + resumed: true, + complete: true, + }, + ); + + // Exited meanwhile: its output and exit, then the request ends. + let (response, relayed) = attach(&id, 3); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(response["data"]["exitCode"], 0, "{response}"); + let names: Vec<_> = relayed.iter().map(|event| &event["event"]).collect(); + assert_eq!( + names, + ["process.attached", "process.output", "process.exit"], + "{relayed:?}" + ); + assert_eq!( + relayed[0]["params"], + json!({"processId": 3, "truncated": false}) + ); + assert_eq!(output(&relayed[1]), b"while away\n"); + + // Its attach ended, so nothing keeps its events any more. + let (again, _) = attach(&id, 3); + assert_eq!(again["error"]["code"], "remote_process_gone", "{again}"); + + // Quiet since the reconnection: the host confirms it runs, then its + // live output follows. + let (response, relayed) = attach(&id, 5); + assert_eq!(response["data"]["exitCode"], 2, "{response}"); + assert_eq!(relayed.len(), 3, "{relayed:?}"); + assert_eq!(relayed[0]["event"], "process.attached"); + assert_eq!(output(&relayed[1]), b"live\n"); + + // Ended before what this Core received, and created by this connection. + for process_id in [6, 7] { + let (gone, relayed) = attach(&id, process_id); + assert_eq!(gone["error"]["code"], "remote_process_gone", "{gone}"); + assert!(relayed.is_empty(), "{relayed:?}"); + } + + test_support::unregister(&id); + let (unknown, _) = attach(&id, 5); + assert_eq!(unknown["error"]["code"], "connection_closed", "{unknown}"); + finished.recv_timeout(STEP).expect("the host finished"); + let _ = socket.shutdown(Shutdown::Both); + host.join().unwrap(); +} + +#[test] +fn a_connection_that_resumed_nothing_has_no_process_to_attach_to() { + let (client, server) = UnixStream::pair().unwrap(); + server.set_read_timeout(Some(STEP)).unwrap(); + server.set_write_timeout(Some(STEP)).unwrap(); + let worker = std::thread::spawn(move || { + let _ = lithe_remote::server::serve_stdio(server.try_clone().unwrap(), server); + }); + let (session, events) = RemoteSession::from_streams( + client.try_clone().unwrap(), + client, + &ConnectOptions { + handshake_timeout: STEP, + ..ConnectOptions::default() + }, + ) + .unwrap(); + drop(events); + let id = test_support::register_in_process(session); + let (gone, _) = attach(&id, 1); + assert_eq!(gone["error"]["code"], "remote_process_gone", "{gone}"); + test_support::unregister(&id); + worker.join().unwrap(); +} diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index 05cf8f1d..4f8c0e0b 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -104,6 +104,14 @@ pub enum ErrorCode { /// started: building runs the folder's code on this machine. Trusting the /// folder and repeating the request builds it. DevcontainerUntrustedFolder, + /// `remote.attachProcess` names a process the host session no longer + /// runs and whose events are gone, or the connection did not resume the + /// session that started it. Nothing was attached; its output ends here. + RemoteProcessGone, + /// `remote.attachProcess` names a process whose events another request + /// already receives: the `remote.runProcess` that started it on this + /// connection, or an earlier `remote.attachProcess`. Nothing changed. + RemoteProcessAttached, /// A failure does not fit a more stable cross-platform category. Unknown, } diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index da3bb9a1..22606796 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -17,7 +17,8 @@ //! so a host that asks for a password asks only once. The host itself //! verifies the installed binary and its directories. //! - [`session`] starts the server, exchanges protocol messages with it and -//! routes each resource's events to its subscriber. +//! routes each resource's events to its subscriber, or keeps them for a +//! reconnecting client until it attaches to the resource. //! - [`api`] offers typed operations and resource handles on a session. //! - [`forward`] forwards local ports through tunnels. //! - [`host_forward`] makes the host listen: relaying to another server, or @@ -65,6 +66,7 @@ pub mod motty; pub mod port_records; pub mod preferences; pub mod prompt; +mod routes; pub mod session; pub mod ssh_config; pub mod transport; diff --git a/rust/crates/remote/src/client/preferences.rs b/rust/crates/remote/src/client/preferences.rs index a6df648c..15f1366f 100644 --- a/rust/crates/remote/src/client/preferences.rs +++ b/rust/crates/remote/src/client/preferences.rs @@ -183,10 +183,12 @@ pub enum ProgramStatus { #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct SshProgram { + /// Whether the document sets the value or Lithe picks it. pub source: Source, /// The setting, or the first `ssh` on `PATH`; `None` when automatic /// finds none. pub path: Option, + /// What is at that path when the page reads it. pub status: ProgramStatus, } @@ -202,6 +204,7 @@ impl SshProgram { #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ReverseForwarding { + /// Whether the document sets the value or Lithe picks it. pub source: Source, /// The value that takes effect. pub allowed: bool, @@ -211,6 +214,7 @@ pub struct ReverseForwarding { #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Closing { + /// Whether the document sets the value or Lithe picks it. pub source: Source, /// The choice that takes effect. pub programs: ClosePrograms, @@ -224,6 +228,7 @@ pub struct Closing { #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Reconnect { + /// Whether the document sets the value or Lithe picks it. pub source: Source, /// The limit that takes effect; 0 turns automatic reconnection off. pub limit_seconds: u32, diff --git a/rust/crates/remote/src/client/routes.rs b/rust/crates/remote/src/client/routes.rs new file mode 100644 index 00000000..b7d36668 --- /dev/null +++ b/rust/crates/remote/src/client/routes.rs @@ -0,0 +1,414 @@ +//! Where the session's reader delivers each event. +//! +//! An event of a resource goes to the resource's subscriber. Without one, it +//! goes to the session's general event channel, unless an earlier connection +//! to the same persistent session created the resource and its family is +//! parked: then the event waits here until a caller attaches to the resource. +//! A reconnecting client resumes the event stream once and attaches to each +//! resource it still shows afterwards, so the events replayed for a running +//! process and its live output reach one owner without a gap or a repeat. +//! Parking and attaching share the reader's lock, so each event is either +//! among the parked ones an attach takes or in its subscription. +//! +//! Parked output is bounded per resource and in total. The oldest output goes +//! first, and the attach reports the loss. Other events, such as an exit, are +//! small and never dropped. + +use super::session::{lock, Event}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::mpsc::{self, Receiver, SyncSender}; +use std::sync::Mutex; + +/// Parked bytes of one resource before its oldest output is dropped. +const RESOURCE_LIMIT_BYTES: usize = 4 * 1024 * 1024; + +/// Parked bytes of every resource together before output is dropped. +const TOTAL_LIMIT_BYTES: usize = 16 * 1024 * 1024; + +pub(crate) type Routes = Mutex; + +/// A resource: its family and id. +type Key = (String, u64); + +/// Subscriptions, and the events parked for resources nobody receives yet. +#[derive(Default)] +pub(crate) struct RouteTable { + subscribers: HashMap>, + /// Families whose resources from earlier connections are parked. + families: HashSet, + /// Resource ids below this were created by earlier connections. + parking_below: u64, + parked: HashMap, + parked_bytes: usize, + /// Resources an attach took; their later events are never parked again. + attached: HashSet, + /// Set once the stream ended. + closed: bool, +} + +/// The events of one resource, oldest first, with their sizes on the wire. +#[derive(Default)] +struct Parked { + events: VecDeque<(Event, usize)>, + bytes: usize, + /// Whether output was dropped to stay within the limits. + lost: bool, +} + +/// The events of a resource that an earlier connection created, from the +/// moment this connection resumed the event stream. +#[derive(Debug)] +pub struct Attachment { + /// Events that arrived before the attach, oldest first. + pub missed: Vec, + /// Whether output among `missed` was dropped to stay within the parking + /// limits. + pub lost: bool, + /// Later events, like a subscription's. Dropping the receiver ends it. + pub events: Receiver, +} + +/// Why an attach took nothing. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AttachRefusal { + /// Another caller receives the resource's events: the subscriber that + /// created it on this connection, or an earlier attach. + Owned, + /// Nothing keeps the resource's events for an attach: its family is not + /// parked, this connection created it and nobody receives it any more, + /// or an earlier attach took its events and stopped receiving. + Unavailable, +} + +impl RouteTable { + pub(crate) fn subscribe(&mut self, family: &str, id: u64, capacity: usize) -> Receiver { + let (sender, receiver) = mpsc::sync_channel(capacity); + // A closed stream drops the sender: the receiver reports at once that + // nothing will arrive. + if !self.closed { + self.subscribers.insert((family.to_owned(), id), sender); + } + receiver + } + + pub(crate) fn unsubscribe(&mut self, family: &str, id: u64) { + self.subscribers.remove(&(family.to_owned(), id)); + } + + /// Parks the events of `family` resources with ids below `below`. + pub(crate) fn park(&mut self, family: &str, below: u64) { + self.families.insert(family.to_owned()); + self.parking_below = below; + } + + /// Takes the parked events of a resource and subscribes to its later ones. + pub(crate) fn attach( + &mut self, + family: &str, + id: u64, + capacity: usize, + ) -> Result { + let key = (family.to_owned(), id); + if self.subscribers.contains_key(&key) { + return Err(AttachRefusal::Owned); + } + if !self.families.contains(family) + || id >= self.parking_below + || self.attached.contains(&key) + { + return Err(AttachRefusal::Unavailable); + } + let parked = self.parked.remove(&key).unwrap_or_default(); + self.parked_bytes -= parked.bytes; + let events = self.subscribe(family, id, capacity); + self.attached.insert(key); + Ok(Attachment { + missed: parked.events.into_iter().map(|(event, _)| event).collect(), + lost: parked.lost, + events, + }) + } + + /// Ends every subscription, which tells their consumers that the stream + /// is gone, and discards the parked events. Returns whether there were + /// any. + pub(crate) fn close(&mut self) -> bool { + self.closed = true; + self.subscribers.clear(); + self.parked_bytes = 0; + let discarded = !self.parked.is_empty(); + self.parked.clear(); + discarded + } + + fn parks(&self, key: &Key) -> bool { + key.1 < self.parking_below && self.families.contains(&key.0) && !self.attached.contains(key) + } + + fn park_event(&mut self, key: Key, event: Event, size: usize) { + let parked = self.parked.entry(key).or_default(); + parked.events.push_back((event, size)); + parked.bytes += size; + self.parked_bytes += size; + while parked.bytes > RESOURCE_LIMIT_BYTES || self.parked_bytes > TOTAL_LIMIT_BYTES { + let Some(oldest) = parked + .events + .iter() + .position(|(event, _)| event.event.ends_with(".output")) + else { + break; + }; + let (_, dropped) = parked.events.remove(oldest).expect("position is in range"); + parked.bytes -= dropped; + self.parked_bytes -= dropped; + parked.lost = true; + } + } +} + +/// Delivers `event`, `size` bytes on the wire. Returns `false` when the +/// connection must resynchronize: a live subscriber or the general channel was +/// full. +pub(crate) fn route( + routes: &Routes, + events: &SyncSender, + event: Event, + size: usize, +) -> bool { + let key = event.resource().map(|(family, id)| (family.to_owned(), id)); + // Neither a resource nor the general consumer may block the sole response + // reader: a process owner needs that reader to acknowledge its kill request. + let subscriber = match &key { + Some(key) => { + let mut table = lock(routes); + match table.subscribers.get(key).cloned() { + Some(subscriber) => Some(subscriber), + None if table.parks(key) => { + table.park_event(key.clone(), event, size); + return true; + } + None => None, + } + } + None => None, + }; + match subscriber { + Some(subscriber) => { + match subscriber.try_send(event) { + Ok(()) => true, + Err(error) => { + if let Some(key) = key { + lock(routes).subscribers.remove(&key); + } + // A live owner losing a frame must resynchronize. Dropping + // a receiver intentionally only ends that subscription. + matches!(error, mpsc::TrySendError::Disconnected(_)) + } + } + } + // A dropped general receiver means nobody consumes these events. + None => !matches!(events.try_send(event), Err(mpsc::TrySendError::Full(_))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn output(id: u64, seq: u64) -> Event { + Event { + event: "process.output".into(), + params: json!({"processId": id, "data": ""}), + seq: Some(seq), + } + } + + fn exit(id: u64) -> Event { + Event { + event: "process.exit".into(), + params: json!({"processId": id, "code": 0}), + seq: None, + } + } + + #[test] + fn full_resource_queue_requires_resynchronization_without_blocking_replies() { + let routes = Routes::default(); + let full = lock(&routes).subscribe("process", 7, 1); + let healthy = lock(&routes).subscribe("process", 8, 1); + let (general, _) = mpsc::sync_channel(1); + assert!(route(&routes, &general, output(7, 1), 1)); + assert!(!route(&routes, &general, output(7, 2), 1)); + assert!(!lock(&routes) + .subscribers + .contains_key(&("process".into(), 7))); + assert!(route(&routes, &general, output(8, 3), 1)); + assert_eq!(healthy.try_recv().unwrap().resource(), Some(("process", 8))); + assert!(full.try_recv().is_ok()); + assert!(matches!( + full.try_recv(), + Err(mpsc::TryRecvError::Disconnected) + )); + } + + #[test] + fn general_overflow_requires_resynchronization_instead_of_losing_watch_changes() { + let routes = Routes::default(); + let (sender, receiver) = mpsc::sync_channel(1); + let event = || Event { + event: "watch.changed".into(), + params: json!({}), + seq: None, + }; + assert!(route(&routes, &sender, event(), 1)); + assert!(!route(&routes, &sender, event(), 1)); + drop(receiver); + assert!(route(&routes, &sender, event(), 1)); + } + + #[test] + fn dropped_resource_receiver_does_not_close_the_connection() { + let routes = Routes::default(); + let receiver = lock(&routes).subscribe("process", 7, 1); + let (general, _) = mpsc::sync_channel(1); + drop(receiver); + assert!(route(&routes, &general, output(7, 1), 1)); + assert!(!lock(&routes) + .subscribers + .contains_key(&("process".into(), 7))); + } + + #[test] + fn attach_receives_the_parked_events_then_the_live_ones_without_a_gap() { + let routes = Routes::default(); + lock(&routes).park("process", 10); + let (general, unrouted) = mpsc::sync_channel(4); + assert!(route(&routes, &general, output(3, 1), 1)); + assert!(route(&routes, &general, output(3, 2), 1)); + let attached = lock(&routes).attach("process", 3, 4).unwrap(); + assert!(route(&routes, &general, exit(3), 1)); + assert_eq!( + attached + .missed + .iter() + .map(|event| event.seq) + .collect::>(), + [Some(1), Some(2)] + ); + assert!(!attached.lost); + assert_eq!(attached.events.try_recv().unwrap().event, "process.exit"); + // Nothing of the parked resource reached the general channel. + assert!(unrouted.try_recv().is_err()); + assert_eq!(lock(&routes).parked_bytes, 0); + } + + #[test] + fn only_resources_of_earlier_connections_in_a_parked_family_are_parked() { + let routes = Routes::default(); + lock(&routes).park("process", 10); + let (general, unrouted) = mpsc::sync_channel(4); + // Created by this connection: its owner subscribed and has finished. + assert!(route(&routes, &general, exit(12), 1)); + let terminal = Event { + event: "terminal.output".into(), + params: json!({"terminalId": 3, "data": ""}), + seq: None, + }; + assert!(route(&routes, &general, terminal, 1)); + assert_eq!(unrouted.try_iter().count(), 2); + assert_eq!( + lock(&routes).attach("process", 12, 4).unwrap_err(), + AttachRefusal::Unavailable + ); + assert_eq!( + lock(&routes).attach("terminal", 3, 4).unwrap_err(), + AttachRefusal::Unavailable + ); + } + + #[test] + fn a_resource_has_one_owner() { + let routes = Routes::default(); + lock(&routes).park("process", 10); + let (general, unrouted) = mpsc::sync_channel(4); + let first = lock(&routes).attach("process", 3, 4).unwrap(); + assert_eq!( + lock(&routes).attach("process", 3, 4).unwrap_err(), + AttachRefusal::Owned + ); + drop(first); + // The owner stopped receiving: this event ends its subscription, and + // the later ones are not parked again for a second attach. + assert!(route(&routes, &general, output(3, 1), 1)); + assert!(route(&routes, &general, output(3, 2), 1)); + assert_eq!( + lock(&routes).attach("process", 3, 4).unwrap_err(), + AttachRefusal::Unavailable + ); + assert_eq!(unrouted.try_iter().count(), 1); + } + + #[test] + fn parking_drops_the_oldest_output_but_keeps_the_exit() { + let routes = Routes::default(); + lock(&routes).park("process", 10); + let (general, _) = mpsc::sync_channel(1); + let half = RESOURCE_LIMIT_BYTES / 2; + for seq in 1..=3 { + assert!(route(&routes, &general, output(3, seq), half)); + } + assert!(route(&routes, &general, exit(3), half)); + let attached = lock(&routes).attach("process", 3, 4).unwrap(); + assert!(attached.lost); + assert_eq!( + attached + .missed + .iter() + .map(|event| (event.event.as_str(), event.seq)) + .collect::>(), + [("process.output", Some(3)), ("process.exit", None)] + ); + } + + #[test] + fn parking_stays_within_the_total_limit() { + let routes = Routes::default(); + lock(&routes).park("process", 100); + let (general, _) = mpsc::sync_channel(1); + let size = RESOURCE_LIMIT_BYTES / 2; + for id in 1..=40 { + assert!(route(&routes, &general, output(id, id), size)); + } + assert!(lock(&routes).parked_bytes <= TOTAL_LIMIT_BYTES); + let last = lock(&routes).attach("process", 40, 4).unwrap(); + assert!(last.lost); + let first = lock(&routes).attach("process", 1, 4).unwrap(); + assert!(!first.lost); + assert_eq!(first.missed.len(), 1); + } + + #[test] + fn closing_ends_subscriptions_and_reports_discarded_events() { + let routes = Routes::default(); + lock(&routes).park("process", 10); + let (general, _) = mpsc::sync_channel(1); + let subscribed = lock(&routes).subscribe("process", 12, 4); + assert!(!lock(&routes).close()); + assert!(matches!( + subscribed.try_recv(), + Err(mpsc::TryRecvError::Disconnected) + )); + + let routes = Routes::default(); + lock(&routes).park("process", 10); + assert!(route(&routes, &general, output(3, 1), 1)); + assert!(lock(&routes).close()); + let late = lock(&routes).attach("process", 3, 4).unwrap(); + assert!(late.missed.is_empty()); + assert!(matches!( + late.events.try_recv(), + Err(mpsc::TryRecvError::Disconnected) + )); + } +} diff --git a/rust/crates/remote/src/client/session.rs b/rust/crates/remote/src/client/session.rs index a6ad0375..d7ee07f9 100644 --- a/rust/crates/remote/src/client/session.rs +++ b/rust/crates/remote/src/client/session.rs @@ -4,6 +4,8 @@ //! request waiting for it, and each event either to the subscriber of its //! resource (`terminal.output` with `terminalId` 7 goes to the subscription //! for terminal 7) or, without one, to the session's general event channel. +//! A reconnecting client can park the events of the resources an earlier +//! connection created until it attaches to them (see [`RemoteSession::park`]). //! //! Every channel is bounded. A stalled resource loses its subscription instead //! of blocking the shared reader: its owner observes disconnection and reclaims @@ -21,6 +23,7 @@ //! register [`RemoteSession::on_closed`] to release them once the stream ends. use crate::client::connection_log::{ConnectionKind, ConnectionLog}; +use crate::client::routes::{route, Routes}; use crate::client::transport::{TransportChain, TransportError}; use crate::protocol::frame::{read_frame, skip_preamble, write_frame}; use crate::protocol::methods::{ @@ -34,7 +37,7 @@ use std::collections::{HashMap, VecDeque}; use std::fmt; use std::io::{self, BufReader, Read, Write}; use std::process::{Child, Command, Stdio}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{self, Receiver, SyncSender}; use std::sync::{Arc, Condvar, Mutex}; use std::thread; @@ -90,6 +93,29 @@ impl Event { } } +/// Where a connection's event stream stands. It stays readable after the +/// session is gone, so the next connection to the same persistent session +/// resumes from it. +#[derive(Clone, Debug, Default)] +pub struct EventPosition { + seq: Arc, + discarded: Arc, +} + +impl EventPosition { + /// Sequence number of the latest event received. + pub fn seq(&self) -> u64 { + self.seq.load(Ordering::Acquire) + } + + /// Whether the stream ended while it kept events for a resource nobody + /// had attached to. The connection acknowledged them, so a later + /// connection's attach misses them. + pub fn discarded(&self) -> bool { + self.discarded.load(Ordering::Acquire) + } +} + /// Failure of a session request or of establishing the session. #[derive(Debug)] pub enum ClientError { @@ -177,7 +203,7 @@ struct Pending { on_closed: Vec, } -type Routes = Mutex>>; +pub use crate::client::routes::{AttachRefusal, Attachment}; /// Options for establishing a session. #[derive(Clone, Debug)] @@ -348,8 +374,7 @@ pub struct RemoteSession { routes: Arc, next_request: Arc, next_resource: AtomicU64, - /// Sequence number of the latest event received. - last_seq: Arc, + position: EventPosition, child: Mutex>, stderr_tail: Arc, hello: Option, @@ -555,7 +580,7 @@ impl RemoteSession { let (ready_sender, ready) = mpsc::channel(); let outgoing = Arc::new(Outgoing::default()); let next_request = Arc::new(AtomicU64::new(0)); - let last_seq = Arc::new(AtomicU64::new(0)); + let position = EventPosition::default(); let writer = { let outgoing = Arc::clone(&outgoing); let pending = Arc::clone(&pending); @@ -574,7 +599,7 @@ impl RemoteSession { events: event_sender, outgoing: Arc::clone(&outgoing), next_request: Arc::clone(&next_request), - last_seq: Arc::clone(&last_seq), + position: position.clone(), log: log.clone(), }; thread::Builder::new() @@ -594,7 +619,7 @@ impl RemoteSession { routes, next_request, next_resource: AtomicU64::new(1), - last_seq, + position, child: Mutex::new(child), stderr_tail, hello: None, @@ -657,7 +682,14 @@ impl RemoteSession { /// to [`RemoteSession::resume`] on the next connection to continue /// without gaps or repeats. pub fn last_event_seq(&self) -> u64 { - self.last_seq.load(Ordering::Acquire) + self.position.seq() + } + + /// Where this connection's event stream stands, readable after the + /// session is gone: the next connection to the same persistent session + /// resumes from it. + pub fn event_position(&self) -> EventPosition { + self.position.clone() } /// Handshake result, including the host capabilities. @@ -681,15 +713,32 @@ impl RemoteSession { /// before creating the resource, so its first events are not missed. /// Dropping the receiver ends the subscription. pub fn subscribe(&self, family: &str, id: u64) -> Receiver { - let (sender, receiver) = mpsc::sync_channel(EVENT_CAPACITY); - lock(&self.routes).insert((family.to_owned(), id), sender); - receiver + lock(&self.routes).subscribe(family, id, EVENT_CAPACITY) } /// Ends the subscription of one resource; its later events go to the general /// event channel. pub fn unsubscribe(&self, family: &str, id: u64) { - lock(&self.routes).remove(&(family.to_owned(), id)); + lock(&self.routes).unsubscribe(family, id); + } + + /// Keeps the events of `family` resources that earlier connections to + /// this persistent session created, and that nobody receives yet, until + /// [`RemoteSession::attach`] takes them. Call it before + /// [`RemoteSession::resume`], connecting with [`ResumeMode::Deferred`], + /// so the replayed events are kept too. + pub fn park(&self, family: &str) { + let below = self.hello().session.next_resource_id; + lock(&self.routes).park(family, below); + } + + /// Starts receiving the events of resource `id` of a parked family that + /// an earlier connection created: first the events kept since this + /// connection resumed, then the later ones, like [`RemoteSession::subscribe`]. + /// Refused when another caller already receives its events, or nothing + /// keeps them for an attach. + pub fn attach(&self, family: &str, id: u64) -> Result { + lock(&self.routes).attach(family, id, EVENT_CAPACITY) } /// Sends a request and waits for its typed result. @@ -860,7 +909,7 @@ struct ReaderContext { events: SyncSender, outgoing: Arc, next_request: Arc, - last_seq: Arc, + position: EventPosition, log: ConnectionLog, } @@ -902,7 +951,7 @@ fn read_loop( events, outgoing, next_request, - last_seq, + position, log, } = context; let mut reader = BufReader::new(reader); @@ -934,11 +983,11 @@ fn read_loop( } } Ok(Message::Event { event, params, seq }) => { - if !route(&routes, &events, Event { event, params, seq }) { + if !route(&routes, &events, Event { event, params, seq }, frame.len()) { break "overflow".to_owned(); } if let Some(seq) = seq { - last_seq.store(seq, Ordering::Release); + position.seq.store(seq, Ordering::Release); if seq >= acknowledged + ACK_INTERVAL && acknowledge(&outgoing, &next_request, seq) { @@ -954,7 +1003,9 @@ fn read_loop( log.stream_ended(&cause); close(&pending); // Ending every subscription tells consumers the stream is gone. - lock(&routes).clear(); + if lock(&routes).close() { + position.discarded.store(true, Ordering::Release); + } } /// Queues `server.ack` without waiting for its response, which the reader @@ -985,30 +1036,6 @@ fn write_loop(mut writer: Box, outgoing: &Outgoing, pending: & } } -fn route(routes: &Routes, events: &SyncSender, event: Event) -> bool { - let key = event.resource().map(|(family, id)| (family.to_owned(), id)); - // Neither a resource nor the general consumer may block the sole response - // reader: a process owner needs that reader to acknowledge its kill request. - let subscriber = key.as_ref().and_then(|key| lock(routes).get(key).cloned()); - match subscriber { - Some(subscriber) => { - match subscriber.try_send(event) { - Ok(()) => true, - Err(error) => { - if let Some(key) = key { - lock(routes).remove(&key); - } - // A live owner losing a frame must resynchronize. Dropping - // a receiver intentionally only ends that subscription. - matches!(error, mpsc::TrySendError::Disconnected(_)) - } - } - } - // A dropped general receiver means nobody consumes these events. - None => !matches!(events.try_send(event), Err(mpsc::TrySendError::Full(_))), - } -} - /// Marks the stream ended, fails every waiting request and then runs the /// closed hooks, outside the lock so that a hook may use the session. The /// reader and the writer can both end the stream; hooks run only once. @@ -1063,7 +1090,7 @@ fn abandon(child: Option) { } } -fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { +pub(super) fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { mutex .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) @@ -1215,65 +1242,6 @@ mod tests { assert_eq!(unrelated.resource(), None); } - #[test] - fn full_resource_queue_requires_resynchronization_without_blocking_replies() { - let routes = Mutex::new(HashMap::new()); - let (full, stalled) = mpsc::sync_channel(1); - let (other, healthy) = mpsc::sync_channel(1); - let (general, _) = mpsc::sync_channel(1); - lock(&routes).insert(("process".into(), 7), full); - lock(&routes).insert(("process".into(), 8), other); - let event = |id| Event { - event: "process.output".into(), - params: json!({"processId": id, "data": ""}), - seq: None, - }; - assert!(route(&routes, &general, event(7))); - assert!(!route(&routes, &general, event(7))); - assert!(!lock(&routes).contains_key(&("process".into(), 7))); - assert!(route(&routes, &general, event(8))); - assert_eq!(healthy.try_recv().unwrap().resource(), Some(("process", 8))); - assert!(stalled.try_recv().is_ok()); - assert!(matches!( - stalled.try_recv(), - Err(mpsc::TryRecvError::Disconnected) - )); - } - - #[test] - fn general_overflow_requires_resynchronization_instead_of_losing_watch_changes() { - let routes = Mutex::new(HashMap::new()); - let (sender, receiver) = mpsc::sync_channel(1); - let event = || Event { - event: "watch.changed".into(), - params: json!({}), - seq: None, - }; - assert!(route(&routes, &sender, event())); - assert!(!route(&routes, &sender, event())); - drop(receiver); - assert!(route(&routes, &sender, event())); - } - - #[test] - fn dropped_resource_receiver_does_not_close_the_connection() { - let routes = Mutex::new(HashMap::new()); - let (sender, receiver) = mpsc::sync_channel(1); - let (general, _) = mpsc::sync_channel(1); - lock(&routes).insert(("process".into(), 7), sender); - drop(receiver); - assert!(route( - &routes, - &general, - Event { - event: "process.output".into(), - params: json!({"processId": 7, "data": ""}), - seq: None, - } - )); - assert!(!lock(&routes).contains_key(&("process".into(), 7))); - } - #[test] fn closed_hooks_run_once_after_waiting_requests_fail() { let pending = Arc::new(Mutex::new(Pending::default())); diff --git a/rust/crates/remote/tests/persistence.rs b/rust/crates/remote/tests/persistence.rs index 8455a0c8..5aef9b21 100644 --- a/rust/crates/remote/tests/persistence.rs +++ b/rust/crates/remote/tests/persistence.rs @@ -230,6 +230,152 @@ fn resuming_after_a_lost_connection_delivers_every_event_exactly_once() { assert!(daemon.wait_until_stopped()); } +/// The standard output of `events` up to the process exit, and its exit code. +fn output_until_exit( + missed: Vec, + events: &std::sync::mpsc::Receiver, + process_id: u64, + mut before_waiting: impl FnMut(&[u8]), +) -> (Vec, Option) { + let deadline = Instant::now() + STEP_TIMEOUT; + let mut stdout = Vec::new(); + let mut missed = missed.into_iter(); + loop { + let event = match missed.next() { + Some(event) => event, + None => { + before_waiting(&stdout); + events + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .unwrap_or_else(|_| panic!("no exit; output has {} bytes", stdout.len())) + } + }; + assert_eq!(event.resource(), Some(("process", process_id))); + match event.event.as_str() { + methods::EVENT_PROCESS_OUTPUT => { + let output: ProcessOutputEvent = event.decode().unwrap(); + stdout.extend(methods::decode_bytes(&output.data).unwrap()); + } + methods::EVENT_PROCESS_EXIT => { + let exit: ProcessExitEvent = event.decode().unwrap(); + return (stdout, exit.exit_code); + } + _ => {} + } + } +} + +// A run window shows a process, the connection drops, and after the +// reconnection it attaches to the same process: the output produced while +// disconnected and the live output arrive once each, in order, and nowhere +// else. +#[test] +fn a_reconnected_client_attaches_to_a_running_process_without_a_gap() { + let daemon = Daemon::new("attach"); + let gate = TempDir::new("gate"); + let (release, written, finish) = ( + gate.join("release"), + gate.join("written"), + gate.join("finish"), + ); + let script = format!( + "echo before; while [ ! -e '{release}' ]; do sleep 0.05; done; echo during; \ + touch '{written}'; while [ ! -e '{finish}' ]; do sleep 0.05; done; echo after" + ); + let (session, _events) = daemon.connect(None); + let process_id = session.allocate_id(); + let subscription = session.subscribe("process", process_id); + session + .request_value( + methods::PROCESS_SPAWN, + serde_json::json!({"processId": process_id, "argv": ["sh", "-c", script]}), + STEP_TIMEOUT, + ) + .unwrap(); + let first = subscription + .recv_timeout(STEP_TIMEOUT) + .expect("output before the disconnect"); + let output: ProcessOutputEvent = first.decode().unwrap(); + assert_eq!(methods::decode_bytes(&output.data).unwrap(), b"before\n"); + let shown = first.seq.unwrap(); + drop(subscription); + drop(session); + std::fs::write(&release, b"").unwrap(); + assert!( + wait_for_file(&written), + "the process did not reach its marker" + ); + + let (session, events) = daemon.connect_deferred(); + assert!(session.hello().session.resumed); + session.park("process"); + assert!(!session.resume(Some(shown)).unwrap().truncated); + let attachment = session.attach("process", process_id).unwrap(); + assert!(!attachment.lost); + assert_eq!( + session.attach("process", process_id).unwrap_err(), + lithe_remote::client::session::AttachRefusal::Owned + ); + let mut finished = false; + let (stdout, exit_code) = output_until_exit( + attachment.missed, + &attachment.events, + process_id, + |stdout| { + // Let the process finish only once the disconnected output + // arrived, so the rest is live. + if !finished && stdout == b"during\n" { + std::fs::write(&finish, b"").unwrap(); + finished = true; + } + }, + ); + assert_eq!(stdout, b"during\nafter\n"); + assert_eq!(exit_code, Some(0)); + assert!( + events + .try_iter() + .all(|event| event.resource() != Some(("process", process_id))), + "the attached process's events also went to the general channel" + ); + session.shutdown(STEP_TIMEOUT); + assert!(daemon.wait_until_stopped()); +} + +// A process that finished while nobody was connected is attached to with its +// remaining output and its exit, and nothing reaches the general channel +// before the attach. +#[test] +fn attaching_to_a_process_that_exited_while_disconnected_replays_its_end() { + let daemon = Daemon::new("attach-exited"); + let (session, _events) = daemon.connect(None); + let process = session + .spawn(SpawnSpec { + argv: argv(&["sh", "-c", "sleep 0.3; echo done"]), + ..SpawnSpec::default() + }) + .unwrap(); + let (process_id, pid) = (process.id, process.pid); + drop(process); + drop(session); + assert!(wait_until_gone(pid), "process {pid} did not finish"); + + let (session, events) = daemon.connect_deferred(); + session.park("process"); + // Without a remembered position every kept event is replayed. + session.resume(None).unwrap(); + let attachment = session.attach("process", process_id).unwrap(); + let (stdout, exit_code) = + output_until_exit(attachment.missed, &attachment.events, process_id, |_| {}); + assert_eq!(stdout, b"done\n"); + assert_eq!(exit_code, Some(0)); + assert!(events + .try_iter() + .all(|event| event.resource() != Some(("process", process_id)))); + session.shutdown(STEP_TIMEOUT); + assert!(daemon.wait_until_stopped()); +} + // A session nobody returns to ends once nothing runs in it, so a host does // not keep daemons for clients that are gone. Finished programs do not // count. diff --git a/rust/crates/workspace/src/host.rs b/rust/crates/workspace/src/host.rs index 22e4bb22..65c9fdfd 100644 --- a/rust/crates/workspace/src/host.rs +++ b/rust/crates/workspace/src/host.rs @@ -3,10 +3,12 @@ //! Streaming calls own their resource and subscription together. Cancellation, //! failed creation, and caller disconnect all close the remote process tree; //! ordinary host requests cannot create an unobserved streaming resource. +//! `remote.attachProcess` takes over a process an earlier connection to the +//! same persistent session started, with the same ownership. use crate::sessions::{lookup, request_error}; use lithe_protocol::{cancellation, CoreError, ErrorCode}; -use lithe_remote::client::session::{ClientError, Event, RemoteSession}; +use lithe_remote::client::session::{AttachRefusal, Attachment, ClientError, Event, RemoteSession}; use lithe_remote::protocol::methods; use lithe_request_context::events as execution_events; use serde::Deserialize; @@ -283,20 +285,118 @@ fn run_on_session( let deadline = request .timeout_milliseconds .map(|timeout| Instant::now() + Duration::from_millis(timeout.min(86_400_000))); - run_observing( + run_observing(session, request, family, method, None, deadline, &mut relay) +} + +/// Relays a resource event to the request's caller. +fn relay(event: Event) -> Result<(), CoreError> { + execution_events::emit(json!({ + "type": "remote", "event": event.event, "params": event.params, + })); + Ok(()) +} + +/// A process an earlier connection to the same persistent host session +/// started. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AttachRequest { + session_id: String, + process_id: u64, +} + +/// Receives the events of a process an earlier connection started, after +/// this connection resumed the session: first the ones since the earlier +/// connections' last event, then the live ones until the process exits. +/// The first event, `process.attached`, says whether output may be missing. +/// From the attach on the request owns the process like `remote.runProcess`: +/// cancelling it ends the process. +pub fn attach_process(request: AttachRequest) -> Result { + cancellation::check()?; + let connection = lookup(&request.session_id)?; + let session = &connection.session; + if session.is_closed() { + return Err(request_error( + &request.session_id, + ClientError::Disconnected { + diagnostics: String::new(), + }, + )); + } + let gone = || { + CoreError::new( + ErrorCode::RemoteProcessGone, + "The host session no longer runs this process", + ) + }; + if !connection.history.resumed { + return Err(gone()); + } + let Attachment { + missed, + lost, + events, + } = match session.attach("process", request.process_id) { + Ok(attachment) => attachment, + Err(AttachRefusal::Owned) => { + return Err(CoreError::new( + ErrorCode::RemoteProcessAttached, + "Another request already receives this process", + )) + } + Err(AttachRefusal::Unavailable) => return Err(gone()), + }; + let mut resource = Resource { session, - request, - family, - method, + family: "process", + id: request.process_id, + creation_attempted: true, + }; + let mut missed = VecDeque::from(missed); + if missed.is_empty() && !still_runs(session, &request.session_id, request.process_id)? { + // The state response follows any earlier exit event on the wire, so + // an exit that arrived meanwhile is already in the subscription. + missed.extend(events.try_iter()); + if missed.is_empty() { + resource.creation_attempted = false; + return Err(gone()); + } + } + relay(Event { + event: "process.attached".into(), + params: json!({ + "processId": request.process_id, + "truncated": lost || !connection.history.complete, + }), + seq: None, + })?; + let outcome = receive_events( + &resource, + &events, + missed, + &request.session_id, None, - deadline, - &mut |event| { - execution_events::emit(json!({ - "type": "remote", "event": event.event, "params": event.params, - })); - Ok(()) - }, - ) + None, + &mut relay, + ); + // See Resource::drop: remove backpressure before trying to stop the tree. + drop(events); + drop(resource); + outcome +} + +/// Whether the host session still owns process `id`. +fn still_runs(session: &RemoteSession, session_id: &str, id: u64) -> Result { + let state = request_cancellable(session, methods::SERVER_STATE, json!({}), REQUEST_TIMEOUT) + .map_err(|error| request_error(session_id, error))?; + let state: methods::ServerState = serde_json::from_value(state).map_err(|error| { + CoreError::new(ErrorCode::ParseFailed, "Invalid host session state") + .with_details(error.to_string()) + })?; + Ok(state + .processes + .iter() + .any(|process| process.process_id == id)) } /// Runs an owned host process with byte-preserving output and optional input. diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index 918f601f..5c931bf1 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -39,6 +39,7 @@ pub mod port_records; pub mod preferences; pub mod probe; pub mod programs; +mod resumption; mod scope; pub mod sessions; pub mod ssh_configuration; diff --git a/rust/crates/workspace/src/programs.rs b/rust/crates/workspace/src/programs.rs index 9a268cd8..9b91260b 100644 --- a/rust/crates/workspace/src/programs.rs +++ b/rust/crates/workspace/src/programs.rs @@ -24,7 +24,9 @@ const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum ProgramKind { + /// A process started by `process.spawn`. Process, + /// A terminal started by `terminal.open`. Terminal, } @@ -32,6 +34,7 @@ pub enum ProgramKind { #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct RunningProgram { + /// Whether the program is a process or a terminal. pub kind: ProgramKind, /// The id the program was started with; unique per kind. pub id: u64, diff --git a/rust/crates/workspace/src/resumption.rs b/rust/crates/workspace/src/resumption.rs new file mode 100644 index 00000000..1f4b5385 --- /dev/null +++ b/rust/crates/workspace/src/resumption.rs @@ -0,0 +1,118 @@ +//! Where each persistent host session's event stream stood when this Core +//! last had a connection to it, so a reconnection continues it (design §9.3). +//! +//! A connection that resumes a session asks the host for the events after +//! the last one the previous connection received. The previous connection's +//! subscribers already showed everything up to there, and the events after it +//! wait in the new connection until a run window attaches to its process +//! (`remote.attachProcess`). Without a remembered position, for example after +//! the application restarted, the host replays every event it still keeps: +//! the attach then reports that output may be missing. +//! +//! The positions live only in this process's memory, keyed by the session +//! key. They hold no host details and are bounded to the most recent +//! sessions. + +use lithe_remote::client::session::EventPosition; +use std::collections::VecDeque; +use std::sync::{Mutex, OnceLock}; + +/// Sessions whose position is remembered; the oldest is forgotten first. +const REMEMBERED_SESSIONS: usize = 32; + +/// The connection that last owned a session. +struct Remembered { + key: String, + position: EventPosition, + /// Whether that connection had every event of the resources earlier + /// connections created, or lost some of them. + complete: bool, +} + +/// Where a reconnection continues the session's event stream. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct Continuation { + /// Sequence number of the latest event the previous connection received. + pub(crate) after_seq: u64, + /// Whether the previous connection lost no event of a resource that an + /// attach can still receive. + pub(crate) complete: bool, +} + +fn positions() -> &'static Mutex> { + static POSITIONS: OnceLock>> = OnceLock::new(); + POSITIONS.get_or_init(Mutex::default) +} + +/// Where the previous connection to session `key` stopped, if this Core had +/// one. +pub(crate) fn continuation(key: &str) -> Option { + positions() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .find(|remembered| remembered.key == key) + .map(|remembered| Continuation { + after_seq: remembered.position.seq(), + // Events the connection kept for a process nobody attached to + // were acknowledged and are gone with it. + complete: remembered.complete && !remembered.position.discarded(), + }) +} + +/// Records the connection that now owns session `key`, replacing the +/// previous one. +pub(crate) fn remember(key: &str, position: EventPosition, complete: bool) { + let mut positions = positions() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + positions.retain(|remembered| remembered.key != key); + if positions.len() >= REMEMBERED_SESSIONS { + positions.pop_front(); + } + positions.push_back(Remembered { + key: key.to_owned(), + position, + complete, + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_session_continues_where_its_latest_connection_stopped() { + let key = "resumption-latest"; + assert_eq!(continuation(key), None); + remember(key, EventPosition::default(), false); + remember(key, EventPosition::default(), true); + assert_eq!( + continuation(key), + Some(Continuation { + after_seq: 0, + complete: true + }) + ); + } + + #[test] + fn only_the_most_recent_sessions_are_remembered() { + for index in 0..=REMEMBERED_SESSIONS { + remember( + &format!("resumption-bounded-{index}"), + EventPosition::default(), + true, + ); + } + assert_eq!(continuation("resumption-bounded-0"), None); + assert!(continuation(&format!("resumption-bounded-{REMEMBERED_SESSIONS}")).is_some()); + assert!( + positions() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .len() + <= REMEMBERED_SESSIONS + ); + } +} diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index a73e0721..7cf763c3 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -27,7 +27,7 @@ use lithe_git_host::ProcessTree; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::connections::{ConnectionError, Reason, SshConnection}; use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched, Stage}; -use lithe_remote::client::session::{ClientError, ConnectOptions}; +use lithe_remote::client::session::{ClientError, ConnectOptions, ResumeMode}; use lithe_remote::client::trust::Target; use lithe_remote::client::{ wsl, ArtifactError, ConnectionKind, ConnectionLog, ContainerConnection, ForwardSet, Hop, @@ -203,6 +203,21 @@ pub struct Connection { /// Port forwards of the ports page; they end with the session. pub(crate) forwards: ForwardSet, pub(crate) transport: ConnectionTransport, + /// What the connection has of the programs earlier connections started. + pub(crate) history: History, +} + +/// What a connection has of the processes earlier connections to the same +/// persistent session started, which `remote.attachProcess` reattaches to. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct History { + /// Whether the connection resumed a session an earlier one kept. + pub resumed: bool, + /// Whether it received every event of those processes after the last one + /// earlier connections showed. `false` after the application restarted, + /// the host dropped events past its retention limit, or an earlier + /// connection discarded events nobody attached to. + pub complete: bool, } /// Owns the native transport independently of the framed workspace session. @@ -222,6 +237,7 @@ impl Connection { session: RemoteSession, trust_target: Target, transport: ConnectionTransport, + history: History, ) -> Self { let session = Arc::new(session); Self { @@ -230,6 +246,7 @@ impl Connection { git_tool: Mutex::new(None), trust_target, transport, + history, } } @@ -960,6 +977,9 @@ fn connect_logged( let options = ConnectOptions { handshake_timeout: HANDSHAKE_TIMEOUT, session_token: resume.map(|resume| resume.token.clone()), + // Events start only after process events are parked below, so the + // ones a resumed session replays wait for `remote.attachProcess`. + resume: ResumeMode::Deferred, log: Some(log.clone()), ..ConnectOptions::default() }; @@ -983,11 +1003,36 @@ fn connect_logged( )); } }; - // Process events are not used yet; draining keeps the session's reader - // from blocking on a full channel. - std::thread::spawn(move || for _ in events {}); let capabilities = session.hello().host.clone(); let info = session.hello().session.clone(); + // Events of resources an earlier connection started wait for + // `remote.attachProcess`; everything else nobody subscribed to is + // drained, so the session's reader never blocks on a full channel. The + // drain runs before `server.resume` because the replay follows at once. + session.park("process"); + std::thread::spawn(move || for _ in events {}); + let earlier = info + .resumed + .then(|| crate::resumption::continuation(&session_key)) + .flatten(); + let history_complete = match session.resume(earlier.map(|earlier| earlier.after_seq)) { + Ok(resumed) => { + !info.resumed || (earlier.is_some_and(|earlier| earlier.complete) && !resumed.truncated) + } + Err(error) => { + drop(session); + // Grace expiry is advisory: the following checked kill/wait owns the final cleanup result. + wait_for_exit(&mut child, EXIT_GRACE); + reap(&tree, &mut child); + let stderr = diagnostics(&client.text(&tail(&stderr_tail))); + return Ok(failed( + ProbeStatus::Failed, + Some(host), + join_diagnostics(&error.to_string(), &stderr), + )); + } + }; + crate::resumption::remember(&session_key, session.event_position(), history_complete); let kept_programs = if info.resumed { crate::programs::running(&session).unwrap_or_else(|error| { // The connection works without the list; the client can ask again. @@ -1015,6 +1060,10 @@ fn connect_logged( child: Mutex::new(child), tree, }, + History { + resumed: info.resumed, + complete: history_complete, + }, )), ); Ok(ConnectResult { diff --git a/rust/crates/workspace/src/test_support.rs b/rust/crates/workspace/src/test_support.rs index 3a6d607a..85809eed 100644 --- a/rust/crates/workspace/src/test_support.rs +++ b/rust/crates/workspace/src/test_support.rs @@ -1,7 +1,7 @@ //! Hooks for `lithe-core`'s end-to-end tests, which drive real Core commands //! against an in-process host server instead of an SSH child. -use crate::sessions::{ended, lookup, nonce, registry, Connection, ConnectionTransport}; +use crate::sessions::{ended, lookup, nonce, registry, Connection, ConnectionTransport, History}; use lithe_remote::client::trust::Target; use lithe_remote::client::{RemoteSession, TransportChain}; use std::sync::Arc; @@ -9,6 +9,12 @@ use std::sync::Arc; /// Registers `session` as a connected host and returns its session id. Its /// trust target has no hops, only the account the server reports. pub fn register_in_process(session: RemoteSession) -> String { + register_in_process_with(session, History::default()) +} + +/// [`register_in_process`] for a connection that resumed a kept session, +/// with what it has of the earlier connections' processes. +pub fn register_in_process_with(session: RemoteSession, history: History) -> String { let id = nonce(); let trust_target = Target::new(&TransportChain::local(), session.hello().host.user_id); registry().lock().unwrap().insert( @@ -17,6 +23,7 @@ pub fn register_in_process(session: RemoteSession) -> String { session, trust_target, ConnectionTransport::InProcess, + history, )), ); id From 2076c054030ceb2ff8c314630e137557d6028848 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 22 Nov 2026 11:39:45 +0800 Subject: [PATCH 2/2] =?UTF-8?q?test(core):=20remote.attachProcess=20?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E8=AF=B7=E6=B1=82=E8=BF=BD=E8=B8=AA=EF=BC=8C?= =?UTF-8?q?=E5=88=97=E5=85=A5=E9=9D=9E=E9=AB=98=E9=A2=91=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=E6=96=AD=E8=A8=80=20(Refs=201lck/Lithe-IDEA#2231)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/crates/core/src/runtime/request_trace.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index 87ce2120..d99e5e88 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -297,6 +297,7 @@ mod tests { "remote.restoreForwards", "remote.runningPrograms", "remote.endPrograms", + "remote.attachProcess", "debug.launch", ] { assert!(!is_hot(method), "{method}");