use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;
use super::breaker::{Admission, ProbeId};
use super::key::{BreakerEvidence, EndpointKey, LookupKey, LookupKind};
use super::memo::RecordState;
use super::{InteractiveFetch, InteractiveFetchGate, InteractiveFetchRequest, NoLiveList};
use crate::ErrorOrigin;
use crate::endpoint_contact::{AttemptContact, Contact, ResponseSeen};
pub(super) const MARGIN: Duration = Duration::from_secs(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum AttemptBudget {
Full,
Truncated,
}
impl AttemptBudget {
pub(super) fn of(remaining: Duration, budget: Duration) -> Self {
if remaining >= budget / 2 {
Self::Full
} else {
Self::Truncated
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum AttemptEnd {
Live,
Err(ErrorOrigin),
Elapsed,
Cancelled,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum AttemptEvidence {
Answered,
Slow,
Inconclusive,
}
pub(super) fn evidence(
end: AttemptEnd,
contact: Contact,
waited: Duration,
budget: Duration,
) -> AttemptEvidence {
let responsive = waited < budget.saturating_sub(MARGIN);
let answered = contact.response == ResponseSeen::Yes;
let stalled = contact.stall >= budget / 2;
match end {
AttemptEnd::Live if responsive && answered => AttemptEvidence::Answered,
AttemptEnd::Live => AttemptEvidence::Inconclusive,
AttemptEnd::Err(_) | AttemptEnd::Elapsed | AttemptEnd::Cancelled if stalled => {
AttemptEvidence::Slow
}
AttemptEnd::Err(ErrorOrigin::Endpoint) if responsive && answered => {
AttemptEvidence::Answered
}
AttemptEnd::Err(_) | AttemptEnd::Elapsed | AttemptEnd::Cancelled => {
AttemptEvidence::Inconclusive
}
}
}
fn attempt_contact(counts: BreakerEvidence, endpoint: EndpointKey) -> AttemptContact {
match (counts, endpoint) {
(
BreakerEvidence::Counts,
EndpointKey::Resolved {
ecosystem,
endpoint,
},
) => AttemptContact::on_endpoint(ecosystem, endpoint),
(BreakerEvidence::Counts, EndpointKey::Scoped { .. }) | (BreakerEvidence::Ignored, _) => {
AttemptContact::own_only()
}
}
}
struct AttemptGuard<'a> {
gate: &'a InteractiveFetchGate,
lookup: &'a Arc<LookupKey>,
generation: u64,
started: Instant,
probe: Option<ProbeId>,
settled: bool,
counts: BreakerEvidence,
contact: AttemptContact,
}
impl AttemptGuard<'_> {
fn finish(mut self, end: AttemptEnd) {
self.settled = true;
self.report(end);
}
fn report(&self, end: AttemptEnd) {
match self.counts {
BreakerEvidence::Counts => {}
BreakerEvidence::Ignored => return,
}
let now = Instant::now();
let waited = now.saturating_duration_since(self.started);
let (contact, view) = self.contact.observe(now);
let evidence = evidence(end, contact, waited, self.lookup.kind().budget());
tracing::debug!(
?evidence,
view = view.as_str(),
stall_ms = u64::try_from(contact.stall.as_millis()).unwrap_or(u64::MAX),
lookup = self.lookup.kind().as_str(),
"interactive attempt breaker evidence"
);
if self.gate.generation() != self.generation {
return;
}
let endpoint = self.lookup.route.endpoint();
self.gate.breaker.report(
&endpoint,
&self.lookup.package,
evidence,
self.probe,
super::now(),
);
if self.gate.generation() != self.generation {
self.gate.breaker.forget(&endpoint);
}
}
}
impl Drop for AttemptGuard<'_> {
fn drop(&mut self) {
if !self.settled {
self.report(AttemptEnd::Cancelled);
}
}
}
pub trait InteractiveFetchError {
fn log_cause(&self) -> (Option<u16>, &'static str);
fn origin(&self) -> ErrorOrigin;
}
impl InteractiveFetchError for crate::DepsError {
fn log_cause(&self) -> (Option<u16>, &'static str) {
self.safe_tracing_summary()
}
fn origin(&self) -> ErrorOrigin {
Self::origin(self)
}
}
#[cfg(test)]
impl InteractiveFetchError for () {
fn log_cause(&self) -> (Option<u16>, &'static str) {
(None, "unspecified")
}
fn origin(&self) -> ErrorOrigin {
ErrorOrigin::Endpoint
}
}
pub(super) async fn bounded_await_until<T, E: InteractiveFetchError>(
fetch: impl Future<Output = Result<T, E>>,
deadline: Instant,
request: &InteractiveFetchRequest<'_>,
kind: LookupKind,
) -> (InteractiveFetch<T>, AttemptEnd) {
match tokio::time::timeout_at(deadline, fetch).await {
Ok(Ok(value)) => (InteractiveFetch::Live(value), AttemptEnd::Live),
Ok(Err(error)) => {
let (status, cause) = error.log_cause();
tracing::debug!(
package = %request.package().for_tracing(),
context = request.context.as_str(),
lookup = kind.as_str(),
?status,
cause,
"interactive registry lookup failed"
);
(
InteractiveFetch::Degraded(NoLiveList::Failed),
AttemptEnd::Err(error.origin()),
)
}
Err(_) => {
tracing::warn!(
package = %request.package().for_tracing(),
context = request.context.as_str(),
lookup = kind.as_str(),
timeout_secs = kind.budget().as_secs(),
"interactive registry lookup timed out"
);
(
InteractiveFetch::Degraded(NoLiveList::Unverified),
AttemptEnd::Elapsed,
)
}
}
}
pub(super) enum Attempted<T> {
Polled(InteractiveFetch<T>, AttemptBudget),
Refused,
}
impl InteractiveFetchGate {
pub(super) async fn attempt<T, E: InteractiveFetchError>(
&self,
fetch: impl Future<Output = Result<T, E>>,
deadline: Instant,
lookup: &Arc<LookupKey>,
request: &InteractiveFetchRequest<'_>,
background_failure_known: bool,
generation: u64,
) -> Attempted<T> {
let counts = lookup.kind().breaker_evidence();
let endpoint = lookup.route.endpoint();
let probe = match self.admit(&endpoint, request.context, counts) {
Admission::Refused => {
super::log_skipped(request, "registry endpoint circuit open");
return Attempted::Refused;
}
Admission::Probe(probe) => Some(probe),
Admission::Proceed => None,
};
let started = Instant::now();
let budget = AttemptBudget::of(
deadline.saturating_duration_since(started),
lookup.kind().budget(),
);
let guard = AttemptGuard {
gate: self,
lookup,
generation,
started,
probe,
settled: false,
counts,
contact: attempt_contact(counts, endpoint),
};
let scoped = guard.contact.scope(fetch);
let (result, end) = bounded_await_until(scoped, deadline, request, lookup.kind()).await;
guard.finish(end);
let result = match result {
InteractiveFetch::Degraded(NoLiveList::Failed) if background_failure_known => {
InteractiveFetch::Degraded(NoLiveList::Unverified)
}
other => other,
};
match (&result, background_failure_known, budget) {
(InteractiveFetch::Degraded(_), _, AttemptBudget::Full) => {
self.record(lookup, RecordState::InteractiveFailed, generation);
}
(InteractiveFetch::Degraded(_), _, AttemptBudget::Truncated) => {}
(InteractiveFetch::Live(_), true, _) => {
self.record(lookup, RecordState::InteractiveSucceeded, generation);
}
(InteractiveFetch::Live(_), false, _) => self.forget_record(lookup),
}
Attempted::Polled(result, budget)
}
}