rings_node/mail/gateway.rs
1//! The gateway's DHT side: whether a DID takes mail, and the write of one mail.
2//!
3//! ```text
4//! recipient(d) = μ(d).recipient() μ(d) = the newest descriptor on descriptor_topic(d)
5//! that is signed for d, binds its key, verifies
6//! and is live
7//! = ⊥ no such descriptor (RCPT: 451)
8//! deliver(d, m) = Extend(mail_topic(d), seal(m, ek(μ(d))), lifetime = MAX_TTL_MS),
9//! reported under StoreQuorum::Any:
10//! = Ok at the first owner's Stored report (DATA: 250)
11//! = Err once every owner refused, or no report within W (DATA: 451)
12//! W = MAIL_STORE_REPORT_WAIT
13//! ```
14//!
15//! A DID with no live descriptor is `451`, not `550`: a gateway that keeps nothing cannot tell
16//! a recipient that is away from one that never took mail, and the sender's retries reach one
17//! that comes back.
18//!
19//! The gateway keeps nothing: each RCPT is one fetch, each DATA one reported write. `deliver`
20//! returning `Ok` means an owner reported holding the mail (#866), so a recipient's fetch can
21//! reach it; the writer's own read-back would be its cache (#982), not an owner's statement. One
22//! owner is enough: waiting for every one would let one slow or refusing owner turn mail that
23//! is held into a retry. A `451` is not a loss: the sender retries, and a copy an owner did hold
24//! is a duplicate the recipient files once (by `Message-ID`).
25
26use std::convert::Infallible;
27use std::future::Future;
28use std::sync::Arc;
29use std::time::Duration;
30
31use async_trait::async_trait;
32use futures::future::select;
33use futures::future::Either;
34use futures::pin_mut;
35use rings_core::consts::MAX_TTL_MS;
36use rings_core::dht::entry::Entry;
37use rings_core::lifecycle::StopSource;
38use rings_core::swarm::storage_api::StoreQuorum;
39use rings_core::swarm::storage_api::StoreUnconfirmed;
40use rings_core::utils::SharedClock;
41use rings_core::utils::SharedRng;
42use rings_runtime::sleep;
43use rings_runtime::MaybeSendSync;
44use thiserror::Error;
45
46use super::descriptor::descriptor_topic;
47use super::descriptor::MailDescriptor;
48use super::descriptor::MailRecipient;
49use super::envelope::seal;
50use super::envelope::MailDigest;
51use super::envelope::SealError;
52use super::envelope::SealedMail;
53use super::mail_topic;
54use crate::descriptor::heard_descriptors;
55use crate::prelude::rings_core::dht::Did;
56use crate::processor::Processor;
57
58/// How long the write of one mail waits for its first owner's store report, the rerouting of
59/// its placements included: far above an overlay round trip, and well inside the ten minutes
60/// an SMTP client waits for the reply to its final dot (RFC 5321 §4.5.3.2.6), so the client
61/// reads a `451`, not its own timeout.
62pub const MAIL_STORE_REPORT_WAIT: Duration = Duration::from_secs(60);
63
64/// Why the gateway could not look a recipient up or write its mail.
65#[derive(Debug, Error)]
66pub enum MailGatewayError {
67 /// The DHT key of the recipient's descriptor topic cannot be derived.
68 #[error("no DHT key for {did}'s mail descriptor topic: {source}")]
69 Key {
70 /// The recipient.
71 did: Did,
72 /// Why.
73 source: rings_core::error::Error,
74 },
75 /// The fetch of the recipient's descriptor topic failed.
76 #[error("cannot fetch {did}'s mail descriptor: {source}")]
77 Fetch {
78 /// The recipient.
79 did: Did,
80 /// Why.
81 source: crate::error::Error,
82 },
83 /// The message could not be sealed; [`SealError::TooLarge`] is the SMTP `552`.
84 #[error(transparent)]
85 Seal(#[from] SealError),
86 /// The write of the sealed mail failed: a placement could not leave this node, as
87 /// `ChordStorageInterface` states, or its rerouting outlived [`MAIL_STORE_REPORT_WAIT`].
88 #[error("cannot write {did}'s mail: {source}")]
89 Write {
90 /// The recipient.
91 did: Did,
92 /// Why.
93 source: crate::error::Error,
94 },
95 /// No owner stored the mail: every one refused it, or this node could not await their
96 /// reports.
97 #[error("no owner stored {did}'s mail: {cause:?}")]
98 Unstored {
99 /// The recipient.
100 did: Did,
101 /// Why the receipt resolved unstored.
102 cause: StoreUnconfirmed,
103 },
104 /// No owner reported the mail within [`MAIL_STORE_REPORT_WAIT`].
105 #[error("no owner reported {did}'s mail in time")]
106 Unreported {
107 /// The recipient.
108 did: Did,
109 },
110}
111
112/// The gateway's DHT side as its SMTP front sees it: the RCPT lookup and the DATA write. The
113/// node's is [`MailGateway`]; a front's tests stand in another.
114#[cfg_attr(rings_browser, async_trait(?Send))]
115#[cfg_attr(rings_native, async_trait)]
116pub trait MailDrop: MaybeSendSync {
117 /// Where mail to `did` goes and the key it is sealed to, if `did` has a live mail
118 /// descriptor: the RCPT rule, which looks it up once per RCPT.
119 async fn recipient(&self, did: Did) -> Result<Option<MailRecipient>, MailGatewayError>;
120
121 /// Seal `message` for `recipient`, write it to the recipient's mail topic as one delta that
122 /// lives [`MAX_TTL_MS`], and await an owner's report that it holds it: the DATA rule.
123 /// Returns the mail's id.
124 async fn deliver(
125 &self,
126 recipient: &MailRecipient,
127 message: &[u8],
128 ) -> Result<MailDigest, MailGatewayError>;
129}
130
131/// The gateway over a node's DHT, signing manifests with the node's authority.
132pub struct MailGateway {
133 processor: Arc<Processor>,
134 clock: SharedClock,
135 rng: SharedRng,
136}
137
138impl MailGateway {
139 /// The gateway writing through `processor`, inheriting its clock and RNG capabilities.
140 pub fn new(processor: Arc<Processor>) -> Self {
141 let clock = processor.clock().clone();
142 let rng = processor.rng().clone();
143 Self {
144 processor,
145 clock,
146 rng,
147 }
148 }
149
150 /// Construct a gateway over `processor` with explicit `clock` and `rng` capabilities for
151 /// deterministic seal and descriptor-liveness replay.
152 pub fn new_with_capabilities(
153 processor: Arc<Processor>,
154 clock: SharedClock,
155 rng: SharedRng,
156 ) -> Self {
157 Self {
158 processor,
159 clock,
160 rng,
161 }
162 }
163}
164
165#[cfg_attr(rings_browser, async_trait(?Send))]
166#[cfg_attr(rings_native, async_trait)]
167impl MailDrop for MailGateway {
168 async fn recipient(&self, did: Did) -> Result<Option<MailRecipient>, MailGatewayError> {
169 let key = Entry::gen_did(&descriptor_topic(did))
170 .map_err(|source| MailGatewayError::Key { did, source })?;
171 let entry = self
172 .processor
173 .fetch_storage_entry(key)
174 .await
175 .map_err(|source| MailGatewayError::Fetch { did, source })?;
176 let now_ms = self.clock.now_ms();
177 let network_id = self.processor.swarm.network_id();
178 Ok(entry.and_then(|entry| {
179 MailDescriptor::live_recipient(heard_descriptors(&entry), did, now_ms, network_id)
180 }))
181 }
182
183 async fn deliver(
184 &self,
185 recipient: &MailRecipient,
186 message: &[u8],
187 ) -> Result<MailDigest, MailGatewayError> {
188 let SealedMail { mail_id, elements } = seal(message, recipient, &mut self.rng.lock_rng())?;
189 let did = recipient.did;
190 let deadline = StopSource::new();
191 let stop = deadline.token();
192 let stored = async {
193 let receipt = self
194 .processor
195 .storage_extend_reported(
196 &mail_topic(did),
197 elements,
198 MAX_TTL_MS,
199 StoreQuorum::Any,
200 &stop,
201 )
202 .await
203 .map_err(|source| MailGatewayError::Write { did, source })?;
204 confirmed(did, receipt, stop.stopped()).await
205 };
206 stopping_after(MAIL_STORE_REPORT_WAIT, &deadline, stored).await?;
207 Ok(mail_id)
208 }
209}
210
211/// The verdict on a mail written to `did`'s topic: stored once its `receipt` resolves stored,
212/// unstored once it resolves otherwise, unreported once `elapsed` resolves first. The receipt
213/// is polled first, so a report that arrives as the wait ends still counts.
214pub(crate) async fn confirmed(
215 did: Did,
216 receipt: impl Future<Output = Result<(), StoreUnconfirmed>>,
217 elapsed: impl Future<Output = ()>,
218) -> Result<(), MailGatewayError> {
219 pin_mut!(receipt, elapsed);
220 match select(receipt, elapsed).await {
221 Either::Left((Ok(()), _)) => Ok(()),
222 Either::Left((Err(cause), _)) => Err(MailGatewayError::Unstored { did, cause }),
223 Either::Right(((), _)) => Err(MailGatewayError::Unreported { did }),
224 }
225}
226
227/// Drive `write` to its end, requesting `deadline`'s stop once `wait` has elapsed. `write` ends
228/// at the stop cooperatively, never dropped midway: its storage operations run to completion
229/// (`ScopedStorage`), and only its waits observe the stop. A timer that cannot be scheduled
230/// stops it at once.
231pub(super) async fn stopping_after<F: Future>(
232 wait: Duration,
233 deadline: &StopSource,
234 write: F,
235) -> F::Output {
236 let timer = async {
237 if let Err(error) = sleep(wait).await {
238 tracing::debug!(
239 ?error,
240 "no timer for a mail's store report wait; stopping now"
241 );
242 }
243 deadline.request_stop();
244 std::future::pending::<Infallible>().await
245 };
246 pin_mut!(write, timer);
247 match select(write, timer).await {
248 Either::Left((output, _)) => output,
249 Either::Right((never, _)) => match never {},
250 }
251}