diff --git a/AGENTS.md b/AGENTS.md index fddf86a..acec01b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,6 +5,7 @@ Tightbeam is private chat between two people on the same LAN: a Rust backend (Ta ## Done - A change is done when the checks in `.github/workflows/ci.yml` pass locally: the UI check from the project root, and fmt, clippy and tests in `src-tauri/`. +- A protocol change gets a test in `src-tauri/src/chat/protocol_tests.rs`, which runs two engines on an in-memory network with paused time. - A change people will notice also gets a line under `## Unreleased` in `CHANGELOG.md`. That section becomes the release text. - Commit messages and PR titles follow Conventional Commits (`feat:`, `fix:`, `refactor:`, `docs:`, `chore:` …). PRs squash-merge, so the title becomes the commit on `main`. diff --git a/GLOSSARY.md b/GLOSSARY.md index 69353e5..4124b94 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -4,6 +4,26 @@ Private chat between two paired peers on the same network. Each person's history ## Language +### Peers + +**Peer**: +The one other person's app this one is paired with. Before pairing, the apps nearby are just nearby. +_Avoid_: contact, friend, remote + +**Pairing**: +Two apps agreeing to trust each other's key, after both screens show the same code. Each app pairs with one peer at a time. +_Avoid_: linking, connecting + +**Session**: +One connected stretch between two paired peers: from their greetings until the connection drops. A newer session replaces an older one. +_Avoid_: connection (for the stretch of chat), call + +**Catch-up**: +The entries a peer is missing, sent at the start of each session, before anything live. +_Avoid_: sync (for this step), backfill + +### Logs + **Log**: One author's history: an append-only, gap-free sequence of entries numbered from 1. _Avoid_: history, timeline (for the stored sequence) diff --git a/README.md b/README.md index c7bcf4a..4803918 100644 --- a/README.md +++ b/README.md @@ -37,13 +37,16 @@ ui/src/store.ts app state (TanStack Store), fed by events from Rust; h ui/src/commands.ts slash commands ui/src/components/ the screens: Setup, Pair, Chat, Search, Files, PairDialog, Notice ui/src/components/ui/ shadcn/ui components (generated; update with the shadcn CLI) -src-tauri/src/chat.rs the engine: discovery, pairing, protocol, sync +src-tauri/src/chat.rs the engine: pairing, protocol, sync +src-tauri/src/chat/protocol_tests.rs the protocol between two engines, on the in-memory network +src-tauri/src/net.rs the network the engine runs on: iroh and mDNS, or in memory for tests +src-tauri/src/clock.rs wall-clock time, which tests move with tokio's paused clock src-tauri/src/entry.rs log entries: each kind, its wire form, admission of a peer's src-tauri/src/db.rs SQLite storage and history paging src-tauri/src/lib.rs Tauri commands and events src-tauri/src/desktop.rs tray, unread count, notifications src-tauri/src/updates.rs automatic updates -src-tauri/tests/ two real engines chatting; paging through 50,000 messages +src-tauri/tests/ two real engines on the real network; paging through 50,000 messages src-tauri/examples/seed.rs fills two test profiles with a long synthetic history ``` @@ -59,7 +62,7 @@ Needs Rust (via rustup) and bun. The Tauri CLI comes with `bun install`. bun install # once bun tauri dev # run the app; the UI hot-reloads as you edit bun tauri build # make an installer in src-tauri/target/release/bundle/ -cd src-tauri; cargo test # run the two-peer test (about 5 seconds) +cd src-tauri; cargo test # run the tests (about 5 seconds, mostly the real-network one) ``` `bun run dev` alone starts only Vite. The UI needs the Tauri bridge, so it won't work in a regular browser. diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 422ed45..305f4a7 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -37,4 +37,6 @@ windows-sys = { version = "0.61", features = [ ] } [dev-dependencies] +# Paused time for the protocol tests. +tokio = { version = "1.54", features = ["full", "test-util"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index ff45cfb..aec8a12 100644 --- a/src-tauri/src/chat.rs +++ b/src-tauri/src/chat.rs @@ -17,20 +17,11 @@ use std::{ collections::{BTreeMap, HashSet}, path::{Path, PathBuf}, sync::{Arc, Mutex, MutexGuard}, - time::{Duration, Instant, SystemTime, UNIX_EPOCH}, + time::{Duration, Instant}, }; use anyhow::{Context, Result, bail, ensure}; -use std::{borrow::Cow, net::IpAddr}; - -use iroh::{ - Endpoint, EndpointId, SecretKey, TransportAddr, - address_lookup::AddrFilter, - endpoint::{Connection, Incoming, PortmapperConfig, RecvStream, SendStream, presets}, - endpoint_info::UserData, -}; -use iroh_mdns_address_lookup::{DiscoveryEvent, MdnsAddressLookup}; -use n0_future::StreamExt; +use iroh::{EndpointId, SecretKey}; use serde::{Deserialize, Serialize}; use tokio::{ io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}, @@ -39,16 +30,15 @@ use tokio::{ }; use crate::{ + clock::Clock, db::{Cursor, Db, FileState, Hit, Message, Page}, entry::{ Entry, FileInfo, Kind, MAX_EMOJI_CHARS, MAX_FILE_BYTES, MAX_TEXT_CHARS, Ref, VANISH_SECS, Wire, checked_file, clean, is_hash, }, + net::{Accepting, Conn, Discoveries, Discovery, Network, RecvStream, SendStream}, }; -pub const ALPN: &[u8] = b"tightbeam/1"; -/// mDNS service name, so we only see other Tightbeam apps (`_tightbeam._udp.local`). -const SERVICE: &str = "tightbeam"; const MAX_FRAME: usize = 64 * 1024; const MAX_NAME_CHARS: usize = 40; const PAIR_PROMPT_TIMEOUT: Duration = Duration::from_secs(120); @@ -253,7 +243,7 @@ struct Session { generation: u64, since: i64, out: mpsc::UnboundedSender, - conn: Connection, + conn: Conn, } struct State { @@ -268,8 +258,9 @@ struct State { session: Option, next_generation: u64, notice: Option, - nudge_sent: Option, - nudge_received: Option, + /// tokio's clock, so tests can move past the limit. + nudge_sent: Option, + nudge_received: Option, away: Option, /// `away` came from `/away`, so it lasts until `/back` or a message, not until input. away_by_hand: bool, @@ -282,9 +273,11 @@ struct State { } pub struct Core { - endpoint: Endpoint, + net: Network, me: EndpointId, db: Mutex, + /// Wall-clock time, shared with `db`. + clock: Clock, /// Where files are kept: `/`, plus `.part` while one arrives. files_dir: PathBuf, /// Wakes the session's downloader when a message with a file arrives. @@ -305,16 +298,25 @@ impl Core { } /// `loopback_only` binds to 127.0.0.1, for running two copies on one machine in tests. - /// (Windows refuses to send from a LAN address to that same address, so same-machine - /// tests over the LAN address are flaky.) pub async fn start_with( data_dir: PathBuf, emit: Emit, loopback_only: bool, + ) -> Result> { + let network = |secret| Network::iroh(secret, loopback_only); + Self::start_on(data_dir, emit, Clock::system(), network).await + } + + /// Starts on the network `network` makes from this computer's secret key. + pub(crate) async fn start_on>>( + data_dir: PathBuf, + emit: Emit, + clock: Clock, + network: impl FnOnce(SecretKey) -> F, ) -> Result> { std::fs::create_dir_all(&data_dir) .with_context(|| format!("creating {}", data_dir.display()))?; - let db = Db::open(&data_dir.join("tightbeam.db"))?; + let db = Db::open_with(&data_dir.join("tightbeam.db"), clock.clone())?; let secret = match db.get("secret_key")? { Some(bytes) => { @@ -340,27 +342,14 @@ impl Core { let peer_features = features_from(db.get_str("peer_features")?.as_deref()); let dnd_until = db.get_str("dnd_until")?.and_then(|s| s.parse().ok()); - // LAN only for now: no relay servers, no public DNS, just mDNS. No UPnP either: - // we never ask the router to open a public port, and we only ever advertise - // private addresses. - let mut builder = Endpoint::builder(presets::Minimal) - .secret_key(secret) - .alpns(vec![ALPN.to_vec()]) - .portmapper_config(PortmapperConfig::Disabled) - .addr_filter(AddrFilter::new(move |addrs| { - Cow::Owned(addrs.iter().filter(|a| is_lan(a, loopback_only)).cloned().collect()) - })); - if loopback_only { - builder = builder.clear_ip_transports().bind_addr("127.0.0.1:0")?; - } - let endpoint = builder.bind().await?; - let mdns = MdnsAddressLookup::builder().service_name(SERVICE).build(endpoint.id())?; - endpoint.address_lookup()?.add(mdns.clone()); + let net = network(secret).await?; + let discoveries = net.discoveries().await; let core = Arc::new(Self { - me: endpoint.id(), - endpoint, + me: net.id(), + net, db: Mutex::new(db), + clock, files_dir: data_dir.join("files"), files_wanted: Notify::new(), state: Mutex::new(State { @@ -393,7 +382,7 @@ impl Core { *core.tasks.lock().unwrap() = vec![ tokio::spawn(core.clone().accept_loop()).abort_handle(), - tokio::spawn(core.clone().discovery_loop(mdns)).abort_handle(), + tokio::spawn(core.clone().discovery_loop(discoveries)).abort_handle(), tokio::spawn(core.clone().dial_loop()).abort_handle(), tokio::spawn(core.clone().vanish_loop()).abort_handle(), ]; @@ -405,7 +394,7 @@ impl Core { for task in self.tasks.lock().unwrap().drain(..) { task.abort(); } - self.endpoint.close().await; + self.net.close().await; } // ---- Queries ------------------------------------------------------------------- @@ -434,7 +423,7 @@ impl Core { notice: st.notice.clone(), away: st.away.clone().filter(|_| st.away_by_hand), peer_away: st.peer_away.clone(), - dnd_until: st.dnd_until.filter(|&t| t > now_ms()), + dnd_until: st.dnd_until.filter(|&t| t > self.clock.now_ms()), peer_dnd_until: st.peer_dnd_until, } } @@ -445,10 +434,8 @@ impl Core { let (mut since, mut address, mut rtt_ms) = (None, None, None); if let Some(session) = &st.session { since = Some(session.since); - let paths = session.conn.paths(); - if let Some(path) = paths.iter().find(|p| p.is_selected()) { - address = Some(path.remote_addr().to_string()); - rtt_ms = Some(path.rtt().as_secs_f64() * 1000.0); + if let Some(route) = session.conn.route() { + (address, rtt_ms) = (Some(route.address), Some(route.rtt_ms)); } } ConnectionInfo { @@ -462,7 +449,7 @@ impl Core { /// Whether my do not disturb is on: no notifications, and nudges are refused. pub fn dnd(&self) -> bool { - self.state().dnd_until.is_some_and(|t| t > now_ms()) + self.state().dnd_until.is_some_and(|t| t > self.clock.now_ms()) } /// The whole history, oldest first. The UI uses `page` instead. @@ -650,7 +637,7 @@ impl Core { /// `/dnd`: no notifications until `until` (ms), and the peer sees it. `None` ends it. pub fn set_dnd(&self, until: Option) -> Result<()> { - let until = until.filter(|&t| t > now_ms()); + let until = until.filter(|&t| t > self.clock.now_ms()); match until { Some(t) => self.db().set("dnd_until", t.to_string())?, None => self.db().delete("dnd_until")?, @@ -739,7 +726,7 @@ impl Core { .map(|s| s.out.clone()) .context("Not connected, so the nudge can't reach them.")?; ensure!( - !st.peer_dnd_until.is_some_and(|t| t > now_ms()), + !st.peer_dnd_until.is_some_and(|t| t > self.clock.now_ms()), "{} has do not disturb on, so nudges are paused.", title_name(st.peer.as_ref().map(|(_, n)| n.clone())) ); @@ -747,7 +734,7 @@ impl Core { !st.nudge_sent.is_some_and(|t| t.elapsed() < NUDGE_EVERY), "You just nudged. Give it a few seconds." ); - st.nudge_sent = Some(Instant::now()); + st.nudge_sent = Some(tokio::time::Instant::now()); out }; let _ = out.send(Frame::Nudge); @@ -825,7 +812,7 @@ impl Core { st.session.take() }; if let Some(s) = session { - s.conn.close(0u32.into(), b"unpaired"); + s.conn.close(0, b"unpaired"); } self.changed(); Ok(()) @@ -853,38 +840,28 @@ impl Core { // ---- Background tasks ---------------------------------------------------------- async fn accept_loop(self: Arc) { - while let Some(incoming) = self.endpoint.accept().await { + while let Some(accepting) = self.net.accept().await { let core = self.clone(); tokio::spawn(async move { - if let Err(e) = core.handle_incoming(incoming).await { + if let Err(e) = core.handle_incoming(accepting).await { eprintln!("incoming connection: {e:#}"); } }); } } - async fn discovery_loop(self: Arc, mdns: MdnsAddressLookup) { - let mut events = mdns.subscribe().await; - while let Some(event) = events.next().await { + async fn discovery_loop(self: Arc, mut discoveries: Discoveries) { + while let Some(event) = discoveries.next().await { { let mut st = self.state(); match event { - DiscoveryEvent::Discovered { endpoint_info, .. } => { - let id = endpoint_info.endpoint_id; - if id == self.me { - continue; - } - let name = endpoint_info - .data - .user_data() - .map(|u| u.to_string()) - .unwrap_or_default(); + Discovery::Found { id, .. } if id == self.me => continue, + Discovery::Found { id, name } => { st.nearby.insert(id.to_string(), name); } - DiscoveryEvent::Expired { endpoint_id } => { - st.nearby.remove(&endpoint_id.to_string()); + Discovery::Lost(id) => { + st.nearby.remove(&id.to_string()); } - _ => continue, } } self.changed(); @@ -911,7 +888,7 @@ impl Core { }; let Some(peer) = target else { continue }; let started = std::time::Instant::now(); - let conn = match timeout(CONNECT_TIMEOUT, self.endpoint.connect(peer, ALPN)).await { + let conn = match timeout(CONNECT_TIMEOUT, self.net.connect(peer)).await { Ok(Ok(conn)) => conn, Ok(Err(e)) => { eprintln!( @@ -943,15 +920,15 @@ impl Core { // ---- Connection handling ------------------------------------------------------- - async fn handle_incoming(self: Arc, incoming: Incoming) -> Result<()> { - let conn = incoming.await?; + async fn handle_incoming(self: Arc, accepting: Accepting) -> Result<()> { + let conn = accepting.connected().await?; let remote = conn.remote_id(); let (send, mut recv) = conn.accept_bi().await?; match read_frame(&mut recv).await? { Frame::PairRequest { name } => self.answer_pair_request(conn, send, recv, name).await, Frame::Hello { name, have, version, features } => { if self.peer_id() != Some(remote) { - conn.close(1u32.into(), b"not paired"); + conn.close(1, b"not paired"); return Ok(()); } let theirs = TheirHello { name, have, version, features }; @@ -963,7 +940,7 @@ impl Core { async fn answer_pair_request( self: Arc, - conn: Connection, + conn: Conn, mut send: SendStream, recv: RecvStream, their_name: String, @@ -1026,7 +1003,7 @@ impl Core { } async fn request_pairing(self: &Arc, remote: EndpointId) -> Result<()> { - let conn = timeout(CONNECT_TIMEOUT, self.endpoint.connect(remote, ALPN)) + let conn = timeout(CONNECT_TIMEOUT, self.net.connect(remote)) .await .context("timed out connecting")??; let (mut send, mut recv) = conn.open_bi().await?; @@ -1051,7 +1028,7 @@ impl Core { /// Runs one connected session with the paired peer until the connection drops. async fn run_session( self: &Arc, - conn: Connection, + conn: Conn, mut send: SendStream, mut recv: RecvStream, their_hello: Option, @@ -1083,14 +1060,18 @@ impl Core { let mut st = self.state(); st.next_generation += 1; let generation = st.next_generation; - let session = - Session { generation, since: now_ms(), out: out.clone(), conn: conn.clone() }; + let session = Session { + generation, + since: self.clock.now_ms(), + out: out.clone(), + conn: conn.clone(), + }; let old = st.session.replace(session); // They say so again if they still are. st.peer_away = None; st.peer_dnd_until = None; if let Some(old) = old { - old.conn.close(0u32.into(), b"replaced"); + old.conn.close(0, b"replaced"); } generation }; @@ -1104,7 +1085,7 @@ impl Core { if let Some(Away { note }) = self.state().away.clone() { let _ = out.send(Frame::Away { note }); } - if let Some(until) = self.state().dnd_until.filter(|&t| t > now_ms()) { + if let Some(until) = self.state().dnd_until.filter(|&t| t > self.clock.now_ms()) { let _ = out.send(Frame::Dnd { until: Some(until) }); } self.changed(); @@ -1119,11 +1100,12 @@ impl Core { // Files go on streams of their own: the ones they ask me for, and the ones I want. let serving = tokio::spawn(self.clone().serve_files(conn.clone())); let fetching = tokio::spawn(self.clone().fetch_files(conn.clone())); + // Stopped however this ends, including when the session itself is dropped (the + // dialer's, at shutdown), so none of them outlives it. + let tasks = [writer, serving, fetching].map(|task| AbortOnDrop(task.abort_handle())); let result = self.read_loop(&mut recv, &peer_str, &out).await; - writer.abort(); - serving.abort(); - fetching.abort(); - conn.close(0u32.into(), b"bye"); + drop(tasks); + conn.close(0, b"bye"); { let mut st = self.state(); if st.session.as_ref().is_some_and(|s| s.generation == generation) { @@ -1199,9 +1181,7 @@ impl Core { } fn advertise_name(&self) { - let name = self.name(); - let data = if name.is_empty() { None } else { UserData::try_from(name).ok() }; - self.endpoint.set_user_data_for_address_lookup(data); + self.net.advertise(&self.name()); } fn save_peer(&self, id: EndpointId, name: &str) -> Result<()> { @@ -1268,7 +1248,7 @@ impl Core { /// `author`'s vanishing messages up to `up_to` have been seen: start their clocks. fn start_vanish(&self, author: &str, up_to: u64) -> Result<()> { - let started = self.db().start_vanish(author, up_to, now_ms())?; + let started = self.db().start_vanish(author, up_to, self.clock.now_ms())?; for at in started { self.updated(&at)?; } @@ -1278,7 +1258,7 @@ impl Core { /// Adds an entry to my log. fn append(&self, text: String, kind: Kind) -> Result { let db = self.db(); - let (seq, ts) = (db.max_seq(&self.id())? + 1, now_ms()); + let (seq, ts) = (db.max_seq(&self.id())? + 1, self.clock.now_ms()); let entry = Entry { author: self.id(), seq, ts, hlc: db.next_hlc(ts)?, text, kind }; db.insert(&entry)?; Ok(entry) @@ -1315,7 +1295,7 @@ impl Core { // ---- Files --------------------------------------------------------------------- /// Answers the peer's file requests for this session. - async fn serve_files(self: Arc, conn: Connection) { + async fn serve_files(self: Arc, conn: Conn) { while let Ok((send, recv)) = conn.accept_bi().await { let core = self.clone(); tokio::spawn(async move { @@ -1373,7 +1353,7 @@ impl Core { /// Downloads the files this computer still needs, one at a time, newest first, for /// as long as the session lasts. - async fn fetch_files(self: Arc, conn: Connection) { + async fn fetch_files(self: Arc, conn: Conn) { // Ones that failed this session: tried again next time. let mut failed = HashSet::new(); loop { @@ -1396,7 +1376,7 @@ impl Core { } } - async fn fetch_file(&self, conn: &Connection, file: &FileInfo) -> Result<()> { + async fn fetch_file(&self, conn: &Conn, file: &FileInfo) -> Result<()> { tokio::fs::create_dir_all(&self.files_dir).await?; let part_path = self.files_dir.join(format!("{}.part", file.hash)); let mut part = tokio::fs::OpenOptions::new() @@ -1498,7 +1478,7 @@ impl Core { let mut ticks = tokio::time::interval(Duration::from_secs(1)); loop { ticks.tick().await; - let gone = self.db().expire(now_ms()); + let gone = self.db().expire(self.clock.now_ms()); match gone { Ok(gone) => { for at in &gone { @@ -1606,7 +1586,7 @@ impl Core { if st.nudge_received.is_some_and(|t| t.elapsed() < NUDGE_EVERY) { return; } - st.nudge_received = Some(Instant::now()); + st.nudge_received = Some(tokio::time::Instant::now()); } (self.emit)(Event::Nudge); } @@ -1644,17 +1624,6 @@ fn pair_code(a: EndpointId, b: EndpointId) -> String { } /// Private-network addresses only (192.168.x, 10.x, 172.16-31.x, link-local, IPv6 ULA). -fn is_lan(addr: &TransportAddr, allow_loopback: bool) -> bool { - match addr { - TransportAddr::Ip(sock) => match sock.ip() { - IpAddr::V4(ip) if ip.is_loopback() => allow_loopback, - IpAddr::V4(ip) => ip.is_private() || ip.is_link_local(), - IpAddr::V6(ip) => ip.is_unique_local() || ip.is_unicast_link_local(), - }, - _ => false, - } -} - /// My `Hello`: who I am, the last of their entries I have, and what this build does. fn hello(name: String, have: u64) -> Frame { let features = FEATURES.iter().map(|f| f.to_string()).collect(); @@ -1745,15 +1714,20 @@ impl Drop for Progress { } } +/// Aborts a task when dropped. +struct AbortOnDrop(tokio::task::AbortHandle); + +impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } +} + /// The peer's name for messages, or a stand-in before they've named themselves. fn title_name(name: Option) -> String { name.filter(|n| !n.is_empty()).unwrap_or_else(|| "the other person".into()) } -fn now_ms() -> i64 { - SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0) -} - async fn write_frame(send: &mut SendStream, frame: &Frame) -> Result<()> { write_json(send, frame).await } @@ -1780,6 +1754,9 @@ async fn read_json(recv: &mut RecvStream) -> Res Ok(serde_json::from_slice(&body)?) } +#[cfg(test)] +mod protocol_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/chat/protocol_tests.rs b/src-tauri/src/chat/protocol_tests.rs new file mode 100644 index 0000000..0c4333b --- /dev/null +++ b/src-tauri/src/chat/protocol_tests.rs @@ -0,0 +1,640 @@ +//! The protocol between two engines, on the in-memory network with paused time: pairing, +//! sessions, catch-up, receipts, presence and files. Each test drives `Core` the way the +//! app does, through its public methods, and watches what it reports. +//! +//! `two_peers.rs` checks the same engine on the real network. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::*; +use crate::net::Lan; + +/// Where the test clock starts: November 2027. +const EPOCH_MS: i64 = 1_826_000_000_000; + +/// Peers on one in-memory LAN, sharing one clock, each with a data folder of its own. +struct World { + lan: Lan, + clock: Clock, + root: PathBuf, +} + +impl World { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::SeqCst); + let nanos = + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("tightbeam-protocol-{nanos}-{n}")); + Self { lan: Lan::default(), clock: Clock::tokio(EPOCH_MS), root } + } + + /// Starts (or restarts) the app in `folder`, named `name`. + async fn start(&self, folder: &str, name: &str) -> Peer { + let dir = self.root.join(folder); + let events = Arc::new(Mutex::new(Vec::new())); + let seen = events.clone(); + let emit: Emit = Arc::new(move |event| seen.lock().unwrap().push(event)); + let lan = self.lan.clone(); + let network = |secret| async move { Ok(lan.join(secret)) }; + let core = Core::start_on(dir, emit, self.clock.clone(), network).await.unwrap(); + core.set_name(name).unwrap(); + Peer { core, events } + } + + /// Pairs `a` and `b` (`a` asks, `b` accepts) and waits until they're connected. + async fn pair(&self, a: &Peer, b: &Peer) { + a.pair_with(&b.id()).unwrap(); + until("the pair request arrives", || b.status().pairing.is_some()).await; + b.answer_pair(true); + until("connected", || a.status().connected && b.status().connected).await; + } +} + +impl Drop for World { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } +} + +/// One running app, and everything it has told the UI. +struct Peer { + core: Arc, + events: Arc>>, +} + +impl std::ops::Deref for Peer { + type Target = Arc; + fn deref(&self) -> &Arc { + &self.core + } +} + +impl Peer { + fn texts(&self) -> Vec { + self.messages().unwrap().into_iter().map(|m| m.text).collect() + } + + fn find(&self, at: &Ref) -> Option { + self.messages().unwrap().into_iter().find(|m| m.author == at.author && m.seq == at.seq) + } + + fn reactions(&self, at: &Ref) -> Vec { + self.find(at).unwrap().reactions.into_iter().map(|r| r.emoji).collect() + } + + fn count(&self, matches: impl Fn(&Event) -> bool) -> usize { + self.events.lock().unwrap().iter().filter(|e| matches(e)).count() + } + + /// Quits the app, and waits until its last task has let go of it (and its log). + async fn stop(self) { + self.core.shutdown().await; + until("the app has stopped", || Arc::strong_count(&self.core) == 1).await; + } +} + +/// Waits until `ok`, letting (paused) time pass. Fails after a minute of test time. +async fn until(what: &str, ok: impl FnMut() -> bool) { + within(60, what, ok).await +} + +/// Waits until `ok`, for at most `secs` seconds of test time. +async fn within(secs: u64, what: &str, mut ok: impl FnMut() -> bool) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(secs); + while !ok() { + assert!(tokio::time::Instant::now() < deadline, "timed out waiting for: {what}"); + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +#[tokio::test(start_paused = true)] +async fn pairs_and_chats() { + let world = World::new(); + let alice = world.start("alice", "Alice").await; + let bob = world.start("bob", "Bob").await; + + let bob_id = bob.id(); + until("alice sees bob nearby", || { + alice.status().nearby.iter().any(|p| p.id == bob_id && p.name == "Bob") + }) + .await; + world.pair(&alice, &bob).await; + assert_eq!(alice.status().peer.unwrap().name, "Bob"); + assert_eq!(bob.status().peer.unwrap().name, "Alice"); + + alice.send_message("hi bob", None, None).unwrap(); + until("bob gets it", || bob.texts() == ["hi bob"]).await; + until("alice sees it delivered", || alice.status().peer_has == 1).await; + bob.send_message("hi alice", None, None).unwrap(); + until("alice gets his", || alice.texts() == ["hi bob", "hi alice"]).await; + assert_eq!(bob.count(|e| matches!(e, Event::Message(_))), 2, "his own and hers"); + + alice.stop().await; + until("bob sees her go", || !bob.status().connected).await; +} + +// ---- Pairing ------------------------------------------------------------------------- + +fn prompts(peer: &Peer) -> usize { + peer.count(|e| matches!(e, Event::Status(s) if s.pairing.is_some())) +} + +#[tokio::test(start_paused = true)] +async fn pairing_both_screens_show_one_code() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + alice.pair_with(&bob.id()).unwrap(); + until("bob is asked", || bob.status().pairing.is_some()).await; + let (asked, asking) = (bob.status().pairing.unwrap(), alice.status().pairing.unwrap()); + assert_eq!(asked.code, asking.code); + assert!(asked.incoming && !asking.incoming); + assert_eq!((asked.name.as_str(), asked.id), ("Alice", alice.id())); +} + +#[tokio::test(start_paused = true)] +async fn pairing_declined() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + alice.pair_with(&bob.id()).unwrap(); + until("bob is asked", || bob.status().pairing.is_some()).await; + bob.answer_pair(false); + until("alice hears no", || alice.status().notice.is_some()).await; + assert_eq!(alice.status().notice.unwrap(), "They declined the pairing request."); + let (a, b) = (alice.status(), bob.status()); + assert!(a.peer.is_none() && b.peer.is_none() && a.pairing.is_none() && b.pairing.is_none()); +} + +#[tokio::test(start_paused = true)] +async fn pairing_prompt_times_out() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + alice.pair_with(&bob.id()).unwrap(); + until("bob is asked", || bob.status().pairing.is_some()).await; + // Nobody answers for two minutes. + within(130, "the prompt goes", || bob.status().pairing.is_none()).await; + until("alice hears no", || alice.status().notice.is_some()).await; + assert!(alice.status().peer.is_none() && bob.status().peer.is_none()); +} + +#[tokio::test(start_paused = true)] +async fn pairing_cancelled_by_the_asker() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + alice.pair_with(&bob.id()).unwrap(); + until("bob is asked", || bob.status().pairing.is_some()).await; + alice.answer_pair(false); + assert!(alice.status().pairing.is_none()); + // Well before the prompt would time out on its own. + within(5, "bob's prompt goes too", || bob.status().pairing.is_none()).await; + assert!(bob.status().peer.is_none()); +} + +#[tokio::test(start_paused = true)] +async fn pairing_again_with_a_trusted_key_needs_no_answer() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + alice.unpair().unwrap(); + until("disconnected", || !bob.status().connected).await; + assert!(bob.status().peer.is_some(), "bob still trusts alice"); + + let asked = prompts(&bob); + alice.pair_with(&bob.id()).unwrap(); + until("connected again", || alice.status().connected && bob.status().connected).await; + assert_eq!(prompts(&bob), asked, "bob wasn't asked"); + assert_eq!(alice.status().peer.unwrap().name, "Bob"); +} + +#[tokio::test(start_paused = true)] +async fn pairing_with_someone_already_paired_is_refused() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + let carol = world.start("carol", "Carol").await; + let asked = prompts(&bob); + carol.pair_with(&bob.id()).unwrap(); + until("carol hears no", || carol.status().notice.is_some()).await; + assert_eq!(prompts(&bob), asked, "bob wasn't asked"); + assert_eq!(bob.status().peer.unwrap().name, "Alice"); + assert!(bob.status().connected, "and stayed connected to alice"); +} + +// ---- Sessions ------------------------------------------------------------------------ + +/// The side that dials (the smaller id), then the other. +fn dialer_first<'a>(a: &'a Peer, b: &'a Peer) -> (&'a Peer, &'a Peer) { + if a.me.as_bytes() < b.me.as_bytes() { (a, b) } else { (b, a) } +} + +#[tokio::test(start_paused = true)] +async fn a_new_session_replaces_a_half_dead_one() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + let (dialer, other) = dialer_first(&alice, &bob); + dialer.set_away("lunch"); + let lunch = Some(Away { note: Some("lunch".into()) }); + until("the other sees it", || other.status().peer_away == lunch).await; + + // The dialer loses its connection; the other side doesn't notice, until the dialer + // connects again and the new session replaces the old one. + world.lan.drop_out(dialer.me); + until("the dialer notices", || !dialer.status().connected).await; + assert!(other.status().connected, "still thinks it's connected"); + until("the dialer is back", || dialer.status().connected).await; + tokio::time::sleep(Duration::from_secs(5)).await; + + // Ending the old session didn't end the new one. + assert!(other.status().connected); + assert_eq!(other.status().peer_away, lunch, "said again on the new session"); + other.send_message("still there?", None, None).unwrap(); + until("it arrives", || dialer.texts().contains(&"still there?".into())).await; +} + +// ---- Catch-up ------------------------------------------------------------------------ + +#[tokio::test(start_paused = true)] +async fn catch_up_after_being_offline() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + alice.send_message("hi bob", None, None).unwrap(); + until("bob gets it", || bob.texts() == ["hi bob"]).await; + bob.mark_seen().unwrap(); + until("alice sees he saw it", || alice.status().peer_seen == 1).await; + + // Bob is off; Alice writes twice and reacts to her own message. + bob.stop().await; + until("alice notices", || !alice.status().connected).await; + alice.send_message("you there?", None, None).unwrap(); + alice.send_message("guess not", None, None).unwrap(); + let first = Ref { author: alice.id(), seq: 1 }; + alice.react(first.clone(), "👍").unwrap(); + assert_eq!(alice.status().peer_has, 1, "not delivered while he's off"); + + let bob = world.start("bob", "Bob").await; + until("reconnected", || alice.status().connected && bob.status().connected).await; + until("alice sees it all delivered", || alice.status().peer_has == 4).await; + assert_eq!(bob.texts(), ["hi bob", "you there?", "guess not"]); + assert_eq!(bob.reactions(&first), ["👍"]); + assert_eq!(alice.status().peer_seen, 1, "seen survives the restart, and doesn't grow"); + bob.mark_seen().unwrap(); + until("alice sees he saw it all", || alice.status().peer_seen == 4).await; +} + +#[tokio::test(start_paused = true)] +async fn sessions_coming_and_going_never_duplicate() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + let (dialer, other) = dialer_first(&alice, &bob); + for round in 0..3 { + dialer.send_message(&format!("from the dialer {round}"), None, None).unwrap(); + other.send_message(&format!("from the other {round}"), None, None).unwrap(); + world.lan.drop_out(dialer.me); + until("the dialer notices", || !dialer.status().connected).await; + // Written while the dialer is off: it arrives with the catch-up. + other.send_message(&format!("while it was off {round}"), None, None).unwrap(); + until("back", || dialer.status().connected).await; + } + until("all arrive", || dialer.texts().len() == 9 && other.texts().len() == 9).await; + assert_eq!(dialer.texts(), other.texts()); + let arrivals = |peer: &Peer| peer.count(|e| matches!(e, Event::Message(_))); + assert_eq!((arrivals(dialer), arrivals(other)), (9, 9), "each message shown once"); + until("all delivered", || dialer.status().peer_has == 3 && other.status().peer_has == 6).await; +} + +/// The log's files in `folder`, the way a backup would copy them. +fn copy_log(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap().flatten() { + if entry.file_type().unwrap().is_file() { + std::fs::copy(entry.path(), to.join(entry.file_name())).unwrap(); + } + } +} + +#[tokio::test(start_paused = true)] +async fn a_peer_that_lost_history_gets_it_again() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + alice.send_message("one", None, None).unwrap(); + until("bob gets it", || bob.texts() == ["one"]).await; + bob.mark_seen().unwrap(); + until("seen", || alice.status().peer_seen == 1).await; + bob.stop().await; + let (folder, backup) = (world.root.join("bob"), world.root.join("backup")); + copy_log(&folder, &backup); + + let bob = world.start("bob", "Bob").await; + alice.send_message("two", None, None).unwrap(); + alice.send_message("three", None, None).unwrap(); + until("bob gets them", || bob.texts().len() == 3).await; + bob.mark_seen().unwrap(); + until("seen", || alice.status().peer_seen == 3).await; + + // Bob restores the backup from when he had only the first. + bob.stop().await; + std::fs::remove_dir_all(&folder).unwrap(); + copy_log(&backup, &folder); + let bob = world.start("bob", "Bob").await; + until("he has them all again", || bob.texts() == ["one", "two", "three"]).await; + until("delivered again", || alice.status().peer_has == 3).await; + assert_eq!(alice.status().peer_seen, 1, "he hasn't seen the ones he lost"); +} + +// ---- Vanishing messages -------------------------------------------------------------- + +#[tokio::test(start_paused = true)] +async fn a_vanishing_message_lasts_from_when_it_is_seen() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + let sent = alice.send_message("the code is 1234", None, Some(5)).unwrap(); + let at = Ref { author: alice.id(), seq: sent.seq }; + until("bob gets it", || bob.find(&at).is_some()).await; + + // Unseen, it stays, however long. + tokio::time::sleep(Duration::from_secs(3600)).await; + let waiting = bob.find(&at).unwrap(); + assert_eq!((waiting.text.as_str(), waiting.expires), ("the code is 1234", None)); + + bob.mark_seen().unwrap(); + until("both clocks run", || { + alice.find(&at).unwrap().expires.is_some() && bob.find(&at).unwrap().expires.is_some() + }) + .await; + within(7, "it vanishes on both sides", || { + alice.find(&at).unwrap().vanished && bob.find(&at).unwrap().vanished + }) + .await; + assert!(alice.find(&at).unwrap().text.is_empty() && bob.find(&at).unwrap().text.is_empty()); +} + +// ---- Other builds -------------------------------------------------------------------- + +/// Another build of the app on the network, played by the test frame by frame. +struct Played { + id: String, + conn: Conn, + send: SendStream, + recv: RecvStream, + _net: Network, +} + +impl Played { + /// Asks `peer` to pair (they accept), then says `hello`. + async fn pair(world: &World, peer: &Peer, hello: Frame) -> Self { + let net = world.lan.join(SecretKey::generate()); + let id = net.id().to_string(); + let conn = net.connect(peer.me).await.unwrap(); + let (mut send, recv) = conn.open_bi().await.unwrap(); + write_frame(&mut send, &Frame::PairRequest { name: "Old".into() }).await.unwrap(); + until("they're asked", || peer.status().pairing.is_some()).await; + peer.answer_pair(true); + let mut played = Self { id, conn, send, recv, _net: net }; + played.next("their answer", |f| matches!(f, Frame::PairAccept { .. })).await; + played.next("their hello", |f| matches!(f, Frame::Hello { .. })).await; + played.say(&hello).await; + until("connected", || peer.status().connected).await; + played + } + + async fn say(&mut self, frame: &Frame) { + write_frame(&mut self.send, frame).await.unwrap(); + } + + /// An entry in my log, as a `msg` frame. + async fn write(&mut self, entry: Entry) { + self.say(&Frame::Msg(entry.into_wire().unwrap())).await; + } + + /// Reads frames until one matches. + async fn next(&mut self, what: &str, wanted: impl Fn(&Frame) -> bool) -> Frame { + let read = async { + loop { + let frame = read_frame(&mut self.recv).await.unwrap(); + if wanted(&frame) { + return frame; + } + } + }; + timeout(Duration::from_secs(60), read).await.unwrap_or_else(|_| panic!("no {what}")) + } + + fn at(&self, seq: u64) -> Ref { + Ref { author: self.id.clone(), seq } + } +} + +fn hello_from(version: Option<&str>, features: &[&str]) -> Frame { + let features = features.iter().map(|f| f.to_string()).collect(); + Frame::Hello { name: "Old".into(), have: 0, version: version.map(Into::into), features } +} + +fn picture() -> NewFile { + NewFile { + name: "sunset.png".into(), + mime: "image/png".into(), + width: Some(1600), + height: Some(900), + preview: None, + text: "look at this".into(), + reply_to: None, + } +} + +#[tokio::test(start_paused = true)] +async fn a_peer_from_before_0_6_gets_neither_vanishing_messages_nor_files() { + let world = World::new(); + let alice = world.start("alice", "Alice").await; + let mut old = Played::pair(&world, &alice, hello_from(None, &[])).await; + + let refused = alice.send_message("psst", None, Some(60)).unwrap_err().to_string(); + assert!(refused.contains("0.6 or later"), "{refused}"); + let refused = alice.send_file(b"png", picture()).unwrap_err().to_string(); + assert!(refused.contains("0.7 or later"), "{refused}"); + alice.send_message("plain is fine", None, None).unwrap(); + let wanted = |f: &Frame| matches!(f, Frame::Msg(w) if w.text == "plain is fine"); + old.next("the message", wanted).await; +} + +#[tokio::test(start_paused = true)] +async fn a_peer_on_0_6_gets_vanishing_messages_but_not_files() { + let world = World::new(); + let alice = world.start("alice", "Alice").await; + let mut old = Played::pair(&world, &alice, hello_from(Some("0.6.0"), &[])).await; + + alice.send_message("psst", None, Some(60)).unwrap(); + let vanishing = |f: &Frame| matches!(f, Frame::Msg(w) if w.vanish == Some(60)); + old.next("the vanishing message", vanishing).await; + let refused = alice.send_file(b"png", picture()).unwrap_err().to_string(); + assert!(refused.contains("0.7 or later"), "{refused}"); +} + +#[tokio::test(start_paused = true)] +async fn frames_from_a_newer_build_are_skipped() { + let world = World::new(); + let alice = world.start("alice", "Alice").await; + let mut newer = Played::pair(&world, &alice, hello_from(Some("9.0.0"), &["files"])).await; + + let pin = serde_json::json!({"t": "pin", "to": {"author": "x", "seq": 1}}); + write_json(&mut newer.send, &pin).await.unwrap(); + newer.write(Entry::message(newer.id.clone(), 1, EPOCH_MS, "after the pin")).await; + until("the message after it arrives", || alice.texts() == ["after the pin"]).await; + assert!(alice.status().connected, "the session carried on"); +} + +// ---- Files --------------------------------------------------------------------------- + +/// Three megabytes that aren't all the same. +fn photo_bytes() -> Vec { + (0..3_000_000u32).map(|i| (i * 7 % 251) as u8).collect() +} + +fn info_for(bytes: &[u8]) -> FileInfo { + FileInfo { + hash: blake3::hash(bytes).to_hex().to_string(), + name: "sunset.png".into(), + size: bytes.len() as u64, + mime: "image/png".into(), + width: None, + height: None, + preview: None, + } +} + +fn with_file(author: &str, seq: u64, file: FileInfo) -> Entry { + let kind = Kind::Message { reply_to: None, vanish: None, file: Some(file) }; + Entry { kind, ..Entry::message(author, seq, EPOCH_MS, "") } +} + +fn file_state(peer: &Peer, at: &Ref) -> Option { + peer.find(at).and_then(|m| m.file).map(|f| f.state) +} + +/// Where `folder`'s app keeps its files. +fn files_in(world: &World, folder: &str) -> PathBuf { + world.root.join(folder).join("files") +} + +#[tokio::test(start_paused = true)] +async fn a_picture_arrives_after_its_message() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + let bytes = photo_bytes(); + let sent = alice.send_file(&bytes, picture()).unwrap(); + assert_eq!(sent.file.as_ref().unwrap().state, FileState::Done, "the sender has it"); + let at = Ref { author: alice.id(), seq: sent.seq }; + until("bob has it", || file_state(&bob, &at) == Some(FileState::Done)).await; + let (path, mime) = bob.file(&sent.file.unwrap().info.hash).unwrap().unwrap(); + assert_eq!((std::fs::read(&path).unwrap(), mime.as_str()), (bytes, "image/png")); + assert_eq!(path.file_name().unwrap(), "sunset.png"); + assert_eq!(bob.find(&at).unwrap().text, "look at this"); +} + +#[tokio::test(start_paused = true)] +async fn a_transfer_resumes_where_it_broke_off() { + let world = World::new(); + let alice = world.start("alice", "Alice").await; + let mut sender = Played::pair(&world, &alice, hello_from(Some("0.7.0"), &["files"])).await; + let bytes = photo_bytes(); + let info = info_for(&bytes); + // Alice already has the first megabyte, from a transfer that broke off. + let files = files_in(&world, "alice"); + std::fs::create_dir_all(&files).unwrap(); + std::fs::write(files.join(format!("{}.part", info.hash)), &bytes[..1 << 20]).unwrap(); + + let me = sender.id.clone(); + sender.write(with_file(&me, 1, info.clone())).await; + let (mut send, mut recv) = sender.conn.accept_bi().await.unwrap(); + let request: FileRequest = read_json(&mut recv).await.unwrap(); + assert_eq!((request.hash.as_str(), request.from), (info.hash.as_str(), 1 << 20)); + write_json(&mut send, &FileReply { found: true }).await.unwrap(); + send.write_all(&bytes[1 << 20..]).await.unwrap(); + send.finish().unwrap(); + + let at = sender.at(1); + until("alice has it", || file_state(&alice, &at) == Some(FileState::Done)).await; + let (path, _) = alice.file(&info.hash).unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), bytes); +} + +#[tokio::test(start_paused = true)] +async fn a_file_that_does_not_match_its_hash_is_not_kept() { + let world = World::new(); + let alice = world.start("alice", "Alice").await; + let mut sender = Played::pair(&world, &alice, hello_from(Some("0.7.0"), &["files"])).await; + let bytes = photo_bytes(); + let info = info_for(&bytes); + + let me = sender.id.clone(); + sender.write(with_file(&me, 1, info.clone())).await; + let (mut send, mut recv) = sender.conn.accept_bi().await.unwrap(); + let _: FileRequest = read_json(&mut recv).await.unwrap(); + write_json(&mut send, &FileReply { found: true }).await.unwrap(); + send.write_all(&vec![0; bytes.len()]).await.unwrap(); // the right size, the wrong bytes + send.finish().unwrap(); + send.stopped().await; // alice has read it all and given up + + let at = sender.at(1); + assert_eq!(file_state(&alice, &at), Some(FileState::Pending), "still to come"); + assert!(alice.file(&info.hash).unwrap().is_none()); + let part = files_in(&world, "alice").join(format!("{}.part", info.hash)); + assert!(!part.exists(), "nothing half-kept"); +} + +#[tokio::test(start_paused = true)] +async fn a_file_deleted_on_its_way_is_not_kept() { + let world = World::new(); + let alice = world.start("alice", "Alice").await; + let mut sender = Played::pair(&world, &alice, hello_from(Some("0.7.0"), &["files"])).await; + let bytes = photo_bytes(); + let info = info_for(&bytes); + let me = sender.id.clone(); + + sender.write(with_file(&me, 1, info.clone())).await; + let (mut send, mut recv) = sender.conn.accept_bi().await.unwrap(); + let _: FileRequest = read_json(&mut recv).await.unwrap(); + write_json(&mut send, &FileReply { found: true }).await.unwrap(); + send.write_all(&bytes[..1 << 20]).await.unwrap(); + + // Halfway through, the sender deletes the message. + let at = sender.at(1); + let delete = Kind::Delete { of: at.clone() }; + sender.write(Entry { kind: delete, ..Entry::message(&me, 2, EPOCH_MS, "") }).await; + until("alice sees the delete", || alice.find(&at).unwrap().deleted).await; + send.write_all(&bytes[1 << 20..]).await.unwrap(); + send.finish().unwrap(); + send.stopped().await; + + assert!(alice.file(&info.hash).unwrap().is_none()); + let files = files_in(&world, "alice"); + assert!(!files.join(&info.hash).exists(), "not kept"); + assert!(!files.join(format!("{}.part", info.hash)).exists(), "nor half-kept"); +} + +#[tokio::test(start_paused = true)] +async fn a_file_the_sender_no_longer_has_ends_up_gone() { + let world = World::new(); + let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await); + world.pair(&alice, &bob).await; + bob.stop().await; + until("alice notices", || !alice.status().connected).await; + + let sent = alice.send_file(&photo_bytes(), picture()).unwrap(); + let hash = sent.file.unwrap().info.hash; + let (path, _) = alice.file(&hash).unwrap().unwrap(); + std::fs::remove_file(path).unwrap(); // tidied away by hand + + let bob = world.start("bob", "Bob").await; + let at = Ref { author: alice.id(), seq: sent.seq }; + until("both give up", || { + file_state(&bob, &at) == Some(FileState::Gone) + && file_state(&alice, &at) == Some(FileState::Gone) + }) + .await; +} diff --git a/src-tauri/src/clock.rs b/src-tauri/src/clock.rs new file mode 100644 index 0000000..e067d12 --- /dev/null +++ b/src-tauri/src/clock.rs @@ -0,0 +1,57 @@ +//! Wall-clock time, one source for the engine and the log. +//! +//! The app reads the system clock. Tests use a clock that follows tokio's paused time, +//! so the waits (`sleep`, `timeout`) and the wall clock move together when a test +//! advances time. + +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Debug, Clone)] +pub(crate) struct Clock(Source); + +#[derive(Debug, Clone)] +enum Source { + System, + /// `epoch_ms` at `start`, then moving with tokio's clock. + #[cfg(test)] + Tokio { + epoch_ms: i64, + start: tokio::time::Instant, + }, +} + +impl Clock { + pub fn system() -> Self { + Self(Source::System) + } + + /// Starts at `epoch_ms` now, then follows tokio's clock (paused, in tests). + #[cfg(test)] + pub fn tokio(epoch_ms: i64) -> Self { + Self(Source::Tokio { epoch_ms, start: tokio::time::Instant::now() }) + } + + /// Milliseconds since the Unix epoch. + pub fn now_ms(&self) -> i64 { + match &self.0 { + Source::System => { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64) + } + #[cfg(test)] + Source::Tokio { epoch_ms, start } => epoch_ms + start.elapsed().as_millis() as i64, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test(start_paused = true)] + async fn follows_paused_time() { + let clock = Clock::tokio(1_000); + assert_eq!(clock.now_ms(), 1_000); + tokio::time::sleep(std::time::Duration::from_secs(90)).await; + assert_eq!(clock.now_ms(), 91_000); + } +} diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index c7d7e62..a62b226 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -22,15 +22,13 @@ //! which the sender no longer has ('gone'). No row means still on its way. A delete //! blanks the message's file details along with its text. -use std::{ - path::Path, - time::{SystemTime, UNIX_EPOCH}, -}; +use std::path::Path; use anyhow::{Result, bail}; use rusqlite::{Connection, OptionalExtension, params}; use serde::{Deserialize, Serialize}; +use crate::clock::Clock; use crate::entry::{DELETE, EDIT, Entry, FileInfo, Kind, MESSAGE, REACTION, Ref}; /// Where a message's file has got to on this computer. @@ -145,10 +143,15 @@ struct Current { deleted: bool, } -pub struct Db(Connection); +pub struct Db(Connection, Clock); impl Db { pub fn open(path: &Path) -> Result { + Self::open_with(path, Clock::system()) + } + + /// Opens the log with `clock` for the time vanishing messages are judged by. + pub(crate) fn open_with(path: &Path, clock: Clock) -> Result { let conn = Connection::open(path)?; // Freed space is zeroed, so deleted and cleared text doesn't linger in the file. conn.execute_batch( @@ -200,7 +203,7 @@ impl Db { COMMIT;", )?; } - let db = Self(conn); + let db = Self(conn, clock); if version < 5 { // One transaction, so the search index is filled using the finished schema. db.0.execute_batch("BEGIN")?; @@ -286,7 +289,7 @@ impl Db { /// Whether a vanishing message's time is up. fn vanished(&self, at: &Ref) -> Result { - Ok(self.expires(at)?.is_some_and(|t| t <= now_ms())) + Ok(self.expires(at)?.is_some_and(|t| t <= self.1.now_ms())) } /// When a message vanishes, if its countdown has started. @@ -701,7 +704,7 @@ impl Db { let at = Ref { author: e.author, seq: e.seq }; let current = self.current(&at, e.text)?; let expires = self.expires(&at)?; - let vanished = expires.is_some_and(|t| t <= now_ms()); + let vanished = expires.is_some_and(|t| t <= self.1.now_ms()); let (author, seq, ts, hlc) = (at.author.clone(), at.seq, e.ts, e.hlc); if current.deleted || vanished { let (text, reply_to, reactions) = (String::new(), None, Vec::new()); @@ -838,10 +841,6 @@ impl Db { } } -fn now_ms() -> i64 { - SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 26c5324..cfe8b41 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,8 +1,10 @@ pub mod chat; +mod clock; pub mod db; mod desktop; pub mod entry; mod idle; +mod net; mod updates; use std::{path::PathBuf, sync::Arc}; diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs new file mode 100644 index 0000000..9f9b491 --- /dev/null +++ b/src-tauri/src/net.rs @@ -0,0 +1,325 @@ +//! The network: how this computer finds and reaches its peer. +//! +//! The engine (`chat`) runs on this port and never touches iroh itself. The app uses +//! iroh over the LAN, found with mDNS. Tests use an in-memory network, so the protocol +//! runs in milliseconds and with time under the test's control. +//! +//! Each type is an enum with one variant per adapter. A connection carries +//! bidirectional streams: the session's frames on the first, files on the rest. + +use std::{borrow::Cow, net::IpAddr, pin::Pin}; + +use anyhow::Result; +use iroh::{ + Endpoint, EndpointId, SecretKey, TransportAddr, + address_lookup::AddrFilter, + endpoint::{Incoming, PortmapperConfig, presets}, + endpoint_info::UserData, +}; +use iroh_mdns_address_lookup::{DiscoveryEvent, MdnsAddressLookup}; +use n0_future::{Stream, StreamExt}; + +#[cfg(test)] +mod memory; +#[cfg(test)] +pub(crate) use memory::Lan; + +/// What connections are for, so only other Tightbeam apps connect. +const ALPN: &[u8] = b"tightbeam/1"; +/// mDNS service name, so we only see other Tightbeam apps (`_tightbeam._udp.local`). +const SERVICE: &str = "tightbeam"; + +pub(crate) enum Network { + Iroh { + endpoint: Endpoint, + mdns: MdnsAddressLookup, + }, + #[cfg(test)] + Memory(memory::Node), +} + +impl Network { + /// iroh on the LAN. `loopback_only` binds to 127.0.0.1, for running two copies on one + /// machine. (Windows refuses to send from a LAN address to that same address.) + pub async fn iroh(secret: SecretKey, loopback_only: bool) -> Result { + // LAN only for now: no relay servers, no public DNS, just mDNS. No UPnP either: + // we never ask the router to open a public port, and we only ever advertise + // private addresses. + let mut builder = Endpoint::builder(presets::Minimal) + .secret_key(secret) + .alpns(vec![ALPN.to_vec()]) + .portmapper_config(PortmapperConfig::Disabled) + .addr_filter(AddrFilter::new(move |addrs| { + Cow::Owned(addrs.iter().filter(|a| is_lan(a, loopback_only)).cloned().collect()) + })); + if loopback_only { + builder = builder.clear_ip_transports().bind_addr("127.0.0.1:0")?; + } + let endpoint = builder.bind().await?; + let mdns = MdnsAddressLookup::builder().service_name(SERVICE).build(endpoint.id())?; + endpoint.address_lookup()?.add(mdns.clone()); + Ok(Self::Iroh { endpoint, mdns }) + } + + pub fn id(&self) -> EndpointId { + match self { + Self::Iroh { endpoint, .. } => endpoint.id(), + #[cfg(test)] + Self::Memory(node) => node.id(), + } + } + + /// The name others see next to this computer when they look for someone to pair with. + pub fn advertise(&self, name: &str) { + match self { + Self::Iroh { endpoint, .. } => { + let data = + if name.is_empty() { None } else { UserData::try_from(name.to_string()).ok() }; + endpoint.set_user_data_for_address_lookup(data); + } + #[cfg(test)] + Self::Memory(node) => node.advertise(name), + } + } + + /// Who comes and goes nearby. + pub async fn discoveries(&self) -> Discoveries { + match self { + Self::Iroh { mdns, .. } => Discoveries::Iroh(Box::pin(mdns.subscribe().await)), + #[cfg(test)] + Self::Memory(node) => node.discoveries(), + } + } + + pub async fn connect(&self, peer: EndpointId) -> Result { + match self { + Self::Iroh { endpoint, .. } => Ok(Conn::Iroh(endpoint.connect(peer, ALPN).await?)), + #[cfg(test)] + Self::Memory(node) => Ok(Conn::Memory(node.connect(peer)?)), + } + } + + /// The next incoming connection, or `None` once the network is closed. + pub async fn accept(&self) -> Option { + match self { + Self::Iroh { endpoint, .. } => endpoint.accept().await.map(Accepting::Iroh), + #[cfg(test)] + Self::Memory(node) => node.accept().await, + } + } + + /// Closes every connection, so the peer notices right away. + pub async fn close(&self) { + match self { + Self::Iroh { endpoint, .. } => endpoint.close().await, + #[cfg(test)] + Self::Memory(node) => node.close(), + } + } +} + +/// Someone nearby appeared, with their advertised name, or went away. +pub(crate) enum Discovery { + Found { id: EndpointId, name: String }, + Lost(EndpointId), +} + +pub(crate) enum Discoveries { + Iroh(Pin + Send>>), + #[cfg(test)] + Memory(tokio::sync::mpsc::UnboundedReceiver), +} + +impl Discoveries { + pub async fn next(&mut self) -> Option { + match self { + Self::Iroh(events) => loop { + match events.next().await? { + DiscoveryEvent::Discovered { endpoint_info, .. } => { + let id = endpoint_info.endpoint_id; + let name = endpoint_info.data.user_data().map(|u| u.to_string()); + return Some(Discovery::Found { id, name: name.unwrap_or_default() }); + } + DiscoveryEvent::Expired { endpoint_id } => { + return Some(Discovery::Lost(endpoint_id)); + } + _ => continue, + } + }, + #[cfg(test)] + Self::Memory(events) => events.recv().await, + } + } +} + +/// A connection on its way in. +// The small variant exists only in tests, so boxing the large one would cost the app. +#[cfg_attr(test, allow(clippy::large_enum_variant))] +pub(crate) enum Accepting { + Iroh(Incoming), + #[cfg(test)] + Memory(memory::Conn), +} + +impl Accepting { + pub async fn connected(self) -> Result { + match self { + Self::Iroh(incoming) => Ok(Conn::Iroh(incoming.await?)), + #[cfg(test)] + Self::Memory(conn) => Ok(Conn::Memory(conn)), + } + } +} + +#[derive(Clone)] +pub(crate) enum Conn { + Iroh(iroh::endpoint::Connection), + #[cfg(test)] + Memory(memory::Conn), +} + +/// The route a connection takes: the peer's address and the round trip in milliseconds. +pub(crate) struct Route { + pub address: String, + pub rtt_ms: f64, +} + +impl Conn { + pub fn remote_id(&self) -> EndpointId { + match self { + Self::Iroh(conn) => conn.remote_id(), + #[cfg(test)] + Self::Memory(conn) => conn.remote_id(), + } + } + + pub async fn open_bi(&self) -> Result<(SendStream, RecvStream)> { + match self { + Self::Iroh(conn) => { + let (send, recv) = conn.open_bi().await?; + Ok((SendStream::Iroh(send), RecvStream::Iroh(recv))) + } + #[cfg(test)] + Self::Memory(conn) => { + let (send, recv) = conn.open_bi()?; + Ok((SendStream::Memory(send), RecvStream::Memory(recv))) + } + } + } + + pub async fn accept_bi(&self) -> Result<(SendStream, RecvStream)> { + match self { + Self::Iroh(conn) => { + let (send, recv) = conn.accept_bi().await?; + Ok((SendStream::Iroh(send), RecvStream::Iroh(recv))) + } + #[cfg(test)] + Self::Memory(conn) => { + let (send, recv) = conn.accept_bi().await?; + Ok((SendStream::Memory(send), RecvStream::Memory(recv))) + } + } + } + + /// Ends the connection for both sides; `reason` is for logs. + pub fn close(&self, code: u32, reason: &[u8]) { + match self { + Self::Iroh(conn) => conn.close(code.into(), reason), + #[cfg(test)] + Self::Memory(conn) => conn.close(), + } + } + + /// Resolves once the connection has ended, from either side. + pub async fn closed(&self) { + match self { + Self::Iroh(conn) => drop(conn.closed().await), + #[cfg(test)] + Self::Memory(conn) => conn.closed().await, + } + } + + pub fn route(&self) -> Option { + match self { + Self::Iroh(conn) => { + let paths = conn.paths(); + let path = paths.iter().find(|p| p.is_selected())?; + let (address, rtt) = (path.remote_addr().to_string(), path.rtt()); + Some(Route { address, rtt_ms: rtt.as_secs_f64() * 1000.0 }) + } + #[cfg(test)] + Self::Memory(_) => None, + } + } +} + +pub(crate) enum SendStream { + Iroh(iroh::endpoint::SendStream), + #[cfg(test)] + Memory(memory::Send), +} + +impl SendStream { + pub async fn write_all(&mut self, buf: &[u8]) -> Result<()> { + match self { + Self::Iroh(send) => Ok(send.write_all(buf).await?), + #[cfg(test)] + Self::Memory(send) => send.write_all(buf), + } + } + + /// No more to send: the other side reads to the end. + pub fn finish(&mut self) -> Result<()> { + match self { + Self::Iroh(send) => Ok(send.finish()?), + #[cfg(test)] + Self::Memory(send) => send.finish(), + } + } + + /// Resolves once the other side has read everything, or stopped reading. + pub async fn stopped(&mut self) { + match self { + Self::Iroh(send) => drop(send.stopped().await), + #[cfg(test)] + Self::Memory(send) => send.stopped().await, + } + } +} + +pub(crate) enum RecvStream { + Iroh(iroh::endpoint::RecvStream), + #[cfg(test)] + Memory(memory::Recv), +} + +impl RecvStream { + /// Some bytes into `buf`, or `None` at the end of the stream. + pub async fn read(&mut self, buf: &mut [u8]) -> Result> { + match self { + Self::Iroh(recv) => Ok(recv.read(buf).await?), + #[cfg(test)] + Self::Memory(recv) => recv.read(buf).await, + } + } + + pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { + match self { + Self::Iroh(recv) => Ok(recv.read_exact(buf).await?), + #[cfg(test)] + Self::Memory(recv) => recv.read_exact(buf).await, + } + } +} + +/// Whether an address is on the local network (or loopback, when allowed). +fn is_lan(addr: &TransportAddr, allow_loopback: bool) -> bool { + match addr { + TransportAddr::Ip(sock) => match sock.ip() { + IpAddr::V4(ip) if ip.is_loopback() => allow_loopback, + IpAddr::V4(ip) => ip.is_private() || ip.is_link_local(), + IpAddr::V6(ip) => ip.is_unique_local() || ip.is_unicast_link_local(), + }, + _ => false, + } +} diff --git a/src-tauri/src/net/memory.rs b/src-tauri/src/net/memory.rs new file mode 100644 index 0000000..f597665 --- /dev/null +++ b/src-tauri/src/net/memory.rs @@ -0,0 +1,347 @@ +//! An in-memory network for tests. Every node that joins a `Lan` discovers the others +//! by name, connects to them instantly, and streams bytes through channels. +//! +//! Like QUIC, a connection ends abruptly: reads and writes on its streams fail at once. +//! Closing it, or dropping every handle to one side of it, ends it for both sides. A node +//! that closes (its app shut down) leaves the LAN: the others see it go, and its +//! connections end. A node can also drop out (`Lan::drop_out`): its connections end on +//! its side only, while the other side notices nothing, the way a laptop that loses its +//! Wi-Fi leaves the other end waiting for a timeout. + +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; + +use anyhow::{Result, anyhow, bail}; +use iroh::{EndpointId, SecretKey}; +use tokio::sync::{mpsc, oneshot, watch}; + +use super::{Accepting, Discoveries, Discovery, Network}; + +#[derive(Clone, Default)] +pub(crate) struct Lan(Arc>); + +#[derive(Default)] +struct Nodes(HashMap); + +struct Joined { + name: String, + incoming: mpsc::UnboundedSender, + watchers: Vec>, + /// Every connection this node is part of, and which side of it is this node's. + links: Vec<(Arc, usize)>, +} + +impl Lan { + /// A node with this key joins, in place of any earlier node with the same key. + pub fn join(&self, secret: SecretKey) -> Network { + let id = secret.public(); + let (incoming, accept) = mpsc::unbounded_channel(); + let mut nodes = self.0.lock().unwrap(); + if let Some(old) = nodes.0.remove(&id) { + old.leave(); + } + nodes.tell_others(id, || Discovery::Found { id, name: String::new() }); + let joined = Joined { name: String::new(), incoming, watchers: vec![], links: vec![] }; + nodes.0.insert(id, joined); + Network::Memory(Node { id, lan: self.clone(), accept: tokio::sync::Mutex::new(accept) }) + } + + /// `id` loses its connections without closing them: they end on its side only. + pub fn drop_out(&self, id: EndpointId) { + if let Some(node) = self.0.lock().unwrap().0.get_mut(&id) { + for (link, side) in node.links.drain(..) { + link.cut[side].send_replace(true); + } + } + } +} + +impl Nodes { + fn tell_others(&mut self, id: EndpointId, event: impl Fn() -> Discovery) { + for (_, node) in self.0.iter_mut().filter(|(other, _)| **other != id) { + node.watchers.retain(|w| w.send(event()).is_ok()); + } + } +} + +impl Joined { + fn leave(self) { + for (link, _) in self.links { + link.closed.send_replace(true); + } + } +} + +pub(crate) struct Node { + id: EndpointId, + lan: Lan, + accept: tokio::sync::Mutex>, +} + +impl Node { + pub fn id(&self) -> EndpointId { + self.id + } + + pub fn advertise(&self, name: &str) { + let mut nodes = self.lan.0.lock().unwrap(); + let Some(me) = nodes.0.get_mut(&self.id) else { return }; + me.name = name.to_string(); + let (id, name) = (self.id, name.to_string()); + nodes.tell_others(id, || Discovery::Found { id, name: name.clone() }); + } + + pub fn discoveries(&self) -> Discoveries { + let (tx, rx) = mpsc::unbounded_channel(); + let mut nodes = self.lan.0.lock().unwrap(); + for (id, node) in nodes.0.iter().filter(|(id, _)| **id != self.id) { + let _ = tx.send(Discovery::Found { id: *id, name: node.name.clone() }); + } + if let Some(me) = nodes.0.get_mut(&self.id) { + me.watchers.push(tx); + } + Discoveries::Memory(rx) + } + + pub fn connect(&self, peer: EndpointId) -> Result { + let mut nodes = self.lan.0.lock().unwrap(); + if !nodes.0.contains_key(&self.id) { + bail!("this node has left the network"); + } + let Some(them) = nodes.0.get_mut(&peer) else { bail!("{peer} isn't on the network") }; + let (mine, theirs) = Conn::pair(self.id, peer); + let link = mine.link.clone(); + if them.incoming.send(theirs).is_err() { + bail!("{peer} isn't accepting connections"); + } + them.links.retain(|(l, _)| !l.is_closed()); + them.links.push((link.clone(), 1)); + let me = nodes.0.get_mut(&self.id).unwrap(); + me.links.retain(|(l, _)| !l.is_closed()); + me.links.push((link, 0)); + Ok(mine) + } + + pub async fn accept(&self) -> Option { + self.accept.lock().await.recv().await.map(Accepting::Memory) + } + + /// Leaves the network: the others see this node go, and its connections end. + pub fn close(&self) { + let mut nodes = self.lan.0.lock().unwrap(); + if let Some(me) = nodes.0.remove(&self.id) { + me.leave(); + let id = self.id; + nodes.tell_others(id, || Discovery::Lost(id)); + } + // Its `incoming` sender went with it, so `accept` now returns `None`. + } +} + +/// What both ends of one connection share. +struct Link { + /// Ended for both sides. + closed: watch::Sender, + /// Ended for one side only (`Lan::drop_out`), by side. + cut: [watch::Sender; 2], +} + +impl Link { + fn is_closed(&self) -> bool { + *self.closed.borrow() + } + + /// Ends the connection for both sides, unless `side` has dropped out: then the other + /// side never hears of it. + fn close_from(&self, side: usize) { + if !*self.cut[side].borrow() { + self.closed.send_replace(true); + } + } + + fn is_down(&self, side: usize) -> bool { + self.is_closed() || *self.cut[side].borrow() + } + + /// Resolves once the connection has ended for `side`. + async fn down(&self, side: usize) { + let (mut closed, mut cut) = (self.closed.subscribe(), self.cut[side].subscribe()); + tokio::select! { + _ = closed.wait_for(|c| *c) => {} + _ = cut.wait_for(|c| *c) => {} + } + } +} + +/// One side's handles; when the last is dropped, the connection closes, as in QUIC. +struct Handle(Arc, usize); + +impl Drop for Handle { + fn drop(&mut self) { + self.0.close_from(self.1); + } +} + +/// Streams the other side opened, waiting to be accepted. +type Streams = mpsc::UnboundedReceiver<(Send, Recv)>; + +#[derive(Clone)] +pub(crate) struct Conn { + remote: EndpointId, + link: Arc, + side: usize, + to_peer: mpsc::UnboundedSender<(Send, Recv)>, + from_peer: Arc>, + _handle: Arc, +} + +impl Conn { + /// Both ends of a new connection from `a` (side 0) to `b` (side 1). + fn pair(a: EndpointId, b: EndpointId) -> (Conn, Conn) { + let link = Arc::new(Link { + closed: watch::Sender::new(false), + cut: [watch::Sender::new(false), watch::Sender::new(false)], + }); + let (a_to_b, b_from_a) = mpsc::unbounded_channel(); + let (b_to_a, a_from_b) = mpsc::unbounded_channel(); + let end = |remote, side, to_peer, from_peer| Conn { + remote, + link: link.clone(), + side, + to_peer, + from_peer: Arc::new(tokio::sync::Mutex::new(from_peer)), + _handle: Arc::new(Handle(link.clone(), side)), + }; + (end(b, 0, a_to_b, a_from_b), end(a, 1, b_to_a, b_from_a)) + } + + pub fn remote_id(&self) -> EndpointId { + self.remote + } + + pub fn open_bi(&self) -> Result<(Send, Recv)> { + if self.link.is_down(self.side) { + bail!("connection lost"); + } + let theirs = 1 - self.side; + let (mine_out, theirs_in) = self.pipe(self.side, theirs); + let (theirs_out, mine_in) = self.pipe(theirs, self.side); + if self.to_peer.send((theirs_out, theirs_in)).is_err() { + bail!("connection lost"); + } + Ok((mine_out, mine_in)) + } + + /// One direction of a stream, from side `from` to side `to`. + fn pipe(&self, from: usize, to: usize) -> (Send, Recv) { + let (tx, rx) = mpsc::unbounded_channel(); + let (reading, stopped) = oneshot::channel(); + let send = Send { tx: Some(tx), stopped, link: self.link.clone(), side: from }; + let recv = + Recv { rx, pending: Vec::new(), _reading: reading, link: self.link.clone(), side: to }; + (send, recv) + } + + pub async fn accept_bi(&self) -> Result<(Send, Recv)> { + let mut from_peer = self.from_peer.lock().await; + tokio::select! { + biased; + _ = self.link.down(self.side) => bail!("connection lost"), + streams = from_peer.recv() => streams.ok_or_else(|| anyhow!("connection lost")), + } + } + + pub fn close(&self) { + self.link.close_from(self.side); + } + + pub async fn closed(&self) { + self.link.down(self.side).await + } +} + +pub(crate) struct Send { + /// `None` once finished. + tx: Option>>, + /// Resolves (as an error) when the reading side is dropped. + stopped: oneshot::Receiver<()>, + link: Arc, + side: usize, +} + +impl Send { + pub fn write_all(&mut self, buf: &[u8]) -> Result<()> { + if self.link.is_down(self.side) { + bail!("connection lost"); + } + let Some(tx) = &self.tx else { bail!("stream already finished") }; + if buf.is_empty() { + return Ok(()); + } + if tx.send(buf.to_vec()).is_err() { + bail!("the other side stopped reading"); + } + Ok(()) + } + + pub fn finish(&mut self) -> Result<()> { + match self.tx.take() { + Some(_) => Ok(()), + None => bail!("stream already finished"), + } + } + + pub async fn stopped(&mut self) { + tokio::select! { + _ = &mut self.stopped => {} + _ = self.link.down(self.side) => {} + } + } +} + +pub(crate) struct Recv { + rx: mpsc::UnboundedReceiver>, + /// Bytes received but not yet read. + pending: Vec, + /// Dropped with this side, which is what `Send::stopped` waits for. + _reading: oneshot::Sender<()>, + link: Arc, + side: usize, +} + +impl Recv { + pub async fn read(&mut self, buf: &mut [u8]) -> Result> { + if self.pending.is_empty() { + tokio::select! { + biased; + _ = self.link.down(self.side) => bail!("connection lost"), + chunk = self.rx.recv() => match chunk { + Some(chunk) => self.pending = chunk, + // A sender that dropped out can't be heard finishing: just silence. + None if *self.link.cut[1 - self.side].borrow() => { + self.link.down(self.side).await; + bail!("connection lost"); + } + None => return Ok(None), + }, + } + } + let n = buf.len().min(self.pending.len()); + buf[..n].copy_from_slice(&self.pending[..n]); + self.pending.drain(..n); + Ok(Some(n)) + } + + pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { + let mut filled = 0; + while filled < buf.len() { + match self.read(&mut buf[filled..]).await? { + Some(n) => filled += n, + None => bail!("stream ended early"), + } + } + Ok(()) + } +} diff --git a/src-tauri/tests/two_peers.rs b/src-tauri/tests/two_peers.rs index 8eba480..90f49e3 100644 --- a/src-tauri/tests/two_peers.rs +++ b/src-tauri/tests/two_peers.rs @@ -1,20 +1,19 @@ -//! Two real Tightbeam cores on this machine, found via mDNS and talking over QUIC. -//! Covers pairing, live messages, delivery acks, seen receipts, catching up after one -//! side was off, replies and reactions, edits and deletes, typing, nudges, away and back, -//! clearing one side's history, versions, do not disturb, vanishing messages, and files. +//! Two real Tightbeam cores on this machine, found via mDNS and talking over QUIC: the +//! part of the engine only the real network can check. Discovery, pairing, a message +//! each way, a restart that redials and catches up, and a file on streams of its own. +//! +//! The protocol itself (receipts, presence, edits, vanishing messages, files that go +//! missing, other builds) is tested on the in-memory network in `chat/protocol_tests.rs`. use std::{ path::PathBuf, - sync::{ - Arc, - atomic::{AtomicUsize, Ordering}, - }, + sync::Arc, time::{Duration, Instant}, }; use tightbeam_lib::{ - chat::{Away, Core, Emit, Event, NewFile}, - db::FileState, + chat::{Core, Emit, NewFile}, + db::{FileState, Message}, entry::Ref, }; @@ -22,15 +21,6 @@ fn quiet() -> Emit { Arc::new(|_| {}) } -/// Counts the nudges and typing signals it's told about. -fn counting(nudges: Arc, typing: Arc) -> Emit { - Arc::new(move |event| match event { - Event::Nudge => drop(nudges.fetch_add(1, Ordering::SeqCst)), - Event::Typing => drop(typing.fetch_add(1, Ordering::SeqCst)), - _ => {} - }) -} - fn temp_dir(label: &str) -> PathBuf { let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); @@ -55,6 +45,10 @@ fn texts(core: &Core) -> Vec { core.messages().unwrap().into_iter().map(|m| m.text).collect() } +fn find(core: &Core, at: &Ref) -> Option { + core.messages().unwrap().into_iter().find(|m| m.author == at.author && m.seq == at.seq) +} + #[tokio::test(flavor = "multi_thread")] async fn pair_chat_and_catch_up() { let _ = tracing_subscriber::fmt() @@ -96,159 +90,28 @@ async fn pair_chat_and_catch_up() { assert_eq!(alice.status().peer.unwrap().name, "Bob"); assert_eq!(bob.status().peer.unwrap().name, "Alice"); - // Live messages both ways, with delivery confirmation. + // Messages both ways, with delivery confirmation. let a = alice.clone(); like_tauri(move || a.send_message("hi bob", None, None)).unwrap(); wait_for("bob gets alice's message", 10, || texts(&bob).contains(&"hi bob".into())).await; bob.send_message("hi alice", None, None).unwrap(); wait_for("alice gets bob's message", 10, || texts(&alice).contains(&"hi alice".into())).await; wait_for("alice sees delivery", 10, || alice.status().peer_has == 1).await; - assert_eq!(alice.status().peer_seen, 0, "delivered isn't seen"); - // Bob looks at the chat: Alice's message shows as seen. - let b = bob.clone(); - like_tauri(move || b.mark_seen()).unwrap(); - wait_for("alice sees bob saw it", 10, || alice.status().peer_seen == 1).await; - - // Bob goes offline; Alice keeps writing. + // Bob quits; Alice keeps writing. He comes back with the same identity, the dialer + // finds him again, and he catches up. bob.shutdown().await; drop(bob); wait_for("alice notices bob left", 40, || !alice.status().connected).await; alice.send_message("you there?", None, None).unwrap(); - alice.send_message("guess not", None, None).unwrap(); - // A reaction while he's away: it syncs with the catch-up. - let first = Ref { author: bob_id.clone(), seq: 1 }; - alice.react(first.clone(), "👍").unwrap(); - assert_eq!(alice.status().peer_has, 1, "undelivered messages must not show as delivered"); - - // Bob comes back with the same identity and catches up. - let (nudges, typing) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); - bob = Core::start_with(dir_b.clone(), counting(nudges.clone(), typing.clone()), true) - .await - .unwrap(); + bob = Core::start_with(dir_b.clone(), quiet(), true).await.unwrap(); assert_eq!(bob.id(), bob_id, "identity must survive a restart"); assert_eq!(bob.status().peer.unwrap().name, "Alice", "pairing must survive a restart"); wait_for("reconnect", 40, || alice.status().connected && bob.status().connected).await; - wait_for("bob catches up", 10, || { - let t = texts(&bob); - t.contains(&"you there?".into()) && t.contains(&"guess not".into()) - }) - .await; - wait_for("alice sees catch-up delivered", 10, || alice.status().peer_has == 4).await; - assert_eq!(texts(&bob).len(), 4, "no duplicates after catch-up, and reactions aren't messages"); - let reactions = |core: &Core| { - let messages = core.messages().unwrap(); - let m = messages.iter().find(|m| m.author == first.author && m.seq == first.seq); - m.unwrap().reactions.iter().map(|r| r.emoji.clone()).collect::>() - }; - wait_for("bob sees the reaction", 10, || reactions(&bob) == ["👍"]).await; - assert_eq!(alice.status().peer_seen, 1, "seen must survive the reconnect, and not grow"); - let b = bob.clone(); - like_tauri(move || b.mark_seen()).unwrap(); - wait_for("alice sees the catch-up seen", 10, || alice.status().peer_seen == 4).await; - - // Bob replies to Alice's first message. Then she takes her reaction back and he adds one. - let hi_bob = Ref { author: alice.id(), seq: 1 }; - let b = bob.clone(); - let sent = like_tauri(move || b.send_message("hi again", Some(hi_bob), None)).unwrap(); - assert_eq!(sent.reply_to.unwrap().text.as_deref(), Some("hi bob")); - wait_for("alice gets the reply", 10, || { - alice.messages().unwrap().iter().any(|m| { - m.text == "hi again" - && m.reply_to.as_ref().is_some_and(|q| q.text.as_deref() == Some("hi bob")) - }) - }) - .await; - alice.react(first.clone(), "").unwrap(); - bob.react(first.clone(), "😂").unwrap(); - wait_for("reactions settle on both sides", 10, || { - reactions(&alice) == ["😂"] && reactions(&bob) == ["😂"] - }) - .await; + wait_for("bob catches up", 10, || texts(&bob).contains(&"you there?".into())).await; + wait_for("alice sees it delivered", 10, || alice.status().peer_has == 2).await; - // Bob edits his reply, then deletes it. Alice sees both, and the text is gone. - let again = Ref { author: bob.id(), seq: 2 }; - bob.edit(again.clone(), "hi once more").unwrap(); - let find = |core: &Core, at: &Ref| { - core.messages().unwrap().into_iter().find(|m| m.author == at.author && m.seq == at.seq) - }; - wait_for("alice sees the edit", 10, || { - find(&alice, &again).is_some_and(|m| m.edited && m.text == "hi once more") - }) - .await; - assert!(alice.edit(again.clone(), "not mine").is_err(), "only the author can edit"); - bob.delete(again.clone()).unwrap(); - wait_for("alice sees the delete", 10, || find(&alice, &again).is_some_and(|m| m.deleted)).await; - - // Typing reaches Bob. - let a = alice.clone(); - like_tauri(move || a.typing()); - wait_for("bob sees alice typing", 10, || typing.load(Ordering::SeqCst) == 1).await; - - // Alice nudges Bob. A second nudge right after is refused. - let a = alice.clone(); - like_tauri(move || a.nudge()).unwrap(); - wait_for("bob gets the nudge", 10, || nudges.load(Ordering::SeqCst) == 1).await; - assert!(alice.nudge().is_err(), "nudges are rate-limited"); - - // Bob goes away with a note. Using the computer doesn't end it; his next message does. - bob.set_away(" lunch\n break "); - let lunch = Some(Away { note: Some("lunch break".into()) }); - wait_for("alice sees bob away", 10, || alice.status().peer_away == lunch).await; - assert_eq!(bob.status().away, lunch); - bob.set_idle(false); - assert_eq!(bob.status().away, lunch, "still away by hand"); - - // Bob clears his copy. Alice keeps hers, and numbering carries on. - let b = bob.clone(); - like_tauri(move || b.clear_history()).unwrap(); - assert!(texts(&bob).is_empty()); - assert_eq!(texts(&alice).len(), 5); - assert_eq!(bob.send_message("fresh start", None, None).unwrap().seq, 6); - wait_for("alice gets it", 10, || texts(&alice).contains(&"fresh start".into())).await; - assert_eq!(texts(&alice).len(), 6); - assert_eq!(texts(&bob), ["fresh start"]); - wait_for("bob's message brings him back", 10, || alice.status().peer_away.is_none()).await; - - // Idle: away without a note, until input resumes. Bob's own screen doesn't show it. - bob.set_idle(true); - let idle = Some(Away { note: None }); - wait_for("alice sees bob idle", 10, || alice.status().peer_away == idle).await; - assert_eq!(bob.status().away, None); - bob.set_idle(false); - wait_for("alice sees bob back", 10, || alice.status().peer_away.is_none()).await; - - // Each side knows the other's version, which is what allows vanishing messages. - let info = alice.connection_info(); - assert_eq!(info.peer_version.as_deref(), Some(env!("CARGO_PKG_VERSION"))); - assert!(info.since.is_some() && info.address.is_some() && info.rtt_ms.is_some()); - - // Do not disturb: Alice sees it, and her nudges are refused until Bob turns it off. - let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap(); - let later = now.as_millis() as i64 + 3_600_000; - bob.set_dnd(Some(later)).unwrap(); - assert!(bob.dnd() && bob.status().dnd_until == Some(later)); - wait_for("alice sees bob's dnd", 10, || alice.status().peer_dnd_until == Some(later)).await; - let refused = alice.nudge().unwrap_err().to_string(); - assert!(refused.contains("do not disturb"), "{refused}"); - bob.set_dnd(None).unwrap(); - wait_for("alice sees it end", 10, || alice.status().peer_dnd_until.is_none()).await; - - // A vanishing message: once Bob has seen it, it's gone from both sides 5 seconds later. - let secret = alice.send_message("the code is 1234", None, Some(5)).unwrap(); - let at = Ref { author: alice.id(), seq: secret.seq }; - wait_for("bob gets it", 10, || find(&bob, &at).is_some()).await; - assert_eq!(find(&bob, &at).unwrap().expires, None, "its clock starts when seen"); - bob.mark_seen().unwrap(); - wait_for("alice's clock starts", 10, || find(&alice, &at).is_some_and(|m| m.expires.is_some())) - .await; - wait_for("it vanishes on both sides", 15, || { - find(&alice, &at).is_some_and(|m| m.vanished) && find(&bob, &at).is_some_and(|m| m.vanished) - }) - .await; - assert!(!texts(&bob).contains(&"the code is 1234".into())); - - // A picture: the message arrives, then the file, checked against its hash. + // A picture: the message arrives, then the file on a stream of its own. let bytes: Vec = (0..3_000_000u32).map(|i| (i * 7 % 251) as u8).collect(); let new = NewFile { name: "sunset.png".into(), @@ -259,10 +122,6 @@ async fn pair_chat_and_catch_up() { text: "look at this".into(), reply_to: None, }; - // Bob already has the first megabyte, as if a transfer had broken off: it resumes. - let hash = blake3::hash(&bytes).to_hex().to_string(); - std::fs::create_dir_all(dir_b.join("files")).unwrap(); - std::fs::write(dir_b.join("files").join(format!("{hash}.part")), &bytes[..1 << 20]).unwrap(); let (a, sent) = (alice.clone(), bytes.clone()); let photo = like_tauri(move || a.send_file(&sent, new)).unwrap(); let file = photo.file.clone().unwrap(); @@ -276,36 +135,6 @@ async fn pair_chat_and_catch_up() { assert_eq!(std::fs::read(&path).unwrap(), bytes); assert_eq!(path.file_name().unwrap(), "sunset.png"); assert_eq!(mime, "image/png"); - assert_eq!(find(&bob, &at).unwrap().text, "look at this"); - let state = |core: &Core| find(core, &at).and_then(|m| m.file).map(|f| f.state); - - // Bob moves the picture out of the data folder: his app gets it again from Alice. - let moved = dir_b.join("moved.png"); - std::fs::rename(&path, &moved).unwrap(); - assert!(bob.file(&file.info.hash).unwrap().is_none(), "noticed when it's next needed"); - wait_for("bob gets it again", 30, || state(&bob) == Some(FileState::Done)).await; - assert_eq!(std::fs::read(&path).unwrap(), bytes); - - // Alice edits her copy in place, keeping the size, and Bob loses his. Alice won't send - // the edited one as the original, so neither has it any more. - let (alice_path, _) = alice.file(&file.info.hash).unwrap().unwrap(); - let mut edited = bytes.clone(); - edited[0] ^= 1; - std::fs::write(&alice_path, &edited).unwrap(); - std::fs::remove_file(&path).unwrap(); - assert!(bob.file(&file.info.hash).unwrap().is_none()); - wait_for("both give up", 30, || { - state(&bob) == Some(FileState::Gone) && state(&alice) == Some(FileState::Gone) - }) - .await; - std::fs::rename(&moved, &path).unwrap(); // the deletes below still clean up - - // Deleting it removes the file on both sides. - alice.delete(at.clone()).unwrap(); - wait_for("bob sees the delete", 10, || find(&bob, &at).is_some_and(|m| m.deleted)).await; - assert!(alice.file(&file.info.hash).unwrap().is_none()); - assert!(bob.file(&file.info.hash).unwrap().is_none()); - assert!(!path.exists(), "the file itself is gone"); alice.shutdown().await; bob.shutdown().await;