mod attempt;
mod breaker;
mod flight;
mod key;
mod memo;
#[cfg(test)]
mod tests;
use std::future::Future;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use dashmap::DashMap;
use tokio::sync::{Semaphore, watch};
pub use self::attempt::InteractiveFetchError;
use self::attempt::{Attempted, bounded_await_until};
use self::breaker::EndpointBreaker;
use self::flight::{FlightKey, FlightResult, ListShape};
use self::key::{
BackgroundSeed, LookupKey, LookupKind, ManifestFingerprint, PermitPolicy, RouteKey, RouteScope,
SourceFingerprint,
};
use self::memo::{Decision, InteractiveRecord};
use super::VersionData;
use crate::freshness::FreshnessSettings;
use crate::single_flight::Slot;
use crate::{
DependencySource, FetchFailure, NetworkMode, PackageName, Registry, RegistryEndpoint, Version,
};
pub type SharedVersions = Arc<[Box<dyn Version>]>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoLiveList {
Failed,
Unverified,
}
#[derive(Debug)]
pub enum InteractiveFetch<T> {
Live(T),
Degraded(NoLiveList),
}
impl<T> InteractiveFetch<T> {
#[must_use]
pub fn into_live(self) -> Option<T> {
match self {
Self::Live(value) => Some(value),
Self::Degraded(_) => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AuxiliaryLookup {
Decoration,
PinResolution,
LatestFallback,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FetchContext {
Hover,
CodeAction,
}
impl FetchContext {
const fn as_str(self) -> &'static str {
match self {
Self::Hover => "hover",
Self::CodeAction => "code action",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct InteractiveFetchRequest<'a> {
versions: VersionData<'a>,
manifest: &'a url::Url,
package: &'a PackageName,
normalized_name: &'a str,
source: &'a DependencySource,
context: FetchContext,
}
impl<'a> InteractiveFetchRequest<'a> {
#[must_use]
pub const fn new(
versions: VersionData<'a>,
manifest: &'a url::Url,
package: &'a PackageName,
normalized_name: &'a str,
source: &'a DependencySource,
context: FetchContext,
) -> Self {
Self {
versions,
manifest,
package,
normalized_name,
source,
context,
}
}
fn gated<R: Registry + ?Sized>(
&self,
registry: &R,
kind: LookupKind,
) -> Option<(&'a InteractiveFetchGate, Arc<LookupKey>)> {
let gate = self.versions.interactive_fetch?;
let ecosystem = self.versions.ecosystem?;
match self.versions.network {
NetworkMode::Offline => None,
NetworkMode::Online => {
let scope = match registry.endpoint_for(self.package, self.source) {
RegistryEndpoint::Resolved(endpoint) => RouteScope::Endpoint(endpoint),
RegistryEndpoint::Unresolved => {
RouteScope::Manifest(ManifestFingerprint::of(self.manifest))
}
};
let key = LookupKey {
route: RouteKey {
ecosystem,
source: SourceFingerprint::of(self.source),
scope,
},
package: PackageName::new(self.normalized_name),
slot: kind,
};
Some((gate, Arc::new(key)))
}
}
}
fn background_failure_known(&self, kind: LookupKind) -> bool {
match kind.background_seed() {
BackgroundSeed::Applies => {}
BackgroundSeed::Ignored => return false,
}
let failure = self
.versions
.outcomes
.and_then(|outcomes| outcomes.fetch_failure(self.normalized_name));
match failure {
Some(FetchFailure::Actionable(_) | FetchFailure::Transient) => true,
Some(FetchFailure::NotAttempted) | None => false,
}
}
}
fn now() -> Instant {
tokio::time::Instant::now().into_std()
}
fn log_skipped(request: &InteractiveFetchRequest<'_>, reason: &str) {
tracing::debug!(
package = %request.package.for_tracing(),
context = request.context.as_str(),
reason,
"interactive registry await skipped"
);
}
#[derive(Debug)]
pub struct InteractiveFetchGate {
memo: DashMap<Arc<LookupKey>, InteractiveRecord>,
version_flights: DashMap<FlightKey, watch::Receiver<Slot<FlightResult>>>,
breaker: EndpointBreaker,
permits: Semaphore,
generation: AtomicU64,
}
impl InteractiveFetchGate {
#[must_use]
pub fn new(dispatch_concurrency: NonZeroUsize) -> Self {
let permits = dispatch_concurrency.get().saturating_sub(1).max(1);
Self {
memo: DashMap::new(),
version_flights: DashMap::new(),
breaker: EndpointBreaker::default(),
permits: Semaphore::new(permits),
generation: AtomicU64::new(0),
}
}
pub fn invalidate_all(&self) {
self.generation.fetch_add(1, Ordering::SeqCst);
self.memo.clear();
self.breaker.clear();
}
#[must_use]
pub fn len(&self) -> usize {
self.memo.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.memo.is_empty()
}
fn generation(&self) -> u64 {
self.generation.load(Ordering::SeqCst)
}
fn admit_request(
&self,
lookup: &Arc<LookupKey>,
request: &InteractiveFetchRequest<'_>,
) -> Result<Admitted<'_>, NoLiveList> {
let generation = self.generation();
let background_failure_known = request.background_failure_known(lookup.kind());
if let Decision::Degrade(kind, reason) =
self.decide(lookup, background_failure_known, generation, now())
{
log_skipped(request, reason.as_str());
return Err(kind);
}
let permit = match lookup.kind().permit_policy() {
PermitPolicy::Required => {
let Ok(permit) = self.permits.try_acquire() else {
log_skipped(request, "interactive fetch concurrency cap reached");
return Err(NoLiveList::Unverified);
};
Some(permit)
}
PermitPolicy::Exempt => None,
};
Ok(Admitted {
generation,
background_failure_known,
_permit: permit,
})
}
}
struct Admitted<'a> {
generation: u64,
background_failure_known: bool,
_permit: Option<tokio::sync::SemaphorePermit<'a>>,
}
pub async fn await_interactive_fetch<T, E: InteractiveFetchError, R: Registry + ?Sized>(
registry: &R,
fetch: impl Future<Output = Result<T, E>>,
request: InteractiveFetchRequest<'_>,
kind: AuxiliaryLookup,
) -> InteractiveFetch<T> {
let kind = LookupKind::Auxiliary(kind);
let Some((gate, lookup)) = request.gated(registry, kind) else {
return plain_bounded_await(fetch, &request, kind).await;
};
let admitted = match gate.admit_request(&lookup, &request) {
Ok(admitted) => admitted,
Err(kind) => return InteractiveFetch::Degraded(kind),
};
let deadline = tokio::time::Instant::now() + lookup.kind().budget();
match gate
.attempt(
fetch,
deadline,
&lookup,
&request,
admitted.background_failure_known,
admitted.generation,
)
.await
{
Attempted::Polled(result, _) => result,
Attempted::Refused => InteractiveFetch::Degraded(NoLiveList::Unverified),
}
}
pub async fn await_interactive_versions<R: Registry + ?Sized>(
registry: &R,
request: InteractiveFetchRequest<'_>,
freshness: FreshnessSettings,
) -> InteractiveFetch<SharedVersions> {
let fetch = async {
registry
.get_versions_from(request.package, request.source, freshness)
.await
.map(SharedVersions::from)
};
let Some((gate, lookup)) = request.gated(registry, LookupKind::VersionList) else {
return plain_bounded_await(fetch, &request, LookupKind::VersionList).await;
};
flight::await_shared(gate, lookup, fetch, &request, ListShape::of(freshness)).await
}
async fn plain_bounded_await<T, E: InteractiveFetchError>(
fetch: impl Future<Output = Result<T, E>>,
request: &InteractiveFetchRequest<'_>,
kind: LookupKind,
) -> InteractiveFetch<T> {
let (result, _) = bounded_await_until(
fetch,
tokio::time::Instant::now() + kind.budget(),
request,
kind,
)
.await;
result
}