From 00a70b8c6f063fe687c9e12c517841fcca60d686 Mon Sep 17 00:00:00 2001 From: oppiliappan Date: Sun, 18 Oct 2026 09:28:19 +0100 Subject: [PATCH] cleanup Signed-off-by: oppiliappan --- Cargo.lock | 18 -- Cargo.toml | 34 --- crates/protocol/src/codec.rs | 62 +++--- crates/protocol/src/json.rs | 25 --- crates/protocol/src/lib.rs | 41 ++-- crates/protocol/src/message.rs | 122 ++++++++++- crates/protocol/src/methods.rs | 148 ++++++++++--- crates/tarp/src/config.rs | 322 ++--------------------------- crates/tarp/src/main.rs | 203 ++++++------------ crates/tarp/src/session.rs | 85 +++----- crates/tarp/src/terminal.rs | 16 +- crates/tarp/src/title_bar.rs | 8 - crates/tarpc/src/error.rs | 3 - crates/tarpc/src/lib.rs | 113 ++++------ crates/tarpc/tests/daemon.rs | 12 +- crates/tarpd/src/config.rs | 68 +++--- crates/tarpd/src/daemon.rs | 70 ++----- crates/tarpd/src/extensions/mod.rs | 8 +- crates/tarpd/src/outbox.rs | 68 +++--- crates/tarpd/src/scripts.rs | 205 +++++------------- crates/tarpd/src/server.rs | 67 +++--- crates/tarpd/src/shell.rs | 8 +- crates/tarpd/src/snapshot.rs | 28 ++- crates/tarpd/src/state.rs | 35 ---- crates/tarpd/src/terminal.rs | 167 ++++----------- crates/tarpd/src/world.rs | 133 +++--------- crates/transport/src/addr.rs | 7 +- crates/transport/src/allow.rs | 22 +- crates/transport/src/identity.rs | 35 +--- crates/transport/src/lib.rs | 23 ++- crates/transport/src/paths.rs | 87 ++++---- crates/transport/src/settings.rs | 12 +- crates/vtgen/Cargo.toml | 17 -- crates/vtgen/src/bin/vtgen.rs | 135 ------------ crates/vtgen/src/lib.rs | 321 ---------------------------- 35 files changed, 775 insertions(+), 1953 deletions(-) delete mode 100644 crates/vtgen/Cargo.toml delete mode 100644 crates/vtgen/src/bin/vtgen.rs delete mode 100644 crates/vtgen/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 09fcdab..e0d9794 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6136,15 +6136,6 @@ dependencies = [ "rand_core 0.9.5", ] -[[package]] -name = "rand_xoshiro" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f703f4665700daf5512dcca5f43afa6af89f09db47fb56be587f80636bda2d41" -dependencies = [ - "rand_core 0.9.5", -] - [[package]] name = "range-alloc" version = "0.1.5" @@ -8348,15 +8339,6 @@ dependencies = [ "libc", ] -[[package]] -name = "vtgen" -version = "0.1.0" -dependencies = [ - "anyhow", - "rand 0.9.5", - "rand_xoshiro", -] - [[package]] name = "wait-timeout" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index d489ec4..728811c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,6 @@ members = [ "crates/tarpd", "crates/protocol", "crates/transport", - "crates/vtgen", ] [workspace.package] @@ -21,7 +20,6 @@ gpui-canvas = { path = "../gpui-canvas" } gpui-terminal = { path = "../gpui-terminal" } protocol = { path = "crates/protocol" } transport = { path = "crates/transport" } -vtgen = { path = "crates/vtgen" } gpui = { package = "gpui-unofficial", version = "1.23.2", default-features = false } gpui_platform = { package = "gpui-platform-gpui-unofficial", version = "1.23.2", features = [ @@ -29,9 +27,6 @@ gpui_platform = { package = "gpui-platform-gpui-unofficial", version = "1.23.2", "font-kit", ] } libghostty-vt = { version = "0.2.1", features = ["tracing"] } -# The Lua VM the daemon embeds. `vendored` builds Lua from source so no system -# Lua is needed; `send` makes the VM `Send`, which the daemon needs because it -# lives inside `Arc>`. mlua = { version = "0.10", features = ["lua54", "vendored", "send"] } anyhow = "1" @@ -39,30 +34,11 @@ base64 = "0.22" clap = { version = "4", features = ["derive"] } confique = { version = "0.4", features = ["toml"] } dirs = "6" -# Pinned to the version gpui's own benchmark harness uses. The `render` bench -# is built on `#[gpui::bench]`, which hands gpui a `criterion::Bencher` -- two -# criterion versions in the graph make that a type mismatch rather than a -# link error, so this has to track gpui's. -criterion = { version = "0.8.2", default-features = false, features = [ - "cargo_bench_support", -] } futures = "0.3" iroh = "1.3" -itertools = "0.14" libc = "0.2" -# The vendored terminal logs through `log`; `tracing_subscriber::fmt` picks -# those records up through its `tracing-log` bridge, so they land in the same -# place as everything else. -log = "0.4" -parking_lot = "0.12" -percent-encoding = "2.3" portable-pty = "0.9" postcard = { version = "1", features = ["use-std"] } -proptest = "1.11" -proptest-derive = { version = "0.8", features = ["boxed_union"] } -rand = "0.9" -rand_xoshiro = "0.7" -regex = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" tempfile = "3" @@ -72,14 +48,4 @@ tokio-util = { version = "0.7", features = ["io", "io-util", "rt"] } toml = "0.8" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } -unicode-width = "0.2" -url = "2" -urlencoding = "2.1" uuid = { version = "1", features = ["serde", "v4"] } -vte = { version = "0.15", features = ["ansi"] } - -# Benchmarks get profiled with `sample`, which needs symbols to say anything -# useful. Line tables only: full debug info costs build time without adding -# signal to a sampling profile. -[profile.bench] -debug = 1 diff --git a/crates/protocol/src/codec.rs b/crates/protocol/src/codec.rs index 6b9bedd..3ddcc5b 100644 --- a/crates/protocol/src/codec.rs +++ b/crates/protocol/src/codec.rs @@ -4,6 +4,7 @@ use serde::{Serialize, de::DeserializeOwned}; use crate::ProtocolError; +/// the maximum length of one frame in bytes. pub const MAX_FRAME_LEN: usize = 64 * 1024 * 1024; pub fn write_frame(writer: &mut W, message: &M) -> Result<(), ProtocolError> @@ -21,8 +22,11 @@ where Ok(()) } +/// a reader that reads length-prefixed frames from a stream. pub struct FrameReader { + /// the stream that supplies the frames. reader: R, + /// the buffer that holds the body of the frame that the reader decodes. buf: Vec, } @@ -36,8 +40,15 @@ impl FrameReader { pub fn read(&mut self) -> Result, ProtocolError> { let mut prefix = [0u8; 4]; - if !read_exact_or_eof(&mut self.reader, &mut prefix)? { - return Ok(None); + let mut filled = 0; + while filled < prefix.len() { + match self.reader.read(&mut prefix[filled..]) { + Ok(0) if filled == 0 => return Ok(None), + Ok(0) => return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into()), + Ok(n) => filled += n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(error) => return Err(error.into()), + } } let len = u32::from_be_bytes(prefix) as usize; if len > MAX_FRAME_LEN { @@ -47,36 +58,25 @@ impl FrameReader { self.reader.read_exact(&mut self.buf)?; Ok(Some(postcard::from_bytes(&self.buf)?)) } - - pub fn get_ref(&self) -> &R { - &self.reader - } -} - -fn read_exact_or_eof(reader: &mut R, buf: &mut [u8]) -> io::Result { - let mut filled = 0; - while filled < buf.len() { - match reader.read(&mut buf[filled..]) { - Ok(0) if filled == 0 => return Ok(false), - Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()), - Ok(n) => filled += n, - Err(error) if error.kind() == io::ErrorKind::Interrupted => {} - Err(error) => return Err(error), - } - } - Ok(true) } #[cfg(test)] mod tests { use super::*; - use crate::{ClientFrame, ServerFrame, Welcome}; + use crate::{ClientFrame, Hello, ServerFrame, Welcome}; + + fn hello(name: &str) -> ClientFrame { + ClientFrame::Hello(Hello { + protocol_version: 1, + client_name: name.into(), + }) + } #[test] fn frames_round_trip_back_to_back() { let mut wire = Vec::new(); - write_frame(&mut wire, &ClientFrame::hello("test")).unwrap(); - write_frame(&mut wire, &ClientFrame::hello("second")).unwrap(); + write_frame(&mut wire, &hello("test")).unwrap(); + write_frame(&mut wire, &hello("second")).unwrap(); let mut reader = FrameReader::new(wire.as_slice()); let names: Vec = std::iter::from_fn(|| reader.read::().unwrap()) @@ -88,22 +88,6 @@ mod tests { assert_eq!(names, ["test", "second"]); } - #[test] - fn a_uuid_terminal_id_survives_a_frame() { - let id = uuid::Uuid::new_v4(); - let mut wire = Vec::new(); - write_frame(&mut wire, &ServerFrame::output(id, b"hi".to_vec())).unwrap(); - - let mut reader = FrameReader::new(wire.as_slice()); - match reader.read::().unwrap().unwrap() { - ServerFrame::Output(output) => { - assert_eq!(output.terminal, id); - assert_eq!(output.data, b"hi"); - } - other => panic!("expected output, got {other:?}"), - } - } - #[test] fn a_stream_cut_mid_frame_is_an_error() { let mut wire = Vec::new(); diff --git a/crates/protocol/src/json.rs b/crates/protocol/src/json.rs index 092355a..73ec5ae 100644 --- a/crates/protocol/src/json.rs +++ b/crates/protocol/src/json.rs @@ -6,10 +6,6 @@ use serde_json::Value as Json; use crate::{ProtocolError, Value}; impl Value { - pub fn is_null(&self) -> bool { - matches!(self, Value::Null) - } - pub fn from_serialize(value: &T) -> Result { serde_json::to_value(value)?.try_into() } @@ -79,7 +75,6 @@ impl TryFrom for Json { #[cfg(test)] mod tests { - use serde::Deserialize; use serde_json::json; use super::*; @@ -109,26 +104,6 @@ mod tests { assert!(matches!(items[1], Value::Number(_))); } - #[test] - fn null_deserializes_as_none() { - assert_eq!(Value::Null.deserialize::>().unwrap(), None); - } - - #[test] - fn structs_go_through_value() { - #[derive(Serialize, Deserialize, PartialEq, Debug)] - struct Params { - terminal: u64, - signal: Option, - } - let params = Params { - terminal: 3, - signal: Some("TERM".into()), - }; - let value = Value::from_serialize(¶ms).unwrap(); - assert_eq!(value.deserialize::().unwrap(), params); - } - #[test] fn values_that_do_not_fit_are_refused() { assert!(matches!( diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 950ecf0..8d75536 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -8,36 +8,42 @@ pub use message::*; pub use methods::Method; pub use uuid::Uuid; +/// the version of the protocol that this crate uses. pub const PROTOCOL_VERSION: u32 = 1; +/// the ALPN value that identifies a tarp connection. pub const ALPN: &[u8] = b"tarp/1"; +/// an error that occurs when you encode, decode or convert protocol data. #[derive(Debug, thiserror::Error)] pub enum ProtocolError { + /// the stream gave an input or output error. #[error(transparent)] Io(#[from] std::io::Error), + /// the encoder cannot write the message as a frame. #[error("could not encode a frame: {0}")] Encode(postcard::Error), + /// the decoder cannot read the frame as a message. #[error("could not decode a frame: {0}")] Decode(#[from] postcard::Error), + /// the frame is longer than the maximum frame length. #[error("a frame of {len} bytes exceeds the {MAX_FRAME_LEN} byte limit")] - FrameTooLarge { len: usize }, + FrameTooLarge { + /// the length of the frame in bytes. + len: usize, + }, + /// the value does not agree with the type that you expect. #[error("value does not fit the expected type: {0}")] Value(#[from] serde_json::Error), + /// the float is NaN or infinite, thus JSON cannot show it. #[error("a float that is NaN or infinite has no JSON form")] NonFiniteNumber, + /// the integer is too large for an i64. #[error("an integer that does not fit in i64 cannot be a protocol value")] IntegerOutOfRange, } impl ClientFrame { - pub fn hello(client_name: impl Into) -> Self { - Self::Hello(Hello { - protocol_version: PROTOCOL_VERSION, - client_name: client_name.into(), - }) - } - pub fn request(id: u64, body: RequestBody) -> Self { Self::Request(Request { id, body }) } @@ -59,14 +65,6 @@ impl ClientFrame { }), ) } - - pub fn input(terminal: Uuid, data: Vec) -> Self { - Self::Input(Input { terminal, data }) - } - - pub fn resize(terminal: Uuid, size: Size) -> Self { - Self::Resize(Resize { terminal, size }) - } } impl Response { @@ -100,10 +98,6 @@ impl ServerFrame { Self::Output(Output { terminal, data }) } - pub fn resync(terminal: Uuid, vt: Vec) -> Self { - Self::Resync(Resync { terminal, vt }) - } - pub fn event(name: impl Into, terminal: Option, data: Value) -> Self { Self::Event(Event { name: name.into(), @@ -111,11 +105,4 @@ impl ServerFrame { data, }) } - - pub fn detached(reason: DetachReason, by: impl Into) -> Self { - Self::Detached(Detached { - reason, - by: by.into(), - }) - } } diff --git a/crates/protocol/src/message.rs b/crates/protocol/src/message.rs index f050337..366f324 100644 --- a/crates/protocol/src/message.rs +++ b/crates/protocol/src/message.rs @@ -3,176 +3,280 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use uuid::Uuid; +/// a frame that a client sends to the daemon. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum ClientFrame { + /// the first frame of a connection. Hello(Hello), + /// a request that the daemon must answer. Request(Request), + /// keyboard input for a terminal. Input(Input), + /// a new size for a terminal. Resize(Resize), } +/// a frame that the daemon sends to a client. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum ServerFrame { + /// the answer to the hello of the client. Welcome(Welcome), + /// the answer to a request. Response(Response), + /// an event that the client subscribed to. Event(Event), + /// bytes that a terminal wrote. Output(Output), + /// the full state of a terminal, which replaces the state that the client has. Resync(Resync), + /// the daemon detached the client. Detached(Detached), + /// the daemon closes the connection. Closing(Closing), } +/// the first frame that a client sends. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Hello { + /// the protocol version of the client. pub protocol_version: u32, + /// the name that identifies the client. pub client_name: String, } +/// the answer of the daemon to a hello. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Welcome { + /// the protocol version of the daemon. pub protocol_version: u32, + /// the identifier of the daemon. pub daemon_id: String, + /// the software version of the daemon. pub daemon_version: String, + /// the name of the host that runs the daemon. pub hostname: String, + /// the identifier that the daemon gives to this client. pub client_id: u64, } +/// a request from a client. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Request { + /// the identifier that connects the request to its response. pub id: u64, + /// the operation that the client requests. pub body: RequestBody, } +/// the operation that a request asks for. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum RequestBody { + /// call a method. Call(Call), + /// run a Lua chunk. Eval(Eval), - Attach { force: bool }, + /// attach the client to the daemon. + Attach { + /// when true, the client replaces the client that is attached now. + force: bool, + }, + /// detach the client from the daemon. Detach, + /// start to send these events to the client. Subscribe(Vec), + /// stop sending these events to the client. Unsubscribe(Vec), } +/// the answer to a request. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Response { + /// the identifier of the request that this response answers. pub id: u64, + /// the result of the request. pub body: ResponseBody, } +/// the result of a request. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum ResponseBody { + /// the request was successful and gave this value. Result(Value), + /// the attach request was successful. Attached(Attached), + /// the request failed. Error(Error), } +/// a call to a method. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Call { + /// the name of the method. pub method: String, + /// the parameters of the method. pub params: Value, } +/// a Lua chunk that the daemon must run. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Eval { + /// the Lua source code. pub source: String, + /// the arguments that the chunk gets. pub args: Value, + /// the name that shows the chunk in error messages. pub chunk_name: String, } +/// the state that a client gets when it attaches. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Attached { + /// a snapshot of each terminal. pub terminals: Vec, + /// the number that identifies this attachment. pub generation: u64, } +/// the state of one terminal at one time. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct TerminalSnapshot { + /// the identifier of the terminal. pub terminal: Uuid, + /// the size of the terminal. pub size: Size, + /// the VT bytes that make the screen of the terminal again. pub vt: Vec, + /// the position of the terminal on the canvas. pub position: Point, } +/// the error that a failed request gives. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Error { + /// the type of the error. pub code: ErrorCode, + /// the text that tells about the error. pub message: String, } +/// the type of an error. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] pub enum ErrorCode { + /// the request is not correct. BadRequest, + /// the daemon does not know the method. UnknownMethod, + /// the daemon cannot find the item. NotFound, + /// the item is in use. Busy, + /// the client must attach before it sends this request. NotAttached, + /// the Lua code gave an error. Lua, + /// the daemon had an internal failure. Internal, } +/// an event that the daemon sends to subscribed clients. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Event { + /// the name of the event. pub name: String, + /// the terminal that the event is about, if there is one. pub terminal: Option, + /// the data of the event. pub data: Value, } +/// keyboard input for a terminal. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Input { + /// the terminal that gets the input. pub terminal: Uuid, + /// the input bytes. pub data: Vec, } +/// a request to change the size of a terminal. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] pub struct Resize { + /// the terminal to change. pub terminal: Uuid, + /// the new size. pub size: Size, } +/// bytes that a terminal wrote. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Output { + /// the terminal that wrote the bytes. pub terminal: Uuid, + /// the output bytes. pub data: Vec, } +/// the full state of a terminal, which replaces the state that the client has. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Resync { + /// the terminal to replace. pub terminal: Uuid, + /// the VT bytes that make the screen of the terminal again. pub vt: Vec, } +/// the header at the start of an output stream. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] pub struct OutputStreamHeader { + /// the terminal that the stream is for. pub terminal: Uuid, + /// the attachment that the stream is for. pub generation: u64, } +/// a message that tells a client that the daemon detached it. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Detached { + /// the cause of the detach. pub reason: DetachReason, + /// the name of the client that caused the detach. pub by: String, } +/// the cause of a detach. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] pub enum DetachReason { + /// the client asked to detach. Requested, + /// a different client attached with force. TakenOver, + /// the client did not read its output fast enough. TooSlow, } +/// a message that tells a client that the daemon closes the connection. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Closing { + /// the cause of the close. pub reason: CloseReason, + /// the text that tells about the close. pub message: String, } +/// the cause of a close. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] pub enum CloseReason { + /// the connection is complete. Done, + /// the client and the daemon use different protocol versions. VersionMismatch, + /// the peer sent data that is not correct. ProtocolError, + /// the daemon stops. Shutdown, + /// the client is not paired with the daemon. NotPaired, + /// the client did not open a control stream. NoControlStream, } @@ -189,11 +293,16 @@ impl CloseReason { } } +/// the size of a terminal. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct Size { + /// the number of columns. pub cols: u16, + /// the number of rows. pub rows: u16, + /// the width in pixels. pub pixel_width: u16, + /// the height in pixels. pub pixel_height: u16, } @@ -208,20 +317,31 @@ impl Size { } } +/// a position on the canvas. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Default)] pub struct Point { + /// the horizontal position. pub x: f32, + /// the vertical position. pub y: f32, } +/// a value that the protocol can send, with the same shape as JSON. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)] pub enum Value { + /// no value. #[default] Null, + /// a true or false value. Boolean(bool), + /// an integer. Integer(i64), + /// a floating-point number. Number(f64), + /// a text string. String(String), + /// a list of values. List(Vec), + /// a map from text keys to values. Map(BTreeMap), } diff --git a/crates/protocol/src/methods.rs b/crates/protocol/src/methods.rs index 3b18ef7..97086b3 100644 --- a/crates/protocol/src/methods.rs +++ b/crates/protocol/src/methods.rs @@ -5,11 +5,17 @@ use uuid::Uuid; pub use crate::{Point, Size}; +/// a method that a client can call on the daemon. pub trait Method { + /// the name that a client uses to call the method. const NAME: &'static str; + /// a short description of the method. const SUMMARY: &'static str; + /// the full description of the method. const DESCRIPTION: &'static str; + /// the parameters that the method gets. type Params: Serialize + DeserializeOwned; + /// the value that the method gives. type Output: Serialize + DeserializeOwned; } @@ -18,6 +24,7 @@ macro_rules! method { method!($ty, $name, $summary, $summary, $params => $output); }; ($ty:ident, $name:literal, $summary:literal, $description:literal, $params:ty => $output:ty) => { + #[doc = $summary] pub struct $ty; impl $crate::methods::Method for $ty { @@ -30,6 +37,7 @@ macro_rules! method { }; } +/// the name, summary and description of each built-in method. pub const BUILT_IN: &[(&str, &str, &str)] = &[ entry::(), entry::(), @@ -51,6 +59,7 @@ const fn entry() -> (&'static str, &'static str, &'static str) { (M::NAME, M::SUMMARY, M::DESCRIPTION) } +/// a time in milliseconds since the Unix epoch. pub type Millis = u64; pub mod api { @@ -69,24 +78,36 @@ pub mod api { DescribeParams => MethodDoc ); + /// a short description of one method. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct MethodInfo { + /// the name of the method. pub name: String, + /// a short description of the method. pub summary: String, + /// true if a Lua script registered the method. pub lua: bool, } + /// the parameters of `api.describe`. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct DescribeParams { + /// the name of the method to describe. pub method: String, } + /// the full documentation of one method. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct MethodDoc { + /// the name of the method. pub name: String, + /// a short description of the method. pub summary: String, + /// the full description of the method. pub description: String, + /// true if a Lua script registered the method. pub lua: bool, + /// an example call of the method, if there is one. pub example: Option, } } @@ -107,15 +128,24 @@ pub mod daemon { () => () ); + /// the identity and the state of the daemon. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct DaemonInfo { + /// the identifier of the daemon. pub id: String, + /// the software version of the daemon. pub version: String, + /// the name of the host that runs the daemon. pub hostname: String, + /// the process identifier of the daemon. pub pid: u32, + /// the network endpoint of the daemon. pub endpoint: net::EndpointInfo, + /// the time when the daemon started. pub started_at: Millis, + /// the number of terminals that the daemon runs. pub terminals: usize, + /// the identifier of the attached client, if there is one. pub attached: Option, } } @@ -130,14 +160,22 @@ pub mod client { () => Vec ); + /// the state of one connected client. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct ClientInfo { + /// the identifier of the client. pub id: u64, + /// the name of the client. pub name: String, + /// the network endpoint of the client. pub endpoint: String, + /// the type of network path that the client uses now. pub path: Option, + /// the time when the client connected. pub connected_at: Millis, + /// true if the client is attached. pub attached: bool, + /// the events that the client subscribed to. pub subscriptions: Vec, } @@ -153,17 +191,24 @@ pub mod client { PathsParams => Vec ); + /// the parameters of `client.paths`. #[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)] #[serde(default)] pub struct PathsParams { + /// the client to show. If empty, the method shows all clients. pub client: Option, } + /// the network paths of one client. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct ClientPaths { + /// the identifier of the client. pub id: u64, + /// the name of the client. pub name: String, + /// true if the client is attached. pub attached: bool, + /// the state of the connection of the client. pub connection: net::ConnectionInfo, } } @@ -171,57 +216,91 @@ pub mod client { pub mod net { use super::*; + /// the network addresses of an endpoint. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] pub struct EndpointInfo { + /// the identifier of the endpoint. pub id: String, + /// the URL of the relay that the endpoint uses, if there is one. pub relay: Option, + /// the direct addresses of the endpoint. pub direct_addrs: Vec, } + /// the type of a network path. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)] #[serde(rename_all = "snake_case")] pub enum PathKind { + /// a direct UDP path. Direct, + /// a path through a relay. Relay, + /// a path through a custom transport. Custom, } + /// the state of one network path. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct PathInfo { + /// the type of the path. pub kind: PathKind, + /// the remote address of the path. pub remote: String, + /// the local address of the path, if it is known. pub local: Option, + /// true if the path carries the data now. pub selected: bool, + /// the round-trip time in microseconds. pub rtt_us: u64, + /// the number of bytes that the path sent. pub tx_bytes: u64, + /// the number of bytes that the path received. pub rx_bytes: u64, + /// the number of packets that the path lost. pub lost_packets: u64, } + /// a change to a network path. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum PathChange { + /// the path opened. Opened, + /// the path closed. Closed, + /// the path became the path that carries data. Selected, + /// the history lost some events. Lagged, } + /// one change in the history of the network paths. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct PathEvent { + /// the time of the change. pub at: Millis, + /// the type of the change. pub change: PathChange, + /// the type of the path, if it is known. pub kind: Option, + /// the remote address of the path, if it is known. pub remote: Option, + /// the round-trip time in microseconds, if it is known. pub rtt_us: Option, } + /// the state of one connection. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] pub struct ConnectionInfo { + /// the identifier of the remote endpoint. pub remote: String, + /// the time when the connection started. pub connected_at: Millis, + /// the network paths that are open now. pub paths: Vec, + /// the type of the path that carries data now. pub selected: Option, + /// the changes to the paths since the connection started. pub history: Vec, } @@ -284,82 +363,127 @@ pub mod terminal { CaptureParams => String ); + /// the state of one terminal. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct TerminalInfo { + /// the identifier of the terminal. pub id: Uuid, + /// the command that the terminal runs. pub command: Vec, + /// the size of the terminal. pub size: Size, + /// the position of the terminal on the canvas. pub position: Point, + /// the process identifier of the command, if it runs. pub pid: Option, + /// the current directory of the command, if it is known. pub cwd: Option, + /// the title of the terminal. pub title: String, + /// the run state of the terminal. pub state: TerminalState, + /// the time when the daemon started the terminal. pub created_at: Millis, } + /// the run state of a terminal. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] #[serde(tag = "state", rename_all = "snake_case")] pub enum TerminalState { + /// the command runs. Running, - Exited { status: Option }, + /// the command stopped. + Exited { + /// the exit status of the command, if it is known. + status: Option, + }, } + /// the parameters of a method that operates on one terminal. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] pub struct Target { + /// the identifier of the terminal. pub terminal: Uuid, } + /// the parameters of `terminal.spawn`. #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)] #[serde(default)] pub struct SpawnParams { + /// the command to run. If empty, the terminal runs the login shell. pub command: Vec, + /// the directory to start the command in. pub cwd: Option, + /// the environment variables to add for the command. pub env: BTreeMap, + /// the start size of the terminal. pub size: Option, + /// the start position of the terminal on the canvas. pub position: Option, } + /// the parameters of `terminal.kill`. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct KillParams { + /// the identifier of the terminal. pub terminal: Uuid, + /// the name of the signal to send. If empty, the daemon sends SIGHUP. #[serde(default)] pub signal: Option, } + /// the parameters of `terminal.write`. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct WriteParams { + /// the identifier of the terminal. pub terminal: Uuid, + /// the text to type into the terminal. pub data: String, } + /// the parameters of `terminal.resize`. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct ResizeParams { + /// the identifier of the terminal. pub terminal: Uuid, + /// the new number of columns. pub cols: u16, + /// the new number of rows. pub rows: u16, } + /// the parameters of `terminal.move`. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)] pub struct MoveParams { + /// the identifier of the terminal. pub terminal: Uuid, + /// the new position on the canvas. pub position: Point, } + /// the parameters of `terminal.capture`. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct CaptureParams { + /// the identifier of the terminal. pub terminal: Uuid, + /// the format of the text. #[serde(default)] pub format: CaptureFormat, + /// true to include the scrollback. #[serde(default)] pub scrollback: bool, } + /// the format of a capture. #[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum CaptureFormat { + /// plain text. #[default] Plain, + /// text with VT escape sequences. Vt, + /// html. Html, } } @@ -375,26 +499,4 @@ mod tests { names.dedup(); assert_eq!(names.len(), BUILT_IN.len()); } - - #[test] - fn summaries_and_descriptions_are_explicit() { - assert_eq!( - terminal::List::SUMMARY, - "List every running terminal. Finished ones are left out." - ); - assert_eq!( - terminal::List::DESCRIPTION, - "List every running terminal. Finished ones are left out." - ); - assert!( - terminal::Capture::DESCRIPTION.contains("scrollback"), - "the whole doc comment should be the description" - ); - } - - #[test] - fn spawn_params_default_every_field() { - let params: terminal::SpawnParams = serde_json::from_str("{}").unwrap(); - assert_eq!(params, terminal::SpawnParams::default()); - } } diff --git a/crates/tarp/src/config.rs b/crates/tarp/src/config.rs index d9877f4..23cd4a6 100644 --- a/crates/tarp/src/config.rs +++ b/crates/tarp/src/config.rs @@ -568,7 +568,7 @@ impl Paths { // a fingerprint of the config files, used to spot edits. #[cfg(any(feature = "ui", test))] pub fn fingerprint(&self) -> u64 { - let mut hash = Fnv::new(); + let mut hash = Fnv(0xcbf29ce484222325); for path in &self.candidates { hash.write(path.to_string_lossy().as_bytes()); match fs::read(path) { @@ -576,7 +576,7 @@ impl Paths { Err(_) => hash.write(b""), } } - hash.finish() + hash.0 } } @@ -585,20 +585,12 @@ struct Fnv(u64); #[cfg(any(feature = "ui", test))] impl Fnv { - fn new() -> Self { - Self(0xcbf29ce484222325) - } - fn write(&mut self, bytes: &[u8]) { for byte in bytes { self.0 ^= u64::from(*byte); self.0 = self.0.wrapping_mul(0x100000001b3); } } - - fn finish(self) -> u64 { - self.0 - } } // the current config, plus the terminal settings it implies. @@ -676,160 +668,10 @@ mod tests { assert!(Color::parse("#gggggg").is_err()); } - #[test] - fn loads_defaults_when_the_file_is_missing() { - let dir = ScratchDir::new(); - let missing = dir.0.join("does-not-exist.toml"); - let config: Config = confique::Config::builder().file(missing).load().unwrap(); - assert_eq!(config.terminal.font_family, None); - assert_eq!(config.terminal.cols, 80); - assert_eq!(config.title_bar.left, "{host} - {title} - {cwd}"); - assert_eq!(config.title_bar.position, TitleBarPosition::Top); - assert!(config.bell.enabled); - assert_eq!(config.canvas.window_size, [1400., 900.]); - assert_eq!(config.canvas.snap_threshold_factor, 2.0); - assert_eq!(config.canvas.startup_mode, StartupMode::Windowed); - assert!(!config.canvas.macos_non_native_fullscreen); - assert_eq!( - config.canvas.background, - Color { - r: 0x1e, - g: 0x1e, - b: 0x22, - a: 0xFF, - } - ); - } - - #[test] - fn overrides_what_the_file_says_and_defaults_the_rest() { - let dir = ScratchDir::new(); - let path = dir.file( - r##" -[canvas] -background = "#ffffff" -window_size = [800.0, 600.0] - -[terminal] -font_family = "Fira Code" -font_size = 14.0 -cols = 100 -rows = 40 -foreground = "#000000" -"##, - ); - let config: Config = confique::Config::builder().file(&path).load().unwrap(); - assert_eq!( - config.canvas.background, - Color { - r: 0xff, - g: 0xff, - b: 0xff, - a: 0xff, - } - ); - assert_eq!(config.canvas.window_size, [800., 600.]); - assert_eq!(config.terminal.font_family.as_deref(), Some("Fira Code")); - assert_eq!(config.terminal.font_size, 14.); - assert_eq!(config.terminal.cols, 100); - assert_eq!( - config.terminal.foreground, - Color { - r: 0, - g: 0, - b: 0, - a: 0xff, - } - ); - assert_eq!(config.terminal.scrollback_lines, 10_000); - assert_eq!(config.terminal.ansi.len(), 16); - } - - #[test] - fn parses_the_terminal_start_options() { - let dir = ScratchDir::new(); - let config: Config = confique::Config::builder() - .file(dir.file( - "[terminal]\ncwd = \"/tmp\"\ninherit_cwd = true\nhost = \"mantis\"\ninherit_host = true\n", - )) - .load() - .unwrap(); - assert_eq!(config.terminal.cwd.as_deref(), Some("/tmp")); - assert!(config.terminal.inherit_cwd); - assert_eq!(config.terminal.host.as_deref(), Some("mantis")); - assert!(config.terminal.inherit_host); - - let defaults: Config = confique::Config::builder().load().unwrap(); - assert_eq!(defaults.terminal.cwd, None); - assert!(!defaults.terminal.inherit_cwd); - assert_eq!(defaults.terminal.host, None); - assert!(!defaults.terminal.inherit_host); - } - - #[test] - #[cfg(feature = "ui")] - fn parses_the_new_terminal_position() { - let dir = ScratchDir::new(); - let config: Config = confique::Config::builder() - .file(dir.file("[canvas]\nnew_terminal_position = \"follow_mouse\"\n")) - .load() - .unwrap(); - assert_eq!( - config.canvas.new_terminal_position, - NewItemPosition::FollowMouse - ); - - let defaults: Config = confique::Config::builder().load().unwrap(); - assert_eq!( - defaults.canvas.new_terminal_position, - NewItemPosition::Optimal - ); - - let bad: Result = confique::Config::builder() - .file(dir.file("[canvas]\nnew_terminal_position = \"sideways\"\n")) - .load(); - assert!(bad.is_err()); - } - - #[test] - #[cfg(feature = "ui")] - fn parses_on_focus() { - let dir = ScratchDir::new(); - let config: Config = confique::Config::builder() - .file(dir.file("[canvas]\non_focus = \"minimal\"\n")) - .load() - .unwrap(); - assert_eq!(config.canvas.on_focus, OnFocus::Minimal); - - let defaults: Config = confique::Config::builder().load().unwrap(); - assert_eq!(defaults.canvas.on_focus, OnFocus::Centered); - - let bad: Result = confique::Config::builder() - .file(dir.file("[canvas]\non_focus = \"maximal\"\n")) - .load(); - assert!(bad.is_err()); - } - #[test] #[cfg(feature = "ui")] - fn parses_the_border_style_and_paints_the_layercard() { - let dir = ScratchDir::new(); - let config: Config = confique::Config::builder() - .file(dir.file("[canvas]\nborder_style = \"opaque\"\n")) - .load() - .unwrap(); - assert_eq!(config.canvas.border_style, BorderStyle::Opaque); - - let bad: Result = confique::Config::builder() - .file(dir.file("[canvas]\nborder_style = \"frosted\"\n")) - .load(); - assert!(bad.is_err()); - + fn paints_the_layercard_by_border_style() { let defaults: Config = confique::Config::builder().load().unwrap(); - assert_eq!(defaults.canvas.border_style, BorderStyle::Liquid); - assert_eq!(defaults.canvas.border_width, 4.0); - assert_eq!(defaults.canvas.border_radius, 12.0); - let border = defaults.canvas.border.to_hsla(); assert!( defaults.canvas.frame_color().a < border.a, @@ -856,33 +698,16 @@ foreground = "#000000" #[test] #[cfg(feature = "ui")] - fn parses_the_background_gradient() { - let dir = ScratchDir::new(); - let config: Config = confique::Config::builder() - .file(dir.file( - "[canvas]\nbackground_style = \"gradient\"\ngradient_type = \"radial\"\n\ - gradient_colors = [\"#f97945\", \"#988dcc\"]\ngradient_angle = 30.0\n", - )) - .load() - .unwrap(); - assert_eq!(config.canvas.background_style, BackgroundStyle::Gradient); - assert_eq!(config.canvas.gradient_type, GradientType::Radial); - - let bad: Result = confique::Config::builder() - .file(dir.file("[canvas]\nbackground_style = \"stripes\"\n")) - .load(); - assert!(bad.is_err()); - - let bad: Result = confique::Config::builder() - .file(dir.file("[canvas]\ngradient_type = \"spiral\"\n")) - .load(); - assert!(bad.is_err()); - + fn paints_the_background_gradient() { let defaults: Config = confique::Config::builder().load().unwrap(); - assert_eq!(defaults.canvas.background_style, BackgroundStyle::Solid); - assert_eq!(defaults.canvas.gradient_type, GradientType::Linear); + let gradient = CanvasConfig { + background_style: BackgroundStyle::Gradient, + gradient_type: GradientType::Radial, + gradient_angle: 30.0, + ..defaults.canvas.clone() + }; - let canvas = config.canvas.to_config(size(px(100.), px(100.)), px(11.)); + let canvas = gradient.to_config(size(px(100.), px(100.)), px(11.)); let gradient = canvas.background.gradient.expect("a gradient"); assert_eq!(gradient.kind, config::GradientKind::Radial); assert_eq!(gradient.from, Color::parse("#f97945").unwrap().to_hsla()); @@ -952,31 +777,21 @@ foreground = "#000000" #[test] #[cfg(feature = "ui")] fn converts_into_terminal_settings() { - let dir = ScratchDir::new(); - let config: Config = confique::Config::builder() - .file(dir.file("[terminal]\nfont_size = 12.0\npadding_x = 3.0\n")) - .load() - .unwrap(); - let settings = config.terminal.to_settings(); + let defaults: Config = confique::Config::builder().load().unwrap(); + let settings = TerminalConfig { + font_family: Some("Nerd Input".into()), + font_size: 12.0, + padding_x: 3.0, + ..defaults.terminal + } + .to_settings(); + assert_eq!(settings.font.family.as_ref(), "Nerd Input"); assert_eq!(settings.font_size, px(12.0)); assert_eq!(settings.padding_x, px(3.0)); assert_eq!(settings.padding_y, px(10.0)); assert_eq!(settings.scrollback_lines, 10_000); } - #[test] - #[cfg(feature = "ui")] - fn live_config_derives_terminal_settings() { - let dir = ScratchDir::new(); - let config: Config = confique::Config::builder() - .file(dir.file("[terminal]\nfont_family = \"Nerd Input\"\nfont_size = 12.0\n")) - .load() - .unwrap(); - let live = LiveConfig::from_config(config); - assert_eq!(live.terminal.font_size, px(12.0)); - assert_eq!(live.terminal.font.family.as_ref(), "Nerd Input"); - } - #[test] fn fingerprint_detects_config_edits() { let dir = ScratchDir::new(); @@ -1010,101 +825,4 @@ foreground = "#000000" .fingerprint() ); } - - #[test] - fn parses_the_startup_mode() { - let dir = ScratchDir::new(); - for (text, mode) in [ - ("\"Windowed\"", StartupMode::Windowed), - ("\"Maximized\"", StartupMode::Maximized), - ("\"Fullscreen\"", StartupMode::Fullscreen), - ] { - let path = dir.file(&format!("[canvas]\nstartup_mode = {text}\n")); - let config: Config = confique::Config::builder().file(&path).load().unwrap(); - assert_eq!(config.canvas.startup_mode, mode); - } - - let path = dir.file("[canvas]\nstartup_mode = \"Borderless\"\n"); - let loaded: Result = - confique::Config::builder().file(&path).load(); - assert!(loaded.is_err()); - } - - #[test] - fn parses_the_title_bar_and_bell() { - let dir = ScratchDir::new(); - let config: Config = confique::Config::builder() - .file(dir.file( - r##" -[title_bar] -position = "bottom" -left = "{host}" -right = "#(date +%H:%M)" -interval = 1.5 -focus_foreground = "#ffffff" - -[bell] -color = "#ff0000" -"##, - )) - .load() - .unwrap(); - assert_eq!(config.title_bar.position, TitleBarPosition::Bottom); - assert_eq!(config.title_bar.left, "{host}"); - assert_eq!(config.title_bar.center, ""); - assert_eq!(config.title_bar.right, "#(date +%H:%M)"); - assert_eq!(config.title_bar.interval, 1.5); - assert!(config.title_bar.focus_foreground.is_some()); - assert!(config.bell.enabled); - assert_eq!( - config.bell.color, - Color { - r: 0xff, - g: 0, - b: 0, - a: 0xff, - } - ); - - for text in [ - "[title_bar]\nposition = \"left\"\n", - "[title_bar]\nformat = \"{host}\"\n", - "[title_bar]\nbackground = \"#303030\"\n", - "[title_bar]\nfocus_background = \"#303030\"\n", - "[terminal]\ntitle_format = \"{host}\"\n", - "[bell]\nactivity = true\n", - ] { - let loaded: Result = - confique::Config::builder().file(dir.file(text)).load(); - assert!(loaded.is_err(), "{text:?} should have been rejected"); - } - } - - #[test] - fn parses_the_hosts_table() { - let dir = ScratchDir::new(); - let path = dir.file( - r##" -[[hosts]] -name = "mantis" -id = "abababababababababababababababababababababababababababababababab" - -[[hosts]] -name = "gpu" -id = "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd@100.64.0.3:3999" -"##, - ); - let config: Config = confique::Config::builder().file(&path).load().unwrap(); - assert_eq!(config.hosts.len(), 2); - assert_eq!(config.hosts[0].name, "mantis"); - assert_eq!( - config.hosts[0].id.as_deref().unwrap(), - "abababababababababababababababababababababababababababababababab" - ); - assert_eq!(config.hosts[1].name, "gpu"); - assert_eq!( - config.hosts[1].id.as_deref().unwrap(), - "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd@100.64.0.3:3999" - ); - } } diff --git a/crates/tarp/src/main.rs b/crates/tarp/src/main.rs index 663e449..b65f7dc 100644 --- a/crates/tarp/src/main.rs +++ b/crates/tarp/src/main.rs @@ -330,7 +330,12 @@ impl Cli { let window = cx .open_window(options, |window, cx| { let settings = live.borrow().terminal.clone(); - let item_size = live.borrow().chrome.item_size(&settings, window); + let item_size = live.borrow().chrome.item_size( + &settings, + settings.cols, + settings.rows, + window, + ); let canvas = cx.new({ let ui = ui.clone(); @@ -357,12 +362,27 @@ impl Cli { .context_menu(move |anchor, _window, cx| { menu.context_menu(anchor, cx) }) - .size_label(move |size, window, _cx| label.size_label(size, window)) + .size_label(move |size, window, _cx| { + let live = label.live.borrow(); + let (cols, rows) = + live.chrome.grid_for(&live.terminal, size, window); + Some(format!("{cols}×{rows}")) + }) } }); - ui.restore(&canvas, attached, window, cx); - ui.watch_layout(&canvas, cx); + ui.restore_terminals(&canvas, attached, false, window, cx); + cx.subscribe(&canvas, { + let watched = canvas.clone(); + let session = ui.session.clone(); + move |_canvas, event: &CanvasEvent, cx| { + let CanvasEvent::LayoutChanged = event; + session.update(cx, |session, cx| { + session.layout_changed(watched.clone(), cx); + }); + } + }) + .detach(); ui.watch_hosts(&canvas, window, cx); Keys::register_grow(&canvas, cx); @@ -484,12 +504,6 @@ impl Ui { .detach(); } - fn size_label(&self, size: Size, window: &mut Window) -> Option { - let live = self.live.borrow(); - let (cols, rows) = live.chrome.grid_for(&live.terminal, size, window); - Some(format!("{cols}×{rows}")) - } - fn context_menu( &self, anchor: Point, @@ -617,16 +631,6 @@ impl Ui { .detach(); } - fn restore( - &self, - canvas: &Entity, - attached: Vec<(usize, Attached)>, - window: &mut Window, - cx: &mut App, - ) { - self.restore_terminals(canvas, attached, false, window, cx); - } - fn restore_terminals( &self, canvas: &Entity, @@ -684,7 +688,7 @@ impl Ui { (session.handle_for(host), session.host_name(host)) }; - let item_size = self.live.borrow().chrome.item_size_for( + let item_size = self.live.borrow().chrome.item_size( &settings, state.size.cols, state.size.rows, @@ -863,18 +867,6 @@ impl Ui { .detach(); }); } - - fn watch_layout(&self, canvas: &Entity, cx: &mut App) { - let watched = canvas.clone(); - let session = self.session.clone(); - cx.subscribe(canvas, move |_canvas, event: &CanvasEvent, cx| { - let CanvasEvent::LayoutChanged = event; - session.update(cx, |session, cx| { - session.layout_changed(watched.clone(), cx); - }); - }) - .detach(); - } } #[cfg(feature = "ui")] @@ -890,24 +882,20 @@ impl Start { ) -> (usize, Option) { let inherit_host = config.inherit_host || config.inherit_cwd; - let host = match requested { - Some(requested) => requested, - None if inherit_host => focused - .as_ref() - .map(|(host, _)| *host) - .or_else(|| { - config - .host - .as_ref() - .and_then(|name| names.iter().position(|host| host == name)) - }) - .unwrap_or(0), - None => config - .host - .as_ref() - .and_then(|name| names.iter().position(|host| host == name)) - .unwrap_or(0), - }; + let host = requested + .or_else(|| { + focused + .as_ref() + .filter(|_| inherit_host) + .map(|(host, _)| *host) + }) + .or_else(|| { + config + .host + .as_ref() + .and_then(|name| names.iter().position(|host| host == name)) + }) + .unwrap_or(0); let cwd = if config.inherit_cwd { focused @@ -988,7 +976,7 @@ impl KillArgs { let specs = HostTable(&config.hosts).resolve(&self.host)?; for (name, spec) in specs { - match spec.connect_running() { + match spec.connect() { Ok(connection) => { let id = connection.welcome().daemon_id.clone(); connection.handle().kill(); @@ -1079,16 +1067,7 @@ impl PairArgs { "`tarp pair` changes the allow list of the daemon on this machine; run it there" ); } - let config = tarpd::config::load(&tarpd::config::Args { - config: None, - bind: None, - relay: None, - no_discovery: false, - state_dir: None, - log_format: None, - command: None, - }) - .context("loading the daemon's configuration")?; + let config = HostSpec::config()?; let path = config.allow_list_path(); let mut list = AllowList::read(&path)?; @@ -1196,7 +1175,7 @@ impl Cli { use protocol::methods::{client, daemon, terminal}; let (name, spec) = Self::one_host(&self.host)?; - let mut connection = match spec.connect_running() { + let mut connection = match spec.connect() { Ok(connection) => connection, Err(error) => { println!("no session on {name} is running: {error:#}"); @@ -1272,7 +1251,7 @@ impl Cli { let (name, spec) = Self::one_host(&hosts)?; let dialing = Instant::now(); let mut connection = spec - .connect_running() + .connect() .with_context(|| format!("reaching the session on {name}"))?; let dialed = dialing.elapsed(); @@ -1402,7 +1381,7 @@ impl Cli { let (name, spec) = Self::one_host(&hosts)?; let mut connection = spec - .connect_running() + .connect() .with_context(|| format!("no session on {name} is running"))?; let params = if params.is_empty() { @@ -1413,7 +1392,13 @@ impl Cli { let value = connection .call_value(method, params, ATTACH_TIMEOUT) .with_context(|| format!("calling {method}"))?; - Reply(value).print(json) + let value: serde_json::Value = value.try_into()?; + match (json, &value) { + (false, serde_json::Value::String(text)) => print!("{text}"), + (false, serde_json::Value::Null) => {} + _ => println!("{}", serde_json::to_string_pretty(&value)?), + } + Ok(()) } } @@ -1525,7 +1510,11 @@ impl Params { let mut params = serde_json::Map::new(); for arg in args { let (key, value) = match arg.split_once('=') { - Some((key, value)) => (key, Self::scalar(value)), + Some((key, value)) => ( + key, + serde_json::from_str(value) + .unwrap_or_else(|_| serde_json::Value::String(value.to_owned())), + ), None => (arg.as_str(), serde_json::Value::Bool(true)), }; let key = key.strip_prefix("--").unwrap_or(key); @@ -1534,10 +1523,6 @@ impl Params { Ok(serde_json::Value::Object(params).try_into()?) } - fn scalar(raw: &str) -> serde_json::Value { - serde_json::from_str(raw).unwrap_or_else(|_| serde_json::Value::String(raw.to_owned())) - } - fn insert( map: &mut serde_json::Map, key: &str, @@ -1561,20 +1546,6 @@ impl Params { } } -struct Reply(Value); - -impl Reply { - fn print(self, json: bool) -> anyhow::Result<()> { - let value: serde_json::Value = self.0.try_into()?; - match (json, &value) { - (false, serde_json::Value::String(text)) => print!("{text}"), - (false, serde_json::Value::Null) => {} - _ => println!("{}", serde_json::to_string_pretty(&value)?), - } - Ok(()) - } -} - #[derive(Clone, Debug)] enum HostSpec { Local, @@ -1593,12 +1564,8 @@ impl HostSpec { } } - fn connect_running(&self) -> anyhow::Result { - self.connect() - } - fn connect_local() -> anyhow::Result { - let state_dir = Self::state_dir()?; + let state_dir = Self::config()?.state_dir(); let file = tarpd::EndpointFile::read(&state_dir).with_context(|| { format!( "no local daemon is running in {}; start one with `tarp daemon`", @@ -1612,10 +1579,6 @@ impl HostSpec { .with_context(|| format!("connecting to the local daemon in {}", state_dir.display())) } - fn state_dir() -> anyhow::Result { - Ok(Self::config()?.state_dir()) - } - fn config() -> anyhow::Result { tarpd::config::load(&tarpd::config::Args { config: None, @@ -1677,42 +1640,14 @@ impl HostTable<'_> { #[cfg(all(test, feature = "ui"))] mod tests { use super::Start; - use crate::config::{Color, TerminalConfig}; - - fn color(value: u32) -> Color { - Color { - r: (value >> 16) as u8, - g: (value >> 8) as u8, - b: value as u8, - a: 0xFF, - } - } + use crate::config::TerminalConfig; - fn terminal( - cwd: Option<&str>, - inherit_cwd: bool, - host: Option<&str>, - inherit_host: bool, - ) -> TerminalConfig { + fn terminal(inherit_cwd: bool, host: Option<&str>, inherit_host: bool) -> TerminalConfig { TerminalConfig { - font_family: None, - font_size: 11.0, - line_height_ratio: 1.3, - padding_x: 5.0, - padding_y: 10.0, - cols: 80, - rows: 24, - foreground: color(0xeeffff), - background: color(0x000000), - ansi: std::array::from_fn(|_| color(0)), - scrollback_lines: 10_000, - shell: None, - cwd: cwd.map(str::to_string), inherit_cwd, host: host.map(str::to_string), inherit_host, - macos_option_as_alt: true, - osc52: true, + ..confique::Config::builder().load().expect("defaults") } } @@ -1725,7 +1660,7 @@ mod tests { #[test] fn requested_host_beats_inheritance() { - let config = terminal(None, true, Some("mantis"), false); + let config = terminal(true, Some("mantis"), false); let (host, cwd) = Start::resolve(&config, Some(1), Some((0, "/home/op".into())), &names()); assert_eq!(host, 1); assert_eq!(cwd, None); @@ -1733,7 +1668,7 @@ mod tests { #[test] fn inherit_cwd_takes_host_and_directory_from_the_focused_terminal() { - let config = terminal(None, true, None, false); + let config = terminal(true, None, false); let (host, cwd) = Start::resolve(&config, None, Some((1, "/code".into())), &names()); assert_eq!(host, 1); assert_eq!(cwd.as_deref(), Some("/code")); @@ -1741,7 +1676,7 @@ mod tests { #[test] fn inherit_host_alone_takes_only_the_host() { - let config = terminal(None, false, Some("local"), true); + let config = terminal(false, Some("local"), true); let (host, cwd) = Start::resolve(&config, None, Some((1, "/code".into())), &names()); assert_eq!(host, 1); assert_eq!(cwd, None); @@ -1749,7 +1684,7 @@ mod tests { #[test] fn configured_host_is_the_fallback_default() { - let config = terminal(None, false, Some("mantis"), false); + let config = terminal(false, Some("mantis"), false); let (host, cwd) = Start::resolve(&config, None, None, &names()); assert_eq!(host, 1); assert_eq!(cwd, None); @@ -1757,16 +1692,8 @@ mod tests { #[test] fn an_unknown_configured_host_falls_back_to_the_first() { - let config = terminal(None, false, Some("gpu"), false); + let config = terminal(false, Some("gpu"), false); let (host, _) = Start::resolve(&config, None, None, &names()); assert_eq!(host, 0); } - - #[test] - fn inheritance_keeps_the_directory_on_the_same_host() { - let config = terminal(Some("/workspace"), true, None, false); - let (host, cwd) = Start::resolve(&config, None, Some((0, "/home/op".into())), &names()); - assert_eq!(host, 0); - assert_eq!(cwd.as_deref(), Some("/home/op")); - } } diff --git a/crates/tarp/src/session.rs b/crates/tarp/src/session.rs index 4b4019c..b58525f 100644 --- a/crates/tarp/src/session.rs +++ b/crates/tarp/src/session.rs @@ -255,7 +255,12 @@ impl Session { while batch.len() < PUMP_BATCH && budget > 0 { match connection.poll() { Poll::Frame(frame) => { - budget = budget.saturating_sub(Self::output_len(&frame)); + let len = match &frame { + ServerFrame::Output(output) => output.data.len(), + ServerFrame::Resync(resync) => resync.vt.len(), + _ => 0, + }; + budget = budget.saturating_sub(len); batch.push(frame); } Poll::Empty => break, @@ -312,7 +317,12 @@ impl Session { let mut runs: HashMap> = HashMap::new(); for frame in batch { - if let Some(id) = Self::ordered_after_output(&frame) + let ordered_after_output = match &frame { + ServerFrame::Resync(resync) => Some(resync.terminal), + ServerFrame::Event(event) => event.terminal, + _ => None, + }; + if let Some(id) = ordered_after_output && let Some(bytes) = runs.remove(&id) { self.feed(id, &bytes, cx); @@ -390,11 +400,6 @@ impl Session { })); } - pub fn flush_layout(&mut self, canvas: &Entity, cx: &mut Context) { - self.layout_push = None; - self.push_layout(canvas, cx); - } - fn push_layout(&mut self, canvas: &Entity, cx: &mut Context) { let current = canvas.read(cx).layout(); @@ -421,7 +426,8 @@ impl Session { } pub fn detach(&mut self, canvas: &Entity, cx: &mut Context) { - self.flush_layout(canvas, cx); + self.layout_push = None; + self.push_layout(canvas, cx); info!("detaching from the session"); let live = || { (0..self.handles.len()) @@ -437,22 +443,6 @@ impl Session { } } } - - fn output_len(frame: &ServerFrame) -> usize { - match frame { - ServerFrame::Output(output) => output.data.len(), - ServerFrame::Resync(resync) => resync.vt.len(), - _ => 0, - } - } - - fn ordered_after_output(frame: &ServerFrame) -> Option { - match frame { - ServerFrame::Resync(resync) => Some(resync.terminal), - ServerFrame::Event(event) => event.terminal, - _ => None, - } - } } #[cfg(test)] @@ -836,6 +826,23 @@ mod tests { root.read_with(cx, |root, cx| root.terminal.read(cx).has_bell()) } + fn wait_for_title_bar(root: &Entity, expected: &str, cx: &mut gpui::VisualTestContext) { + let terminal = root.read_with(cx, |root, _| root.terminal.clone()); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + cx.run_until_parked(); + let text = terminal.read_with(cx, |terminal, cx| terminal.title_bar_text(cx)); + if text == expected { + break; + } + assert!( + Instant::now() < deadline, + "the title bar never showed {expected:?}: {text:?}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + } + #[gpui::test] async fn output_alone_flags_nothing(cx: &mut TestAppContext) { let (root, cx, _peer) = Single::open("", cx); @@ -873,20 +880,7 @@ mod tests { "[title_bar]\nleft = \"[#(printf '%s-%s' \\\"$TARP_HOST\\\" \\\"$TARP_IDX\\\")]\"\n", cx, ); - let terminal = root.read_with(cx, |root, _| root.terminal.clone()); - let deadline = Instant::now() + Duration::from_secs(5); - loop { - cx.run_until_parked(); - let text = terminal.read_with(cx, |terminal, cx| terminal.title_bar_text(cx)); - if text == "[local-1]" { - break; - } - assert!( - Instant::now() < deadline, - "the command never filled in: {text:?}" - ); - std::thread::sleep(Duration::from_millis(20)); - } + wait_for_title_bar(&root, "[local-1]", cx); } #[gpui::test] @@ -896,20 +890,7 @@ mod tests { cx, ); output(&root, b"\x1b]2;$(echo pwned)\x07", cx); - let terminal = root.read_with(cx, |root, _| root.terminal.clone()); - let deadline = Instant::now() + Duration::from_secs(5); - loop { - cx.run_until_parked(); - let text = terminal.read_with(cx, |terminal, cx| terminal.title_bar_text(cx)); - if text == "$(echo pwned)" { - break; - } - assert!( - Instant::now() < deadline, - "the title never came through: {text:?}" - ); - std::thread::sleep(Duration::from_millis(20)); - } + wait_for_title_bar(&root, "$(echo pwned)", cx); } #[test] diff --git a/crates/tarp/src/terminal.rs b/crates/tarp/src/terminal.rs index 61a47e0..6ba5a09 100644 --- a/crates/tarp/src/terminal.rs +++ b/crates/tarp/src/terminal.rs @@ -258,7 +258,13 @@ impl Terminal { cx.notify(); }), cx.subscribe(&emulator, |terminal, _, event, cx| match event { - EmulatorEvent::Bell => terminal.note_bell(cx), + EmulatorEvent::Bell => { + if terminal.chrome.bell.is_some() && !terminal.focused && !terminal.bell { + debug!(id = %terminal.id, "bell rang while unfocused"); + terminal.bell = true; + cx.notify(); + } + } EmulatorEvent::BreadcrumbsChanged => terminal.run_commands(cx), _ => {} }), @@ -335,14 +341,6 @@ impl Terminal { self.chrome.bell.filter(|_| self.bell) } - fn note_bell(&mut self, cx: &mut Context) { - if self.chrome.bell.is_some() && !self.focused && !self.bell { - debug!(id = %self.id, "bell rang while unfocused"); - self.bell = true; - cx.notify(); - } - } - #[cfg(test)] pub fn title_bar_text(&self, cx: &App) -> String { let vars = self.variables(self.focused, cx); diff --git a/crates/tarp/src/title_bar.rs b/crates/tarp/src/title_bar.rs index 445e506..cc1528c 100644 --- a/crates/tarp/src/title_bar.rs +++ b/crates/tarp/src/title_bar.rs @@ -519,14 +519,6 @@ impl Chrome { } pub fn item_size( - &self, - settings: &TerminalSettings, - window: &mut gpui::Window, - ) -> gpui::Size { - self.item_size_for(settings, settings.cols, settings.rows, window) - } - - pub fn item_size_for( &self, settings: &TerminalSettings, cols: u16, diff --git a/crates/tarpc/src/error.rs b/crates/tarpc/src/error.rs index a449deb..5feefc1 100644 --- a/crates/tarpc/src/error.rs +++ b/crates/tarpc/src/error.rs @@ -13,9 +13,6 @@ pub enum Error { #[error("opening the control stream to {addr}: {reason}")] ControlStream { addr: String, reason: String }, - #[error(transparent)] - Transport(#[from] transport::Error), - #[error("could not load this client's key: {reason}")] ClientKey { reason: String }, diff --git a/crates/tarpc/src/lib.rs b/crates/tarpc/src/lib.rs index 2357ebe..dc378cb 100644 --- a/crates/tarpc/src/lib.rs +++ b/crates/tarpc/src/lib.rs @@ -89,7 +89,12 @@ pub fn use_identity(identity: Identity) -> bool { pub fn identity() -> Result<&'static Identity, Error> { IDENTITY - .get_or_init(|| Identity::load_or_create(&client_key_path()).map_err(|e| format!("{e:#}"))) + .get_or_init(|| { + let path = std::env::var_os("TARP_CLIENT_KEY") + .map(PathBuf::from) + .unwrap_or_else(|| state_home().join("tarp/client.key")); + Identity::load_or_create(&path).map_err(|e| format!("{e:#}")) + }) .as_ref() .map_err(|reason| Error::ClientKey { reason: reason.clone(), @@ -107,12 +112,6 @@ fn state_home() -> PathBuf { }) } -pub fn client_key_path() -> PathBuf { - std::env::var_os("TARP_CLIENT_KEY") - .map(PathBuf::from) - .unwrap_or_else(|| state_home().join("tarp/client.key")) -} - static ENDPOINT: OnceLock> = OnceLock::new(); const SHUTDOWN_GRACE: Duration = Duration::from_secs(1); @@ -157,8 +156,10 @@ pub struct Handle { } impl Handle { - fn next_id(&self) -> u64 { - self.ids.fetch_add(1, Ordering::Relaxed) + fn request(&self, body: RequestBody) -> u64 { + let id = self.ids.fetch_add(1, Ordering::Relaxed); + self.send(ClientFrame::request(id, body)); + id } pub fn send(&self, frame: ClientFrame) { @@ -176,64 +177,43 @@ impl Handle { } pub fn call(&self, method: &str, params: Value) -> u64 { - let id = self.next_id(); - self.send(ClientFrame::call_named(id, method, params)); - id + self.request(RequestBody::Call(protocol::Call { + method: method.into(), + params, + })) } pub fn call_typed(&self, params: &M::Params) -> u64 { - let id = self.next_id(); - self.send(ClientFrame::call::(id, params).expect("method params serialize")); - id - } - - pub fn spawn(&self, params: &terminal::SpawnParams) -> u64 { - self.call_typed::(params) - } - - pub fn capture(&self, params: &terminal::CaptureParams) -> u64 { - self.call_typed::(params) + self.call( + M::NAME, + Value::from_serialize(params).expect("method params serialize"), + ) } pub fn input(&self, terminal: Uuid, bytes: &[u8]) { - self.send(ClientFrame::input(terminal, bytes.to_vec())); + self.send(ClientFrame::Input(protocol::Input { + terminal, + data: bytes.to_vec(), + })); } pub fn resize(&self, terminal: Uuid, cols: u16, rows: u16) { - self.send(ClientFrame::resize(terminal, Size::cells(cols, rows))); + self.send(ClientFrame::Resize(protocol::Resize { + terminal, + size: Size::cells(cols, rows), + })); } pub fn move_terminal(&self, terminal: Uuid, position: Point) -> u64 { self.call_typed::(&terminal::MoveParams { terminal, position }) } - pub fn close_terminal(&self, terminal: Uuid) -> u64 { - self.call_typed::(&terminal::KillParams { - terminal, - signal: None, - }) - } - - pub fn attach(&self, force: bool) -> u64 { - let id = self.next_id(); - self.send(ClientFrame::request(id, RequestBody::Attach { force })); - id - } - pub fn kill(&self) -> u64 { self.call_typed::(&()) } pub fn detach(&self) -> u64 { - let id = self.next_id(); - self.send(ClientFrame::request(id, RequestBody::Detach)); - id - } - - pub fn subscribe(&self, patterns: Vec) -> u64 { - let id = self.next_id(); - self.send(ClientFrame::request(id, RequestBody::Subscribe(patterns))); - id + self.request(RequestBody::Detach) } } @@ -377,8 +357,9 @@ impl Connection { } pub fn attach(&mut self, force: bool, timeout: Duration) -> Result { - self.handle.subscribe(vec!["terminal.*".to_owned()]); - let id = self.handle.attach(force); + self.handle + .request(RequestBody::Subscribe(vec!["terminal.*".to_owned()])); + let id = self.handle.request(RequestBody::Attach { force }); let deadline = Instant::now() + timeout; match self.response(id, deadline)? { ResponseBody::Attached(attached) => { @@ -410,15 +391,8 @@ impl Connection { params: &M::Params, timeout: Duration, ) -> Result { - let id = self.handle.call_typed::(params); - let deadline = Instant::now() + timeout; - match self.response(id, deadline)? { - ResponseBody::Result(value) => Ok(value.deserialize()?), - ResponseBody::Error(error) => Err(Error::Refused { - message: error.message, - }), - ResponseBody::Attached(_) => Err(Error::Attached), - } + let params = Value::from_serialize(params).expect("method params serialize"); + Ok(self.call_value(M::NAME, params, timeout)?.deserialize()?) } pub fn call_value( @@ -438,18 +412,6 @@ impl Connection { } } - pub fn recv(&mut self) -> Option { - loop { - let incoming = match self.pending.pop_front() { - Some(incoming) => incoming, - None => self.incoming.recv().ok()?, - }; - if let Some(frame) = self.gate.admit(incoming) { - return Some(frame); - } - } - } - pub fn poll(&mut self) -> Poll { loop { let incoming = match self.pending.pop_front() { @@ -475,7 +437,7 @@ impl Connection { fn response(&mut self, id: u64, deadline: Instant) -> Result { loop { - match self.recv_before(deadline)? { + match recv_before(&self.incoming, deadline)? { Incoming::Control(ServerFrame::Response(response)) if response.id == id => { if let ResponseBody::Attached(attached) = &response.body { self.gate.attached(attached.generation); @@ -486,10 +448,6 @@ impl Connection { } } } - - fn recv_before(&mut self, deadline: Instant) -> Result { - recv_before(&self.incoming, deadline) - } } fn handshake( @@ -498,7 +456,10 @@ fn handshake( pending: &mut VecDeque, addr: &EndpointAddr, ) -> Result { - handle.send(ClientFrame::hello("tarp@client")); + handle.send(ClientFrame::Hello(protocol::Hello { + protocol_version: protocol::PROTOCOL_VERSION, + client_name: "tarp@client".into(), + })); let deadline = Instant::now() + Duration::from_secs(10); loop { match recv_before(incoming, deadline)? { diff --git a/crates/tarpc/tests/daemon.rs b/crates/tarpc/tests/daemon.rs index 6fab17a..72c6a8d 100644 --- a/crates/tarpc/tests/daemon.rs +++ b/crates/tarpc/tests/daemon.rs @@ -27,13 +27,6 @@ fn start_daemon(dir: &Path) -> EndpointAddr { start_daemon_with(dir, "") } -fn pair(dir: &Path) { - let path = AllowList::path(&dir.join("state")); - let mut list = AllowList::read(&path).unwrap(); - list.add(tarpc::identity().unwrap().id(), Some("test".into())); - list.write(&path).unwrap(); -} - fn start_daemon_with(dir: &Path, config: &str) -> EndpointAddr { tarpc::use_settings(offline()); tarpc::use_identity(Identity::generate()); @@ -273,7 +266,10 @@ fn an_unpaired_client_is_refused_until_it_is_paired() { Ok(_) => panic!("an unpaired client got in"), } - pair(dir.path()); + let path = AllowList::path(&dir.path().join("state")); + let mut list = AllowList::read(&path).unwrap(); + list.add(tarpc::identity().unwrap().id(), Some("test".into())); + list.write(&path).unwrap(); let mut connection = Connection::connect(addr).expect("a paired client gets in"); connection .call::(&(), TIMEOUT) diff --git a/crates/tarpd/src/config.rs b/crates/tarpd/src/config.rs index f5da541..987878b 100644 --- a/crates/tarpd/src/config.rs +++ b/crates/tarpd/src/config.rs @@ -1,7 +1,4 @@ -use std::{ - net::SocketAddr, - path::{Path, PathBuf}, -}; +use std::{net::SocketAddr, path::PathBuf}; use confique::Layer as _; @@ -143,17 +140,18 @@ pub fn load(args: &Args) -> Result { let path = match &args.config { Some(path) if !path.exists() => return Err(Error::ConfigMissing(path.clone())), - Some(path) => Some(path.clone()), - None => default_path(), + Some(path) => path.clone(), + None => std::env::var_os("TARPD_CONFIG").map_or_else( + || xdg_dir("XDG_CONFIG_HOME", ".config").join("tarpd/config.toml"), + PathBuf::from, + ), }; - let mut builder = ::builder() + Ok(::builder() .preloaded(flags) - .env(); - if let Some(path) = path { - builder = builder.file(path); - } - Ok(builder.load()?) + .env() + .file(path) + .load()?) } pub fn template() -> String { @@ -165,14 +163,7 @@ impl Config { self.server .state_dir .clone() - .unwrap_or_else(crate::state::default_state_dir) - } - - pub fn key_path(&self) -> PathBuf { - self.server - .secret_key_file - .clone() - .unwrap_or_else(|| self.state_dir().join("endpoint.key")) + .unwrap_or_else(|| xdg_dir("XDG_STATE_HOME", ".local/state").join("tarpd")) } pub fn allow_list_path(&self) -> PathBuf { @@ -195,7 +186,12 @@ impl Config { } pub fn identity(&self) -> Result { - Ok(transport::Identity::load_or_create(&self.key_path())?) + let key_path = self + .server + .secret_key_file + .clone() + .unwrap_or_else(|| self.state_dir().join("endpoint.key")); + Ok(transport::Identity::load_or_create(&key_path)?) } pub fn net(&self) -> Result { @@ -207,26 +203,21 @@ impl Config { } } -fn default_path() -> Option { - if let Some(path) = std::env::var_os("TARPD_CONFIG") { - return Some(path.into()); - } - Some(xdg_dir("XDG_CONFIG_HOME", ".config").join("tarpd/config.toml")) -} - fn xdg_dir(var: &str, fallback: &str) -> PathBuf { std::env::var_os(var) .map(PathBuf::from) .filter(|path| path.is_absolute()) - .unwrap_or_else(|| home().join(fallback)) -} - -fn home() -> PathBuf { - dirs::home_dir().unwrap_or_else(|| Path::new("/").to_path_buf()) + .unwrap_or_else(|| { + dirs::home_dir() + .unwrap_or_else(|| PathBuf::from("/")) + .join(fallback) + }) } #[cfg(test)] mod tests { + use std::path::Path; + use clap::Parser; use super::*; @@ -283,15 +274,4 @@ mod tests { let args = Args::parse_from(["tarpd", "--config", path.to_str().unwrap()]); assert!(matches!(load(&args), Err(Error::Config(_)))); } - - #[test] - fn the_template_covers_every_section() { - let template = template(); - for section in ["[server]", "[log]", "[terminal]", "[script]"] { - assert!( - template.contains(section), - "{section} missing from\n{template}" - ); - } - } } diff --git a/crates/tarpd/src/daemon.rs b/crates/tarpd/src/daemon.rs index 8c343d9..a89f45b 100644 --- a/crates/tarpd/src/daemon.rs +++ b/crates/tarpd/src/daemon.rs @@ -1,15 +1,7 @@ use std::path::PathBuf; use crossbeam_channel::Receiver; -use protocol::{ - Attached, - DetachReason, - Eval, - Method, - ServerFrame, - Value, - methods::{BUILT_IN, api}, -}; +use protocol::{Attached, DetachReason, Eval, Method, ServerFrame, Value, methods::api}; use tracing::info; use crate::{ @@ -19,7 +11,7 @@ use crate::{ id::{ClientId, DaemonId, TerminalId}, scripts::Scripts, terminal::PtyEvent, - world::{Attach, World, answer}, + world::{Attach, World, answer, is_built_in}, }; pub struct Daemon { @@ -45,30 +37,31 @@ impl Daemon { .expect("the event receiver is taken once") } - pub fn on_terminal_event(&mut self, id: TerminalId, event: PtyEvent) { - self.world.on_terminal_event(id, event); - } - pub fn attach(&mut self, client: ClientId, force: bool) -> Result { if let Attach::TookOver { from } = self.world.attach(client, force)? { let by = self.world.client(client)?.name.clone(); if let Ok(displaced) = self.world.client(from) { displaced .outbox - .send_control(ServerFrame::detached(DetachReason::TakenOver, by)); + .send_control(ServerFrame::Detached(protocol::Detached { + reason: DetachReason::TakenOver, + by, + })); } } - self.world.nudge_all(); + for terminal in self + .world + .terminals() + .filter(|terminal| terminal.is_running()) + { + terminal.nudge_foreground(); + } Ok(Attached { terminals: self.world.snapshots(), generation: self.world.client(client)?.generation, }) } - pub fn detach(&mut self, client: ClientId) -> Result<(), RequestError> { - self.world.detach(client) - } - pub fn eval(&mut self, eval: Eval) -> Result { self.scripts.eval(eval, &mut self.world) } @@ -95,10 +88,14 @@ impl Daemon { pub fn call(&mut self, method: &str, params: Value) -> Result { if method == api::List::NAME { - return answer::(params, |()| Ok(self.methods())); + return answer::(params, |()| Ok(self.scripts.method_infos())); } if method == api::Describe::NAME { - return answer::(params, |params| self.describe(¶ms.method)); + return answer::(params, |params| { + self.scripts + .method_doc(¶ms.method) + .ok_or(RequestError::UnknownMethod(params.method)) + }); } if is_built_in(method) { return self.world.call(method, params); @@ -108,20 +105,6 @@ impl Daemon { } Err(RequestError::UnknownMethod(method.to_owned())) } - - fn methods(&self) -> Vec { - self.scripts.method_infos(&self.world) - } - - fn describe(&self, method: &str) -> Result { - self.scripts - .method_doc(method) - .ok_or_else(|| RequestError::UnknownMethod(method.to_owned())) - } -} - -fn is_built_in(method: &str) -> bool { - BUILT_IN.iter().any(|(name, _, _)| *name == method) } #[cfg(test)] @@ -420,21 +403,6 @@ mod tests { assert_eq!(info.position, protocol::Point { x: 12.5, y: 900.0 }); } - #[test] - fn moving_a_missing_terminal_is_not_found() { - let mut daemon = daemon(); - let missing = TerminalId(uuid::Uuid::from_u128(9)); - let params = Value::from_serialize(&terminal::MoveParams { - terminal: missing.into(), - position: protocol::Point::default(), - }) - .unwrap(); - assert_eq!( - daemon.call(terminal::Move::NAME, params), - Err(RequestError::NoSuchTerminal(missing)) - ); - } - #[test] fn a_missing_terminal_is_not_found() { let mut daemon = daemon(); diff --git a/crates/tarpd/src/extensions/mod.rs b/crates/tarpd/src/extensions/mod.rs index 457b0c0..4772333 100644 --- a/crates/tarpd/src/extensions/mod.rs +++ b/crates/tarpd/src/extensions/mod.rs @@ -41,17 +41,13 @@ pub struct Extensions { impl Default for Extensions { fn default() -> Self { - Self::new() - } -} - -impl Extensions { - pub fn new() -> Self { Self { extensions: vec![Box::new(user_vars::Scanner::default())], } } +} +impl Extensions { /// Feed one chunk of output, returning everything the extensions found. pub fn feed(&mut self, bytes: &[u8]) -> Vec { let mut out = Vec::new(); diff --git a/crates/tarpd/src/outbox.rs b/crates/tarpd/src/outbox.rs index 3abe13f..46b66f2 100644 --- a/crates/tarpd/src/outbox.rs +++ b/crates/tarpd/src/outbox.rs @@ -72,17 +72,30 @@ impl Outbox { pub fn send_output(&self, terminal: Uuid, generation: u64, data: Vec) -> Sent { let len = data.len(); - self.push_output( - terminal, - generation, - len, - ServerFrame::output(terminal, data), + self.push_stream( + StreamItem { + terminal, + generation, + frame: ServerFrame::output(terminal, data), + last: false, + len, + }, + true, ) } pub fn send_resync(&self, terminal: Uuid, generation: u64, vt: Vec) -> Sent { let len = vt.len(); - self.push_output(terminal, generation, len, ServerFrame::resync(terminal, vt)) + self.push_stream( + StreamItem { + terminal, + generation, + frame: ServerFrame::Resync(protocol::Resync { terminal, vt }), + last: false, + len, + }, + true, + ) } pub fn send_terminal_event( @@ -92,27 +105,19 @@ impl Outbox { frame: ServerFrame, last: bool, ) -> Sent { - let mut state = self.lock(); - if state.closed || state.wedged { - return Sent::Wedged; - } - if state.stream.len() >= STREAM_CAP { - state.wedged = true; - self.ready.notify_all(); - return Sent::Wedged; - } - state.stream.push_back(StreamItem { - terminal, - generation, - frame, - last, - len: 0, - }); - self.ready.notify_all(); - Sent::Queued + self.push_stream( + StreamItem { + terminal, + generation, + frame, + last, + len: 0, + }, + false, + ) } - fn push_output(&self, terminal: Uuid, generation: u64, len: usize, frame: ServerFrame) -> Sent { + fn push_stream(&self, item: StreamItem, droppable: bool) -> Sent { let mut state = self.lock(); if state.closed || state.wedged { return Sent::Wedged; @@ -122,21 +127,14 @@ impl Outbox { self.ready.notify_all(); return Sent::Wedged; } - if state.output_bytes + len > OUTPUT_CAP && !state.stream.is_empty() { + if droppable && state.output_bytes + item.len > OUTPUT_CAP && !state.stream.is_empty() { return Sent::Dropped; } - state.output_bytes += len; - state.stream.push_back(StreamItem { - terminal, - generation, - frame, - last: false, - len, - }); + state.output_bytes += item.len; + state.stream.push_back(item); self.ready.notify_all(); Sent::Queued } - pub fn recv_control(&self) -> Option { let mut state = self.lock(); loop { diff --git a/crates/tarpd/src/scripts.rs b/crates/tarpd/src/scripts.rs index 8cf1544..a75f49f 100644 --- a/crates/tarpd/src/scripts.rs +++ b/crates/tarpd/src/scripts.rs @@ -15,7 +15,7 @@ use tracing::{debug, error, info, trace, warn}; use crate::{ RequestError, - world::{self, World}, + world::{World, is_built_in}, }; #[derive(Debug, Clone, Default)] @@ -30,26 +30,6 @@ struct ScriptMethod { function: Function, } -impl ScriptMethod { - fn info(&self, name: &str) -> api::MethodInfo { - api::MethodInfo { - name: name.to_owned(), - summary: self.doc.summary.clone(), - lua: true, - } - } - - fn doc(&self, name: &str) -> api::MethodDoc { - api::MethodDoc { - name: name.to_owned(), - summary: self.doc.summary.clone(), - description: self.doc.description.clone(), - lua: true, - example: self.doc.example.clone(), - } - } -} - type MethodTable = BTreeMap; struct CallState<'a> { @@ -84,19 +64,8 @@ impl Scripts { self.methods.contains_key(name) } - pub fn list(&self) -> Vec { - self.methods - .iter() - .map(|(name, method)| method.info(name)) - .collect() - } - - pub fn doc(&self, name: &str) -> Option { - self.methods.get(name).map(|method| method.doc(name)) - } - - pub fn method_infos(&self, world: &World) -> Vec { - merge_methods(world, self.methods.iter()) + pub fn method_infos(&self) -> Vec { + merge_methods(&self.methods) } pub fn method_doc(&self, name: &str) -> Option { @@ -105,7 +74,11 @@ impl Scripts { pub fn eval(&mut self, mut request: Eval, world: &mut World) -> Result { let args = to_lua_multi(&self.lua, std::mem::take(&mut request.args))?; - let name = chunk_name(&request); + let name = if request.chunk_name.is_empty() { + "eval".to_owned() + } else { + request.chunk_name.clone() + }; let source = request.source; self.run_scoped(world, move |lua| { lua.load(&source) @@ -160,14 +133,6 @@ impl Scripts { } } -fn chunk_name(request: &Eval) -> String { - if request.chunk_name.is_empty() { - "eval".to_owned() - } else { - request.chunk_name.clone() - } -} - fn install_module(lua: &Lua) -> mlua::Result<()> { let tarp = lua.create_table()?; @@ -220,7 +185,14 @@ fn install_scope<'scope, 'a>( let register = scope.create_function( move |_lua, (name, doc, function): (String, Table, Function)| { - let doc = doc_from_table(&doc)?; + let summary: Option = doc.get("summary")?; + let description: Option = doc.get("description")?; + let example: Option = doc.get("example")?; + let doc = ScriptDoc { + summary: summary.unwrap_or_default(), + description: description.unwrap_or_default(), + example, + }; insert_method(&mut state.methods.borrow_mut(), &name, doc, function) .map_err(mlua::Error::RuntimeError) }, @@ -233,7 +205,13 @@ fn install_scope<'scope, 'a>( table.set("unregister", unregister)?; let log = scope.create_function(|_lua, (level, message): (String, String)| { - log_message(&level, &message); + match level.to_ascii_lowercase().as_str() { + "error" => error!("{message}"), + "warn" | "warning" => warn!("{message}"), + "debug" => debug!("{message}"), + "trace" => trace!("{message}"), + _ => info!("{message}"), + } Ok(()) })?; table.set("log", log)?; @@ -255,17 +233,40 @@ fn set_current(lua: &Lua, table: Option) { } } -fn merge_methods<'a>( - world: &World, - methods: impl Iterator, -) -> Vec { - let mut list = world.built_in_methods(); - list.extend(methods.map(|(name, method)| method.info(name))); - list +fn merge_methods(methods: &MethodTable) -> Vec { + let built_ins = BUILT_IN.iter().map(|(name, summary, _)| api::MethodInfo { + name: (*name).to_owned(), + summary: (*summary).to_owned(), + lua: false, + }); + let scripts = methods.iter().map(|(name, method)| api::MethodInfo { + name: name.clone(), + summary: method.doc.summary.clone(), + lua: true, + }); + built_ins.chain(scripts).collect() } fn find_doc(methods: &MethodTable, name: &str) -> Option { - world::built_in_doc(name).or_else(|| methods.get(name).map(|method| method.doc(name))) + BUILT_IN + .iter() + .find(|(built_in, _, _)| *built_in == name) + .map(|(built_in, summary, description)| api::MethodDoc { + name: (*built_in).to_owned(), + summary: (*summary).to_owned(), + description: (*description).to_owned(), + lua: false, + example: None, + }) + .or_else(|| { + methods.get(name).map(|method| api::MethodDoc { + name: name.to_owned(), + summary: method.doc.summary.clone(), + description: method.doc.description.clone(), + lua: true, + example: method.doc.example.clone(), + }) + }) } fn dispatch( @@ -275,9 +276,7 @@ fn dispatch( params: Option, ) -> mlua::Result { if name == api::List::NAME { - let w = state.world.borrow(); - let m = state.methods.borrow(); - let list = merge_methods(&w, m.iter()); + let list = merge_methods(&state.methods.borrow()); return to_lua(lua, Value::from_serialize(&list).map_err(lua_err)?).map_err(lua_err); } if name == api::Describe::NAME { @@ -303,7 +302,7 @@ fn dispatch( .map_err(lua_err)? .unwrap_or_default(); - if BUILT_IN.iter().any(|(built_in, _, _)| *built_in == name) { + if is_built_in(name) { let result = state .world .borrow_mut() @@ -351,7 +350,7 @@ fn insert_method( doc: ScriptDoc, function: Function, ) -> Result<(), String> { - if BUILT_IN.iter().any(|(built_in, _, _)| *built_in == name) { + if is_built_in(name) { return Err(format!("{name:?} is a built-in method")); } if methods.contains_key(name) { @@ -361,27 +360,6 @@ fn insert_method( Ok(()) } -fn doc_from_table(table: &Table) -> mlua::Result { - let summary: Option = table.get("summary")?; - let description: Option = table.get("description")?; - let example: Option = table.get("example")?; - Ok(ScriptDoc { - summary: summary.unwrap_or_default(), - description: description.unwrap_or_default(), - example, - }) -} - -fn log_message(level: &str, message: &str) { - match level.to_ascii_lowercase().as_str() { - "error" => error!("{message}"), - "warn" | "warning" => warn!("{message}"), - "debug" => debug!("{message}"), - "trace" => trace!("{message}"), - _ => info!("{message}"), - } -} - fn lua_err(error: impl Into) -> mlua::Error { mlua::Error::RuntimeError(error.into().to_string()) } @@ -523,27 +501,6 @@ mod tests { ) } - #[test] - fn a_chunk_returns_its_value() { - let mut scripts = Scripts::new(5000); - let mut world = world(); - let value = eval(&mut scripts, &mut world, "return 1 + 1").unwrap(); - assert_eq!(value, Value::from_serialize(&2_i64).unwrap()); - } - - #[test] - fn a_chunk_can_call_a_method() { - let mut scripts = Scripts::new(5000); - let mut world = world(); - let value = eval( - &mut scripts, - &mut world, - "return #tarp.call('terminal.list')", - ) - .unwrap(); - assert_eq!(value, Value::from_serialize(&0_i64).unwrap()); - } - #[test] fn the_tarp_module_is_stable_across_calls() { let mut scripts = Scripts::new(5000); @@ -578,14 +535,6 @@ mod tests { assert_eq!(value, Value::from_serialize(&0_i64).unwrap()); } - #[test] - fn dotted_sugar_calls_a_built_in() { - let mut scripts = Scripts::new(5000); - let mut world = world(); - let value = eval(&mut scripts, &mut world, "return #tarp.terminal.list()").unwrap(); - assert_eq!(value, Value::from_serialize(&0_i64).unwrap()); - } - #[test] fn a_chunk_sees_its_arguments() { let mut scripts = Scripts::new(5000); @@ -603,46 +552,6 @@ mod tests { assert_eq!(value, Value::from_serialize(&5_i64).unwrap()); } - #[test] - fn a_registered_method_is_listed_described_and_callable() { - let mut scripts = Scripts::new(5000); - let mut world = world(); - eval( - &mut scripts, - &mut world, - r#" - tarp.register("my.greet", { - summary = "Greet someone.", - description = "Returns a greeting.", - }, function(params) - return "hello, " .. params.name - end) - "#, - ) - .unwrap(); - - assert!(scripts.has("my.greet")); - let listed = scripts.list(); - assert_eq!(listed.len(), 1); - assert_eq!(listed[0].summary, "Greet someone."); - assert!(listed[0].lua); - assert_eq!( - scripts.doc("my.greet").unwrap().description, - "Returns a greeting." - ); - - #[derive(serde::Serialize)] - struct Greet { - name: String, - } - let params = Value::from_serialize(&Greet { - name: "ada".to_owned(), - }) - .unwrap(); - let value = scripts.call("my.greet", params, &mut world).unwrap(); - assert_eq!(value, Value::from_serialize(&"hello, ada").unwrap()); - } - #[test] fn a_built_in_name_cannot_be_registered() { let mut scripts = Scripts::new(5000); diff --git a/crates/tarpd/src/server.rs b/crates/tarpd/src/server.rs index 2fb517e..0c52a5c 100644 --- a/crates/tarpd/src/server.rs +++ b/crates/tarpd/src/server.rs @@ -182,7 +182,7 @@ fn spawn_event_thread(daemon: Shared, events: Receiver<(TerminalId, PtyEvent)>) .name("tarpd-events".into()) .spawn(move || { for (id, event) in events { - lock(&daemon).on_terminal_event(id, event); + lock(&daemon).world.on_terminal_event(id, event); } }); if let Err(error) = spawned { @@ -192,7 +192,7 @@ fn spawn_event_thread(daemon: Shared, events: Receiver<(TerminalId, PtyEvent)>) fn converse( reader: impl Read, - control: Writer, + mut control: Writer, link: Link, daemon: &Shared, ) -> Result<(), ProtocolError> { @@ -243,7 +243,16 @@ fn converse( thread::Builder::new().name("tarpd-write".into()).spawn({ let outbox = Arc::clone(&outbox); let connection = connection.clone(); - move || control_loop(control, outbox, connection) + move || { + while let Some(frame) = outbox.recv_control() { + if let Err(error) = write_frame(&mut control, &frame) { + debug!(%error, "could not write a frame; ending the connection"); + break; + } + } + let _ = control.shutdown(); + connection.close(CloseReason::Done.code().into(), b"done"); + } }), thread::Builder::new().name("tarpd-streams".into()).spawn({ let outbox = Arc::clone(&outbox); @@ -295,17 +304,6 @@ fn converse( result } -fn control_loop(mut writer: Writer, outbox: Arc, connection: Connection) { - while let Some(frame) = outbox.recv_control() { - if let Err(error) = write_frame(&mut writer, &frame) { - debug!(%error, "could not write a frame; ending the connection"); - break; - } - } - let _ = writer.shutdown(); - connection.close(CloseReason::Done.code().into(), b"done"); -} - fn stream_loop(connection: Connection, outbox: Arc) { let mut streams: HashMap = HashMap::new(); let mut finished: HashSet<(Uuid, u64)> = HashSet::new(); @@ -379,37 +377,32 @@ fn open_stream( fn respond(request: Request, client: ClientId, daemon: &Shared) -> Response { let id = request.id; let mut daemon = lock(daemon); - match request.body { + let result = match request.body { RequestBody::Call(call) => { debug!(%client, method = %call.method, "call"); - match daemon.call(&call.method, call.params) { - Ok(value) => Response::result(id, value), - Err(error) => Response::error(id, error.code(), error.to_string()), - } + daemon.call(&call.method, call.params) } RequestBody::Eval(eval) => { debug!(%client, chunk = %eval.chunk_name, "eval"); - match daemon.eval(eval) { - Ok(value) => Response::result(id, value), - Err(error) => Response::error(id, error.code(), error.to_string()), - } + daemon.eval(eval) } RequestBody::Attach { force } => match daemon.attach(client, force) { - Ok(attached) => Response::attached(id, attached), - Err(error) => Response::error(id, error.code(), error.to_string()), - }, - RequestBody::Detach => match daemon.detach(client) { - Ok(()) => Response::result(id, Value::Null), - Err(error) => Response::error(id, error.code(), error.to_string()), - }, - RequestBody::Subscribe(patterns) => match daemon.world.subscribe(client, patterns) { - Ok(()) => Response::result(id, Value::Null), - Err(error) => Response::error(id, error.code(), error.to_string()), - }, - RequestBody::Unsubscribe(patterns) => match daemon.world.unsubscribe(client, &patterns) { - Ok(()) => Response::result(id, Value::Null), - Err(error) => Response::error(id, error.code(), error.to_string()), + Ok(attached) => return Response::attached(id, attached), + Err(error) => Err(error), }, + RequestBody::Detach => daemon.world.detach(client).map(|()| Value::Null), + RequestBody::Subscribe(patterns) => daemon + .world + .subscribe(client, patterns) + .map(|()| Value::Null), + RequestBody::Unsubscribe(patterns) => daemon + .world + .unsubscribe(client, &patterns) + .map(|()| Value::Null), + }; + match result { + Ok(value) => Response::result(id, value), + Err(error) => Response::error(id, error.code(), error.to_string()), } } diff --git a/crates/tarpd/src/shell.rs b/crates/tarpd/src/shell.rs index 42e2e35..c349509 100644 --- a/crates/tarpd/src/shell.rs +++ b/crates/tarpd/src/shell.rs @@ -37,7 +37,8 @@ pub fn command(id: TerminalId, params: &SpawnParams, config: &TerminalConfig) -> command.env("COLORTERM", "truecolor"); command.env("TERM_PROGRAM", "tarp"); - command.env("TARP", tarp_env()); + let endpoint = ENDPOINT.get().map(String::as_str).unwrap_or_default(); + command.env("TARP", format!("{endpoint},{}", std::process::id())); command.env("TARP_ID", id.to_string()); for (key, value) in ¶ms.env { @@ -62,8 +63,3 @@ static ENDPOINT: OnceLock = OnceLock::new(); pub fn set_endpoint(endpoint: String) { let _ = ENDPOINT.set(endpoint); } - -fn tarp_env() -> String { - let endpoint = ENDPOINT.get().map(String::as_str).unwrap_or_default(); - format!("{endpoint},{}", std::process::id()) -} diff --git a/crates/tarpd/src/snapshot.rs b/crates/tarpd/src/snapshot.rs index c42d6ee..87e0ced 100644 --- a/crates/tarpd/src/snapshot.rs +++ b/crates/tarpd/src/snapshot.rs @@ -50,7 +50,11 @@ fn serialize(terminal: &Terminal<'static, 'static>, scrollback_rows: usize) -> R let mut formatter = Formatter::new(terminal, options)?; out.extend_from_slice(formatter.format_alloc(None)?.as_ref()); - push_viewport_into_history(&mut out, scrollback - first, rows); + let scrolls = (scrollback - first).min(usize::from(rows)); + out.extend_from_slice(format!("\x1b[{rows};1H").as_bytes()); + for _ in 0..scrolls { + out.extend_from_slice(b"\r\n"); + } } out.extend_from_slice(RESET_VIEWPORT); @@ -79,16 +83,12 @@ fn serialize(terminal: &Terminal<'static, 'static>, scrollback_rows: usize) -> R if let Ok(pwd) = terminal.pwd() && !pwd.is_empty() { - out.extend_from_slice(b"\x1b]7;"); - push_osc_text(&mut out, pwd); - out.extend_from_slice(b"\x1b\\"); + push_osc(&mut out, b"7", pwd); } if let Ok(title) = terminal.title() && !title.is_empty() { - out.extend_from_slice(b"\x1b]2;"); - push_osc_text(&mut out, title); - out.extend_from_slice(b"\x1b\\"); + push_osc(&mut out, b"2", title); } Ok(out) @@ -128,19 +128,15 @@ pub fn capture( Ok(formatter.format_alloc(None)?.as_ref().to_vec()) } -fn push_viewport_into_history(out: &mut Vec, replayed_rows: usize, rows: u16) { - let scrolls = replayed_rows.min(usize::from(rows)); - out.extend_from_slice(format!("\x1b[{rows};1H").as_bytes()); - for _ in 0..scrolls { - out.extend_from_slice(b"\r\n"); - } -} - -fn push_osc_text(out: &mut Vec, text: &str) { +fn push_osc(out: &mut Vec, code: &[u8], text: &str) { + out.extend_from_slice(b"\x1b]"); + out.extend_from_slice(code); + out.push(b';'); out.extend( text.bytes() .filter(|byte| !byte.is_ascii_control() && *byte != 0x7f), ); + out.extend_from_slice(b"\x1b\\"); } fn history_point(x: u16, y: usize) -> Point { diff --git a/crates/tarpd/src/state.rs b/crates/tarpd/src/state.rs index 4cbebb6..f5a4add 100644 --- a/crates/tarpd/src/state.rs +++ b/crates/tarpd/src/state.rs @@ -75,47 +75,12 @@ impl EndpointFile { } } -fn state_home() -> PathBuf { - std::env::var_os("XDG_STATE_HOME") - .map(PathBuf::from) - .filter(|path| path.is_absolute()) - .unwrap_or_else(|| { - dirs::home_dir() - .unwrap_or_else(|| PathBuf::from("/")) - .join(".local/state") - }) -} - -pub fn default_state_dir() -> PathBuf { - state_home().join("tarpd") -} - #[cfg(test)] mod tests { use transport::Identity; use super::*; - #[test] - fn an_unspecified_bind_is_reached_on_loopback() { - let id = Identity::generate().id(); - let file = EndpointFile::new( - id, - &[ - "0.0.0.0:4000".parse().unwrap(), - "[::]:4001".parse().unwrap(), - ], - ); - assert_eq!( - file.addrs, - [ - "127.0.0.1:4000".parse::().unwrap(), - "[::1]:4001".parse().unwrap() - ] - ); - assert_eq!(file.addr().unwrap().id, id); - } - #[test] fn the_file_round_trips_and_removes() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/tarpd/src/terminal.rs b/crates/tarpd/src/terminal.rs index 34633a8..d96932f 100644 --- a/crates/tarpd/src/terminal.rs +++ b/crates/tarpd/src/terminal.rs @@ -1,5 +1,4 @@ use std::{ - collections::BTreeMap, io::{Read, Write}, sync::{ Arc, @@ -21,7 +20,6 @@ use libghostty_vt::{ DeviceAttributeFeature, DeviceAttributes, DeviceType, - Mode, Options, PrimaryDeviceAttributes, SecondaryDeviceAttributes, @@ -172,15 +170,13 @@ impl Terminal { .unwrap_or(self.size) } - pub fn process(&self) -> Process { - self.inner + pub fn is_running(&self) -> bool { + let process = self + .inner .as_ref() .map(TerminalHandle::process) - .unwrap_or(self.process) - } - - pub fn is_running(&self) -> bool { - matches!(self.process(), Process::Running { .. }) + .unwrap_or(self.process); + matches!(process, Process::Running { .. }) } pub fn snapshot(&self) -> Vec { @@ -289,9 +285,6 @@ enum TermCommand { }, Resync, NudgeForeground, - Focus { - focused: bool, - }, Signal(i32), } @@ -301,7 +294,6 @@ pub struct TerminalHandle { rows: u16, title: Arc>, cwd: Arc>, - user_vars: Arc>>, state: Arc>, command: crossbeam_channel::Sender, } @@ -416,8 +408,6 @@ impl TerminalHandle { let title_for_worker = Arc::clone(&title); let cwd = Arc::new(Mutex::new(String::new())); let cwd_for_worker = Arc::clone(&cwd); - let user_vars = Arc::new(Mutex::new(BTreeMap::new())); - let user_vars_for_worker = Arc::clone(&user_vars); let state = Arc::new(Mutex::new(Process::Running { pid: child_pid.unwrap_or(0), })); @@ -451,7 +441,6 @@ impl TerminalHandle { cwd: cwd_for_worker, last_cwd: String::new(), extensions: Extensions::default(), - user_vars: user_vars_for_worker, state: state_for_worker, }; run_worker(id, worker, output_rx, command_rx, on_event); @@ -468,7 +457,6 @@ impl TerminalHandle { rows, title, cwd, - user_vars, state, command: command_tx, }) @@ -503,15 +491,6 @@ impl TerminalHandle { .clone() } - pub fn user_vars(&self) -> Vec<(String, String)> { - self.user_vars - .lock() - .unwrap_or_else(|poison| poison.into_inner()) - .iter() - .map(|(name, value)| (name.clone(), value.clone())) - .collect() - } - pub fn write_input(&self, bytes: &[u8]) { if bytes.is_empty() { return; @@ -572,10 +551,6 @@ impl TerminalHandle { let _ = self.command.send(TermCommand::NudgeForeground); } - pub fn focus(&self, focused: bool) { - let _ = self.command.send(TermCommand::Focus { focused }); - } - pub fn signal(&self, signal: i32) { let _ = self.command.send(TermCommand::Signal(signal)); } @@ -593,7 +568,6 @@ struct VtWorker { cwd: Arc>, last_cwd: String, extensions: Extensions, - user_vars: Arc>>, state: Arc>, } @@ -617,7 +591,7 @@ impl VtWorker { self.apply(events) } - /// Act on what an extension found: answer a query or keep a shell + /// Act on what an extension found: answer a query or pass on a shell /// variable. Returns the events for the daemon. fn apply(&mut self, events: Vec) -> Vec { let mut out = Vec::new(); @@ -625,16 +599,6 @@ impl VtWorker { match event { ExtensionEvent::Reply(bytes) => self.input.send(&bytes), ExtensionEvent::UserVar { name, value } => { - let mut vars = self - .user_vars - .lock() - .unwrap_or_else(|poison| poison.into_inner()); - if value.is_empty() { - vars.remove(&name); - } else { - vars.insert(name.clone(), value.clone()); - } - drop(vars); out.push(PtyEvent::UserVar { name, value }); } } @@ -671,6 +635,30 @@ impl VtWorker { self.apply(events) } + fn output(&mut self, message: Option, on_event: &impl Fn(PtyEvent)) -> bool { + match message { + Some(PtyEvent::Output(bytes)) => { + let events = self.feed(&bytes); + on_event(PtyEvent::Output(bytes)); + for event in events { + on_event(event); + } + false + } + Some(PtyEvent::Exited { status }) => { + for event in self.set_exited(status) { + on_event(event); + } + on_event(PtyEvent::Exited { status }); + true + } + Some( + PtyEvent::WorkingDirectory(_) | PtyEvent::UserVar { .. } | PtyEvent::Resync(_), + ) => false, + None => true, + } + } + fn serialize(&mut self, scrollback_rows: usize, what: &str) -> Vec { match snapshot::snapshot(&mut self.terminal, scrollback_rows) { Ok(blob) => blob, @@ -681,7 +669,7 @@ impl VtWorker { } } - fn command(&mut self, command: TermCommand) -> Option { + fn command(&mut self, command: TermCommand, on_event: &impl Fn(PtyEvent)) { match command { TermCommand::Input(bytes) => self.input.send(&bytes), TermCommand::Resize { cols, rows } => self.resize(cols, rows), @@ -706,17 +694,17 @@ impl VtWorker { TermCommand::Resync => { let blob = self.serialize(snapshot::MAX_RESYNC_SCROLLBACK_ROWS, "resync"); debug!(id = %self.id, len = blob.len(), "resyncing a stale client"); - return Some(PtyEvent::Resync(blob)); + on_event(PtyEvent::Resync(blob)); } TermCommand::NudgeForeground => self.nudge_foreground(), - TermCommand::Focus { focused } => { - if self.terminal.mode(Mode::FOCUS_EVENT).unwrap_or(false) { - self.input.send(if focused { b"\x1b[I" } else { b"\x1b[O" }); + TermCommand::Signal(signal) => match self.child_pid { + Some(pid) => { + debug!(id = %self.id, pid, signal, "signalling the shell"); + unsafe { libc::kill(-(pid as i32), signal) }; } - } - TermCommand::Signal(signal) => self.signal(signal), + None => warn!(id = %self.id, "no pid for this terminal; cannot signal it"), + }, } - None } fn resize(&mut self, cols: u16, rows: u16) { @@ -754,15 +742,6 @@ impl VtWorker { ); unsafe { libc::kill(-group, libc::SIGWINCH) }; } - - fn signal(&self, signal: i32) { - let Some(pid) = self.child_pid else { - warn!(id = %self.id, "no pid for this terminal; cannot signal it"); - return; - }; - debug!(id = %self.id, pid, signal, "signalling the shell"); - unsafe { libc::kill(-(pid as i32), signal) }; - } } fn child_cwd(pid: Option) -> Option { @@ -819,9 +798,7 @@ fn run_worker( loop { match command_rx.try_recv() { Ok(command) => { - if let Some(event) = worker.command(command) { - on_event(event); - } + worker.command(command, &on_event); continue; } Err(TryRecvError::Empty) => {} @@ -830,25 +807,10 @@ fn run_worker( if !reader_done { match output_rx.try_recv() { - Ok(PtyEvent::Output(bytes)) => { - let events = worker.feed(&bytes); - on_event(PtyEvent::Output(bytes)); - for event in events { - on_event(event); - } - continue; - } - Ok(PtyEvent::Exited { status }) => { - for event in worker.set_exited(status) { - on_event(event); - } - on_event(PtyEvent::Exited { status }); - reader_done = true; + Ok(message) => { + reader_done = worker.output(Some(message), &on_event); continue; } - Ok( - PtyEvent::WorkingDirectory(_) | PtyEvent::UserVar { .. } | PtyEvent::Resync(_), - ) => {} Err(TryRecvError::Empty) => {} Err(TryRecvError::Disconnected) => { reader_done = true; @@ -859,11 +821,7 @@ fn run_worker( if reader_done { match command_rx.recv() { - Ok(command) => { - if let Some(event) = worker.command(command) { - on_event(event); - } - } + Ok(command) => worker.command(command, &on_event), Err(_) => break, } continue; @@ -871,34 +829,11 @@ fn run_worker( crossbeam_channel::select! { recv(command_rx) -> message => match message { - Ok(command) => { - if let Some(event) = worker.command(command) { - on_event(event); - } - } + Ok(command) => worker.command(command, &on_event), Err(RecvError) => break, }, - recv(output_rx) -> message => match message { - Ok(PtyEvent::Output(bytes)) => { - let events = worker.feed(&bytes); - on_event(PtyEvent::Output(bytes)); - for event in events { - on_event(event); - } - } - Ok(PtyEvent::Exited { status }) => { - for event in worker.set_exited(status) { - on_event(event); - } - on_event(PtyEvent::Exited { status }); - reader_done = true; - } - Ok( - PtyEvent::WorkingDirectory(_) - | PtyEvent::UserVar { .. } - | PtyEvent::Resync(_), - ) => {} - Err(RecvError) => reader_done = true, + recv(output_rx) -> message => { + reader_done = worker.output(message.ok(), &on_event); }, recv(crossbeam_channel::at(next_cwd_poll)) -> _ => { next_cwd_poll = Instant::now() + CWD_POLL_INTERVAL; @@ -976,15 +911,3 @@ fn device_attributes() -> DeviceAttributes { tertiary: Default::default(), } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_palette_is_the_standard_xterm_one() { - assert_eq!(PALETTE[0], rgb(0x00, 0x00, 0x00)); - assert_eq!(PALETTE[15], rgb(0xFF, 0xFF, 0xFF)); - assert_eq!(PALETTE.len(), 16); - } -} diff --git a/crates/tarpd/src/world.rs b/crates/tarpd/src/world.rs index 93827d3..3a1977b 100644 --- a/crates/tarpd/src/world.rs +++ b/crates/tarpd/src/world.rs @@ -13,7 +13,7 @@ use protocol::{ TerminalSnapshot, Value, Welcome, - methods::{BUILT_IN, Method, api, client, daemon, net, terminal}, + methods::{BUILT_IN, Method, client, daemon, net, terminal}, }; use tracing::info; use transport::{Endpoint, Link}; @@ -276,53 +276,6 @@ impl World { Ok(id) } - pub fn move_terminal( - &mut self, - id: TerminalId, - position: protocol::Point, - ) -> Result<(), RequestError> { - self.terminal_mut(id)?.position = position; - Ok(()) - } - - pub fn write_terminal(&self, id: TerminalId, data: &str) -> Result<(), RequestError> { - self.terminal(id)?.write_input(data.as_bytes()); - Ok(()) - } - - pub fn resize_terminal( - &mut self, - id: TerminalId, - cols: u16, - rows: u16, - ) -> Result<(), RequestError> { - self.terminal_mut(id)?.resize(cols, rows); - Ok(()) - } - - pub fn signal_terminal( - &self, - id: TerminalId, - signal: Option<&str>, - ) -> Result<(), RequestError> { - let signal = match signal { - Some(name) => signal_number(name) - .ok_or_else(|| RequestError::BadRequest(format!("unknown signal {name:?}")))?, - None => libc::SIGHUP, - }; - self.terminal(id)?.signal(signal); - Ok(()) - } - - pub fn capture_terminal( - &self, - id: TerminalId, - format: terminal::CaptureFormat, - scrollback: bool, - ) -> Result { - Ok(self.terminal(id)?.capture(format, scrollback)) - } - /// One snapshot per terminal still running, for `Attach`. /// /// A finished terminal is kept so its screen can still be read, but it is @@ -346,14 +299,6 @@ impl World { } } - /// Nudge every running terminal's foreground process, so a reattached TUI - /// redraws. - pub fn nudge_all(&self) { - for terminal in self.terminals().filter(|terminal| terminal.is_running()) { - terminal.nudge_foreground(); - } - } - pub fn client_input(&mut self, client: ClientId, id: TerminalId, data: &[u8]) { if self.attached != Some(client) { return; @@ -376,7 +321,15 @@ impl World { match event { PtyEvent::Output(bytes) => self.relay_output(id, bytes), PtyEvent::Resync(vt) => self.relay_resync(id, vt), - PtyEvent::Exited { status } => self.on_exited(id, status), + PtyEvent::Exited { status } => { + self.stale.remove(&id); + self.last_resync.remove(&id); + self.emit( + "terminal.exited", + Some(id), + Value::from_serialize(&status).unwrap_or_default(), + ); + } PtyEvent::WorkingDirectory(path) => self.emit( "terminal.cwd", Some(id), @@ -443,16 +396,6 @@ impl World { self.last_resync.insert(id, Instant::now()); } - fn on_exited(&mut self, id: TerminalId, status: Option) { - self.stale.remove(&id); - self.last_resync.remove(&id); - self.emit( - "terminal.exited", - Some(id), - Value::from_serialize(&status).unwrap_or_default(), - ); - } - fn emit(&self, name: &str, terminal: Option, data: Value) { let frame = ServerFrame::event(name, terminal.map(Into::into), data); for client in self.clients.values() { @@ -527,23 +470,33 @@ impl World { Ok(self.terminal(id)?.info()) }), m if m == terminal::Kill::NAME => answer::(params, |params| { - self.signal_terminal(TerminalId(params.terminal), params.signal.as_deref()) + let signal = match params.signal.as_deref() { + Some(name) => signal_number(name).ok_or_else(|| { + RequestError::BadRequest(format!("unknown signal {name:?}")) + })?, + None => libc::SIGHUP, + }; + self.terminal(TerminalId(params.terminal))?.signal(signal); + Ok(()) }), m if m == terminal::Write::NAME => answer::(params, |params| { - self.write_terminal(TerminalId(params.terminal), ¶ms.data) + self.terminal(TerminalId(params.terminal))? + .write_input(params.data.as_bytes()); + Ok(()) }), m if m == terminal::Resize::NAME => answer::(params, |params| { - self.resize_terminal(TerminalId(params.terminal), params.cols, params.rows) + self.terminal_mut(TerminalId(params.terminal))? + .resize(params.cols, params.rows); + Ok(()) }), m if m == terminal::Move::NAME => answer::(params, |params| { - self.move_terminal(TerminalId(params.terminal), params.position) + self.terminal_mut(TerminalId(params.terminal))?.position = params.position; + Ok(()) }), m if m == terminal::Capture::NAME => answer::(params, |params| { - self.capture_terminal( - TerminalId(params.terminal), - params.format, - params.scrollback, - ) + Ok(self + .terminal(TerminalId(params.terminal))? + .capture(params.format, params.scrollback)) }), m => match BUILT_IN.iter().find(|(name, _, _)| *name == m) { Some((name, _, _)) => Err(RequestError::Unimplemented(name)), @@ -552,17 +505,6 @@ impl World { } } - pub fn built_in_methods(&self) -> Vec { - BUILT_IN - .iter() - .map(|(name, summary, _)| api::MethodInfo { - name: (*name).to_owned(), - summary: (*summary).to_owned(), - lua: false, - }) - .collect() - } - fn info(&self) -> daemon::DaemonInfo { daemon::DaemonInfo { id: self.id.to_string(), @@ -583,19 +525,6 @@ impl World { } } -pub fn built_in_doc(name: &str) -> Option { - BUILT_IN - .iter() - .find(|(built_in, _, _)| *built_in == name) - .map(|(built_in, summary, description)| api::MethodDoc { - name: (*built_in).to_owned(), - summary: (*summary).to_owned(), - description: (*description).to_owned(), - lua: false, - example: None, - }) -} - pub(crate) fn answer( params: Value, f: impl FnOnce(M::Params) -> Result, @@ -604,6 +533,10 @@ pub(crate) fn answer( Ok(Value::from_serialize(&output)?) } +pub(crate) fn is_built_in(name: &str) -> bool { + BUILT_IN.iter().any(|(built_in, _, _)| *built_in == name) +} + fn signal_number(name: &str) -> Option { let name = name.trim().to_ascii_uppercase(); let name = name.strip_prefix("SIG").unwrap_or(&name); diff --git a/crates/transport/src/addr.rs b/crates/transport/src/addr.rs index e672aeb..4b12f3e 100644 --- a/crates/transport/src/addr.rs +++ b/crates/transport/src/addr.rs @@ -3,7 +3,7 @@ use std::{ str::FromStr, }; -use iroh::{Endpoint, EndpointAddr, EndpointId, RelayUrl, TransportAddr}; +use iroh::{EndpointAddr, EndpointId, RelayUrl, TransportAddr}; use crate::Error; @@ -33,11 +33,6 @@ pub fn endpoint_addr(id: EndpointId, sockets: &[SocketAddr]) -> EndpointAddr { ) } -/// The address that reaches `endpoint` from the same machine. -pub fn local_addr(endpoint: &Endpoint) -> EndpointAddr { - endpoint_addr(endpoint.id(), &endpoint.bound_sockets()) -} - pub fn parse_addr(input: &str) -> Result { let error = |reason: String| Error::Addr { input: input.to_owned(), diff --git a/crates/transport/src/allow.rs b/crates/transport/src/allow.rs index b4d8235..ef6e6f7 100644 --- a/crates/transport/src/allow.rs +++ b/crates/transport/src/allow.rs @@ -1,13 +1,13 @@ use std::{ fs, - io::{self, Write as _}, + io, path::{Path, PathBuf}, str::FromStr, }; use iroh::EndpointId; -use crate::Error; +use crate::{Error, write_private}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Allowed { @@ -21,10 +21,8 @@ pub struct AllowList { } impl AllowList { - pub const NAME: &str = "allowed_clients"; - pub fn path(state_dir: &Path) -> PathBuf { - state_dir.join(Self::NAME) + state_dir.join("allowed_clients") } pub fn read(path: &Path) -> Result { @@ -60,20 +58,10 @@ impl AllowList { } pub fn write(&self, path: &Path) -> Result<(), Error> { - let io_error = |source| Error::AllowList { + write_private(path, &self.to_string()).map_err(|source| Error::AllowList { path: path.to_path_buf(), source, - }; - let dir = path.parent().unwrap_or_else(|| Path::new(".")); - fs::create_dir_all(dir).map_err(io_error)?; - let mut temporary = tempfile::NamedTempFile::new_in(dir).map_err(io_error)?; - temporary - .write_all(self.to_string().as_bytes()) - .map_err(io_error)?; - temporary - .persist(path) - .map_err(|error| io_error(error.error))?; - Ok(()) + }) } pub fn contains(&self, id: EndpointId) -> bool { diff --git a/crates/transport/src/identity.rs b/crates/transport/src/identity.rs index d23ec4d..3946e1e 100644 --- a/crates/transport/src/identity.rs +++ b/crates/transport/src/identity.rs @@ -1,14 +1,8 @@ -use std::{ - fmt::Write as _, - fs, - io::{self, Write as _}, - path::Path, - str::FromStr, -}; +use std::{fmt::Write as _, fs, io, path::Path, str::FromStr}; use iroh::{EndpointId, SecretKey}; -use crate::Error; +use crate::{Error, write_private}; #[derive(Debug, Clone)] pub struct Identity { @@ -35,7 +29,12 @@ impl Identity { }), Err(error) if error.kind() == io::ErrorKind::NotFound => { let identity = Self::generate(); - write_private(path, &identity.to_hex()).map_err(io_error)?; + let mut hex = String::with_capacity(65); + for byte in identity.secret.to_bytes() { + let _ = write!(hex, "{byte:02x}"); + } + hex.push('\n'); + write_private(path, &hex).map_err(io_error)?; Ok(identity) } Err(error) => Err(io_error(error)), @@ -49,24 +48,6 @@ impl Identity { pub fn secret_key(&self) -> &SecretKey { &self.secret } - - fn to_hex(&self) -> String { - let mut hex = String::with_capacity(65); - for byte in self.secret.to_bytes() { - let _ = write!(hex, "{byte:02x}"); - } - hex.push('\n'); - hex - } -} - -fn write_private(path: &Path, contents: &str) -> io::Result<()> { - let dir = path.parent().unwrap_or_else(|| Path::new(".")); - fs::create_dir_all(dir)?; - let mut temporary = tempfile::NamedTempFile::new_in(dir)?; - temporary.write_all(contents.as_bytes())?; - temporary.persist(path).map_err(|error| error.error)?; - Ok(()) } #[cfg(test)] diff --git a/crates/transport/src/lib.rs b/crates/transport/src/lib.rs index c5df77e..0ff5f41 100644 --- a/crates/transport/src/lib.rs +++ b/crates/transport/src/lib.rs @@ -6,23 +6,23 @@ mod paths; mod settings; mod stream; -use std::sync::OnceLock; +use std::{fs, io, io::Write as _, path::Path, sync::OnceLock}; -use iroh::endpoint::presets; pub use iroh::{ Endpoint, EndpointAddr, EndpointId, endpoint::{Connection, ConnectionError, RecvStream, SendStream}, }; +use iroh::{RelayMode, endpoint::presets}; use tokio::runtime::Runtime; pub use crate::{ - addr::{endpoint_addr, format_addr, local_addr, local_sockets, parse_addr}, + addr::{endpoint_addr, format_addr, local_sockets, parse_addr}, allow::{AllowList, Allowed}, error::Error, identity::Identity, - paths::{Link, PathLog, arrives_locally, describe, endpoint_info}, + paths::{Link, arrives_locally, endpoint_info}, settings::{Relay, Settings}, stream::{Reader, Writer, reader, writer}, }; @@ -52,7 +52,11 @@ pub async fn bind( let mut builder = builder .secret_key(identity.secret_key().clone()) .alpns(alpns) - .relay_mode(settings.relay.mode()); + .relay_mode(match &settings.relay { + Relay::Default => RelayMode::Default, + Relay::Disabled => RelayMode::Disabled, + Relay::Custom(urls) => RelayMode::custom(urls.iter().cloned()), + }); if let Some(addr) = settings.bind { builder = builder .clear_ip_transports() @@ -61,3 +65,12 @@ pub async fn bind( } builder.bind().await.map_err(Error::Bind) } + +pub(crate) fn write_private(path: &Path, contents: &str) -> io::Result<()> { + let dir = path.parent().unwrap_or_else(|| Path::new(".")); + fs::create_dir_all(dir)?; + let mut temporary = tempfile::NamedTempFile::new_in(dir)?; + temporary.write_all(contents.as_bytes())?; + temporary.persist(path).map_err(|error| error.error)?; + Ok(()) +} diff --git a/crates/transport/src/paths.rs b/crates/transport/src/paths.rs index 2dc5472..99c5a2d 100644 --- a/crates/transport/src/paths.rs +++ b/crates/transport/src/paths.rs @@ -8,7 +8,7 @@ use futures::StreamExt as _; use iroh::{ Endpoint, TransportAddr, - endpoint::{Connection, PathEvent as IrohPathEvent}, + endpoint::{Connection, LocalTransportAddr, PathEvent as IrohPathEvent}, }; use protocol::methods::net::{ ConnectionInfo, @@ -25,7 +25,7 @@ use crate::runtime; const HISTORY: usize = 128; #[derive(Debug, Clone)] -pub struct PathLog { +struct PathLog { inner: Arc>, } @@ -36,7 +36,7 @@ struct Log { } impl PathLog { - pub fn watch(connection: &Connection) -> Self { + fn watch(connection: &Connection) -> Self { let log = Self { inner: Arc::new(Mutex::new(Log { connected_at: SystemTime::now(), @@ -65,14 +65,6 @@ impl PathLog { log } - pub fn connected_at(&self) -> SystemTime { - self.lock().connected_at - } - - pub fn history(&self) -> Vec { - self.lock().history.iter().cloned().collect() - } - fn record(&self, event: IrohPathEvent) { match event { IrohPathEvent::Opened { remote_addr, .. } => self.push( @@ -127,36 +119,6 @@ impl PathLog { } } -pub fn describe(connection: &Connection, log: &PathLog) -> ConnectionInfo { - let paths: Vec = connection - .paths() - .iter() - .map(|path| { - let stats = path.stats(); - PathInfo { - kind: kind(path.remote_addr()), - remote: show(path.remote_addr()), - local: local(path.local_addr()), - selected: path.is_selected(), - rtt_us: micros(path.rtt()), - tx_bytes: stats.udp_tx.bytes, - rx_bytes: stats.udp_rx.bytes, - lost_packets: stats.lost_packets, - } - }) - .collect(); - ConnectionInfo { - remote: connection.remote_id().to_string(), - connected_at: millis(log.connected_at()), - selected: paths - .iter() - .find(|path| path.selected) - .map(|path| path.kind), - paths, - history: log.history(), - } -} - pub async fn arrives_locally(connection: &Connection, wait: Duration) -> bool { let mut events = connection.path_events(); if on_loopback(connection) { @@ -204,15 +166,6 @@ fn kind(addr: &TransportAddr) -> PathKind { } } -fn local(addr: &iroh::endpoint::LocalTransportAddr) -> Option { - use iroh::endpoint::LocalTransportAddr; - match addr { - LocalTransportAddr::Ip(ip) => ip.map(|ip| ip.to_string()), - LocalTransportAddr::Relay(url) => Some(url.to_string()), - _ => None, - } -} - fn micros(duration: std::time::Duration) -> u64 { u64::try_from(duration.as_micros()).unwrap_or(u64::MAX) } @@ -243,7 +196,39 @@ impl Link { } pub fn describe(&self) -> ConnectionInfo { - describe(&self.connection, &self.log) + let paths: Vec = self + .connection + .paths() + .iter() + .map(|path| { + let stats = path.stats(); + PathInfo { + kind: kind(path.remote_addr()), + remote: show(path.remote_addr()), + local: match path.local_addr() { + LocalTransportAddr::Ip(ip) => ip.map(|ip| ip.to_string()), + LocalTransportAddr::Relay(url) => Some(url.to_string()), + _ => None, + }, + selected: path.is_selected(), + rtt_us: micros(path.rtt()), + tx_bytes: stats.udp_tx.bytes, + rx_bytes: stats.udp_rx.bytes, + lost_packets: stats.lost_packets, + } + }) + .collect(); + let log = self.log.lock(); + ConnectionInfo { + remote: self.connection.remote_id().to_string(), + connected_at: millis(log.connected_at), + selected: paths + .iter() + .find(|path| path.selected) + .map(|path| path.kind), + paths, + history: log.history.iter().cloned().collect(), + } } pub fn selected(&self) -> Option { diff --git a/crates/transport/src/settings.rs b/crates/transport/src/settings.rs index 7c688ed..f552bb5 100644 --- a/crates/transport/src/settings.rs +++ b/crates/transport/src/settings.rs @@ -1,6 +1,6 @@ use std::{fmt, net::SocketAddr, str::FromStr}; -use iroh::{RelayMode, RelayUrl}; +use iroh::RelayUrl; use crate::Error; @@ -12,16 +12,6 @@ pub enum Relay { Custom(Vec), } -impl Relay { - pub fn mode(&self) -> RelayMode { - match self { - Relay::Default => RelayMode::Default, - Relay::Disabled => RelayMode::Disabled, - Relay::Custom(urls) => RelayMode::custom(urls.iter().cloned()), - } - } -} - impl FromStr for Relay { type Err = Error; diff --git a/crates/vtgen/Cargo.toml b/crates/vtgen/Cargo.toml deleted file mode 100644 index ea7a32f..0000000 --- a/crates/vtgen/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "vtgen" -version.workspace = true -edition.workspace = true -publish.workspace = true - -[lib] -path = "src/lib.rs" - -[[bin]] -name = "vtgen" -path = "src/bin/vtgen.rs" - -[dependencies] -anyhow.workspace = true -rand.workspace = true -rand_xoshiro.workspace = true diff --git a/crates/vtgen/src/bin/vtgen.rs b/crates/vtgen/src/bin/vtgen.rs deleted file mode 100644 index 7e94c61..0000000 --- a/crates/vtgen/src/bin/vtgen.rs +++ /dev/null @@ -1,135 +0,0 @@ -use std::{ - fs::File, - io::{self, BufWriter, Write}, - process::ExitCode, -}; - -use vtgen::Profile; - -const USAGE: &str = "\ -usage: vtgen [--bytes SIZE] [--seed N] [--out PATH] - vtgen --list - - which kind of output to generate; see --list - --bytes SIZE how much to generate, e.g. 4096, 64KiB, 256MiB, 2GiB - (default 64MiB) - --seed N generation seed; the same seed always gives the same bytes - (default 0) - --out PATH where to write; stdout if unset -"; - -fn main() -> ExitCode { - match run() { - Ok(()) => ExitCode::SUCCESS, - Err(error) => { - eprintln!("vtgen: {error}"); - ExitCode::FAILURE - } - } -} - -fn run() -> anyhow::Result<()> { - let mut args = std::env::args().skip(1); - - let mut profile: Option = None; - let mut bytes: u64 = 64 * 1024 * 1024; - let mut seed: u64 = 0; - let mut out: Option = None; - - while let Some(arg) = args.next() { - match arg.as_str() { - "--list" => { - for profile in Profile::ALL { - println!("{}", profile.name()); - } - return Ok(()); - } - "-h" | "--help" => { - print!("{USAGE}"); - return Ok(()); - } - "--bytes" => bytes = parse_size(&next(&mut args, "--bytes")?)?, - "--seed" => seed = next(&mut args, "--seed")?.parse()?, - "--out" => out = Some(next(&mut args, "--out")?), - other if other.starts_with('-') => { - anyhow::bail!("unknown option {other}\n\n{USAGE}"); - } - other => { - profile = Some( - Profile::parse(other) - .ok_or_else(|| anyhow::anyhow!("unknown profile {other}\n\n{USAGE}"))?, - ); - } - } - } - - let profile = profile.ok_or_else(|| anyhow::anyhow!("no profile given\n\n{USAGE}"))?; - - let written = match out.as_deref() { - Some(path) => { - let file = File::create(path)?; - let mut writer = BufWriter::with_capacity(1 << 20, file); - let written = vtgen::generate(&mut writer, profile, bytes, seed)?; - writer.flush()?; - eprintln!( - "vtgen: wrote {written} bytes of {} to {path}", - profile.name() - ); - written - } - None => { - let stdout = io::stdout(); - let mut writer = BufWriter::with_capacity(1 << 20, stdout.lock()); - let written = vtgen::generate(&mut writer, profile, bytes, seed)?; - writer.flush()?; - written - } - }; - - debug_assert!(written >= bytes); - Ok(()) -} - -fn next(args: &mut impl Iterator, flag: &str) -> anyhow::Result { - args.next() - .ok_or_else(|| anyhow::anyhow!("{flag} needs a value")) -} - -fn parse_size(text: &str) -> anyhow::Result { - let text = text.trim(); - let (number, scale) = match text - .char_indices() - .find(|(_, c)| !c.is_ascii_digit() && *c != '_') - { - None => (text, 1u64), - Some((split, _)) => { - let scale = match text[split..].trim().to_ascii_lowercase().as_str() { - "k" | "kb" | "kib" => 1024, - "m" | "mb" | "mib" => 1024 * 1024, - "g" | "gb" | "gib" => 1024 * 1024 * 1024, - "b" | "" => 1, - other => anyhow::bail!("unknown size suffix {other:?}"), - }; - (&text[..split], scale) - } - }; - - let number: u64 = number.replace('_', "").parse()?; - number - .checked_mul(scale) - .ok_or_else(|| anyhow::anyhow!("{text} overflows a byte count")) -} - -#[cfg(test)] -mod tests { - use super::parse_size; - - #[test] - fn sizes_parse_with_and_without_suffixes() { - assert_eq!(parse_size("4096").unwrap(), 4096); - assert_eq!(parse_size("64KiB").unwrap(), 64 * 1024); - assert_eq!(parse_size("2gb").unwrap(), 2 * 1024 * 1024 * 1024); - assert_eq!(parse_size("1_000").unwrap(), 1000); - assert!(parse_size("12furlongs").is_err()); - } -} diff --git a/crates/vtgen/src/lib.rs b/crates/vtgen/src/lib.rs deleted file mode 100644 index 65a39f2..0000000 --- a/crates/vtgen/src/lib.rs +++ /dev/null @@ -1,321 +0,0 @@ -use std::io::{self, Write}; - -use rand::{Rng, SeedableRng as _}; -use rand_xoshiro::Xoshiro256PlusPlus; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Profile { - Ascii, - Wrap, - Styled, - Unicode, - Osc, - Tui, - Tree, -} - -impl Profile { - pub const ALL: [Profile; 7] = [ - Profile::Ascii, - Profile::Wrap, - Profile::Styled, - Profile::Unicode, - Profile::Osc, - Profile::Tui, - Profile::Tree, - ]; - - pub fn name(self) -> &'static str { - match self { - Profile::Ascii => "ascii", - Profile::Wrap => "wrap", - Profile::Styled => "styled", - Profile::Unicode => "unicode", - Profile::Osc => "osc", - Profile::Tui => "tui", - Profile::Tree => "tree", - } - } - - pub fn parse(name: &str) -> Option { - Profile::ALL.into_iter().find(|p| p.name() == name) - } -} - -pub fn generate(out: &mut W, profile: Profile, bytes: u64, seed: u64) -> io::Result { - let mut rng = Xoshiro256PlusPlus::seed_from_u64(seed); - let mut sink = CountingWriter { inner: out, len: 0 }; - let mut tree = TreeState::default(); - - while sink.len < bytes { - match profile { - Profile::Ascii => ascii_line(&mut sink, &mut rng, true)?, - Profile::Wrap => ascii_line(&mut sink, &mut rng, false)?, - Profile::Styled => styled_line(&mut sink, &mut rng)?, - Profile::Unicode => unicode_line(&mut sink, &mut rng)?, - Profile::Osc => osc_line(&mut sink, &mut rng)?, - Profile::Tui => tui_frame(&mut sink, &mut rng)?, - Profile::Tree => tree_line(&mut sink, &mut rng, &mut tree)?, - } - } - - Ok(sink.len) -} - -const ALPHABET: &[u8] = b"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\ -[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; - -fn ascii_line(out: &mut W, rng: &mut impl Rng, breaks: bool) -> io::Result<()> { - let len = if breaks { - rng.random_range(40..=80) - } else { - 1024 - }; - - let mut buf = [0u8; 1024]; - for slot in buf.iter_mut().take(len) { - *slot = ALPHABET[rng.random_range(0..ALPHABET.len())]; - } - out.write_all(&buf[..len])?; - if breaks { - out.write_all(b"\r\n")?; - } - Ok(()) -} - -const SGR_CODES: &[&[u8]] = &[ - b"\x1b[0m", - b"\x1b[1m", - b"\x1b[2m", - b"\x1b[3m", - b"\x1b[4m", - b"\x1b[9m", - b"\x1b[7m", - b"\x1b[31m", - b"\x1b[32m", - b"\x1b[33m", - b"\x1b[34m", - b"\x1b[35m", - b"\x1b[36m", - b"\x1b[91m", - b"\x1b[92m", - b"\x1b[93m", - b"\x1b[38;5;208m", - b"\x1b[38;2;180;140;255m", - b"\x1b[41m", - b"\x1b[44m", - b"\x1b[48;5;236m", -]; - -fn styled_line(out: &mut W, rng: &mut impl Rng) -> io::Result<()> { - let mut remaining = rng.random_range(40..=80); - while remaining > 0 { - out.write_all(SGR_CODES[rng.random_range(0..SGR_CODES.len())])?; - - let run = rng.random_range(4..=16).min(remaining); - let mut buf = [0u8; 16]; - for slot in buf.iter_mut().take(run) { - *slot = ALPHABET[rng.random_range(0..ALPHABET.len())]; - } - out.write_all(&buf[..run])?; - remaining -= run; - } - out.write_all(b"\x1b[0m\r\n") -} - -const LATIN: &[char] = &['á', 'ë', 'î', 'ø', 'ü', 'ñ', 'ç', 'å', 'æ', 'ß']; -const CJK: &[char] = &['日', '本', '語', '漢', '字', '中', '文', '테', '스', 'ト']; -const EMOJI: &[char] = &['😀', '🚀', '🎨', '🔥', '🌍', '✨', '🐙', '📦']; -const COMBINING: char = '\u{0301}'; - -fn unicode_line(out: &mut W, rng: &mut impl Rng) -> io::Result<()> { - let mut line = String::with_capacity(256); - for _ in 0..rng.random_range(20..=40) { - let ch = match rng.random_range(0..10) { - 0..=4 => ALPHABET[rng.random_range(0..ALPHABET.len())] as char, - 5..=6 => LATIN[rng.random_range(0..LATIN.len())], - 7..=8 => CJK[rng.random_range(0..CJK.len())], - _ => EMOJI[rng.random_range(0..EMOJI.len())], - }; - line.push(ch); - if rng.random_range(0..20) == 0 { - line.push(COMBINING); - } - } - line.push_str("\r\n"); - out.write_all(line.as_bytes()) -} - -fn osc_line(out: &mut W, rng: &mut impl Rng) -> io::Result<()> { - if rng.random_range(0..32) == 0 { - write!(out, "\x1b]0;tarp bench {}\x07", rng.random::())?; - } - - let mut remaining = rng.random_range(40..=80); - while remaining > 0 { - let run = rng.random_range(8..=24).min(remaining); - write!( - out, - "\x1b]8;;https://example.invalid/{}\x1b\\", - rng.random::() - )?; - - let mut buf = [0u8; 24]; - for slot in buf.iter_mut().take(run) { - *slot = ALPHABET[rng.random_range(0..ALPHABET.len())]; - } - out.write_all(&buf[..run])?; - out.write_all(b"\x1b]8;;\x1b\\")?; - remaining -= run; - } - out.write_all(b"\r\n") -} - -fn tui_frame(out: &mut W, rng: &mut impl Rng) -> io::Result<()> { - const ROWS: usize = 40; - const COLS: usize = 100; - - out.write_all(b"\x1b[?2026h")?; - for row in 1..=ROWS { - write!(out, "\x1b[{row};1H\x1b[K")?; - out.write_all(SGR_CODES[rng.random_range(0..SGR_CODES.len())])?; - - let width = rng.random_range(COLS / 2..=COLS); - let mut buf = [0u8; COLS]; - for slot in buf.iter_mut().take(width) { - *slot = ALPHABET[rng.random_range(0..ALPHABET.len())]; - } - out.write_all(&buf[..width])?; - } - write!( - out, - "\x1b[0m\x1b[{};{}H\x1b[?2026l", - rng.random_range(1..=ROWS), - rng.random_range(1..=COLS) - ) -} - -#[derive(Default)] -struct TreeState { - open: Vec, -} - -const SYLLABLES: &[&str] = &[ - "con", "fig", "ser", "vice", "hand", "ler", "mod", "ule", "cli", "ent", "par", "ser", "ren", - "der", "wid", "get", "buf", "fer", "win", "dow", "ter", "min", "al", "can", "vas", "pro", "to", - "col", -]; - -const TREE_COLOURS: &[&str] = &["\x1b[01;34m", "\x1b[01;32m", "\x1b[01;35m", ""]; - -fn tree_line(out: &mut W, rng: &mut impl Rng, state: &mut TreeState) -> io::Result<()> { - if state.open.is_empty() || (state.open.len() < 8 && rng.random_range(0..3) == 0) { - state.open.push(rng.random_range(0..4) != 0); - } else if rng.random_range(0..5) == 0 { - state.open.pop(); - } - - let depth = state.open.len(); - for level in 0..depth.saturating_sub(1) { - out.write_all(if state.open[level] { - "\u{2502} ".as_bytes() - } else { - b" " - })?; - } - - let last = rng.random_range(0..4) == 0; - if last { - out.write_all("\u{2514}\u{2500}\u{2500} ".as_bytes())?; - if let Some(flag) = state.open.last_mut() { - *flag = false; - } - } else { - out.write_all("\u{251C}\u{2500}\u{2500} ".as_bytes())?; - } - - let colour = TREE_COLOURS[rng.random_range(0..TREE_COLOURS.len())]; - out.write_all(colour.as_bytes())?; - for _ in 0..rng.random_range(2..=5) { - out.write_all(SYLLABLES[rng.random_range(0..SYLLABLES.len())].as_bytes())?; - } - if rng.random_range(0..2) == 0 { - out.write_all(b".rs")?; - } - if !colour.is_empty() { - out.write_all(b"\x1b[0m")?; - } - - out.write_all(b"\r\n") -} - -struct CountingWriter<'a, W> { - inner: &'a mut W, - len: u64, -} - -impl Write for CountingWriter<'_, W> { - fn write(&mut self, buf: &[u8]) -> io::Result { - let n = self.inner.write(buf)?; - self.len += n as u64; - Ok(n) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.inner.write_all(buf)?; - self.len += buf.len() as u64; - Ok(()) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_same_seed_generates_the_same_bytes() { - for profile in Profile::ALL { - let mut first = Vec::new(); - let mut second = Vec::new(); - generate(&mut first, profile, 64 * 1024, 42).expect("generate"); - generate(&mut second, profile, 64 * 1024, 42).expect("generate"); - assert_eq!(first, second, "{} is not deterministic", profile.name()); - } - } - - #[test] - fn different_seeds_generate_different_bytes() { - let mut first = Vec::new(); - let mut second = Vec::new(); - generate(&mut first, Profile::Ascii, 64 * 1024, 1).expect("generate"); - generate(&mut second, Profile::Ascii, 64 * 1024, 2).expect("generate"); - assert_ne!(first, second); - } - - #[test] - fn a_corpus_is_the_size_it_was_asked_for() { - for profile in Profile::ALL { - let mut out = Vec::new(); - let len = generate(&mut out, profile, 256 * 1024, 7).expect("generate"); - assert_eq!(len as usize, out.len()); - assert!( - out.len() >= 256 * 1024 && out.len() < 256 * 1024 + 16 * 1024, - "{} overshot: {} bytes", - profile.name(), - out.len() - ); - } - } - - #[test] - fn every_profile_has_a_name_that_parses_back() { - for profile in Profile::ALL { - assert_eq!(Profile::parse(profile.name()), Some(profile)); - } - assert_eq!(Profile::parse("nonsense"), None); - } -} -- knotmirror 0.0.1