From 6745e96c64cf037266042b4557fab26300aa2b20 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 22 Sep 2024 16:06:10 -0500 Subject: [PATCH] SimpleLRU: fix repeated calls fetching --- src/utils/SimpleLRU.test.ts | 21 +++++++++++++++++++++ src/utils/SimpleLRU.ts | 10 ++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 src/utils/SimpleLRU.test.ts diff --git a/src/utils/SimpleLRU.test.ts b/src/utils/SimpleLRU.test.ts new file mode 100644 index 00000000..a73e4f36 --- /dev/null +++ b/src/utils/SimpleLRU.test.ts @@ -0,0 +1,21 @@ +import { SimpleLRU } from '@/utils/SimpleLRU.ts'; +import { assertEquals, assertRejects } from '@std/assert'; + +Deno.test("SimpleLRU doesn't repeat failed calls", async () => { + let calls = 0; + + const cache = new SimpleLRU( + // deno-lint-ignore require-await + async () => { + calls++; + throw new Error('gg'); + }, + { max: 100 }, + ); + + await assertRejects(() => cache.fetch('foo')); + assertEquals(calls, 1); + + await assertRejects(() => cache.fetch('foo')); + assertEquals(calls, 1); +}); diff --git a/src/utils/SimpleLRU.ts b/src/utils/SimpleLRU.ts index c48b8d0c..f18a6211 100644 --- a/src/utils/SimpleLRU.ts +++ b/src/utils/SimpleLRU.ts @@ -22,7 +22,13 @@ export class SimpleLRU< constructor(fetchFn: FetchFn, private opts: SimpleLRUOpts) { this.cache = new LRUCache({ - fetchMethod: (key, _staleValue, { signal }) => fetchFn(key, { signal: signal as unknown as AbortSignal }), + async fetchMethod(key, _staleValue, { signal }) { + try { + return await fetchFn(key, { signal: signal as unknown as AbortSignal }); + } catch { + return null as unknown as V; + } + }, ...opts, }); } @@ -32,7 +38,7 @@ export class SimpleLRU< this.opts.gauge?.set(this.cache.size); - if (result === undefined) { + if (result === undefined || result === null) { throw new Error('SimpleLRU: fetch failed'); }