use std::convert::Infallible;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use futures::future::select;
use futures::future::Either;
use futures::pin_mut;
use rand::rngs::OsRng;
use rings_core::consts::MAX_TTL_MS;
use rings_core::dht::entry::Entry;
use rings_core::lifecycle::StopSource;
use rings_core::swarm::storage_api::StoreQuorum;
use rings_core::swarm::storage_api::StoreUnconfirmed;
use rings_core::utils::get_epoch_ms;
use rings_runtime::sleep;
use rings_runtime::MaybeSendSync;
use thiserror::Error;
use super::descriptor::descriptor_topic;
use super::descriptor::MailDescriptor;
use super::descriptor::MailRecipient;
use super::envelope::seal;
use super::envelope::MailDigest;
use super::envelope::SealError;
use super::envelope::SealedMail;
use super::mail_topic;
use crate::descriptor::heard_descriptors;
use crate::prelude::rings_core::dht::Did;
use crate::processor::Processor;
pub const MAIL_STORE_REPORT_WAIT: Duration = Duration::from_secs(60);
#[derive(Debug, Error)]
pub enum MailGatewayError {
#[error("no DHT key for {did}'s mail descriptor topic: {source}")]
Key {
did: Did,
source: rings_core::error::Error,
},
#[error("cannot fetch {did}'s mail descriptor: {source}")]
Fetch {
did: Did,
source: crate::error::Error,
},
#[error(transparent)]
Seal(#[from] SealError),
#[error("cannot write {did}'s mail: {source}")]
Write {
did: Did,
source: crate::error::Error,
},
#[error("no owner stored {did}'s mail: {cause:?}")]
Unstored {
did: Did,
cause: StoreUnconfirmed,
},
#[error("no owner reported {did}'s mail in time")]
Unreported {
did: Did,
},
}
#[cfg_attr(rings_browser, async_trait(?Send))]
#[cfg_attr(rings_native, async_trait)]
pub trait MailDrop: MaybeSendSync {
async fn recipient(&self, did: Did) -> Result<Option<MailRecipient>, MailGatewayError>;
async fn deliver(
&self,
recipient: &MailRecipient,
message: &[u8],
) -> Result<MailDigest, MailGatewayError>;
}
pub struct MailGateway {
processor: Arc<Processor>,
}
impl MailGateway {
pub fn new(processor: Arc<Processor>) -> Self {
Self { processor }
}
}
#[cfg_attr(rings_browser, async_trait(?Send))]
#[cfg_attr(rings_native, async_trait)]
impl MailDrop for MailGateway {
async fn recipient(&self, did: Did) -> Result<Option<MailRecipient>, MailGatewayError> {
let key = Entry::gen_did(&descriptor_topic(did))
.map_err(|source| MailGatewayError::Key { did, source })?;
let entry = self
.processor
.fetch_storage_entry(key)
.await
.map_err(|source| MailGatewayError::Fetch { did, source })?;
let now_ms = get_epoch_ms();
let network_id = self.processor.swarm.network_id();
Ok(entry.and_then(|entry| {
MailDescriptor::live_recipient(heard_descriptors(&entry), did, now_ms, network_id)
}))
}
async fn deliver(
&self,
recipient: &MailRecipient,
message: &[u8],
) -> Result<MailDigest, MailGatewayError> {
let SealedMail { mail_id, elements } = seal(message, recipient, &mut OsRng)?;
let did = recipient.did;
let deadline = StopSource::new();
let stop = deadline.token();
let stored = async {
let receipt = self
.processor
.storage_extend_reported(
&mail_topic(did),
elements,
MAX_TTL_MS,
StoreQuorum::Any,
&stop,
)
.await
.map_err(|source| MailGatewayError::Write { did, source })?;
confirmed(did, receipt, stop.stopped()).await
};
stopping_after(MAIL_STORE_REPORT_WAIT, &deadline, stored).await?;
Ok(mail_id)
}
}
pub(super) async fn confirmed(
did: Did,
receipt: impl Future<Output = Result<(), StoreUnconfirmed>>,
elapsed: impl Future<Output = ()>,
) -> Result<(), MailGatewayError> {
pin_mut!(receipt, elapsed);
match select(receipt, elapsed).await {
Either::Left((Ok(()), _)) => Ok(()),
Either::Left((Err(cause), _)) => Err(MailGatewayError::Unstored { did, cause }),
Either::Right(((), _)) => Err(MailGatewayError::Unreported { did }),
}
}
pub(super) async fn stopping_after<F: Future>(
wait: Duration,
deadline: &StopSource,
write: F,
) -> F::Output {
let timer = async {
if let Err(error) = sleep(wait).await {
tracing::debug!(
?error,
"no timer for a mail's store report wait; stopping now"
);
}
deadline.request_stop();
std::future::pending::<Infallible>().await
};
pin_mut!(write, timer);
match select(write, timer).await {
Either::Left((output, _)) => output,
Either::Right((never, _)) => match never {},
}
}