Skip to content

Commit 18feb4a

Browse files
authored
feat(remote): 重连续传后停放旧连接的进程事件,remote.attachProcess 接回运行窗口 (Refs 1lck/Lithe-IDEA#2231) (#167)
* feat(remote): 重连续传后停放旧连接的进程事件,remote.attachProcess 接回运行窗口 (Refs 1lck/Lithe-IDEA#2231) - 客户端:连接可延后续传;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 缺的字段文档(注释检查原本不过)。 * test(core): remote.attachProcess 记录请求追踪,列入非高频命令断言 (Refs 1lck/Lithe-IDEA#2231)
1 parent 2e4be2c commit 18feb4a

19 files changed

Lines changed: 1231 additions & 120 deletions

File tree

‎rust/contracts/application-boundary.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,10 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported:
418418
be read or is not the build its SHA-256 names
419419
- `devcontainer_untrusted_folder`: the folder is not trusted, so its dev
420420
container was not built or started
421+
- `remote_process_gone`: the remote process to attach to no longer runs and
422+
its output is gone, or the reconnection started a new host session
423+
- `remote_process_attached`: another request already receives the output of
424+
the remote process to attach to
421425
- `unknown`
422426

423427
GitHub authorization is independent of a Lithe account. Device Flow is the

‎rust/contracts/rust-core-api.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -810,6 +810,7 @@ or removing a command fails until the table changes in the same commit.
810810
| `remote.writeFile` | Save a file over an open remote connection |
811811
| `remote.hostRequest` | Perform a non-streaming operation on an existing workspace host |
812812
| `remote.runProcess` | Own a remote process and relays output until it exits or is cancelled |
813+
| `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 |
813814
| `remote.captureProcess` | Capture a short remote process with explicit time and output budgets |
814815
| `remote.runTerminal` | Own a remote PTY and relays output until it exits or is cancelled |
815816
| `remote.runWatch` | Own a host watch and relays changes until cancellation or root removal |
@@ -6232,6 +6233,7 @@ gone. Requests over it take `sessionId`:
62326233
| `remote.uploadFile` | `{ sessionId, sourcePath, path, sha256, mode }` | verified `{ size, sha256 }` |
62336234
| `remote.runWatch` | `{ sessionId, params: { root, excludeNames? } }` | waits until root removal or cancellation; relays `watch.started`, `watch.changed`, `watch.error` |
62346235
| `remote.runProcess` | `{ sessionId, params: { argv, cwd?, environment?, env?, pipeStdin?, label? } }` | leader exit; relays `process.started`, `process.output`, `process.exit` |
6236+
| `remote.attachProcess` | `{ sessionId, processId }` | leader exit; relays `process.attached` (`{ processId, truncated }`), `process.output`, `process.exit` |
62356237
| `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, env?, columns, rows, label? } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` |
62366238
| `remote.captureProcess` | `{ sessionId, params, timeoutMilliseconds, maxOutputBytes }` | base64 `stdout`, `stderr`, nullable `exitCode` and `signal` |
62376239
| `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
62596261
the creating worker cleans it after publication. A rejected or timed-out close
62606262
worker cannot turn an already accepted cancellation into an orphaned resource.
62616263

6264+
`remote.connect` that resumes a persistent session (`resumed: true`) asks
6265+
the host once for the events after the last one this Core received over the
6266+
session, then keeps the output and exit of every process an earlier
6267+
connection started until a caller attaches to it. `remote.attachProcess`
6268+
takes those events, then relays the live ones; the request owns the process
6269+
from then on exactly like the `remote.runProcess` that started it, so
6270+
cancelling it ends the process. A run window that showed the process before
6271+
the connection dropped attaches with the `processId` from its
6272+
`process.started`; a kept program listed in `keptPrograms` or by
6273+
`remote.runningPrograms` attaches with its `id`. `process.attached` comes
6274+
first, and `truncated: true` means output between what the caller already
6275+
showed and the first relayed event may be missing: this Core was restarted
6276+
since, the host dropped events past its retention limit, or more than 4 MiB
6277+
of one process's output (16 MiB together) waited for an attach, in which
6278+
case the oldest output went first. Exit events are never dropped. A process
6279+
that exited while the connection was down ends the request at once with its
6280+
replayed output and exit.
6281+
6282+
`remote.attachProcess` fails with `remote_process_gone` when the connection
6283+
did not resume a session, the process ended before the events this Core
6284+
received, or an earlier attach of it already ended; with
6285+
`remote_process_attached` when another request receives it, the
6286+
`remote.runProcess` that started it or an earlier `remote.attachProcess`.
6287+
Neither changes the process. Terminals and watches are not reattached.
6288+
62626289
Watch startup emits `watch.started` before buffered changes. The caller rescans
62636290
on startup, `overflow`, or watch error; `ROOT_REMOVED` ends the call. Watch paths
62646291
remain absolute host paths until the native adapter maps the owning workspace

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -995,6 +995,10 @@ pub enum RemoteCommand {
995995
HostRequest,
996996
/// Owns a remote process and relays output until it exits or is cancelled.
997997
RunProcess,
998+
/// Takes over a process an earlier connection to the resumed host session
999+
/// started and relays its output until it exits or is cancelled
1000+
/// (`remote.attachProcess`).
1001+
AttachProcess,
9981002
/// Captures a short remote process with explicit time and output budgets.
9991003
CaptureProcess,
10001004
/// Owns a remote PTY and relays output until it exits or is cancelled.
@@ -1635,6 +1639,7 @@ impl CoreCommand {
16351639
"remote.writeFile" => Some(Self::Remote(RemoteCommand::WriteFile)),
16361640
"remote.hostRequest" => Some(Self::Remote(RemoteCommand::HostRequest)),
16371641
"remote.runProcess" => Some(Self::Remote(RemoteCommand::RunProcess)),
1642+
"remote.attachProcess" => Some(Self::Remote(RemoteCommand::AttachProcess)),
16381643
"remote.captureProcess" => Some(Self::Remote(RemoteCommand::CaptureProcess)),
16391644
"remote.runTerminal" => Some(Self::Remote(RemoteCommand::RunTerminal)),
16401645
"remote.runWatch" => Some(Self::Remote(RemoteCommand::RunWatch)),

‎rust/crates/core/src/runtime/dispatcher/remote.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,18 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, payload: Valu
9393
Err(error) => CoreResponse::failure(id, error),
9494
}
9595
}
96+
RemoteCommand::AttachProcess => {
97+
match serde_json::from_value(payload)
98+
.map_err(|error| {
99+
CoreError::new(ErrorCode::InvalidRequest, "Invalid process attach request")
100+
.with_details(error.to_string())
101+
})
102+
.and_then(lithe_workspace::host::attach_process)
103+
{
104+
Ok(value) => CoreResponse::success(id, value),
105+
Err(error) => CoreResponse::failure(id, error),
106+
}
107+
}
96108
RemoteCommand::HostRequest
97109
| RemoteCommand::RunProcess
98110
| RemoteCommand::RunWatch

‎rust/crates/core/src/runtime/request_trace.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ mod tests {
297297
"remote.restoreForwards",
298298
"remote.runningPrograms",
299299
"remote.endPrograms",
300+
"remote.attachProcess",
300301
"debug.launch",
301302
] {
302303
assert!(!is_hot(method), "{method}");

‎rust/crates/core/src/tests/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ mod protocol;
6464
mod published_build_plugins;
6565
mod rank_names;
6666
#[cfg(unix)]
67+
mod remote_attach;
68+
#[cfg(unix)]
6769
mod remote_sessions;
6870
mod request_events;
6971
mod row_selection;
Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
//! `remote.attachProcess` over a resumed persistent session: a scripted host
2+
//! replays what its processes did while nobody was connected.
3+
4+
use lithe_remote::client::session::{ConnectOptions, ResumeMode};
5+
use lithe_remote::client::RemoteSession;
6+
use lithe_remote::protocol::frame::{read_frame, write_frame};
7+
use lithe_remote::protocol::{methods, Message, PREAMBLE};
8+
use lithe_workspace::sessions::History;
9+
use lithe_workspace::test_support;
10+
use serde_json::{json, Value};
11+
use std::io::Write;
12+
use std::net::Shutdown;
13+
use std::os::unix::net::UnixStream;
14+
use std::sync::{mpsc, Arc, Mutex};
15+
use std::time::Duration;
16+
17+
const STEP: Duration = Duration::from_secs(10);
18+
19+
/// Process 3 exited while the connection was down, 5 runs quietly and 6
20+
/// ended before the events this Core received.
21+
fn scripted_host(mut server: UnixStream, done: mpsc::Sender<()>) {
22+
let send = |server: &mut UnixStream, message: Message| {
23+
write_frame(server, &serde_json::to_vec(&message).unwrap()).unwrap();
24+
server.flush().unwrap();
25+
};
26+
let event = |event: &str, params: Value, seq: u64| Message::Event {
27+
event: event.into(),
28+
params,
29+
seq: Some(seq),
30+
};
31+
let mut states = 0;
32+
server.write_all(PREAMBLE).unwrap();
33+
while let Ok(Some(frame)) = read_frame(&mut server) {
34+
let Message::Request { id, method, params } = serde_json::from_slice(&frame).unwrap()
35+
else {
36+
continue;
37+
};
38+
let result = match method.as_str() {
39+
methods::SERVER_HELLO => json!({
40+
"protocolVersion": 1, "serverVersion": "test",
41+
"host": {"os": "linux", "arch": "x86_64", "hostName": "build.example",
42+
"userName": "dev", "homeDirectory": "/home/dev", "defaultShell": "/bin/sh",
43+
"pathSeparator": "/", "process": {"orphanProtection": "parentDeathSignal"},
44+
"watch": {"backend": "inotify", "directoryLimit": 128}, "features": []},
45+
"session": {"persistent": true, "resumed": true, "nextResourceId": 7, "lastEventSeq": 6}
46+
}),
47+
methods::SERVER_RESUME => {
48+
assert_eq!(params["afterSeq"], 4);
49+
let data = methods::encode_bytes(b"while away\n");
50+
send(
51+
&mut server,
52+
event(
53+
methods::EVENT_PROCESS_OUTPUT,
54+
json!({"processId": 3, "stream": "stdout", "data": data}),
55+
5,
56+
),
57+
);
58+
send(
59+
&mut server,
60+
event(
61+
methods::EVENT_PROCESS_EXIT,
62+
json!({"processId": 3, "exitCode": 0, "signal": null}),
63+
6,
64+
),
65+
);
66+
json!({"truncated": false})
67+
}
68+
methods::SERVER_STATE => {
69+
states += 1;
70+
let processes = if states == 1 {
71+
json!([{"processId": 5, "pid": 55, "argv": ["build"], "runningMs": 9,
72+
"leaderExited": false}])
73+
} else {
74+
json!([])
75+
};
76+
send(
77+
&mut server,
78+
Message::success(
79+
id,
80+
json!({"processes": processes, "terminals": [], "watches": []}),
81+
),
82+
);
83+
if states == 1 {
84+
// The quiet process speaks and exits only after the attach
85+
// checked that it still runs.
86+
let data = methods::encode_bytes(b"live\n");
87+
send(
88+
&mut server,
89+
event(
90+
methods::EVENT_PROCESS_OUTPUT,
91+
json!({"processId": 5, "stream": "stdout", "data": data}),
92+
7,
93+
),
94+
);
95+
send(
96+
&mut server,
97+
event(
98+
methods::EVENT_PROCESS_EXIT,
99+
json!({"processId": 5, "exitCode": 2, "signal": null}),
100+
8,
101+
),
102+
);
103+
}
104+
continue;
105+
}
106+
// The attach owns the process: its end releases it as a run does.
107+
methods::PROCESS_KILL => Value::Null,
108+
methods::SERVER_SHUTDOWN => {
109+
send(&mut server, Message::success(id, Value::Null));
110+
break;
111+
}
112+
other => panic!("unexpected method {other}"),
113+
};
114+
send(&mut server, Message::success(id, result));
115+
}
116+
let _ = done.send(());
117+
}
118+
119+
/// Runs `remote.attachProcess` and returns its response with the remote
120+
/// events it relayed.
121+
fn attach(session_id: &str, process_id: u64) -> (Value, Vec<Value>) {
122+
let relayed = Arc::new(Mutex::new(Vec::new()));
123+
let records = Arc::clone(&relayed);
124+
let response = crate::execute_json_with_events(
125+
&json!({"id": test_support::unique_id(), "command": "remote.attachProcess",
126+
"timeoutMilliseconds": 30_000,
127+
"payload": {"sessionId": session_id, "processId": process_id}})
128+
.to_string(),
129+
Arc::new(move |raw: &str| {
130+
let event: Value = serde_json::from_str(raw).unwrap();
131+
if event["type"] == "remote" {
132+
records.lock().unwrap().push(event);
133+
}
134+
}),
135+
);
136+
let events = relayed.lock().unwrap().clone();
137+
(serde_json::from_str(&response).unwrap(), events)
138+
}
139+
140+
fn output(event: &Value) -> Vec<u8> {
141+
methods::decode_bytes(event["params"]["data"].as_str().unwrap()).unwrap()
142+
}
143+
144+
#[test]
145+
fn attaching_after_a_reconnection_relays_what_each_process_did_meanwhile() {
146+
let (client, server) = UnixStream::pair().unwrap();
147+
server.set_read_timeout(Some(STEP)).unwrap();
148+
server.set_write_timeout(Some(STEP)).unwrap();
149+
let socket = client.try_clone().unwrap();
150+
let (done, finished) = mpsc::channel();
151+
let host = std::thread::spawn(move || scripted_host(server, done));
152+
let (session, events) = RemoteSession::from_streams(
153+
client.try_clone().unwrap(),
154+
client,
155+
&ConnectOptions {
156+
handshake_timeout: STEP,
157+
resume: ResumeMode::Deferred,
158+
..ConnectOptions::default()
159+
},
160+
)
161+
.unwrap();
162+
session.park("process");
163+
drop(events);
164+
assert!(!session.resume(Some(4)).unwrap().truncated);
165+
let id = test_support::register_in_process_with(
166+
session,
167+
History {
168+
resumed: true,
169+
complete: true,
170+
},
171+
);
172+
173+
// Exited meanwhile: its output and exit, then the request ends.
174+
let (response, relayed) = attach(&id, 3);
175+
assert_eq!(response["ok"], true, "{response}");
176+
assert_eq!(response["data"]["exitCode"], 0, "{response}");
177+
let names: Vec<_> = relayed.iter().map(|event| &event["event"]).collect();
178+
assert_eq!(
179+
names,
180+
["process.attached", "process.output", "process.exit"],
181+
"{relayed:?}"
182+
);
183+
assert_eq!(
184+
relayed[0]["params"],
185+
json!({"processId": 3, "truncated": false})
186+
);
187+
assert_eq!(output(&relayed[1]), b"while away\n");
188+
189+
// Its attach ended, so nothing keeps its events any more.
190+
let (again, _) = attach(&id, 3);
191+
assert_eq!(again["error"]["code"], "remote_process_gone", "{again}");
192+
193+
// Quiet since the reconnection: the host confirms it runs, then its
194+
// live output follows.
195+
let (response, relayed) = attach(&id, 5);
196+
assert_eq!(response["data"]["exitCode"], 2, "{response}");
197+
assert_eq!(relayed.len(), 3, "{relayed:?}");
198+
assert_eq!(relayed[0]["event"], "process.attached");
199+
assert_eq!(output(&relayed[1]), b"live\n");
200+
201+
// Ended before what this Core received, and created by this connection.
202+
for process_id in [6, 7] {
203+
let (gone, relayed) = attach(&id, process_id);
204+
assert_eq!(gone["error"]["code"], "remote_process_gone", "{gone}");
205+
assert!(relayed.is_empty(), "{relayed:?}");
206+
}
207+
208+
test_support::unregister(&id);
209+
let (unknown, _) = attach(&id, 5);
210+
assert_eq!(unknown["error"]["code"], "connection_closed", "{unknown}");
211+
finished.recv_timeout(STEP).expect("the host finished");
212+
let _ = socket.shutdown(Shutdown::Both);
213+
host.join().unwrap();
214+
}
215+
216+
#[test]
217+
fn a_connection_that_resumed_nothing_has_no_process_to_attach_to() {
218+
let (client, server) = UnixStream::pair().unwrap();
219+
server.set_read_timeout(Some(STEP)).unwrap();
220+
server.set_write_timeout(Some(STEP)).unwrap();
221+
let worker = std::thread::spawn(move || {
222+
let _ = lithe_remote::server::serve_stdio(server.try_clone().unwrap(), server);
223+
});
224+
let (session, events) = RemoteSession::from_streams(
225+
client.try_clone().unwrap(),
226+
client,
227+
&ConnectOptions {
228+
handshake_timeout: STEP,
229+
..ConnectOptions::default()
230+
},
231+
)
232+
.unwrap();
233+
drop(events);
234+
let id = test_support::register_in_process(session);
235+
let (gone, _) = attach(&id, 1);
236+
assert_eq!(gone["error"]["code"], "remote_process_gone", "{gone}");
237+
test_support::unregister(&id);
238+
worker.join().unwrap();
239+
}

‎rust/crates/protocol/src/error.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,14 @@ pub enum ErrorCode {
104104
/// started: building runs the folder's code on this machine. Trusting the
105105
/// folder and repeating the request builds it.
106106
DevcontainerUntrustedFolder,
107+
/// `remote.attachProcess` names a process the host session no longer
108+
/// runs and whose events are gone, or the connection did not resume the
109+
/// session that started it. Nothing was attached; its output ends here.
110+
RemoteProcessGone,
111+
/// `remote.attachProcess` names a process whose events another request
112+
/// already receives: the `remote.runProcess` that started it on this
113+
/// connection, or an earlier `remote.attachProcess`. Nothing changed.
114+
RemoteProcessAttached,
107115
/// A failure does not fit a more stable cross-platform category.
108116
Unknown,
109117
}

‎rust/crates/remote/src/client/mod.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
//! so a host that asks for a password asks only once. The host itself
1818
//! verifies the installed binary and its directories.
1919
//! - [`session`] starts the server, exchanges protocol messages with it and
20-
//! routes each resource's events to its subscriber.
20+
//! routes each resource's events to its subscriber, or keeps them for a
21+
//! reconnecting client until it attaches to the resource.
2122
//! - [`api`] offers typed operations and resource handles on a session.
2223
//! - [`forward`] forwards local ports through tunnels.
2324
//! - [`host_forward`] makes the host listen: relaying to another server, or
@@ -65,6 +66,7 @@ pub mod motty;
6566
pub mod port_records;
6667
pub mod preferences;
6768
pub mod prompt;
69+
mod routes;
6870
pub mod session;
6971
pub mod ssh_config;
7072
pub mod transport;

0 commit comments

Comments
 (0)