1use 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub enum Connector {
16 #[default]
18 Public,
19 Relay(String),
21 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#[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#[derive(Clone, Debug)]
90pub struct Letter {
91 pub id: String,
93 pub from: String,
95 pub to: Address,
96 pub body: String,
97 pub wake: bool,
99 pub reply_to: Option<String>,
100 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 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#[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 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 pub online: bool,
179 pub agents: Vec<Agent>,
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub enum Sent {
184 Delivered,
186 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}