refactor(identity): consolidate UID resolution behind IdentityService

Pull the cache→DB→network-fetch fallback cascade for UIN→UID translation
into a single async `resolveUid` on IdentityService, and drop the
duplicated `resolveUserUid` helper that used to live in bridge-oidb. Bridge
injects itself as the IdentityFetcher post-construction so the network
fallback runs through the same OIDB profile fetch the helper used.

Each action module's `resolveUserUid(bridge, uin, groupId?)` call becomes
`bridge.resolveUserUid(uin, groupId?)` — same signature on Bridge, but
internally it now goes through `identity.resolveUid` so future changes
(retry, coalescing, alternative resolvers) only need to land in one place.

This is part 1 of the IdentityService deepening (RoadMap item 1). The
QQInfo bypass in msg-push-handler and the broader QQInfo absorption land
in the follow-up commit.
This commit is contained in:
DrSmoothl committed 2026-05-15 00:32:59 +08:00
1 parent 2e4dd9b01e
commit 030336a25c
20 files changed
+157 -75

No files matched your search

+4 -4
View File
@@ -3,7 +3,7 @@
// protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb';
import { sendOidbAndCheck } from '../bridge-oidb';
import {
OidbDeleteFriendSchema,
OidbFriendRequestActionSchema,
@@ -13,14 +13,14 @@ import {
export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise<void> {
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await resolveUserUid(bridge, parseInt(uidOrFlag, 10));
targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
}
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb5d_44', 0xB5D, 44,
{ accept: approve ? 3 : 5, targetUid }, OidbFriendRequestActionSchema);
}
export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await resolveUserUid(bridge, userId);
const targetUid = await bridge.resolveUserUid(userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x126b_0', 0x126B, 0,
{
field1: {
@@ -47,7 +47,7 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false
}
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId);
const uid = await bridge.resolveUserUid(userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2,
{ targetUid: uid, remark }, OidbSetFriendRemarkSchema);
}
@@ -4,7 +4,7 @@
// so callers can grep across the two layers.
import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb';
import {
Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema,
@@ -26,7 +26,7 @@ import {
// ─────────────── mute / un-mute ───────────────
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1253_1', 0x1253, 1,
{ groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, OidbMuteMemberSchema);
}
@@ -62,13 +62,13 @@ export async function setGroupAddRequest(
// ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema);
}
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => resolveUserUid(bridge, userId, groupId)));
const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1,
{ groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, Oidb0x8a0ReqSchema);
}
@@ -81,13 +81,13 @@ export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void>
// ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1096_1', 0x1096, 1,
{ groupUin: groupId, uid, isAdmin: enable }, OidbSetAdminSchema);
}
export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_3', 0x8FC, 3,
{ groupUin: groupId, body: { targetUid: uid, targetName: card } }, OidbRenameMemberSchema);
}
@@ -98,7 +98,7 @@ export async function setGroupName(bridge: Bridge, groupId: number, name: string
}
export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await resolveUserUid(bridge, userId, groupId);
const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_2', 0x8FC, 2,
{ groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, OidbSpecialTitleSchema);
}
@@ -7,7 +7,7 @@
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { sendOidbAndDecode } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
import {
@@ -368,12 +368,12 @@ export async function uploadPrivateFile(
const loaded = await loadBinarySource(source, 'file');
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await resolveUserUid(bridge, userId);
const targetUid = await bridge.resolveUserUid(userId);
let selfUid = bridge.qqInfo.selfUid;
if (!selfUid) {
const selfUin = toInt(bridge.qqInfo.uin);
if (selfUin > 0) {
selfUid = await resolveUserUid(bridge, selfUin);
selfUid = await bridge.resolveUserUid(selfUin);
}
}
if (!selfUid) throw new Error('self uid is unavailable');
@@ -568,7 +568,7 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId:
}
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await resolveUserUid(bridge, userId);
const uid = await bridge.resolveUserUid(userId);
const resp = await sendOidbAndDecode<any>(
bridge,
'OidbSvcTrpcTcp.0xe37_1200',
@@ -5,7 +5,7 @@
import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, resolveUserUid } from '../bridge-oidb';
import { sendOidbAndCheck } from '../bridge-oidb';
import {
C2CRecallRequestSchema,
GroupRecallRequestSchema,
@@ -28,7 +28,7 @@ export async function recallPrivateMessage(
bridge: Bridge, userUin: number, clientSeq: number,
msgSeq: number, random: number, timestamp: number,
): Promise<void> {
const targetUid = await resolveUserUid(bridge, userUin);
const targetUid = await bridge.resolveUserUid(userUin);
const request = protoEncode({
type: 1,
targetUid,
@@ -53,7 +53,7 @@ export async function markPrivateMessageRead(
msgSeq: number,
timestamp: number = Math.floor(Date.now() / 1000),
): Promise<void> {
const uid = await resolveUserUid(bridge, userId);
const uid = await bridge.resolveUserUid(userId);
const request = protoEncode({
c2cList: [
+3 -3
View File
@@ -4,7 +4,7 @@
import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, sendOidbAndDecode, resolveUserUid } from '../bridge-oidb';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import {
@@ -119,7 +119,7 @@ export async function setInputStatus(
userId: number,
eventType: number,
) {
const targetUid = await resolveUserUid(bridge, userId);
const targetUid = await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
@@ -167,7 +167,7 @@ export async function getProfileLike(
const isSelf = !userId;
const targetUid = isSelf
? await resolveSelfUid(bridge)
: await resolveUserUid(bridge, userId);
: await bridge.resolveUserUid(userId);
if (!targetUid) {
throw new Error('target uid not found');
+1 -2
View File
@@ -3,7 +3,6 @@
// same five-line utility from every themed file.
import type { Bridge } from '../bridge';
import { resolveUserUid } from '../bridge-oidb';
/**
* Coerce numbers, strings, and bigints to a plain integer.
@@ -48,7 +47,7 @@ export async function resolveSelfUid(bridge: Bridge): Promise<string> {
if (selfUin <= 0) {
throw new Error('self uid is unavailable');
}
selfUid = await resolveUserUid(bridge, selfUin);
selfUid = await bridge.resolveUserUid(selfUin);
return selfUid;
}
+1 -23
View File
@@ -1,4 +1,4 @@
// OIDB protocol helpers -- encode requests, send+check, send+decode, UID resolution.
// OIDB protocol helpers -- encode requests, send+check, send+decode.
import type { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode';
@@ -67,25 +67,3 @@ export async function sendOidbAndDecode<T>(
return (resp as any).body as T;
}
/**
* Resolve a UIN to a UID string, using cache or fetching as needed.
* Mirrors C++ resolve_user_uid_for_action.
*/
export async function resolveUserUid(bridge: Bridge, uin: number, groupId?: number): Promise<string> {
// Try group member first
if (groupId !== undefined) {
const uid = bridge.identity.findUidByUin(uin, groupId);
if (uid) return uid;
// Try fetching member list
try { await bridge.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const uid2 = bridge.identity.findUidByUin(uin, groupId);
if (uid2) return uid2;
}
// Try cached
const uid = bridge.identity.findUidByUin(uin);
if (uid) return uid;
// Fetch profile
const profile = await bridge.fetchUserProfile(uin);
if (profile.uid) return profile.uid;
throw new Error(`failed to resolve UID for UIN ${uin}`);
}
+5 -2
View File
@@ -18,7 +18,6 @@ import {
} from './proto/action';
// Delegated modules
import { resolveUserUid as resolveUserUid_ } from './bridge-oidb';
import {
fetchFriendList as fetchFriendList_,
fetchGroupList as fetchGroupList_,
@@ -176,6 +175,10 @@ export class Bridge {
constructor(qqInfo: QQInfo, identity = IdentityService.memory(qqInfo)) {
this.qqInfo_ = qqInfo;
this.identity = identity;
this.identity.setFetcher({
fetchProfile: (uin) => this.fetchUserProfile(uin),
fetchGroupMemberList: (gid) => this.fetchGroupMemberList(gid),
});
this.registerDefaultHandlers();
}
@@ -553,7 +556,7 @@ export class Bridge {
// --- Delegated: OIDB helpers ---
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return resolveUserUid_(this, uin, groupId);
return this.identity.resolveUid(uin, groupId);
}
// --- Delegated: Contact / info queries ---
@@ -8,6 +8,17 @@ import { createLogger } from '../utils/logger';
const log = createLogger('Identity');
/**
* Hooks Identity uses when its read methods miss every cache layer. Wired in
* after construction (Bridge owns these methods, but Bridge can't exist
* before Identity does). Each call is expected to invoke the matching
* remember* observation on this service as a side effect.
*/
export interface IdentityFetcher {
fetchProfile(uin: number): Promise<UserProfileInfo>;
fetchGroupMemberList?(groupId: number): Promise<unknown>;
}
interface UserInput {
uid?: string;
uin?: number;
@@ -71,6 +82,7 @@ export class IdentityService {
private readonly uinByUid = new Map<string, number>();
private readonly uidByUin = new Map<number, string>();
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
constructor(
private readonly qqInfo: QQInfo,
@@ -105,6 +117,38 @@ export class IdentityService {
return this.db !== null;
}
setFetcher(fetcher: IdentityFetcher): void {
this.fetcher = fetcher;
}
/**
* UIN → UID with network fallback. Returns cached value on hit; otherwise
* invokes the registered fetcher (typically `bridge.fetchUserProfile`),
* which is expected to write the result back through `rememberUserProfile`
* before this method re-queries the cache. Throws if no UID can be
* obtained from any layer.
*/
async resolveUid(uin: number, groupId?: number): Promise<string> {
const normalized = normalizeUin(uin);
if (normalized === null) throw new Error(`invalid uin: ${uin}`);
const cached = this.findUidByUin(normalized, groupId);
if (cached) return cached;
if (groupId !== undefined && this.fetcher?.fetchGroupMemberList) {
try { await this.fetcher.fetchGroupMemberList(groupId); } catch { /* ignore */ }
const afterMembers = this.findUidByUin(normalized, groupId);
if (afterMembers) return afterMembers;
}
if (!this.fetcher) throw new Error(`failed to resolve UID for UIN ${normalized}: no fetcher`);
const profile = await this.fetcher.fetchProfile(normalized);
if (profile.uid) return profile.uid;
throw new Error(`failed to resolve UID for UIN ${normalized}`);
}
rememberFriends(friends: FriendInfo[]): void {
this.qqInfo.setFriends(friends);
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);