use std::{
net::SocketAddr,
sync::{
Mutex,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
#[cfg(feature = "metrics")]
use metrics::{SharedString, Unit};
#[cfg(feature = "metrics")]
use metrics_util::{CompositeKey, debugging::DebugValue};
use super::*;
use crate::{
app::{
inbound_handler::frames::InboundFrames,
recovery_codec::{DecodeFailure, DecodeOrigin, DecodedItem},
},
codec::ProtocolError,
};
pub(super) const CONSUMED: usize = 8;
pub(super) struct HookCall {
policy: RecoveryPolicy,
error_type: &'static str,
peer_address: Option<SocketAddr>,
}
pub(in crate::app::inbound_handler) struct RecordingHook {
selected: RecoveryPolicy,
quarantine: Duration,
calls: Mutex<Vec<HookCall>>,
consultations: AtomicUsize,
}
impl RecordingHook {
pub(in crate::app::inbound_handler) fn new(
selected: RecoveryPolicy,
quarantine: Duration,
) -> Self {
Self {
selected,
quarantine,
calls: Mutex::new(Vec::new()),
consultations: AtomicUsize::new(0),
}
}
pub(in crate::app::inbound_handler) fn consultations(&self) -> usize {
self.consultations.load(Ordering::Relaxed)
}
pub(in crate::app::inbound_handler) fn applied_policies(&self) -> Vec<RecoveryPolicy> {
self.calls
.lock()
.expect("hook call log lock")
.iter()
.map(|call| call.policy)
.collect()
}
pub(in crate::app::inbound_handler) fn error_types(&self) -> Vec<&'static str> {
self.calls
.lock()
.expect("hook call log lock")
.iter()
.map(|call| call.error_type)
.collect()
}
pub(super) fn peer_addresses(&self) -> Vec<Option<SocketAddr>> {
self.calls
.lock()
.expect("hook call log lock")
.iter()
.map(|call| call.peer_address)
.collect()
}
}
impl RecoveryPolicyHook for RecordingHook {
fn recovery_policy(&self, _error: &CodecError, _ctx: &CodecErrorContext) -> RecoveryPolicy {
self.consultations.fetch_add(1, Ordering::Relaxed);
self.selected
}
fn quarantine_duration(&self, _error: &CodecError, _ctx: &CodecErrorContext) -> Duration {
self.quarantine
}
fn on_error(&self, error: &CodecError, ctx: &CodecErrorContext, policy: RecoveryPolicy) {
self.calls
.lock()
.expect("hook call log lock")
.push(HookCall {
policy,
error_type: error.error_type(),
peer_address: ctx.peer_address,
});
}
}
pub(super) struct ScriptedHook {
policies: Vec<RecoveryPolicy>,
next: AtomicUsize,
}
impl ScriptedHook {
pub(super) fn new(policies: Vec<RecoveryPolicy>) -> Self {
Self {
policies,
next: AtomicUsize::new(0),
}
}
pub(super) fn consultations(&self) -> usize { self.next.load(Ordering::Relaxed) }
}
impl RecoveryPolicyHook for ScriptedHook {
fn recovery_policy(&self, _error: &CodecError, _ctx: &CodecErrorContext) -> RecoveryPolicy {
let index = self.next.fetch_add(1, Ordering::Relaxed);
self.policies
.get(index)
.copied()
.unwrap_or(RecoveryPolicy::Disconnect)
}
fn quarantine_duration(&self, _error: &CodecError, _ctx: &CodecErrorContext) -> Duration {
Duration::ZERO
}
}
pub(in crate::app::inbound_handler) fn protocol_failure() -> DecodeFailure {
let error = CodecError::Protocol(ProtocolError::UnknownMessageType { type_id: 7 });
DecodeFailure::new(error.into(), DecodeOrigin::Decode, CONSUMED)
}
pub(in crate::app::inbound_handler) fn tight_config() -> RecoveryConfig {
RecoveryConfig::default()
.max_consecutive_drops(2)
.quarantine_duration(Duration::from_millis(5))
}
pub(super) fn inbound_with_pending_failure() -> InboundFrames<DecodedItem<u8>, u8> {
InboundFrames {
pending: Some(DecodedItem::Failure(protocol_failure())),
pipeline: FramePipeline::new(None),
message_assembly: None,
read_deadline: None,
evicted_streams: Vec::new(),
}
}
#[cfg(feature = "metrics")]
pub(in crate::app::inbound_handler) type MetricSample =
(CompositeKey, Option<Unit>, Option<SharedString>, DebugValue);
#[cfg(feature = "metrics")]
pub(in crate::app::inbound_handler) fn policy_count(
samples: &[MetricSample],
expected: &str,
) -> u64 {
samples
.iter()
.filter(|(key, ..)| key.key().name() == crate::metrics::CODEC_ERRORS)
.filter(|(key, ..)| {
key.key()
.labels()
.any(|label| label.key() == "recovery_policy" && label.value() == expected)
})
.map(|(_, _, _, value)| match value {
DebugValue::Counter(count) => *count,
_ => 0,
})
.sum()
}