fix(protocol): isolate catalog lookups and event subscriptions

This commit is contained in:
手瓜一十雪 committed 2026-10-18 13:31:10 +08:00
1 parent fb39af6c28
commit 95a2d0d257
7 files changed
+384 -206

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
import { describe, expect, it, vi } from 'vitest';
import { BridgeEventBus } from '../src/event-bus';
import type { FriendMessage, GroupMessage } from '../src/events';
function makeFriendMessage(): FriendMessage {
return {
kind: 'friend_message',
time: 1700000000,
selfUin: 10001,
senderUin: 22222,
senderNick: 'peer',
msgSeq: 1,
msgId: 1,
elements: [{ type: 'text', text: 'hi' }],
};
}
function makeGroupMessage(): GroupMessage {
return {
kind: 'group_message',
groupName: '',
time: 1700000000,
selfUin: 10001,
groupId: 99999,
senderUin: 22222,
senderNick: 'peer',
senderCard: '',
senderRole: 'member',
msgSeq: 2,
msgId: 2,
elements: [{ type: 'text', text: 'hi' }],
};
}
describe('BridgeEventBus', () => {
it('keeps the current kind and wildcard subscribers stable while dispatching', async () => {
const bus = new BridgeEventBus();
const peer = vi.fn();
const tap = vi.fn();
const later = vi.fn();
const laterTap = vi.fn();
bus.on('friend_message', () => {
offPeer();
offTap();
bus.on('friend_message', later);
bus.onAny(laterTap);
});
const offPeer = bus.on('friend_message', peer);
const offTap = bus.onAny(tap);
await bus.emit(makeFriendMessage());
expect(peer).toHaveBeenCalledOnce();
expect(tap).toHaveBeenCalledOnce();
expect(later).not.toHaveBeenCalled();
expect(laterTap).not.toHaveBeenCalled();
await bus.emit(makeFriendMessage());
expect(peer).toHaveBeenCalledOnce();
expect(tap).toHaveBeenCalledOnce();
expect(later).toHaveBeenCalledOnce();
expect(laterTap).toHaveBeenCalledOnce();
});
it('finishes the current dispatch when a handler clears subscriptions', async () => {
const bus = new BridgeEventBus();
const peer = vi.fn();
const tap = vi.fn();
bus.on('friend_message', () => bus.clear());
bus.on('friend_message', peer);
bus.onAny(tap);
await bus.emit(makeFriendMessage());
await bus.emit(makeFriendMessage());
expect(peer).toHaveBeenCalledOnce();
expect(tap).toHaveBeenCalledOnce();
});
it.each(['kind', 'any'] as const)('owns each %s subscription independently', async (type) => {
const bus = new BridgeEventBus();
const handler = vi.fn();
const subscribe = () =>
type === 'kind' ? bus.on('friend_message', handler) : bus.onAny(handler);
const off = subscribe();
subscribe();
off();
off();
await bus.emit(makeFriendMessage());
expect(handler).toHaveBeenCalledOnce();
bus.clear();
subscribe();
off();
await bus.emit(makeFriendMessage());
expect(handler).toHaveBeenCalledTimes(2);
});
it('off removes every registration of the named handler', async () => {
const bus = new BridgeEventBus();
const handler = vi.fn();
bus.on('friend_message', handler);
bus.on('friend_message', handler);
bus.off('friend_message', handler);
expect(bus.has('friend_message')).toBe(false);
await bus.emit(makeFriendMessage());
expect(handler).not.toHaveBeenCalled();
});
it('routes events only to subscribers of the matching kind', async () => {
const bus = new BridgeEventBus();
const friend = vi.fn();
const group = vi.fn();
bus.on('friend_message', friend);
bus.on('group_message', group);
await bus.emit(makeFriendMessage());
await bus.emit(makeGroupMessage());
expect(friend).toHaveBeenCalledTimes(1);
expect(group).toHaveBeenCalledTimes(1);
});
it('runs every subscriber in parallel for one kind', async () => {
const bus = new BridgeEventBus();
const order: string[] = [];
bus.on('friend_message', async () => {
await new Promise((r) => setTimeout(r, 20));
order.push('slow');
});
bus.on('friend_message', () => {
order.push('fast');
});
await bus.emit(makeFriendMessage());
// The synchronous handler must finish before the async one — proves we
// don't serialize handlers across the kind.
expect(order).toEqual(['fast', 'slow']);
});
it('isolates handler errors and reports them via onError', async () => {
const seen: Array<{ kind: string; err: unknown }> = [];
const bus = new BridgeEventBus({ onError: (kind, err) => seen.push({ kind, err }) });
const ok = vi.fn();
bus.on('friend_message', () => {
throw new Error('boom');
});
bus.on('friend_message', ok);
await bus.emit(makeFriendMessage());
expect(ok).toHaveBeenCalledTimes(1);
expect(seen).toHaveLength(1);
expect(seen[0].kind).toBe('friend_message');
expect((seen[0].err as Error).message).toBe('boom');
});
it('supports unsubscribe via the returned disposer', async () => {
const bus = new BridgeEventBus();
const handler = vi.fn();
const off = bus.on('friend_message', handler);
await bus.emit(makeFriendMessage());
expect(handler).toHaveBeenCalledTimes(1);
off();
await bus.emit(makeFriendMessage());
expect(handler).toHaveBeenCalledTimes(1);
});
it('supports onAny and isolates its errors separately', async () => {
const seen: Array<{ kind: string; err: unknown }> = [];
const bus = new BridgeEventBus({ onError: (kind, err) => seen.push({ kind, err }) });
const tap = vi.fn();
bus.onAny(tap);
bus.onAny(() => {
throw new Error('any-fail');
});
await bus.emit(makeFriendMessage());
await bus.emit(makeGroupMessage());
expect(tap).toHaveBeenCalledTimes(2);
expect(seen).toHaveLength(2);
expect(seen.every((s) => s.kind === '*')).toBe(true);
});
it('reports has() based on per-kind + onAny subscriptions', () => {
const bus = new BridgeEventBus();
expect(bus.has('friend_message')).toBe(false);
const off = bus.on('friend_message', () => {});
expect(bus.has('friend_message')).toBe(true);
off();
expect(bus.has('friend_message')).toBe(false);
bus.onAny(() => {});
expect(bus.has('friend_message')).toBe(true);
});
it('clear() drops every subscriber', async () => {
const bus = new BridgeEventBus();
const handler = vi.fn();
bus.on('friend_message', handler);
bus.onAny(handler);
bus.clear();
await bus.emit(makeFriendMessage());
expect(handler).not.toHaveBeenCalled();
});
});
+133
View File
@@ -26,6 +26,16 @@ import {
import { buildSendElems } from '../src/element-builder';
import { FetchSysFace } from '../src/oidb-services/sys-faces/fetch-sys-face';
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
function entry(
qSid: string,
aniStickerType: number | null,
@@ -296,6 +306,79 @@ describe('FetchSysFaces.deserialize', () => {
describe('SysFaceStore — persistent catalog and query seam', () => {
const sender = {} as never;
it.each(['snapshot', 'read error'] as const)(
'does not replace a refreshed catalog with a late cache %s',
async (result) => {
const cache = deferred<SysFaceCatalogSnapshot | null>();
const store = new SysFaceStore({
storage: { load: () => cache.promise, save: async () => {} },
fetchCatalog: async () => CATALOG,
});
const ready = store.ensureReady(sender);
await store.refresh(sender);
if (result === 'snapshot') {
cache.resolve({ schemaVersion: 1, fetchedAt: 1, packs: CATALOG.slice(0, 1) });
} else {
cache.reject(new Error('obsolete cache read failed'));
}
await ready;
await expect(store.getCatalog(sender)).resolves.toEqual(CATALOG);
expect(store.lookup(392)?.qSid).toBe('392');
},
);
it('waits for a refresh that started during the disk read', async () => {
const cache = deferred<SysFaceCatalogSnapshot | null>();
const remote = deferred<SysFacePackEntry[]>();
const store = new SysFaceStore({
storage: { load: () => cache.promise, save: async () => {} },
fetchCatalog: () => remote.promise,
});
let ready = false;
const reading = store.ensureReady(sender).then(() => {
ready = true;
});
const refreshing = store.refresh(sender);
cache.resolve({ schemaVersion: 1, fetchedAt: 1, packs: CATALOG.slice(0, 1) });
await new Promise((resolve) => setImmediate(resolve));
expect(ready).toBe(false);
remote.resolve(CATALOG);
await Promise.all([reading, refreshing]);
expect(store.lookup(392)?.qSid).toBe('392');
});
it('retains a failed cache read until an explicit refresh repairs the catalog', async () => {
const load = vi.fn(async () => {
throw new Error('corrupt cache');
});
const fetchCatalog = vi.fn(async () => CATALOG);
const store = new SysFaceStore({ storage: { load, save: async () => {} }, fetchCatalog });
await expect(store.ensureReady(sender)).rejects.toThrow('corrupt cache');
await expect(store.ensureReady(sender)).rejects.toThrow('corrupt cache');
expect(load).toHaveBeenCalledOnce();
expect(fetchCatalog).not.toHaveBeenCalled();
await store.refresh(sender);
await expect(store.getCatalog(sender)).resolves.toEqual(CATALOG);
});
it('retries a failed login prewarm, then shares the completed job', async () => {
const load = vi.fn(async () => null);
const fetchCatalog = vi
.fn()
.mockRejectedValueOnce(new Error('network failed'))
.mockResolvedValueOnce(CATALOG);
const store = new SysFaceStore({ storage: { load, save: async () => {} }, fetchCatalog });
await expect(store.prewarm(sender)).rejects.toThrow('network failed');
const retry = store.prewarm(sender);
expect(store.prewarm(sender)).toBe(retry);
await retry;
await store.prewarm(sender);
expect(load).toHaveBeenCalledOnce();
expect(fetchCatalog).toHaveBeenCalledTimes(2);
});
it('accepts face id 0 from the authoritative catalog', async () => {
const zero = entry('0', null, null, null, '/惊讶');
const store = new SysFaceStore({
@@ -738,6 +821,56 @@ describe('makeFaceElem (via buildSendElems) — three-way wire encoding', () =>
});
describe('system faces outside visible panels', () => {
it.each(['result', 'error'] as const)(
'ignores an older catalog’s lookup %s after refresh',
async (outcome) => {
const stale = deferred<SysFaceEntry | null>();
const started = deferred<void>();
const latest = entry('507', 1, 4, 108);
const fetchFace = vi
.fn()
.mockImplementationOnce(() => {
started.resolve();
return stale.promise;
})
.mockResolvedValue(latest);
const store = new SysFaceStore({ fetchCatalog: async () => CATALOG, fetchFace });
const first = store.resolveWire({} as never, 507);
await started.promise;
await store.refresh({} as never);
const second = store.resolveWire({} as never, 507);
if (outcome === 'result') {
stale.resolve(entry('507', 1, 4, 107));
} else {
stale.reject(new Error('outdated lookup failed'));
}
const expected = { kind: 'super', packId: '4', stickerId: '108', stickerType: 1 };
await expect(first).resolves.toEqual(expected);
await expect(second).resolves.toEqual(expected);
expect(fetchFace).toHaveBeenCalledTimes(2);
expect(store.lookup(507)).toEqual(latest);
},
);
it('uses an explicitly loaded catalog when an older single-face lookup completes', async () => {
const stale = deferred<SysFaceEntry | null>();
const started = deferred<void>();
const fetchFace = vi.fn(() => {
started.resolve();
return stale.promise;
});
const store = new SysFaceStore({ fetchCatalog: async () => CATALOG, fetchFace });
const result = store.resolveWire({} as never, 507);
await started.promise;
const latest = entry('507', 1, 4, 108);
store.load([{ packName: '最新', emojis: [latest] }]);
stale.resolve(entry('507', 1, 4, 107));
await expect(result).resolves.toMatchObject({ stickerId: '108' });
expect(store.lookup(507)).toEqual(latest);
});
it('resolves missing animation metadata once and shares concurrent lookups', async () => {
const fetchFace = vi.fn(async () => entry('507', 1, 4, 107));
const store = new SysFaceStore({ fetchCatalog: async () => CATALOG, fetchFace });