fix(common): release retained cache and log memory

Dispose contact caches with account sessions and prevent late loads from restoring timers. Release discarded log content while preserving visible text.

Refs #651
This commit is contained in:
DrSmoothl committed 2026-11-04 23:23:44 +08:00
1 parent ae1ec3be0e
commit b6b433af98
8 files changed
+226 -1

No files matched your search

+10 -1
View File
@@ -117,5 +117,14 @@ export function sanitizeLogLine(line: string): string {
// Join contiguous spans once. Appending each character creates a retained
// V8 cons-string node per character in the in-memory log rings.
parts.push(line.slice(start));
return parts.join('');
const plain = parts.join('');
// A single visible span can remain a slice of the original input after join.
// Copy when that would retain more discarded text than visible text. Splitting
// into UTF-16 code units preserves unpaired surrogates and works in browsers.
if (plain.length > 0 && plain.length < line.length / 2) {
return plain.split('').join('');
}
return plain;
}
@@ -23,6 +23,7 @@ export class SingleFlightCache<K, V> {
private readonly fresh = new Map<K, { at: number; value: V }>();
private readonly inflight = new Map<K, Promise<V>>();
private expiryTimer: ReturnType<typeof setTimeout> | undefined;
private disposed = false;
constructor(opts: SingleFlightCacheOptions<K, V>) {
this.ttlMs = opts.ttlMs;
@@ -47,6 +48,10 @@ export class SingleFlightCache<K, V> {
* rather than starting a second one.
*/
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
if (this.disposed) {
return Promise.reject(new Error('SingleFlightCache is disposed'));
}
const hit = this.fresh.get(key);
if (hit) {
@@ -100,6 +105,12 @@ export class SingleFlightCache<K, V> {
this.cancelExpiryIfEmpty();
}
/** Release this owner's cache permanently; pending callers still settle. */
dispose(): void {
this.disposed = true;
this.clear();
}
private cancelExpiryIfEmpty(): void {
if (this.fresh.size === 0 && this.expiryTimer !== undefined) {
clearTimeout(this.expiryTimer);
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest';
import { execFileSync } from 'node:child_process';
import { sanitizeLogLine } from '../src/log-sanitize';
describe('sanitizeLogLine', () => {
@@ -44,4 +45,43 @@ describe('sanitizeLogLine', () => {
expect(sanitizeLogLine('a\x00\x1b[31m\u009b0m\r\u007fb')).toBe('ab');
expect(sanitizeLogLine('')).toBe('');
});
it('preserves every visible UTF-16 code unit when removing a large hidden payload', () => {
const visible = 'visible 🌌 e\u0301\ud800x\udc00';
expect(sanitizeLogLine(`${visible}\x1b]${'hidden'.repeat(1000)}`)).toBe(visible);
});
it('does not retain discarded control-string payloads through a short visible span', () => {
const moduleUrl = new URL('../src/log-sanitize.ts', import.meta.url).href;
const output = execFileSync(
process.execPath,
[
'--expose-gc',
'--input-type=module',
'-e',
`
import { setImmediate } from 'node:timers/promises';
import { sanitizeLogLine } from ${JSON.stringify(moduleUrl)};
async function used() {
await setImmediate();
global.gc();
global.gc();
return process.memoryUsage().heapUsed;
}
function record(i) {
return sanitizeLogLine('visible record ' + i + '\\x1b]' + 'x'.repeat(1024 * 1024));
}
const before = await used();
const records = Array.from({ length: 16 }, (_, i) => record(i));
const retained = (await used()) - before;
console.log(JSON.stringify({ retained, records }));
`,
],
{ encoding: 'utf8', timeout: 10_000 },
);
const result = JSON.parse(output);
expect(result.records).toEqual(Array.from({ length: 16 }, (_, i) => `visible record ${i}`));
// Leave ample GC/runtime overhead while rejecting retention of the 16 MiB input.
expect(result.retained).toBeLessThan(4 * 1024 * 1024);
});
});
@@ -17,6 +17,48 @@ describe('SingleFlightCache', () => {
vi.useRealTimers();
});
it('disposes retained values and rejects new reads without restarting loads or timers', async () => {
vi.useFakeTimers();
const load = vi.fn(async (key: string) => ({ key }));
const cache = createSingleFlightCache({ ttlMs: 300_000, load });
await cache.get('first');
await cache.get('second');
expect(vi.getTimerCount()).toBe(1);
cache.dispose();
cache.dispose();
cache.clear();
expect(cache.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
await expect(cache.get('first')).rejects.toThrow('disposed');
await expect(cache.get('new', { force: true })).rejects.toThrow('disposed');
expect(load).toHaveBeenCalledTimes(2);
});
it.each(['resolve', 'reject'] as const)(
'preserves a pending %s after disposal without retaining the result',
async (outcome) => {
vi.useFakeTimers();
const pending = deferred<string>();
const cache = createSingleFlightCache({ ttlMs: 300_000, load: () => pending.promise });
const first = cache.get('key');
expect(cache.get('key')).toBe(first);
cache.dispose();
if (outcome === 'resolve') {
pending.resolve('late value');
await expect(first).resolves.toBe('late value');
} else {
pending.reject(new Error('late failure'));
await expect(first).rejects.toThrow('late failure');
}
expect(cache.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
},
);
it('releases expired values while idle without expiring newer values early', async () => {
vi.useFakeTimers();
const load = vi.fn(async (key: string) => ({ key }));
@@ -132,6 +132,12 @@ export class ContactsApi {
constructor(private readonly ctx: BridgeContext) {}
dispose(): void {
// Late roster responses must not start new profile loads after shutdown.
this.memberListCache.dispose();
this.friendProfiles.dispose();
}
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
if (this.robotUinRangesPromise_) {
return this.robotUinRangesPromise_;
+1
View File
@@ -102,6 +102,7 @@ export class Bridge implements BridgeInterface {
this.disposePromise_ = (async () => {
try {
await Promise.allSettled(this.pendingPackets_);
this.apis.contacts.dispose();
await this.identity.close();
} finally {
this.events.clear();
@@ -26,6 +26,7 @@ const bridges: Bridge[] = [];
afterEach(async () => {
await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose()));
vi.restoreAllMocks();
vi.useRealTimers();
});
function friend(uin: number, name = 'Roster'): OidbFriend {
@@ -118,6 +119,40 @@ function setup(roster: () => OidbFriend[], load: (uin: number) => Promise<void>
}
describe('explicit friend profile enrichment', () => {
it('releases profile cache timers when its Bridge is disposed', async () => {
vi.useFakeTimers();
const { api, bridge, profileCalls } = setup(() => [friend(10001)]);
await api.fetchFriendList({ withProfile: true });
expect(profileCalls).toEqual([10001]);
expect(vi.getTimerCount()).toBe(1);
await bridge.dispose();
expect(vi.getTimerCount()).toBe(0);
});
it('does not start profile cache loads when a roster response arrives after disposal', async () => {
vi.useFakeTimers();
const { api, bridge, send, profileCalls } = setup(() => [friend(10001)]);
const response = await send.getMockImplementation()!(
'OidbSvcTrpcTcp.0xfd4_1',
new Uint8Array(),
);
let resolve!: (value: typeof response) => void;
send.mockReturnValueOnce(
new Promise((yes) => {
resolve = yes;
}),
);
const pending = api.fetchFriendList({ withProfile: true });
const checked = expect(pending).rejects.toThrow('friend profile enrichment failed');
await bridge.dispose();
resolve(response);
await checked;
expect(profileCalls).toEqual([]);
expect(vi.getTimerCount()).toBe(0);
});
it('does not fan out on a cold 160-friend ordinary or categorized list', async () => {
const { api, profileCalls, send } = setup(() =>
Array.from({ length: 160 }, (_, i) => friend(10000 + i)),
@@ -0,0 +1,81 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
import { FetchRobotUinRanges } from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
import { Bridge } from '../src/bridge/bridge';
afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});
describe('Bridge contact cache lifecycle', () => {
it('keeps contact lookups available to packets already draining during shutdown', async () => {
vi.useFakeTimers();
const bridge = new Bridge(IdentityService.memory('10001'));
vi.spyOn(FetchRobotUinRanges, 'invoke').mockResolvedValue({ version: 1, ranges: [] });
const load = vi
.spyOn(FetchGroupMemberListPage, 'invoke')
.mockResolvedValue({ members: [], token: '' });
await bridge.apis.contacts.fetchGroupMemberList(42);
let memberRead: Promise<unknown> | undefined;
bridge.registerCmd('test.contact-cache', () => {
memberRead = bridge.apis.contacts.fetchGroupMemberList(42);
return [];
});
const packet = bridge.onPacket({
pid: 1,
uin: '10001',
serviceCmd: 'test.contact-cache',
seqId: 1,
retCode: 0,
fromClient: false,
body: new Uint8Array(),
});
const closing = bridge.dispose();
await packet;
await expect(memberRead).resolves.toEqual([]);
await closing;
expect(load).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
});
it.each([false, true])(
'releases member caches before identity closes, close failure=%s',
async (fails) => {
vi.useFakeTimers();
const identity = IdentityService.memory('10001');
const bridge = new Bridge(identity);
vi.spyOn(FetchRobotUinRanges, 'invoke').mockResolvedValue({ version: 1, ranges: [] });
const load = vi
.spyOn(FetchGroupMemberListPage, 'invoke')
.mockResolvedValue({ members: [], token: '' });
await bridge.apis.contacts.fetchGroupMemberList(42);
await bridge.apis.contacts.fetchGroupMemberList(42);
expect(load).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(1);
const originalClose = identity.close.bind(identity);
vi.spyOn(identity, 'close').mockImplementation(async () => {
expect(vi.getTimerCount()).toBe(0);
await originalClose();
if (fails) {
throw new Error('identity close failed');
}
});
const closing = bridge.dispose();
expect(bridge.dispose()).toBe(closing);
if (fails) {
await expect(closing).rejects.toThrow('identity close failed');
} else {
await closing;
}
await expect(bridge.apis.contacts.fetchGroupMemberList(42)).rejects.toThrow('disposed');
expect(load).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
},
);
});