diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index ef3893ed..536679ce 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -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, 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 diff --git a/packages/onebot/src/history-persistence.ts b/packages/onebot/src/history-persistence.ts new file mode 100644 index 00000000..c858b842 --- /dev/null +++ b/packages/onebot/src/history-persistence.ts @@ -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[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; +} diff --git a/packages/onebot/src/history-sync.ts b/packages/onebot/src/history-sync.ts new file mode 100644 index 00000000..16bb7355 --- /dev/null +++ b/packages/onebot/src/history-sync.ts @@ -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; +} + +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 = Promise.resolve(); + + constructor(private readonly clock: LoginHistorySyncClock = SYSTEM_CLOCK) {} + + async schedule( + ref: LoginHistorySyncRef, + signal: AbortSignal, + ): Promise { + 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 { + 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( + 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 { + 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 { + 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 { + 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 { + 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 { + throwIfAborted(signal); + return new Promise((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( + result: Promise, + signal: AbortSignal, + hasStarted: () => boolean, +): Promise { + if (signal.aborted && !hasStarted()) { + return Promise.reject(signal.reason ?? new Error('login history sync aborted')); + } + + return new Promise((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); +} diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 4baf731c..6b733bbc 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -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>(); + private readonly historySyncAbortController = new AbortController(); + private readonly historySyncEnabledAtStartup: boolean; + private historySyncStartRequested = false; + private historySyncTask: Promise | 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 { 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) { diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index 33bdeafc..878e0f7e 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -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 { +interface BridgeWarmupResult { + friendsLoaded: boolean; + groupsLoaded: boolean; +} + +async function warmUpBridgeState( + uin: string, + bridge: BridgeInterface, +): Promise { 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 }; } diff --git a/packages/onebot/src/message-store.ts b/packages/onebot/src/message-store.ts index 10601be8..2ef0afeb 100644 --- a/packages/onebot/src/message-store.ts +++ b/packages/onebot/src/message-store.ts @@ -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 diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 58cd6261..afce542d 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -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 { if (!hasAuthoritativeSequence(meta)) { throw new Error('message has no authoritative QQ sequence and cannot be recalled'); diff --git a/packages/onebot/src/types.ts b/packages/onebot/src/types.ts index 87ee68ab..fb2d820a 100644 --- a/packages/onebot/src/types.ts +++ b/packages/onebot/src/types.ts @@ -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. */ diff --git a/packages/onebot/tests/config.test.ts b/packages/onebot/tests/config.test.ts index c0cfdf94..2142ad4e 100644 --- a/packages/onebot/tests/config.test.ts +++ b/packages/onebot/tests/config.test.ts @@ -6,6 +6,7 @@ import { assertValidOneBotConfig, loadOneBotConfig, makeDefaultOneBotConfig, + prepareOneBotConfigForRestore, saveOneBotConfig, STATUS_COMMAND_TRIGGER_MAX_LENGTH, } from '../src/config'; @@ -31,6 +32,7 @@ describe('makeDefaultOneBotConfig', () => { expect(config.networks.wsServers[0].reportSelfMessage).toBe(false); expect(config.networks.wsClients).toEqual([]); expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5, trigger: '#sl' }); + expect(config.historySync).toEqual({ enabled: false }); expect(config.notifications).toEqual({ channelIds: [] }); }); }); @@ -573,3 +575,64 @@ describe('OneBotConfig.notifications (per-UIN channel opt-in)', () => { expect(onDisk.notifications).toEqual({ channelIds: ['discord', 'serverchan'] }); }); }); + +describe('OneBotConfig login history sync', () => { + let tempDir: string; + let prevCwd: string; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-history-sync-')); + prevCwd = process.cwd(); + process.chdir(tempDir); + }); + + afterEach(() => { + process.chdir(prevCwd); + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it('defaults old configurations to disabled', () => { + const config = loadOneBotConfig('30001'); + expect(config.historySync).toEqual({ enabled: false }); + }); + + it('round-trips the per-account opt-in', () => { + const config = makeDefaultOneBotConfig(); + config.historySync.enabled = true; + saveOneBotConfig('30002', config); + + expect(loadOneBotConfig('30002').historySync).toEqual({ enabled: true }); + const onDisk = JSON.parse( + fs.readFileSync(path.join(tempDir, 'config', 'onebot_30002.json'), 'utf8'), + ); + expect(onDisk.historySync).toEqual({ enabled: true }); + }); + + it('rejects malformed history sync settings during save and restore', () => { + const malformed = makeDefaultOneBotConfig() as unknown as Record; + malformed.historySync = { enabled: 'yes' }; + expect(() => assertValidOneBotConfig(malformed)).toThrow(/historySync\.enabled/); + + const source = { + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + historySync: { enabled: true, interval: 1 }, + }; + expect(() => prepareOneBotConfigForRestore(source, 'per-uin')) + .toThrow(/\$\.historySync\.interval is not supported/); + }); + + it('rejects malformed on-disk settings instead of inheriting an enabled value', () => { + const dir = path.join(tempDir, 'config'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'onebot.json'), JSON.stringify({ + historySync: { enabled: true }, + }), 'utf8'); + fs.writeFileSync(path.join(dir, 'onebot_30003.json'), JSON.stringify({ + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + historySync: { enabled: 'yes' }, + }), 'utf8'); + + expect(() => loadOneBotConfig('30003')) + .toThrow(/historySync\.enabled must be a boolean/); + }); +}); diff --git a/packages/onebot/tests/history-sync.test.ts b/packages/onebot/tests/history-sync.test.ts new file mode 100644 index 00000000..47c478b8 --- /dev/null +++ b/packages/onebot/tests/history-sync.test.ts @@ -0,0 +1,831 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { + FriendMessage, + GroupMessage, + MessageElement, +} from '@snowluma/protocol/events'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { ConverterContext } from '../src/event-converter'; +import { + LOGIN_HISTORY_SYNC_LIMITS, + LoginHistorySyncCoordinator, +} from '../src/history-sync'; +import { hashMessageIdInt32 } from '../src/message-id'; +import { MessageStore } from '../src/message-store'; +import { + getFriendMsgHistory, + getGroupMsgHistory, +} from '../src/modules/message-actions'; + +const SELF_ID = 10001; + +function groupMessage( + groupId: number, + sequence: number, + elements: MessageElement[] = [{ type: 'text', text: `group-${sequence}` }], +): GroupMessage { + return { + kind: 'group_message', + groupId, + groupName: `group-${groupId}`, + senderUin: 20001, + senderNick: 'friend', + senderCard: '', + senderRole: 'member', + selfUin: SELF_ID, + time: 1_700_000_000 + sequence, + msgSeq: sequence, + msgId: sequence + 10_000, + elements, + }; +} + +function friendMessage( + peerUin: number, + sequence: number, + sentBySelf = false, +): FriendMessage { + return { + kind: 'friend_message', + senderUin: sentBySelf ? SELF_ID : peerUin, + peerUin, + senderUid: sentBySelf ? 'u_self' : `u_${peerUin}`, + senderNick: sentBySelf ? 'self' : 'friend', + selfUin: SELF_ID, + time: 1_700_000_000 + sequence, + msgSeq: sequence + 1_000, + ntMsgSeq: sequence, + clientSeq: sequence + 1_000, + sequenceAuthoritative: true, + msgId: sequence + 20_000, + elements: [{ type: 'text', text: `private-${sequence}` }], + }; +} + +function converterContext(): ConverterContext { + return { + selfId: SELF_ID, + imageUrlResolver: null, + mediaUrlResolver: null, + messageIdResolver: (isGroup, sessionId, sequence, eventName) => + hashMessageIdInt32(sequence, sessionId, eventName), + mediaSegmentSink: null, + }; +} + +function makeStore(): { store: MessageStore; close(): void } { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-history-sync-')); + const store = new MessageStore(path.join(dir, 'messages.db')); + return { + store, + close: () => { + store.close(); + fs.rmSync(dir, { recursive: true, force: true }); + }, + }; +} + +function makeBridge(options: { + groupCount?: number; + friendCount?: number; + probe?: ReturnType; + groupPage?: ReturnType; + privatePage?: ReturnType; + privateLatestPage?: ReturnType; +} = {}): BridgeInterface { + const groupCount = options.groupCount ?? 1; + const friendCount = options.friendCount ?? 1; + return { + identity: { + groups: Array.from({ length: groupCount }, (_, index) => ({ + groupId: 30001 + index, + })), + friends: Array.from({ length: friendCount }, (_, index) => ({ + uin: 40001 + index, + uid: `u_${40001 + index}`, + })), + }, + apis: { + message: { + probeHistorySyncState: options.probe ?? vi.fn(async () => ({ + groups: [{ groupId: 30001, readSeq: 0, latestSeq: 20 }], + privateUsers: [{ + userId: 40001, + uid: 'u_40001', + readSeq: 0, + latestSeq: 20, + lastMsgTime: 1_700_000_000, + }], + })), + getGroupHistorySyncPage: options.groupPage ?? vi.fn(async () => [ + groupMessage(30001, 1), + ]), + getC2cHistorySyncPage: options.privatePage ?? vi.fn(async () => []), + getC2cLatestHistorySyncPage: options.privateLatestPage ?? vi.fn(async () => [ + friendMessage(40001, 1), + ]), + }, + }, + } as unknown as BridgeInterface; +} + +const resources: Array> = []; +afterEach(() => { + for (const resource of resources.splice(0)) resource.close(); + vi.restoreAllMocks(); +}); + +describe('login history sync', () => { + it('waits for the fixed grace period and silently backfills queryable history', async () => { + const delays: number[] = []; + const coordinator = new LoginHistorySyncCoordinator({ + sleep: async (ms) => { delays.push(ms); }, + }); + const resource = makeStore(); + resources.push(resource); + const bridge = makeBridge(); + + const result = await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(delays).toEqual([LOGIN_HISTORY_SYNC_LIMITS.startupDelayMs]); + expect(result).toMatchObject({ + selectedGroups: 1, + selectedPrivateUsers: 1, + fetchedMessages: 2, + storedMessages: 2, + failedSessions: 0, + }); + await expect(getGroupMsgHistory(resource.store, 30001, undefined, 20)) + .resolves.toHaveLength(1); + await expect(getFriendMsgHistory(resource.store, 40001, undefined, 20)) + .resolves.toHaveLength(1); + }); + + it('limits one login to three groups, three friends and one page per session', async () => { + const groupPage = vi.fn(async ( + groupId: number, + startSeq: number, + ) => [groupMessage(groupId, startSeq)]); + const privateLatestPage = vi.fn(async ( + _uid: string, + _count: number, + _selfId: number, + _beforeTime: number, + ) => []); + const probe = vi.fn(async () => ({ + groups: Array.from({ length: 4 }, (_, index) => ({ + groupId: 30001 + index, + readSeq: 0, + latestSeq: 100 - index, + })), + privateUsers: Array.from({ length: 4 }, (_, index) => ({ + userId: 40001 + index, + uid: `u_${40001 + index}`, + readSeq: 0, + latestSeq: 100 - index, + lastMsgTime: 1_700_000_000 - index, + })), + })); + const bridge = makeBridge({ + groupCount: 4, + friendCount: 4, + probe, + groupPage, + privateLatestPage, + }); + const resource = makeStore(); + resources.push(resource); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(probe).toHaveBeenCalledOnce(); + expect(groupPage).toHaveBeenCalledTimes(3); + expect(privateLatestPage).toHaveBeenCalledTimes(3); + for (const call of groupPage.mock.calls) { + expect(call[2] - call[1] + 1).toBeLessThanOrEqual( + LOGIN_HISTORY_SYNC_LIMITS.messagesPerSession, + ); + } + for (const call of privateLatestPage.mock.calls) { + expect(call[1]).toBe(LOGIN_HISTORY_SYNC_LIMITS.messagesPerSession); + } + }); + + it('truncates large rosters before the single read-only probe', async () => { + const probe = vi.fn(async ( + groupIds: readonly number[], + privateTargets: ReadonlyArray<{ userId: number; uid: string }>, + ) => { + expect(groupIds).toHaveLength(LOGIN_HISTORY_SYNC_LIMITS.scannedGroups); + expect(privateTargets).toHaveLength( + LOGIN_HISTORY_SYNC_LIMITS.scannedPrivateUsers, + ); + return { groups: [], privateUsers: [] }; + }); + const bridge = makeBridge({ + groupCount: LOGIN_HISTORY_SYNC_LIMITS.scannedGroups + 1, + friendCount: LOGIN_HISTORY_SYNC_LIMITS.scannedPrivateUsers + 1, + probe, + }); + const resource = makeStore(); + resources.push(resource); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + const result = await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(probe).toHaveBeenCalledOnce(); + expect(result).toMatchObject({ + scannedGroups: LOGIN_HISTORY_SYNC_LIMITS.scannedGroups, + scannedPrivateUsers: LOGIN_HISTORY_SYNC_LIMITS.scannedPrivateUsers, + truncatedGroups: true, + truncatedPrivateUsers: true, + }); + }); + + it('fills a known local gap from its oldest missing sequence', async () => { + const resource = makeStore(); + resources.push(resource); + const local = groupMessage(30001, 50); + const localEvent = { + time: local.time, + post_type: 'message', + message_type: 'group', + message_id: 123, + message_seq: 50, + group_id: 30001, + }; + resource.store.storeEvent(123, true, 30001, 50, 'group_message', localEvent); + + const groupPage = vi.fn(async () => []); + const bridge = makeBridge({ + probe: vi.fn(async () => ({ + groups: [{ groupId: 30001, readSeq: 40, latestSeq: 100 }], + privateUsers: [], + })), + groupPage, + friendCount: 0, + }); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(groupPage).toHaveBeenCalledWith( + 30001, + 51, + 70, + SELF_ID, + expect.any(AbortSignal), + ); + }); + + it('backfills past a newer metadata-only authoritative row', async () => { + const resource = makeStore(); + resources.push(resource); + resource.store.storeEvent(123, true, 30001, 50, 'group_message', { + time: 1_700_000_050, + post_type: 'message', + message_type: 'group', + message_id: 123, + message_seq: 50, + group_id: 30001, + }); + resource.store.storeMeta(124, { + isGroup: true, + targetId: 30001, + sequence: 100, + sequenceAuthoritative: true, + eventName: 'group_message', + clientSequence: 0, + random: 0, + timestamp: 1_700_000_100, + }); + expect(resource.store.findLatestAuthoritativeSequence(true, 30001)).toBe(100); + expect(resource.store.findLatestPersistedAuthoritativeSequence(true, 30001)).toBe(50); + + const groupPage = vi.fn(async () => []); + const bridge = makeBridge({ + probe: vi.fn(async () => ({ + groups: [{ groupId: 30001, readSeq: 40, latestSeq: 100 }], + privateUsers: [], + })), + groupPage, + friendCount: 0, + }); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(groupPage).toHaveBeenCalledWith( + 30001, + 51, + 70, + SELF_ID, + expect.any(AbortSignal), + ); + }); + + it('backfills a metadata-only session even when the server read cursor is current', async () => { + const resource = makeStore(); + resources.push(resource); + resource.store.storeMeta(124, { + isGroup: true, + targetId: 30001, + sequence: 100, + sequenceAuthoritative: true, + eventName: 'group_message', + clientSequence: 0, + random: 0, + timestamp: 1_700_000_100, + }); + expect(resource.store.findLatestPersistedAuthoritativeSequence(true, 30001)).toBeNull(); + + const groupPage = vi.fn(async () => []); + const bridge = makeBridge({ + probe: vi.fn(async () => ({ + groups: [{ groupId: 30001, readSeq: 100, latestSeq: 100 }], + privateUsers: [], + })), + groupPage, + friendCount: 0, + }); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(groupPage).toHaveBeenCalledWith( + 30001, + 81, + 100, + SELF_ID, + expect.any(AbortSignal), + ); + }); + + it('uses the authoritative private sequence for a known local gap', async () => { + const resource = makeStore(); + resources.push(resource); + resource.store.storeEvent( + 456, + false, + 40001, + 50, + 'private_message_nt', + { + time: 1_700_000_050, + post_type: 'message', + message_type: 'private', + sub_type: 'friend', + user_id: 40001, + message_id: 456, + message_seq: 1_050, + }, + { sequenceAuthoritative: true }, + ); + + const privatePage = vi.fn(async () => []); + const privateLatestPage = vi.fn(async () => []); + const bridge = makeBridge({ + groupCount: 0, + probe: vi.fn(async () => ({ + groups: [], + privateUsers: [{ + userId: 40001, + uid: 'u_40001', + readSeq: 40, + latestSeq: 100, + lastMsgTime: 1_700_000_100, + }], + })), + privatePage, + privateLatestPage, + }); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(privatePage).toHaveBeenCalledWith( + 'u_40001', + 51, + 70, + SELF_ID, + expect.any(AbortSignal), + ); + expect(privateLatestPage).not.toHaveBeenCalled(); + }); + + it('does not retry a failed session and continues with the next one', async () => { + const groupPage = vi.fn(async (groupId: number, startSeq: number) => { + if (groupId === 30001) throw new Error('first group unavailable'); + return [groupMessage(groupId, startSeq)]; + }); + const bridge = makeBridge({ + groupCount: 2, + friendCount: 0, + probe: vi.fn(async () => ({ + groups: [ + { groupId: 30001, readSeq: 0, latestSeq: 30 }, + { groupId: 30002, readSeq: 0, latestSeq: 20 }, + ], + privateUsers: [], + })), + groupPage, + }); + const resource = makeStore(); + resources.push(resource); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + const result = await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(groupPage.mock.calls.map(call => call[0])).toEqual([30001, 30002]); + expect(result).toMatchObject({ + fetchedMessages: 1, + storedMessages: 1, + failedSessions: 1, + }); + await expect(getGroupMsgHistory(resource.store, 30002, undefined, 20)) + .resolves.toHaveLength(1); + }); + + it('keeps the stored count accurate when a later history record is invalid', async () => { + const groupPage = vi.fn(async () => [ + groupMessage(30001, 1), + groupMessage(30001, 0), + ]); + const bridge = makeBridge({ + friendCount: 0, + probe: vi.fn(async () => ({ + groups: [{ groupId: 30001, readSeq: 0, latestSeq: 20 }], + privateUsers: [], + })), + groupPage, + }); + const resource = makeStore(); + resources.push(resource); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + const result = await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: { + ...converterContext(), + messageIdResolver: null, + }, + }, new AbortController().signal); + + expect(groupPage).toHaveBeenCalledOnce(); + expect(result).toMatchObject({ + fetchedMessages: 2, + storedMessages: 1, + failedSessions: 1, + }); + await expect(getGroupMsgHistory(resource.store, 30001, undefined, 20)) + .resolves.toHaveLength(1); + }); + + it('does not restore a private message hidden by a recall tombstone', async () => { + const resource = makeStore(); + resources.push(resource); + const recalled = friendMessage(40001, 1); + resource.store.recordPrivateRecall( + 40001, + recalled.clientSeq!, + false, + recalled.time + 1, + ); + const bridge = makeBridge({ + groupCount: 0, + probe: vi.fn(async () => ({ + groups: [], + privateUsers: [{ + userId: 40001, + uid: 'u_40001', + readSeq: 0, + latestSeq: 1, + lastMsgTime: recalled.time, + }], + })), + privateLatestPage: vi.fn(async () => [recalled]), + }); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + const result = await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(result).toMatchObject({ + fetchedMessages: 1, + storedMessages: 0, + failedSessions: 0, + }); + await expect(getFriendMsgHistory(resource.store, 40001, undefined, 20)) + .resolves.toEqual([]); + }); + + it('rejects private history attributed to a different peer', async () => { + const resource = makeStore(); + resources.push(resource); + const bridge = makeBridge({ + groupCount: 0, + probe: vi.fn(async () => ({ + groups: [], + privateUsers: [{ + userId: 40001, + uid: 'u_40001', + readSeq: 0, + latestSeq: 1, + lastMsgTime: 1_700_000_000, + }], + })), + privateLatestPage: vi.fn(async () => [friendMessage(40002, 1)]), + }); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + const result = await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, new AbortController().signal); + + expect(result).toMatchObject({ + fetchedMessages: 1, + storedMessages: 0, + failedSessions: 1, + }); + await expect(getFriendMsgHistory(resource.store, 40001, undefined, 20)) + .resolves.toEqual([]); + await expect(getFriendMsgHistory(resource.store, 40002, undefined, 20)) + .resolves.toEqual([]); + }); + + it('does not issue media URL requests outside the history packet budget', async () => { + const imageUrlResolver = vi.fn(async () => { + throw new Error('image resolver must not run'); + }); + const mediaUrlResolver = vi.fn(async () => { + throw new Error('media resolver must not run'); + }); + const resource = makeStore(); + resources.push(resource); + const bridge = makeBridge({ + friendCount: 0, + groupPage: vi.fn(async () => [groupMessage(30001, 1, [ + { type: 'image', imageUrl: 'https://example.test/image' }, + { type: 'record', url: 'https://example.test/record' }, + ])]), + }); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + await coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: { + ...converterContext(), + imageUrlResolver, + mediaUrlResolver, + }, + }, new AbortController().signal); + + expect(imageUrlResolver).not.toHaveBeenCalled(); + expect(mediaUrlResolver).not.toHaveBeenCalled(); + await expect(getGroupMsgHistory(resource.store, 30001, undefined, 20)) + .resolves.toMatchObject([{ + message: [ + { type: 'image', data: { url: 'https://example.test/image' } }, + { type: 'record', data: { url: 'https://example.test/record' } }, + ], + }]); + }); + + it('serializes different accounts process-wide', async () => { + let releaseFirst!: () => void; + const firstProbe = vi.fn(() => new Promise<{ + groups: []; + privateUsers: []; + }>((resolve) => { + releaseFirst = () => resolve({ groups: [], privateUsers: [] }); + })); + const secondProbe = vi.fn(async () => ({ groups: [], privateUsers: [] })); + const firstStore = makeStore(); + const secondStore = makeStore(); + resources.push(firstStore, secondStore); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + const first = coordinator.schedule({ + selfId: SELF_ID, + bridge: makeBridge({ probe: firstProbe, groupCount: 0, friendCount: 0 }), + messageStore: firstStore.store, + converterCtx: converterContext(), + }, new AbortController().signal); + const second = coordinator.schedule({ + selfId: SELF_ID + 1, + bridge: makeBridge({ probe: secondProbe, groupCount: 0, friendCount: 0 }), + messageStore: secondStore.store, + converterCtx: { ...converterContext(), selfId: SELF_ID + 1 }, + }, new AbortController().signal); + + await vi.waitFor(() => expect(firstProbe).toHaveBeenCalledOnce()); + expect(secondProbe).not.toHaveBeenCalled(); + releaseFirst(); + await Promise.all([first, second]); + expect(secondProbe).toHaveBeenCalledOnce(); + }); + + it('cancels a queued account immediately without blocking later accounts', async () => { + let releaseFirst!: () => void; + const firstProbe = vi.fn(() => new Promise<{ + groups: []; + privateUsers: []; + }>((resolve) => { + releaseFirst = () => resolve({ groups: [], privateUsers: [] }); + })); + const cancelledProbe = vi.fn(async () => ({ groups: [], privateUsers: [] })); + const thirdProbe = vi.fn(async () => ({ groups: [], privateUsers: [] })); + const firstStore = makeStore(); + const cancelledStore = makeStore(); + const thirdStore = makeStore(); + resources.push(firstStore, cancelledStore, thirdStore); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + const cancelledController = new AbortController(); + + const first = coordinator.schedule({ + selfId: SELF_ID, + bridge: makeBridge({ probe: firstProbe, groupCount: 0, friendCount: 0 }), + messageStore: firstStore.store, + converterCtx: converterContext(), + }, new AbortController().signal); + const cancelled = coordinator.schedule({ + selfId: SELF_ID + 1, + bridge: makeBridge({ probe: cancelledProbe, groupCount: 0, friendCount: 0 }), + messageStore: cancelledStore.store, + converterCtx: { ...converterContext(), selfId: SELF_ID + 1 }, + }, cancelledController.signal); + + await vi.waitFor(() => expect(firstProbe).toHaveBeenCalledOnce()); + cancelledController.abort(new Error('queued account disposed')); + await expect(cancelled).rejects.toThrow('queued account disposed'); + expect(cancelledProbe).not.toHaveBeenCalled(); + + releaseFirst(); + await first; + + await coordinator.schedule({ + selfId: SELF_ID + 2, + bridge: makeBridge({ probe: thirdProbe, groupCount: 0, friendCount: 0 }), + messageStore: thirdStore.store, + converterCtx: { ...converterContext(), selfId: SELF_ID + 2 }, + }, new AbortController().signal); + + expect(cancelledProbe).not.toHaveBeenCalled(); + expect(thirdProbe).toHaveBeenCalledOnce(); + }); + + it('does not persist an in-flight page after the account is disposed', async () => { + let releasePage!: () => void; + const groupPage = vi.fn(() => new Promise((resolve) => { + releasePage = () => resolve([groupMessage(30001, 1)]); + })); + const resource = makeStore(); + resources.push(resource); + const bridge = makeBridge({ + friendCount: 0, + groupPage, + }); + const messageIdResolver = vi.fn(converterContext().messageIdResolver); + const controller = new AbortController(); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + const operation = coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: { + ...converterContext(), + messageIdResolver, + }, + }, controller.signal); + + await vi.waitFor(() => expect(groupPage).toHaveBeenCalledOnce()); + controller.abort(new Error('account disposed during history request')); + releasePage(); + + await expect(operation).rejects.toThrow('account disposed during history request'); + expect(messageIdResolver).not.toHaveBeenCalled(); + await expect(getGroupMsgHistory(resource.store, 30001, undefined, 20)) + .resolves.toEqual([]); + }); + + it('stops conversion side effects when disposal happens during conversion', async () => { + const resource = makeStore(); + resources.push(resource); + const controller = new AbortController(); + const mediaSegmentSink = vi.fn(); + const bridge = makeBridge({ + friendCount: 0, + groupPage: vi.fn(async () => [groupMessage(30001, 1, [{ + type: 'image', + imageUrl: 'https://example.test/history-image', + }])]), + }); + const messageIdResolver = vi.fn(( + _isGroup: boolean, + sessionId: number, + sequence: number, + eventName: string, + ) => { + controller.abort(new Error('account disposed during conversion')); + return hashMessageIdInt32(sequence, sessionId, eventName); + }); + const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined }); + + const operation = coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: { + ...converterContext(), + messageIdResolver, + mediaSegmentSink, + }, + }, controller.signal); + + await expect(operation).rejects.toThrow('account disposed during conversion'); + expect(messageIdResolver).toHaveBeenCalledOnce(); + expect(mediaSegmentSink).not.toHaveBeenCalled(); + await expect(getGroupMsgHistory(resource.store, 30001, undefined, 20)) + .resolves.toEqual([]); + }); + + it('cancels during the grace period without probing QQ', async () => { + const probe = vi.fn(); + const bridge = makeBridge({ probe }); + const coordinator = new LoginHistorySyncCoordinator({ + sleep: (_ms, signal) => new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }), + }); + const resource = makeStore(); + resources.push(resource); + const controller = new AbortController(); + + const operation = coordinator.schedule({ + selfId: SELF_ID, + bridge, + messageStore: resource.store, + converterCtx: converterContext(), + }, controller.signal); + controller.abort(new Error('session closed')); + + await expect(operation).rejects.toThrow('session closed'); + expect(probe).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/instance-config-lifecycle.test.ts b/packages/onebot/tests/instance-config-lifecycle.test.ts index 377d6d2d..eae88518 100644 --- a/packages/onebot/tests/instance-config-lifecycle.test.ts +++ b/packages/onebot/tests/instance-config-lifecycle.test.ts @@ -7,6 +7,7 @@ function config(trigger: string): OneBotConfig { return { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, statusCommand: { enabled: true, swallow: false, cooldownSeconds: 5, trigger }, + historySync: { enabled: false }, notifications: { channelIds: [] }, }; } diff --git a/packages/onebot/tests/instance-network-dispose.test.ts b/packages/onebot/tests/instance-network-dispose.test.ts index b8507ea2..6bffabd5 100644 --- a/packages/onebot/tests/instance-network-dispose.test.ts +++ b/packages/onebot/tests/instance-network-dispose.test.ts @@ -1,7 +1,10 @@ -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { loginHistorySyncCoordinator } from '../src/history-sync'; import { OneBotInstance } from '../src/instance'; import type { NetworkShutdownResult } from '../src/network'; +afterEach(() => vi.restoreAllMocks()); + function fabricatedInstance(results: NetworkShutdownResult[]) { const instance = Object.create(OneBotInstance.prototype) as OneBotInstance; const closeMessage = vi.fn(); @@ -19,6 +22,8 @@ function fabricatedInstance(results: NetworkShutdownResult[]) { disposeRequested: false, acceptingActions: true, inFlightActions: new Set>(), + historySyncAbortController: new AbortController(), + historySyncTask: null, lifecycleTail: Promise.resolve(), storeCloseState: { message: false, media: false, reaction: false }, apiHandler: { quiesce: vi.fn() }, @@ -32,6 +37,46 @@ function fabricatedInstance(results: NetworkShutdownResult[]) { } describe('OneBotInstance.dispose network/store ordering', () => { + it('uses the startup opt-in snapshot and starts history sync at most once', async () => { + const schedule = vi.spyOn(loginHistorySyncCoordinator, 'schedule') + .mockResolvedValue({ + scannedGroups: 0, + scannedPrivateUsers: 0, + selectedGroups: 0, + selectedPrivateUsers: 0, + fetchedMessages: 0, + storedMessages: 0, + failedSessions: 0, + truncatedGroups: false, + truncatedPrivateUsers: false, + }); + const disabled = fabricatedInstance([{ closed: true, errors: [] }]).instance; + Object.assign(disabled as unknown as Record, { + historySyncEnabledAtStartup: false, + historySyncStartRequested: false, + bridge: {}, + converterCtx: {}, + log: { debug: vi.fn(), error: vi.fn() }, + }); + + disabled.startLoginHistorySync(); + expect(schedule).not.toHaveBeenCalled(); + + const enabled = fabricatedInstance([{ closed: true, errors: [] }]).instance; + Object.assign(enabled as unknown as Record, { + historySyncEnabledAtStartup: true, + historySyncStartRequested: false, + bridge: {}, + converterCtx: {}, + log: { debug: vi.fn(), error: vi.fn() }, + }); + enabled.startLoginHistorySync(); + enabled.startLoginHistorySync(); + await Promise.resolve(); + + expect(schedule).toHaveBeenCalledOnce(); + }); + it('keeps stores open after an incomplete network shutdown and retries later', async () => { const failure = { name: 'http', @@ -141,4 +186,27 @@ describe('OneBotInstance.dispose network/store ordering', () => { expect(f.closeMedia).toHaveBeenCalledTimes(1); expect(f.closeReaction).toHaveBeenCalledTimes(1); }); + + it('aborts and drains login history sync before closing message storage', async () => { + const f = fabricatedInstance([{ closed: true, errors: [] }]); + let finishSync!: () => void; + const historySyncTask = new Promise((resolve) => { finishSync = resolve; }); + const controller = new AbortController(); + Object.assign(f.instance as unknown as Record, { + historySyncAbortController: controller, + historySyncTask, + }); + + const disposing = f.instance.dispose(); + expect(controller.signal.aborted).toBe(true); + await Promise.resolve(); + await Promise.resolve(); + expect(f.shutdown).not.toHaveBeenCalled(); + expect(f.closeMessage).not.toHaveBeenCalled(); + + finishSync(); + await disposing; + expect(f.shutdown).toHaveBeenCalledOnce(); + expect(f.closeMessage).toHaveBeenCalledOnce(); + }); }); diff --git a/packages/onebot/tests/manager-config-apply.test.ts b/packages/onebot/tests/manager-config-apply.test.ts index fc48eeff..a5022d23 100644 --- a/packages/onebot/tests/manager-config-apply.test.ts +++ b/packages/onebot/tests/manager-config-apply.test.ts @@ -6,6 +6,7 @@ function config(trigger: string): OneBotConfig { return { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, statusCommand: { enabled: true, swallow: false, cooldownSeconds: 5, trigger }, + historySync: { enabled: false }, notifications: { channelIds: [] }, }; } diff --git a/packages/onebot/tests/message-store.test.ts b/packages/onebot/tests/message-store.test.ts index bdfbb0e6..143247b9 100644 --- a/packages/onebot/tests/message-store.test.ts +++ b/packages/onebot/tests/message-store.test.ts @@ -235,6 +235,56 @@ describe('MessageStore', () => { clientSequence: 88, }); }); + + it('rolls back private history metadata when storing the event body fails', () => { + const messageId = -987654321; + const peerId = 555; + const database = new DatabaseSync(testDbPath); + database.exec(` + CREATE TRIGGER reject_history_event_body + BEFORE UPDATE OF data ON messages + WHEN NEW.message_hash = ${messageId} AND NEW.data IS NOT NULL + BEGIN + SELECT RAISE(ABORT, 'history event body rejected'); + END + `); + database.close(); + + expect(() => store.storeHistoryEvent( + messageId, + false, + peerId, + 850, + PRIVATE_MESSAGE_EVENT, + { + time: 1_700_000_000, + post_type: 'message', + message_type: 'private', + sub_type: 'friend', + user_id: peerId, + message_id: messageId, + message_seq: 50, + }, + { + sequenceAuthoritative: true, + meta: { + isGroup: false, + targetId: peerId, + sequence: 850, + sequenceAuthoritative: true, + eventName: PRIVATE_MESSAGE_EVENT, + clientSequence: 50, + privateDirection: 'incoming', + random: 42, + timestamp: 1_700_000_000, + }, + }, + )).toThrow(/history event body rejected/); + + expect(store.findMeta(messageId)).toBeNull(); + expect(store.findEvent(messageId)).toBeNull(); + expect(store.findLatestAuthoritativeSequence(false, peerId)).toBeNull(); + }); }); describe('listSessionEvents', () => { diff --git a/packages/onebot/tests/network-reconcile.test.ts b/packages/onebot/tests/network-reconcile.test.ts index 1515d3e3..edde9212 100644 --- a/packages/onebot/tests/network-reconcile.test.ts +++ b/packages/onebot/tests/network-reconcile.test.ts @@ -89,6 +89,7 @@ function emptyConfig(): OneBotConfig { return { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, statusCommand: { enabled: true, swallow: false, cooldownSeconds: 5, trigger: '#sl' }, + historySync: { enabled: false }, notifications: { channelIds: [] }, }; }