1use std::collections::BTreeMap;
38use std::sync::Arc;
39use std::time::Duration;
40
41use async_trait::async_trait;
42use futures::lock::Mutex;
43use rings_core::consts::MAX_TTL_MS;
44use rings_core::consts::TS_OFFSET_TOLERANCE_MS;
45use rings_core::dht::entry::Entry;
46use rings_core::ecc::PublicKey;
47use rings_core::lifecycle::StopToken;
48use rings_core::storage::KvStorageInterface;
49use rings_core::utils::SharedClock;
50use rings_core::utils::SystemClock;
51use rings_runtime::MaybeSendSync;
52use serde::Deserialize;
53use serde::Serialize;
54use thiserror::Error;
55
56use super::envelope::MailDigest;
57use super::mail_topic;
58use super::open::open_mail_with_keys;
59use super::open::OpenedMail;
60use super::open::Opening;
61use super::write_lowercase_hex;
62use crate::processor::sleep_unless_stopped;
63use crate::processor::Processor;
64
65pub const DEFAULT_MAIL_POLL_INTERVAL: Duration = Duration::from_secs(60);
67pub const DEFAULT_MAIL_POLL_TIMEOUT: Duration = Duration::from_secs(30);
69pub const MAX_MAIL_POLL_INTERVAL: Duration = Duration::from_millis(MAX_TTL_MS / 2);
71pub const OPENED_RETENTION_MS: u128 = MAX_TTL_MS as u128 + TS_OFFSET_TOLERANCE_MS;
74pub const MESSAGE_ID_RETENTION_MS: u128 = 5 * 24 * 3600 * 1000;
77
78#[cfg_attr(rings_browser, async_trait(?Send))]
81#[cfg_attr(rings_native, async_trait)]
82pub trait MailInbox: MaybeSendSync {
83 type Error: std::error::Error + MaybeSendSync;
85
86 async fn file(&self, mail: &OpenedMail) -> Result<(), Self::Error>;
88}
89
90#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
92pub struct StoredMail {
93 pub message: Vec<u8>,
95 pub filed_at_ms: u128,
97}
98
99pub struct KvInbox<K> {
101 store: K,
102 clock: SharedClock,
103}
104
105impl<K> KvInbox<K> {
106 pub fn new(store: K) -> Self {
108 Self::new_with_clock(store, Arc::new(SystemClock))
109 }
110
111 pub fn new_with_clock(store: K, clock: SharedClock) -> Self {
113 Self { store, clock }
114 }
115
116 pub fn store(&self) -> &K {
118 &self.store
119 }
120}
121
122#[cfg_attr(rings_browser, async_trait(?Send))]
123#[cfg_attr(rings_native, async_trait)]
124impl<K> MailInbox for KvInbox<K>
125where K: KvStorageInterface<StoredMail> + MaybeSendSync
126{
127 type Error = rings_core::error::Error;
128
129 async fn file(&self, mail: &OpenedMail) -> Result<(), Self::Error> {
130 let stored = StoredMail {
131 message: mail.message.clone(),
132 filed_at_ms: self.clock.now_ms(),
133 };
134 self.store
135 .put(&format!("mail-{}", mail.mail_id), &stored)
136 .await
137 }
138}
139
140#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
142pub enum RecipientRecord {
143 Opened {
146 at_ms: u128,
148 },
149 Filed {
151 at_ms: u128,
153 },
154}
155
156impl RecipientRecord {
157 pub fn outlived_at(&self, now_ms: u128) -> bool {
159 let (since, retention) = match self {
160 Self::Opened { at_ms } => (*at_ms, OPENED_RETENTION_MS),
161 Self::Filed { at_ms } => (*at_ms, MESSAGE_ID_RETENTION_MS),
162 };
163 now_ms >= since.saturating_add(retention)
164 }
165}
166
167fn opened_record_name(delegatee_public_key: PublicKey<33>, mail_id: MailDigest) -> String {
173 let mut name = String::with_capacity(7 + 66 + 1 + 64);
174 name.push_str("opened-");
175 let _ = write_lowercase_hex(&mut name, &delegatee_public_key.0);
176 name.push('-');
177 let _ = std::fmt::Write::write_fmt(&mut name, format_args!("{mail_id}"));
178 name
179}
180
181fn filed_record_name(key: MailDigest) -> String {
183 format!("filed-{key}")
184}
185
186fn dedup_key(mail: &OpenedMail) -> MailDigest {
188 mail.message_id().map_or(mail.mail_id, |message_id| {
189 MailDigest::of(message_id.as_bytes())
190 })
191}
192
193#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
195pub struct PollReport {
196 pub filed: usize,
198 pub duplicates: usize,
200 pub unreadable: usize,
202 pub incomplete: usize,
204}
205
206#[derive(Debug, Error)]
208pub enum RecipientError<E> {
209 #[error(
211 "mail poll interval {interval:?} exceeds {MAX_MAIL_POLL_INTERVAL:?}, half the horizon"
212 )]
213 PollInterval {
214 interval: Duration,
216 },
217 #[error("no DHT key for the mail topic: {0}")]
219 Key(#[source] rings_core::error::Error),
220 #[error("cannot fetch the mail topic: {0}")]
222 Fetch(#[source] crate::error::Error),
223 #[error("mail records: {0}")]
225 Records(#[source] rings_core::error::Error),
226 #[error("cannot file a mail: {0}")]
228 Inbox(#[source] E),
229 #[error("mail recipient stopped")]
231 Stopped,
232 #[error("mail poll timed out after {timeout:?}")]
234 PollTimeout {
235 timeout: Duration,
237 },
238 #[error("mail poll timer failed: {0}")]
240 Timer(#[source] rings_runtime::TimerError),
241}
242
243enum OpeningAction {
246 Incomplete,
248 AlreadyHandledByRetained {
251 retained_opened_record: Option<String>,
252 active_opened_record: String,
253 },
254 Unreadable { active_opened_record: String },
257 Duplicate {
259 retained_opened_record: Option<String>,
260 active_opened_record: String,
261 },
262 FileNew {
264 mail: OpenedMail,
265 filed_record: String,
266 retained_opened_record: Option<String>,
267 active_opened_record: String,
268 },
269}
270
271fn classify_opening(
279 opening: Opening,
280 opened_by: Option<PublicKey<33>>,
281 delegatee_public_key: PublicKey<33>,
282 decryption_keys: &[rings_core::delegation::DelegateeKey],
283 records: &BTreeMap<String, RecipientRecord>,
284) -> OpeningAction {
285 let mail_id = opening.mail_id();
286 let active_opened_record = opened_record_name(delegatee_public_key, mail_id);
287 let retained_opened_record = opened_by
288 .filter(|&pk| pk != delegatee_public_key)
289 .map(|pk| opened_record_name(pk, mail_id));
290 let already_handled_by_retained_key = match &retained_opened_record {
291 Some(record_name) => records.contains_key(record_name),
292 None if opened_by.is_none() => decryption_keys.iter().skip(1).any(|key| {
293 records.contains_key(&opened_record_name(key.delegatee_public_key(), mail_id))
294 }),
295 None => false,
296 };
297
298 match opening {
299 Opening::Incomplete { .. } => OpeningAction::Incomplete,
300 Opening::Unreadable { .. } if already_handled_by_retained_key => {
301 OpeningAction::AlreadyHandledByRetained {
302 retained_opened_record,
303 active_opened_record,
304 }
305 }
306 Opening::Unreadable { .. } => OpeningAction::Unreadable {
307 active_opened_record,
308 },
309 Opening::Opened(_) if already_handled_by_retained_key => {
310 OpeningAction::AlreadyHandledByRetained {
311 retained_opened_record,
312 active_opened_record,
313 }
314 }
315 Opening::Opened(mail) => {
316 let filed_record = filed_record_name(dedup_key(&mail));
317 if records.contains_key(&filed_record) {
318 OpeningAction::Duplicate {
319 retained_opened_record,
320 active_opened_record,
321 }
322 } else {
323 OpeningAction::FileNew {
324 mail,
325 filed_record,
326 retained_opened_record,
327 active_opened_record,
328 }
329 }
330 }
331 }
332}
333
334pub struct Recipient<I, K> {
337 processor: Arc<Processor>,
338 inbox: I,
339 records: K,
340 interval: Duration,
341 poll_timeout: Duration,
342 poll_lock: Mutex<()>,
344}
345
346impl<I, K> Recipient<I, K>
347where
348 I: MailInbox,
349 K: KvStorageInterface<RecipientRecord> + MaybeSendSync,
350{
351 pub fn start(
354 processor: Arc<Processor>,
355 inbox: I,
356 records: K,
357 interval: Duration,
358 ) -> Result<Self, RecipientError<I::Error>> {
359 if interval > MAX_MAIL_POLL_INTERVAL {
360 return Err(RecipientError::PollInterval { interval });
361 }
362 Ok(Self {
363 processor,
364 inbox,
365 records,
366 interval,
367 poll_timeout: DEFAULT_MAIL_POLL_TIMEOUT,
368 poll_lock: Mutex::new(()),
369 })
370 }
371
372 pub fn with_poll_timeout(mut self, poll_timeout: Duration) -> Self {
374 self.poll_timeout = poll_timeout;
375 self
376 }
377
378 pub fn inbox(&self) -> &I {
380 &self.inbox
381 }
382
383 pub async fn poll(&self) -> Result<PollReport, RecipientError<I::Error>> {
386 let stop = self.processor.tasks().stop_token();
387 self.poll_with_stop(&stop).await
388 }
389
390 pub async fn poll_with_stop(
393 &self,
394 stop: &StopToken,
395 ) -> Result<PollReport, RecipientError<I::Error>> {
396 let node_stop = self.processor.tasks().stop_token();
397 if stop.should_stop() || node_stop.should_stop() {
398 return Err(RecipientError::Stopped);
399 }
400 let work = self.poll_inner(stop);
401 let caller_stopped = stop.stopped();
402 let node_stopped = node_stop.stopped();
403 let deadline = rings_runtime::sleep(self.poll_timeout);
404 futures::pin_mut!(work, caller_stopped, node_stopped, deadline);
405 let any_stop = futures::future::select(caller_stopped, node_stopped);
406 match futures::future::select(work, futures::future::select(any_stop, deadline)).await {
407 futures::future::Either::Left((result, _)) => result,
408 futures::future::Either::Right((futures::future::Either::Left(_), _)) => {
409 Err(RecipientError::Stopped)
410 }
411 futures::future::Either::Right((
412 futures::future::Either::Right((timer_result, _)),
413 _,
414 )) => match timer_result {
415 Ok(()) => {
416 tracing::warn!(
417 timeout = ?self.poll_timeout,
418 "mail: recipient poll timed out on stalled fetch or storage"
419 );
420 Err(RecipientError::PollTimeout {
421 timeout: self.poll_timeout,
422 })
423 }
424 Err(error) => Err(RecipientError::Timer(error)),
425 },
426 }
427 }
428
429 async fn poll_inner(&self, stop: &StopToken) -> Result<PollReport, RecipientError<I::Error>> {
430 let _poll_guard = rings_core::utils::SlowLockGuard::acquire(
431 "Recipient::poll_lock",
432 self.poll_lock.lock(),
433 )
434 .await;
435 let did = self.processor.did();
436 let key = Entry::gen_did(&mail_topic(did)).map_err(RecipientError::Key)?;
437 let entry = match self
438 .processor
439 .fetch_storage_entry_with_stop(key, stop)
440 .await
441 {
442 Ok(entry) => entry,
443 Err(crate::error::Error::RegistrationStopped) => {
444 return Err(RecipientError::Stopped);
445 }
446 Err(error) => return Err(RecipientError::Fetch(error)),
447 };
448 let now_ms = self.processor.clock().now_ms();
449 let mut records = self.retained_records(now_ms).await?;
450 let Some(entry) = entry else {
451 return Ok(PollReport::default());
452 };
453 let delegatee_key = self.processor.delegatee_key();
454 let delegatee_public_key = delegatee_key.delegatee_public_key();
455 let decryption_keys = self.processor.decryption_keys_at(now_ms);
456 let fresh = |mail_id: &MailDigest| {
457 !records.contains_key(&opened_record_name(delegatee_public_key, *mail_id))
458 };
459 let openings = open_mail_with_keys(&entry.data, did, &decryption_keys, fresh);
460 let mut report = PollReport::default();
461 for (opening, opened_by) in openings {
462 match classify_opening(
463 opening,
464 opened_by,
465 delegatee_public_key,
466 &decryption_keys,
467 &records,
468 ) {
469 OpeningAction::Incomplete => {
470 report.incomplete = report.incomplete.saturating_add(1);
471 }
472 OpeningAction::AlreadyHandledByRetained {
473 retained_opened_record,
474 active_opened_record,
475 } => {
476 self.remember_opened_pair(
477 &mut records,
478 retained_opened_record,
479 active_opened_record,
480 now_ms,
481 )
482 .await?;
483 }
484 OpeningAction::Unreadable {
485 active_opened_record,
486 } => {
487 report.unreadable = report.unreadable.saturating_add(1);
488 self.remember_opened_pair(&mut records, None, active_opened_record, now_ms)
489 .await?;
490 }
491 OpeningAction::Duplicate {
492 retained_opened_record,
493 active_opened_record,
494 } => {
495 report.duplicates = report.duplicates.saturating_add(1);
496 self.remember_opened_pair(
497 &mut records,
498 retained_opened_record,
499 active_opened_record,
500 now_ms,
501 )
502 .await?;
503 }
504 OpeningAction::FileNew {
505 mail,
506 filed_record,
507 retained_opened_record,
508 active_opened_record,
509 } => {
510 self.inbox
511 .file(&mail)
512 .await
513 .map_err(RecipientError::Inbox)?;
514 self.remember(&mut records, filed_record, RecipientRecord::Filed {
515 at_ms: now_ms,
516 })
517 .await?;
518 report.filed = report.filed.saturating_add(1);
519 self.remember_opened_pair(
520 &mut records,
521 retained_opened_record,
522 active_opened_record,
523 now_ms,
524 )
525 .await?;
526 }
527 }
528 }
529 Ok(report)
530 }
531
532 async fn remember_opened_pair(
534 &self,
535 records: &mut BTreeMap<String, RecipientRecord>,
536 retained_opened_record: Option<String>,
537 active_opened_record: String,
538 now_ms: u128,
539 ) -> Result<(), RecipientError<I::Error>> {
540 if let Some(retained_name) = retained_opened_record {
541 self.remember(records, retained_name, RecipientRecord::Opened {
542 at_ms: now_ms,
543 })
544 .await?;
545 }
546 self.remember(records, active_opened_record, RecipientRecord::Opened {
547 at_ms: now_ms,
548 })
549 .await
550 }
551
552 pub async fn run(&self, stop: StopToken) {
554 let node_stop = self.processor.tasks().stop_token();
555 loop {
556 match self.poll_with_stop(&stop).await {
557 Ok(report) if report.filed > 0 => {
558 tracing::info!(filed = report.filed, "mail: filed new mail");
559 }
560 Ok(_) => {}
561 Err(RecipientError::Stopped) => return,
562 Err(_) if stop.should_stop() || node_stop.should_stop() => return,
563 Err(error) => tracing::warn!("mail: poll failed: {error}"),
564 }
565 match sleep_unless_stopped(self.interval, &stop, &node_stop).await {
566 Ok(true) => {}
567 Ok(false) => return,
568 Err(error) => {
569 tracing::warn!("mail: stopping after a timer error: {error:?}");
570 return;
571 }
572 }
573 }
574 }
575
576 async fn retained_records(
578 &self,
579 now_ms: u128,
580 ) -> Result<BTreeMap<String, RecipientRecord>, RecipientError<I::Error>> {
581 let (expired, retained): (Vec<_>, Vec<_>) = self
582 .records
583 .get_all()
584 .await
585 .map_err(RecipientError::Records)?
586 .into_iter()
587 .partition(|(_, record)| record.outlived_at(now_ms));
588 for (name, _) in expired {
589 self.records
590 .remove(&name)
591 .await
592 .map_err(RecipientError::Records)?;
593 }
594 Ok(retained.into_iter().collect())
595 }
596
597 async fn remember(
600 &self,
601 records: &mut BTreeMap<String, RecipientRecord>,
602 name: String,
603 record: RecipientRecord,
604 ) -> Result<(), RecipientError<I::Error>> {
605 self.records
606 .put(&name, &record)
607 .await
608 .map_err(RecipientError::Records)?;
609 records.insert(name, record);
610 Ok(())
611 }
612}
613
614#[cfg(all(test, rings_native))]
616mod tests;