refactor(common,core): extract single-flight+TTL cache primitive
阶段 1:把手写多份的「单飞+TTL 记忆化」收进一个 common 原语,消除各处
各自实现「TTL 判定 / inflight 去重 / finally 清理」的漂移风险(底层都是 Tencent
风控:忙碌客户端会为每条消息发一次未缓存 OIDB 拉取,持续爆发触发封号)。
- 新增 common/single-flight-cache.ts:createSingleFlightCache<K,V>({ ttlMs, load,
shouldCache?, now? }).get(key, {force});shouldCache 容纳「错误结果不缓存以便
重试」,now 可注入便于测 TTL。7 个单测覆盖新鲜命中/单飞去重/force/TTL 过期/
shouldCache/错误传播/invalidate。
- 迁移 contacts.fetchGroupMemberList(key=groupId, ttl 60s, 默认 shouldCache)与
update-check.getUpdateInfo(全局 key, ttl 6h, shouldCache=!error)。行为严格不变。
对抗性 Agent 逐条对比 HEAD 确认两处等价(含 update-check 时间戳来源毫秒级微差、
对 6h TTL 可忽略)。common 43 / core 467 全绿、typecheck 干净。
This commit is contained in:
5 files changed
+256
-40
No files matched your search
@@ -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<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
private readonly memberListCache: SingleFlightCache<number, GroupMemberInfo[]> =
|
||||
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<GroupMemberInfo[]> {
|
||||
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<GroupMemberInfo[]> {
|
||||
|
||||
@@ -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<UpdateCheckResult> | 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<string, UpdateCheckResult>({
|
||||
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<UpdateCheckResult> {
|
||||
const base: UpdateCheckResult = {
|
||||
@@ -133,21 +148,7 @@ export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
|
||||
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 {
|
||||
|
||||
Reference in new issue
Block a user