1use serde::Serialize;
36use std::collections::VecDeque;
37use std::io::{BufRead, BufReader};
38use std::net::TcpStream;
39use std::path::PathBuf;
40use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio};
41use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
42use std::sync::{Arc, Condvar, Mutex, MutexGuard};
43use std::time::{Duration, Instant};
44use tungstenite::Message;
45
46pub const PROTOCOL: u32 = 1;
48pub const READY_PREFIX: &str = "BREP-STREAM-READY ";
50
51#[derive(Debug)]
53pub enum Error {
54 Launch(String),
56 Connection(String),
58 Refused { code: String, message: String },
60 Timeout(String),
62}
63
64impl std::fmt::Display for Error {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 match self {
67 Error::Launch(m) => write!(f, "launch: {m}"),
68 Error::Connection(m) => write!(f, "connection: {m}"),
69 Error::Refused { code, message } => write!(f, "refused ({code}): {message}"),
70 Error::Timeout(m) => write!(f, "timed out: {m}"),
71 }
72 }
73}
74
75impl std::error::Error for Error {}
76
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
80pub struct Mods {
81 #[serde(rename = "c")]
82 pub ctrl: bool,
83 #[serde(rename = "s")]
84 pub shift: bool,
85 #[serde(rename = "a")]
86 pub alt: bool,
87 #[serde(rename = "m")]
88 pub meta: bool,
89}
90
91impl Mods {
92 pub const NONE: Mods = Mods { ctrl: false, shift: false, alt: false, meta: false };
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum PointerButton {
97 Primary,
98 Secondary,
99 Middle,
100 Back,
101 Forward,
102}
103
104impl PointerButton {
105 fn code(self) -> u8 {
106 match self {
107 PointerButton::Primary => 0,
108 PointerButton::Secondary => 1,
109 PointerButton::Middle => 2,
110 PointerButton::Back => 3,
111 PointerButton::Forward => 4,
112 }
113 }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum WheelUnit {
119 Pixel,
120 Line,
121 Page,
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum TouchPhase {
126 Start,
127 Move,
128 End,
129 Cancel,
130}
131
132#[derive(Debug, Clone, PartialEq)]
135pub enum Input {
136 PointerMove { x: f32, y: f32 },
137 Button { x: f32, y: f32, button: PointerButton, down: bool, mods: Mods },
138 PointerLeave,
140 Wheel { dx: f32, dy: f32, unit: WheelUnit, mods: Mods },
143 Key { key: String, down: bool, repeat: bool, mods: Mods },
148 Text(String),
150 Paste(String),
152 ImePreedit(String),
154 ImeCommit(String),
156 Touch { id: u64, phase: TouchPhase, x: f32, y: f32, force: Option<f32> },
157 Focus(bool),
159}
160
161impl Input {
162 fn message(&self) -> serde_json::Value {
163 use serde_json::json;
164 match self {
165 Input::PointerMove { x, y } => json!({"t": "pm", "x": x, "y": y}),
166 Input::Button { x, y, button, down, mods } => json!({"t": "pb", "x": x, "y": y, "b": button.code(), "down": down, "mods": mods}),
167 Input::PointerLeave => json!({"t": "leave"}),
168 Input::Wheel { dx, dy, unit, mods } => {
169 let mode = match unit {
170 WheelUnit::Pixel => 0,
171 WheelUnit::Line => 1,
172 WheelUnit::Page => 2,
173 };
174 json!({"t": "wheel", "dx": dx, "dy": dy, "mode": mode, "mods": mods})
175 }
176 Input::Key { key, down, repeat, mods } => json!({"t": "key", "key": key, "code": "", "down": down, "repeat": repeat, "mods": mods}),
177 Input::Text(s) => json!({"t": "text", "s": s}),
178 Input::Paste(s) => json!({"t": "paste", "s": s}),
179 Input::ImePreedit(s) => json!({"t": "ime", "phase": "update", "s": s}),
180 Input::ImeCommit(s) => json!({"t": "ime", "phase": "commit", "s": s}),
181 Input::Touch { id, phase, x, y, force } => {
182 let phase = match phase {
183 TouchPhase::Start => "start",
184 TouchPhase::Move => "move",
185 TouchPhase::End => "end",
186 TouchPhase::Cancel => "cancel",
187 };
188 json!({"t": "touch", "id": id, "phase": phase, "x": x, "y": y, "force": force})
189 }
190 Input::Focus(on) => json!({"t": "focus", "on": on}),
191 }
192 }
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub enum Role {
199 Control,
200 View,
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub struct Rect {
206 pub x: u32,
207 pub y: u32,
208 pub width: u32,
209 pub height: u32,
210}
211
212impl Rect {
213 fn union(self, o: Rect) -> Rect {
214 let (x0, y0) = (self.x.min(o.x), self.y.min(o.y));
215 let x1 = (self.x + self.width).max(o.x + o.width);
216 let y1 = (self.y + self.height).max(o.y + o.height);
217 Rect { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }
218 }
219}
220
221#[derive(Debug, Clone, PartialEq)]
223pub enum Event {
224 Cursor(String),
227 Clipboard(String),
229 OpenUrl { url: String, new_tab: bool },
231 Role(Role),
233 ImeArea(Option<[f32; 4]>),
236 Closed(String),
238 Other(serde_json::Value),
240}
241
242#[derive(Debug, Clone, Default)]
244pub struct Frame {
245 pub width: u32,
247 pub height: u32,
248 pub rgba: Vec<u8>,
250 pub seq: u32,
252 pub frames: u64,
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct Update {
259 pub resized: bool,
261 pub dirty: Rect,
263}
264
265#[derive(Debug, Clone)]
267pub struct ConnectOptions {
268 pub role: Role,
269 pub width: f32,
272 pub height: f32,
273 pub density: f32,
274 pub timeout: Duration,
276}
277
278impl Default for ConnectOptions {
279 fn default() -> Self {
280 ConnectOptions { role: Role::Control, width: 1280.0, height: 800.0, density: 1.0, timeout: Duration::from_secs(20) }
281 }
282}
283
284type Waker = Box<dyn Fn() + Send + Sync>;
285
286struct Shared {
287 frame: Mutex<Frame>,
288 dirty: Mutex<Option<Update>>,
289 events: Mutex<VecDeque<Event>>,
290 role: Mutex<Role>,
291 closed: Mutex<Option<String>>,
292 changed: Condvar,
293 waker: Mutex<Option<Waker>>,
294 size: Mutex<(f32, f32, f32)>,
297}
298
299impl Shared {
300 fn wake(&self) {
301 self.changed.notify_all();
302 if let Some(w) = self.waker.lock().unwrap().as_ref() {
303 w();
304 }
305 }
306
307 fn event(&self, e: Event) {
308 self.events.lock().unwrap().push_back(e);
309 self.wake();
310 }
311}
312
313pub struct Client {
316 out: Sender<String>,
317 shared: Arc<Shared>,
318 session: String,
319 dropped: Arc<std::sync::atomic::AtomicBool>,
323}
324
325impl Drop for Client {
326 fn drop(&mut self) {
327 self.dropped.store(true, std::sync::atomic::Ordering::SeqCst);
328 }
329}
330
331const IO_POLL: Duration = Duration::from_millis(2);
334
335impl Client {
336 pub fn connect(url: &str, token: &str, options: ConnectOptions) -> Result<Client, Error> {
340 let url = if url.starts_with("ws://") || url.starts_with("wss://") { url.to_string() } else { format!("ws://{url}/stream/ws") };
341 if url.starts_with("wss://") {
342 return Err(Error::Connection("wss:// is not supported; reach a remote session through a tunnel or a proxy that ends TLS".into()));
343 }
344 let (mut ws, _) = tungstenite::connect(url.as_str()).map_err(|e| Error::Connection(format!("{url}: {e}")))?;
345 let tungstenite::stream::MaybeTlsStream::Plain(stream) = ws.get_ref() else {
346 return Err(Error::Connection("not a plain TCP stream".into()));
347 };
348 stream.set_nodelay(true).ok();
349 stream.set_read_timeout(Some(Duration::from_millis(50))).map_err(|e| Error::Connection(e.to_string()))?;
350 let role = match options.role {
351 Role::Control => "control",
352 Role::View => "view",
353 };
354 let hello = serde_json::json!({"t": "hello", "v": PROTOCOL, "token": token, "role": role, "w": options.width, "h": options.height, "dpr": options.density});
355 ws.send(Message::Text(hello.to_string())).map_err(|e| Error::Connection(e.to_string()))?;
356 let start = Instant::now();
357 let welcome: serde_json::Value = loop {
358 if start.elapsed() > options.timeout {
359 return Err(Error::Timeout("no welcome from the server".into()));
360 }
361 match ws.read() {
362 Ok(Message::Text(t)) => break serde_json::from_str(&t).map_err(|e| Error::Connection(e.to_string()))?,
363 Ok(Message::Close(_)) => return Err(Error::Connection("the server closed the connection".into())),
364 Ok(_) => {}
365 Err(tungstenite::Error::Io(e)) if would_block(&e) => {}
366 Err(e) => return Err(Error::Connection(e.to_string())),
367 }
368 };
369 if welcome["t"] == "error" {
370 return Err(Error::Refused { code: welcome["code"].as_str().unwrap_or("").into(), message: welcome["msg"].as_str().unwrap_or("").into() });
371 }
372 if welcome["t"] != "welcome" {
373 return Err(Error::Connection(format!("expected a welcome, got {welcome}")));
374 }
375 if let tungstenite::stream::MaybeTlsStream::Plain(stream) = ws.get_ref() {
376 stream.set_read_timeout(Some(IO_POLL)).map_err(|e| Error::Connection(e.to_string()))?;
377 }
378 let role = if welcome["role"] == "control" { Role::Control } else { Role::View };
379 let shared = Arc::new(Shared {
380 frame: Mutex::new(Frame::default()),
381 dirty: Mutex::new(None),
382 events: Mutex::new(VecDeque::new()),
383 role: Mutex::new(role),
384 closed: Mutex::new(None),
385 changed: Condvar::new(),
386 waker: Mutex::new(None),
387 size: Mutex::new((options.width, options.height, options.density)),
388 });
389 let (out_tx, out_rx) = mpsc::channel::<String>();
390 let (frame_tx, frame_rx) = mpsc::channel::<Vec<u8>>();
391 {
394 let shared = shared.clone();
395 let out = out_tx.clone();
396 std::thread::Builder::new()
397 .name("brep-stream-decode".into())
398 .spawn(move || decode_loop(frame_rx, &shared, &out))
399 .map_err(|e| Error::Connection(e.to_string()))?;
400 }
401 let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
402 {
403 let (shared, dropped) = (shared.clone(), dropped.clone());
404 std::thread::Builder::new()
405 .name("brep-stream-io".into())
406 .spawn(move || io_loop(ws, out_rx, frame_tx, &shared, &dropped))
407 .map_err(|e| Error::Connection(e.to_string()))?;
408 }
409 Ok(Client { out: out_tx, shared, session: welcome["session"].as_str().unwrap_or("").to_string(), dropped })
410 }
411
412 pub fn session_id(&self) -> &str {
414 &self.session
415 }
416
417 pub fn send(&self, input: Input) {
419 let _ = self.out.send(input.message().to_string());
420 }
421
422 pub fn resize(&self, width: f32, height: f32, density: f32) {
425 *self.shared.size.lock().unwrap() = (width, height, density);
426 let _ = self.out.send(serde_json::json!({"t": "resize", "w": width, "h": height, "dpr": density}).to_string());
427 }
428
429 pub fn take_control(&self) {
431 let _ = self.out.send(serde_json::json!({"t": "take_control"}).to_string());
432 }
433
434 pub fn set_quality(&self, jpeg: u8) {
436 let _ = self.out.send(serde_json::json!({"t": "quality", "jpeg": jpeg}).to_string());
437 }
438
439 pub fn role(&self) -> Role {
440 *self.shared.role.lock().unwrap()
441 }
442
443 pub fn closed(&self) -> Option<String> {
445 self.shared.closed.lock().unwrap().clone()
446 }
447
448 pub fn set_waker(&self, waker: impl Fn() + Send + Sync + 'static) {
451 *self.shared.waker.lock().unwrap() = Some(Box::new(waker));
452 }
453
454 pub fn frame(&self) -> MutexGuard<'_, Frame> {
456 self.shared.frame.lock().unwrap()
457 }
458
459 pub fn take_update(&self) -> Option<Update> {
461 self.shared.dirty.lock().unwrap().take()
462 }
463
464 pub fn poll_events(&self) -> Vec<Event> {
466 self.shared.events.lock().unwrap().drain(..).collect()
467 }
468
469 pub fn wait_frame(&self, timeout: Duration) -> Result<(), Error> {
471 let start = Instant::now();
472 let mut frame = self.shared.frame.lock().unwrap();
473 let seen = frame.frames;
474 while frame.frames == seen {
475 if let Some(why) = self.closed() {
476 return Err(Error::Connection(why));
477 }
478 let left = timeout.checked_sub(start.elapsed()).ok_or_else(|| Error::Timeout("no frame".into()))?;
479 frame = self.shared.changed.wait_timeout(frame, left.min(Duration::from_millis(200))).unwrap().0;
480 }
481 Ok(())
482 }
483
484 pub fn wait_still(&self, quiet: Duration, timeout: Duration) -> Result<(), Error> {
487 let start = Instant::now();
488 loop {
489 let frames = self.frame().frames;
490 std::thread::sleep(quiet);
491 if self.frame().frames == frames && frames > 0 {
492 return Ok(());
493 }
494 if let Some(why) = self.closed() {
495 return Err(Error::Connection(why));
496 }
497 if start.elapsed() > timeout {
498 return Err(Error::Timeout("the picture never went still".into()));
499 }
500 }
501 }
502}
503
504fn would_block(e: &std::io::Error) -> bool {
505 matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)
506}
507
508fn io_loop(
509 mut ws: tungstenite::WebSocket<tungstenite::stream::MaybeTlsStream<TcpStream>>,
510 out: Receiver<String>,
511 frames: Sender<Vec<u8>>,
512 shared: &Shared,
513 dropped: &std::sync::atomic::AtomicBool,
514) {
515 let why = loop {
516 if dropped.load(std::sync::atomic::Ordering::SeqCst) {
517 let _ = ws.close(None);
520 let _ = ws.flush();
521 return;
522 }
523 let mut gone = false;
525 loop {
526 match out.try_recv() {
527 Ok(text) => {
528 if ws.write(Message::Text(text)).is_err() {
529 gone = true;
530 break;
531 }
532 }
533 Err(mpsc::TryRecvError::Empty) => break,
534 Err(mpsc::TryRecvError::Disconnected) => {
536 let _ = ws.close(None);
537 let _ = ws.flush();
538 return;
539 }
540 }
541 }
542 if gone || ws.flush().is_err() {
543 break "the connection broke".to_string();
544 }
545 match ws.read() {
546 Ok(Message::Binary(m)) => {
547 if frames.send(m).is_err() {
548 break "closed".to_string();
549 }
550 }
551 Ok(Message::Text(t)) => {
552 if let Ok(v) = serde_json::from_str::<serde_json::Value>(&t) {
553 if v["t"] == "role" && v["role"] == "control" {
554 let (w, h, dpr) = *shared.size.lock().unwrap();
556 let _ = ws.write(Message::Text(serde_json::json!({"t": "resize", "w": w, "h": h, "dpr": dpr}).to_string()));
557 }
558 control(&v, shared);
559 }
560 }
561 Ok(Message::Close(frame)) => break frame.map(|f| f.reason.to_string()).filter(|r| !r.is_empty()).unwrap_or_else(|| "the server closed the session".into()),
562 Ok(_) => {}
563 Err(tungstenite::Error::Io(e)) if would_block(&e) => {}
564 Err(e) => break e.to_string(),
565 }
566 };
567 *shared.closed.lock().unwrap() = Some(why.clone());
568 shared.event(Event::Closed(why));
569}
570
571fn control(v: &serde_json::Value, shared: &Shared) {
572 let s = |k: &str| v[k].as_str().unwrap_or("").to_string();
573 let event = match v["t"].as_str().unwrap_or("") {
574 "cursor" => Event::Cursor(s("css")),
575 "clipboard" => Event::Clipboard(s("s")),
576 "open_url" => Event::OpenUrl { url: s("url"), new_tab: v["new_tab"].as_bool().unwrap_or(true) },
577 "role" => {
578 let role = if v["role"] == "control" { Role::Control } else { Role::View };
579 *shared.role.lock().unwrap() = role;
580 Event::Role(role)
581 }
582 "ime_area" => {
583 let f = |k: &str| v[k].as_f64().map(|x| x as f32);
584 Event::ImeArea(match (f("x"), f("y"), f("w"), f("h")) {
585 (Some(x), Some(y), Some(w), Some(h)) => Some([x, y, w, h]),
586 _ => None,
587 })
588 }
589 _ => Event::Other(v.clone()),
590 };
591 shared.event(event);
592}
593
594fn decode_loop(frames: Receiver<Vec<u8>>, shared: &Shared, out: &Sender<String>) {
595 while let Ok(m) = frames.recv() {
596 match apply(&m, shared) {
597 Ok(seq) => {
598 let _ = out.send(serde_json::json!({"t": "ack", "seq": seq}).to_string());
599 shared.wake();
600 }
601 Err(e) => shared.event(Event::Other(serde_json::json!({"t": "decode_error", "msg": e}))),
602 }
603 }
604}
605
606fn apply(m: &[u8], shared: &Shared) -> Result<u32, String> {
608 let u16_at = |o: usize| -> Result<u32, String> { m.get(o..o + 2).map(|b| u16::from_le_bytes([b[0], b[1]]) as u32).ok_or("short frame".to_string()) };
609 if m.len() < 12 || m[0] != 1 {
610 return Err("not a frame".into());
611 }
612 let n = u16_at(2)? as usize;
613 let seq = u32::from_le_bytes([m[4], m[5], m[6], m[7]]);
614 let (w, h) = (u16_at(8)?, u16_at(10)?);
615 let mut tiles = Vec::with_capacity(n);
617 let mut off = 12;
618 for _ in 0..n {
619 let (x, y, tw, th) = (u16_at(off)?, u16_at(off + 2)?, u16_at(off + 4)?, u16_at(off + 6)?);
620 let codec = *m.get(off + 8).ok_or("short frame")?;
621 let len = m.get(off + 10..off + 14).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).ok_or("short frame")?;
622 off += 14;
623 let bytes = m.get(off..off + len).ok_or("short frame")?;
624 off += len;
625 let format = if codec == 2 { image::ImageFormat::Jpeg } else { image::ImageFormat::Png };
626 let tile = image::load_from_memory_with_format(bytes, format).map_err(|e| e.to_string())?.to_rgba8();
627 if (tile.width(), tile.height()) != (tw, th) || x + tw > w || y + th > h {
628 return Err("a tile does not fit the frame".into());
629 }
630 tiles.push((x, y, tile));
631 }
632 let mut frame = shared.frame.lock().unwrap();
633 let resized = (frame.width, frame.height) != (w, h);
634 if resized {
635 *frame = Frame { width: w, height: h, rgba: vec![0; (w * h * 4) as usize], seq: frame.seq, frames: frame.frames };
636 }
637 let mut dirty: Option<Rect> = None;
638 for (x, y, tile) in &tiles {
639 let (tw, th) = (tile.width(), tile.height());
640 for row in 0..th {
641 let dst = (((y + row) * w + x) * 4) as usize;
642 let src = (row * tw * 4) as usize;
643 frame.rgba[dst..dst + (tw * 4) as usize].copy_from_slice(&tile.as_raw()[src..src + (tw * 4) as usize]);
644 }
645 let r = Rect { x: *x, y: *y, width: tw, height: th };
646 dirty = Some(dirty.map_or(r, |d| d.union(r)));
647 }
648 frame.seq = seq;
649 frame.frames += 1;
650 drop(frame);
651 let mut held = shared.dirty.lock().unwrap();
652 let full = Rect { x: 0, y: 0, width: w, height: h };
653 *held = match (*held, resized, dirty) {
654 (_, true, _) => Some(Update { resized: true, dirty: full }),
655 (Some(u), false, Some(d)) => Some(Update { resized: u.resized, dirty: if u.resized { full } else { u.dirty.union(d) } }),
656 (None, false, Some(d)) => Some(Update { resized: false, dirty: d }),
657 (held, false, None) => held,
658 };
659 Ok(seq)
660}
661
662pub struct Launcher {
664 command: Command,
665 options: ConnectOptions,
666 ready_timeout: Duration,
667}
668
669impl Launcher {
670 pub fn new(program: impl AsRef<std::ffi::OsStr>) -> Launcher {
672 Launcher::from_command(Command::new(program))
673 }
674
675 pub fn from_command(command: Command) -> Launcher {
679 Launcher { command, options: ConnectOptions::default(), ready_timeout: Duration::from_secs(120) }
680 }
681
682 pub fn size(mut self, width: f32, height: f32, density: f32) -> Launcher {
684 (self.options.width, self.options.height, self.options.density) = (width, height, density);
685 self
686 }
687
688 pub fn ready_timeout(mut self, timeout: Duration) -> Launcher {
690 self.ready_timeout = timeout;
691 self
692 }
693
694 pub fn launch(mut self) -> Result<Session, Error> {
696 let token_file = std::env::temp_dir().join(format!(
697 "brep-stream-{}-{}.token",
698 std::process::id(),
699 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
700 ));
701 self.command
702 .args(["--stream", "127.0.0.1:0", "--stream-until-stdin-closes", "--stream-token-file"])
703 .arg(&token_file)
704 .stdin(Stdio::piped())
705 .stdout(Stdio::piped());
706 let mut child = self.command.spawn().map_err(|e| Error::Launch(format!("{:?}: {e}", self.command.get_program())))?;
707 let stdin = child.stdin.take();
708 let stdout = child.stdout.take().ok_or_else(|| Error::Launch("no stdout".into()))?;
709 let (ready_tx, ready_rx) = mpsc::channel::<Result<serde_json::Value, String>>();
712 std::thread::Builder::new()
713 .name("brep-stream-stdout".into())
714 .spawn(move || {
715 let mut ready = Some(ready_tx);
716 for line in BufReader::new(stdout).lines() {
717 let Ok(line) = line else { break };
718 if let (Some(rest), Some(tx)) = (line.strip_prefix(READY_PREFIX), ready.as_ref()) {
719 let _ = tx.send(serde_json::from_str(rest).map_err(|e| e.to_string()));
720 ready = None;
721 }
722 }
723 if let Some(tx) = ready {
724 let _ = tx.send(Err("the app ended before it was ready".into()));
725 }
726 })
727 .map_err(|e| Error::Launch(e.to_string()))?;
728 let mut session = Session { child: Some(child), stdin, client: None, token_file: token_file.clone(), url: String::new(), token: String::new() };
729 let ready = match ready_rx.recv_timeout(self.ready_timeout) {
730 Ok(Ok(ready)) => ready,
731 Ok(Err(why)) => return Err(Error::Launch(format!("{why} ({})", session.exit_note()))),
732 Err(RecvTimeoutError::Timeout) => return Err(Error::Timeout(format!("the app was not ready in {} s", self.ready_timeout.as_secs()))),
733 Err(RecvTimeoutError::Disconnected) => return Err(Error::Launch("the app's output closed".into())),
734 };
735 let ws = ready["ws"].as_str().ok_or_else(|| Error::Launch(format!("a ready line without `ws`: {ready}")))?.to_string();
736 let token = std::fs::read_to_string(&token_file).map_err(|e| Error::Launch(format!("token file {}: {e}", token_file.display())))?;
737 let _ = std::fs::remove_file(&token_file);
738 session.client = Some(Client::connect(&ws, token.trim(), self.options)?);
739 (session.url, session.token) = (ws, token.trim().to_string());
740 Ok(session)
741 }
742}
743
744pub struct Session {
748 child: Option<Child>,
749 stdin: Option<ChildStdin>,
750 client: Option<Client>,
751 token_file: PathBuf,
752 url: String,
753 token: String,
754}
755
756impl Session {
757 pub fn url(&self) -> &str {
760 &self.url
761 }
762
763 pub fn token(&self) -> &str {
765 &self.token
766 }
767
768 pub fn pid(&self) -> Option<u32> {
770 self.child.as_ref().map(Child::id)
771 }
772
773 pub fn shutdown(mut self, timeout: Duration) -> std::io::Result<ExitStatus> {
775 self.end(timeout)
776 }
777
778 fn end(&mut self, timeout: Duration) -> std::io::Result<ExitStatus> {
779 self.client = None;
780 drop(self.stdin.take());
781 let Some(mut child) = self.child.take() else {
782 return Err(std::io::Error::other("already ended"));
783 };
784 let start = Instant::now();
785 loop {
786 if let Some(status) = child.try_wait()? {
787 return Ok(status);
788 }
789 if start.elapsed() > timeout {
790 child.kill()?;
791 return child.wait();
792 }
793 std::thread::sleep(Duration::from_millis(20));
794 }
795 }
796
797 fn exit_note(&mut self) -> String {
798 match self.child.as_mut().map(Child::try_wait) {
799 Some(Ok(Some(status))) => format!("it exited: {status}"),
800 _ => "it is still running".into(),
801 }
802 }
803}
804
805impl std::ops::Deref for Session {
806 type Target = Client;
807 fn deref(&self) -> &Client {
808 self.client.as_ref().expect("a launched session is connected")
809 }
810}
811
812impl Drop for Session {
813 fn drop(&mut self) {
814 let _ = self.end(Duration::from_secs(15));
815 let _ = std::fs::remove_file(&self.token_file);
816 }
817}
818