use std::sync::Arc;
use channels::ChannelSenders;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use crate::{
interest::Interests,
session::{error::ChannelReceiverDropped, intents::Intent},
};
mod aoi_finder;
mod capabilities;
mod challenge;
pub(crate) mod channels;
mod data;
mod error;
pub mod intents;
mod pai_finder;
mod payload;
mod reconciler;
mod resource;
mod run;
mod static_tokens;
pub(crate) use self::{
challenge::InitialTransmission, channels::Channels, error::Error, run::run_session,
};
pub(crate) type SessionId = u64;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub enum Role {
Alfie,
Betty,
}
impl Role {
pub fn is_alfie(&self) -> bool {
matches!(self, Role::Alfie)
}
pub fn is_betty(&self) -> bool {
matches!(self, Role::Betty)
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum SessionMode {
ReconcileOnce,
Continuous,
}
impl SessionMode {
pub fn is_live(&self) -> bool {
matches!(self, Self::Continuous)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInit {
pub interests: Interests,
pub mode: SessionMode,
}
impl SessionInit {
pub fn new(interests: impl Into<Interests>, mode: SessionMode) -> Self {
let interests = interests.into();
Self { interests, mode }
}
pub fn continuous(interests: impl Into<Interests>) -> Self {
Self::new(interests, SessionMode::Continuous)
}
pub fn reconcile_once(interests: impl Into<Interests>) -> Self {
Self::new(interests, SessionMode::ReconcileOnce)
}
}
#[derive(Debug, Clone)]
pub(crate) struct EventSender(pub mpsc::Sender<SessionEvent>);
impl EventSender {
pub(crate) async fn send(&self, event: SessionEvent) -> Result<(), ChannelReceiverDropped> {
self.0.send(event).await.map_err(|_| ChannelReceiverDropped)
}
}
#[derive(derive_more::Debug)]
pub(crate) enum SessionEvent {
Established,
Complete {
result: Result<(), Arc<Error>>,
#[cfg_attr(not(test), allow(dead_code))]
we_cancelled: bool,
#[debug("ChannelSenders")]
senders: ChannelSenders,
remaining_intents: Vec<Intent>,
},
}
#[derive(Debug)]
pub(crate) enum SessionUpdate {
SubmitIntent(Intent),
Abort(Error),
}
#[derive(Debug)]
pub(crate) struct SessionHandle {
pub(crate) update_tx: mpsc::Sender<SessionUpdate>,
pub(crate) event_rx: mpsc::Receiver<SessionEvent>,
}
impl SessionHandle {
#[cfg(test)]
pub(crate) async fn complete(&mut self) -> Result<(ChannelSenders, bool), Arc<Error>> {
while let Some(event) = self.event_rx.recv().await {
if let SessionEvent::Complete {
result,
senders,
we_cancelled,
..
} = event
{
return result.map(|()| (senders, we_cancelled));
}
}
Err(Arc::new(Error::ActorFailed))
}
}