feat(onebot): fetch real group history from server (#99)

get_group_msg_history was served only from the local observed-message store,
so it could never return more than what SnowLuma saw live (the "only 100
messages" symptom). It now fetches real history from the server.

- protocol: new SsoGetGroupMsg packet (trpc.msg.register_proxy.RegisterProxy
  .SsoGetGroupMsg, sequence-range fetch; fields per Lagrange). Each returned
  PushMsgBody is decoded by the existing group decoder via a factored-out
  buildContextFromMessage.
- core: MessageApi.getGroupHistory walks backward in small sequence windows
  with rate-limiting + data-volume guards — a process-wide throttle (≥300ms
  between sends), 30-seq chunks, ≤12 requests, ≤200 messages per call — so a
  hammering client can't make us flood the server and get kicked.
- onebot: get_group_msg_history resolves the anchor sequence (requested
  message_id or latest observed), fetches from the server, converts + returns,
  and persists each fetched message. Falls back to the local store on
  unknown anchor / empty / error.

Persisting fetched history also fixes replying to pre-injection messages:
the reply path resolves message_id→sequence via the store, which now contains
the fetched messages.

Tests: SsoGetGroupMsg request/response round-trip + decode reuse (protocol);
walk-back chunking/dedup/cap/floor (core).
This commit is contained in:
DrSmoothl committed 2026-06-14 19:11:03 +08:00
1 parent ee8eb928b3
commit 987ac09896
11 files changed
+419 -12

No files matched your search

+22 -8
View File
@@ -1,7 +1,7 @@
import { protobuf_decode } from '@snowluma/proton';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { IdentityService } from '../identity-service';
import type { ContentHead, MessageBody, PushMsg, ResponseHead } from '@snowluma/proto-defs/message';
import type { ContentHead, MessageBody, PushMsg, PushMsgBody as ProtoMessage, ResponseHead } from '@snowluma/proto-defs/message';
export type PushMsgBody = MessageBody;
export type PushMsgResponseHead = ResponseHead;
@@ -37,7 +37,27 @@ export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPus
const push = protobuf_decode<PushMsg>(pkt.body);
if (!push?.message) return null;
const msg = push.message;
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) selfUin = n;
}
return buildContextFromMessage(push.message, selfUin, identity);
}
/**
* Build a push context from an already-extracted per-message struct (the same
* `PushMsgBody` shape that `PushMsg.message` carries). Used both by
* {@link buildContext} (live OlPush) and by the group-history fetch, whose
* `SsoGetGroupMsgResponse.body.messages` are these same structs — so the
* regular msg-push decoders parse fetched history unchanged.
*/
export function buildContextFromMessage(
msg: ProtoMessage,
selfUin: number,
identity: IdentityService,
): MsgPushContext | null {
if (!msg.contentHead) return null;
const head: MsgPushHead = {
@@ -55,12 +75,6 @@ export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPus
fromUid = msg.responseHead.fromUid ?? '';
}
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) selfUin = n;
}
const content = msg.body?.msgContent ?? new Uint8Array(0);
return {
@@ -0,0 +1,56 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { buildContextFromMessage } from './context';
import { decodeGroupMessage } from './decoders/group-message';
export const SSO_GET_GROUP_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetGroupMsg';
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
}
/**
* Fetch one [startSeq, endSeq] window of group history from the server via
* `SsoGetGroupMsg`, decoding each returned message with the regular group
* decoder. Returns `group_message` events sorted oldest→newest by sequence.
*
* One packet per call — the caller (MessageApi.getGroupHistory) owns the
* chunking/throttling so the server's frequency limits aren't tripped.
*/
export async function fetchGroupMessageRange(
sender: RawSender,
identity: IdentityService,
selfUin: number,
groupUin: number,
startSeq: number,
endSeq: number,
): Promise<GroupMessage[]> {
if (!(groupUin > 0) || !(endSeq > 0) || startSeq > endSeq) return [];
const req = protobuf_encode<SsoGetGroupMsg>({
info: { groupUin, startSequence: startSeq, endSequence: endSeq },
direction: true,
});
const res = await sender.sendRawPacket(SSO_GET_GROUP_MSG_CMD, req);
if (!res.success || !res.gotResponse || !res.responseData) return [];
const decoded = protobuf_decode<SsoGetGroupMsgResponse>(res.responseData);
const messages = decoded?.body?.messages ?? [];
const out: GroupMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) continue;
for (const ev of decodeGroupMessage(ctx)) {
if (ev.kind === 'group_message' && ev.msgSeq > 0) out.push(ev);
}
}
out.sort((a, b) => a.msgSeq - b.msgSeq);
return out;
}
+2
View File
@@ -18,6 +18,8 @@ import { decodeTempMessage } from './decoders/temp-message';
import { PkgType } from './enums';
import { MsgPushRegistry } from './registry';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
const registry = new MsgPushRegistry();
@@ -0,0 +1,80 @@
// Round-trips the SsoGetGroupMsg request/response protos (proton codegen +
// field tags) and the fetched-history decode path (each returned PushMsgBody
// re-uses the regular group decoder).
import { describe, expect, it } from 'vitest';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg';
import type { IdentityService } from '../../src/identity-service';
import { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from '../../src/msg-push';
const identity = { findGroupMember: () => undefined } as unknown as IdentityService;
function okResult(data: Uint8Array): SendPacketResult {
return { success: true, gotResponse: true, responseData: data } as SendPacketResult;
}
describe('fetchGroupMessageRange / SsoGetGroupMsg', () => {
it('sends the right command and request field tags', async () => {
let captured: { cmd: string; body: Uint8Array } | null = null;
const sender = {
sendRawPacket: async (cmd: string, body: Uint8Array) => {
captured = { cmd, body };
return okResult(protobuf_encode<SsoGetGroupMsgResponse>({ body: { groupUin: 9999, messages: [] } }));
},
};
await fetchGroupMessageRange(sender, identity, 10001, 9999, 100, 120);
expect(captured!.cmd).toBe(SSO_GET_GROUP_MSG_CMD);
const req = protobuf_decode<SsoGetGroupMsg>(captured!.body);
expect(req.info?.groupUin).toBe(9999);
expect(req.info?.startSequence).toBe(100);
expect(req.info?.endSequence).toBe(120);
expect(req.direction).toBe(true);
});
it('decodes returned group messages (seq/group/sender, self uin), oldest→newest', async () => {
const resp = protobuf_encode<SsoGetGroupMsgResponse>({
body: {
groupUin: 9999,
startSequence: 100,
endSequence: 120,
messages: [
{
responseHead: { fromUin: 222, grp: { groupUin: 9999, memberName: 'Bob' } },
contentHead: { msgType: 82, sequence: 120, timestamp: 1700000120, msgId: 5120 },
body: { richText: { elems: [] } },
},
{
responseHead: { fromUin: 111, grp: { groupUin: 9999, memberName: 'Alice' } },
contentHead: { msgType: 82, sequence: 110, timestamp: 1700000110, msgId: 5110 },
body: { richText: { elems: [] } },
},
],
},
});
const sender = { sendRawPacket: async () => okResult(resp) };
const out = await fetchGroupMessageRange(sender, identity, 10001, 9999, 100, 120);
expect(out.map((m) => m.msgSeq)).toEqual([110, 120]); // sorted ascending
expect(out.every((m) => m.kind === 'group_message')).toBe(true);
expect(out.every((m) => m.groupId === 9999)).toBe(true);
expect(out.every((m) => m.selfUin === 10001)).toBe(true);
expect(out[0]).toMatchObject({ msgSeq: 110, senderUin: 111, senderNick: 'Alice' });
expect(out[1]).toMatchObject({ msgSeq: 120, senderUin: 222, senderNick: 'Bob' });
});
it('returns [] on a failed packet or out-of-range request', async () => {
const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) };
expect(await fetchGroupMessageRange(failSender, identity, 10001, 9999, 100, 120)).toEqual([]);
// start > end is rejected before any send
let sent = false;
const guardSender = { sendRawPacket: async () => { sent = true; return okResult(new Uint8Array()); } };
expect(await fetchGroupMessageRange(guardSender, identity, 10001, 9999, 200, 100)).toEqual([]);
expect(sent).toBe(false);
});
});