Skip to main content

codync_network/node/
mod.rs

1//! One computer on the network: its iroh endpoint, its roster and the agents it offers.
2
3mod conns;
4mod directory;
5mod endpoint;
6mod hello;
7mod inbound;
8mod outbox;
9
10use crate::guard::{self, Guard};
11use crate::reach::{Held, Reach};
12use crate::roster::{self, Change, Role, Roster};
13use crate::rules::{self, Rule};
14use crate::types::{Address, Connector, Letter, Message, Peer, Sent};
15use crate::wire::{self, ALPN, Agent, Request, Response, Ticket};
16use anyhow::{Context, Result, anyhow, bail};
17use iroh::endpoint::Connection;
18use iroh::protocol::Router;
19use iroh::{Endpoint, EndpointId};
20use std::collections::{HashMap, VecDeque};
21use std::path::{Path, PathBuf};
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::{Arc, Mutex, MutexGuard};
24use std::time::{Duration, Instant};
25use tokio::sync::{mpsc, watch};
26
27/// How long an invite stays good.
28pub const INVITE_FOR: Duration = Duration::from_hours(1);
29const INBOX_SIZE: usize = 256;
30/// Letters whose handoff count a reply may need, and requests an answer may come back to, newest kept.
31const HEARD_MAX: usize = 1000;
32
33pub struct Node {
34    inner: Arc<Inner>,
35    router: Router,
36}
37
38struct Inner {
39    endpoint: Endpoint,
40    dir: PathBuf,
41    roster: Mutex<Option<Roster>>,
42    agents: Mutex<Vec<(Agent, Reach)>>,
43    /// Names the app also sends as without offering them (`set_senders`).
44    senders: Mutex<Vec<String>>,
45    /// The app offered its agents since the node started: until then, letters wait at the sender.
46    ready: AtomicBool,
47    /// The handoff count of letters taken here, by id, so a reply carries the chain on.
48    heard: Mutex<VecDeque<(String, u8)>>,
49    /// What each other computer offered when it last answered or wrote.
50    seen: Mutex<HashMap<EndpointId, directory::Seen>>,
51    invites: Mutex<HashMap<String, Instant>>,
52    guard: Mutex<Guard>,
53    held: Mutex<Held>,
54    /// Letters already taken, so a sender's retry isn't delivered twice.
55    taken: Mutex<VecDeque<String>>,
56    /// Who may write to this computer's agents (`rules`).
57    rules: Mutex<Vec<Rule>>,
58    /// Requests this computer sent, newest kept: the letter's id, the computer it went to and
59    /// the agent here that sent it. That computer's answer to that agent passes the rules.
60    asked: Mutex<VecDeque<(String, EndpointId, String)>>,
61    outbox: Mutex<Vec<outbox::Queued>>,
62    inbox: mpsc::Sender<Message>,
63    /// The open connection to each other computer, whichever side opened it ([`conns`]).
64    conns: Mutex<HashMap<EndpointId, Connection>>,
65    /// One connection attempt at a time per computer.
66    dialing: Mutex<HashMap<EndpointId, Arc<tokio::sync::Mutex<()>>>>,
67    /// The command an agent the network knocks on runs to answer.
68    reply_command: Mutex<String>,
69    /// What the app calls this network; invites carry it (`set_network_name`).
70    network_name: Mutex<Option<String>>,
71    /// Ticks when the members, their roles or names, or what the others offer or whether they
72    /// answer, change.
73    changed: watch::Sender<()>,
74}
75
76fn locked<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
77    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
78}
79
80impl Node {
81    /// Starts this computer's node. State (its key and the roster) lives in `dir`. Messages for
82    /// agents the app delivers to ([`Reach::App`]) come out of the returned inbox.
83    pub async fn start(dir: &Path, connector: &Connector) -> Result<(Self, mpsc::Receiver<Message>)> {
84        std::fs::create_dir_all(dir)?;
85        let key = endpoint::load_key(dir)?;
86        let endpoint = endpoint::bind(dir, key, connector).await?;
87        let (tx, rx) = mpsc::channel(INBOX_SIZE);
88        let inner = Arc::new(Inner {
89            endpoint: endpoint.clone(),
90            dir: dir.to_path_buf(),
91            roster: Mutex::new(Roster::load(dir)?),
92            agents: Mutex::default(),
93            senders: Mutex::default(),
94            ready: AtomicBool::new(false),
95            heard: Mutex::default(),
96            seen: Mutex::default(),
97            invites: Mutex::default(),
98            guard: Mutex::default(),
99            held: Mutex::default(),
100            taken: Mutex::default(),
101            rules: Mutex::default(),
102            asked: Mutex::default(),
103            outbox: Mutex::default(),
104            inbox: tx,
105            conns: Mutex::default(),
106            dialing: Mutex::default(),
107            reply_command: Mutex::new("codync-network".into()),
108            network_name: Mutex::default(),
109            changed: watch::Sender::new(()),
110        });
111        let router = Router::builder(endpoint).accept(ALPN, inbound::Handler(inner.clone())).spawn();
112        endpoint::settle(&inner.endpoint, connector).await;
113        inner.locate(inner.endpoint.addr())?;
114        tokio::spawn(outbox::retry_loop(Arc::downgrade(&inner)));
115        tokio::spawn(endpoint::follow_addr(Arc::downgrade(&inner), inner.endpoint.watch_addr()));
116        Ok((Self { inner, router }, rx))
117    }
118
119    pub fn id(&self) -> EndpointId {
120        self.inner.endpoint.id()
121    }
122
123    /// This computer's name, once it is in a network.
124    pub fn name(&self) -> Option<String> {
125        locked(&self.inner.roster).as_ref().map(|r| r.name(&self.id()))
126    }
127
128    /// The network's id (its root key), once this computer is in one.
129    pub fn network_id(&self) -> Option<String> {
130        locked(&self.inner.roster).as_ref().map(|r| r.network.to_string())
131    }
132
133    pub fn role(&self) -> Option<Role> {
134        locked(&self.inner.roster).as_ref().and_then(|r| r.role(&self.id()))
135    }
136
137    /// Starts a new network with this computer as its owner. Returns the recovery code: show it
138    /// once; it is kept nowhere.
139    pub fn create(&self, name: &str) -> Result<String> {
140        let mut roster = locked(&self.inner.roster);
141        if roster.is_some() {
142            bail!("this computer is already in a network");
143        }
144        let key = self.inner.endpoint.secret_key();
145        let (new, root) = Roster::create(key, check_name(name)?, self.inner.endpoint.addr(), wire::now_ms());
146        self.inner.save(&new)?;
147        *roster = Some(new);
148        Ok(roster::recovery_code(&root))
149    }
150
151    /// A one-time invite for another computer, good for an hour while this one stays on.
152    pub fn invite(&self) -> Result<String> {
153        let roster = self.inner.roster()?;
154        if !roster.role(&self.id()).is_some_and(Role::invites) {
155            bail!("only the owner and admins can invite computers");
156        }
157        let secret = wire::random_hex(16);
158        locked(&self.inner.invites).insert(secret.clone(), Instant::now() + INVITE_FOR);
159        let name = locked(&self.inner.network_name).clone();
160        Ticket { network: roster.network, secret, addr: self.inner.endpoint.addr(), name }.encode()
161    }
162
163    pub async fn join(&self, ticket: &str, name: &str) -> Result<()> {
164        if locked(&self.inner.roster).is_some() {
165            bail!("this computer is already in a network");
166        }
167        let ticket = Ticket::decode(ticket)?;
168        let request = Request::Join { network: ticket.network, secret: ticket.secret, name: check_name(name)? };
169        let conn = conns::dial(&self.inner.endpoint, ticket.addr)
170            .await
171            .context("the inviting computer didn't answer; is it on?")?;
172        let answer = conns::ask(&conn, &request).await;
173        conn.close(0u32.into(), b"done");
174        match answer? {
175            Response::Welcome { roster } if roster.network == ticket.network => {
176                let mut roster = roster.verified();
177                if !roster.is_member(&self.id()) {
178                    bail!("the inviting computer gave an unexpected answer");
179                }
180                // Where this computer is; nothing to add when it knows no address yet.
181                let addr = self.inner.endpoint.addr();
182                let _ = roster.sign(
183                    self.inner.endpoint.secret_key(),
184                    wire::now_ms(),
185                    Change::Locate { addr: roster::bounded_addr(addr) },
186                );
187                // Held across saving and keeping it, so whoever `changes` wakes sees it.
188                let mut guard = locked(&self.inner.roster);
189                self.inner.save(&roster)?;
190                *guard = Some(roster);
191                drop(guard);
192                // Before the app offers its agents, a hello would tell the others it offers none
193                // (and could land after the one that does): the first `set_agents` says it.
194                if self.inner.ready.load(Ordering::Acquire) {
195                    self.inner.clone().hello_all();
196                }
197                Ok(())
198            }
199            Response::Refused { reason } => bail!("{reason}"),
200            _ => bail!("the inviting computer gave an unexpected answer"),
201        }
202    }
203
204    /// Takes a computer out of the network for good. `cascade` also voids every computer it
205    /// admitted: for one that was stolen.
206    pub fn remove(&self, computer: &str, cascade: bool) -> Result<()> {
207        let id = self.inner.member(computer)?;
208        if id == self.id() {
209            bail!("a computer can't remove itself; remove it from another one");
210        }
211        self.inner.change(Change::Remove { id, cascade }, "only the owner removes admins; admins remove members")
212    }
213
214    /// The owner makes a computer an admin: it can invite and remove members.
215    pub fn promote(&self, computer: &str) -> Result<()> {
216        let id = self.inner.member(computer)?;
217        self.inner.change(Change::Promote { id }, "only the owner promotes computers")
218    }
219
220    /// Makes this computer the owner with the network's recovery code, for when the owner was
221    /// lost. Remove the old one afterwards.
222    pub fn recover(&self, code: &str) -> Result<()> {
223        let root = roster::root_from_code(code)?;
224        let mut guard = locked(&self.inner.roster);
225        let roster = guard.as_mut().ok_or_else(|| anyhow!("this computer isn't in a network"))?;
226        if root.public() != roster.network {
227            bail!("that recovery code is for another network");
228        }
229        let name = roster.name(&self.id());
230        roster.sign(&root, wire::now_ms(), Change::Owner { id: self.id(), name })?;
231        self.inner.save(roster)?;
232        drop(guard);
233        self.inner.clone().hello_all();
234        Ok(())
235    }
236
237    /// What this computer offers. The first call opens it to letters, and the others hear at once
238    /// (the hello that catches up with them, which a computer that was off may need for a removal it
239    /// missed), so what waited for it while it started comes now.
240    pub fn set_agents(&self, agents: impl IntoIterator<Item = (Agent, Reach)>) {
241        let before = self.inner.offered();
242        // A session the network knocks on is the kind its harness is, whatever the app said.
243        let agents = agents.into_iter().map(|(mut agent, reach)| {
244            if let Some(kind) = reach.kind() {
245                agent.kind = kind;
246            }
247            (agent, reach)
248        });
249        *locked(&self.inner.agents) = agents.collect();
250        if self.inner.offered() != before {
251            self.inner.changed.send_replace(());
252        }
253        if !self.inner.ready.swap(true, Ordering::AcqRel) {
254            self.inner.clone().hello_all();
255        }
256    }
257
258    /// Names the app sends letters as without offering them to the network: a hosted assistant that
259    /// asks agents elsewhere but can't be asked itself. Answers to its letters still come back.
260    pub fn set_senders(&self, senders: impl IntoIterator<Item = String>) {
261        *locked(&self.inner.senders) = senders.into_iter().collect();
262    }
263
264    /// Who on the other computers may write to this computer's agents, the first match deciding.
265    /// Answers to this computer's own letters always pass, so a rule added while a request runs
266    /// doesn't strand it.
267    pub fn set_rules(&self, rules: Vec<Rule>) -> Result<()> {
268        rules::check_all(&rules)?;
269        *locked(&self.inner.rules) = rules;
270        Ok(())
271    }
272
273    pub fn rules(&self) -> Vec<Rule> {
274        locked(&self.inner.rules).clone()
275    }
276
277    /// What the app calls this network (`home`, `work`) when a computer is in several: the invites
278    /// it makes carry the name, so the computer that joins can call it the same ([`crate::read_invite`]).
279    pub fn set_network_name(&self, name: Option<String>) {
280        *locked(&self.inner.network_name) = name;
281    }
282
283    /// The command agents the network knocks on run to reply (default `codync-network`).
284    pub fn set_reply_command(&self, command: impl Into<String>) {
285        *locked(&self.inner.reply_command) = command.into();
286    }
287
288    /// Every computer in the network, asked now for what it offers.
289    pub async fn peers(&self) -> Result<Vec<Peer>> {
290        self.inner.roster()?;
291        self.inner.hello_each(self.inner.others()).await;
292        Ok(self.directory())
293    }
294
295    /// Every computer in the network, as last heard, without asking anyone.
296    pub fn directory(&self) -> Vec<Peer> {
297        self.inner.directory()
298    }
299
300    /// Changes whenever what [`Node::directory`] shows does: a computer joins or leaves, a role
301    /// or name changes, another computer offers different agents, or it starts or stops
302    /// answering. Ticks only; read the directory for what changed.
303    pub fn changes(&self) -> watch::Receiver<()> {
304        self.inner.changed.subscribe()
305    }
306
307    /// Where a bare agent name or a full `agent@computer` points: this computer first, then the
308    /// directory. Refuses a name more than one computer has, naming them.
309    pub fn resolve(&self, name: &str) -> Result<Address> {
310        self.inner.resolve(name)
311    }
312
313    /// Sends a letter from one of the agents this computer offers. An answer (`reply_to`) may also
314    /// come from one it no longer offers: renamed or gone while it worked, it still says how it ended.
315    pub async fn send(&self, letter: Letter) -> Result<Sent> {
316        let sender = |from: &str| {
317            self.inner.offered().iter().any(|a| a.id == from) || locked(&self.inner.senders).iter().any(|s| s == from)
318        };
319        if letter.reply_to.is_none() && !sender(&letter.from) {
320            bail!("{} isn't one of this computer's agents", letter.from);
321        }
322        // A reply carries on the chain of the letter it answers (one more handoff).
323        let mut letter = letter;
324        if letter.hops == 0
325            && let Some(hops) = letter.reply_to.as_deref().and_then(|id| self.inner.hops_of(id))
326        {
327            letter.hops = hops.saturating_add(1);
328        }
329        guard::check_hops(letter.hops).map_err(anyhow::Error::msg)?;
330        let roster = locked(&self.inner.roster).clone();
331        let id = match &roster {
332            None => self.id(),
333            Some(r) => {
334                r.find(&letter.to.computer).ok_or_else(|| anyhow!("no computer called {}", letter.to.computer))?
335            }
336        };
337        let local = id == self.id();
338        let envelope = letter.seal(wire::now_ms());
339        wire::check(&envelope)?;
340        // A request, which an answer may come back to past the other computer's rules.
341        if !local && envelope.wake && envelope.reply_to.is_none() {
342            remember(&mut locked(&self.inner.asked), (envelope.id.clone(), id, envelope.from.clone()), HEARD_MAX);
343        }
344        let name = |id: &EndpointId| roster.as_ref().map_or_else(|| "this computer".into(), |r| r.name(id));
345        let answer = if local {
346            Ok(self.inner.take(id, envelope.clone()).await)
347        } else {
348            self.inner.call(id, &Request::Deliver { envelope: envelope.clone() }).await
349        };
350        match answer {
351            Ok(Response::Stored) => Ok(Sent::Delivered),
352            Ok(Response::Refused { reason }) => bail!("{} refused it: {reason}", name(&id)),
353            Ok(Response::Later { reason }) if local => bail!("{reason}"),
354            Ok(Response::Later { reason }) => {
355                tracing::info!(to = %name(&id), reason, "queued for a computer that is starting");
356                self.inner.queue(id, envelope)?;
357                Ok(Sent::Queued)
358            }
359            Ok(_) => bail!("{} gave an unexpected answer", name(&id)),
360            Err(e) => {
361                tracing::info!(to = %name(&id), error = format!("{e:#}"), "queued for a computer that is away");
362                self.inner.queue(id, envelope)?;
363                Ok(Sent::Queued)
364            }
365        }
366    }
367
368    /// Stops answering and closes the endpoint (leaving a network, or quitting).
369    pub async fn shutdown(&self) {
370        let _ = self.router.shutdown().await;
371    }
372}
373
374impl Inner {
375    fn roster(&self) -> Result<Roster> {
376        locked(&self.roster).clone().ok_or_else(|| anyhow!("this computer isn't in a network yet"))
377    }
378
379    fn me(&self) -> EndpointId {
380        self.endpoint.id()
381    }
382
383    /// Whether a letter from `peer` answers a request this computer sent there, from the agent
384    /// the letter is for.
385    pub(super) fn answers(&self, peer: EndpointId, envelope: &wire::Envelope) -> bool {
386        let Some(id) = envelope.reply_to.as_deref() else { return false };
387        locked(&self.asked).iter().any(|(sent, to, by)| sent == id && *to == peer && *by == envelope.to)
388    }
389
390    fn hops_of(&self, letter: &str) -> Option<u8> {
391        locked(&self.heard).iter().rev().find(|(id, _)| id == letter).map(|(_, hops)| *hops)
392    }
393
394    fn heard(&self, letter: &str, hops: u8) {
395        remember(&mut locked(&self.heard), (letter.to_owned(), hops), HEARD_MAX);
396    }
397
398    fn offered(&self) -> Vec<Agent> {
399        locked(&self.agents).iter().map(|(agent, _)| agent.clone()).collect()
400    }
401
402    fn member(&self, computer: &str) -> Result<EndpointId> {
403        self.roster()?.find(computer).ok_or_else(|| anyhow!("no computer called {computer}"))
404    }
405
406    /// Signs `change` as this computer, saves it and tells the others.
407    fn change(self: &Arc<Self>, change: Change, refused: &str) -> Result<()> {
408        let mut guard = locked(&self.roster);
409        let roster = guard.as_mut().ok_or_else(|| anyhow!("this computer isn't in a network"))?;
410        roster.sign(self.endpoint.secret_key(), wire::now_ms(), change).map_err(|_| anyhow!("{refused}"))?;
411        self.save(roster)?;
412        drop(guard);
413        self.clone().hello_all();
414        Ok(())
415    }
416
417    /// Keeps `roster` on disk and tells whoever watches [`Node::changes`]. Callers hold the roster
418    /// lock until `roster` is the one kept in memory, so a watcher woken here reads it.
419    fn save(&self, roster: &Roster) -> Result<()> {
420        roster.save(&self.dir)?;
421        self.close_outsiders(roster);
422        self.changed.send_replace(());
423        Ok(())
424    }
425}
426
427fn check_name(name: &str) -> Result<String> {
428    let name = name.trim();
429    if name.is_empty() || name.len() > 40 || name.contains(roster::NOT_IN_NAMES) {
430        bail!("a computer's name is 1–40 characters, without spaces, /, @ or .");
431    }
432    Ok(name.into())
433}
434
435/// Keeps `item` in a list of the newest `max`.
436fn remember<T>(list: &mut VecDeque<T>, item: T, max: usize) {
437    if list.len() >= max {
438        list.pop_front();
439    }
440    list.push_back(item);
441}
442
443#[cfg(test)]
444mod testing {
445    use crate::reach::Reach;
446    use crate::wire::{Agent, AgentKind};
447    use std::time::Duration;
448
449    /// An agent the app takes letters for.
450    pub(super) fn agent(id: &str) -> (Agent, Reach) {
451        (Agent { id: id.into(), name: id.into(), about: String::new(), kind: AgentKind::Codync }, Reach::App)
452    }
453
454    /// Waits up to 10 s until `done`.
455    pub(super) async fn until(what: &str, done: impl Fn() -> bool) {
456        tokio::time::timeout(Duration::from_secs(10), async {
457            while !done() {
458                tokio::time::sleep(Duration::from_millis(50)).await;
459            }
460        })
461        .await
462        .unwrap_or_else(|_| panic!("timed out waiting until {what}"));
463    }
464}