use super::{dialog::TerminatedReason, DialogId};
use crate::platform::{mpsc, Instant};
use crate::sip::StatusCode;
use crate::transaction::key::TransactionRole;
use core::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LifecycleTime {
pub monotonic: Instant,
pub since_unix_epoch: Option<Duration>,
}
impl LifecycleTime {
pub(crate) fn now() -> Self {
Self {
monotonic: Instant::now(),
#[cfg(feature = "std")]
since_unix_epoch: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok(),
#[cfg(not(feature = "std"))]
since_unix_epoch: None,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum DialogLifecycleKind {
InviteAccepted { status: StatusCode },
LocalTerminationRequested,
RemoteByeReceived,
DialogTerminated { reason: TerminatedReason },
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct DialogLifecycleEvent {
pub dialog_id: DialogId,
pub role: TransactionRole,
pub sequence: u64,
pub occurred_at: LifecycleTime,
pub kind: DialogLifecycleKind,
}
pub type DialogLifecycleSender = mpsc::UnboundedSender<DialogLifecycleEvent>;
pub type DialogLifecycleReceiver = mpsc::UnboundedReceiver<DialogLifecycleEvent>;
pub fn dialog_lifecycle_channel() -> (DialogLifecycleSender, DialogLifecycleReceiver) {
mpsc::unbounded_channel()
}
#[derive(Default)]
pub(crate) struct LifecycleState {
pub sender: Option<DialogLifecycleSender>,
pub sequence: u64,
pub emitted: u8,
}
impl LifecycleState {
pub fn emit(
&mut self,
id: DialogId,
role: TransactionRole,
time: LifecycleTime,
kind: DialogLifecycleKind,
) {
let Some(sender) = &self.sender else { return };
let bit = match &kind {
DialogLifecycleKind::InviteAccepted { .. } => 1,
DialogLifecycleKind::LocalTerminationRequested => 2,
DialogLifecycleKind::RemoteByeReceived => 4,
DialogLifecycleKind::DialogTerminated { .. } => 8,
};
if self.emitted & bit != 0 || (self.emitted & 8 != 0 && bit != 1) {
return;
}
self.emitted |= bit;
self.sequence += 1;
let _ = sender.send(DialogLifecycleEvent {
dialog_id: id,
role,
sequence: self.sequence,
occurred_at: time,
kind,
});
}
}