Skip to main content

PypiRegistry

Struct PypiRegistry 

Source
pub struct PypiRegistry { /* private fields */ }
Expand description

Client for interacting with the PyPI registry.

Uses the PyPI JSON API for package metadata. All requests are cached via the provided HttpCache.

§Examples

let cache = Arc::new(HttpCache::new());
let registry = PypiRegistry::new(cache);

let versions = registry.get_versions("requests").await.unwrap();
assert!(!versions.is_empty());

Implementations§

Source§

impl PypiRegistry

Source

pub fn new(cache: Arc<HttpCache>) -> Self

Creates a new PyPI registry client with the given HTTP cache.

Source

pub fn with_public_base_for_test( cache: Arc<HttpCache>, simple_base: String, ) -> Self

Test-only: constructs a Public-tier root client with simple_base pointed at a mock server, so the implicit public fallback hop (spec FR-005(b)) can be exercised in a behavioral test — request order/count via mockito — without ever contacting the real pypi.org. Mirrors PypiIndexUrl’s identical cfg(test)/test-util-gated loopback carve-out (validator finding #9).

Self::register_chain’s implicit-public-fallback hop is built from root’s own simple_base (not the hardcoded PYPI_SIMPLE_BASE constant), so registering a chain against a root constructed this way makes that hop resolve to the mock server too — the same code path production uses, just pointed elsewhere.

Source

pub fn with_base( cache: Arc<HttpCache>, simple_base: &PypiIndexUrl, fallback_chain: Vec<Arc<Self>>, ) -> Self

Creates a PypiRegistry client for one resolved private-index hop — an ordinary production constructor, WorkspaceDeclared-tier so it fetches through HttpCache::get_cached_workspace_with_headers (FR-008’s redirect-hop gating) instead of the ungated transport.

fallback_chain is empty for every call except the head client Self::register_chain builds for a multi-hop chain — every other hop (a chain’s own leaf hops, or a single-hop named-source client) is a dead end with nothing further to fall through to, matching plan.md §1’s “leaf clients are never themselves looked up by key, only walked positionally” design. Its own alternates map starts empty and is never populated — only the root ever registers a chain (see Self::alternates’s doc).

Source

pub fn register_chain(root: &Arc<Self>, chain: &ResolvedChain)

Builds the full hop tree for one ResolvedChain and inserts the head into root.alternates under chain.key. Idempotent per key (a repeat registration for the same key is a no-op), capacity-capped at MAX_ALTERNATE_REGISTRIES.

Called only from PypiEcosystem::parse_manifest over PypiIndexConfig::resolved_chains(), at parse time only. Takes root: &Arc<Self> as a plain parameter rather than &self (fixes N1, second critic pass) — self: &Arc<Self> receivers are unstable, and building the implicit-public final hop needs an owned Arc<Self>; PypiEcosystem already holds registry: Arc<PypiRegistry> and passes it here directly.

The implicit-public final hop (when chain.implicit_public_fallback is set) is a freshly-constructed Public-tier client (Self::new, same URL/transport as the root), never Arc::clone(root) — cloning the root would create a root→alternates→head→fallback_chain→root reference cycle (N1’s second half).

Source

pub fn register_named_source(root: &Arc<Self>, index: &PypiIndexUrl)

Registers a single-hop named-source client (Poetry source =/uv index =, spec FR-007/FR-013) under index’s own URL into root.alternates. Same idempotency/capacity rules and root: &Arc<Self> parameter shape as Self::register_chain.

Source

pub fn alternate_client(&self, index: &str) -> Option<Arc<Self>>

The registered client for index (a ResolvedChain::key or a named source’s own URL), if any — read-only, performs no registration, no validation.

Intentionally only ever meaningful on the root — a chain-hop leaf’s own alternates map is always empty by construction (Self::with_base never populates it), so calling this on a non-root client always returns None, documenting the invariant rather than a bug: Self::get_versions_chained never calls this on self, only walks the already-resolved Self::fallback_chain positionally.

Source

pub async fn get_versions(&self, name: &str) -> Result<Vec<PypiVersion>>

Fetches all versions for a package from PyPI’s Simple API (PEP 691).

Requests the JSON representation (Accept: application/vnd.pypi.simple.v1+json), which is smaller than the full JSON API and provides the version list directly, without needing to derive versions from release-file names.

Returns versions sorted newest-first. Filters out yanked versions by default.

§Errors

Returns an error if:

  • HTTP request fails
  • Response body is invalid UTF-8
  • JSON parsing fails
  • Package does not exist
§Examples
let cache = Arc::new(HttpCache::new());
let registry = PypiRegistry::new(cache);

let versions = registry.get_versions("flask").await.unwrap();
assert!(!versions.is_empty());
Source

pub async fn get_latest_matching( &self, name: &str, req_str: &str, ) -> Result<Option<PypiVersion>>

Finds the latest version matching the given PEP 440 version specifier.

Only returns non-yanked, non-prerelease versions by default.

§Errors

Returns an error if:

  • HTTP request fails
  • Package does not exist
  • Version specifier is invalid
§Examples
let cache = Arc::new(HttpCache::new());
let registry = PypiRegistry::new(cache);

let latest = registry.get_latest_matching("flask", ">=3.0,<4.0").await.unwrap();
assert!(latest.is_some());
Source

pub fn search( &self, query: &str, limit: usize, ) -> impl Future<Output = Result<Vec<PypiPackage>>> + use<>

Searches for packages whose PEP 503 normalized name starts with query.

PyPI removed its XML-RPC search API and offers no first-party ranked search, so this serves unranked, alphabetically-sorted prefix matches against a lazily-built, in-memory index of the full PyPI Simple API project list (~882k names) — the same approach PyCharm’s PyPI completion uses. See crate::search for the index’s build/backoff lifecycle.

On a cold start (the index has not finished building yet), this returns an empty result immediately rather than blocking on a ~9.6 MB download, and triggers a background build. Once built, the index is never rebuilt for the life of the process — there is no TTL (see crate::search’s module doc for why). Because the result set can be a truncated view of a much larger match set, callers should treat every result (empty or not) as incomplete; PypiEcosystem::generate_completions does this by reporting deps_core::completion::Completions::is_incomplete for the PackageName completion context this method backs.

§Errors

Never returns Err: a failed background build is logged and degrades to an empty result, matching this method’s pre-existing observable behavior.

§Examples
let cache = Arc::new(HttpCache::new());
let registry = PypiRegistry::new(cache);

// May be empty on a cold start; a later call (once the index has built)
// returns matches.
let _results = registry.search("flask", 10).await.unwrap();
Source

pub fn warm_search_index(&self)

Starts building the package-name search index in the background if it isn’t ready yet (or a prior failed attempt’s backoff window has elapsed).

Safe to call unconditionally and often — a cheap no-op once the index is crate::search::IndexState::Ready or while a prior failure is still within its backoff window. deps-pypi’s PypiEcosystem calls this on every completion request in a Python manifest (not only package-name completion), so the index is typically already built by the time the user starts typing a package name.

Source

pub async fn get_package_metadata(&self, name: &str) -> Result<PypiPackage>

Fetches package metadata including description and project URLs.

§Errors

Returns an error if:

  • HTTP request fails
  • Package does not exist
  • JSON parsing fails
  • self is WorkspaceDeclared-tier (T008, fixes S4/M3) — this method is pub, ungated, and unrouted by any in-workspace caller today, but a future call site reaching it on a private-index client would otherwise send that client’s package name to pypi.org’s JSON API (metadata_url is always built from the hardcoded PYPI_BASE, never parameterized — see metadata_url’s doc) — closed here before any such call site exists, not relied on via the call graph

Trait Implementations§

Source§

impl Clone for PypiRegistry

Source§

fn clone(&self) -> PypiRegistry

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Registry for PypiRegistry

Source§

fn get_versions_from<'a>( &'a self, name: &'a PackageName, source: &'a DependencySource, freshness: FreshnessSettings, ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>>

Dispatches by source (spec FR-010): an AlternateRegistry whose index has a registered client routes through Self::get_versions_chained (FR-005’s chain walk); one with no registered client is PackageNotFound, never a fall back to pypi.org (PyPI always sets mirrors_crates_io: false, so Cargo’s mirror-degradation arm is dead here and must not be written — falling back would send a private package name to the public index, the exact #248-class leak this feature closes). Every other source keeps today’s public-registry path unchanged.

Source§

fn get_latest_matching_from<'a>( &'a self, name: &'a PackageName, source: &'a DependencySource, req: &'a VersionReq, _minimum_stability: Option<&'a str>, ) -> BoxFuture<'a, Result<Option<Box<dyn Version>>>>

get_versions_from’s get_latest_matching-shaped counterpart — same dispatch, same “never fall back to pypi.org for an unregistered AlternateRegistry” invariant.

Derived from Self::get_versions_chained + Registry::select_latest_matching (fixes M4) rather than an independent per-hop version-matching walk: the winning hop (first hop with a non-empty version list) is selected once by Self::get_versions_chained, and matching happens only within that single hop’s list. If the winning hop has no version matching req, that is terminal (Ok(None)), not a trigger to search later hops for a “better” match — continuing would reintroduce the cross-index version comparison this design avoids for the same dependency-confusion reasons FR-005(b)’s ordering exists.

Source§

fn get_versions<'a>( &'a self, name: &'a PackageName, ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>>

Fetches all available versions for a package. Read more
Source§

fn get_latest_matching<'a>( &'a self, name: &'a PackageName, req: &'a VersionReq, ) -> BoxFuture<'a, Result<Option<Box<dyn Version>>>>

Finds the latest version matching a version requirement. Read more
Source§

fn search<'a>( &'a self, query: &'a str, limit: usize, ) -> BoxFuture<'a, Result<Vec<Box<dyn Metadata>>>>

Searches for packages by name or keywords. Read more
Source§

fn select_latest_matching( &self, versions: &[Box<dyn Version>], req: &VersionReq, ) -> Option<usize>

Index of the latest version in versions satisfying req, with no I/O. Read more
Source§

fn as_any(&self) -> &dyn Any

Downcast to concrete registry type for ecosystem-specific operations
Source§

fn get_versions_with<'a>( &'a self, name: &'a PackageName, freshness: FreshnessSettings, ) -> Pin<Box<dyn Future<Output = Result<Vec<Box<dyn Version>>, DepsError>> + Send + 'a>>

Like get_versions, but lets a registry that can obtain Version::published_at only through an extra request gate that request behind freshness.enabled instead of always paying for it. Read more
Source§

fn get_latest_matching_with_context<'a>( &'a self, name: &'a PackageName, req: &'a VersionReq, minimum_stability: Option<&'a str>, ) -> Pin<Box<dyn Future<Output = Result<Option<Box<dyn Version>>, DepsError>> + Send + 'a>>

Like get_latest_matching, but lets a registry whose “latest matching” selection can be refined by ecosystem-specific manifest state (e.g. Composer’s minimum-stability field, #424) read it, alongside req. Read more
Source§

fn select_latest_matching_with_context( &self, versions: &[Box<dyn Version>], req: &VersionReq, minimum_stability: Option<&str>, ) -> Option<usize>

Like select_latest_matching, but lets a registry whose selection can be refined by ecosystem-specific manifest state (e.g. Composer’s minimum-stability field, #424) read it, alongside versions and req. See get_latest_matching_with_context for why minimum_stability is an opaque per-ecosystem string rather than a shared type. Read more
Source§

fn reports_yanked(&self) -> bool

Whether get_versions results carry meaningful per-version yank/deprecation data via Version::removal_status. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more