use std::collections::HashMap;
use std::future::Future;
use std::net::{SocketAddr, TcpListener};
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::OnceCell;
use super::{StubFormatter, test_uri};
use crate::ecosystem::BoxFuture;
use crate::lsp_helpers::{
DependencyOutcomes, FetchContext, InteractiveFetch, InteractiveFetchGate,
InteractiveFetchRequest, NoLiveList, SharedVersions, VersionData, await_interactive_versions,
};
use crate::{
DependencySource, EcosystemId, EgressTier, FreshnessSettings, HttpCache, PackageKey,
PackageName, Registry, RegistryEndpoint,
};
#[derive(Debug)]
pub struct SilentListener(TcpListener);
impl Default for SilentListener {
fn default() -> Self {
Self::new()
}
}
impl SilentListener {
#[must_use]
pub fn new() -> Self {
Self(TcpListener::bind("127.0.0.1:0").expect("a loopback port must be available"))
}
#[must_use]
pub fn addr(&self) -> SocketAddr {
self.0
.local_addr()
.expect("a bound socket has a local address")
}
}
const GATE_CONCURRENCY: NonZeroUsize = NonZeroUsize::MIN.saturating_add(3);
async fn hover<R: Registry + ?Sized>(
registry: &R,
gate: &InteractiveFetchGate,
ecosystem: EcosystemId,
name: &str,
) -> InteractiveFetch<SharedVersions> {
let package = PackageName::new(name);
let source = DependencySource::Registry;
let outcomes = DependencyOutcomes::new();
let (cached, resolved) = (HashMap::new(), HashMap::new());
let manifest = test_uri("/project/stalled/manifest");
let request = InteractiveFetchRequest::from_parts(
VersionData::new(&cached, &resolved)
.with_ecosystem(ecosystem)
.with_outcomes(&outcomes)
.with_interactive_fetch_gate(gate),
&manifest,
PackageKey::new(&package, &StubFormatter::DEFAULT),
source,
FetchContext::Hover,
);
await_interactive_versions(registry, request, FreshnessSettings::Disabled).await
}
async fn cancelled_hover<R: Registry + ?Sized>(
registry: &R,
gate: &InteractiveFetchGate,
ecosystem: EcosystemId,
name: &str,
after: Duration,
) {
let outcome = tokio::time::timeout(after, hover(registry, gate, ecosystem, name)).await;
assert!(outcome.is_err(), "the hover must still be waiting");
}
pub async fn waiters_open_the_breaker_while<R: Registry + ?Sized>(
registry: &R,
ecosystem: EcosystemId,
packages: [&str; 3],
background: impl Future<Output = ()>,
) -> bool {
let [first, second, third] = packages;
let gate = InteractiveFetchGate::new(GATE_CONCURRENCY);
let hovers = async {
tokio::time::sleep(Duration::from_millis(500)).await;
futures::join!(
cancelled_hover(
registry,
&gate,
ecosystem,
first,
Duration::from_millis(5500)
),
cancelled_hover(
registry,
&gate,
ecosystem,
second,
Duration::from_millis(5500)
),
);
tokio::time::sleep(Duration::from_millis(100)).await;
let started = tokio::time::Instant::now();
let third = hover(registry, &gate, ecosystem, third).await;
matches!(third, InteractiveFetch::Degraded(NoLiveList::Unverified))
&& started.elapsed() < Duration::from_secs(1)
};
let ((), refused) = futures::join!(background, hovers);
refused
}
pub struct StalledCoalescingRegistry {
cache: Arc<HttpCache>,
url: String,
endpoint: RegistryEndpoint,
index: OnceCell<()>,
_socket: SilentListener,
}
impl Default for StalledCoalescingRegistry {
fn default() -> Self {
Self::new()
}
}
impl StalledCoalescingRegistry {
#[must_use]
pub fn new() -> Self {
let socket = SilentListener::new();
let url = format!("http://{}/index", socket.addr());
Self {
cache: Arc::new(HttpCache::new()),
endpoint: RegistryEndpoint::from_base_str(&url, EgressTier::Baseline),
url,
index: OnceCell::new(),
_socket: socket,
}
}
async fn await_index(&self) -> crate::Result<()> {
self.index
.get_or_try_init(|| async { self.cache.get_cached(&self.url).await.map(drop) })
.await?;
Ok(())
}
pub async fn waiters_open_the_breaker_while(
&self,
ecosystem: EcosystemId,
background: impl Future<Output = ()>,
) -> bool {
waiters_open_the_breaker_while(
self,
ecosystem,
["hover-a", "hover-b", "hover-c"],
background,
)
.await
}
}
impl Registry for StalledCoalescingRegistry {
fn get_versions<'a>(
&'a self,
_name: &'a PackageName,
) -> BoxFuture<'a, crate::Result<Vec<Box<dyn crate::Version>>>> {
Box::pin(async move {
self.await_index().await?;
Ok(Vec::new())
})
}
fn get_latest_matching<'a>(
&'a self,
_name: &'a PackageName,
_req: &'a crate::VersionReq,
_selection_context: &'a crate::SelectionContext,
) -> BoxFuture<'a, crate::Result<Option<Box<dyn crate::Version>>>> {
Box::pin(async move {
self.await_index().await?;
Ok(None)
})
}
fn search_raw<'a>(
&'a self,
_query: &'a str,
_limit: usize,
) -> BoxFuture<'a, crate::Result<Vec<Box<dyn crate::Metadata>>>> {
Box::pin(async move { Ok(Vec::new()) })
}
fn endpoint_for(&self, _name: &PackageName, _source: &DependencySource) -> RegistryEndpoint {
self.endpoint
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}