use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use dashmap::DashMap;
use dashmap::mapref::entry::Entry;
use super::attempt::{AttemptEvidence, MARGIN};
use super::key::{BreakerEvidence, EndpointKey, MAX_LOOKUP_BUDGET};
use super::memo::INTERACTIVE_FAILURE_TTL;
use super::{FetchContext, InteractiveFetchGate};
use crate::PackageName;
use crate::cache_policy::evict_oldest_batch_where;
pub(super) const BREAKER_OPEN_DURATION: Duration = INTERACTIVE_FAILURE_TTL;
const EVIDENCE_TTL: Duration = INTERACTIVE_FAILURE_TTL;
pub(super) const PROBE_LEASE: Duration = MAX_LOOKUP_BUDGET.saturating_add(MARGIN);
const ANSWER_REFRESH: Duration = Duration::from_secs(5);
pub(super) const BREAKER_CAP: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct ProbeId(u64);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Suspect {
pub(super) package: PackageName,
pub(super) at: Instant,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum EndpointHealth {
Closed {
last_answered: Option<Instant>,
suspect: Option<Suspect>,
},
Open {
until: Instant,
},
HalfOpen {
probe: ProbeId,
since: Instant,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Verdict {
Proceed,
Refuse,
TakeProbe,
}
pub(super) fn verdict(
health: Option<&EndpointHealth>,
counts: BreakerEvidence,
now: Instant,
) -> Verdict {
let probe_or_refuse = match counts {
BreakerEvidence::Counts => Verdict::TakeProbe,
BreakerEvidence::Ignored => Verdict::Refuse,
};
match health {
None | Some(EndpointHealth::Closed { .. }) => Verdict::Proceed,
Some(EndpointHealth::Open { until }) if now < *until => Verdict::Refuse,
Some(EndpointHealth::Open { .. }) => probe_or_refuse,
Some(EndpointHealth::HalfOpen { since, .. })
if now.saturating_duration_since(*since) < PROBE_LEASE =>
{
Verdict::Refuse
}
Some(EndpointHealth::HalfOpen { .. }) => probe_or_refuse,
}
}
impl EndpointHealth {
const UNKNOWN: Self = Self::Closed {
last_answered: None,
suspect: None,
};
pub(super) fn after(
&self,
evidence: AttemptEvidence,
package: &PackageName,
probe: Option<ProbeId>,
now: Instant,
) -> Self {
match evidence {
AttemptEvidence::Answered => Self::Closed {
last_answered: Some(now),
suspect: None,
},
AttemptEvidence::Slow => self.after_slow(package, probe, now),
AttemptEvidence::Inconclusive => match self {
Self::HalfOpen { probe: leased, .. } if Some(*leased) == probe => {
Self::Open { until: now }
}
Self::Closed { .. } | Self::Open { .. } | Self::HalfOpen { .. } => self.clone(),
},
}
}
fn after_slow(&self, package: &PackageName, probe: Option<ProbeId>, now: Instant) -> Self {
match self {
Self::HalfOpen { probe: leased, .. } if Some(*leased) == probe => Self::Open {
until: now + BREAKER_OPEN_DURATION,
},
Self::Open { .. } | Self::HalfOpen { .. } => self.clone(),
Self::Closed {
last_answered,
suspect,
} => {
let recently_answered = last_answered
.is_some_and(|at| now.saturating_duration_since(at) < EVIDENCE_TTL);
if recently_answered {
return self.clone();
}
let corroborated = suspect.as_ref().is_some_and(|suspect| {
suspect.package != *package
&& now.saturating_duration_since(suspect.at) < EVIDENCE_TTL
});
if corroborated {
Self::Open {
until: now + BREAKER_OPEN_DURATION,
}
} else {
Self::Closed {
last_answered: *last_answered,
suspect: Some(Suspect {
package: package.clone(),
at: now,
}),
}
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum BreakerAdmission {
Enforce,
ObserveOnly,
}
impl BreakerAdmission {
pub(super) const fn of(context: FetchContext) -> Self {
match context {
FetchContext::Hover => Self::Enforce,
FetchContext::CodeAction => Self::ObserveOnly,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Admission {
Proceed,
Probe(ProbeId),
Refused,
}
#[derive(Debug)]
struct EndpointState {
health: EndpointHealth,
touched: Instant,
}
#[derive(Debug, Default)]
pub(super) struct EndpointBreaker {
endpoints: DashMap<EndpointKey, EndpointState>,
next_probe: AtomicU64,
}
impl EndpointBreaker {
pub(super) fn admit(
&self,
endpoint: &EndpointKey,
admission: BreakerAdmission,
counts: BreakerEvidence,
now: Instant,
) -> Admission {
match admission {
BreakerAdmission::ObserveOnly => return Admission::Proceed,
BreakerAdmission::Enforce => {}
}
let optimistic = {
let state = self.endpoints.get(endpoint);
verdict(state.as_deref().map(|state| &state.health), counts, now)
};
match optimistic {
Verdict::Proceed => Admission::Proceed,
Verdict::Refuse => Admission::Refused,
Verdict::TakeProbe => self.take_probe(endpoint, counts, now),
}
}
pub(super) fn take_probe(
&self,
endpoint: &EndpointKey,
counts: BreakerEvidence,
now: Instant,
) -> Admission {
let Some(mut state) = self.endpoints.get_mut(endpoint) else {
return Admission::Proceed;
};
match verdict(Some(&state.health), counts, now) {
Verdict::Proceed => Admission::Proceed,
Verdict::Refuse => Admission::Refused,
Verdict::TakeProbe => {
let probe = ProbeId(self.next_probe.fetch_add(1, Ordering::Relaxed));
*state = EndpointState {
health: EndpointHealth::HalfOpen { probe, since: now },
touched: now,
};
Admission::Probe(probe)
}
}
}
pub(super) fn report(
&self,
endpoint: &EndpointKey,
package: &PackageName,
evidence: AttemptEvidence,
probe: Option<ProbeId>,
now: Instant,
) {
self.report_between(endpoint, package, evidence, probe, now, || {});
}
pub(super) fn report_between(
&self,
endpoint: &EndpointKey,
package: &PackageName,
evidence: AttemptEvidence,
probe: Option<ProbeId>,
now: Instant,
between_passes: impl FnOnce(),
) {
if probe.is_none() && self.is_noop(endpoint, package, evidence, now) {
return;
}
between_passes();
if !self.endpoints.contains_key(endpoint) && !self.make_room(now) {
return;
}
match self.endpoints.entry(*endpoint) {
Entry::Occupied(mut entry) => {
let health = entry.get().health.after(evidence, package, probe, now);
*entry.get_mut() = EndpointState {
health,
touched: now,
};
}
Entry::Vacant(entry) => {
entry.insert(EndpointState {
health: EndpointHealth::UNKNOWN.after(evidence, package, probe, now),
touched: now,
});
}
}
}
fn is_noop(
&self,
endpoint: &EndpointKey,
package: &PackageName,
evidence: AttemptEvidence,
now: Instant,
) -> bool {
let state = self.endpoints.get(endpoint);
let Some(state) = state.as_deref() else {
return false;
};
let refreshed_recently = matches!(
(&state.health, evidence),
(
EndpointHealth::Closed {
last_answered: Some(at),
suspect: None,
},
AttemptEvidence::Answered,
) if now.saturating_duration_since(*at) < ANSWER_REFRESH
);
refreshed_recently || state.health.after(evidence, package, None, now) == state.health
}
fn make_room(&self, now: Instant) -> bool {
if self.endpoints.len() < BREAKER_CAP {
return true;
}
self.endpoints
.retain(|_, state| now.saturating_duration_since(state.touched) < EVIDENCE_TTL);
if self.endpoints.len() < BREAKER_CAP {
return true;
}
evict_oldest_batch_where(
&self.endpoints,
BREAKER_CAP,
|state| state.touched,
|state| matches!(state.health, EndpointHealth::Closed { .. }),
);
self.endpoints.len() < BREAKER_CAP
}
pub(super) fn forget(&self, endpoint: &EndpointKey) {
self.endpoints.remove(endpoint);
}
pub(super) fn clear(&self) {
self.endpoints.clear();
}
#[cfg(test)]
pub(super) fn len(&self) -> usize {
self.endpoints.len()
}
#[cfg(test)]
pub(super) fn health(&self, endpoint: &EndpointKey) -> Option<EndpointHealth> {
self.endpoints
.get(endpoint)
.map(|state| state.health.clone())
}
}
impl InteractiveFetchGate {
pub(super) fn admit(
&self,
endpoint: &EndpointKey,
context: FetchContext,
counts: BreakerEvidence,
) -> Admission {
self.breaker.admit(
endpoint,
BreakerAdmission::of(context),
counts,
super::now(),
)
}
}