Skip to main content

codync_network/
types.rs

1//! The values an app hands the network and gets back from it.
2
3use crate::roster::Role;
4use crate::wire::{self, Agent, Envelope};
5use anyhow::{Result, anyhow, bail};
6use iroh::EndpointId;
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8use serde_json::Value;
9use std::fmt;
10use std::str::FromStr;
11
12/// How computers reach each other when they can't connect directly. Written as `public`,
13/// `private` or the relay's URL, also in JSON.
14#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub enum Connector {
16    /// iroh's public relays and address lookup. Free, rate-limited, meant for trying things out.
17    #[default]
18    Public,
19    /// Your own `iroh-relay`, and nothing of anyone else's.
20    Relay(String),
21    /// No relay at all: only computers reachable directly (same network, Tailscale, VPN).
22    Private,
23}
24
25impl FromStr for Connector {
26    type Err = anyhow::Error;
27
28    fn from_str(s: &str) -> Result<Self> {
29        match s {
30            "public" => Ok(Self::Public),
31            "private" => Ok(Self::Private),
32            url if url.starts_with("https://") || url.starts_with("http://") => Ok(Self::Relay(url.into())),
33            _ => bail!("connector is public, private or a relay URL"),
34        }
35    }
36}
37
38impl fmt::Display for Connector {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::Public => f.write_str("public"),
42            Self::Private => f.write_str("private"),
43            Self::Relay(url) => f.write_str(url),
44        }
45    }
46}
47
48impl Serialize for Connector {
49    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
50        s.collect_str(self)
51    }
52}
53
54impl<'de> Deserialize<'de> for Connector {
55    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
56        String::deserialize(d)?.parse().map_err(serde::de::Error::custom)
57    }
58}
59
60/// `agent@computer`, like ssh's `user@host`. A bare `agent` is looked up with
61/// [`Node::resolve`](crate::Node::resolve).
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct Address {
64    pub agent: String,
65    pub computer: String,
66}
67
68impl FromStr for Address {
69    type Err = anyhow::Error;
70
71    fn from_str(s: &str) -> Result<Self> {
72        let (agent, computer) = s.trim().rsplit_once('@').ok_or_else(|| anyhow!("an address is agent@computer"))?;
73        if agent.is_empty() || computer.is_empty() {
74            bail!("an address is agent@computer");
75        }
76        Ok(Self { agent: agent.into(), computer: computer.into() })
77    }
78}
79
80impl fmt::Display for Address {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        write!(f, "{}@{}", self.agent, self.computer)
83    }
84}
85
86/// A message on its way out. Ways of working together (requests and replies, rooms, task
87/// boards…) are built on letters: `reply_to` links them, `meta` carries the app's own structure,
88/// and the network never reads either.
89#[derive(Clone, Debug)]
90pub struct Letter {
91    /// Made here, so the sender knows it before the letter goes (a reply names it in `reply_to`).
92    pub id: String,
93    /// The sending agent: one of this computer's.
94    pub from: String,
95    pub to: Address,
96    pub body: String,
97    /// `false` makes it a notice: it waits for the agent's next turn instead of starting one.
98    pub wake: bool,
99    pub reply_to: Option<String>,
100    /// Handoffs so far in this chain; 0 when a person started it.
101    pub hops: u8,
102    pub meta: Option<Value>,
103}
104
105impl Letter {
106    pub fn new(from: impl Into<String>, to: Address, body: impl Into<String>) -> Self {
107        Self {
108            id: wire::random_hex(12),
109            from: from.into(),
110            to,
111            body: body.into(),
112            wake: true,
113            reply_to: None,
114            hops: 0,
115            meta: None,
116        }
117    }
118
119    #[must_use]
120    pub fn notice(mut self) -> Self {
121        self.wake = false;
122        self
123    }
124
125    #[must_use]
126    pub fn reply_to(mut self, id: impl Into<String>) -> Self {
127        self.reply_to = Some(id.into());
128        self
129    }
130
131    #[must_use]
132    pub fn hops(mut self, hops: u8) -> Self {
133        self.hops = hops;
134        self
135    }
136
137    #[must_use]
138    pub fn meta(mut self, meta: Value) -> Self {
139        self.meta = Some(meta);
140        self
141    }
142
143    /// The letter as it goes on the wire: the receiving computer knows the sender by its key.
144    pub(crate) fn seal(self, sent_at: u64) -> Envelope {
145        let Self { id, from, to, body, wake, reply_to, hops, meta } = self;
146        Envelope { id, from, to: to.agent, body, wake, reply_to, hops, meta, sent_at }
147    }
148}
149
150/// A message that reached one of this computer's agents.
151#[derive(Clone, Debug)]
152pub struct Message {
153    pub id: String,
154    pub from: Address,
155    pub to: String,
156    pub body: String,
157    pub wake: bool,
158    pub reply_to: Option<String>,
159    pub hops: u8,
160    pub meta: Option<Value>,
161}
162
163impl Envelope {
164    /// The letter as the agent gets it, from the computer that sent it.
165    pub(crate) fn open(self, computer: String) -> Message {
166        let Self { id, from, to, body, wake, reply_to, hops, meta, sent_at: _ } = self;
167        Message { id, from: Address { agent: from, computer }, to, body, wake, reply_to, hops, meta }
168    }
169}
170
171#[derive(Clone, Debug)]
172pub struct Peer {
173    pub id: EndpointId,
174    pub name: String,
175    pub role: Role,
176    pub me: bool,
177    /// It answered the last time this computer asked (or wrote).
178    pub online: bool,
179    pub agents: Vec<Agent>,
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub enum Sent {
184    /// It reached the agent: the app took it, or the agent's own harness did.
185    Delivered,
186    /// The computer is away; it gets the letter when it's back (within a day).
187    Queued,
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use serde_json::json;
194
195    #[test]
196    fn connectors_read_and_write_as_text() {
197        for text in ["public", "private", "https://relay.example"] {
198            let connector: Connector = serde_json::from_value(json!(text)).unwrap();
199            assert_eq!(serde_json::to_value(&connector).unwrap(), text);
200        }
201        assert!(serde_json::from_value::<Connector>(json!("ftp://relay.example")).is_err());
202    }
203}