Skip to content

Commit 99982b9

Browse files
astegmaierCopilotzkochan
authored
perf(npm-resolver): normalize non-abbreviated registry metadata (#12772)
pnpm requests abbreviated package metadata (Accept: application/vnd.npm.install-v1+json). Some registries (e.g. Azure DevOps Artifacts) ignore that header and return the full CouchDB document, including per-version fields the installer never reads (scripts, exports, devDependencies, readme, custom package.json fields). pnpm stored that response verbatim in the abbreviated metadata cache, so every later resolution re-read and re-parsed those unused fields. Fix the response at the boundary where it enters pnpm: fetchMetadataFromFromRegistry inspects the response Content-Type. When an abbreviated request comes back with anything other than application/vnd.npm.install-v1+json, the registry ignored the header and served the full document, so the fetch layer strips it to the abbreviated field set (via the existing clearMeta helper) and re-serializes. Registries that honor the header (the npm registry echoes the abbreviated Content-Type) take an early return: no clearMeta, no re-serialization. clearMeta is extracted from pickPackage.ts into its own module so the network layer can use it without a circular import, and is made null-safe on versions. pickPackage's abbreviated slot no longer needs special-casing. Alternative to #12766, which applied the same normalization in pickPackage; both produce a byte-identical cache, this variant skips the work for spec-compliant registries and removes resolver special-casing. --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Zoltan Kochan <[email protected]>
1 parent 84cf84c commit 99982b9

9 files changed

Lines changed: 426 additions & 49 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@pnpm/resolving.npm-resolver": patch
3+
"pnpm": patch
4+
---
5+
6+
Sped up resolution and reduced memory use against registries that ignore npm's abbreviated metadata format and always return the full package document (for example, Azure DevOps Artifacts). pnpm now strips such documents down to the abbreviated field set before caching them. Resolution output is unchanged, and registries that honor the abbreviated format (such as the npm registry) pay no extra cost.

‎pacquet/crates/resolving-npm-resolver/src/fetch_full_metadata.rs‎

Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use pacquet_network::{
2323
use pacquet_registry::Package;
2424
use reqwest::{StatusCode, header};
2525

26-
use crate::{FetchMetadataError, registry_url::to_registry_url};
26+
use crate::{FetchMetadataError, mirror::clear_meta, registry_url::to_registry_url};
2727

2828
/// Accept header for the full packument.
2929
pub(crate) const ACCEPT_FULL_DOC: &str = "application/json; q=1.0, */*";
@@ -32,6 +32,23 @@ pub(crate) const ACCEPT_FULL_DOC: &str = "application/json; q=1.0, */*";
3232
pub(crate) const ACCEPT_ABBREVIATED_DOC: &str =
3333
"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*";
3434

35+
/// Content type of an abbreviated (install-oriented) packument. A
36+
/// spec-compliant registry echoes this in the response `Content-Type` when it
37+
/// honors the abbreviated `Accept` header. Its absence signals that the
38+
/// registry ignored the header and served the full document instead.
39+
/// <https://github.com/npm/registry/blob/main/docs/responses/package-metadata.md>
40+
const ABBREVIATED_META_CONTENT_TYPE: &str = "application/vnd.npm.install-v1+json";
41+
42+
/// Whether the response `Content-Type` declares the abbreviated packument
43+
/// media type. Parameters (`; charset=utf-8`) are dropped and the comparison
44+
/// is case-insensitive (RFC 9110 §8.3.1).
45+
pub(crate) fn is_abbreviated_content_type(headers: &header::HeaderMap) -> bool {
46+
headers.get(header::CONTENT_TYPE).and_then(|value| value.to_str().ok()).is_some_and(|value| {
47+
let media_type = value.split_once(';').map_or(value, |(media_type, _)| media_type);
48+
media_type.trim().eq_ignore_ascii_case(ABBREVIATED_META_CONTENT_TYPE)
49+
})
50+
}
51+
3552
/// Options bundle for [`fetch_full_metadata`]. The cached variant
3653
/// ([`crate::FetchFullMetadataCachedOptions`]) layers a
3754
/// cache-directory field on top of these.
@@ -107,6 +124,8 @@ pub async fn fetch_full_metadata(
107124
let response = response.error_for_status().map_err(|error| {
108125
FetchMetadataError::Network { url: redact_url_credentials(&url), error }
109126
})?;
127+
let normalize_to_abbreviated =
128+
!opts.full_metadata && !is_abbreviated_content_type(response.headers());
110129
let raw_body = response.text().await.map_err(|error| FetchMetadataError::BodyRead {
111130
url: redact_url_credentials(&url),
112131
error,
@@ -118,11 +137,11 @@ pub async fn fetch_full_metadata(
118137
// `fetch_full_metadata_cached` for the cold-install numbers).
119138
drop(client);
120139
let task_url = url.clone();
121-
let meta = tokio::task::spawn_blocking(move || {
122-
serde_json::from_str::<Package>(&raw_body).map_err(|error| FetchMetadataError::Decode {
123-
url: redact_url_credentials(&task_url),
124-
error,
125-
})
140+
let meta = tokio::task::spawn_blocking(move || -> Result<Package, FetchMetadataError> {
141+
let meta = serde_json::from_str::<Package>(&raw_body).map_err(|error| {
142+
FetchMetadataError::Decode { url: redact_url_credentials(&task_url), error }
143+
})?;
144+
Ok(if normalize_to_abbreviated { normalize_abbreviated_meta(meta) } else { meta })
126145
})
127146
.await
128147
.map_err(|error| FetchMetadataError::ParseTask {
@@ -134,5 +153,31 @@ pub async fn fetch_full_metadata(
134153
.await
135154
}
136155

156+
/// Strip a packument served for an **abbreviated** request down to the
157+
/// abbreviated field set, for a registry that ignored the `Accept` header
158+
/// (detected via [`is_abbreviated_content_type`]) and returned the full
159+
/// document. Neither the in-memory pick nor the on-disk mirror then carries
160+
/// the install-irrelevant data (scripts, exports, readme, custom fields) a
161+
/// full document contains. Registries that honor the header (e.g. the npm
162+
/// registry) echo the abbreviated `Content-Type` and skip this entirely.
163+
///
164+
/// Normalization is a cache optimization, not a correctness requirement, so
165+
/// the practically-unreachable [`clear_meta`] failure (a fragment that was
166+
/// parsed from the response body failing to re-parse) keeps the full
167+
/// document rather than failing the fetch.
168+
pub(crate) fn normalize_abbreviated_meta(meta: Package) -> Package {
169+
match clear_meta(&meta) {
170+
Ok(normalized) => normalized,
171+
Err(error) => {
172+
tracing::warn!(
173+
target: "pacquet_resolving_npm_resolver",
174+
%error,
175+
"could not normalize a non-abbreviated metadata response; keeping the full document",
176+
);
177+
meta
178+
}
179+
}
180+
}
181+
137182
#[cfg(test)]
138183
mod tests;

‎pacquet/crates/resolving-npm-resolver/src/fetch_full_metadata/tests.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,19 @@
11
use pacquet_network::{AuthHeaders, RetryOpts, ThrottledClient};
22
use std::time::Duration;
33

4-
use super::{FetchFullMetadataOptions, FetchFullMetadataOutcome, fetch_full_metadata};
4+
use super::{
5+
ABBREVIATED_META_CONTENT_TYPE, ACCEPT_ABBREVIATED_DOC, FetchFullMetadataOptions,
6+
FetchFullMetadataOutcome, fetch_full_metadata,
7+
};
8+
9+
/// The two constants repeat the media type as separate literals (Rust
10+
/// cannot build one string const from another without a macro), so
11+
/// guard against them drifting apart: the `Accept` header must offer
12+
/// the same media type the response detection recognizes.
13+
#[test]
14+
fn accept_header_offers_the_detected_abbreviated_media_type() {
15+
assert!(ACCEPT_ABBREVIATED_DOC.starts_with(ABBREVIATED_META_CONTENT_TYPE));
16+
}
517

618
/// Unwrap a [`FetchFullMetadataOutcome::Modified`], panicking on
719
/// `NotModified`. Used by the success-path tests below where the

‎pacquet/crates/resolving-npm-resolver/src/fetch_full_metadata_cached.rs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ use reqwest::{StatusCode, header};
2424

2525
use crate::{
2626
FetchMetadataError,
27-
fetch_full_metadata::{ACCEPT_ABBREVIATED_DOC, ACCEPT_FULL_DOC},
27+
fetch_full_metadata::{
28+
ACCEPT_ABBREVIATED_DOC, ACCEPT_FULL_DOC, is_abbreviated_content_type,
29+
normalize_abbreviated_meta,
30+
},
2831
mirror::{
2932
ABBREVIATED_META_DIR, FULL_FILTERED_META_DIR, FULL_META_DIR, clear_meta,
3033
get_pkg_mirror_path, load_meta_async, load_meta_headers_async, save_meta_indexed,
@@ -155,6 +158,8 @@ pub async fn fetch_full_metadata_cached(
155158
.get(header::ETAG)
156159
.and_then(|value| value.to_str().ok())
157160
.map(str::to_string);
161+
let normalize_to_abbreviated =
162+
!opts.full_metadata && !is_abbreviated_content_type(response.headers());
158163
let raw_body = response.text().await.map_err(|error| FetchMetadataError::BodyRead {
159164
url: redact_url_credentials(&url),
160165
error,
@@ -180,6 +185,9 @@ pub async fn fetch_full_metadata_cached(
180185
let mut meta: Package = serde_json::from_str(&raw_body).map_err(|error| {
181186
FetchMetadataError::Decode { url: redact_url_credentials(&task_url), error }
182187
})?;
188+
if normalize_to_abbreviated {
189+
meta = normalize_abbreviated_meta(meta);
190+
}
183191
if should_filter_metadata {
184192
meta = clear_meta(&meta).map_err(|error| FetchMetadataError::FilterMetadata {
185193
url: redact_url_credentials(&task_url),

‎pacquet/crates/resolving-npm-resolver/src/fetch_full_metadata_cached/tests.rs‎

Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ use tempfile::TempDir;
33

44
use super::{FetchFullMetadataCachedOptions, fetch_full_metadata_cached};
55
use crate::mirror::{
6-
FULL_FILTERED_META_DIR, FULL_META_DIR, get_pkg_mirror_path, load_meta, load_meta_headers,
6+
ABBREVIATED_META_DIR, FULL_FILTERED_META_DIR, FULL_META_DIR, get_pkg_mirror_path, load_meta,
7+
load_meta_headers,
78
};
89

910
const PACKAGE_BODY: &str = r#"{
@@ -137,6 +138,109 @@ async fn filtered_full_cache_writes_filtered_mirror_on_200() {
137138
assert!(!manifest.other.contains_key("scripts"));
138139
}
139140

141+
const ACCEPT_ABBREVIATED: &str =
142+
"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*";
143+
144+
#[tokio::test]
145+
async fn a_full_doc_served_for_an_abbreviated_request_is_normalized_before_caching() {
146+
let mut server = mockito::Server::new_async().await;
147+
// A full document: what a registry that ignores the abbreviated `Accept`
148+
// header (e.g. Azure DevOps Artifacts) serves. It carries per-version
149+
// fields the resolver never reads.
150+
let full_body = PACKAGE_BODY.replace(
151+
r#""dist": {"#,
152+
r#""readme": "drop me", "scripts": { "postinstall": "node install.js" }, "exports": { ".": "./index.js" }, "dependencies": { "bar": "^1.0.0" }, "dist": {"#,
153+
);
154+
let mock = server
155+
.mock("GET", "/acme")
156+
.match_header("accept", ACCEPT_ABBREVIATED)
157+
.with_status(200)
158+
// application/json (not the abbreviated content type) signals that
159+
// the registry ignored the abbreviated `Accept` header and served
160+
// the full document.
161+
.with_header("content-type", "application/json")
162+
.with_body(full_body)
163+
.expect(1)
164+
.create_async()
165+
.await;
166+
167+
let cache = TempDir::new().expect("tempdir");
168+
let registry = format!("{}/", server.url());
169+
let http_client = ThrottledClient::default();
170+
let auth_headers = AuthHeaders::default();
171+
let opts = FetchFullMetadataCachedOptions {
172+
registry: &registry,
173+
http_client: &http_client,
174+
auth_headers: &auth_headers,
175+
cache_dir: Some(cache.path()),
176+
full_metadata: false,
177+
filter_metadata: false,
178+
retry_opts: no_retry_opts(),
179+
};
180+
181+
let pkg = fetch_full_metadata_cached("acme", &opts).await.expect("200 → ok");
182+
assert_eq!(pkg.name, "acme");
183+
mock.assert_async().await;
184+
185+
let mirror_path = get_pkg_mirror_path(cache.path(), ABBREVIATED_META_DIR, &registry, "acme")
186+
.expect("abbreviated path");
187+
let persisted = load_meta(&mirror_path).expect("mirror readable");
188+
let manifest = persisted.versions.get("1.0.0").expect("manifest");
189+
// Install-irrelevant fields dropped.
190+
assert!(!manifest.other.contains_key("readme"));
191+
assert!(!manifest.other.contains_key("scripts"));
192+
assert!(!manifest.other.contains_key("exports"));
193+
// Install-relevant fields kept, so resolution is unchanged.
194+
assert_eq!(
195+
manifest.dependencies.as_ref().and_then(|deps| deps.get("bar")).map(String::as_str),
196+
Some("^1.0.0"),
197+
);
198+
}
199+
200+
#[tokio::test]
201+
async fn a_doc_served_with_the_abbreviated_content_type_is_cached_verbatim() {
202+
let mut server = mockito::Server::new_async().await;
203+
// A custom per-version field proves the fragment is mirrored verbatim
204+
// (no stripping) on the honored-header happy path.
205+
let abbreviated_body =
206+
PACKAGE_BODY.replace(r#""dist": {"#, r#""_cacheUntouchedMarker": "kept", "dist": {"#);
207+
let mock = server
208+
.mock("GET", "/acme")
209+
.match_header("accept", ACCEPT_ABBREVIATED)
210+
.with_status(200)
211+
// Uppercase + a parameter: media-type detection must be
212+
// case-insensitive and drop parameters.
213+
.with_header("content-type", "APPLICATION/VND.NPM.INSTALL-V1+JSON; charset=utf-8")
214+
.with_body(abbreviated_body)
215+
.expect(1)
216+
.create_async()
217+
.await;
218+
219+
let cache = TempDir::new().expect("tempdir");
220+
let registry = format!("{}/", server.url());
221+
let http_client = ThrottledClient::default();
222+
let auth_headers = AuthHeaders::default();
223+
let opts = FetchFullMetadataCachedOptions {
224+
registry: &registry,
225+
http_client: &http_client,
226+
auth_headers: &auth_headers,
227+
cache_dir: Some(cache.path()),
228+
full_metadata: false,
229+
filter_metadata: false,
230+
retry_opts: no_retry_opts(),
231+
};
232+
233+
let pkg = fetch_full_metadata_cached("acme", &opts).await.expect("200 → ok");
234+
assert_eq!(pkg.name, "acme");
235+
mock.assert_async().await;
236+
237+
let mirror_path = get_pkg_mirror_path(cache.path(), ABBREVIATED_META_DIR, &registry, "acme")
238+
.expect("abbreviated path");
239+
let persisted = load_meta(&mirror_path).expect("mirror readable");
240+
let manifest = persisted.versions.get("1.0.0").expect("manifest");
241+
assert!(manifest.other.contains_key("_cacheUntouchedMarker"));
242+
}
243+
140244
#[tokio::test]
141245
async fn warm_cache_serves_from_mirror_on_304() {
142246
let mut server = mockito::Server::new_async().await;
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import type { PackageMeta } from '@pnpm/resolving.registry.types'
2+
import { pick } from 'ramda'
3+
4+
// The list taken from https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md#abbreviated-version-object
5+
// with the addition of 'libc'
6+
const ABBREVIATED_VERSION_FIELDS = [
7+
'name',
8+
'version',
9+
'bin',
10+
'directories',
11+
'devDependencies',
12+
'optionalDependencies',
13+
'dependencies',
14+
'peerDependencies',
15+
'dist',
16+
'engines',
17+
'peerDependenciesMeta',
18+
'cpu',
19+
'os',
20+
'libc',
21+
'deprecated',
22+
'bundleDependencies',
23+
'bundledDependencies',
24+
'hasInstallScript',
25+
'_npmUser',
26+
] as const
27+
28+
/**
29+
* Reduces a package metadata document to the abbreviated field set that the
30+
* resolver actually reads, dropping install-irrelevant fields (scripts,
31+
* exports, readme, custom `_`-prefixed fields, etc.).
32+
*
33+
* Used in two places:
34+
* - The network layer (`fetch.ts`) normalizes a registry that ignored the
35+
* abbreviated `Accept` header and returned a full document.
36+
* - The resolver (`pickPackage.ts`) narrows a deliberately-fetched full
37+
* document into the `filterMetadata` cache slot.
38+
*
39+
* Null-safe on `versions` so it can be called on an unpublished package (no
40+
* versions), which the abbreviated path can reach.
41+
*/
42+
export function clearMeta (pkg: PackageMeta): PackageMeta {
43+
// A null prototype so that a registry-controlled version key named
44+
// `__proto__` becomes a regular own property instead of mutating the
45+
// prototype of the map (js/prototype-polluting-assignment).
46+
const versions: PackageMeta['versions'] = Object.create(null)
47+
for (const [version, info] of Object.entries(pkg.versions ?? {})) {
48+
versions[version] = pick(ABBREVIATED_VERSION_FIELDS, info)
49+
}
50+
51+
return {
52+
name: pkg.name,
53+
'dist-tags': pkg['dist-tags'],
54+
versions,
55+
time: pkg.time,
56+
modified: pkg.modified,
57+
}
58+
}

0 commit comments

Comments
 (0)