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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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` |
Expand Down Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)),
Expand Down
12 changes: 12 additions & 0 deletions rust/crates/core/src/runtime/dispatcher/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,18 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, 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
Expand Down
1 change: 1 addition & 0 deletions rust/crates/core/src/runtime/request_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ mod tests {
"remote.restoreForwards",
"remote.runningPrograms",
"remote.endPrograms",
"remote.attachProcess",
"debug.launch",
] {
assert!(!is_hot(method), "{method}");
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/core/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
239 changes: 239 additions & 0 deletions rust/crates/core/src/tests/remote_attach.rs
Original file line number Diff line number Diff line change
@@ -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<Value>) {
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<u8> {
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();
}
8 changes: 8 additions & 0 deletions rust/crates/protocol/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
4 changes: 3 additions & 1 deletion rust/crates/remote/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading