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