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:
8 files changed
+226
-1
No files matched your search
@@ -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 }));
|
||||
|
||||
Reference in new issue
Block a user