diff --git a/packages/common/package.json b/packages/common/package.json index 374511fe..e0cb2dbd 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -20,6 +20,10 @@ "types": "./src/coerce.ts", "default": "./src/coerce.ts" }, + "./single-flight-cache": { + "types": "./src/single-flight-cache.ts", + "default": "./src/single-flight-cache.ts" + }, "./hex": { "types": "./src/hex.ts", "default": "./src/hex.ts" diff --git a/packages/common/src/single-flight-cache.ts b/packages/common/src/single-flight-cache.ts new file mode 100644 index 00000000..4b21ab0b --- /dev/null +++ b/packages/common/src/single-flight-cache.ts @@ -0,0 +1,93 @@ +/** + * Single-flight + TTL memoization. + * + * Concentrates the "don't refetch what's fresh, and don't stampede the same + * key with concurrent loads" pattern that was hand-rolled (slightly + * differently each time) across the codebase — e.g. `ContactsApi`'s group + * member-list cache and the WebUI update-check. Each copy re-implemented the + * same fiddly trio: a TTL freshness check, an in-flight promise map to + * de-dupe concurrent callers, and `finally`-cleanup of that map. Getting any + * of the three subtly wrong (forgetting the `finally`, caching an error, + * racing the timestamp) is a real hazard — so it lives in one place. + * + * The underlying concern is Tencent risk-control: a busy OneBot client can + * fan out one uncached OIDB fetch per inbound message, and sustained bursts + * trip a ban. TTL + single-flight collapse that fan-out. + */ + +export interface SingleFlightCacheOptions { + /** Freshness window in ms. A cached entry older than this is reloaded. */ + ttlMs: number; + /** Load the value for a key. Rejections propagate and are never cached. */ + load: (key: K) => Promise; + /** + * Decide whether a resolved value should be cached. Default: always. + * Return `false` to leave an entry uncached (e.g. an error-shaped result the + * next call should retry) while still de-duping concurrent in-flight callers. + */ + shouldCache?: (value: V) => boolean; + /** Clock, injectable for tests. Defaults to `Date.now`. */ + now?: () => number; +} + +export class SingleFlightCache { + private readonly ttlMs: number; + private readonly load: (key: K) => Promise; + private readonly shouldCache: (value: V) => boolean; + private readonly now: () => number; + private readonly fresh = new Map(); + private readonly inflight = new Map>(); + + constructor(opts: SingleFlightCacheOptions) { + this.ttlMs = opts.ttlMs; + this.load = opts.load; + this.shouldCache = opts.shouldCache ?? (() => true); + this.now = opts.now ?? Date.now; + } + + /** + * Get the value for `key`. + * + * - Returns a fresh cached value when the last load was within `ttlMs`. + * - Otherwise de-dupes concurrent callers onto a single `load()` and caches + * the result (subject to `shouldCache`). A rejected `load` propagates to + * every joined caller, clears the in-flight slot, and is not cached. + * - `force` bypasses the freshness check but still joins an in-flight load + * rather than starting a second one. + */ + get(key: K, opts: { force?: boolean } = {}): Promise { + if (!opts.force) { + const hit = this.fresh.get(key); + if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value); + } + const existing = this.inflight.get(key); + if (existing) return existing; + const task = (async () => { + try { + const value = await this.load(key); + if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value }); + return value; + } finally { + this.inflight.delete(key); + } + })(); + this.inflight.set(key, task); + return task; + } + + /** Drop a cached entry. Does not abort an in-flight load. */ + invalidate(key: K): void { + this.fresh.delete(key); + } + + /** Drop all cached entries. Does not abort in-flight loads. */ + clear(): void { + this.fresh.clear(); + } +} + +export function createSingleFlightCache( + opts: SingleFlightCacheOptions, +): SingleFlightCache { + return new SingleFlightCache(opts); +} diff --git a/packages/common/tests/single-flight-cache.test.ts b/packages/common/tests/single-flight-cache.test.ts new file mode 100644 index 00000000..77233282 --- /dev/null +++ b/packages/common/tests/single-flight-cache.test.ts @@ -0,0 +1,131 @@ +import { describe, it, expect, vi } from 'vitest'; +import { createSingleFlightCache } from '../src/single-flight-cache'; + +/** A promise whose resolve/reject is exposed, for driving single-flight races. */ +function deferred() { + let resolve!: (v: T) => void; + let reject!: (e: unknown) => void; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + return { promise, resolve, reject }; +} + +describe('SingleFlightCache', () => { + it('caches within the TTL and reloads once expired', async () => { + let clock = 1000; + const load = vi.fn(async (k: string) => `${k}@${clock}`); + const cache = createSingleFlightCache({ ttlMs: 100, load, now: () => clock }); + + expect(await cache.get('a')).toBe('a@1000'); + clock = 1050; // still fresh (< 100) + expect(await cache.get('a')).toBe('a@1000'); + expect(load).toHaveBeenCalledTimes(1); + + clock = 1101; // 101ms since store → expired + expect(await cache.get('a')).toBe('a@1101'); + expect(load).toHaveBeenCalledTimes(2); + }); + + it('de-dupes concurrent callers onto a single load (single-flight)', async () => { + const d = deferred(); + const load = vi.fn(() => d.promise); + const cache = createSingleFlightCache({ ttlMs: 1000, load }); + + const p1 = cache.get('k'); + const p2 = cache.get('k'); + const p3 = cache.get('k'); + expect(load).toHaveBeenCalledTimes(1); // only one load in flight + + d.resolve('v'); + expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']); + expect(load).toHaveBeenCalledTimes(1); + }); + + it('keys independently — different keys load separately', async () => { + const load = vi.fn(async (k: number) => k * 2); + const cache = createSingleFlightCache({ ttlMs: 1000, load }); + expect(await cache.get(1)).toBe(2); + expect(await cache.get(2)).toBe(4); + expect(load).toHaveBeenCalledTimes(2); + }); + + it('force bypasses the freshness check but still joins an in-flight load', async () => { + let clock = 0; + const load = vi.fn(async (k: string) => `${k}@${clock}`); + const cache = createSingleFlightCache({ ttlMs: 10_000, load, now: () => clock }); + + expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh + clock = 5; // still fresh + expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh + expect(load).toHaveBeenCalledTimes(2); + + // force still single-flights: two concurrent forced gets share one load. + const d = deferred(); + load.mockImplementationOnce(() => d.promise); + const p1 = cache.get('a', { force: true }); + const p2 = cache.get('a', { force: true }); + expect(load).toHaveBeenCalledTimes(3); // not 4 + d.resolve('shared'); + expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']); + }); + + it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => { + let n = 0; + const load = vi.fn(async () => ({ error: true as boolean, n: ++n })); + const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error }); + + // concurrent callers still share one load... + const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]); + expect(a).toEqual({ error: true, n: 1 }); + expect(b).toEqual({ error: true, n: 1 }); + expect(load).toHaveBeenCalledTimes(1); + + // ...but nothing was cached, so the next call reloads. + expect(await cache.get('k')).toEqual({ error: true, n: 2 }); + expect(load).toHaveBeenCalledTimes(2); + + // a good result IS cached. + load.mockImplementationOnce(async () => ({ error: false, n: ++n })); + const good = await cache.get('k'); + expect(good).toEqual({ error: false, n: 3 }); + expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache + expect(load).toHaveBeenCalledTimes(3); + }); + + it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => { + let attempt = 0; + const load = vi.fn(async () => { + attempt++; + if (attempt === 1) throw new Error('boom'); + return 'ok'; + }); + const cache = createSingleFlightCache({ ttlMs: 10_000, load }); + + const p1 = cache.get('k'); + const p2 = cache.get('k'); + await expect(p1).rejects.toThrow('boom'); + await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection + expect(load).toHaveBeenCalledTimes(1); + + // in-flight cleared + not cached → next call retries and succeeds. + expect(await cache.get('k')).toBe('ok'); + expect(load).toHaveBeenCalledTimes(2); + }); + + it('invalidate drops a cached entry; clear drops all', async () => { + const load = vi.fn(async (k: string) => k.toUpperCase()); + const cache = createSingleFlightCache({ ttlMs: 10_000, load }); + await cache.get('a'); + await cache.get('b'); + expect(load).toHaveBeenCalledTimes(2); + + cache.invalidate('a'); + await cache.get('a'); // reloads + await cache.get('b'); // still cached + expect(load).toHaveBeenCalledTimes(3); + + cache.clear(); + await cache.get('a'); + await cache.get('b'); + expect(load).toHaveBeenCalledTimes(5); + }); +}); diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index 24a9618b..6514b216 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -8,6 +8,7 @@ import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetc import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid'; import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark'; import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark'; +import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache'; import type { FriendInfo, GroupMemberInfo, @@ -55,16 +56,19 @@ const MEMBER_LIST_TTL_MS = 60_000; export class ContactsApi { /** - * Per-group inflight + last-fetch cache for `fetchGroupMemberList`. - * Keyed by groupId, lives for the lifetime of the Bridge. + * Per-group TTL + single-flight cache for `fetchGroupMemberList`, keyed by + * groupId, living for the lifetime of the Bridge. * * Without this, a busy OneBot client (e.g. MaiBot calling * `get_group_member_info` once per inbound message) triggers one * OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips * Tencent risk-control and gets the account banned for 7 days. */ - private memberListInflight = new Map>(); - private memberListLastFetch = new Map(); + private readonly memberListCache: SingleFlightCache = + createSingleFlightCache({ + ttlMs: MEMBER_LIST_TTL_MS, + load: (groupId) => this.fetchGroupMemberListUncached(groupId), + }); constructor(private readonly ctx: BridgeContext) { } @@ -139,28 +143,11 @@ export class ContactsApi { }; } - async fetchGroupMemberList( + fetchGroupMemberList( groupId: number, options: { force?: boolean } = {}, ): Promise { - const now = Date.now(); - const last = this.memberListLastFetch.get(groupId); - if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) { - return last.data; - } - const inflight = this.memberListInflight.get(groupId); - if (inflight) return inflight; - const task = (async () => { - try { - const data = await this.fetchGroupMemberListUncached(groupId); - this.memberListLastFetch.set(groupId, { at: Date.now(), data }); - return data; - } finally { - this.memberListInflight.delete(groupId); - } - })(); - this.memberListInflight.set(groupId, task); - return task; + return this.memberListCache.get(groupId, { force: options.force }); } private async fetchGroupMemberListUncached(groupId: number): Promise { diff --git a/packages/core/src/webui/update-check.ts b/packages/core/src/webui/update-check.ts index c1c6da30..1b122b4b 100644 --- a/packages/core/src/webui/update-check.ts +++ b/packages/core/src/webui/update-check.ts @@ -11,6 +11,7 @@ // "无法检查更新" rather than nagging). import { createLogger } from '@snowluma/common/logger'; +import { createSingleFlightCache } from '@snowluma/common/single-flight-cache'; const log = createLogger('Update'); @@ -79,8 +80,22 @@ export function compareVersions(a: string, b: string): number { return pa.pre < pb.pre ? -1 : 1; } -let cache: UpdateCheckResult | null = null; -let inflight: Promise | null = null; +// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's +// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results +// are intentionally not cached (shouldCache) so the next check retries. +const updateCache = createSingleFlightCache({ + ttlMs: CACHE_TTL_MS, + shouldCache: (r) => !r.error, + load: async (current) => { + const result = await fetchLatest(current); + if (result.error) { + log.debug('update check failed: %s', result.error); + } else if (result.hasUpdate) { + log.info('a newer release is available: v%s (running v%s)', result.latest, current); + } + return result; + }, +}); async function fetchLatest(current: string): Promise { const base: UpdateCheckResult = { @@ -133,21 +148,7 @@ export async function getUpdateInfo(force = false): Promise { if (!isEnabled()) { return { ...emptyResult(current), error: 'disabled' }; } - if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache; - if (inflight) return inflight; - inflight = (async () => { - const result = await fetchLatest(current); - if (result.error) { - log.debug('update check failed: %s', result.error); - } else { - cache = result; // only cache good results so transient errors retry - if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current); - } - return result; - })().finally(() => { - inflight = null; - }); - return inflight; + return updateCache.get(current, { force }); } function emptyResult(current: string): UpdateCheckResult {