From 57e04165148d81d7d9d84aeb61500bf5f53bb252 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Fri, 15 Nov 2024 13:30:29 +0100 Subject: [PATCH] fixup --- lib/cache/memory-cache-store.js | 24 +++++++++++++++++++++++- types/cache-interceptor.d.ts | 5 +++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/cache/memory-cache-store.js b/lib/cache/memory-cache-store.js index a7a379a11bf..37cd1929811 100644 --- a/lib/cache/memory-cache-store.js +++ b/lib/cache/memory-cache-store.js @@ -14,8 +14,11 @@ const { Writable } = require('node:stream') */ class MemoryCacheStore { #maxCount = Infinity + #maxSize = Infinity #maxEntrySize = Infinity + #size = 0 + /** * @type {Map>} */ @@ -42,6 +45,17 @@ class MemoryCacheStore { this.#maxCount = opts.maxCount } + if (opts.maxSize !== undefined) { + if ( + typeof opts.maxSize !== 'number' || + !Number.isInteger(opts.maxSize) || + opts.maxSize < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer') + } + this.#maxSize = opts.maxSize + } + if (opts.maxEntrySize !== undefined) { if ( typeof opts.maxEntrySize !== 'number' || @@ -56,7 +70,7 @@ class MemoryCacheStore { } get isFull () { - return this.#arr.length >= this.#maxCount + return this.#arr.length >= this.#maxCount || this.#size >= this.#maxSize } /** @@ -120,7 +134,12 @@ class MemoryCacheStore { let value = findValue(key, values) if (!value) { value = { ...opts, body } + store.#arr.push(value) + for (const buf of body) { + store.#size += buf.byteLength + } + values.push(value) } else { Object.assign(value, opts, { body }) @@ -172,6 +191,9 @@ class MemoryCacheStore { const count = Math.max(0, this.#arr.length - this.#maxCount / 2) for (const value of this.#arr.splice(0, count)) { + for (const buf of value.body) { + this.#size -= buf.byteLength + } value.body = null } diff --git a/types/cache-interceptor.d.ts b/types/cache-interceptor.d.ts index 015c2025eba..c104a0d08cd 100644 --- a/types/cache-interceptor.d.ts +++ b/types/cache-interceptor.d.ts @@ -79,6 +79,11 @@ declare namespace CacheHandler { */ maxCount?: number + /** + * @default Infinity + */ + maxSize?: number + /** * @default Infinity */