refactor(protocol): move roster refresh into the packet pipeline

Replace the shallow refreshMemberCache adapter with fetchGroupList
and fetchGroupMemberList ports. Skip, swallow, and coalesce stay
next to the join/leave/admin trigger.
This commit is contained in:
DrSmoothl committed 2026-08-16 23:18:04 +08:00
1 parent 9772d4f0bf
commit 206727f823
7 files changed
+265 -44

No files matched your search

+6 -10
View File
@@ -58,8 +58,12 @@ export class Bridge implements BridgeInterface {
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
fetchGroupList: async () => {
await this.apis.contacts.fetchGroupList();
},
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequestsByUid(false),
@@ -240,14 +244,6 @@ export class Bridge implements BridgeInterface {
return this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
+4 -2
View File
@@ -494,7 +494,8 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)',
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -942,7 +943,8 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
+2 -1
View File
@@ -134,7 +134,8 @@ function makePipeline(identity: IdentityService): IncomingPacketPipeline {
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: async () => false,
fetchGroupList: async () => {},
fetchGroupMemberList: async () => {},
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
return pipeline;
+25 -24
View File
@@ -40,12 +40,12 @@ class EnrichedDispatchError extends Error {
export interface PacketPipelineDeps {
identity: IdentityService;
events: BridgeEventBus;
/**
* Refresh group + member roster as a side-effect. Resolves with
* whether any refresh actually ran (false when the group is unknown
* and `refreshGroupList` was false).
*/
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
/** Account group-list fetch. Roster side-effect only; the pipeline
* swallows failures and does not read the returned roster. */
fetchGroupList(): Promise<void>;
/** One group's member-list fetch (adapter TTL applies). Roster
* side-effect only; the pipeline does not pass `force`. */
fetchGroupMemberList(groupId: number): Promise<void>;
/**
* Resolve the verify message ("postscript") + server sequence number
* for a pending group-join / group-invite. The OIDB push only
@@ -335,12 +335,11 @@ export class IncomingPacketPipeline {
pkt: PacketInfo,
event: QQEventVariant,
mode: 'sync' | 'enriched',
alreadyRefreshed = false,
): number {
// Snapshot the sender's cached group card BEFORE dispatch — the side-effects
// inside finishDispatch self-heal it, so the old value must be read first.
const cardBefore = this.groupCardBefore(event);
this.finishDispatch(event, alreadyRefreshed);
this.finishDispatch(event);
this.traceDispatch(pkt, event.kind, mode);
if (!this.emitGroupCardChange(event, cardBefore)) return 1;
this.traceDispatch(pkt, 'group_card_change', 'derived');
@@ -382,13 +381,10 @@ export class IncomingPacketPipeline {
/**
* Common dispatch tail shared by the sync path and the two async enrichment
* paths: run side effects, log the event, then emit it. `alreadyRefreshed` is
* threaded through to `handleSideEffects` (true only on the identity-refresh
* path, where the roster refresh was already done) — it defaults false, so
* `finishDispatch(event)` matches the old `handleSideEffects(event)` calls.
* paths: run side effects, log the event, then emit it.
*/
private finishDispatch(event: QQEventVariant, alreadyRefreshed = false): void {
this.handleSideEffects(event, alreadyRefreshed);
private finishDispatch(event: QQEventVariant): void {
this.handleSideEffects(event);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
}
@@ -422,9 +418,8 @@ export class IncomingPacketPipeline {
pkt: PacketInfo,
event: Extract<QQEventVariant, { kind: 'group_member_join' }>,
): Promise<number> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="identity_refresh" error=%j',
@@ -438,7 +433,7 @@ export class IncomingPacketPipeline {
}
try {
return this.dispatchEvent(pkt, event, 'enriched', refreshed);
return this.dispatchEvent(pkt, event, 'enriched');
} catch (error) {
throw new EnrichedDispatchError(error);
}
@@ -546,15 +541,13 @@ export class IncomingPacketPipeline {
}
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid) return false;
if (event.userUin > 0 || !event.userUid) return;
const uin = await this.deps.identity.resolveUin(event.userUid, event.groupId);
if (uin !== null) event.userUin = uin;
this.resolveMemberIdentityFromCache(event);
// Roster refresh stays a post-dispatch side-effect, not the UIN hop.
return false;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
@@ -574,9 +567,8 @@ export class IncomingPacketPipeline {
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
}
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
private handleSideEffects(event: QQEventVariant): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
@@ -607,7 +599,16 @@ export class IncomingPacketPipeline {
const task = (async () => {
try {
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
if (refreshGroupList) {
try {
await this.deps.fetchGroupList();
} catch { /* ignore */ }
}
if (!this.deps.identity.findGroup(groupId)) {
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
return;
}
await this.deps.fetchGroupMemberList(groupId);
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
@@ -0,0 +1,215 @@
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { QQEventVariant } from '@snowluma/protocol/events';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
import { afterEach, describe, expect, it, vi } from 'vitest';
const SELF_UIN = 10001;
const GROUP_ID = 123456789;
const previousLogLevel = getLogLevel();
afterEach(() => {
setLogLevel(previousLogLevel);
});
function makeProfile(uin: number, uid = ''): UserProfileInfo {
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 };
}
function makeMember(uin: number, uid: string): GroupMemberInfo {
return {
uin, uid, nickname: '', card: '', isRobot: false, role: 'member',
level: 0, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0,
};
}
function makeGroup(): QQGroupInfo {
return {
groupId: GROUP_ID, groupName: 'g', remark: '', memberCount: 1, memberMax: 500,
members: new Map([[22222, makeMember(22222, 'u_member')]]),
};
}
function pkt(): PacketInfo {
return {
pid: 1, uin: String(SELF_UIN), serviceCmd: 'test.roster', seqId: 1,
retCode: 0, fromClient: false, body: new Uint8Array(),
};
}
function join(over: Partial<Extract<QQEventVariant, { kind: 'group_member_join' }>> = {}): QQEventVariant {
return {
kind: 'group_member_join', time: 1, selfUin: SELF_UIN, groupId: GROUP_ID,
userUin: 22222, operatorUin: 0, userUid: 'u_member', operatorUid: 'u_op',
...over,
};
}
function leave(): QQEventVariant {
return {
kind: 'group_member_leave', time: 1, selfUin: SELF_UIN, groupId: GROUP_ID,
userUin: 22222, operatorUin: 0, userUid: 'u_member', operatorUid: 'u_op',
leaveType: 'leave',
};
}
function admin(): QQEventVariant {
return {
kind: 'group_admin', time: 1, selfUin: SELF_UIN, groupId: GROUP_ID,
userUin: 22222, set: true,
};
}
function makePipeline(opts: {
plantGroup?: boolean;
plantGroupOnListFetch?: boolean;
fetchGroupList?: () => Promise<void>;
fetchGroupMemberList?: (groupId: number) => Promise<void>;
fetchProfileByUid?: () => Promise<UserProfileInfo>;
} = {}) {
const identity = IdentityService.memory(String(SELF_UIN));
if (opts.plantGroup) identity.rememberGroups([makeGroup()]);
if (opts.fetchProfileByUid) {
identity.setFetcher({
fetchProfile: async () => makeProfile(0),
fetchProfileByUid: opts.fetchProfileByUid,
});
}
const fetchGroupList = opts.fetchGroupList ?? vi.fn(async () => {
if (opts.plantGroupOnListFetch) identity.rememberGroups([makeGroup()]);
});
const fetchGroupMemberList = opts.fetchGroupMemberList ?? vi.fn(async () => {});
const events = new BridgeEventBus();
const captured: QQEventVariant[] = [];
events.onAny((event) => { captured.push(event as QQEventVariant); });
const pipeline = new IncomingPacketPipeline({
identity,
events,
fetchGroupList,
fetchGroupMemberList,
resolveGroupJoinRequest: vi.fn(async () => null),
});
return { identity, pipeline, captured, fetchGroupList, fetchGroupMemberList };
}
async function afterSideEffect(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
}
describe('IncomingPacketPipeline roster refresh', () => {
it('unknown-group join fetches the group list and skips members when still unknown', async () => {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline();
pipeline.registerCmd('test.roster', () => [join()]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(fetchGroupMemberList).not.toHaveBeenCalled();
});
it('swallows fetchGroupList failure and still skips members when the group is unknown', async () => {
const fetchGroupList = vi.fn(async () => {
throw new Error('list down');
});
const { pipeline, captured, fetchGroupMemberList } = makePipeline({ fetchGroupList });
pipeline.registerCmd('test.roster', () => [join()]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(fetchGroupMemberList).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
});
it('fetches members after an unknown-group join if the list fetch plants the group', async () => {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline({
plantGroupOnListFetch: true,
});
pipeline.registerCmd('test.roster', () => [join()]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
});
it('known-group join / leave / admin fetch only the member list', async () => {
for (const event of [join(), leave(), admin()]) {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline({ plantGroup: true });
pipeline.registerCmd('test.roster', () => [event]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).not.toHaveBeenCalled();
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
}
});
it('self-join of a known group fetches both the group list and the member list', async () => {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline({ plantGroup: true });
pipeline.registerCmd('test.roster', () => [join({ userUin: SELF_UIN, userUid: 'u_self' })]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
});
it('unknown-group leave / admin do not fetch the group list or members', async () => {
for (const event of [leave(), admin()]) {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline();
pipeline.registerCmd('test.roster', () => [event]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).not.toHaveBeenCalled();
expect(fetchGroupMemberList).not.toHaveBeenCalled();
}
});
it('warns when the member list fails and still emits the event', async () => {
const entries: LogEntry[] = [];
setLogLevel('warn');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, captured } = makePipeline({
plantGroup: true,
fetchGroupMemberList: vi.fn(async () => {
throw new Error('net down');
}),
});
pipeline.registerCmd('test.roster', () => [leave()]);
await pipeline.process(pkt());
expect(captured).toHaveLength(1);
await afterSideEffect();
expect(entries.some((entry) => (
entry.level === 'warn' && String(entry.message).includes('failed to refresh member cache')
))).toBe(true);
} finally {
unsubscribe();
}
});
it('resolves an unresolved join UIN through Identity, not the roster ports', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(22222, 'u_new'));
const { pipeline, captured, fetchGroupList, fetchGroupMemberList } = makePipeline({
plantGroup: true,
fetchProfileByUid,
});
pipeline.registerCmd('test.roster', () => [join({ userUin: 0, userUid: 'u_new' })]);
await pipeline.process(pkt());
expect(captured).toHaveLength(1);
expect((captured[0] as Extract<QQEventVariant, { kind: 'group_member_join' }>).userUin).toBe(22222);
expect(fetchProfileByUid).toHaveBeenCalledWith('u_new');
await afterSideEffect();
expect(fetchGroupList).not.toHaveBeenCalled();
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
});
it('coalesces concurrent refreshes for the same group', async () => {
const { pipeline, fetchGroupMemberList } = makePipeline({ plantGroup: true });
pipeline.registerCmd('test.roster', () => [leave(), admin()]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupMemberList).toHaveBeenCalledOnce();
});
});
@@ -37,7 +37,8 @@ function makePipeline(opts: {
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest,
resolveGroupInviteCardSequence,
});
@@ -387,7 +388,8 @@ describe('IncomingPacketPipeline / #1 group card self-heal', () => {
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
return { identity, pipeline };
@@ -452,7 +454,8 @@ describe('IncomingPacketPipeline / group_card_change from message traffic', () =
const events = new BridgeEventBus();
const pipeline = new IncomingPacketPipeline({
identity, events,
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
const captured: QQEventVariant[] = [];
@@ -519,7 +522,8 @@ describe('IncomingPacketPipeline / invite-card pending application', () => {
const pipeline = new IncomingPacketPipeline({
identity: IdentityService.memory('10001'),
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence,
});
@@ -74,7 +74,8 @@ function msgPushContext(
}
function makePipeline(opts: {
refreshMemberCache?: () => Promise<boolean>;
fetchGroupList?: () => Promise<void>;
fetchGroupMemberList?: (groupId: number) => Promise<void>;
fetchProfileByUid?: () => Promise<{ uin: number; uid: string; nickname: string; remark: string; qid: string; sex: string; age: number; sign: string; avatar: string; level: number }>;
} = {}) {
const identity = IdentityService.memory('10001');
@@ -91,7 +92,8 @@ function makePipeline(opts: {
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: opts.refreshMemberCache ?? vi.fn(async () => false),
fetchGroupList: opts.fetchGroupList ?? vi.fn(async () => {}),
fetchGroupMemberList: opts.fetchGroupMemberList ?? vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
const dispatched: Array<{ event: QQEventVariant; req: number | undefined }> = [];
@@ -214,7 +216,7 @@ describe('IncomingPacketPipeline TRACE lifecycle', () => {
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, dispatched } = makePipeline({
refreshMemberCache: vi.fn(async () => {
fetchGroupList: vi.fn(async () => {
throw new Error('fixture refresh failed');
}),
});