refactor(protocol): own inbound UID-to-UIN resolution in Identity

Inbound person lookup used to be split across decoders, the packet
pipeline, and Bridge closures. Missing identities were filled from
unrelated packet headers, and "who is this person" was coupled to
roster refresh and pending-request enrichment.

Identity now owns both directions of resolution. The hot path stays
synchronous and emits unresolved events on a miss. Only the paths
that already waited before dispatch perform a network lookup, and
that lookup is a profile fetch by UID rather than a member-list
refresh. Pending-request comments and approval flags stay outside
Identity.

Decoders no longer invent a UIN from a group routing header. Private
chat routing still uses a hop's own wire UIN when the hop is named
that way. Inbound misses stay availability-first: they do not throw
and do not mark Identity degraded.
This commit is contained in:
DrSmoothl committed 2026-08-13 14:37:56 +08:00
1 parent d26aef86d8
commit 7d5ca5523b
16 files changed
+334 -187

No files matched your search

+1 -9
View File
@@ -52,6 +52,7 @@ export class Bridge implements BridgeInterface {
this.apis = buildApiHub(this);
this.identity.setFetcher({
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
fetchProfileByUid: (uid) => this.apis.contacts.fetchUserProfileByUid(uid),
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
@@ -59,15 +60,6 @@ export class Bridge implements BridgeInterface {
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
resolveStrangerProfile: async (uid) => {
try {
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
if (p.uin <= 0) return null;
return { uin: p.uin, nickname: p.nickname };
} catch {
return null;
}
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequestsByUid(false),
@@ -35,28 +35,19 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
};
}
class RefreshingBridge extends Bridge {
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
super(identity);
// `fetchGroupMemberList` moved from Bridge onto `apis.contacts`
// under the #6 refactor — patch the method on the constructed
// ContactsApi instance to intercept calls + record them for
// assertions. (Direct property assignment works because the
// method is just an own property on the Api instance, not on
// its prototype.)
this.apis.contacts.fetchGroupMemberList = async (
groupId: number,
options: { force?: boolean } = {},
): Promise<GroupMemberInfo[]> => {
this.memberFetches.push({ groupId, force: Boolean(options.force) });
for (const member of this.refreshedMembers) {
this.identity.updateGroupMember(groupId, member);
}
return this.refreshedMembers;
};
}
function emptyProfile(uin: number, uid: string) {
return {
uin,
uid,
nickname: '',
remark: '',
qid: '',
sex: 'unknown',
age: 0,
sign: '',
avatar: '',
level: 0,
};
}
function makePacket(): PacketInfo {
@@ -87,11 +78,21 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin>
}
describe('Bridge group member identity refresh', () => {
it('forces a fresh member list before dispatching an unresolved join event', async () => {
it('resolves an unresolved join UIN via inbound profile before dispatch', async () => {
const member = makeGroupMember(22222, 'u_new_member');
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const bridge = new RefreshingBridge(identity, [member]);
const bridge = new Bridge(identity);
const profileFetches: string[] = [];
const memberFetches: Array<{ groupId: number; force: boolean }> = [];
bridge.apis.contacts.fetchUserProfileByUid = async (uid) => {
profileFetches.push(uid);
return emptyProfile(member.uin, uid);
};
bridge.apis.contacts.fetchGroupMemberList = async (groupId, options = {}) => {
memberFetches.push({ groupId, force: Boolean(options.force) });
return [];
};
const seen: GroupMemberJoin[] = [];
bridge.registerCmd('test.member_join', () => [{
@@ -111,9 +112,9 @@ describe('Bridge group member identity refresh', () => {
bridge.onPacket(makePacket());
const event = await waitForEvent(seen);
expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
expect(profileFetches).toEqual([member.uid]);
expect(memberFetches.some((fetch) => fetch.force)).toBe(false);
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(member.uin);
});
it('remembers UID mappings from realtime request events', () => {
@@ -974,3 +974,146 @@ describe('IdentityService.resolveUid', () => {
expect(fetchProfile).not.toHaveBeenCalled();
});
});
describe('IdentityService inbound UID→UIN', () => {
function makeProfile(uin: number, uid: string): UserProfileInfo {
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 };
}
it('findUinByUid treats a numeric uid as that uin without consulting maps', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberRequestIdentity({ uid: '22999', uin: 11111 });
expect(identity.findUinByUid('22999')).toBe(22999);
expect(identity.findUinByUid('0')).toBeNull();
expect(identity.findUinByUid('')).toBeNull();
});
it('returns the cached uin without invoking fetchProfileByUid', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberRequestIdentity({ uid: 'u_known', uin: 12345 });
const fetchProfileByUid = vi.fn(async () => makeProfile(999, 'should-not-be-used'));
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid,
});
await expect(identity.resolveUin('u_known')).resolves.toBe(12345);
expect(fetchProfileByUid).not.toHaveBeenCalled();
});
it('does not call fetchProfileByUid for a numeric uid', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchProfileByUid = vi.fn(async () => makeProfile(1, '1'));
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid,
});
await expect(identity.resolveUin('22999')).resolves.toBe(22999);
expect(fetchProfileByUid).not.toHaveBeenCalled();
});
it('falls back to fetchProfileByUid on miss and returns the profile uin', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchProfileByUid = vi.fn(async (uid: string) => {
identity.rememberUserProfile(makeProfile(88888, uid));
return makeProfile(88888, uid);
});
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid,
});
await expect(identity.resolveUin('u_stranger')).resolves.toBe(88888);
expect(fetchProfileByUid).toHaveBeenCalledWith('u_stranger');
});
it('returns the profile uin even when the fetcher forgets to remember', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => makeProfile(77777, 'u_forgetful'),
});
await expect(identity.resolveUin('u_forgetful')).resolves.toBe(77777);
});
it('does not pull a group member list even when groupId is provided', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchGroupMemberList = vi.fn(async () => []);
const fetchProfileByUid = vi.fn(async () => makeProfile(66666, 'u_invitee'));
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid,
fetchGroupMemberList,
});
await expect(identity.resolveUin('u_invitee', GROUP_ID)).resolves.toBe(66666);
expect(fetchGroupMemberList).not.toHaveBeenCalled();
expect(fetchProfileByUid).toHaveBeenCalledWith('u_invitee');
});
it('does not pull a group member list when the inbound fetcher is absent', async () => {
const identity = IdentityService.memory(SELF_UIN);
const fetchGroupMemberList = vi.fn(async () => []);
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchGroupMemberList,
});
await expect(identity.resolveUin('u_none', GROUP_ID)).resolves.toBeNull();
expect(fetchGroupMemberList).not.toHaveBeenCalled();
});
it('uses a mapping remembered before the inbound fetcher throws', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async (uid: string) => {
identity.rememberUserProfile(makeProfile(55555, uid));
throw new Error('transport reset after remember');
},
});
await expect(identity.resolveUin('u_remembered')).resolves.toBe(55555);
});
it('returns null on miss, fetcher error, empty profile, or missing inbound fetcher', async () => {
const identity = IdentityService.memory(SELF_UIN);
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
identity.setFetcher({ fetchProfile: async () => makeProfile(0, '') });
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => makeProfile(0, 'u_none'),
});
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => {
throw new Error('oidb down');
},
});
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
});
it('does not enter Identity degraded when the inbound fetcher throws', async () => {
const dbPath = tempDbPath('inbound-fetch-throw');
const identity = new IdentityService(SELF_UIN, dbPath);
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => {
throw new Error('oidb down');
},
});
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
expect(identity.persistenceStatus.state).toBe('healthy');
expect(identity.persistenceStatus.pendingWrites).toBe(0);
identity.close();
});
});
+1 -3
View File
@@ -495,7 +495,6 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)',
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
resolveStrangerProfile: vi.fn(async () => null),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -979,8 +978,7 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
const [event] = parseMsgPush(makeGroupAdminPacket('u_unknown', true), identity) as GroupAdminEvent[];
expect(event.kind).toBe('group_admin');
// fromUin (the group id) is the resolve fallback — it must not be
// confused for a real, promotable member.
expect(event.userUin).toBe(0);
expect(identity.findGroupMember(GROUP_ID, GROUP_ID)).toBeNull();
});
});