|
| 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 | +} |
0 commit comments