deps_core/registry.rs
1use crate::error::{DepsError, ErrorOrigin, Result};
2use crate::parser::DependencySource;
3use crate::{ConcreteVersion, EcosystemId, PackageName, RegistryEndpoint, VersionReq};
4use dashmap::DashMap;
5use dashmap::mapref::entry::Entry;
6use std::hash::Hash;
7use std::pin::Pin;
8
9/// Whether a version fetch must return publish times for a native release-age window.
10///
11/// [`NotRequired`](Self::NotRequired) keeps each registry's existing request shape;
12/// [`NativeWindow`](Self::NativeWindow) asks for dated versions even when freshness is off.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum PublishTimeDemand {
15 /// No native window applies; fetch exactly what is fetched today.
16 NotRequired,
17 /// A native window applies; publish times are needed.
18 NativeWindow,
19}
20
21impl PublishTimeDemand {
22 /// The demand of a whole document: [`NativeWindow`](Self::NativeWindow) iff at least one of
23 /// its dependencies carries a native window.
24 #[must_use]
25 pub fn for_document(document: &dyn crate::ParsedManifest) -> Self {
26 let mut native = false;
27 document.for_each_formatted_dependency(&mut |bound| {
28 native |= bound.dependency().native_cooldown().is_some();
29 });
30 if native {
31 Self::NativeWindow
32 } else {
33 Self::NotRequired
34 }
35 }
36}
37
38type BoxFuture<'a, T> = Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
39
40/// Declares one `*Any` supertrait: `as_any` under `test`/`test-util`, an empty blanket
41/// marker otherwise, so a production downcast is a compile error rather than a lint.
42macro_rules! test_only_downcast {
43 ($(#[$doc:meta])* $name:ident, $target:literal) => {
44 $(#[$doc])*
45 ///
46 /// With `test` or the `test-util` feature enabled, this trait carries
47 /// `fn as_any(&self) -> &dyn Any` and is implemented for every `'static` type.
48 #[cfg(any(test, feature = "test-util"))]
49 #[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
50 pub trait $name: ::std::any::Any {
51 #[doc = concat!("Downcasts to the concrete ", $target, " type; test-only.")]
52 fn as_any(&self) -> &dyn ::std::any::Any;
53 }
54
55 #[cfg(any(test, feature = "test-util"))]
56 impl<T: ::std::any::Any> $name for T {
57 fn as_any(&self) -> &dyn ::std::any::Any {
58 self
59 }
60 }
61
62 $(#[$doc])*
63 ///
64 /// Without `test` or the `test-util` feature, this trait is an empty marker
65 /// implemented for every type, so no downcast method exists in release builds.
66 #[cfg(not(any(test, feature = "test-util")))]
67 pub trait $name {}
68
69 #[cfg(not(any(test, feature = "test-util")))]
70 impl<T: ?Sized> $name for T {}
71 };
72}
73
74test_only_downcast!(
75 /// Test-only downcast supertrait of [`Registry`].
76 ///
77 /// Blanket-implemented, so registry implementors write nothing for it.
78 RegistryAny,
79 "registry"
80);
81
82test_only_downcast!(
83 /// Test-only downcast supertrait of [`Version`].
84 ///
85 /// Blanket-implemented, so version implementors write nothing for it.
86 VersionAny,
87 "version"
88);
89
90test_only_downcast!(
91 /// Test-only downcast supertrait of [`Metadata`].
92 ///
93 /// Blanket-implemented, so metadata implementors write nothing for it.
94 MetadataAny,
95 "metadata"
96);
97
98/// Generic package registry interface.
99///
100/// Implementors provide access to a package registry (crates.io, npm, PyPI, etc.)
101/// with version lookup, search, and metadata retrieval capabilities.
102///
103/// All methods return `Result<T>` to allow graceful error handling.
104/// LSP handlers must never panic on registry errors.
105///
106/// # Type Erasure
107///
108/// This trait uses `Box<dyn Trait>` return types instead of associated types
109/// to allow runtime polymorphism and dynamic ecosystem registration.
110///
111/// # Registry client API contract (#834)
112///
113/// Each ecosystem crate's own registry struct (`CratesIoRegistry`, `NpmRegistry`,
114/// `MavenCentralRegistry`, ...) additionally exposes a set of **inherent** async methods
115/// with concrete (non-boxed) parameter/return types — this trait's own methods box and
116/// type-erase, which every hover/completion/diagnostic call site needs, but a caller that
117/// already knows the concrete ecosystem (most ecosystem-crate-internal code, and every
118/// conformance test) wants the unboxed value directly. The trait method of the same name is
119/// expected to delegate to its inherent counterpart (see `deps-cargo::registry::CratesIoRegistry`
120/// for the canonical shape). Naming previously drifted per crate (issue #760, #834); the
121/// canonical vocabulary going forward is:
122///
123/// - `get_versions` — fetch all versions.
124/// - `get_versions_with` — fetch all versions plus extra data (e.g. publish dates).
125/// - `get_latest_matching` — fetch the single version matching a requirement.
126/// - `search` — fetch search results for a query.
127/// - `register_alternate` — register an alternate/private registry source.
128/// - `package_url` — build the registry's web-display URL for a package (re-exported from
129/// the crate root wherever it exists).
130/// - `with_base` — construct a registry client pointed at a non-default base URL (tests,
131/// alternate-registry hops); a plain, ungated `with_base` for production use, distinct
132/// from any additional `#[cfg(test)]`/`test-util`-gated constructor a crate also needs
133/// (see `deps-npm::registry::NpmRegistry::with_public_base_for_test` for that shape).
134/// - Pure in-memory getters (no I/O) drop the `get_` prefix entirely, per the Rust API
135/// Guidelines' C-GETTER (e.g. `ResolvedPackages::version`/`all`,
136/// `EcosystemRegistry::for_filename`/`for_uri`/`for_lockfile`/`for_watched_config`).
137///
138/// Two sanctioned, named exceptions to this vocabulary (a deliberate #834 scope decision,
139/// not drift left to fix): ecosystem-specific display-URL builder names (`gem_url` in
140/// `deps-bundler`, `crate_url` in `deps-cargo`, `jsr_package_url` in `deps-deno`) stay as-is
141/// — only re-export consistency was in scope, not the name itself; and the metadata-fetch
142/// **return type** stays per-ecosystem (`GemInfo`/`PackageInfo`/`ArtifactInfo`/`CrateInfo`/
143/// `DenoMetadata`/`GoMetadata`, ...) — only the *method* name converges on
144/// `get_package_metadata`.
145///
146/// [`crate::registry_conformance!`]'s `ty:` form asserts the first four names exist on a
147/// given registry type at compile time (and, since #834 critic S5, actually asserts they
148/// are *inherent* — see [`crate::conformance::NotInherent`]'s own doc), so a future
149/// ecosystem crate cannot silently reintroduce this drift. Wired directly into 9 of the 14
150/// ecosystem crates as of #834; `deps-gradle` reuses `deps-maven`'s `MavenCentralRegistry`
151/// unchanged and so is covered transitively through `deps-maven`'s own check. Four crates
152/// are exempt, each for a distinct, documented reason rather than a silent gap:
153/// - `deps-gitlab-ci` — route-based, no name+version registry concept at all; every one of
154/// the four trait methods is an inline stub in the `Registry` impl itself, with no real
155/// per-package logic anywhere to extract.
156/// - `deps-deno` — `DenoRegistry`, the type that implements `Registry`, is a
157/// scheme-dispatching facade with no single struct holding all four methods (it dispatches
158/// by `jsr:`/`npm:` prefix to either its `JsrRegistry` field or an `NpmRegistry`, with
159/// different call shapes on each side). Note this is a statement about `DenoRegistry`
160/// specifically, not about the crate as a whole: `JsrRegistry` itself already has genuine
161/// inherent `get_versions`/`search`, just not `get_versions_with`/`get_latest_matching`,
162/// and its `get_versions(&self, scope: &str, name: &str)` is a fifth, two-part-key
163/// argument shape for the canonical `get_versions` name (JSR packages are scoped,
164/// `@scope/name`) that this contract's table does not otherwise cover.
165/// - `deps-go`, `deps-github-actions` — both have genuine inherent `get_versions`/
166/// `get_versions_with`/`get_latest_matching`; only `search` is missing, because neither
167/// registry (the Go module proxy, the GitHub tags API) exposes a search endpoint this
168/// crate can call at all. An inherent `search` here would be a fabricated always-empty
169/// stub whose only purpose is satisfying this check, not a real, callable operation — the
170/// `Registry` trait impl's own `search` (also always empty, for the same reason) is the
171/// honest place for that.
172///
173/// # Examples
174///
175/// ```no_run
176/// use deps_core::{Registry, Version, Metadata, PackageName, ConcreteVersion};
177/// use std::pin::Pin;
178///
179/// struct MyRegistry;
180///
181/// #[derive(Clone)]
182/// struct MyVersion { version: ConcreteVersion }
183///
184/// impl Version for MyVersion {
185/// fn version_string(&self) -> &ConcreteVersion { &self.version }
186/// }
187///
188/// #[derive(Clone)]
189/// struct MyMetadata { name: PackageName, latest: ConcreteVersion }
190///
191/// impl Metadata for MyMetadata {
192/// fn name(&self) -> &PackageName { &self.name }
193/// fn description(&self) -> Option<&str> { None }
194/// fn repository(&self) -> Option<&str> { None }
195/// fn documentation(&self) -> Option<&str> { None }
196/// fn latest_version(&self) -> &ConcreteVersion { &self.latest }
197/// }
198///
199/// impl Registry for MyRegistry {
200/// fn get_versions<'a>(&'a self, _name: &'a PackageName)
201/// -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Vec<Box<dyn Version>>>> + Send + 'a>>
202/// {
203/// Box::pin(async move { Ok(vec![Box::new(MyVersion { version: "1.0.0".into() }) as Box<dyn Version>]) })
204/// }
205///
206/// fn get_latest_matching<'a>(&'a self, _name: &'a PackageName, _req: &'a deps_core::VersionReq, _selection_context: &'a deps_core::SelectionContext)
207/// -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Option<Box<dyn Version>>>> + Send + 'a>>
208/// {
209/// Box::pin(async move { Ok(None) })
210/// }
211///
212/// fn search_raw<'a>(&'a self, _query: &'a str, _limit: usize)
213/// -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Vec<Box<dyn Metadata>>>> + Send + 'a>>
214/// {
215/// Box::pin(async move { Ok(vec![]) })
216/// }
217///
218/// }
219/// ```
220pub trait Registry: Send + Sync + RegistryAny {
221 /// Fetches all available versions for a package.
222 ///
223 /// Returns versions sorted newest-first. May include yanked/deprecated versions.
224 ///
225 /// # Errors
226 ///
227 /// Returns error if:
228 /// - Package does not exist
229 /// - Network request fails
230 /// - Response parsing fails
231 fn get_versions<'a>(
232 &'a self,
233 name: &'a PackageName,
234 ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>>;
235
236 /// Like [`get_versions`](Self::get_versions), but lets a registry that can obtain
237 /// [`Version::published_at`] only through an *extra* request gate that request behind
238 /// `freshness.is_enabled()` instead of always paying for it.
239 ///
240 /// Implementors overriding this method MUST keep every other aspect of
241 /// [`get_versions`](Self::get_versions)'s behavior — set, order, and content of the
242 /// returned versions — identical; the only difference the override may introduce is
243 /// populating [`Version::published_at`]. Callers that render publish ages MUST call this
244 /// method rather than [`get_versions`](Self::get_versions): the default implementation
245 /// below simply forwards to `get_versions` and ignores `freshness`, so a caller that
246 /// keeps calling `get_versions` silently gets no freshness signal even from a registry
247 /// that implements this override.
248 ///
249 /// Default: forwards to [`get_versions`](Self::get_versions), ignoring `freshness`. This
250 /// keeps the ten registries with no extra publish-time source unchanged, and keeps
251 /// [`FreshnessSettings`](crate::freshness::FreshnessSettings) — a `Copy + 'static` DTO —
252 /// out of every `Registry::new` signature and the `register!` ecosystem-registration
253 /// macro.
254 fn get_versions_with<'a>(
255 &'a self,
256 name: &'a PackageName,
257 freshness: crate::freshness::FreshnessSettings,
258 ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>> {
259 let _ = freshness;
260 self.get_versions(name)
261 }
262
263 /// Like [`get_versions_with`](Self::get_versions_with), but additionally carries the
264 /// dependency's resolved [`DependencySource`], for a registry that routes a single
265 /// fetch across more than one underlying index (e.g. `deps-cargo`'s `CargoRegistry`,
266 /// which dispatches a `DependencySource::AlternateRegistry` to a private sparse index
267 /// instead of crates.io).
268 ///
269 /// Default: forwards to [`get_versions_with`](Self::get_versions_with), ignoring
270 /// `source` entirely. This keeps every registry with no per-dependency routing concept
271 /// — every ecosystem except Cargo today — bit-identical: `source` is accepted and
272 /// dropped, so a caller migrating to this method from `get_versions_with` changes no
273 /// observable behavior for them.
274 ///
275 /// Callers that know which source a dependency resolved to should call this rather
276 /// than [`get_versions_with`](Self::get_versions_with), even against a registry with no
277 /// override — the whole point is that call sites don't need to know which registries
278 /// route on source and which don't.
279 fn get_versions_from<'a>(
280 &'a self,
281 name: &'a PackageName,
282 source: &'a DependencySource,
283 freshness: crate::freshness::FreshnessSettings,
284 ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>> {
285 let _ = source;
286 self.get_versions_with(name, freshness)
287 }
288
289 /// Whether this registry returns publish times only when asked through
290 /// [`get_versions_from_with_demand`](Self::get_versions_from_with_demand) with
291 /// [`PublishTimeDemand::NativeWindow`].
292 ///
293 /// A document whose demand rises is refetched in full only for such a registry: every other
294 /// one already returns the times its window judges, so a refetch would only add requests.
295 ///
296 /// Pairing: return `true` only if [`get_versions_from_with_demand`](Self::get_versions_from_with_demand)
297 /// fetches times it would not fetch otherwise. Returning `true` without that override makes
298 /// every demand rise refetch for nothing; overriding it without returning `true` leaves
299 /// cached versions undated when a window appears.
300 ///
301 /// Default: `false`.
302 fn honors_publish_time_demand(&self) -> bool {
303 false
304 }
305
306 /// Like [`get_versions_from`](Self::get_versions_from), additionally carrying whether the
307 /// caller needs publish times for a native release-age window.
308 ///
309 /// With [`PublishTimeDemand::NotRequired`] this is identical to
310 /// [`get_versions_from`](Self::get_versions_from). An override may only add `published_at`
311 /// values and must not change the set, order or content of the returned versions.
312 ///
313 /// Default: ignores `demand` and forwards to [`get_versions_from`](Self::get_versions_from),
314 /// which is correct for every registry that already returns publish times regardless of
315 /// freshness settings.
316 fn get_versions_from_with_demand<'a>(
317 &'a self,
318 name: &'a PackageName,
319 source: &'a DependencySource,
320 freshness: crate::freshness::FreshnessSettings,
321 demand: PublishTimeDemand,
322 ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>> {
323 let _ = demand;
324 self.get_versions_from(name, source, freshness)
325 }
326
327 /// Finds the latest version matching a version requirement.
328 ///
329 /// Filter with [`RemovalStatus::blocks_resolution`], never with
330 /// [`RemovalStatus::is_flagged`]. An `AdvisoryDeprecated` version is fully
331 /// installable — excluding it turns an existing package into a false
332 /// "Unknown package" (#347). Under a wildcard/empty requirement
333 /// (`"*"`/`""`, see [`is_existence_wildcard`]) this is an *existence* check ("does this
334 /// package exist / what is its newest version for display purposes"), not an upgrade
335 /// recommendation: an implementation may prefer a non-yanked version but fall back to a
336 /// yanked one rather than returning `None` when no non-yanked version exists — a yanked
337 /// package still exists. `deps-npm` implements this fallback (mirrored by
338 /// [`select_latest_matching`](Self::select_latest_matching)'s wildcard branch on the
339 /// same registry, which every caller reaching this trait method through the shared
340 /// fetch loop actually goes through first); the exception never applies to a concrete
341 /// requirement.
342 ///
343 /// `selection_context` is the caller's [`crate::SelectionContext`] — opaque and
344 /// ecosystem-owned (see that type's own doc), mirroring [`get_versions_with`](Self::get_versions_with)'s
345 /// [`FreshnessSettings`](crate::freshness::FreshnessSettings) precedent for "an optional
346 /// extra parameter most registries ignore"; only the one registry that understands its
347 /// contents (`PackagistRegistry`, via [`crate::SelectionContext::minimum_stability`])
348 /// overrides this method to read it — every other registry ignores it. A caller with no
349 /// ecosystem-specific manifest state to thread passes [`crate::SelectionContext::none()`]
350 /// explicitly (#1444: this parameter is required, not defaulted, so skipping it is always
351 /// a visible, reviewable choice at the call site rather than an easy-to-forget separate
352 /// method name).
353 ///
354 /// # Arguments
355 ///
356 /// * `name` - Package name
357 /// * `req` - Version requirement string (e.g., "^1.0", ">=2.0")
358 /// * `selection_context` - Manifest-scoped selection state; [`crate::SelectionContext::none()`]
359 /// when the caller has none
360 ///
361 /// # Returns
362 ///
363 /// - `Ok(Some(version))` - Latest matching version found
364 /// - `Ok(None)` - No matching version found
365 /// - `Err(_)` - Network or parsing error
366 fn get_latest_matching<'a>(
367 &'a self,
368 name: &'a PackageName,
369 req: &'a VersionReq,
370 selection_context: &'a crate::SelectionContext,
371 ) -> BoxFuture<'a, Result<Option<Box<dyn Version>>>>;
372
373 /// Like [`get_latest_matching`](Self::get_latest_matching), but additionally carries the
374 /// dependency's resolved [`DependencySource`] — the `get_latest_matching`-shaped
375 /// counterpart to [`get_versions_from`](Self::get_versions_from), covering the fallback
376 /// path a caller takes when the list-based pick fails on a non-empty
377 /// [`get_versions_from`](Self::get_versions_from) result (see
378 /// `deps_core::lsp_helpers::hover`'s `list_fallback_latest` and `deps-lsp`'s
379 /// background-fetch fallback for the two call sites this exists for).
380 ///
381 /// Default: forwards to [`get_latest_matching`](Self::get_latest_matching), ignoring
382 /// `source` — every registry with no per-dependency routing concept stays bit-identical,
383 /// exactly as [`get_versions_from`](Self::get_versions_from) does for the list-fetching
384 /// side.
385 fn get_latest_matching_from<'a>(
386 &'a self,
387 name: &'a PackageName,
388 source: &'a DependencySource,
389 req: &'a VersionReq,
390 selection_context: &'a crate::SelectionContext,
391 ) -> BoxFuture<'a, Result<Option<Box<dyn Version>>>> {
392 let _ = source;
393 self.get_latest_matching(name, req, selection_context)
394 }
395
396 /// The network path a fetch of `name` from `source` travels, for fail-fast circuit
397 /// breaking of interactive awaits.
398 ///
399 /// Two lookups with equal [`RegistryEndpoint::Resolved`] values must travel the same
400 /// network path, so a stall of one is evidence about the other. An implementor must derive
401 /// the result from the same routing decision [`get_versions_from`](Self::get_versions_from)
402 /// takes, never from a parallel rule, so the two cannot drift apart.
403 ///
404 /// Default: [`RegistryEndpoint::Unresolved`], which scopes the breaker to the manifest and
405 /// source instead of sharing it, the conservative choice for a registry that cannot say.
406 fn endpoint_for(&self, name: &PackageName, source: &DependencySource) -> RegistryEndpoint {
407 let _ = (name, source);
408 RegistryEndpoint::Unresolved
409 }
410
411 /// Searches for packages by name or keywords.
412 ///
413 /// Returns up to `limit` results sorted by relevance/popularity.
414 ///
415 /// Named `search_raw`, not `search` (#1215): this required method carries no
416 /// credential-bearing-query gate of its own, and a `fn search` provided-method default
417 /// could be silently skipped by an override — an *inherent* `search` on `dyn Registry`
418 /// (below) wraps this method with [`crate::redact::is_credential_or_query_bearing`]
419 /// and cannot be silently overridden by an implementor, unlike a provided trait method
420 /// default — every `&dyn Registry`/`Arc<dyn Registry>` call site through the gate gets it
421 /// automatically. This is a dispatch-level guarantee, not a hard access barrier: `search_raw`
422 /// is still `pub`, so a caller holding a `&dyn Registry` can call it directly and skip the
423 /// gate with one extra token — call it directly only from a context that already knows
424 /// `query` is safe (e.g. a concrete registry's own inherent `search`, which independently
425 /// gates its own callers).
426 ///
427 /// # Errors
428 ///
429 /// Returns error if network request or parsing fails.
430 fn search_raw<'a>(
431 &'a self,
432 query: &'a str,
433 limit: usize,
434 ) -> BoxFuture<'a, Result<Vec<Box<dyn Metadata>>>>;
435
436 /// Whether [`search_raw`](Self::search_raw) matches `query` against a *normalized* form
437 /// of package names rather than the raw typed text.
438 ///
439 /// A `true` implementor guarantees its search is performed against normalized names (e.g.
440 /// PyPI's PEP 503 normalization, which folds `-`/`_`/`.` together), so a returned
441 /// [`Metadata::name`] is not guaranteed to be a literal subsequence of the raw `query` an
442 /// LSP client typed — the caller must not assume `filter_text` defaulting to `label` will
443 /// still match client-side. Callers use this to decide whether a completion response needs
444 /// its `filter_text` rewritten to the raw typed prefix (see
445 /// [`crate::completion::apply_raw_prefix_filter_text`]).
446 ///
447 /// Default `false` — the correct answer for every registry whose search already matches
448 /// literal substrings/prefixes of the raw query, which is every registry in this workspace
449 /// except `deps-pypi`'s `PypiRegistry` (see that crate's own override).
450 ///
451 /// An implementor returning `true` must be paired with its owning
452 /// `EcosystemBase::package_search_is_incomplete` also returning `true`: the client re-issuing a
453 /// fresh search on the very next keystroke (and so discarding this response's rewritten
454 /// `filter_text` rather than continuing to filter it locally forever) is what makes the
455 /// rewrite in [`crate::completion::apply_raw_prefix_filter_text`] safe. This crate has no
456 /// compile-time way to enforce that pairing across the two traits — it is a contract on the
457 /// implementor, not a checked invariant.
458 fn search_normalizes_query(&self) -> bool {
459 false
460 }
461
462 /// Index of the latest version in `versions` satisfying `req`, with no I/O.
463 ///
464 /// Filter with [`RemovalStatus::blocks_resolution`], never with
465 /// [`RemovalStatus::is_flagged`]. An `AdvisoryDeprecated` version is fully
466 /// installable — excluding it turns an existing package into a false
467 /// "Unknown package" (#347). Under a wildcard/empty requirement (see
468 /// [`is_existence_wildcard`]) this is an *existence* check, not an upgrade
469 /// recommendation: Cargo, PyPI, Dart, npm, and Deno implement it by gating on
470 /// [`is_existence_wildcard`] and delegating to [`select_latest_for_existence`].
471 ///
472 /// `versions` must be a newest-first list as returned by this registry's
473 /// [`get_versions`](Self::get_versions). Returns an index rather than a reference so
474 /// callers holding an owned `Vec` can move the chosen element out
475 /// (`versions.into_iter().nth(i)`) — a borrow into the list would keep it frozen while
476 /// [`get_latest_matching`](Self::get_latest_matching) needs to return an owned
477 /// `Box<dyn Version>`, and `Version` has no `clone_box`.
478 ///
479 /// `selection_context` is the caller's [`crate::SelectionContext`] — see
480 /// [`get_latest_matching`](Self::get_latest_matching) for why this parameter is required
481 /// rather than defaulted; every registry with no ecosystem-specific manifest state to
482 /// refine selection with ignores it via this method's own default.
483 ///
484 /// Default: `None`. Every registry reachable from the LSP fetch path overrides this so
485 /// the fetch loop can obtain both "latest" and the full version list from one round
486 /// trip; the default exists so test doubles that never resolve a "latest" compile
487 /// unchanged.
488 fn select_latest_matching(
489 &self,
490 _versions: &[Box<dyn Version>],
491 _req: &VersionReq,
492 _selection_context: &crate::SelectionContext,
493 ) -> Option<usize> {
494 None
495 }
496
497 /// Whether [`get_versions`](Self::get_versions) results carry meaningful
498 /// per-version yank/deprecation data via [`Version::removal_status`].
499 ///
500 /// Default `true`: a registry is opted into the yanked-version diagnostic
501 /// unless it explicitly says it cannot answer. This fails toward
502 /// correctness — a registry whose `removal_status` later becomes real
503 /// data starts participating automatically, by deleting its opt-out
504 /// rather than by someone remembering to add an opt-in. Return `false`
505 /// only when `removal_status()` is hardcoded (e.g. always
506 /// `RemovalStatus::Available`) or otherwise cannot reflect real registry
507 /// data; a `true` return authorizes callers to trust `removal_status()`
508 /// on versions from this registry's normal
509 /// [`get_versions`](Self::get_versions)/
510 /// [`get_latest_matching`](Self::get_latest_matching) results — it does
511 /// not trigger any additional network request.
512 fn reports_yanked(&self) -> bool {
513 true
514 }
515}
516
517impl dyn Registry + '_ {
518 /// Rejects a credential- or query-bearing `query` before it ever reaches
519 /// [`Registry::search_raw`] (#1215), then delegates.
520 ///
521 /// An **inherent** method on the trait object, not a provided trait method: an inherent
522 /// method cannot be shadowed by a `Registry` implementor the way a provided trait method
523 /// can be silently overridden, so every `&dyn Registry`/`Arc<dyn Registry>` call site gets
524 /// this gate automatically, present and future — the same enforcement shape issue #1206
525 /// already established for [`crate::completion::reject_credential_bearing_value`],
526 /// generalized to the trait boundary itself rather than left to each call site to
527 /// remember. This is a dispatch-level guarantee, not a hard access barrier:
528 /// [`Registry::search_raw`] is still `pub`, so a caller holding a `&dyn Registry` can call
529 /// it directly and skip this gate with one extra token — see that method's own doc.
530 ///
531 /// Returns `Ok(vec![])` without calling [`Registry::search_raw`] at all when `query` is
532 /// flagged by [`crate::redact::is_credential_or_query_bearing`] — a redacted value is
533 /// not a useful search term, so the request is dropped rather than redacted-and-sent.
534 ///
535 /// # Errors
536 ///
537 /// Returns error if [`Registry::search_raw`]'s underlying network request or parsing
538 /// fails.
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// use deps_core::Registry;
544 ///
545 /// struct MyRegistry;
546 /// # use deps_core::{Metadata, PackageName, Version};
547 /// # use std::pin::Pin;
548 /// impl Registry for MyRegistry {
549 /// # fn get_versions<'a>(&'a self, _name: &'a PackageName)
550 /// # -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Vec<Box<dyn Version>>>> + Send + 'a>>
551 /// # { Box::pin(async move { Ok(vec![]) }) }
552 /// # fn get_latest_matching<'a>(&'a self, _name: &'a PackageName, _req: &'a deps_core::VersionReq, _selection_context: &'a deps_core::SelectionContext)
553 /// # -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Option<Box<dyn Version>>>> + Send + 'a>>
554 /// # { Box::pin(async move { Ok(None) }) }
555 /// fn search_raw<'a>(&'a self, _query: &'a str, _limit: usize)
556 /// -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Vec<Box<dyn Metadata>>>> + Send + 'a>>
557 /// {
558 /// panic!("must never be reached for a credential-bearing query");
559 /// }
560 /// }
561 ///
562 /// # #[tokio::main]
563 /// # async fn main() {
564 /// let registry: &dyn Registry = &MyRegistry;
565 /// let results = registry
566 /// .search("user:hunter2@registry.example", 10)
567 /// .await
568 /// .unwrap();
569 /// assert!(results.is_empty());
570 /// # }
571 /// ```
572 pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<Box<dyn Metadata>>> {
573 if crate::redact::is_credential_or_query_bearing(query) {
574 crate::lsp_helpers::warn_rejected_value("credential_bearing", "registry search", query);
575 return Ok(vec![]);
576 }
577 self.search_raw(query, limit).await
578 }
579}
580
581/// Whether `version` contains one of the common pre-release substrings
582/// (`-alpha`, `-beta`, `-rc`, `-dev`, `-pre`, `-snapshot`, `-canary`,
583/// `-nightly`), case-insensitively.
584///
585/// This is [`Version::is_prerelease`]'s default heuristic, extracted so an
586/// ecosystem that overrides `is_prerelease` to cover format-specific gaps
587/// (e.g. Composer's `dev-` branch-alias prefix) can extend this baseline
588/// instead of copy-pasting the substring list out of sync with it.
589///
590/// # Examples
591///
592/// ```
593/// use deps_core::has_default_prerelease_marker;
594///
595/// assert!(has_default_prerelease_marker("1.0.0-beta"));
596/// assert!(has_default_prerelease_marker("1.0.0-RC1"));
597/// assert!(!has_default_prerelease_marker("1.0.0"));
598/// ```
599#[must_use]
600pub fn has_default_prerelease_marker(version: &str) -> bool {
601 let v = version.to_lowercase();
602 v.contains("-alpha")
603 || v.contains("-beta")
604 || v.contains("-rc")
605 || v.contains("-dev")
606 || v.contains("-pre")
607 || v.contains("-snapshot")
608 || v.contains("-canary")
609 || v.contains("-nightly")
610}
611
612/// Maps a `404` (plus any status in `also_not_found`) [`DepsError::HttpStatus`] to
613/// [`DepsError::PackageNotFound`], passing through any other error unchanged.
614///
615/// The result is an [`ErrorOrigin::Endpoint`] not-found (#1854): it consumes an HTTP status the
616/// caller received, so it vouches for the endpoint. That is a contract on the caller, not
617/// something the types enforce.
618///
619/// Extracted from four byte-identical copies of this mapper in `deps-pypi`, `deps-deno`,
620/// `deps-npm`, and `deps-go` (deps-lsp#929 item 1). `also_not_found` keeps ecosystem-specific
621/// extra statuses explicit at the call site instead of hardcoded here — `deps-go` passes
622/// `&[410]` for the Go module proxy's "retracted" status, which the other three ecosystems
623/// must not silently inherit.
624///
625/// # Examples
626///
627/// ```
628/// use deps_core::DepsError;
629/// use deps_core::redact::RedactedUrl;
630/// use deps_core::not_found_or;
631///
632/// let url = RedactedUrl::new("https://example.test/pkg");
633/// let not_found = DepsError::HttpStatus {
634/// url: url.clone(),
635/// status: 404,
636/// };
637/// assert!(matches!(
638/// not_found_or(not_found, "pkg", "example", &[]),
639/// DepsError::PackageNotFound { .. }
640/// ));
641///
642/// let server_error = DepsError::HttpStatus { url, status: 500 };
643/// assert!(matches!(
644/// not_found_or(server_error, "pkg", "example", &[]),
645/// DepsError::HttpStatus { status: 500, .. }
646/// ));
647/// ```
648#[must_use]
649pub fn not_found_or(
650 err: DepsError,
651 package: &str,
652 registry: &'static str,
653 also_not_found: &[u16],
654) -> DepsError {
655 match err {
656 DepsError::HttpStatus { status, .. }
657 if status == 404 || also_not_found.contains(&status) =>
658 {
659 DepsError::not_found_at_endpoint(package, registry)
660 }
661 other => other,
662 }
663}
664
665/// Accumulates the provenance of the misses along an alternate-registry chain, so the
666/// not-found a chain finally reports vouches for an endpoint iff some hop actually reached one
667/// (#1854).
668///
669/// # Examples
670///
671/// ```
672/// use deps_core::DepsError;
673/// use deps_core::error::ErrorOrigin;
674/// use deps_core::registry::ChainNotFound;
675///
676/// let mut chain = ChainNotFound::new();
677/// chain.record(&DepsError::not_found_locally("pkg", "npm"));
678/// assert_eq!(chain.error("pkg", "npm").origin(), ErrorOrigin::Unattributed);
679///
680/// chain.record_answered_empty();
681/// assert_eq!(chain.error("pkg", "npm").origin(), ErrorOrigin::Endpoint);
682/// ```
683#[derive(Debug, Clone, Copy)]
684pub struct ChainNotFound {
685 origin: ErrorOrigin,
686}
687
688impl ChainNotFound {
689 /// A chain that has not reached any endpoint yet.
690 #[must_use]
691 pub const fn new() -> Self {
692 Self {
693 origin: ErrorOrigin::Unattributed,
694 }
695 }
696
697 /// Folds in a hop's not-found, keeping any endpoint involvement it carries.
698 pub fn record(&mut self, miss: &DepsError) {
699 self.origin = self.origin.merge(miss.origin());
700 }
701
702 /// Folds in a hop that answered successfully with no versions. The caller attests that a
703 /// response was received; the type cannot check it.
704 pub fn record_answered_empty(&mut self) {
705 self.origin = self.origin.merge(ErrorOrigin::Endpoint);
706 }
707
708 /// The not-found the whole chain reports, carrying the accumulated origin.
709 #[must_use]
710 pub fn error(&self, package: &str, registry: &'static str) -> DepsError {
711 match self.origin {
712 ErrorOrigin::Endpoint => DepsError::not_found_at_endpoint(package, registry),
713 ErrorOrigin::Unattributed => DepsError::not_found_locally(package, registry),
714 }
715 }
716}
717
718impl Default for ChainNotFound {
719 fn default() -> Self {
720 Self::new()
721 }
722}
723
724/// Classifies a manifest-declared registry URL against an ecosystem's own default-registry
725/// aliases.
726///
727/// A URL matching one of `default_urls` (ignoring a trailing slash) resolves to
728/// [`DependencySource::Registry`]; anything else has no client this LSP can query, so it
729/// becomes [`DependencySource::CustomRegistry`].
730///
731/// Extracted from byte-identical logic independently added to `deps-bundler` (rubygems.org)
732/// and `deps-dart` (pub.dev, plus its legacy `pub.dartlang.org` alias) in the same change
733/// (deps-lsp#980) — this project's cross-ecosystem-consistency rule treats that pattern as a
734/// bug class rather than an acceptable duplication (see `.claude/CLAUDE.md`, and the #976/#969
735/// precedent of centralizing similarly-shaped per-crate logic into `deps-core`).
736///
737/// # Examples
738///
739/// ```
740/// use deps_core::DependencySource;
741/// use deps_core::classify_default_registry_url;
742///
743/// assert_eq!(
744/// classify_default_registry_url("https://rubygems.org".to_string(), &["https://rubygems.org"]),
745/// DependencySource::Registry
746/// );
747///
748/// // A trailing slash is ignored when comparing against the default list.
749/// assert_eq!(
750/// classify_default_registry_url("https://pub.dev/".to_string(), &["https://pub.dev", "https://pub.dartlang.org"]),
751/// DependencySource::Registry
752/// );
753///
754/// assert_eq!(
755/// classify_default_registry_url("https://gems.mycorp.com".to_string(), &["https://rubygems.org"]),
756/// DependencySource::CustomRegistry { url: "https://gems.mycorp.com".to_string() }
757/// );
758/// ```
759#[must_use]
760pub fn classify_default_registry_url(url: String, default_urls: &[&str]) -> DependencySource {
761 let normalized = url.trim_end_matches('/');
762 if default_urls.contains(&normalized) {
763 DependencySource::Registry
764 } else {
765 DependencySource::CustomRegistry { url }
766 }
767}
768
769/// Hashes an ordered sequence of `&str` routing-hop parts into an opaque
770/// `"{prefix}:{digest:016x}"` chain-identity key, using
771/// [`std::collections::hash_map::DefaultHasher`].
772///
773/// Extracted from three independently hand-rolled copies of this exact pattern
774/// (`deps_pypi::config::ResolvedChain::chain`, `deps_nuget::config::NuGetSourceChain::chain`,
775/// `deps_go::config::GoProxyChain::keyed`, #579) so "never hash a credential" is a property of
776/// one function signature instead of a convention repeated in three doc comments.
777///
778/// Deliberately takes `&str`, not `impl Hash`: a caller with a typed credential wrapper (e.g.
779/// `NuGetAuth`, which deliberately does not derive `Hash` — see its doc) must explicitly
780/// convert it to a string before it can even be considered here, rather than being able to
781/// `.hash()` the whole struct in place. Prefer a small, explicit, non-`Debug` `as_key_str()`-
782/// style accessor on the hashed field's own type over `format!("{value:?}")` at the call
783/// site — chain identity would otherwise silently change if that type's `Debug` output is
784/// ever reworded (e.g. an enum variant rename), even though nothing routing-relevant changed.
785///
786/// **Security invariant**: `parts` must contain only routing-identity data (URLs, slot/hop
787/// kind markers, boolean flags) — **never** credential material. Hashing a credential would
788/// make the chain's identity key change whenever that credential value rotates, defeating
789/// rotation-stability guarantees callers rely on (e.g. NuGet issue #561's FR-016). This
790/// function has no way to enforce that; it is a caller obligation.
791///
792/// # Examples
793///
794/// ```
795/// use deps_core::hash_routing_key;
796///
797/// let key = hash_routing_key("pypi-chain", ["https://example.test/simple/", "true"].into_iter());
798/// assert!(key.starts_with("pypi-chain:"));
799/// assert_eq!(key.len(), "pypi-chain:".len() + 16);
800///
801/// // Same parts, same key — deterministic within a process.
802/// let key2 = hash_routing_key("pypi-chain", ["https://example.test/simple/", "true"].into_iter());
803/// assert_eq!(key, key2);
804///
805/// // Hop order is part of the identity.
806/// let forward = hash_routing_key("go-proxy", ["a", "b"].into_iter());
807/// let reversed = hash_routing_key("go-proxy", ["b", "a"].into_iter());
808/// assert_ne!(forward, reversed);
809/// ```
810#[must_use]
811pub fn hash_routing_key<'a>(prefix: &str, parts: impl Iterator<Item = &'a str>) -> String {
812 use std::hash::{Hash, Hasher};
813
814 let mut hasher = std::collections::hash_map::DefaultHasher::new();
815 for part in parts {
816 part.hash(&mut hasher);
817 }
818 format!("{prefix}:{:016x}", hasher.finish())
819}
820
821/// Outcome of a registry's per-version removal/deprecation signal.
822///
823/// Replaces a bare `is_yanked(): bool`, which could not distinguish a version
824/// a registry has *hard-removed from resolution* (`Yanked`) from one that is
825/// merely flagged as deprecated/abandoned but still fully installable
826/// (`AdvisoryDeprecated`). Conflating the two caused #347: Composer's
827/// package-level `abandoned` flag was read through `is_yanked()`, so every
828/// version of an abandoned-but-installable package was filtered out of
829/// resolution, turning an existing package into a false "Unknown package"
830/// diagnostic.
831///
832/// Call [`blocks_resolution`](Self::blocks_resolution) to decide whether a
833/// version may be selected as an upgrade/latest candidate. Call
834/// [`is_flagged`](Self::is_flagged) only to surface the registry's flag to
835/// the user (e.g. a yanked/deprecated diagnostic) — never to filter
836/// resolution.
837///
838/// # Examples
839///
840/// ```
841/// use deps_core::RemovalStatus;
842///
843/// assert!(!RemovalStatus::Available.blocks_resolution());
844/// assert!(!RemovalStatus::AdvisoryDeprecated.blocks_resolution());
845/// assert!(RemovalStatus::Yanked.blocks_resolution());
846///
847/// assert!(RemovalStatus::AdvisoryDeprecated.is_flagged());
848/// assert!(RemovalStatus::Yanked.is_flagged());
849/// assert!(!RemovalStatus::Available.is_flagged());
850/// ```
851#[non_exhaustive]
852#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
853pub enum RemovalStatus {
854 /// The registry reports no removal/deprecation signal for this version.
855 Available,
856 /// The registry flags this version (or its package) as
857 /// deprecated/abandoned, but the version remains fully resolvable and
858 /// installable.
859 AdvisoryDeprecated,
860 /// The registry has hard-removed this version from fresh resolution (a
861 /// real yank/retraction). Existing installs may keep using it, but it
862 /// must not be selected as an upgrade/latest candidate.
863 Yanked,
864}
865
866impl RemovalStatus {
867 /// Whether fresh resolution must skip this version.
868 ///
869 /// `true` only for [`Yanked`](Self::Yanked). An
870 /// [`AdvisoryDeprecated`](Self::AdvisoryDeprecated) version is fully
871 /// installable — excluding it from resolution is what caused #347.
872 ///
873 /// # Examples
874 ///
875 /// ```
876 /// use deps_core::RemovalStatus;
877 ///
878 /// assert!(!RemovalStatus::AdvisoryDeprecated.blocks_resolution());
879 /// assert!(RemovalStatus::Yanked.blocks_resolution());
880 /// ```
881 #[must_use]
882 pub const fn blocks_resolution(self) -> bool {
883 matches!(self, Self::Yanked)
884 }
885
886 /// Whether the registry flags this version at all, hard or advisory.
887 ///
888 /// Use this only to decide whether to surface a warning to the user —
889 /// never to filter resolution; use
890 /// [`blocks_resolution`](Self::blocks_resolution) for that.
891 ///
892 /// # Examples
893 ///
894 /// ```
895 /// use deps_core::RemovalStatus;
896 ///
897 /// assert!(!RemovalStatus::Available.is_flagged());
898 /// assert!(RemovalStatus::AdvisoryDeprecated.is_flagged());
899 /// assert!(RemovalStatus::Yanked.is_flagged());
900 /// ```
901 #[must_use]
902 pub const fn is_flagged(self) -> bool {
903 !matches!(self, Self::Available)
904 }
905
906 /// Builds a status from a registry's hard yanked/retracted boolean flag.
907 ///
908 /// # Examples
909 ///
910 /// ```
911 /// use deps_core::RemovalStatus;
912 ///
913 /// assert_eq!(RemovalStatus::from_yanked(true), RemovalStatus::Yanked);
914 /// assert_eq!(RemovalStatus::from_yanked(false), RemovalStatus::Available);
915 /// ```
916 #[must_use]
917 pub const fn from_yanked(flag: bool) -> Self {
918 if flag { Self::Yanked } else { Self::Available }
919 }
920
921 /// Builds a status from a registry's advisory deprecated/abandoned boolean flag.
922 ///
923 /// # Examples
924 ///
925 /// ```
926 /// use deps_core::RemovalStatus;
927 ///
928 /// assert_eq!(RemovalStatus::from_advisory(true), RemovalStatus::AdvisoryDeprecated);
929 /// assert_eq!(RemovalStatus::from_advisory(false), RemovalStatus::Available);
930 /// ```
931 #[must_use]
932 pub const fn from_advisory(flag: bool) -> Self {
933 if flag {
934 Self::AdvisoryDeprecated
935 } else {
936 Self::Available
937 }
938 }
939}
940
941/// Package-level deprecation/abandonment payload: why a package is deprecated, and what
942/// to use instead.
943///
944/// Distinct from [`RemovalStatus`], which answers *"may resolution select this
945/// version"*. `Deprecation` answers *"what should the user be told"* — the reason text
946/// and/or a registry-supplied replacement package name. Kept as a separate type rather
947/// than a payload-carrying `RemovalStatus` variant: `RemovalStatus` is `Copy`, returned
948/// from `const fn`s, and matched in every ecosystem crate, so widening it would ripple
949/// everywhere for a concept that only a couple of registries expose.
950///
951/// Both fields are `None` when the registry has nothing to say beyond "deprecated" —
952/// e.g. Packagist's bare `"abandoned": true`, with no replacement named.
953///
954/// # Examples
955///
956/// ```
957/// use deps_core::Deprecation;
958///
959/// let deprecation = Deprecation {
960/// reason: Some("no longer maintained".into()),
961/// replacement: Some("some-other/package".into()),
962/// };
963///
964/// assert_eq!(deprecation.reason.as_deref(), Some("no longer maintained"));
965/// assert_eq!(deprecation.replacement.as_deref(), Some("some-other/package"));
966/// ```
967// Exhaustive, not `#[non_exhaustive]`: 25+ existing struct-literal sites across `deps-npm`,
968// `deps-composer`, and `deps-lsp` already build this by field, not worth migrating for a
969// two-field type (issue #755).
970#[derive(Debug, Clone, PartialEq, Eq)]
971pub struct Deprecation {
972 /// Free-text reason the registry gives for the deprecation, if any.
973 pub reason: Option<String>,
974 /// Registry-supplied replacement package name, if any. Only ever populated from a
975 /// structured registry field (never regex-extracted from free text — see #205's
976 /// typosquatting rationale), so it is safe to offer as a rename target.
977 pub replacement: Option<String>,
978}
979
980/// Version information trait.
981///
982/// All version types must implement this to work with generic handlers.
983pub trait Version: Send + Sync + VersionAny {
984 /// Version string (e.g., "1.0.214", "14.21.3").
985 fn version_string(&self) -> &ConcreteVersion;
986
987 /// This version's removal/deprecation status as reported by the registry.
988 ///
989 /// Default: [`RemovalStatus::Available`] — ecosystems with no
990 /// yank/deprecation signal need no override.
991 fn removal_status(&self) -> RemovalStatus {
992 RemovalStatus::Available
993 }
994
995 /// Package-level deprecation payload, when this version's registry data carries one.
996 ///
997 /// Default `None` — the `Option` is the capability gate: an ecosystem that never
998 /// overrides this produces no deprecation diagnostic/hover/quickfix at all, rather
999 /// than depending on a separate "does this ecosystem report deprecation" predicate.
1000 fn deprecation(&self) -> Option<&Deprecation> {
1001 None
1002 }
1003
1004 /// Whether this version is a pre-release (alpha, beta, rc, etc.).
1005 ///
1006 /// Default implementation checks for common pre-release patterns via
1007 /// [`has_default_prerelease_marker`].
1008 fn is_prerelease(&self) -> bool {
1009 has_default_prerelease_marker(self.version_string().as_str())
1010 }
1011
1012 /// Available feature flags (empty if not supported by ecosystem).
1013 fn features(&self) -> Vec<String> {
1014 vec![]
1015 }
1016
1017 /// Whether this version is stable: not hard-yanked and not a pre-release.
1018 ///
1019 /// An [`AdvisoryDeprecated`](RemovalStatus::AdvisoryDeprecated) version counts as
1020 /// stable here — it remains fully resolvable, just flagged. Only
1021 /// [`Yanked`](RemovalStatus::Yanked) disqualifies a version; see
1022 /// [`RemovalStatus::blocks_resolution`].
1023 fn is_stable(&self) -> bool {
1024 !self.removal_status().blocks_resolution() && !self.is_prerelease()
1025 }
1026
1027 /// When this version was published, if the registry exposes it.
1028 ///
1029 /// Default `None` — ecosystems without publish metadata (or where
1030 /// fetching it would add a network round trip) degrade to pre-feature
1031 /// behavior: no freshness signal shown, no error, no change in ranking.
1032 fn published_at(&self) -> Option<crate::freshness::PublishTime> {
1033 None
1034 }
1035
1036 /// SPDX license identifier(s) declared for this version, when the registry's
1037 /// already-fetched version-list response carries them.
1038 ///
1039 /// Default: empty slice — the capability gate for ecosystems whose hot-path
1040 /// version fetch doesn't carry license data (issue #204). `Vec<String>`, never
1041 /// `Option<String>`, everywhere this is implemented: a package can declare more
1042 /// than one license (an SPDX `OR`/dual-license split reported as discrete
1043 /// identifiers by the registry), and a single shape avoids an `Option` vs `Vec`
1044 /// split across ecosystems (spec 010 plan.md's "License shape" decision). An
1045 /// empty slice means "unknown/not reported", never "explicitly no license".
1046 fn license(&self) -> &[String] {
1047 &[]
1048 }
1049}
1050
1051/// Finds the latest stable version from a list of versions.
1052///
1053/// Returns the first version that is:
1054/// - Not hard-yanked ([`RemovalStatus::Yanked`]) — an
1055/// [`AdvisoryDeprecated`](RemovalStatus::AdvisoryDeprecated) version still counts as
1056/// stable, since it remains fully resolvable
1057/// - Not a pre-release (alpha, beta, rc, etc.)
1058///
1059/// Assumes versions are sorted newest-first (as returned by registries).
1060///
1061/// # Examples
1062///
1063/// ```
1064/// use deps_core::registry::{RemovalStatus, Version, find_latest_stable};
1065/// use deps_core::ConcreteVersion;
1066///
1067/// struct MyVersion { version: ConcreteVersion, yanked: bool }
1068///
1069/// impl Version for MyVersion {
1070/// fn version_string(&self) -> &ConcreteVersion { &self.version }
1071/// fn removal_status(&self) -> RemovalStatus { RemovalStatus::from_yanked(self.yanked) }
1072/// }
1073///
1074/// let versions: Vec<Box<dyn Version>> = vec![
1075/// Box::new(MyVersion { version: "2.0.0-alpha.1".into(), yanked: false }),
1076/// Box::new(MyVersion { version: "1.5.0".into(), yanked: true }),
1077/// Box::new(MyVersion { version: "1.4.0".into(), yanked: false }),
1078/// ];
1079///
1080/// let latest = find_latest_stable(&versions);
1081/// assert_eq!(latest.map(|v| v.version_string().as_str()), Some("1.4.0"));
1082/// ```
1083pub fn find_latest_stable(versions: &[Box<dyn Version>]) -> Option<&dyn Version> {
1084 versions.iter().find(|v| v.is_stable()).map(|v| v.as_ref())
1085}
1086
1087/// Whether `req` is a wildcard/empty requirement (`""` or `"*"`, ignoring surrounding
1088/// whitespace) rather than a concrete version constraint.
1089///
1090/// A wildcard requirement turns [`get_latest_matching`](Registry::get_latest_matching) and
1091/// [`select_latest_matching`](Registry::select_latest_matching) into an *existence* check
1092/// ("does this package exist / what is its newest version for display purposes") instead of
1093/// an upgrade recommendation — see [`select_latest_for_existence`], which callers must gate
1094/// on this function before use.
1095///
1096/// # Examples
1097///
1098/// ```
1099/// use deps_core::{VersionReq, is_existence_wildcard};
1100///
1101/// assert!(is_existence_wildcard(&VersionReq::new("*")));
1102/// assert!(is_existence_wildcard(&VersionReq::new("")));
1103/// assert!(!is_existence_wildcard(&VersionReq::new("^1.2")));
1104/// ```
1105#[must_use]
1106pub fn is_existence_wildcard(req: &crate::VersionReq) -> bool {
1107 is_existence_wildcard_str(req.as_str())
1108}
1109
1110/// [`is_existence_wildcard`] for a raw `&str`, without allocating a [`VersionReq`] wrapper.
1111///
1112/// Exists for callers that hold a version requirement as `&str` rather than a `VersionReq`
1113/// (e.g. an inherent method taking `req_str: &str` for its own parsing needs) — going through
1114/// [`is_existence_wildcard`] there would allocate a `String` via `VersionReq::new` on every
1115/// call just to check it.
1116///
1117/// # Examples
1118///
1119/// ```
1120/// use deps_core::registry::is_existence_wildcard_str;
1121///
1122/// assert!(is_existence_wildcard_str("*"));
1123/// assert!(is_existence_wildcard_str(""));
1124/// assert!(!is_existence_wildcard_str("^1.2"));
1125/// ```
1126#[must_use]
1127pub fn is_existence_wildcard_str(req: &str) -> bool {
1128 matches!(req.trim(), "" | "*")
1129}
1130
1131/// Builds the canonical existence-check requirement (`"*"`) [`is_existence_wildcard`] recognizes.
1132///
1133/// [`Registry::select_latest_matching`] callers pass this when they want "the newest version
1134/// for display purposes" rather than an upgrade recommendation against a real constraint.
1135/// Centralizes what was three independent `VersionReq::new("*")` call sites (hover, version
1136/// completion, code-action quick-fixes) all constructing the identical value for the
1137/// identical purpose.
1138///
1139/// # Examples
1140///
1141/// ```
1142/// use deps_core::{existence_wildcard_req, is_existence_wildcard};
1143///
1144/// assert!(is_existence_wildcard(&existence_wildcard_req()));
1145/// ```
1146#[must_use]
1147pub fn existence_wildcard_req() -> crate::VersionReq {
1148 crate::VersionReq::new("*")
1149}
1150
1151/// Index of the version an *existence* check should report as "latest", ignoring `req`
1152/// entirely.
1153///
1154/// This is the shared 3-rung fallback ladder used under a wildcard/empty requirement, where
1155/// every version satisfies by definition and the question is only which one to prefer for
1156/// display:
1157///
1158/// 1. The newest version that is neither flagged
1159/// ([`RemovalStatus::is_flagged`]) nor a pre-release ([`Version::is_prerelease`]).
1160/// 2. Else, the newest version that does not block resolution
1161/// ([`RemovalStatus::blocks_resolution`]) — an `AdvisoryDeprecated` version counts here.
1162/// 3. Else, index `0` unconditionally — the newest version overall, however it is flagged.
1163/// A yanked-or-prerelease-only package still exists; this rung is what turns that case
1164/// into "here is its newest version" instead of a false "Unknown package" (#347, #364).
1165///
1166/// `versions` must be sorted newest-first, as returned by [`Registry::get_versions`]. Returns
1167/// `None` only when `versions` is empty.
1168///
1169/// # Requirement-blindness is deliberate and dangerous
1170///
1171/// This function takes no `req` parameter and does not check whether the caller is under a
1172/// wildcard requirement — it always returns rung 3 as a last resort, regardless of what a
1173/// concrete requirement might demand. It is **only correct once the caller has already
1174/// confirmed the requirement is a wildcard** via [`is_existence_wildcard`]. Calling it
1175/// ungated — e.g. under a concrete `^1.2` requirement — can return a version that does not
1176/// satisfy that requirement at all, silently corrupting upgrade resolution.
1177///
1178/// # Examples
1179///
1180/// ```
1181/// use deps_core::registry::{RemovalStatus, Version, select_latest_for_existence};
1182/// use deps_core::ConcreteVersion;
1183///
1184/// struct MyVersion { version: ConcreteVersion, status: RemovalStatus, prerelease: bool }
1185///
1186/// impl Version for MyVersion {
1187/// fn version_string(&self) -> &ConcreteVersion { &self.version }
1188/// fn removal_status(&self) -> RemovalStatus { self.status }
1189/// fn is_prerelease(&self) -> bool { self.prerelease }
1190/// }
1191///
1192/// // Newest version is yanked; rung 3 still returns it rather than `None`.
1193/// let versions = vec![
1194/// MyVersion { version: "2.0.0".into(), status: RemovalStatus::Yanked, prerelease: false },
1195/// MyVersion { version: "1.5.0".into(), status: RemovalStatus::Yanked, prerelease: false },
1196/// ];
1197///
1198/// let idx = select_latest_for_existence(&versions, |v| v as &dyn Version);
1199/// assert_eq!(idx, Some(0));
1200///
1201/// assert_eq!(select_latest_for_existence::<MyVersion>(&[], |v| v as &dyn Version), None);
1202/// ```
1203#[must_use]
1204pub fn select_latest_for_existence<T>(
1205 versions: &[T],
1206 as_version: impl Fn(&T) -> &dyn Version,
1207) -> Option<usize> {
1208 if versions.is_empty() {
1209 return None;
1210 }
1211 Some(
1212 versions
1213 .iter()
1214 .position(|v| {
1215 let v = as_version(v);
1216 !v.removal_status().is_flagged() && !v.is_prerelease()
1217 })
1218 .or_else(|| {
1219 versions
1220 .iter()
1221 .position(|v| !as_version(v).removal_status().blocks_resolution())
1222 })
1223 .unwrap_or(0),
1224 )
1225}
1226
1227/// Package metadata trait.
1228///
1229/// Used for completion items and hover documentation.
1230pub trait Metadata: Send + Sync + MetadataAny {
1231 /// The package name as the *registry* reports it.
1232 ///
1233 /// This is the identifier the registry displays and that completion
1234 /// pastes into a manifest. It is not guaranteed byte-identical to the
1235 /// manifest-declared [`Dependency::name`](crate::ecosystem::Dependency::name)
1236 /// for the same package: casing may differ (NuGet, Composer, Swift), and
1237 /// for Maven/Gradle it is a `"group:artifact"` value synthesized from two
1238 /// separate response fields. Do not compare it to a manifest name
1239 /// without going through
1240 /// [`NormalizeName::normalize_package_name`](crate::lsp_helpers::NormalizeName::normalize_package_name).
1241 fn name(&self) -> &crate::PackageName;
1242
1243 /// Short description (optional).
1244 fn description(&self) -> Option<&str>;
1245
1246 /// Repository URL (optional).
1247 fn repository(&self) -> Option<&str>;
1248
1249 /// Documentation URL (optional).
1250 fn documentation(&self) -> Option<&str>;
1251
1252 /// Latest stable version.
1253 fn latest_version(&self) -> &ConcreteVersion;
1254}
1255
1256/// The error for a dependency whose `AlternateRegistry` index has no registered client.
1257///
1258/// Every routing registry answers this way instead of falling back to the public registry,
1259/// which would send a private package name there.
1260///
1261/// # Examples
1262///
1263/// ```
1264/// use deps_core::PackageName;
1265/// use deps_core::registry::alternate_not_registered;
1266///
1267/// let error = alternate_not_registered(&PackageName::new("internal"));
1268/// assert!(error.is_not_found());
1269/// ```
1270#[must_use]
1271pub fn alternate_not_registered(name: &PackageName) -> DepsError {
1272 DepsError::not_found_locally(name.as_str(), "alternate registry (not registered)")
1273}
1274
1275/// Shared capacity ceiling for a per-ecosystem alternate-registry client map.
1276///
1277/// Reached via each ecosystem's own `register_alternate` (`Cargo`, `npm`, `PyPI`, `NuGet`,
1278/// `Go`, #976). Once reached, a not-yet-registered key is refused rather than evicting an
1279/// existing, possibly still-in-use, client.
1280pub const MAX_ALTERNATE_REGISTRIES: usize = 256;
1281
1282/// How a [`register_capped`]/[`register_capped_with_occupied`] key must be rendered in the
1283/// cap-reached log line (#969 S3).
1284///
1285/// A URL-shaped key is redacted via [`crate::redact::RedactedUrl`]; an already-opaque
1286/// token (e.g. a [`hash_routing_key`] digest) is logged verbatim, since `RedactedUrl`'s
1287/// Maven-coordinate/REST-path false-positive scan would otherwise collapse every such key —
1288/// which is exactly one colon plus a hex digest, the shape that scan is designed to catch —
1289/// to an identical, information-free `"<prefix>:***"`, destroying the very correlation handle
1290/// the log line exists to provide. A closed, two-variant choice rather than an open `Display`
1291/// bypass: a call site declares which shape its key is, but cannot smuggle an unredacted URL
1292/// through under the `Opaque` label by accident in the type system's own vocabulary — though
1293/// nothing stops a caller from mislabeling one at the value level, so get this right: labeling
1294/// a URL-shaped key `Opaque` leaks any query-string credential it carries (the dangerous
1295/// direction); labeling an opaque token `Url` only over-redacts a value that had no secret to
1296/// begin with (the safe direction).
1297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1298pub enum KeyShape {
1299 /// Redact via [`crate::redact::RedactedUrl`] before logging.
1300 Url,
1301 /// Log verbatim — this value is known to never carry a credential (e.g. a
1302 /// [`hash_routing_key`] digest, or another fixed, non-URL literal).
1303 Opaque,
1304}
1305
1306/// Outcome of a [`register_capped`]/[`register_capped_with_occupied`] call.
1307///
1308/// `#[non_exhaustive]`: this is a result-shaped enum (introduced in #1218), and a distinct
1309/// outcome for a new capacity-related edge case is a realistic future addition — e.g.
1310/// distinguishing an eviction from a refusal, should this map ever gain eviction. No
1311/// consumer outside this workspace depends on it yet, making now the cheapest point to
1312/// mark it non-exhaustive; doing so later, once external crates match on it, would itself
1313/// be a breaking change (part of #1226).
1314#[non_exhaustive]
1315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1316pub enum CapResult {
1317 /// `make()` ran and its value was inserted (the `Vacant`, under-capacity arm).
1318 Inserted,
1319 /// `key` was already registered; the existing value stuck (`on_occupied` ran, if any).
1320 AlreadyPresent,
1321 /// `key` was absent but the map was at [`MAX_ALTERNATE_REGISTRIES`]; nothing was
1322 /// inserted and a cap-reached `warn!` was emitted.
1323 RefusedAtCapacity,
1324}
1325
1326/// Registers `key` in a capacity-bounded alternate-client map, refusing (never evicting)
1327/// once full.
1328///
1329/// A no-op when `key` is already registered — the first successful registration for a given
1330/// key sticks. A no-op, with a `tracing::warn!`, once [`MAX_ALTERNATE_REGISTRIES`] is reached
1331/// and `key` is not already present.
1332///
1333/// Reads `map.len()` **before** calling `entry()`: `DashMap::len` read-locks every shard,
1334/// while `entry()` holds a write guard on one — checking capacity from inside the `Vacant`
1335/// arm would self-deadlock on that shard.
1336///
1337/// `ecosystem` names the caller in the cap-reached log line.
1338/// `key_shape` picks how `key` is rendered in that same line — see [`KeyShape`].
1339///
1340/// Returns [`CapResult::Inserted`] when `make()` was inserted, [`CapResult::AlreadyPresent`]
1341/// when `key` was already occupied, or [`CapResult::RefusedAtCapacity`] when the map was at
1342/// capacity.
1343///
1344/// # Examples
1345///
1346/// ```
1347/// use dashmap::DashMap;
1348/// use deps_core::EcosystemId;
1349/// use deps_core::registry::{CapResult, KeyShape, register_capped};
1350///
1351/// let map: DashMap<String, u32> = DashMap::new();
1352/// assert_eq!(
1353/// register_capped(&map, "a".to_string(), EcosystemId::Cargo, KeyShape::Opaque, || 1),
1354/// CapResult::Inserted
1355/// );
1356/// assert_eq!(
1357/// register_capped(&map, "a".to_string(), EcosystemId::Cargo, KeyShape::Opaque, || 2),
1358/// CapResult::AlreadyPresent
1359/// );
1360/// assert_eq!(*map.get("a").unwrap(), 1);
1361/// ```
1362pub fn register_capped<K, V>(
1363 map: &DashMap<K, V>,
1364 key: K,
1365 ecosystem: EcosystemId,
1366 key_shape: KeyShape,
1367 make: impl FnOnce() -> V,
1368) -> CapResult
1369where
1370 K: Eq + Hash + AsRef<str>,
1371{
1372 register_capped_with_occupied(map, key, ecosystem, key_shape, make, |_| {})
1373}
1374
1375/// [`register_capped`], plus an `on_occupied` callback for an already-registered key.
1376///
1377/// Lets an ecosystem still act on that key — folding a re-registration's trust tier
1378/// (`deps-cargo`) or rebuilding a client whose credential digest changed (`deps-nuget`).
1379///
1380/// `on_occupied` runs instead of `make`/the capacity check, never gated by
1381/// [`MAX_ALTERNATE_REGISTRIES`] — replacing an already-occupied slot does not grow the map,
1382/// so gating it would strand a legitimate in-place update (e.g. a rotated credential) once
1383/// the cap is hit for unrelated keys.
1384///
1385/// Returns [`CapResult::Inserted`] when `make()` was inserted (the `Vacant` arm),
1386/// [`CapResult::AlreadyPresent`] or [`CapResult::RefusedAtCapacity`] otherwise —
1387/// `on_occupied` signals its own outcome (e.g. via `tracing::warn!`) rather than through this
1388/// return value.
1389///
1390/// # Examples
1391///
1392/// ```
1393/// use dashmap::DashMap;
1394/// use deps_core::EcosystemId;
1395/// use deps_core::registry::{CapResult, KeyShape, register_capped_with_occupied};
1396///
1397/// let map: DashMap<String, u32> = DashMap::new();
1398/// register_capped_with_occupied(
1399/// &map,
1400/// "a".to_string(),
1401/// EcosystemId::Cargo,
1402/// KeyShape::Opaque,
1403/// || 1,
1404/// |_| {},
1405/// );
1406/// let outcome = register_capped_with_occupied(
1407/// &map,
1408/// "a".to_string(),
1409/// EcosystemId::Cargo,
1410/// KeyShape::Opaque,
1411/// || 1,
1412/// |v| *v += 10,
1413/// );
1414/// assert_eq!(outcome, CapResult::AlreadyPresent);
1415/// assert_eq!(*map.get("a").unwrap(), 11);
1416/// ```
1417pub fn register_capped_with_occupied<K, V>(
1418 map: &DashMap<K, V>,
1419 key: K,
1420 ecosystem: EcosystemId,
1421 key_shape: KeyShape,
1422 make: impl FnOnce() -> V,
1423 on_occupied: impl FnOnce(&mut V),
1424) -> CapResult
1425where
1426 K: Eq + Hash + AsRef<str>,
1427{
1428 let at_capacity = map.len() >= MAX_ALTERNATE_REGISTRIES;
1429
1430 match map.entry(key) {
1431 Entry::Occupied(mut slot) => {
1432 on_occupied(slot.get_mut());
1433 CapResult::AlreadyPresent
1434 }
1435 Entry::Vacant(slot) => {
1436 if at_capacity {
1437 // `slot.key()` reads the key back out of the entry rather than requiring a
1438 // borrow held across the `entry()` call above, so the (possibly allocating)
1439 // redaction work below stays entirely off the far more common
1440 // successful-registration path.
1441 let key_ref = slot.key().as_ref();
1442 let rendered_key = match key_shape {
1443 KeyShape::Url => crate::redact::RedactedUrl::new(key_ref).into_inner(),
1444 KeyShape::Opaque => key_ref.to_string(),
1445 };
1446 tracing::warn!(
1447 key = %rendered_key,
1448 cap = MAX_ALTERNATE_REGISTRIES,
1449 %ecosystem,
1450 "{ecosystem} alternate registry cap reached; not registering a new entry"
1451 );
1452 return CapResult::RefusedAtCapacity;
1453 }
1454 slot.insert(make());
1455 CapResult::Inserted
1456 }
1457 }
1458}
1459
1460#[cfg(test)]
1461mod tests {
1462 use std::assert_matches;
1463
1464 use super::*;
1465
1466 use crate::test_util::MockVersion;
1467
1468 fn http_404() -> DepsError {
1469 DepsError::HttpStatus {
1470 url: "https://r.example/pkg".into(),
1471 status: 404,
1472 }
1473 }
1474
1475 #[test]
1476 fn not_found_or_maps_a_received_status_to_an_endpoint_origin() {
1477 let mapped = not_found_or(http_404(), "pkg", "npm", &[]);
1478 assert_matches!(mapped, DepsError::PackageNotFound { .. });
1479 assert_eq!(mapped.origin(), ErrorOrigin::Endpoint);
1480 }
1481
1482 #[test]
1483 fn not_found_or_extra_status_is_an_endpoint_origin() {
1484 let gone = DepsError::HttpStatus {
1485 url: "https://r.example/pkg".into(),
1486 status: 410,
1487 };
1488 let mapped = not_found_or(gone, "pkg", "go", &[410]);
1489 assert_eq!(mapped.origin(), ErrorOrigin::Endpoint);
1490 }
1491
1492 #[test]
1493 fn locally_decided_not_found_is_unattributed() {
1494 assert_eq!(
1495 DepsError::not_found_locally("pkg", "npm").origin(),
1496 ErrorOrigin::Unattributed
1497 );
1498 assert_eq!(
1499 alternate_not_registered(&PackageName::new("pkg")).origin(),
1500 ErrorOrigin::Unattributed
1501 );
1502 }
1503
1504 #[test]
1505 fn chain_not_found_starts_unattributed() {
1506 let chain = ChainNotFound::new();
1507 assert_eq!(chain.error("p", "npm").origin(), ErrorOrigin::Unattributed);
1508 }
1509
1510 #[test]
1511 fn chain_not_found_remote_miss_then_local_miss_stays_endpoint() {
1512 let mut chain = ChainNotFound::new();
1513 chain.record(¬_found_or(http_404(), "p", "npm", &[]));
1514 chain.record(&DepsError::not_found_locally("p", "npm"));
1515 assert_eq!(chain.error("p", "npm").origin(), ErrorOrigin::Endpoint);
1516 }
1517
1518 #[test]
1519 fn chain_not_found_answered_empty_is_endpoint() {
1520 let mut chain = ChainNotFound::new();
1521 chain.record_answered_empty();
1522 assert_eq!(chain.error("p", "npm").origin(), ErrorOrigin::Endpoint);
1523 }
1524
1525 #[test]
1526 fn chain_not_found_all_local_misses_stay_unattributed() {
1527 let mut chain = ChainNotFound::new();
1528 chain.record(&DepsError::not_found_locally("p", "npm"));
1529 chain.record(&DepsError::not_found_locally("p", "npm"));
1530 assert_eq!(chain.error("p", "npm").origin(), ErrorOrigin::Unattributed);
1531 }
1532
1533 #[test]
1534 fn error_origin_merge_lets_endpoint_win() {
1535 use ErrorOrigin::{Endpoint, Unattributed};
1536 assert_eq!(Unattributed.merge(Unattributed), Unattributed);
1537 assert_eq!(Unattributed.merge(Endpoint), Endpoint);
1538 assert_eq!(Endpoint.merge(Unattributed), Endpoint);
1539 assert_eq!(Endpoint.merge(Endpoint), Endpoint);
1540 }
1541
1542 /// A [`Registry`] whose `search_raw` records whether it was called, for
1543 /// [`dyn_registry_search_rejects_credential_bearing_query_before_calling_search_raw`]
1544 /// (#1215) — mirrors `conformance.rs`'s `AlwaysHasResultsRegistry::search_was_called`.
1545 struct ProbeRegistry {
1546 search_raw_called: std::sync::atomic::AtomicBool,
1547 }
1548
1549 impl ProbeRegistry {
1550 fn new() -> Self {
1551 Self {
1552 search_raw_called: std::sync::atomic::AtomicBool::new(false),
1553 }
1554 }
1555
1556 fn search_raw_was_called(&self) -> bool {
1557 self.search_raw_called
1558 .load(std::sync::atomic::Ordering::SeqCst)
1559 }
1560 }
1561
1562 impl Registry for ProbeRegistry {
1563 fn get_versions<'a>(
1564 &'a self,
1565 _name: &'a PackageName,
1566 ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>> {
1567 Box::pin(async move { Ok(vec![]) })
1568 }
1569
1570 fn get_latest_matching<'a>(
1571 &'a self,
1572 _name: &'a PackageName,
1573 _req: &'a VersionReq,
1574 _selection_context: &'a crate::SelectionContext,
1575 ) -> BoxFuture<'a, Result<Option<Box<dyn Version>>>> {
1576 Box::pin(async move { Ok(None) })
1577 }
1578
1579 fn search_raw<'a>(
1580 &'a self,
1581 _query: &'a str,
1582 _limit: usize,
1583 ) -> BoxFuture<'a, Result<Vec<Box<dyn Metadata>>>> {
1584 self.search_raw_called
1585 .store(true, std::sync::atomic::Ordering::SeqCst);
1586 Box::pin(async move {
1587 let metadata = crate::test_util::MockMetadata::new("probe", "1.0.0");
1588 Ok(vec![Box::new(metadata) as Box<dyn Metadata>])
1589 })
1590 }
1591 }
1592
1593 #[tokio::test]
1594 async fn dyn_registry_search_rejects_credential_bearing_query_before_calling_search_raw() {
1595 let probe = ProbeRegistry::new();
1596 let registry: &dyn Registry = &probe;
1597
1598 let results = registry
1599 .search("user:hunter2@registry.example", 10)
1600 .await
1601 .unwrap();
1602
1603 assert!(
1604 results.is_empty(),
1605 "a credential-shaped query must return no results"
1606 );
1607 assert!(
1608 !probe.search_raw_was_called(),
1609 "a credential-shaped query must be rejected before ever calling `search_raw` \
1610 (issue #1215) — redacting the value and searching anyway, then dropping the \
1611 result, would still satisfy the empty-result assertion above but fail this one"
1612 );
1613 }
1614
1615 #[tokio::test]
1616 async fn dyn_registry_search_delegates_to_search_raw_for_a_safe_query() {
1617 let probe = ProbeRegistry::new();
1618 let registry: &dyn Registry = &probe;
1619
1620 let results = registry.search("serde", 10).await.unwrap();
1621
1622 assert!(
1623 !results.is_empty(),
1624 "a safe query must reach `search_raw` and return its result"
1625 );
1626 assert!(probe.search_raw_was_called());
1627 }
1628
1629 #[test]
1630 fn test_version_default_features() {
1631 let version = MockVersion::new("1.0.0").yanked(false);
1632
1633 assert_eq!(version.features(), Vec::<String>::new());
1634 }
1635
1636 #[test]
1637 fn test_version_trait_object() {
1638 let version = MockVersion::new("1.2.3").yanked(false);
1639
1640 let boxed: Box<dyn Version> = Box::new(version);
1641 assert_eq!(boxed.version_string().as_str(), "1.2.3");
1642 assert!(!boxed.removal_status().blocks_resolution());
1643 }
1644
1645 #[test]
1646 fn test_version_downcast() {
1647 let version = MockVersion::new("1.0.0").yanked(true);
1648
1649 let boxed: Box<dyn Version> = Box::new(version);
1650 let any = VersionAny::as_any(&*boxed);
1651
1652 assert!(any.is::<MockVersion>());
1653 }
1654
1655 struct MockMetadata {
1656 name: crate::PackageName,
1657 latest: ConcreteVersion,
1658 }
1659
1660 impl Metadata for MockMetadata {
1661 fn name(&self) -> &crate::PackageName {
1662 &self.name
1663 }
1664
1665 fn description(&self) -> Option<&str> {
1666 None
1667 }
1668
1669 fn repository(&self) -> Option<&str> {
1670 None
1671 }
1672
1673 fn documentation(&self) -> Option<&str> {
1674 None
1675 }
1676
1677 fn latest_version(&self) -> &ConcreteVersion {
1678 &self.latest
1679 }
1680 }
1681
1682 #[test]
1683 fn test_metadata_trait_object() {
1684 let metadata = MockMetadata {
1685 name: crate::PackageName::new("test-package"),
1686 latest: "2.0.0".into(),
1687 };
1688
1689 let boxed: Box<dyn Metadata> = Box::new(metadata);
1690 assert_eq!(boxed.name(), "test-package");
1691 assert_eq!(boxed.latest_version().as_str(), "2.0.0");
1692 assert!(boxed.description().is_none());
1693 assert!(boxed.repository().is_none());
1694 assert!(boxed.documentation().is_none());
1695 }
1696
1697 #[test]
1698 fn test_metadata_with_full_info() {
1699 struct FullMetadata {
1700 name: crate::PackageName,
1701 desc: String,
1702 repo: String,
1703 docs: String,
1704 latest: ConcreteVersion,
1705 }
1706
1707 impl Metadata for FullMetadata {
1708 fn name(&self) -> &crate::PackageName {
1709 &self.name
1710 }
1711 fn description(&self) -> Option<&str> {
1712 Some(&self.desc)
1713 }
1714 fn repository(&self) -> Option<&str> {
1715 Some(&self.repo)
1716 }
1717 fn documentation(&self) -> Option<&str> {
1718 Some(&self.docs)
1719 }
1720 fn latest_version(&self) -> &ConcreteVersion {
1721 &self.latest
1722 }
1723 }
1724
1725 let meta = FullMetadata {
1726 name: crate::PackageName::new("serde"),
1727 desc: "Serialization framework".into(),
1728 repo: "https://github.com/serde-rs/serde".into(),
1729 docs: "https://docs.rs/serde".into(),
1730 latest: "1.0.214".into(),
1731 };
1732
1733 assert_eq!(meta.description(), Some("Serialization framework"));
1734 assert_eq!(meta.repository(), Some("https://github.com/serde-rs/serde"));
1735 assert_eq!(meta.documentation(), Some("https://docs.rs/serde"));
1736 }
1737
1738 #[test]
1739 fn test_is_prerelease_alpha() {
1740 let version = MockVersion::new("4.0.0-alpha.13").yanked(false);
1741 assert!(version.is_prerelease());
1742 }
1743
1744 #[test]
1745 fn test_is_prerelease_beta() {
1746 let version = MockVersion::new("2.0.0-beta.1").yanked(false);
1747 assert!(version.is_prerelease());
1748 }
1749
1750 #[test]
1751 fn test_is_prerelease_rc() {
1752 let version = MockVersion::new("1.5.0-rc.2").yanked(false);
1753 assert!(version.is_prerelease());
1754 }
1755
1756 #[test]
1757 fn test_is_prerelease_dev() {
1758 let version = MockVersion::new("3.0.0-dev").yanked(false);
1759 assert!(version.is_prerelease());
1760 }
1761
1762 #[test]
1763 fn test_is_prerelease_canary() {
1764 let version = MockVersion::new("5.0.0-canary").yanked(false);
1765 assert!(version.is_prerelease());
1766 }
1767
1768 #[test]
1769 fn test_is_prerelease_nightly() {
1770 let version = MockVersion::new("6.0.0-nightly").yanked(false);
1771 assert!(version.is_prerelease());
1772 }
1773
1774 #[test]
1775 fn test_is_not_prerelease_stable() {
1776 let version = MockVersion::new("1.2.3").yanked(false);
1777 assert!(!version.is_prerelease());
1778 }
1779
1780 #[test]
1781 fn test_is_not_prerelease_patch() {
1782 let version = MockVersion::new("1.0.214").yanked(false);
1783 assert!(!version.is_prerelease());
1784 }
1785
1786 #[test]
1787 fn test_is_stable_true() {
1788 let version = MockVersion::new("1.0.0").yanked(false);
1789 assert!(version.is_stable());
1790 }
1791
1792 #[test]
1793 fn test_is_stable_false_yanked() {
1794 let version = MockVersion::new("1.0.0").yanked(true);
1795 assert!(!version.is_stable());
1796 }
1797
1798 #[test]
1799 fn test_is_stable_false_prerelease() {
1800 let version = MockVersion::new("1.0.0-alpha.1").yanked(false);
1801 assert!(!version.is_stable());
1802 }
1803
1804 #[test]
1805 fn test_find_latest_stable_skips_prerelease() {
1806 let versions: Vec<Box<dyn Version>> = vec![
1807 Box::new(MockVersion::new("2.0.0-alpha.1").yanked(false)),
1808 Box::new(MockVersion::new("1.5.0").yanked(false)),
1809 ];
1810 let latest = super::find_latest_stable(&versions);
1811 assert_eq!(latest.map(|v| v.version_string().as_str()), Some("1.5.0"));
1812 }
1813
1814 #[test]
1815 fn test_find_latest_stable_skips_yanked() {
1816 let versions: Vec<Box<dyn Version>> = vec![
1817 Box::new(MockVersion::new("2.0.0").yanked(true)),
1818 Box::new(MockVersion::new("1.5.0").yanked(false)),
1819 ];
1820 let latest = super::find_latest_stable(&versions);
1821 assert_eq!(latest.map(|v| v.version_string().as_str()), Some("1.5.0"));
1822 }
1823
1824 #[test]
1825 fn test_find_latest_stable_returns_first_stable() {
1826 let versions: Vec<Box<dyn Version>> = vec![
1827 Box::new(MockVersion::new("3.0.0-beta.1").yanked(false)),
1828 Box::new(MockVersion::new("2.0.0").yanked(true)),
1829 Box::new(MockVersion::new("1.5.0").yanked(false)),
1830 Box::new(MockVersion::new("1.4.0").yanked(false)),
1831 ];
1832 let latest = super::find_latest_stable(&versions);
1833 assert_eq!(latest.map(|v| v.version_string().as_str()), Some("1.5.0"));
1834 }
1835
1836 #[test]
1837 fn test_find_latest_stable_empty_list() {
1838 let versions: Vec<Box<dyn Version>> = vec![];
1839 let latest = super::find_latest_stable(&versions);
1840 assert!(latest.is_none());
1841 }
1842
1843 #[test]
1844 fn test_find_latest_stable_no_stable_versions() {
1845 let versions: Vec<Box<dyn Version>> = vec![
1846 Box::new(MockVersion::new("2.0.0-alpha.1").yanked(false)),
1847 Box::new(MockVersion::new("1.0.0").yanked(true)),
1848 ];
1849 let latest = super::find_latest_stable(&versions);
1850 assert!(latest.is_none());
1851 }
1852
1853 struct StatusVersion {
1854 version: ConcreteVersion,
1855 status: RemovalStatus,
1856 }
1857
1858 impl Version for StatusVersion {
1859 fn version_string(&self) -> &ConcreteVersion {
1860 &self.version
1861 }
1862
1863 fn removal_status(&self) -> RemovalStatus {
1864 self.status
1865 }
1866 }
1867
1868 #[test]
1869 fn test_is_stable_true_for_advisory_deprecated() {
1870 let version = StatusVersion {
1871 version: "1.0.0".into(),
1872 status: RemovalStatus::AdvisoryDeprecated,
1873 };
1874 assert!(version.is_stable());
1875 }
1876
1877 #[test]
1878 fn test_is_stable_false_for_yanked() {
1879 let version = StatusVersion {
1880 version: "1.0.0".into(),
1881 status: RemovalStatus::Yanked,
1882 };
1883 assert!(!version.is_stable());
1884 }
1885
1886 #[test]
1887 fn test_removal_status_blocks_resolution() {
1888 assert!(!RemovalStatus::Available.blocks_resolution());
1889 assert!(!RemovalStatus::AdvisoryDeprecated.blocks_resolution());
1890 assert!(RemovalStatus::Yanked.blocks_resolution());
1891 }
1892
1893 #[test]
1894 fn test_removal_status_is_flagged() {
1895 assert!(!RemovalStatus::Available.is_flagged());
1896 assert!(RemovalStatus::AdvisoryDeprecated.is_flagged());
1897 assert!(RemovalStatus::Yanked.is_flagged());
1898 }
1899
1900 #[test]
1901 fn test_removal_status_from_yanked() {
1902 assert_eq!(RemovalStatus::from_yanked(true), RemovalStatus::Yanked);
1903 assert_eq!(RemovalStatus::from_yanked(false), RemovalStatus::Available);
1904 }
1905
1906 #[test]
1907 fn test_removal_status_from_advisory() {
1908 assert_eq!(
1909 RemovalStatus::from_advisory(true),
1910 RemovalStatus::AdvisoryDeprecated
1911 );
1912 assert_eq!(
1913 RemovalStatus::from_advisory(false),
1914 RemovalStatus::Available
1915 );
1916 }
1917
1918 #[test]
1919 fn test_hash_routing_key_format() {
1920 let key = hash_routing_key("pypi-chain", ["https://example.test/simple/"].into_iter());
1921 assert!(key.starts_with("pypi-chain:"));
1922 assert_eq!(key.len(), "pypi-chain:".len() + 16);
1923 }
1924
1925 #[test]
1926 fn test_hash_routing_key_deterministic() {
1927 let parts = || ["https://a.test/", "https://b.test/", "true"].into_iter();
1928 assert_eq!(
1929 hash_routing_key("go-proxy", parts()),
1930 hash_routing_key("go-proxy", parts())
1931 );
1932 }
1933
1934 #[test]
1935 fn test_hash_routing_key_distinguishes_prefix() {
1936 let parts = || ["same"].into_iter();
1937 assert_ne!(
1938 hash_routing_key("pypi-chain", parts()),
1939 hash_routing_key("nuget-chain", parts())
1940 );
1941 }
1942
1943 #[test]
1944 fn test_hash_routing_key_distinguishes_parts() {
1945 assert_ne!(
1946 hash_routing_key("chain", ["a", "b"].into_iter()),
1947 hash_routing_key("chain", ["a", "c"].into_iter())
1948 );
1949 }
1950
1951 /// Hop order is part of chain identity (spec 034's fallback order, PyPI's FR-005
1952 /// primary-before-extras order, NuGet's declaration order all rely on this) — the same
1953 /// set of parts in a different order must not collide.
1954 #[test]
1955 fn test_hash_routing_key_order_sensitive() {
1956 assert_ne!(
1957 hash_routing_key("chain", ["a", "b", "c"].into_iter()),
1958 hash_routing_key("chain", ["c", "b", "a"].into_iter())
1959 );
1960 }
1961
1962 /// Documents that credential exclusion is a caller obligation, not something
1963 /// `hash_routing_key` enforces: two calls that differ only in a credential-shaped extra
1964 /// part produce different keys, so a caller who mistakenly includes one breaks the
1965 /// rotation-stability invariant this function's doc warns about.
1966 #[test]
1967 fn test_hash_routing_key_only_hashes_what_callers_pass() {
1968 let identity_only =
1969 hash_routing_key("nuget-chain", ["https://feed.test/", "corp"].into_iter());
1970 let with_credential_included = hash_routing_key(
1971 "nuget-chain",
1972 ["https://feed.test/", "corp", "hunter2"].into_iter(),
1973 );
1974 assert_ne!(identity_only, with_credential_included);
1975 }
1976
1977 /// #969 S1: a `KeyShape::Url` key must be redacted before it reaches the cap-reached log
1978 /// line — the query-string credential must never appear, but the non-secret host must.
1979 #[cfg(feature = "test-util")]
1980 #[test]
1981 fn test_register_capped_url_shape_redacts_credential_on_cap_reached() {
1982 let map: DashMap<String, usize> = DashMap::new();
1983 for i in 0..MAX_ALTERNATE_REGISTRIES {
1984 assert_eq!(
1985 register_capped(
1986 &map,
1987 format!("https://index{i}.example"),
1988 EcosystemId::Cargo,
1989 KeyShape::Url,
1990 || i,
1991 ),
1992 CapResult::Inserted
1993 );
1994 }
1995
1996 let log = crate::test_util::capture_tracing_output(|| {
1997 register_capped(
1998 &map,
1999 "https://overflow.example/?api_key=SUPERSECRET_TOKEN".to_string(),
2000 EcosystemId::Cargo,
2001 KeyShape::Url,
2002 || 0,
2003 );
2004 });
2005
2006 assert!(
2007 log.contains("cargo alternate registry cap reached"),
2008 "log: {log}"
2009 );
2010 assert!(!log.contains("SUPERSECRET_TOKEN"), "log: {log}");
2011 assert!(log.contains("overflow.example"), "log: {log}");
2012 }
2013
2014 /// #969 S3: a `KeyShape::Opaque` key (e.g. a [`hash_routing_key`] digest) must survive
2015 /// the cap-reached log line intact — `RedactedUrl`'s Maven-coordinate false-positive scan
2016 /// would otherwise collapse a `"<prefix>:<hex>"` shape to an information-free
2017 /// `"<prefix>:***"`, destroying the correlation handle to other diagnostics about the
2018 /// same chain.
2019 #[cfg(feature = "test-util")]
2020 #[test]
2021 fn test_register_capped_opaque_shape_is_not_redacted_on_cap_reached() {
2022 let map: DashMap<String, usize> = DashMap::new();
2023 for i in 0..MAX_ALTERNATE_REGISTRIES {
2024 let key = hash_routing_key("test-chain", std::iter::once(i.to_string().as_str()));
2025 assert_eq!(
2026 register_capped(&map, key, EcosystemId::Cargo, KeyShape::Opaque, || i),
2027 CapResult::Inserted
2028 );
2029 }
2030
2031 let overflow_key = hash_routing_key("test-chain", std::iter::once("overflow"));
2032 let log = crate::test_util::capture_tracing_output(|| {
2033 register_capped(
2034 &map,
2035 overflow_key.clone(),
2036 EcosystemId::Cargo,
2037 KeyShape::Opaque,
2038 || 0,
2039 );
2040 });
2041
2042 assert!(
2043 log.contains("cargo alternate registry cap reached"),
2044 "log: {log}"
2045 );
2046 assert!(
2047 log.contains(&overflow_key),
2048 "opaque key must not be redacted: {log}"
2049 );
2050 assert!(
2051 !log.contains("***"),
2052 "opaque key must not collapse to '***': {log}"
2053 );
2054 }
2055}