@vltpkg/registry-client 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,9 +8,11 @@ export type CacheEntryOptions = {
8
8
  /**
9
9
  * An optional body to use.
10
10
  *
11
- * This is used when decoding a cache entry from a buffer, and the body
12
- * is already in a ArrayBuffer we can use. When this option is
13
- * provided the `addBody` method should not be used.
11
+ * Adopted as-is (no copy). The caller must not mutate or reuse it.
12
+ * Used when decoding a cache entry from a buffer. Do not call
13
+ * `addBody` after providing this. Worker-thread transfers must
14
+ * copy or structuredClone first so the cache ArrayBuffer is not
15
+ * detached.
14
16
  */
15
17
  body?: Uint8Array;
16
18
  /**
@@ -65,6 +67,8 @@ export declare class CacheEntry {
65
67
  * Add contents to the entry body.
66
68
  */
67
69
  addBody(b: Uint8Array): void;
70
+ /** True when this entry was decoded from the on-disk cache. */
71
+ get fromCache(): boolean;
68
72
  get statusCode(): number;
69
73
  get headers(): Uint8Array[];
70
74
  /**
@@ -25,6 +25,17 @@ import { inspect } from 'node:util';
25
25
  import { gunzipSync } from 'node:zlib';
26
26
  import { getRawHeader, setRawHeader } from "./raw-header.js";
27
27
  import { getDecodedValue, getEncondedValue, } from "./string-encoding.js";
28
+ // same bound as @vltpkg/tar unpack: reject decompression bombs
29
+ // rather than committing unbounded memory to gunzipSync.
30
+ const MAX_DECOMPRESSION_RATIO = 1000;
31
+ const defaultMaxUnpackedBytes = 2 * 1024 * 1024 * 1024;
32
+ const parseMaxUnpackedBytes = (raw) => {
33
+ const n = Number(raw);
34
+ return Number.isFinite(n) && n >= 1 ?
35
+ Math.floor(n)
36
+ : defaultMaxUnpackedBytes;
37
+ };
38
+ const maxUnpackedBytes = parseMaxUnpackedBytes(process.env.VLT_TAR_MAX_UNPACKED_BYTES);
28
39
  const readSize = (buf, offset) => {
29
40
  const a = buf[offset];
30
41
  const b = buf[offset + 1];
@@ -64,6 +75,7 @@ export class CacheEntry {
64
75
  #json;
65
76
  #trustIntegrity;
66
77
  #staleWhileRevalidateFactor;
78
+ #fromCache = false;
67
79
  constructor(statusCode, headers, { body, integrity, trustIntegrity = false, 'stale-while-revalidate-factor': staleWhileRevalidateFactor = 60, contentLength, } = {}) {
68
80
  this.#headers = headers;
69
81
  this.#statusCode = statusCode;
@@ -76,12 +88,9 @@ export class CacheEntry {
76
88
  if (contentLength != null && typeof contentLength === 'number') {
77
89
  this.#contentLength = contentLength;
78
90
  }
79
- // if a body is provided then use that, in this case the `addBody`
80
- // method should no longer be used.
91
+ // if a body is provided then adopt it; `addBody` must not be used.
81
92
  if (body) {
82
- const buffer = new ArrayBuffer(body.byteLength);
83
- this.#body = new Uint8Array(buffer, 0, body.byteLength);
84
- this.#body.set(body, 0);
93
+ this.#body = body;
85
94
  this.#bodyLength = body.byteLength;
86
95
  /* c8 ignore start */
87
96
  }
@@ -160,17 +169,18 @@ export class CacheEntry {
160
169
  this.#cacheControl = cc ? ccp.parse(cc) : {};
161
170
  return this.#cacheControl;
162
171
  }
163
- #staleWhileRevalidate;
172
+ #staleUntil;
164
173
  get staleWhileRevalidate() {
165
- if (this.#staleWhileRevalidate !== undefined)
166
- return this.#staleWhileRevalidate;
174
+ // memoize the deadline, not the answer, so an entry held for a
175
+ // long time (decoded-entry memo, long-lived process) still expires
176
+ if (this.#staleUntil !== undefined)
177
+ return Date.now() < this.#staleUntil;
167
178
  if (this.valid || !this.date)
168
179
  return true;
169
180
  const swv = this.cacheControl['stale-while-revalidate'] ??
170
181
  this.maxAge * this.#staleWhileRevalidateFactor;
171
- this.#staleWhileRevalidate =
172
- this.date.getTime() + swv * 1000 > Date.now();
173
- return this.#staleWhileRevalidate;
182
+ this.#staleUntil = this.date.getTime() + swv * 1000;
183
+ return Date.now() < this.#staleUntil;
174
184
  }
175
185
  #contentType;
176
186
  get contentType() {
@@ -184,9 +194,15 @@ export class CacheEntry {
184
194
  * valid to use.
185
195
  */
186
196
  #valid;
197
+ #validUntil;
187
198
  get valid() {
188
199
  if (this.#valid !== undefined)
189
200
  return this.#valid;
201
+ // time-based validity memoizes the deadline, not the answer, so
202
+ // an entry held for a long time (decoded-entry memo, long-lived
203
+ // process) still expires and gets revalidated
204
+ if (this.#validUntil !== undefined)
205
+ return Date.now() < this.#validUntil;
190
206
  // immutable = never changes
191
207
  if (this.cacheControl.immutable)
192
208
  return (this.#valid = true);
@@ -201,9 +217,8 @@ export class CacheEntry {
201
217
  // do not set a cache control header at all.
202
218
  if (!this.date)
203
219
  return (this.#valid = false);
204
- this.#valid =
205
- this.date.getTime() + this.maxAge * 1000 > Date.now();
206
- return this.#valid;
220
+ this.#validUntil = this.date.getTime() + this.maxAge * 1000;
221
+ return Date.now() < this.#validUntil;
207
222
  }
208
223
  /**
209
224
  * Add contents to the entry body.
@@ -222,6 +237,10 @@ export class CacheEntry {
222
237
  this.#bodyLength += b.byteLength;
223
238
  }
224
239
  }
240
+ /** True when this entry was decoded from the on-disk cache. */
241
+ get fromCache() {
242
+ return this.#fromCache;
243
+ }
225
244
  get statusCode() {
226
245
  return this.#statusCode;
227
246
  }
@@ -335,12 +354,15 @@ export class CacheEntry {
335
354
  // if it says it's json, assume json
336
355
  if (ct)
337
356
  return (this.#isJSON = /\bjson\b/.test(ct));
338
- const text = this.text();
339
357
  // don't cache, because we might just not have it yet.
340
- if (!text)
358
+ if (!this._body.length)
359
+ return false;
360
+ this.unzip();
361
+ const buf = this._body;
362
+ if (!buf.length)
341
363
  return false;
342
364
  // all registry json starts with {, and no tarball ever can.
343
- this.#isJSON = text.startsWith('{');
365
+ this.#isJSON = buf[0] === 0x7b;
344
366
  if (this.#isJSON)
345
367
  this.setHeader('content-type', 'text/json');
346
368
  return this.#isJSON;
@@ -378,7 +400,21 @@ export class CacheEntry {
378
400
  if (this._body.length === 0)
379
401
  throw error('Invalid buffer, cant unzip');
380
402
  /* c8 ignore stop */
381
- const b = gunzipSync(this._body);
403
+ const max = Math.min(maxUnpackedBytes, this._body.length * MAX_DECOMPRESSION_RATIO);
404
+ let b;
405
+ try {
406
+ b = gunzipSync(this._body, { maxOutputLength: max });
407
+ }
408
+ catch (er) {
409
+ throw (er.code ===
410
+ 'ERR_BUFFER_TOO_LARGE') ?
411
+ error('cache entry exceeds maximum unpacked size', {
412
+ found: this._body.length,
413
+ max,
414
+ cause: er,
415
+ })
416
+ : er;
417
+ }
382
418
  this.setHeader('content-encoding', 'identity');
383
419
  const u8 = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
384
420
  this.#body = u8;
@@ -447,14 +483,17 @@ export class CacheEntry {
447
483
  trustIntegrity: true,
448
484
  contentLength: body.byteLength,
449
485
  });
450
- if (c.isJSON) {
451
- try {
452
- c.json();
453
- }
454
- catch {
455
- return emptyCacheEntry;
486
+ c.#fromCache = true;
487
+ try {
488
+ if (c.isJSON) {
489
+ c.unzip();
490
+ if (!looksLikeJson(c._body))
491
+ return emptyCacheEntry;
456
492
  }
457
493
  }
494
+ catch {
495
+ return emptyCacheEntry;
496
+ }
458
497
  return c;
459
498
  }
460
499
  static isGzipEntry(buffer) {
@@ -514,4 +553,42 @@ export class CacheEntry {
514
553
  return out;
515
554
  }
516
555
  }
556
+ const isJsonWs = (c) => c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d;
557
+ const looksLikeJson = (buf) => {
558
+ // skip a UTF-8 BOM; TextDecoder strips it when the body is parsed
559
+ const bom = buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf ? 3 : 0;
560
+ // an empty body is parsed as '{}' by json()
561
+ if (buf.byteLength === bom)
562
+ return true;
563
+ let first;
564
+ let start = bom;
565
+ for (let i = bom; i < buf.byteLength; i++) {
566
+ const c = buf[i];
567
+ /* c8 ignore start */
568
+ if (c === undefined)
569
+ break;
570
+ /* c8 ignore stop */
571
+ if (!isJsonWs(c)) {
572
+ first = c;
573
+ break;
574
+ }
575
+ start++;
576
+ }
577
+ if (first === undefined)
578
+ return false;
579
+ let last = first;
580
+ for (let j = buf.byteLength - 1; j > start; j--) {
581
+ const c = buf[j];
582
+ /* c8 ignore start */
583
+ if (c === undefined)
584
+ break;
585
+ /* c8 ignore stop */
586
+ if (!isJsonWs(c)) {
587
+ last = c;
588
+ break;
589
+ }
590
+ }
591
+ return ((first === 0x7b && last === 0x7d) ||
592
+ (first === 0x5b && last === 0x5d));
593
+ };
517
594
  const emptyCacheEntry = new CacheEntry(0, [], { contentLength: 0 });
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import module from 'node:module';
2
3
  import { __CODE_SPLIT_SCRIPT_NAME } from "./revalidate.js";
3
4
  const isDeno = globalThis.Deno != undefined;
4
5
  let didProcessBeforeExitHook = false;
@@ -14,11 +15,17 @@ export const register = (path, method, url) => {
14
15
  }
15
16
  };
16
17
  const handleBeforeExit = () => {
18
+ // The compile cache is enabled in-process by the CLI entry, which does
19
+ // not propagate to child processes, so the worker has to be pointed at
20
+ // it through the environment to skip re-compiling its bundle.
21
+ const compileCacheDir = module.getCompileCacheDir();
17
22
  for (const [path, r] of registered) {
18
23
  /* c8 ignore next */
19
24
  if (!r.size)
20
25
  return;
21
26
  const env = { ...process.env };
27
+ if (compileCacheDir)
28
+ env.NODE_COMPILE_CACHE ??= compileCacheDir;
22
29
  const args = [];
23
30
  /* c8 ignore start */
24
31
  // If we are running deno from source we need to add the
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { logRequest } from '@vltpkg/output';
6
6
  import { urlOpen } from '@vltpkg/url-open';
7
7
  import { XDG } from '@vltpkg/xdg';
8
8
  import { randomUUID } from 'node:crypto';
9
+ import { availableParallelism } from 'node:os';
9
10
  import { dirname, resolve } from 'node:path';
10
11
  import { setTimeout } from 'node:timers/promises';
11
12
  import { loadPackageJson } from 'package-json-from-dist';
@@ -33,6 +34,22 @@ const nua = globalThis.navigator?.userAgent ??
33
34
  : node ? `Node.js/${node}`
34
35
  : '(unknown platform)');
35
36
  export const userAgent = `@vltpkg/registry-client/${version} ${nua}`;
37
+ // Agent-level knobs only. Do not spread these onto per-request options —
38
+ // connections/pipelining/keepAlive/connect are ignored at dispatch time,
39
+ // and bodyTimeout/headersTimeout would clobber caller overrides.
40
+ //
41
+ // Keep undici (not globalThis.fetch): fetch measured +56% user CPU and
42
+ // +90–140MB RSS on the same 753-body install workload.
43
+ // pipelining:1 is intentional — pipelining:10 had no measured CPU benefit
44
+ // and HOL-blocks packuments behind large tarballs; some CDNs drop pipelined
45
+ // requests.
46
+ // connections scales with reify's in-flight cap ((cores-1)*8, see
47
+ // src/graph/src/reify/index.ts) so tarball fetches don't queue behind
48
+ // the pool on many-core machines. The floor of 64 bounds cold-start TLS
49
+ // on small machines; the ceiling of 128 avoids connection storms and
50
+ // CDN throttling beyond what reify can consume.
51
+ // HTTP/2 (allowH2) is untested and unjustified while transport CPU is ~1/4
52
+ // of body handling.
36
53
  const agentOptions = {
37
54
  bodyTimeout: 600_000,
38
55
  headersTimeout: 600_000,
@@ -45,16 +62,24 @@ const agentOptions = {
45
62
  keepAliveInitialDelay: 30_000,
46
63
  sessionTimeout: 600,
47
64
  },
48
- connections: 128,
49
- pipelining: 10,
65
+ connections: Math.min(128, Math.max(64, (availableParallelism() - 1) * 8)),
66
+ pipelining: 1,
50
67
  };
51
68
  const xdg = new XDG('vlt');
69
+ const defaultCacheMaxSize = 256 * 1024 * 1024;
70
+ const parseCacheMaxSize = (raw) => {
71
+ const n = Number(raw);
72
+ return Number.isFinite(n) && n >= 1 ?
73
+ Math.floor(n)
74
+ : defaultCacheMaxSize;
75
+ };
52
76
  export class RegistryClient {
53
77
  agent;
54
78
  cache;
55
79
  identity;
56
80
  staleWhileRevalidateFactor;
57
81
  #session = randomUUID();
82
+ #decoded = new WeakMap();
58
83
  constructor(options) {
59
84
  const { cache = xdg.cache(), 'fetch-retry-factor': timeoutFactor = 2, 'fetch-retry-mintimeout': minTimeout = 0, 'fetch-retry-maxtimeout': maxTimeout = 30_000, 'fetch-retries': maxRetries = 3, identity = '', 'stale-while-revalidate-factor': staleWhileRevalidateFactor = 576, // 48h for a 5min cache
60
85
  } = options;
@@ -63,6 +88,7 @@ export class RegistryClient {
63
88
  const path = resolve(cache, 'registry-client');
64
89
  this.cache = new Cache({
65
90
  path,
91
+ maxSize: parseCacheMaxSize(process.env.VLT_CACHE_MAX_SIZE),
66
92
  onDiskWrite(_path, key, data) {
67
93
  if (CacheEntry.isGzipEntry(data)) {
68
94
  cacheUnzipRegister(path, key);
@@ -186,6 +212,28 @@ export class RegistryClient {
186
212
  /* c8 ignore stop */
187
213
  return result;
188
214
  }
215
+ #decodeCached(buffer) {
216
+ const hit = this.#decoded.get(buffer);
217
+ if (hit)
218
+ return hit;
219
+ const entry = CacheEntry.decode(buffer);
220
+ // statusCode 0 == undecodable, and a cached JSON body that fails
221
+ // to parse is corrupt. Treat both as a total miss: the caller
222
+ // refetches without conditional headers, so a fresh response
223
+ // overwrites the bad entry rather than a 304 re-blessing it.
224
+ if (!entry.statusCode)
225
+ return undefined;
226
+ if (entry.isJSON) {
227
+ try {
228
+ entry.json();
229
+ }
230
+ catch {
231
+ return undefined;
232
+ }
233
+ this.#decoded.set(buffer, entry);
234
+ }
235
+ return entry;
236
+ }
189
237
  async #checkLogin(url, options = {}) {
190
238
  const response = await this.request(url, {
191
239
  ...options,
@@ -216,12 +264,14 @@ export class RegistryClient {
216
264
  const m = isCacheableMethod(method) ? method : undefined;
217
265
  const { useCache = !!m } = options;
218
266
  signal?.throwIfAborted();
219
- // first, try to get from the cache before making any request.
267
+ // Method + URL only. Headers (including accept) are not part of the
268
+ // key and there is no Vary handling — callers must not vary the
269
+ // response representation for the same URL.
220
270
  const key = `${method !== 'GET' ? method + ' ' : ''}${u}`;
221
271
  const buffer = useCache ?
222
272
  await this.cache.fetch(key, { context: { integrity } })
223
273
  : undefined;
224
- const entry = buffer ? CacheEntry.decode(buffer) : undefined;
274
+ const entry = buffer ? this.#decodeCached(buffer) : undefined;
225
275
  if (entry?.valid) {
226
276
  logRequest(url, 'cache', { method });
227
277
  return entry;
@@ -237,10 +287,8 @@ export class RegistryClient {
237
287
  // either no cache entry, or need to revalidate before use.
238
288
  setCacheHeaders(options, entry);
239
289
  redirections.add(String(url));
240
- Object.assign(options, {
241
- path: u.pathname.replace(/\/+$/, '') + u.search,
242
- ...agentOptions,
243
- });
290
+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- deprecated for callers; this is the one place that sets it
291
+ options.path = u.pathname.replace(/\/+$/, '') + u.search;
244
292
  options.origin = u.origin;
245
293
  options.headers = addHeader(addHeader(addHeader(options.headers, 'accept-encoding', 'gzip;q=1.0, identity;q=0.5'), 'user-agent', userAgent), 'npm-session', this.#session);
246
294
  if (otp) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vltpkg/registry-client",
3
3
  "description": "Fetch package artifacts and metadata from registries",
4
- "version": "1.0.2",
4
+ "version": "1.0.4",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,14 +13,14 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
16
- "@vltpkg/cache": "1.0.2",
17
- "@vltpkg/cache-unzip": "1.0.2",
18
- "@vltpkg/error-cause": "1.0.2",
19
- "@vltpkg/keychain": "1.0.2",
20
- "@vltpkg/output": "1.0.2",
21
- "@vltpkg/types": "1.0.2",
22
- "@vltpkg/url-open": "1.0.2",
23
- "@vltpkg/xdg": "1.0.2",
16
+ "@vltpkg/cache": "1.0.4",
17
+ "@vltpkg/cache-unzip": "1.0.4",
18
+ "@vltpkg/error-cause": "1.0.4",
19
+ "@vltpkg/keychain": "1.0.4",
20
+ "@vltpkg/output": "1.0.4",
21
+ "@vltpkg/types": "1.0.4",
22
+ "@vltpkg/url-open": "1.0.4",
23
+ "@vltpkg/xdg": "1.0.4",
24
24
  "cache-control-parser": "^2.0.6",
25
25
  "package-json-from-dist": "^1.0.1",
26
26
  "undici": "^7.16.0"