feat(onebot): backfill cloud history after login
Add an opt-in per-account login history backfill that waits for roster warmup and a 30-second grace period before silently filling local message history. The setting defaults to disabled and applies on the next account lifecycle. Run one account at a time, prioritize known local gaps, and process at most three groups plus three friends with one 20-message page per session. Failures are logged and never retried during the same login. Persist reconstructed history without dispatching OneBot events or changing QQ read state. Keep private metadata and event bodies atomic, honor recall tombstones, suppress live-only history side effects, avoid extra media requests, and stop queued, in-flight, or converting work when the account closes. Share the persistence path with manual history actions and add lifecycle, cancellation, corruption, partial-failure, peer-identity, and storage-atomicity regression coverage. Refs #280.
This commit is contained in:
15 files changed
+1810
-68
No files matched your search
@@ -67,6 +67,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
wsClients: [],
|
||||
},
|
||||
statusCommand: makeDefaultStatusCommand(),
|
||||
historySync: { enabled: false },
|
||||
notifications: { channelIds: [] },
|
||||
};
|
||||
}
|
||||
@@ -187,7 +188,7 @@ export function prepareOneBotConfigForRestore(
|
||||
}
|
||||
|
||||
const RESTORE_TOP_LEVEL_KEYS = new Set([
|
||||
'mode', 'networks', 'statusCommand', 'notifications', 'musicSignUrl',
|
||||
'mode', 'networks', 'statusCommand', 'historySync', 'notifications', 'musicSignUrl',
|
||||
'httpServers', 'httpClients', 'httpPostEndpoints', 'wsServers', 'wsClients',
|
||||
'messageFormat', 'reportSelfMessage',
|
||||
]);
|
||||
@@ -237,6 +238,7 @@ function validateOneBotRestoreSource(value: JsonObject): void {
|
||||
}
|
||||
|
||||
validateRestoreStatusCommand(value.statusCommand);
|
||||
validateRestoreHistorySync(value.historySync);
|
||||
validateRestoreNotifications(value.notifications);
|
||||
|
||||
const parsed = fromJson([value], false);
|
||||
@@ -345,6 +347,15 @@ function validateRestoreNotifications(value: unknown): void {
|
||||
});
|
||||
}
|
||||
|
||||
function validateRestoreHistorySync(value: unknown): void {
|
||||
if (value === undefined) return;
|
||||
if (!isObject(value)) invalid('$.historySync must be an object');
|
||||
rejectUnknownKeys(value, new Set(['enabled']), '$.historySync');
|
||||
if (value.enabled !== undefined && typeof value.enabled !== 'boolean') {
|
||||
invalid('$.historySync.enabled must be a boolean');
|
||||
}
|
||||
}
|
||||
|
||||
function rejectUnknownKeys(value: JsonObject, allowed: ReadonlySet<string>, at: string): void {
|
||||
const unknown = Object.keys(value).find((key) => !allowed.has(key));
|
||||
if (unknown) invalid(`${at}.${unknown} is not supported`);
|
||||
@@ -435,6 +446,11 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
|
||||
invalid(`statusCommand.trigger must be non-empty, single-line, and <= ${STATUS_COMMAND_TRIGGER_MAX_LENGTH} characters`);
|
||||
}
|
||||
|
||||
if (!isObject(value.historySync)) invalid('historySync must be an object');
|
||||
if (typeof value.historySync.enabled !== 'boolean') {
|
||||
invalid('historySync.enabled must be a boolean');
|
||||
}
|
||||
|
||||
if (value.notifications !== undefined) {
|
||||
if (!isObject(value.notifications) || !Array.isArray(value.notifications.channelIds)) {
|
||||
invalid('notifications.channelIds must be an array');
|
||||
@@ -612,6 +628,7 @@ function toJsonObject(config: OneBotConfig, mode: 'snapshot' | 'overlay'): JsonO
|
||||
cooldownSeconds: config.statusCommand.cooldownSeconds,
|
||||
trigger: config.statusCommand.trigger,
|
||||
},
|
||||
historySync: { enabled: config.historySync.enabled },
|
||||
notifications: { channelIds: config.notifications?.channelIds ?? [] },
|
||||
};
|
||||
}
|
||||
@@ -698,12 +715,28 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
|
||||
const config: OneBotConfig = {
|
||||
networks,
|
||||
statusCommand: parseStatusCommand(sources),
|
||||
historySync: parseHistorySync(sources),
|
||||
notifications: parseNotifications(sources),
|
||||
};
|
||||
assertValidOneBotConfig(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
function parseHistorySync(sources: JsonObject[]): { enabled: boolean } {
|
||||
let enabled = false;
|
||||
for (const source of sources) {
|
||||
if (!Object.prototype.hasOwnProperty.call(source, 'historySync')) continue;
|
||||
const raw = source.historySync;
|
||||
if (!isObject(raw)) invalid('historySync must be an object');
|
||||
rejectUnknownKeys(raw, new Set(['enabled']), 'historySync');
|
||||
if (typeof raw.enabled !== 'boolean') {
|
||||
invalid('historySync.enabled must be a boolean');
|
||||
}
|
||||
enabled = raw.enabled;
|
||||
}
|
||||
return { enabled };
|
||||
}
|
||||
|
||||
/** Last-write-wins merge of `notifications.channelIds` across config sources,
|
||||
* each id validated as a slug + deduped. Mirrors the channel-id rule in
|
||||
* packages/core/src/notifications/config.ts (CHANNEL_ID_RE) — duplicated
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { FriendMessage } from '@snowluma/protocol/events';
|
||||
import {
|
||||
GROUP_MESSAGE_EVENT,
|
||||
privateMessageEventName,
|
||||
} from './message-id';
|
||||
import type { MessageStore } from './message-store';
|
||||
import type { JsonObject } from './types';
|
||||
|
||||
/**
|
||||
* Persist a converted server-history event without dispatching it.
|
||||
*
|
||||
* Private history needs the conversation peer explicitly because `user_id`
|
||||
* names the sender and therefore equals the bot account on outgoing messages.
|
||||
*/
|
||||
export function persistHistoryEvent(
|
||||
store: MessageStore,
|
||||
event: JsonObject,
|
||||
privatePeerId?: number,
|
||||
source?: FriendMessage,
|
||||
): void {
|
||||
const messageId = toHistoryInt(event.message_id);
|
||||
if (!Number.isSafeInteger(messageId) || messageId === 0) {
|
||||
throw new Error(`history event has invalid message_id ${String(event.message_id)}`);
|
||||
}
|
||||
if (event.message_type !== 'group' && event.message_type !== 'private') {
|
||||
throw new Error(`history event has invalid message_type ${String(event.message_type)}`);
|
||||
}
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup
|
||||
? toHistoryInt(event.group_id)
|
||||
: (privatePeerId && privatePeerId > 0 ? privatePeerId : toHistoryInt(event.user_id));
|
||||
const messageSequence = toHistoryInt(event.message_seq);
|
||||
const sequence = source?.ntMsgSeq ?? messageSequence;
|
||||
if (!Number.isSafeInteger(sessionId) || sessionId <= 0) {
|
||||
throw new Error(`history event has invalid session id ${String(sessionId)}`);
|
||||
}
|
||||
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
|
||||
throw new Error(`history event has invalid sequence ${String(sequence)}`);
|
||||
}
|
||||
const sequenceAuthoritative = source?.sequenceAuthoritative !== false && sequence > 0;
|
||||
const isOutgoingPrivate = !isGroup && source?.senderUin === source?.selfUin;
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: source
|
||||
? privateMessageEventName(isOutgoingPrivate, sequenceAuthoritative)
|
||||
: privateMessageEventName(event.post_type === 'message_sent', false);
|
||||
const meta = !isGroup && source
|
||||
? {
|
||||
isGroup: false,
|
||||
targetId: sessionId,
|
||||
sequence,
|
||||
sequenceAuthoritative,
|
||||
eventName,
|
||||
clientSequence: source.clientSeq ?? source.msgSeq,
|
||||
privateDirection: source.senderUin === source.selfUin
|
||||
? 'outgoing'
|
||||
: 'incoming',
|
||||
random: source.msgId,
|
||||
timestamp: source.time,
|
||||
} satisfies Parameters<MessageStore['storeMeta']>[1]
|
||||
: undefined;
|
||||
store.storeHistoryEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
{ sequenceAuthoritative, meta },
|
||||
);
|
||||
}
|
||||
|
||||
export function toHistoryInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const number = Number(value);
|
||||
if (Number.isFinite(number)) return Math.trunc(number);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import {
|
||||
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS,
|
||||
type GroupHistorySyncState,
|
||||
type PrivateHistorySyncState,
|
||||
} from '@snowluma/core/apis';
|
||||
import type { FriendMessage, GroupMessage } from '@snowluma/protocol/events';
|
||||
import { convertEvent, type ConverterContext } from './event-converter';
|
||||
import { persistHistoryEvent, toHistoryInt } from './history-persistence';
|
||||
import type { MessageStore } from './message-store';
|
||||
|
||||
export const LOGIN_HISTORY_SYNC_LIMITS = {
|
||||
startupDelayMs: 30_000,
|
||||
scannedGroups: LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxTargetsPerKind,
|
||||
scannedPrivateUsers: LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxTargetsPerKind,
|
||||
maxGroups: 3,
|
||||
maxPrivateUsers: 3,
|
||||
messagesPerSession: LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession,
|
||||
} as const;
|
||||
|
||||
export interface LoginHistorySyncClock {
|
||||
sleep(ms: number, signal: AbortSignal): Promise<void>;
|
||||
}
|
||||
|
||||
export interface LoginHistorySyncRef {
|
||||
selfId: number;
|
||||
bridge: BridgeInterface;
|
||||
messageStore: MessageStore;
|
||||
converterCtx: ConverterContext;
|
||||
}
|
||||
|
||||
export interface LoginHistorySyncResult {
|
||||
scannedGroups: number;
|
||||
scannedPrivateUsers: number;
|
||||
selectedGroups: number;
|
||||
selectedPrivateUsers: number;
|
||||
fetchedMessages: number;
|
||||
storedMessages: number;
|
||||
failedSessions: number;
|
||||
truncatedGroups: boolean;
|
||||
truncatedPrivateUsers: boolean;
|
||||
}
|
||||
|
||||
interface GroupCandidate {
|
||||
state: GroupHistorySyncState;
|
||||
localSequence: number | null;
|
||||
priority: number;
|
||||
knownGap: boolean;
|
||||
}
|
||||
|
||||
interface PrivateCandidate {
|
||||
state: PrivateHistorySyncState;
|
||||
localSequence: number | null;
|
||||
priority: number;
|
||||
knownGap: boolean;
|
||||
}
|
||||
|
||||
const log = createLogger('OneBot.HistorySync');
|
||||
|
||||
const SYSTEM_CLOCK: LoginHistorySyncClock = {
|
||||
sleep: (ms, signal) => abortableSleep(ms, signal),
|
||||
};
|
||||
|
||||
/**
|
||||
* Process-wide coordinator for automatic login backfill.
|
||||
*
|
||||
* The 30-second grace period happens before entering the global FIFO, so one
|
||||
* account waiting out startup does not block another account that is already
|
||||
* ready. The complete per-account operation is serialized so conversion and
|
||||
* persistence cannot overlap another account's automatic sync.
|
||||
*/
|
||||
export class LoginHistorySyncCoordinator {
|
||||
private tail: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(private readonly clock: LoginHistorySyncClock = SYSTEM_CLOCK) {}
|
||||
|
||||
async schedule(
|
||||
ref: LoginHistorySyncRef,
|
||||
signal: AbortSignal,
|
||||
): Promise<LoginHistorySyncResult> {
|
||||
await this.clock.sleep(LOGIN_HISTORY_SYNC_LIMITS.startupDelayMs, signal);
|
||||
throwIfAborted(signal);
|
||||
|
||||
let operationStarted = false;
|
||||
const operation = this.tail.then(async () => {
|
||||
throwIfAborted(signal);
|
||||
operationStarted = true;
|
||||
return this.runAccount(ref, signal);
|
||||
});
|
||||
this.tail = operation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return rejectWhileQueuedOnAbort(operation, signal, () => operationStarted);
|
||||
}
|
||||
|
||||
private async runAccount(
|
||||
ref: LoginHistorySyncRef,
|
||||
signal: AbortSignal,
|
||||
): Promise<LoginHistorySyncResult> {
|
||||
const groups = ref.bridge.identity.groups
|
||||
.filter(group => Number.isSafeInteger(group.groupId) && group.groupId > 0);
|
||||
const privateUsers = ref.bridge.identity.friends
|
||||
.filter(friend => (
|
||||
Number.isSafeInteger(friend.uin)
|
||||
&& friend.uin > 0
|
||||
&& friend.uin !== ref.selfId
|
||||
&& typeof friend.uid === 'string'
|
||||
&& friend.uid.trim().length > 0
|
||||
));
|
||||
const truncatedGroups = groups.length > LOGIN_HISTORY_SYNC_LIMITS.scannedGroups;
|
||||
const truncatedPrivateUsers = privateUsers.length
|
||||
> LOGIN_HISTORY_SYNC_LIMITS.scannedPrivateUsers;
|
||||
const scannedGroups = groups.slice(0, LOGIN_HISTORY_SYNC_LIMITS.scannedGroups);
|
||||
const scannedPrivateUsers = privateUsers.slice(
|
||||
0,
|
||||
LOGIN_HISTORY_SYNC_LIMITS.scannedPrivateUsers,
|
||||
);
|
||||
|
||||
if (truncatedGroups || truncatedPrivateUsers) {
|
||||
log.warn(
|
||||
'login history sync roster truncated: UIN=%d groups=%d/%d private=%d/%d',
|
||||
ref.selfId,
|
||||
scannedGroups.length,
|
||||
groups.length,
|
||||
scannedPrivateUsers.length,
|
||||
privateUsers.length,
|
||||
);
|
||||
}
|
||||
|
||||
throwIfAborted(signal);
|
||||
const state = await ref.bridge.apis.message.probeHistorySyncState(
|
||||
scannedGroups.map(group => group.groupId),
|
||||
scannedPrivateUsers.map(friend => ({
|
||||
userId: friend.uin,
|
||||
uid: friend.uid,
|
||||
})),
|
||||
signal,
|
||||
);
|
||||
const groupCandidates = selectGroupCandidates(ref.messageStore, state.groups);
|
||||
const privateCandidates = selectPrivateCandidates(
|
||||
ref.messageStore,
|
||||
state.privateUsers,
|
||||
);
|
||||
// URL resolvers may issue additional QQ requests for rkeys or media
|
||||
// download addresses. Automatic backfill must stay inside its one-probe
|
||||
// plus six-page packet budget, so persist only URLs already present in the
|
||||
// history response. Message-id resolution and local media indexing remain
|
||||
// enabled.
|
||||
const mediaSegmentSink = ref.converterCtx.mediaSegmentSink;
|
||||
const persistenceRef: LoginHistorySyncRef = {
|
||||
...ref,
|
||||
converterCtx: {
|
||||
...ref.converterCtx,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
mediaSegmentSink: mediaSegmentSink
|
||||
? (mediaType, element, data, isGroup, sessionId) => {
|
||||
throwIfAborted(signal);
|
||||
mediaSegmentSink(mediaType, element, data, isGroup, sessionId);
|
||||
}
|
||||
: null,
|
||||
},
|
||||
};
|
||||
|
||||
const result: LoginHistorySyncResult = {
|
||||
scannedGroups: scannedGroups.length,
|
||||
scannedPrivateUsers: scannedPrivateUsers.length,
|
||||
selectedGroups: groupCandidates.length,
|
||||
selectedPrivateUsers: privateCandidates.length,
|
||||
fetchedMessages: 0,
|
||||
storedMessages: 0,
|
||||
failedSessions: 0,
|
||||
truncatedGroups,
|
||||
truncatedPrivateUsers,
|
||||
};
|
||||
log.info(
|
||||
'login history sync selected: UIN=%d scanned=%d/%d selected=%d/%d',
|
||||
ref.selfId,
|
||||
result.scannedGroups,
|
||||
result.scannedPrivateUsers,
|
||||
result.selectedGroups,
|
||||
result.selectedPrivateUsers,
|
||||
);
|
||||
|
||||
for (const candidate of groupCandidates) {
|
||||
throwIfAborted(signal);
|
||||
try {
|
||||
const messages = await fetchGroupCandidate(persistenceRef, candidate, signal);
|
||||
throwIfAborted(signal);
|
||||
result.fetchedMessages += messages.length;
|
||||
for (const message of messages) {
|
||||
throwIfAborted(signal);
|
||||
await persistGroupMessage(persistenceRef, message, signal);
|
||||
result.storedMessages += 1;
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal.aborted) throwIfAborted(signal);
|
||||
result.failedSessions += 1;
|
||||
log.warn(
|
||||
'login history sync group failed: UIN=%d group=%d error=%s',
|
||||
ref.selfId,
|
||||
candidate.state.groupId,
|
||||
errorText(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (const candidate of privateCandidates) {
|
||||
throwIfAborted(signal);
|
||||
try {
|
||||
const messages = await fetchPrivateCandidate(persistenceRef, candidate, signal);
|
||||
throwIfAborted(signal);
|
||||
result.fetchedMessages += messages.length;
|
||||
for (const message of messages) {
|
||||
throwIfAborted(signal);
|
||||
if (await persistPrivateMessage(
|
||||
persistenceRef,
|
||||
candidate.state.userId,
|
||||
message,
|
||||
signal,
|
||||
)) {
|
||||
result.storedMessages += 1;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal.aborted) throwIfAborted(signal);
|
||||
result.failedSessions += 1;
|
||||
log.warn(
|
||||
'login history sync private failed: UIN=%d peer=%d error=%s',
|
||||
ref.selfId,
|
||||
candidate.state.userId,
|
||||
errorText(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
log.info(
|
||||
'login history sync complete: UIN=%d fetched=%d stored=%d failed=%d',
|
||||
ref.selfId,
|
||||
result.fetchedMessages,
|
||||
result.storedMessages,
|
||||
result.failedSessions,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export const loginHistorySyncCoordinator = new LoginHistorySyncCoordinator();
|
||||
|
||||
function selectGroupCandidates(
|
||||
store: MessageStore,
|
||||
states: readonly GroupHistorySyncState[],
|
||||
): GroupCandidate[] {
|
||||
return states
|
||||
.flatMap((state): GroupCandidate[] => {
|
||||
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) return [];
|
||||
const observedSequence = store.findLatestAuthoritativeSequence(true, state.groupId);
|
||||
const localSequence = store.findLatestPersistedAuthoritativeSequence(
|
||||
true,
|
||||
state.groupId,
|
||||
);
|
||||
if (localSequence !== null) {
|
||||
if (state.latestSeq <= localSequence) return [];
|
||||
return [{
|
||||
state,
|
||||
localSequence,
|
||||
priority: state.latestSeq - localSequence,
|
||||
knownGap: true,
|
||||
}];
|
||||
}
|
||||
if (observedSequence !== null) {
|
||||
return [{
|
||||
state,
|
||||
localSequence: null,
|
||||
priority: state.latestSeq,
|
||||
knownGap: true,
|
||||
}];
|
||||
}
|
||||
if (state.latestSeq <= state.readSeq) return [];
|
||||
return [{
|
||||
state,
|
||||
localSequence: null,
|
||||
priority: state.latestSeq - state.readSeq,
|
||||
knownGap: false,
|
||||
}];
|
||||
})
|
||||
.sort(compareCandidates)
|
||||
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxGroups);
|
||||
}
|
||||
|
||||
function selectPrivateCandidates(
|
||||
store: MessageStore,
|
||||
states: readonly PrivateHistorySyncState[],
|
||||
): PrivateCandidate[] {
|
||||
return states
|
||||
.flatMap((state): PrivateCandidate[] => {
|
||||
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) return [];
|
||||
const observedSequence = store.findLatestAuthoritativeSequence(false, state.userId);
|
||||
const localSequence = store.findLatestPersistedAuthoritativeSequence(
|
||||
false,
|
||||
state.userId,
|
||||
);
|
||||
if (localSequence !== null) {
|
||||
if (state.latestSeq <= localSequence) return [];
|
||||
return [{
|
||||
state,
|
||||
localSequence,
|
||||
priority: state.latestSeq - localSequence,
|
||||
knownGap: true,
|
||||
}];
|
||||
}
|
||||
if (!Number.isSafeInteger(state.lastMsgTime) || state.lastMsgTime <= 0) return [];
|
||||
return [{
|
||||
state,
|
||||
localSequence: null,
|
||||
priority: state.lastMsgTime,
|
||||
knownGap: observedSequence !== null,
|
||||
}];
|
||||
})
|
||||
.sort(compareCandidates)
|
||||
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxPrivateUsers);
|
||||
}
|
||||
|
||||
function compareCandidates<T extends {
|
||||
localSequence: number | null;
|
||||
priority: number;
|
||||
knownGap: boolean;
|
||||
}>(
|
||||
left: T,
|
||||
right: T,
|
||||
): number {
|
||||
if (left.knownGap !== right.knownGap) return left.knownGap ? -1 : 1;
|
||||
if ((left.localSequence !== null) !== (right.localSequence !== null)) {
|
||||
return left.localSequence !== null ? -1 : 1;
|
||||
}
|
||||
return right.priority - left.priority;
|
||||
}
|
||||
|
||||
function fetchGroupCandidate(
|
||||
ref: LoginHistorySyncRef,
|
||||
candidate: GroupCandidate,
|
||||
signal: AbortSignal,
|
||||
): Promise<GroupMessage[]> {
|
||||
const endSeq = candidate.localSequence === null
|
||||
? candidate.state.latestSeq
|
||||
: Math.min(
|
||||
candidate.state.latestSeq,
|
||||
candidate.localSequence + LOGIN_HISTORY_SYNC_LIMITS.messagesPerSession,
|
||||
);
|
||||
const startSeq = candidate.localSequence === null
|
||||
? Math.max(1, endSeq - LOGIN_HISTORY_SYNC_LIMITS.messagesPerSession + 1)
|
||||
: candidate.localSequence + 1;
|
||||
return ref.bridge.apis.message.getGroupHistorySyncPage(
|
||||
candidate.state.groupId,
|
||||
startSeq,
|
||||
endSeq,
|
||||
ref.selfId,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
|
||||
function fetchPrivateCandidate(
|
||||
ref: LoginHistorySyncRef,
|
||||
candidate: PrivateCandidate,
|
||||
signal: AbortSignal,
|
||||
): Promise<FriendMessage[]> {
|
||||
if (candidate.localSequence !== null) {
|
||||
const endSeq = Math.min(
|
||||
candidate.state.latestSeq,
|
||||
candidate.localSequence + LOGIN_HISTORY_SYNC_LIMITS.messagesPerSession,
|
||||
);
|
||||
return ref.bridge.apis.message.getC2cHistorySyncPage(
|
||||
candidate.state.uid,
|
||||
candidate.localSequence + 1,
|
||||
endSeq,
|
||||
ref.selfId,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
const beforeTime = Math.min(0xffff_ffff, candidate.state.lastMsgTime + 1);
|
||||
return ref.bridge.apis.message.getC2cLatestHistorySyncPage(
|
||||
candidate.state.uid,
|
||||
LOGIN_HISTORY_SYNC_LIMITS.messagesPerSession,
|
||||
ref.selfId,
|
||||
beforeTime,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
|
||||
async function persistGroupMessage(
|
||||
ref: LoginHistorySyncRef,
|
||||
message: GroupMessage,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
throwIfAborted(signal);
|
||||
const converted = await convertEvent(ref.converterCtx, message);
|
||||
throwIfAborted(signal);
|
||||
if (!converted || converted.message_type !== 'group') {
|
||||
throw new Error(
|
||||
`group history conversion failed: group=${message.groupId} seq=${message.msgSeq} `
|
||||
+ `messageType=${String(converted?.message_type)}`,
|
||||
);
|
||||
}
|
||||
persistHistoryEvent(ref.messageStore, converted);
|
||||
}
|
||||
|
||||
async function persistPrivateMessage(
|
||||
ref: LoginHistorySyncRef,
|
||||
peerUin: number,
|
||||
message: FriendMessage,
|
||||
signal: AbortSignal,
|
||||
): Promise<boolean> {
|
||||
throwIfAborted(signal);
|
||||
const receivedPeer = message.peerUin ?? 0;
|
||||
if (receivedPeer > 0 && receivedPeer !== peerUin) {
|
||||
throw new Error(
|
||||
`private history peer mismatch: requested=${peerUin} received=${receivedPeer} `
|
||||
+ `seq=${String(message.ntMsgSeq ?? message.msgSeq)}`,
|
||||
);
|
||||
}
|
||||
if (receivedPeer <= 0) message.peerUin = peerUin;
|
||||
const clientSequence = message.clientSeq ?? message.msgSeq;
|
||||
const sentBySelf = message.senderUin === ref.selfId;
|
||||
const converted = await convertEvent(ref.converterCtx, message);
|
||||
throwIfAborted(signal);
|
||||
if (!converted || converted.message_type !== 'private') {
|
||||
throw new Error(
|
||||
`private history conversion failed: peer=${peerUin} `
|
||||
+ `seq=${String(message.ntMsgSeq ?? message.msgSeq)} `
|
||||
+ `messageType=${String(converted?.message_type)}`,
|
||||
);
|
||||
}
|
||||
if (ref.messageStore.isPrivateMessageRecalled(
|
||||
peerUin,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
message.time,
|
||||
)) {
|
||||
log.debug(
|
||||
'login history sync omitted recalled private message: UIN=%d peer=%d clientSeq=%d self=%s',
|
||||
ref.selfId,
|
||||
peerUin,
|
||||
clientSequence,
|
||||
String(sentBySelf),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (converted.post_type === 'message_sent' && toHistoryInt(converted.target_id) === 0) {
|
||||
converted.target_id = peerUin;
|
||||
}
|
||||
persistHistoryEvent(ref.messageStore, converted, peerUin, message);
|
||||
return true;
|
||||
}
|
||||
|
||||
function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
|
||||
throwIfAborted(signal);
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
timer.unref?.();
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(signal.reason ?? new Error('login history sync aborted'));
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function throwIfAborted(signal: AbortSignal): void {
|
||||
if (signal.aborted) {
|
||||
throw signal.reason ?? new Error('login history sync aborted');
|
||||
}
|
||||
}
|
||||
|
||||
function rejectWhileQueuedOnAbort<T>(
|
||||
result: Promise<T>,
|
||||
signal: AbortSignal,
|
||||
hasStarted: () => boolean,
|
||||
): Promise<T> {
|
||||
if (signal.aborted && !hasStarted()) {
|
||||
return Promise.reject(signal.reason ?? new Error('login history sync aborted'));
|
||||
}
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
if (!hasStarted()) {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
reject(signal.reason ?? new Error('login history sync aborted'));
|
||||
}
|
||||
};
|
||||
signal.addEventListener('abort', onAbort);
|
||||
result.then(resolve, reject).finally(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function errorText(error: unknown): string {
|
||||
return error instanceof Error ? (error.stack ?? error.message) : String(error);
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { MessageStore } from './message-store';
|
||||
import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions';
|
||||
import { buildStatusText, matchesStatusCommand, statusCooldownElapsed } from './modules/status-command';
|
||||
import { loginHistorySyncCoordinator } from './history-sync';
|
||||
import {
|
||||
HttpPostAdapter,
|
||||
HttpServerAdapter,
|
||||
@@ -70,6 +71,10 @@ export class OneBotInstance {
|
||||
private disposeRequested = false;
|
||||
private acceptingActions = true;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
private readonly historySyncAbortController = new AbortController();
|
||||
private readonly historySyncEnabledAtStartup: boolean;
|
||||
private historySyncStartRequested = false;
|
||||
private historySyncTask: Promise<void> | null = null;
|
||||
private readonly storeCloseState = {
|
||||
message: false,
|
||||
media: false,
|
||||
@@ -116,6 +121,7 @@ export class OneBotInstance {
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig, globalSettings: GlobalSettings) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
this.historySyncEnabledAtStartup = config.historySync.enabled;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
@@ -187,6 +193,40 @@ export class OneBotInstance {
|
||||
return this.networkReady;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the optional login-time backfill once roster warmup has completed.
|
||||
* The startup snapshot is intentional: hot config edits take effect on the
|
||||
* next account lifecycle and never cause an unexpected QQ request.
|
||||
*/
|
||||
startLoginHistorySync(): void {
|
||||
if (this.historySyncStartRequested || this.disposeRequested) return;
|
||||
this.historySyncStartRequested = true;
|
||||
if (!this.historySyncEnabledAtStartup) {
|
||||
this.log.debug('login history sync disabled for this account lifecycle');
|
||||
return;
|
||||
}
|
||||
|
||||
this.historySyncTask = loginHistorySyncCoordinator.schedule({
|
||||
selfId: Number.parseInt(this.uin, 10) || 0,
|
||||
bridge: this.bridge,
|
||||
messageStore: this.messageStore,
|
||||
converterCtx: this.converterCtx,
|
||||
}, this.historySyncAbortController.signal).then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
if (this.historySyncAbortController.signal.aborted) {
|
||||
this.log.debug('login history sync cancelled: %s',
|
||||
error instanceof Error ? error.message : String(error));
|
||||
return;
|
||||
}
|
||||
this.log.error(
|
||||
'login history sync failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): Promise<NetworkReconcileResult> {
|
||||
if (this.disposeRequested) return Promise.reject(new Error(`OneBot instance UIN=${this.uin} is disposing`));
|
||||
const snapshot = structuredClone(config);
|
||||
@@ -220,6 +260,9 @@ export class OneBotInstance {
|
||||
this.apiHandler.quiesce();
|
||||
this.online = false;
|
||||
this.stopHeartbeat();
|
||||
this.historySyncAbortController?.abort(
|
||||
new Error(`OneBot instance UIN=${this.uin} is disposing`),
|
||||
);
|
||||
const pipeline = this.eventPipeline;
|
||||
if (pipeline) {
|
||||
pipeline.stop();
|
||||
@@ -235,6 +278,7 @@ export class OneBotInstance {
|
||||
await Promise.all([
|
||||
Promise.all(this.inFlightActions),
|
||||
this.eventPipelineDrain,
|
||||
this.historySyncTask ?? Promise.resolve(),
|
||||
]);
|
||||
const shutdown = await this.networkManager.shutdown();
|
||||
if (!shutdown.closed) {
|
||||
|
||||
@@ -194,9 +194,28 @@ export class OneBotManager {
|
||||
if (result.applied) log.info('network startup applied: UIN=%s adapters=%d', uin, result.statuses.length);
|
||||
else log.warn('network startup degraded: UIN=%s failures=%d', uin, result.errors.length);
|
||||
}));
|
||||
warmUpBridgeState(uin, bridge).catch((err) => {
|
||||
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
void warmUpBridgeState(uin, bridge).then(
|
||||
(warmup) => {
|
||||
if (warmup.friendsLoaded && warmup.groupsLoaded) {
|
||||
instance.startLoginHistorySync();
|
||||
return;
|
||||
}
|
||||
log.warn(
|
||||
'login history sync skipped because roster warmup was incomplete: '
|
||||
+ 'UIN=%s friendsLoaded=%s groupsLoaded=%s',
|
||||
uin,
|
||||
String(warmup.friendsLoaded),
|
||||
String(warmup.groupsLoaded),
|
||||
);
|
||||
},
|
||||
(err) => {
|
||||
log.warn(
|
||||
'warmup error for UIN %s: %s',
|
||||
uin,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private onSessionClosed(uin: string): void {
|
||||
@@ -279,9 +298,18 @@ export class OneBotManager {
|
||||
|
||||
}
|
||||
|
||||
async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<void> {
|
||||
interface BridgeWarmupResult {
|
||||
friendsLoaded: boolean;
|
||||
groupsLoaded: boolean;
|
||||
}
|
||||
|
||||
async function warmUpBridgeState(
|
||||
uin: string,
|
||||
bridge: BridgeInterface,
|
||||
): Promise<BridgeWarmupResult> {
|
||||
const selfUin = parseInt(uin, 10) || 0;
|
||||
let selfResolved = false;
|
||||
let friendsLoaded = false;
|
||||
|
||||
// Step 1: Fetch friend list + derive self profile when QQ happens to
|
||||
// include self in the response. Some accounts / versions omit self,
|
||||
@@ -289,6 +317,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<
|
||||
// explicit fallback.
|
||||
try {
|
||||
const friends = await bridge.apis.contacts.fetchFriendList();
|
||||
friendsLoaded = true;
|
||||
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
||||
|
||||
for (const f of friends) {
|
||||
@@ -327,8 +356,10 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<
|
||||
|
||||
// Step 2: Fetch group list
|
||||
let groups: { groupId: number }[] = [];
|
||||
let groupsLoaded = false;
|
||||
try {
|
||||
groups = await bridge.apis.contacts.fetchGroupList();
|
||||
groupsLoaded = true;
|
||||
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
|
||||
} catch (e) {
|
||||
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
@@ -360,4 +391,5 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<
|
||||
loadedMemberCount,
|
||||
failedGroupCount,
|
||||
);
|
||||
return { friendsLoaded, groupsLoaded };
|
||||
}
|
||||
@@ -15,6 +15,14 @@ export interface StoreEventOptions {
|
||||
sequenceAuthoritative?: boolean;
|
||||
}
|
||||
|
||||
export interface StoreHistoryEventOptions extends StoreEventOptions {
|
||||
/**
|
||||
* Private history metadata that must become visible atomically with the
|
||||
* event body. Group history does not require a separate metadata write.
|
||||
*/
|
||||
meta?: MessageMeta;
|
||||
}
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtStoreEvent: StatementSync;
|
||||
@@ -27,6 +35,7 @@ export class MessageStore {
|
||||
private readonly stmtListEventsAnchoredForward: StatementSync;
|
||||
private readonly stmtListEventsLatest: StatementSync;
|
||||
private readonly stmtFindLatestAuthoritativeSequence: StatementSync;
|
||||
private readonly stmtFindLatestPersistedAuthoritativeSequence: StatementSync;
|
||||
private readonly stmtListIncomingC2CSessions: StatementSync;
|
||||
private readonly stmtFindPrivateRecall: StatementSync;
|
||||
private readonly stmtFindPrivateRecallTombstone: StatementSync;
|
||||
@@ -139,6 +148,15 @@ export class MessageStore {
|
||||
LIMIT 1`,
|
||||
);
|
||||
|
||||
this.stmtFindLatestPersistedAuthoritativeSequence = this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
|
||||
AND sequence_authoritative = 1 AND sequence > 0
|
||||
ORDER BY sequence DESC
|
||||
LIMIT 1`,
|
||||
);
|
||||
|
||||
this.stmtListIncomingC2CSessions = this.db.prepare(
|
||||
`SELECT session_id
|
||||
FROM messages
|
||||
@@ -269,6 +287,55 @@ export class MessageStore {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store one fetched history event.
|
||||
*
|
||||
* Private history needs both metadata and the event body. Keep those writes
|
||||
* in one transaction so a failed body write can never leave an authoritative
|
||||
* sequence that makes a later login skip the missing message.
|
||||
*/
|
||||
storeHistoryEvent(
|
||||
messageId: number,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
eventName: string,
|
||||
event: JsonObject,
|
||||
options: StoreHistoryEventOptions = {},
|
||||
): void {
|
||||
const { meta, ...eventOptions } = options;
|
||||
if (!meta) {
|
||||
this.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
eventOptions,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
this.storeMeta(messageId, meta);
|
||||
this.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
eventOptions,
|
||||
);
|
||||
this.db.exec('COMMIT');
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
findEvent(messageId: number): JsonObject | null {
|
||||
if (!isValidMessageId(messageId)) return null;
|
||||
const row = this.stmtFindEvent.get(messageId) as { data: string } | undefined;
|
||||
@@ -415,6 +482,24 @@ export class MessageStore {
|
||||
return row.sequence;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the latest server-confirmed sequence whose OneBot event body is
|
||||
* actually present. Automatic history backfill must use this cursor so a
|
||||
* metadata-only live row cannot hide a missing event body.
|
||||
*/
|
||||
findLatestPersistedAuthoritativeSequence(
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): number | null {
|
||||
if (!Number.isInteger(sessionId) || sessionId <= 0) return null;
|
||||
const row = this.stmtFindLatestPersistedAuthoritativeSequence.get(
|
||||
isGroup ? 1 : 0,
|
||||
sessionId,
|
||||
) as { sequence: number } | undefined;
|
||||
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null;
|
||||
return row.sequence;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a private recall's sender-local client sequence to the OneBot
|
||||
* message id and remove the cached row. The protocol recall notice does not
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/v
|
||||
import type { MessageSendResult } from '../api-handler';
|
||||
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import { persistHistoryEvent, toHistoryInt } from '../history-persistence';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import {
|
||||
GROUP_MESSAGE_EVENT,
|
||||
@@ -257,7 +258,7 @@ export async function getFriendHistory(
|
||||
? ref.messageStore.findEvent(messageId as number)
|
||||
: null;
|
||||
const belongsToPeer = meta?.targetId === userId
|
||||
|| (meta?.targetId === ref.selfId && toHistInt(storedEvent?.target_id) === userId);
|
||||
|| (meta?.targetId === ref.selfId && toHistoryInt(storedEvent?.target_id) === userId);
|
||||
if (!hasAuthoritativeSequence(meta) || meta.isGroup || !belongsToPeer) {
|
||||
return getFriendMsgHistory(ref.messageStore, userId, messageId, count, reverseOrder);
|
||||
}
|
||||
@@ -311,7 +312,7 @@ export async function getFriendHistory(
|
||||
}
|
||||
// Private history is scoped by the requested peer, while user_id is
|
||||
// the sender and therefore equals selfId for outgoing messages.
|
||||
if (json.post_type === 'message_sent' && toHistInt(json.target_id) === 0) {
|
||||
if (json.post_type === 'message_sent' && toHistoryInt(json.target_id) === 0) {
|
||||
json.target_id = userId;
|
||||
}
|
||||
persistHistoryEvent(ref.messageStore, json, userId, ev);
|
||||
@@ -540,66 +541,6 @@ function buildBackfillEvent(
|
||||
return privateEvent;
|
||||
}
|
||||
|
||||
// Persist a converted history event so reply / get_msg / future listing resolve
|
||||
// it. Private history callers provide the conversation peer because `user_id`
|
||||
// identifies the sender and equals the bot account on outgoing messages.
|
||||
function persistHistoryEvent(
|
||||
store: MessageStore,
|
||||
event: JsonObject,
|
||||
privatePeerId?: number,
|
||||
source?: FriendMessage,
|
||||
): void {
|
||||
const messageId = toHistInt(event.message_id);
|
||||
if (messageId === 0) return;
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup
|
||||
? toHistInt(event.group_id)
|
||||
: (privatePeerId && privatePeerId > 0 ? privatePeerId : toHistInt(event.user_id));
|
||||
const messageSequence = toHistInt(event.message_seq);
|
||||
const sequence = source?.ntMsgSeq ?? messageSequence;
|
||||
const sequenceAuthoritative = source?.sequenceAuthoritative !== false && sequence > 0;
|
||||
const isOutgoingPrivate = !isGroup && source?.senderUin === source?.selfUin;
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: source
|
||||
? privateMessageEventName(isOutgoingPrivate, sequenceAuthoritative)
|
||||
: privateMessageEventName(event.post_type === 'message_sent', false);
|
||||
if (sessionId === 0) return;
|
||||
if (!isGroup && source) {
|
||||
store.storeMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: sessionId,
|
||||
sequence,
|
||||
sequenceAuthoritative,
|
||||
eventName,
|
||||
clientSequence: source.clientSeq ?? source.msgSeq,
|
||||
privateDirection: source.senderUin === source.selfUin
|
||||
? 'outgoing'
|
||||
: 'incoming',
|
||||
random: source.msgId,
|
||||
timestamp: source.time,
|
||||
});
|
||||
}
|
||||
store.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
}
|
||||
|
||||
function toHistInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) return Math.trunc(n);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise<void> {
|
||||
if (!hasAuthoritativeSequence(meta)) {
|
||||
throw new Error('message has no authoritative QQ sequence and cannot be recalled');
|
||||
|
||||
@@ -109,11 +109,19 @@ export interface RKeyConfig {
|
||||
fallbackServers: string[];
|
||||
}
|
||||
|
||||
/** Conservative, login-scoped cloud history backfill. */
|
||||
export interface HistorySyncConfig {
|
||||
/** Disabled by default. Changes take effect on the next account lifecycle. */
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** Per-UIN OneBot configuration. */
|
||||
export interface OneBotConfig {
|
||||
networks: OneBotNetworks;
|
||||
/** Built-in `#sl` status command settings. Always present after normalization. */
|
||||
statusCommand: StatusCommandConfig;
|
||||
/** Silent login-time history backfill. Always present after normalization. */
|
||||
historySync: HistorySyncConfig;
|
||||
/** Which GLOBAL notification channels this account opts into (channel ids are
|
||||
* validated slugs; channels themselves live in config/notifications.json).
|
||||
* Always present after normalization. */
|
||||
|
||||
Reference in new issue
Block a user