use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use id_effect::{Effect, UtcDateTime, fail, succeed, suspend};
use super::{Account, AccountError, AccountToken, TokenKind};
#[derive(Clone, PartialEq, Eq)]
pub struct AccountMail {
pub kind: TokenKind,
pub account: Account,
pub token: AccountToken,
pub expires_at: UtcDateTime,
pub valid_for: Duration,
}
impl fmt::Debug for AccountMail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AccountMail")
.field("kind", &self.kind)
.field("account", &self.account)
.field("token", &self.token)
.field("expires_at", &self.expires_at)
.finish_non_exhaustive()
}
}
pub trait AccountNotifier: Send + Sync + 'static {
fn notify(&self, mail: AccountMail) -> Effect<(), AccountError>;
}
#[derive(Default)]
struct MemoryNotifierState {
mails: Vec<AccountMail>,
fail: Option<String>,
}
#[derive(Clone, Default)]
pub struct MemoryAccountNotifier {
inner: Arc<Mutex<MemoryNotifierState>>,
}
impl fmt::Debug for MemoryAccountNotifier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemoryAccountNotifier")
.field("sent", &self.state().mails.len())
.finish()
}
}
impl MemoryAccountNotifier {
#[inline]
pub fn new() -> Self {
Self::default()
}
fn state(&self) -> MutexGuard<'_, MemoryNotifierState> {
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn mails(&self) -> Vec<AccountMail> {
self.state().mails.clone()
}
pub fn last(&self, kind: TokenKind) -> Option<AccountMail> {
self
.state()
.mails
.iter()
.rev()
.find(|m| m.kind == kind)
.cloned()
}
pub fn fail_with(&self, message: Option<&str>) {
self.state().fail = message.map(str::to_owned);
}
}
impl AccountNotifier for MemoryAccountNotifier {
fn notify(&self, mail: AccountMail) -> Effect<(), AccountError> {
let this = self.clone();
suspend(move || {
let mut st = this.state();
match st.fail.clone() {
Some(m) => fail(AccountError::Notify(m)),
None => {
st.mails.push(mail);
succeed(())
}
}
})
}
}