Skip to main content

deps_core/lsp_helpers/interactive_fetch/
attempt.rs

1//! One polled registry attempt: its deadline, what it tells the breaker, and what it writes to
2//! the memo.
3
4use std::future::Future;
5use std::sync::Arc;
6use std::time::Duration;
7
8use tokio::time::Instant;
9
10use super::breaker::{Admission, ProbeId};
11use super::key::{BreakerEvidence, EndpointKey, LookupKey, LookupKind};
12use super::memo::RecordState;
13use super::{InteractiveFetch, InteractiveFetchGate, InteractiveFetchRequest, NoLiveList};
14use crate::ErrorOrigin;
15use crate::endpoint_contact::{AttemptContact, Contact, ResponseSeen};
16
17/// Margin below the budget within which an answer may be a stale-serve or a race against the
18/// 10 s connect timeout rather than proof the endpoint is responsive.
19pub(super) const MARGIN: Duration = Duration::from_secs(1);
20
21/// Whether an attempt started with enough of the request's budget for its failure to say
22/// anything about the registry.
23///
24/// A request promoted to leader after its predecessor was cancelled inherits the deadline it
25/// entered with, so it may poll with a sliver of the budget left. Such an attempt elapsing
26/// proves nothing, and memoizing it would suppress a package for 30 s on a guess.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub(super) enum AttemptBudget {
29    /// At least half of the kind's budget remained: an error or elapse is a real failure.
30    Full,
31    /// Less than half remained: an error or elapse is inconclusive and writes no failure.
32    Truncated,
33}
34
35impl AttemptBudget {
36    pub(super) fn of(remaining: Duration, budget: Duration) -> Self {
37        if remaining >= budget / 2 {
38            Self::Full
39        } else {
40            Self::Truncated
41        }
42    }
43}
44
45/// How a polled attempt ended.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub(super) enum AttemptEnd {
48    Live,
49    Err(ErrorOrigin),
50    Elapsed,
51    /// The awaiting future was dropped, for instance by `$/cancelRequest`.
52    Cancelled,
53}
54
55/// What an attempt says about the endpoint's responsiveness.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub(super) enum AttemptEvidence {
58    Answered,
59    Slow,
60    Inconclusive,
61}
62
63/// Evidence from an attempt that ended as `end` after `waited` against a budget of `budget`,
64/// given what it did on the wire (`contact`).
65///
66/// A response is required to vouch for an endpoint, and a stalled request to accuse it:
67///
68/// - A `Live` result, or an endpoint-attributed `Err`, within the budget minus a margin is
69///   [`AttemptEvidence::Answered`] only if a response arrived. One served from a memo, a fresh
70///   cache entry or a local error never touched the endpoint. A `Live` near the budget is
71///   inconclusive: the HTTP cache serves stale data after a failed revalidation, so it may come
72///   from a dead host.
73/// - An ending after a request was outstanding for at least half the budget, by elapse, cancel
74///   or any error, is [`AttemptEvidence::Slow`]. The stall is busy time since the last response,
75///   so a chain whose first hop answers fast and whose second hangs is slow, a request that
76///   fails after a long wait still counts, and a paginating fetch that keeps receiving
77///   responses is not slow. An attempt that received no response of its own also counts the
78///   time another task's request on the same endpoint was outstanding during its wait (see
79///   [`AttemptContact::observe`]), so a lookup coalesced onto a background fetch's request
80///   accuses the endpoint just as one that sent it would.
81/// - Everything else is [`AttemptEvidence::Inconclusive`]: a promoted request with little
82///   budget left, an early cancel, a fast local failure, a lookup that waited on another task's
83///   lock or single-flight with no request outstanding behind it, and an attempt whose
84///   concurrent requests were partially answered (a response clears the busy time even if a
85///   sibling still hangs).
86pub(super) fn evidence(
87    end: AttemptEnd,
88    contact: Contact,
89    waited: Duration,
90    budget: Duration,
91) -> AttemptEvidence {
92    let responsive = waited < budget.saturating_sub(MARGIN);
93    let answered = contact.response == ResponseSeen::Yes;
94    let stalled = contact.stall >= budget / 2;
95    match end {
96        AttemptEnd::Live if responsive && answered => AttemptEvidence::Answered,
97        AttemptEnd::Live => AttemptEvidence::Inconclusive,
98        AttemptEnd::Err(_) | AttemptEnd::Elapsed | AttemptEnd::Cancelled if stalled => {
99            AttemptEvidence::Slow
100        }
101        AttemptEnd::Err(ErrorOrigin::Endpoint) if responsive && answered => {
102            AttemptEvidence::Answered
103        }
104        AttemptEnd::Err(_) | AttemptEnd::Elapsed | AttemptEnd::Cancelled => {
105            AttemptEvidence::Inconclusive
106        }
107    }
108}
109
110/// The wire view of an attempt: it joins its endpoint's shared ledger only when its evidence
111/// counts and the endpoint is resolved. A decoration never writes shared state, since its
112/// host may differ from the base fetch's.
113fn attempt_contact(counts: BreakerEvidence, endpoint: EndpointKey) -> AttemptContact {
114    match (counts, endpoint) {
115        (
116            BreakerEvidence::Counts,
117            EndpointKey::Resolved {
118                ecosystem,
119                endpoint,
120            },
121        ) => AttemptContact::on_endpoint(ecosystem, endpoint),
122        (BreakerEvidence::Counts, EndpointKey::Scoped { .. }) | (BreakerEvidence::Ignored, _) => {
123            AttemptContact::own_only()
124        }
125    }
126}
127
128/// Reports an attempt's evidence to the breaker exactly once.
129///
130/// Finishing it reports the real end. Dropping it unfinished means the awaiting future was
131/// cancelled, which reports [`AttemptEnd::Cancelled`] — a hover that waited most of the budget
132/// before the editor gave up is evidence the endpoint is slow.
133struct AttemptGuard<'a> {
134    gate: &'a InteractiveFetchGate,
135    lookup: &'a Arc<LookupKey>,
136    generation: u64,
137    started: Instant,
138    probe: Option<ProbeId>,
139    settled: bool,
140    counts: BreakerEvidence,
141    contact: AttemptContact,
142}
143
144impl AttemptGuard<'_> {
145    fn finish(mut self, end: AttemptEnd) {
146        self.settled = true;
147        self.report(end);
148    }
149
150    fn report(&self, end: AttemptEnd) {
151        match self.counts {
152            BreakerEvidence::Counts => {}
153            BreakerEvidence::Ignored => return,
154        }
155        let now = Instant::now();
156        let waited = now.saturating_duration_since(self.started);
157        let (contact, view) = self.contact.observe(now);
158        let evidence = evidence(end, contact, waited, self.lookup.kind().budget());
159        tracing::debug!(
160            ?evidence,
161            view = view.as_str(),
162            stall_ms = u64::try_from(contact.stall.as_millis()).unwrap_or(u64::MAX),
163            lookup = self.lookup.kind().as_str(),
164            "interactive attempt breaker evidence"
165        );
166        if self.gate.generation() != self.generation {
167            return;
168        }
169        let endpoint = self.lookup.route.endpoint();
170        self.gate.breaker.report(
171            &endpoint,
172            &self.lookup.package,
173            evidence,
174            self.probe,
175            super::now(),
176        );
177        // Re-checked after the write, as for the memo: an invalidation in between would
178        // otherwise leave this endpoint's stale evidence behind.
179        if self.gate.generation() != self.generation {
180            self.gate.breaker.forget(&endpoint);
181        }
182    }
183}
184
185impl Drop for AttemptGuard<'_> {
186    fn drop(&mut self) {
187        if !self.settled {
188            self.report(AttemptEnd::Cancelled);
189        }
190    }
191}
192
193/// An error an interactive await may log, exposing only a URL- and credential-free cause.
194///
195/// `Display` and `Debug` of a registry error can embed the raw request URL, so a lookup never
196/// logs them; it logs this coarse classification instead.
197///
198/// # Examples
199///
200/// ```
201/// use deps_core::DepsError;
202/// use deps_core::lsp_helpers::InteractiveFetchError;
203///
204/// let error = DepsError::RecentlyFailed;
205/// assert_eq!(error.log_cause(), (None, "recently-failed"));
206/// assert_eq!(InteractiveFetchError::origin(&error), deps_core::ErrorOrigin::Unattributed);
207/// ```
208pub trait InteractiveFetchError {
209    /// The HTTP status when there is one, plus a short stable cause label.
210    fn log_cause(&self) -> (Option<u16>, &'static str);
211
212    /// Whether the failure is evidence about the registry endpoint, which decides if a fast
213    /// failure vouches for it (see [`ErrorOrigin`]).
214    fn origin(&self) -> ErrorOrigin;
215}
216
217impl InteractiveFetchError for crate::DepsError {
218    fn log_cause(&self) -> (Option<u16>, &'static str) {
219        self.safe_tracing_summary()
220    }
221
222    fn origin(&self) -> ErrorOrigin {
223        Self::origin(self)
224    }
225}
226
227/// For test lookups that carry no error detail.
228#[cfg(test)]
229impl InteractiveFetchError for () {
230    fn log_cause(&self) -> (Option<u16>, &'static str) {
231        (None, "unspecified")
232    }
233
234    fn origin(&self) -> ErrorOrigin {
235        ErrorOrigin::Endpoint
236    }
237}
238
239/// Awaits `fetch` until `deadline`, mapping an error to [`NoLiveList::Failed`] and an elapse to
240/// [`NoLiveList::Unverified`].
241pub(super) async fn bounded_await_until<T, E: InteractiveFetchError>(
242    fetch: impl Future<Output = Result<T, E>>,
243    deadline: Instant,
244    request: &InteractiveFetchRequest<'_>,
245    kind: LookupKind,
246) -> (InteractiveFetch<T>, AttemptEnd) {
247    match tokio::time::timeout_at(deadline, fetch).await {
248        Ok(Ok(value)) => (InteractiveFetch::Live(value), AttemptEnd::Live),
249        Ok(Err(error)) => {
250            let (status, cause) = error.log_cause();
251            tracing::debug!(
252                package = %request.package().for_tracing(),
253                context = request.context.as_str(),
254                lookup = kind.as_str(),
255                ?status,
256                cause,
257                "interactive registry lookup failed"
258            );
259            (
260                InteractiveFetch::Degraded(NoLiveList::Failed),
261                AttemptEnd::Err(error.origin()),
262            )
263        }
264        Err(_) => {
265            tracing::warn!(
266                package = %request.package().for_tracing(),
267                context = request.context.as_str(),
268                lookup = kind.as_str(),
269                timeout_secs = kind.budget().as_secs(),
270                "interactive registry lookup timed out"
271            );
272            (
273                InteractiveFetch::Degraded(NoLiveList::Unverified),
274                AttemptEnd::Elapsed,
275            )
276        }
277    }
278}
279
280/// How [`InteractiveFetchGate::attempt`] ended.
281pub(super) enum Attempted<T> {
282    /// The attempt ran; `budget` says whether a failure of it proves anything.
283    Polled(InteractiveFetch<T>, AttemptBudget),
284    /// The endpoint's breaker is open: nothing was polled and nothing was written.
285    Refused,
286}
287
288impl InteractiveFetchGate {
289    /// Polls `fetch` until `deadline`, tells the endpoint breaker what happened, and records
290    /// the outcome in the memo.
291    ///
292    /// Only an attempt that began with a [`AttemptBudget::Full`] budget writes a failure; a
293    /// truncated one leaves the memo alone. Success records follow the same rules at any budget.
294    pub(super) async fn attempt<T, E: InteractiveFetchError>(
295        &self,
296        fetch: impl Future<Output = Result<T, E>>,
297        deadline: Instant,
298        lookup: &Arc<LookupKey>,
299        request: &InteractiveFetchRequest<'_>,
300        background_failure_known: bool,
301        generation: u64,
302    ) -> Attempted<T> {
303        let counts = lookup.kind().breaker_evidence();
304        let endpoint = lookup.route.endpoint();
305        let probe = match self.admit(&endpoint, request.context, counts) {
306            Admission::Refused => {
307                super::log_skipped(request, "registry endpoint circuit open");
308                return Attempted::Refused;
309            }
310            Admission::Probe(probe) => Some(probe),
311            Admission::Proceed => None,
312        };
313        let started = Instant::now();
314        let budget = AttemptBudget::of(
315            deadline.saturating_duration_since(started),
316            lookup.kind().budget(),
317        );
318        let guard = AttemptGuard {
319            gate: self,
320            lookup,
321            generation,
322            started,
323            probe,
324            settled: false,
325            counts,
326            contact: attempt_contact(counts, endpoint),
327        };
328        let scoped = guard.contact.scope(fetch);
329        let (result, end) = bounded_await_until(scoped, deadline, request, lookup.kind()).await;
330        guard.finish(end);
331        let result = match result {
332            // The background fetch still reports this package as failing, so a stale seeded
333            // record must not flip to fail-open after one TTL.
334            InteractiveFetch::Degraded(NoLiveList::Failed) if background_failure_known => {
335                InteractiveFetch::Degraded(NoLiveList::Unverified)
336            }
337            other => other,
338        };
339        match (&result, background_failure_known, budget) {
340            (InteractiveFetch::Degraded(_), _, AttemptBudget::Full) => {
341                self.record(lookup, RecordState::InteractiveFailed, generation);
342            }
343            (InteractiveFetch::Degraded(_), _, AttemptBudget::Truncated) => {}
344            (InteractiveFetch::Live(_), true, _) => {
345                self.record(lookup, RecordState::InteractiveSucceeded, generation);
346            }
347            // Nothing a success record could override, so it must not occupy the capped memo.
348            (InteractiveFetch::Live(_), false, _) => self.forget_record(lookup),
349        }
350        Attempted::Polled(result, budget)
351    }
352}