use super::ConnectionContext;
use crate::{codec::EofError, push::PushHandle};
type BeforeSendHook<F> = Box<dyn FnMut(&mut F, &mut ConnectionContext) + Send + 'static>;
type OnConnectionSetupHook<F> =
Box<dyn FnOnce(PushHandle<F>, &mut ConnectionContext) + Send + 'static>;
type OnCommandEndHook = Box<dyn FnMut(&mut ConnectionContext) + Send + 'static>;
type HandleErrorHook<E> = Box<dyn FnMut(E, &mut ConnectionContext) + Send + 'static>;
type StreamEndHook<F> = Box<dyn FnMut(&mut ConnectionContext) -> Option<F> + Send + 'static>;
type OnEofHook = Box<dyn FnMut(&EofError, &[u8], &mut ConnectionContext) + Send + 'static>;
pub struct CustomProtocolHooks<F, E> {
pub on_connection_setup: Option<OnConnectionSetupHook<F>>,
pub before_send: Option<BeforeSendHook<F>>,
pub on_command_end: Option<OnCommandEndHook>,
pub handle_error: Option<HandleErrorHook<E>>,
pub stream_end: Option<StreamEndHook<F>>,
pub on_eof: Option<OnEofHook>,
}
impl<F, E> Default for CustomProtocolHooks<F, E> {
fn default() -> Self {
Self {
on_connection_setup: None,
before_send: None,
on_command_end: None,
handle_error: None,
stream_end: None,
on_eof: None,
}
}
}
impl<F, E> CustomProtocolHooks<F, E> {
pub(super) fn on_connection_setup(
&mut self,
handle: PushHandle<F>,
ctx: &mut ConnectionContext,
) {
if let Some(hook) = self.on_connection_setup.take() {
hook(handle, ctx);
}
}
pub(super) fn before_send(&mut self, frame: &mut F, ctx: &mut ConnectionContext) {
if let Some(hook) = &mut self.before_send {
hook(frame, ctx);
}
}
pub(super) fn on_command_end(&mut self, ctx: &mut ConnectionContext) {
if let Some(hook) = &mut self.on_command_end {
hook(ctx);
}
}
pub(super) fn handle_error(&mut self, error: E, ctx: &mut ConnectionContext) {
if let Some(hook) = &mut self.handle_error {
hook(error, ctx);
}
}
pub(super) fn stream_end_frame(&mut self, ctx: &mut ConnectionContext) -> Option<F> {
self.stream_end.as_mut().and_then(|hook| hook(ctx))
}
pub(super) fn on_eof(
&mut self,
error: &EofError,
partial_data: &[u8],
ctx: &mut ConnectionContext,
) {
if let Some(hook) = &mut self.on_eof {
hook(error, partial_data, ctx);
}
}
}