stats: add a Semaphore when refreshing author stats

This commit is contained in:
Alex Gleason 2024-05-17 19:00:56 -05:00
parent 23a366081f
commit f9a0055e78
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
2 changed files with 12 additions and 4 deletions

View file

@ -20,6 +20,7 @@
"@bradenmacdonald/s3-lite-client": "jsr:@bradenmacdonald/s3-lite-client@^0.7.4", "@bradenmacdonald/s3-lite-client": "jsr:@bradenmacdonald/s3-lite-client@^0.7.4",
"@db/sqlite": "jsr:@db/sqlite@^0.11.1", "@db/sqlite": "jsr:@db/sqlite@^0.11.1",
"@isaacs/ttlcache": "npm:@isaacs/ttlcache@^1.4.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", "@noble/secp256k1": "npm:@noble/secp256k1@^2.0.0",
"@nostrify/nostrify": "jsr:@nostrify/nostrify@^0.20.0", "@nostrify/nostrify": "jsr:@nostrify/nostrify@^0.20.0",
"@sentry/deno": "https://deno.land/x/sentry@7.112.2/index.mjs", "@sentry/deno": "https://deno.land/x/sentry@7.112.2/index.mjs",

View file

@ -1,3 +1,4 @@
import { Semaphore } from '@lambdalisue/async';
import { NKinds, NostrEvent, NStore } from '@nostrify/nostrify'; import { NKinds, NostrEvent, NStore } from '@nostrify/nostrify';
import Debug from '@soapbox/stickynotes/debug'; import Debug from '@soapbox/stickynotes/debug';
import { InsertQueryBuilder, Kysely } from 'kysely'; import { InsertQueryBuilder, Kysely } from 'kysely';
@ -253,13 +254,19 @@ async function countAuthorStats(
}; };
} }
const lru = new LRUCache<string, true>({ max: 1000 }); const authorStatsSemaphore = new Semaphore(10);
const refreshedAuthors = new LRUCache<string, true>({ max: 1000 });
/** Calls `refreshAuthorStats` only once per author. */ /** Calls `refreshAuthorStats` only once per author. */
function refreshAuthorStatsDebounced(pubkey: string): void { function refreshAuthorStatsDebounced(pubkey: string): void {
if (lru.get(pubkey)) return; if (refreshedAuthors.get(pubkey)) {
lru.set(pubkey, true); return;
refreshAuthorStats(pubkey).catch(() => {}); }
refreshedAuthors.set(pubkey, true);
authorStatsSemaphore
.lock(() => refreshAuthorStats(pubkey).catch(() => {}));
} }
export { refreshAuthorStats, refreshAuthorStatsDebounced, updateStats }; export { refreshAuthorStats, refreshAuthorStatsDebounced, updateStats };