From f9a0055e78a582e26e88458bdc8ba1f5eaa6c798 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 17 May 2024 19:00:56 -0500 Subject: [PATCH] stats: add a Semaphore when refreshing author stats --- deno.json | 1 + src/stats.ts | 15 +++++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/deno.json b/deno.json index e8719a4..84d5351 100644 --- a/deno.json +++ b/deno.json @@ -20,6 +20,7 @@ "@bradenmacdonald/s3-lite-client": "jsr:@bradenmacdonald/s3-lite-client@^0.7.4", "@db/sqlite": "jsr:@db/sqlite@^0.11.1", "@isaacs/ttlcache": "npm:@isaacs/ttlcache@^1.4.1", + "@lambdalisue/async": "jsr:@lambdalisue/async@^2.1.1", "@noble/secp256k1": "npm:@noble/secp256k1@^2.0.0", "@nostrify/nostrify": "jsr:@nostrify/nostrify@^0.20.0", "@sentry/deno": "https://deno.land/x/sentry@7.112.2/index.mjs", diff --git a/src/stats.ts b/src/stats.ts index 9f0d257..7112496 100644 --- a/src/stats.ts +++ b/src/stats.ts @@ -1,3 +1,4 @@ +import { Semaphore } from '@lambdalisue/async'; import { NKinds, NostrEvent, NStore } from '@nostrify/nostrify'; import Debug from '@soapbox/stickynotes/debug'; import { InsertQueryBuilder, Kysely } from 'kysely'; @@ -253,13 +254,19 @@ async function countAuthorStats( }; } -const lru = new LRUCache({ max: 1000 }); +const authorStatsSemaphore = new Semaphore(10); +const refreshedAuthors = new LRUCache({ max: 1000 }); /** Calls `refreshAuthorStats` only once per author. */ function refreshAuthorStatsDebounced(pubkey: string): void { - if (lru.get(pubkey)) return; - lru.set(pubkey, true); - refreshAuthorStats(pubkey).catch(() => {}); + if (refreshedAuthors.get(pubkey)) { + return; + } + + refreshedAuthors.set(pubkey, true); + + authorStatsSemaphore + .lock(() => refreshAuthorStats(pubkey).catch(() => {})); } export { refreshAuthorStats, refreshAuthorStatsDebounced, updateStats };