1use 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
16pub enum Connector {
17 #[default]
19 Public,
20 Relay(String),
22 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#[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#[derive(Clone, Debug)]
91pub struct Letter {
92 pub id: String,
94 pub from: String,
96 pub to: Address,
97 pub body: String,
98 pub wake: bool,
100 pub reply_to: Option<String>,
101 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 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#[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 pub access: Access,
165}
166
167impl Envelope {
168 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 pub online: bool,
183 pub agents: Vec<Agent>,
184}
185
186#[derive(Clone, Copy, Debug, PartialEq, Eq)]
187pub enum Sent {
188 Delivered,
190 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}