deps_core/lsp_helpers/interactive_fetch/
attempt.rs1use 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
17pub(super) const MARGIN: Duration = Duration::from_secs(1);
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub(super) enum AttemptBudget {
29 Full,
31 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub(super) enum AttemptEnd {
48 Live,
49 Err(ErrorOrigin),
50 Elapsed,
51 Cancelled,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub(super) enum AttemptEvidence {
58 Answered,
59 Slow,
60 Inconclusive,
61}
62
63pub(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
110fn 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
128struct 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 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
193pub trait InteractiveFetchError {
209 fn log_cause(&self) -> (Option<u16>, &'static str);
211
212 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#[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
239pub(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
280pub(super) enum Attempted<T> {
282 Polled(InteractiveFetch<T>, AttemptBudget),
284 Refused,
286}
287
288impl InteractiveFetchGate {
289 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 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 (InteractiveFetch::Live(_), false, _) => self.forget_record(lookup),
349 }
350 Attempted::Polled(result, budget)
351 }
352}