refactor(api): move contacts methods to ContactsApi (#6 commit 2/13)

Second of 13 commits decomposing Bridge. Moves the six "fetch the
roster / a profile / outstanding requests / download rkeys" methods
off Bridge and onto a new `apis.contacts.*`.

Methods moved
-------------
* fetchFriendList       — OIDB 0xfd4_1 + identity.rememberFriends
* fetchGroupList        — OIDB 0xfe5_2 + identity.rememberGroups
* fetchGroupMemberList  — OIDB 0xfe7_3 + identity.rememberGroupMembers
                          (includes the 60s TTL + per-group inflight
                          coalesce cache that prevents Tencent
                          risk-control from triggering)
* fetchUserProfile      — OIDB 0xfe1_2 + identity.rememberUserProfile
* fetchGroupRequests    — OIDB 0x10c0_{1,2}
* fetchDownloadRKeys    — OIDB 0x9067_202

Cache fields moved
------------------
The two member-list throttle maps (`memberListInflight_`,
`memberListLastFetch_`) move from Bridge to `ContactsApi` as private
fields. Same TTL, same semantics — just owned by the Api class that
exposes the method.

Constructor ordering
--------------------
`buildApiHub(this)` now runs BEFORE `identity.setFetcher(...)` in the
Bridge constructor because the `fetchProfile` / `fetchGroupMemberList`
callbacks installed there reach into `this.apis.contacts.*`. With
eager construction this is safe; the alternative (pass a thunk that
forwards once apis is built) was strictly worse for readability.

bridge-contacts.ts removed
--------------------------
The file existed solely as the previous module-function delegate
target; ContactsApi inlines every function body so there's nothing
left to keep.

Caller-site updates
-------------------
* `bridge/actions/friend.ts` — `bridge.fetchFriendList()` →
  `bridge.apis.contacts.fetchFriendList()`.
* `onebot/manager.ts`, `onebot/instance-rkey.ts`,
  `onebot/modules/contact-actions.ts`, `modules/request-actions.ts`,
  `actions/extended.ts` — same shape rewrite (6 method names).

Test plumbing
-------------
* `tests/actions/_helpers.ts` — `mockApiHub()` grows a `contacts`
  field built by `mockContactsApi()`.
* `tests/bridge-member-identity.test.ts::RefreshingBridge` — was
  `override async fetchGroupMemberList()`. After the move the method
  lives on `this.apis.contacts`, not `this`. Switched to patching the
  method on the constructed ContactsApi instance directly.
* `tests/actions/friend.test.ts` — `bridge.fetchFriendList` →
  `bridge.apis.contacts.fetchFriendList`; the "refresh throws" branch
  overrides via `bridge.apis.contacts.fetchFriendList = vi.fn(…)`.
* `tests/onebot/contact-actions.test.ts`, `extended-actions.test.ts`,
  `request-actions.test.ts` — local `fakeBridge` helpers gained an
  auto-promotion shim that rewrites flat method stubs (the pre-#6
  test API) into the new `apis.<area>.method` shape. Keeps existing
  test setup readable while the production code uses the new path.

Tests: 587/587 pass (same baseline; pre-existing network-manager
native-addon failure unchanged).
This commit is contained in:
DrSmoothl committed 2026-05-20 22:27:32 +08:00
1 parent 3e5dca1bd4
commit 6bf53890dc
17 files changed
+547 -465

No files matched your search

+22
View File
@@ -41,14 +41,36 @@ export function mockMessageApi(): MockMessageApi {
};
}
export interface MockContactsApi {
fetchFriendList: ReturnType<typeof vi.fn>;
fetchGroupList: ReturnType<typeof vi.fn>;
fetchGroupMemberList: ReturnType<typeof vi.fn>;
fetchUserProfile: ReturnType<typeof vi.fn>;
fetchGroupRequests: ReturnType<typeof vi.fn>;
fetchDownloadRKeys: ReturnType<typeof vi.fn>;
}
export function mockContactsApi(): MockContactsApi {
return {
fetchFriendList: vi.fn(async () => []),
fetchGroupList: vi.fn(async () => []),
fetchGroupMemberList: vi.fn(async () => []),
fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
fetchGroupRequests: vi.fn(async () => []),
fetchDownloadRKeys: vi.fn(async () => []),
};
}
export interface MockApiHub {
message: MockMessageApi;
contacts: MockContactsApi;
// additional Apis added commit-by-commit as #6 progresses
}
export function mockApiHub(overrides: Partial<MockApiHub> = {}): MockApiHub {
return {
message: overrides.message ?? mockMessageApi(),
contacts: overrides.contacts ?? mockContactsApi(),
};
}
+6 -4
View File
@@ -41,13 +41,15 @@ describe('actions/friend', () => {
expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).field1.block).toBe(true);
expect(bridge.fetchFriendList).toHaveBeenCalled();
expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalled();
});
it('deleteFriend still succeeds when the friend-list refresh throws', async () => {
const bridge = mockBridge({
fetchFriendList: vi.fn(async () => { throw new Error('cache miss'); }),
});
const bridge = mockBridge();
// `fetchFriendList` lives on `apis.contacts` post-#6 refactor;
// override the default no-op stub to make the friend-list refresh
// throw and verify deleteFriend swallows the error.
bridge.apis.contacts.fetchFriendList = vi.fn(async () => { throw new Error('cache miss'); });
await expect(friend.deleteFriend(bridge as any, 10001))
.resolves.toBeUndefined();
});
@@ -39,14 +39,22 @@ class RefreshingBridge extends Bridge {
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
super(identity);
}
override async fetchGroupMemberList(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;
// `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;
};
}
}
@@ -25,8 +25,28 @@ import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
* fail loudly if they exercise a code path the fake hasn't been told
* about. Tests just spread the methods they care about.
*/
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
// `apisAutoPromote` lets tests written before #6 (which stubbed flat
// methods like `fetchFriendList: vi.fn()` on bridge directly) keep
// working without restructuring — the helper rewrites flat stubs into
// the new `apis.<area>.method` shape automatically. New code can also
// pass `apis: { contacts: { … } }` explicitly; the two merge.
const APIS_ROUTING: Record<string, string> = {
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
const apisSynth: Record<string, Record<string, any>> = {};
for (const [k, v] of Object.entries(overrides)) {
const area = APIS_ROUTING[k];
if (area) {
if (!apisSynth[area]) apisSynth[area] = {};
apisSynth[area][k] = v;
}
}
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
@@ -99,7 +119,7 @@ describe('onebot/contact-actions / getFriendList', () => {
});
const out = await getFriendList(bridge);
expect(out).toEqual([{ user_id: 22222, nickname: 'alice', remark: 'best-friend' }]);
expect(bridge.fetchFriendList).toHaveBeenCalledOnce();
expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalledOnce();
});
it('falls back to identity.friends on fetch failure', async () => {
@@ -117,7 +137,7 @@ describe('onebot/contact-actions / getGroupList', () => {
it('triggers fetch when the in-memory roster is empty', async () => {
const fetched = [makeGroup(100, 'Group A')];
// `groups` starts empty; the fetch callback flips it to mimic
// bridge.fetchGroupList writing back through identity.rememberGroups.
// bridge.apis.contacts.fetchGroupList writing back through identity.rememberGroups.
let groups: QQGroupInfo[] = [];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => { groups = fetched; return fetched; }),
@@ -126,7 +146,7 @@ describe('onebot/contact-actions / getGroupList', () => {
}),
});
const out = await getGroupList(bridge);
expect(bridge.fetchGroupList).toHaveBeenCalledOnce();
expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
expect(out).toEqual([{
group_id: 100, group_name: 'Group A',
member_count: 0, max_member_count: 500,
@@ -140,7 +160,7 @@ describe('onebot/contact-actions / getGroupList', () => {
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge);
expect(bridge.fetchGroupList).not.toHaveBeenCalled();
expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
});
it('forces fetch when noCache=true even with a populated cache', async () => {
@@ -150,7 +170,7 @@ describe('onebot/contact-actions / getGroupList', () => {
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge, true);
expect(bridge.fetchGroupList).toHaveBeenCalledOnce();
expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
});
it('serves the stale cache when the fetch path throws', async () => {
@@ -174,7 +194,7 @@ describe('onebot/contact-actions / getGroupInfo', () => {
});
const out = await getGroupInfo(bridge, 500);
expect(out).toMatchObject({ group_id: 500, group_name: 'Group E' });
expect(bridge.fetchGroupList).not.toHaveBeenCalled();
expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
});
it('triggers fetch when the group is unknown to the cache', async () => {
@@ -245,7 +265,7 @@ describe('onebot/contact-actions / getGroupMemberInfo', () => {
});
const out = await getGroupMemberInfo(bridge, 1000, 44);
expect(out).toMatchObject({ user_id: 44, nickname: 'dave', card: 'D' });
expect(bridge.fetchGroupMemberList).not.toHaveBeenCalled();
expect(bridge.apis.contacts.fetchGroupMemberList).not.toHaveBeenCalled();
});
it('triggers fetch when member is unknown and re-queries the cache', async () => {
@@ -28,8 +28,27 @@ function fakeMeta(overrides: Partial<MessageMeta> = {}): MessageMeta {
* pre-stubbed for the test. Same pattern as contact-actions.test.ts —
* keeps tests honest about which surface they actually need.
*/
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
// Maps flat method names → ApiHub area they moved to under the #6
// refactor. Auto-promotion lets tests written against the pre-refactor
// flat surface (`fetchGroupRequests: vi.fn()`) keep working without
// per-test restructure.
const APIS_ROUTING: Record<string, string> = {
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
const apisSynth: Record<string, Record<string, any>> = {};
for (const [k, v] of Object.entries(overrides)) {
const area = APIS_ROUTING[k];
if (area) {
if (!apisSynth[area]) apisSynth[area] = {};
apisSynth[area][k] = v;
}
}
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
@@ -3,8 +3,24 @@ import { handleGroupAddRequest } from '../../src/onebot/modules/request-actions'
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { GroupRequestInfo } from '../../src/bridge/qq-info';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
// See `contact-actions.test.ts` for the auto-promotion rationale.
const APIS_ROUTING: Record<string, string> = {
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
const apisSynth: Record<string, Record<string, any>> = {};
for (const [k, v] of Object.entries(overrides)) {
const area = APIS_ROUTING[k];
if (area) {
if (!apisSynth[area]) apisSynth[area] = {};
apisSynth[area][k] = v;
}
}
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);