fix(onebot): correct private message history (#256)
Use the C2C roam cursor and canonical NT sequence for bidirectional history. Persist direction-aware recall tombstones so recalled messages cannot reappear.
This commit is contained in:
37 files changed
+1853
-242
No files matched your search
@@ -14,7 +14,11 @@ import type {
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
|
||||
import {
|
||||
fetchC2cMessageRange,
|
||||
fetchC2cRoamMessagePage,
|
||||
fetchGroupMessageRange,
|
||||
} from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
@@ -152,6 +156,7 @@ async function walkBackHistory<T extends { msgSeq: number }>(
|
||||
endSeq: number,
|
||||
count: number,
|
||||
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
|
||||
sequenceOf: (event: T) => number = (event) => event.msgSeq,
|
||||
): Promise<T[]> {
|
||||
if (!(endSeq > 0)) return [];
|
||||
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
|
||||
@@ -165,15 +170,19 @@ async function walkBackHistory<T extends { msgSeq: number }>(
|
||||
if (batch.length > 0) {
|
||||
let minSeq = curEnd;
|
||||
for (const ev of batch) {
|
||||
collected.set(ev.msgSeq, ev);
|
||||
if (ev.msgSeq < minSeq) minSeq = ev.msgSeq;
|
||||
const sequence = sequenceOf(ev);
|
||||
if (!Number.isInteger(sequence) || sequence < start || sequence > curEnd) {
|
||||
throw new Error(`history response sequence is outside requested range ${start}-${curEnd}`);
|
||||
}
|
||||
collected.set(sequence, ev);
|
||||
if (sequence < minSeq) minSeq = sequence;
|
||||
}
|
||||
curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps)
|
||||
} else {
|
||||
curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it
|
||||
}
|
||||
}
|
||||
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
|
||||
const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b));
|
||||
return all.slice(-want); // newest `want`, oldest→newest
|
||||
}
|
||||
|
||||
@@ -186,6 +195,7 @@ async function walkForwardHistory<T extends { msgSeq: number }>(
|
||||
startSeq: number,
|
||||
count: number,
|
||||
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
|
||||
sequenceOf: (event: T) => number = (event) => event.msgSeq,
|
||||
): Promise<T[]> {
|
||||
if (!(startSeq > 0) || startSeq > HISTORY_MAX_SEQUENCE) return [];
|
||||
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
|
||||
@@ -195,13 +205,13 @@ async function walkForwardHistory<T extends { msgSeq: number }>(
|
||||
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);
|
||||
const window = await fetchForwardWindow(curStart, end, budget, fetchWindow, sequenceOf);
|
||||
for (const event of window.messages) collected.set(sequenceOf(event), event);
|
||||
if (!window.complete || end === HISTORY_MAX_SEQUENCE) break;
|
||||
curStart = end + 1;
|
||||
}
|
||||
|
||||
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
|
||||
const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b));
|
||||
return all.slice(0, want);
|
||||
}
|
||||
|
||||
@@ -222,6 +232,7 @@ async function fetchForwardWindow<T extends { msgSeq: number }>(
|
||||
endSeq: number,
|
||||
budget: { remaining: number },
|
||||
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
|
||||
sequenceOf: (event: T) => number,
|
||||
): Promise<ForwardWindowResult<T>> {
|
||||
if (budget.remaining <= 0) return { messages: [], complete: false };
|
||||
|
||||
@@ -230,17 +241,24 @@ async function fetchForwardWindow<T extends { msgSeq: number }>(
|
||||
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);
|
||||
const messages = [...new Map(batch.map((event) => [sequenceOf(event), event])).values()]
|
||||
.sort((a, b) => sequenceOf(a) - sequenceOf(b));
|
||||
for (const message of messages) {
|
||||
if (!Number.isInteger(message.msgSeq) || message.msgSeq < startSeq || message.msgSeq > endSeq) {
|
||||
const sequence = sequenceOf(message);
|
||||
if (!Number.isInteger(sequence) || sequence < startSeq || sequence > endSeq) {
|
||||
throw new Error(`history response sequence is outside requested range ${startSeq}-${endSeq}`);
|
||||
}
|
||||
}
|
||||
const firstSequence = messages[0]!.msgSeq;
|
||||
const firstSequence = sequenceOf(messages[0]!);
|
||||
if (firstSequence === startSeq) return { messages, complete: true };
|
||||
|
||||
const prefix = await fetchForwardWindow(startSeq, firstSequence - 1, budget, fetchWindow);
|
||||
const prefix = await fetchForwardWindow(
|
||||
startSeq,
|
||||
firstSequence - 1,
|
||||
budget,
|
||||
fetchWindow,
|
||||
sequenceOf,
|
||||
);
|
||||
if (!prefix.complete) return prefix;
|
||||
return { messages: [...prefix.messages, ...messages], complete: true };
|
||||
}
|
||||
@@ -825,9 +843,78 @@ export class MessageApi {
|
||||
if (!friendUid) return [];
|
||||
const fetchWindow = (start: number, end: number) =>
|
||||
fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end);
|
||||
const serverSequence = (message: FriendMessage) => message.ntMsgSeq ?? 0;
|
||||
return reverseOrder
|
||||
? walkBackHistory(anchorSeq, count, fetchWindow)
|
||||
: walkForwardHistory(anchorSeq, count, fetchWindow);
|
||||
? walkBackHistory(anchorSeq, count, fetchWindow, serverSequence)
|
||||
: walkForwardHistory(anchorSeq, count, fetchWindow, serverSequence);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the latest private history page without relying on a locally cached
|
||||
* sequence. C2C field-5 sequences are sender-local, so only SsoGetRoamMsg's
|
||||
* timestamp cursor can safely bootstrap an unanchored conversation.
|
||||
*/
|
||||
async getC2cLatestHistory(
|
||||
friendUid: string,
|
||||
count: number,
|
||||
selfUin = 0,
|
||||
beforeTime = Math.floor(Date.now() / 1000) + 1,
|
||||
): Promise<FriendMessage[]> {
|
||||
if (!friendUid) return [];
|
||||
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
|
||||
const collected = new Map<number, FriendMessage>();
|
||||
let cursor = { time: beforeTime, random: 0 };
|
||||
const seenCursors = new Set<string>([`${cursor.time}:${cursor.random}`]);
|
||||
let reachedEnd = false;
|
||||
|
||||
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want; i++) {
|
||||
await throttleHistory();
|
||||
const page = await fetchC2cRoamMessagePage(
|
||||
this.ctx,
|
||||
this.ctx.identity,
|
||||
selfUin,
|
||||
friendUid,
|
||||
cursor.time,
|
||||
want - collected.size,
|
||||
cursor.random,
|
||||
);
|
||||
for (const message of page.messages) {
|
||||
const sequence = message.ntMsgSeq ?? 0;
|
||||
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
|
||||
throw new Error(`private roam history returned invalid NT sequence ${String(sequence)}`);
|
||||
}
|
||||
collected.set(sequence, message);
|
||||
}
|
||||
|
||||
if (collected.size >= want) break;
|
||||
if (page.cursor.time === 0 && page.cursor.random === 0) {
|
||||
reachedEnd = true;
|
||||
break;
|
||||
}
|
||||
const nextCursorKey = `${page.cursor.time}:${page.cursor.random}`;
|
||||
if (seenCursors.has(nextCursorKey)) {
|
||||
if (page.messages.length === 0) {
|
||||
reachedEnd = true;
|
||||
break;
|
||||
}
|
||||
throw new Error(
|
||||
`private roam history cursor did not advance from ${cursor.time}/${cursor.random}`,
|
||||
);
|
||||
}
|
||||
seenCursors.add(nextCursorKey);
|
||||
cursor = page.cursor;
|
||||
}
|
||||
|
||||
if (collected.size < want && !reachedEnd) {
|
||||
throw new Error(
|
||||
`private roam history request budget exhausted after ${HISTORY_MAX_REQUESTS} pages `
|
||||
+ `(requested=${want}, collected=${collected.size})`,
|
||||
);
|
||||
}
|
||||
|
||||
return [...collected.values()]
|
||||
.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time)
|
||||
.slice(-want);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -848,16 +935,16 @@ export class MessageApi {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single c2c message by its exact sequence — `SsoGetC2cMsg` over a
|
||||
* 1-wide `[seq, seq]` range, through the same throttle gate. `friendUid` is the
|
||||
* conversation peer. Returns the matching `friend_message`, or null.
|
||||
* Fetch a single c2c message by its exact conversation-wide NT sequence —
|
||||
* `SsoGetC2cMsg` over a 1-wide `[seq, seq]` range, through the same throttle
|
||||
* gate. Sender-local reply/recall sequences must not be passed here.
|
||||
*/
|
||||
async getC2cMessageBySeq(friendUid: string, seq: number, selfUin = 0): Promise<FriendMessage | null> {
|
||||
if (!friendUid || !(seq > 0)) return null;
|
||||
await throttleHistory();
|
||||
try {
|
||||
const batch = await fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, seq, seq);
|
||||
return batch.find((m) => m.msgSeq === seq) ?? null;
|
||||
return batch.find((m) => m.ntMsgSeq === seq) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -6,14 +6,24 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/msg-push', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@snowluma/protocol/msg-push')>();
|
||||
return { ...actual, fetchGroupMessageRange: vi.fn(), fetchC2cMessageRange: vi.fn() };
|
||||
return {
|
||||
...actual,
|
||||
fetchGroupMessageRange: vi.fn(),
|
||||
fetchC2cMessageRange: vi.fn(),
|
||||
fetchC2cRoamMessagePage: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
|
||||
import {
|
||||
fetchC2cMessageRange,
|
||||
fetchC2cRoamMessagePage,
|
||||
fetchGroupMessageRange,
|
||||
} from '@snowluma/protocol/msg-push';
|
||||
import { MessageApi } from '../src/bridge/apis/message';
|
||||
|
||||
const mockFetch = vi.mocked(fetchGroupMessageRange);
|
||||
const mockC2cFetch = vi.mocked(fetchC2cMessageRange);
|
||||
const mockC2cRoamFetch = vi.mocked(fetchC2cRoamMessagePage);
|
||||
|
||||
function gm(seq: number): any {
|
||||
return {
|
||||
@@ -32,6 +42,7 @@ describe('MessageApi history pagination', () => {
|
||||
beforeEach(() => {
|
||||
mockFetch.mockReset();
|
||||
mockC2cFetch.mockReset();
|
||||
mockC2cRoamFetch.mockReset();
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
@@ -90,13 +101,110 @@ describe('MessageApi history pagination', () => {
|
||||
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));
|
||||
for (let s = start; s <= end; s++) {
|
||||
out.push({ ...gm(s + 10_000), kind: 'friend_message', ntMsgSeq: 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]);
|
||||
expect(res.map((message) => message.ntMsgSeq)).toEqual([300, 301, 302]);
|
||||
});
|
||||
|
||||
it('fetches the latest private page by timestamp without inventing a sequence anchor', async () => {
|
||||
mockC2cRoamFetch.mockResolvedValue({
|
||||
cursor: { time: 0, random: 0 },
|
||||
messages: [
|
||||
{ ...gm(32742), kind: 'friend_message', ntMsgSeq: 63213, time: 1700000002 },
|
||||
{ ...gm(32743), kind: 'friend_message', ntMsgSeq: 63214, time: 1700000001 },
|
||||
],
|
||||
} as any);
|
||||
|
||||
const result = await runHistory(
|
||||
new MessageApi(ctx).getC2cLatestHistory('u_friend', 20, 10001, 1700000100),
|
||||
);
|
||||
|
||||
expect(mockC2cRoamFetch).toHaveBeenCalledWith(
|
||||
ctx,
|
||||
ctx.identity,
|
||||
10001,
|
||||
'u_friend',
|
||||
1700000100,
|
||||
20,
|
||||
0,
|
||||
);
|
||||
expect(result.map((message) => message.ntMsgSeq)).toEqual([63213, 63214]);
|
||||
expect(mockC2cFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('follows the private roam cursor until the requested count is filled', async () => {
|
||||
mockC2cRoamFetch
|
||||
.mockResolvedValueOnce({
|
||||
cursor: { time: 1700000000, random: 7 },
|
||||
messages: [
|
||||
{ ...gm(32744), kind: 'friend_message', ntMsgSeq: 63215, time: 1700000002 },
|
||||
],
|
||||
} as any)
|
||||
.mockResolvedValueOnce({
|
||||
cursor: { time: 1699999900, random: 8 },
|
||||
messages: [
|
||||
{ ...gm(32742), kind: 'friend_message', ntMsgSeq: 63213, time: 1700000000 },
|
||||
{ ...gm(32743), kind: 'friend_message', ntMsgSeq: 63214, time: 1700000001 },
|
||||
],
|
||||
} as any);
|
||||
|
||||
const result = await runHistory(
|
||||
new MessageApi(ctx).getC2cLatestHistory('u_friend', 3, 10001, 1700000100),
|
||||
);
|
||||
|
||||
expect(mockC2cRoamFetch).toHaveBeenNthCalledWith(
|
||||
1, ctx, ctx.identity, 10001, 'u_friend', 1700000100, 3, 0,
|
||||
);
|
||||
expect(mockC2cRoamFetch).toHaveBeenNthCalledWith(
|
||||
2, ctx, ctx.identity, 10001, 'u_friend', 1700000000, 2, 7,
|
||||
);
|
||||
expect(result.map((message) => message.ntMsgSeq)).toEqual([63213, 63214, 63215]);
|
||||
});
|
||||
|
||||
it('rejects a stalled private roam cursor instead of returning a partial page', async () => {
|
||||
mockC2cRoamFetch.mockResolvedValue({
|
||||
cursor: { time: 1700000100, random: 0 },
|
||||
messages: [
|
||||
{ ...gm(32742), kind: 'friend_message', ntMsgSeq: 63213, time: 1700000000 },
|
||||
],
|
||||
} as any);
|
||||
|
||||
const assertion = expect(
|
||||
new MessageApi(ctx).getC2cLatestHistory('u_friend', 2, 10001, 1700000100),
|
||||
).rejects.toThrow('cursor did not advance');
|
||||
await vi.runAllTimersAsync();
|
||||
await assertion;
|
||||
});
|
||||
|
||||
it('rejects a partial private page when the request budget is exhausted', async () => {
|
||||
let page = 0;
|
||||
mockC2cRoamFetch.mockImplementation(async () => {
|
||||
page++;
|
||||
return {
|
||||
cursor: { time: 1700000100 - page, random: page },
|
||||
messages: [
|
||||
{
|
||||
...gm(32000 + page),
|
||||
kind: 'friend_message',
|
||||
ntMsgSeq: 63000 + page,
|
||||
time: 1700000100 - page,
|
||||
},
|
||||
],
|
||||
} as any;
|
||||
});
|
||||
|
||||
const assertion = expect(
|
||||
new MessageApi(ctx).getC2cLatestHistory('u_friend', 20, 10001, 1700000200),
|
||||
).rejects.toThrow('request budget exhausted');
|
||||
await vi.runAllTimersAsync();
|
||||
await assertion;
|
||||
expect(mockC2cRoamFetch).toHaveBeenCalledTimes(12);
|
||||
});
|
||||
|
||||
it('stops forward pagination at the unsigned sequence ceiling', async () => {
|
||||
|
||||
@@ -780,6 +780,8 @@ describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => {
|
||||
expect(event.kind).toBe('friend_recall');
|
||||
expect(event.userUin).toBe(77777);
|
||||
expect(event.msgSeq).toBe(4242);
|
||||
expect(event.clientSeq).toBe(4242);
|
||||
expect(event.recalledBySelf).toBe(false);
|
||||
});
|
||||
|
||||
it('subType 139 picks toUid as the peer (we recalled our msg sent to friend)', () => {
|
||||
@@ -791,6 +793,7 @@ describe('parseMsgPush Event0x210 subType=139 (self-recall direction)', () => {
|
||||
|
||||
expect(event.kind).toBe('friend_recall');
|
||||
expect(event.userUin).toBe(77777); // resolved from toUid (the friend), not fromUid (us)
|
||||
expect(event.recalledBySelf).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user