mod channels;
mod counter;
mod dispatch;
mod drain;
mod drive;
mod event;
mod frame;
mod grace;
mod init;
mod interruption;
mod multi_packet;
mod observation;
mod observation_loop;
mod output;
mod peer_close;
mod polling;
mod pushes;
mod response;
mod setters;
mod shutdown;
mod sink;
mod state;
mod terminator;
#[cfg(all(test, not(loom)))]
mod tests;
mod writes;
use std::{
net::SocketAddr,
sync::{Arc, OnceLock},
};
pub use channels::ConnectionChannels;
pub(crate) use counter::ActiveConnection;
#[cfg(loom)]
pub use counter::LoomConnectionGuard;
pub use counter::active_connection_count;
pub(crate) use drive::{PEER_CLOSED_RESPONSE_GRACE, ResponseOutcome};
use grace::{GraceTimer, TokioGraceTimer};
use init::ActorInit;
#[cfg(test)]
pub(crate) use init::UntrackedActorInit;
use log::info;
pub(crate) use observation::UnobservedCause;
use output::ActiveOutput;
pub(crate) use pushes::PendingPushes;
pub(crate) use sink::{FrameSink, ProgressSignal, PushSink};
pub(crate) use terminator::TerminatorCorrelation;
use thiserror::Error;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
#[cfg(all(test, not(loom)))]
pub(crate) use writes::WriteBound;
pub(crate) use writes::{WriteOutcome, write_before_bound};
pub use crate::fairness::FairnessConfig;
use crate::{
NoProtocolError,
app::Packet,
correlation::CorrelatableFrame,
fairness::FairnessTracker,
fragment::Fragmenter,
hooks::{ConnectionContext, ConnectionProtocol, ProtocolHooks},
push::{FrameLike, PushHandle, PushQueues},
response::FrameStream,
session::ConnectionId,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
pub enum ConnectionStateError {
#[error("cannot set response while a multi-packet channel is active")]
MultiPacketActive,
#[error("cannot set multi-packet channel while a response stream is active")]
ResponseActive,
}
pub struct ConnectionActor<F, E = NoProtocolError, P = F> {
high_rx: Option<mpsc::Receiver<P>>,
low_rx: Option<mpsc::Receiver<P>>,
active_output: ActiveOutput<F, E>,
shutdown: CancellationToken,
counter: Option<ActiveConnection>,
protocol: Option<ConnectionProtocol<F, E>>,
terminator_correlation: TerminatorCorrelation,
fairness: FairnessTracker,
fragmenter: Option<Fragmenter>,
composer: pushes::PushComposer<F, E, P>,
connection_id: Option<ConnectionId>,
peer_addr: Option<SocketAddr>,
command_end_pending: bool,
response_failed: bool,
abandon_response_on_shutdown: bool,
peer_closed: CancellationToken,
peer_closed_grace: std::time::Duration,
grace_timer: Arc<dyn GraceTimer>,
response_correlation: Option<u64>,
unobserved_cause: Option<Arc<OnceLock<UnobservedCause>>>,
}
impl<F, E> ConnectionActor<F, E>
where
F: FrameLike + CorrelatableFrame + Packet,
E: std::fmt::Debug,
{
#[must_use]
pub fn new(
queues: PushQueues<F>,
handle: PushHandle<F>,
response: Option<FrameStream<F, E>>,
shutdown: CancellationToken,
) -> Self {
Self::with_hooks(
ConnectionChannels::new(queues, handle),
response,
shutdown,
ProtocolHooks::<F, E>::default(),
)
}
#[must_use]
pub fn with_hooks(
channels: ConnectionChannels<F>,
response: Option<FrameStream<F, E>>,
shutdown: CancellationToken,
hooks: ProtocolHooks<F, E>,
) -> Self {
let handle = channels.handle.clone();
let mut actor = Self::build(
ActorInit {
channels,
response,
shutdown,
hooks: Some(hooks),
ctx: ConnectionContext::default(),
composer: pushes::PushComposer::Inline(Self::compose_inline_push),
},
Some(ActiveConnection::new()),
);
actor.run_connection_setup(handle);
actor
}
fn run_connection_setup(&mut self, handle: PushHandle<F>) {
if let Some(protocol) = self.protocol.as_mut() {
protocol.on_connection_setup(handle);
}
}
fn compose_inline_push(actor: &mut Self, frame: F, pushes: &mut Vec<F>) {
actor.process_frame_with_hooks_and_metrics(frame, pushes);
}
}
impl<F, E, P> ConnectionActor<F, E, P>
where
F: FrameLike + CorrelatableFrame + Packet,
E: std::fmt::Debug,
P: FrameLike,
{
#[cfg(test)]
#[must_use]
pub(crate) fn new_untracked(init: UntrackedActorInit<F, E, P>) -> Self {
Self::build(
ActorInit {
channels: init.channels,
response: init.response,
shutdown: init.shutdown,
hooks: Some(init.hooks),
ctx: init.ctx,
composer: pushes::PushComposer::Deferred,
},
None,
)
}
#[must_use]
pub(crate) fn new_prepared_untracked(
channels: ConnectionChannels<P>,
shutdown: CancellationToken,
connection_id: Option<ConnectionId>,
peer_addr: Option<SocketAddr>,
) -> Self {
let mut actor = Self::build(
ActorInit {
channels,
response: None,
shutdown,
hooks: None,
ctx: ConnectionContext::default(),
composer: pushes::PushComposer::Deferred,
},
None,
);
actor.connection_id = connection_id;
actor.peer_addr = peer_addr;
actor
}
fn build(init: ActorInit<F, E, P>, counter: Option<ActiveConnection>) -> Self {
let ActorInit {
channels,
response,
shutdown,
hooks,
ctx,
composer,
} = init;
let ConnectionChannels { queues, .. } = channels;
let connection_id = ctx.connection_id();
let peer_addr = ctx.peer_addr();
let active_output = response.map_or_else(|| ActiveOutput::None, ActiveOutput::Response);
let actor = Self {
high_rx: Some(queues.high_priority_rx),
low_rx: Some(queues.low_priority_rx),
active_output,
shutdown,
counter,
terminator_correlation: if hooks.is_some() {
TerminatorCorrelation::ACTOR
} else {
TerminatorCorrelation::PREPARED
},
protocol: hooks.map(|installed| ConnectionProtocol::with_context(installed, ctx)),
fairness: FairnessTracker::new(FairnessConfig::default()),
fragmenter: None,
composer,
connection_id,
peer_addr,
command_end_pending: false,
response_failed: false,
abandon_response_on_shutdown: true,
peer_closed: CancellationToken::new(),
peer_closed_grace: PEER_CLOSED_RESPONSE_GRACE,
grace_timer: Arc::new(TokioGraceTimer),
response_correlation: None,
unobserved_cause: None,
};
if actor.counter.is_some() {
info!(
"connection opened: wireframe_active_connections={}, id={:?}, peer={:?}",
counter::current_count(),
actor.connection_id,
actor.peer_addr
);
}
actor
}
}
#[cfg(all(not(loom), any(test, feature = "test-support")))]
pub mod test_support;