use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use super::codec::encode_outbound_message;
use super::models::{OutboundVoiceMessage, SessionDisconnected};
use super::turn::{TargetTurn, TargetTurnOrigin};
use super::VoiceError;
use crate::scope::FoundryRequestContext;
pub const CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SessionTermination {
Completed,
Cancelled,
ProtocolError,
AcceptError,
CallbackError,
InternalError,
TransportError,
}
impl SessionTermination {
pub fn as_str(self) -> &'static str {
match self {
Self::Completed => "completed",
Self::Cancelled => "cancelled",
Self::ProtocolError => "protocol_error",
Self::AcceptError => "accept_error",
Self::CallbackError => "callback_error",
Self::InternalError => "internal_error",
Self::TransportError => "transport_error",
}
}
}
pub(crate) struct Outgoing {
pub(crate) frame: String,
pub(crate) ack: oneshot::Sender<Result<(), VoiceError>>,
}
#[derive(Default)]
struct State {
terminal: bool,
termination: Option<SessionTermination>,
close_code: Option<u16>,
disconnect: Option<SessionDisconnected>,
connection_span: Option<tracing::Span>,
}
struct Inner {
outgoing: mpsc::Sender<Outgoing>,
state: Mutex<State>,
context: FoundryRequestContext,
}
#[derive(Clone)]
pub struct Session {
inner: Arc<Inner>,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("termination", &self.termination())
.finish_non_exhaustive()
}
}
impl Session {
pub(crate) fn new(
outgoing: mpsc::Sender<Outgoing>,
context: FoundryRequestContext,
connection_span: tracing::Span,
) -> Self {
Self {
inner: Arc::new(Inner {
outgoing,
state: Mutex::new(State {
connection_span: Some(connection_span),
..State::default()
}),
context,
}),
}
}
fn state(&self) -> MutexGuard<'_, State> {
self.inner
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn same_connection(&self, other: &Session) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
pub fn termination(&self) -> Option<SessionTermination> {
self.state().termination
}
pub fn context(&self) -> &FoundryRequestContext {
&self.inner.context
}
pub async fn send(&self, message: impl Into<OutboundVoiceMessage>) -> Result<(), VoiceError> {
self.ensure_writable()?;
let frame = encode_outbound_message(&message.into())?;
let (ack, done) = oneshot::channel();
if self
.inner
.outgoing
.send(Outgoing { frame, ack })
.await
.is_err()
{
return Err(self.gone());
}
done.await.unwrap_or_else(|_| Err(self.gone()))
}
fn gone(&self) -> VoiceError {
if self.state().terminal {
VoiceError::Terminating
} else {
VoiceError::Transport("Voice WebSocket send failed: the connection is closed".into())
}
}
fn ensure_writable(&self) -> Result<(), VoiceError> {
if self.state().terminal {
return Err(VoiceError::Terminating);
}
Ok(())
}
pub fn start_target_turn(
&self,
origin: TargetTurnOrigin,
input_count: u64,
) -> Result<TargetTurn, VoiceError> {
let span = self.live_span()?;
TargetTurn::create(&span, origin, input_count)
}
fn live_span(&self) -> Result<tracing::Span, VoiceError> {
let state = self.state();
match (&state.connection_span, state.terminal) {
(Some(span), false) => Ok(span.clone()),
_ => Err(VoiceError::Terminating),
}
}
#[cfg(feature = "otel")]
#[cfg_attr(docsrs, doc(cfg(feature = "otel")))]
pub fn start_target_turn_linked(
&self,
origin: TargetTurnOrigin,
input_count: u64,
trigger: opentelemetry::trace::SpanContext,
) -> Result<TargetTurn, VoiceError> {
let span = self.live_span()?;
let turn = TargetTurn::create(&span, origin, input_count)?;
turn.link(trigger)?;
Ok(turn)
}
pub(crate) fn is_terminal(&self) -> bool {
self.state().terminal
}
pub(crate) fn begin_termination(&self, termination: Option<SessionTermination>) {
let mut state = self.state();
state.terminal = true;
state.connection_span = None;
if state.termination.is_none() {
state.termination = termination;
}
}
pub(crate) fn select_close_code(&self, code: u16) {
self.state().close_code.get_or_insert(code);
}
pub(crate) fn selected_close_code(&self) -> Option<u16> {
self.state().close_code
}
pub(crate) fn observe_disconnect(
&self,
code: u16,
reason: Option<String>,
termination: SessionTermination,
) {
let mut state = self.state();
state.terminal = true;
state.connection_span = None;
state.close_code.get_or_insert(code);
if state.termination.is_none() {
state.termination = Some(termination);
}
if state.disconnect.is_none() {
state.disconnect = Some(SessionDisconnected { code, reason });
}
}
pub(crate) fn peek_disconnect(&self) -> Option<SessionDisconnected> {
self.state().disconnect.clone()
}
pub(crate) fn take_disconnect(&self) -> Option<SessionDisconnected> {
self.state().disconnect.take()
}
}