diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index 84a2086e..324d42a3 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -123,6 +123,7 @@ const HISTORY_MAX_COUNT = 200; // hard cap on messages returned per call const HISTORY_CHUNK_SEQ = 30; // sequence span per server request (small packet) const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends +const HISTORY_MAX_SEQUENCE = 0xffff_ffff; // sequence fields are protobuf uint32 // Serialized throttle gate: chains so concurrent callers queue, and enforces // at least HISTORY_MIN_GAP_MS between actual sends (the first send isn't @@ -160,12 +161,7 @@ async function walkBackHistory( for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) { const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1); await throttleHistory(); - let batch: T[]; - try { - batch = await fetchWindow(start, curEnd); - } catch { - break; // network/decode error — return whatever we have so far - } + const batch = await fetchWindow(start, curEnd); if (batch.length > 0) { let minSeq = curEnd; for (const ev of batch) { @@ -181,6 +177,74 @@ async function walkBackHistory( return all.slice(-want); // newest `want`, oldest→newest } +/** + * Pull sequence windows starting at `startSeq`, retaining the oldest `want` + * messages at or after the anchor. The returned list is chronological, matching + * the existing backward-history API shape. + */ +async function walkForwardHistory( + startSeq: number, + count: number, + fetchWindow: (startSeq: number, endSeq: number) => Promise, +): Promise { + if (!(startSeq > 0) || startSeq > HISTORY_MAX_SEQUENCE) return []; + const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); + + const collected = new Map(); + const budget = { remaining: HISTORY_MAX_REQUESTS }; + let curStart = startSeq; + while (budget.remaining > 0 && collected.size < want && curStart <= HISTORY_MAX_SEQUENCE) { + const end = Math.min(HISTORY_MAX_SEQUENCE, curStart + HISTORY_CHUNK_SEQ - 1); + const window = await fetchForwardWindow(curStart, end, budget, fetchWindow); + for (const event of window.messages) collected.set(event.msgSeq, event); + if (!window.complete || end === HISTORY_MAX_SEQUENCE) break; + curStart = end + 1; + } + + const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq); + return all.slice(0, want); +} + +interface ForwardWindowResult { + messages: T[]; + complete: boolean; +} + +/** + * Resolve one forward window from its lower boundary. The history service may + * short-cap a range to its newest suffix; recursively fetch the omitted prefix + * before exposing that suffix so callers never skip messages nearest the + * anchor. An exhausted request budget marks the window incomplete, preventing + * later messages from being returned ahead of an unresolved prefix. + */ +async function fetchForwardWindow( + startSeq: number, + endSeq: number, + budget: { remaining: number }, + fetchWindow: (startSeq: number, endSeq: number) => Promise, +): Promise> { + if (budget.remaining <= 0) return { messages: [], complete: false }; + + budget.remaining--; + await throttleHistory(); + const batch = await fetchWindow(startSeq, endSeq); + if (batch.length === 0) return { messages: [], complete: true }; + + const messages = [...new Map(batch.map((event) => [event.msgSeq, event])).values()] + .sort((a, b) => a.msgSeq - b.msgSeq); + for (const message of messages) { + if (!Number.isInteger(message.msgSeq) || message.msgSeq < startSeq || message.msgSeq > endSeq) { + throw new Error(`history response sequence is outside requested range ${startSeq}-${endSeq}`); + } + } + const firstSequence = messages[0]!.msgSeq; + if (firstSequence === startSeq) return { messages, complete: true }; + + const prefix = await fetchForwardWindow(startSeq, firstSequence - 1, budget, fetchWindow); + if (!prefix.complete) return prefix; + return { messages: [...prefix.messages, ...messages], complete: true }; +} + export class MessageApi { constructor(private readonly ctx: BridgeContext) { } @@ -726,29 +790,44 @@ export class MessageApi { } /** - * Fetch real group history from the server (`SsoGetGroupMsg`), ending at and - * including `endSeq`, walking backward in small windows until `count` - * messages are gathered or the floor is reached. Rate-limited + capped so a - * hammering client can't make us flood the server (and get the account - * kicked). Returns decoded `group_message` events oldest→newest. + * Fetch real group history from the server (`SsoGetGroupMsg`), including the + * anchor and walking backward or forward in small windows. Rate-limited and + * capped so a hammering client cannot flood the server. Returns decoded + * `group_message` events oldest→newest regardless of query direction. */ - async getGroupHistory(groupUin: number, endSeq: number, count: number, selfUin = 0): Promise { + async getGroupHistory( + groupUin: number, + anchorSeq: number, + count: number, + selfUin = 0, + reverseOrder = true, + ): Promise { if (!(groupUin > 0)) return []; - return walkBackHistory(endSeq, count, (start, end) => - fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end)); + const fetchWindow = (start: number, end: number) => + fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end); + return reverseOrder + ? walkBackHistory(anchorSeq, count, fetchWindow) + : walkForwardHistory(anchorSeq, count, fetchWindow); } /** - * Fetch real private (c2c) history from the server (`SsoGetC2cMsg`), ending - * at and including `endSeq`. Same rate-limit + data-volume guards as the - * group variant (they share the throttle gate). `friendUid` is the - * conversation peer's UID. Returns decoded `friend_message` events - * oldest→newest. + * Fetch real private history from the server (`SsoGetC2cMsg`), including the + * anchor in the requested direction. It shares the group variant's throttle + * and data-volume guards. Returns decoded events oldest→newest. */ - async getC2cHistory(friendUid: string, endSeq: number, count: number, selfUin = 0): Promise { + async getC2cHistory( + friendUid: string, + anchorSeq: number, + count: number, + selfUin = 0, + reverseOrder = true, + ): Promise { if (!friendUid) return []; - return walkBackHistory(endSeq, count, (start, end) => - fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end)); + const fetchWindow = (start: number, end: number) => + fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end); + return reverseOrder + ? walkBackHistory(anchorSeq, count, fetchWindow) + : walkForwardHistory(anchorSeq, count, fetchWindow); } /** diff --git a/packages/core/tests/group-history-walkback.test.ts b/packages/core/tests/group-history-walkback.test.ts index 97ff47a7..62cf3913 100644 --- a/packages/core/tests/group-history-walkback.test.ts +++ b/packages/core/tests/group-history-walkback.test.ts @@ -1,21 +1,20 @@ -// MessageApi.getGroupHistory walk-back loop: chunking, dedup, server-short-cap -// handling, floor termination, slice(-want). fetchGroupMessageRange is mocked -// so this exercises the loop/cursor logic, not the wire decode (covered in -// packages/protocol/tests/msg-push/fetch-group-history.test.ts). +// MessageApi history pagination: bidirectional chunking, dedup, short-cap +// handling, floor termination, and chronological output. Range fetches are +// mocked so this exercises cursor logic rather than wire decoding. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('@snowluma/protocol/msg-push', async (importOriginal) => { const actual = await importOriginal(); - return { ...actual, fetchGroupMessageRange: vi.fn() }; + return { ...actual, fetchGroupMessageRange: vi.fn(), fetchC2cMessageRange: vi.fn() }; }); -import { fetchGroupMessageRange } from '@snowluma/protocol/msg-push'; +import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push'; import { MessageApi } from '../src/bridge/apis/message'; const mockFetch = vi.mocked(fetchGroupMessageRange); +const mockC2cFetch = vi.mocked(fetchC2cMessageRange); -// eslint-disable-next-line @typescript-eslint/no-explicit-any function gm(seq: number): any { return { kind: 'group_message', groupName: '', time: 0, selfUin: 0, senderUin: 1, msgSeq: seq, @@ -23,16 +22,16 @@ function gm(seq: number): any { }; } -// eslint-disable-next-line @typescript-eslint/no-explicit-any const ctx = { identity: {}, sendRawPacket: vi.fn() } as any; -describe('MessageApi.getGroupHistory walk-back', () => { +describe('MessageApi history pagination', () => { // The walk-back loop enforces a real ~300ms gap between each SsoGetGroupMsg // send (a deliberate anti-flood throttle, unchanged in production). Fake the // clock so the test exercises the loop/cursor logic instantly instead of // waiting out 300ms × up-to-12 real sends. beforeEach(() => { mockFetch.mockReset(); + mockC2cFetch.mockReset(); vi.useFakeTimers(); }); afterEach(() => vi.useRealTimers()); @@ -62,6 +61,58 @@ describe('MessageApi.getGroupHistory walk-back', () => { } }); + it('walks forward from and including the anchor when reverse order is disabled', async () => { + mockFetch.mockImplementation(async (_s, _id, _self, _g, start, end) => { + const out = []; + for (let s = start; s <= end; s++) out.push(gm(s)); + return out; + }); + + const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 100, 5, 0, false)); + + expect(res.map((message) => message.msgSeq)).toEqual([100, 101, 102, 103, 104]); + }); + + it('does not skip the anchor-side prefix when a forward window is short-capped', async () => { + mockFetch.mockImplementation(async (_s, _id, _self, _g, start, end) => { + const out = []; + for (let s = Math.max(start, end - 9); s <= end; s++) out.push(gm(s)); + return out; + }); + + const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 100, 20, 0, false)); + + expect(res.map((message) => message.msgSeq)).toEqual( + Array.from({ length: 20 }, (_, index) => 100 + index), + ); + }); + + it('uses the same forward semantics for private history', async () => { + mockC2cFetch.mockImplementation(async (_s, _id, _self, _uid, start, end) => { + const out = []; + for (let s = start; s <= end; s++) out.push(gm(s)); + return out; + }); + + const res = await runHistory(new MessageApi(ctx).getC2cHistory('u_friend', 300, 3, 0, false)); + + expect(res.map((message) => message.msgSeq)).toEqual([300, 301, 302]); + }); + + it('stops forward pagination at the unsigned sequence ceiling', async () => { + mockFetch.mockImplementation(async (_s, _id, _self, _g, start, end) => { + const out = []; + for (let s = start; s <= end; s++) out.push(gm(s)); + return out; + }); + + const res = await runHistory( + new MessageApi(ctx).getGroupHistory(9999, 0xffff_fffe, 5, 0, false), + ); + + expect(res.map((message) => message.msgSeq)).toEqual([0xffff_fffe, 0xffff_ffff]); + }); + it('stops at the sequence floor when fewer messages exist than requested', async () => { mockFetch.mockImplementation(async (_s, _id, _self, _g, start, end) => { const out = []; @@ -85,6 +136,18 @@ describe('MessageApi.getGroupHistory walk-back', () => { expect(res.length).toBeLessThanOrEqual(200); // HISTORY_MAX_COUNT }); + it('rejects a failed later window instead of presenting partial history as complete', async () => { + mockFetch + .mockResolvedValueOnce([gm(200)]) + .mockRejectedValueOnce(new Error('history transport failed')); + + const assertion = expect( + new MessageApi(ctx).getGroupHistory(9999, 200, 20), + ).rejects.toThrow('history transport failed'); + await vi.runAllTimersAsync(); + await assertion; + }); + it('returns [] for an invalid anchor without sending', async () => { expect(await new MessageApi(ctx).getGroupHistory(0, 100, 10)).toEqual([]); expect(await new MessageApi(ctx).getGroupHistory(9999, 0, 10)).toEqual([]);