diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d0c12e217..22a22d042 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: run: npm run check windows-workspaces: - name: Workspace regression tests (Windows) + name: Workspace and QQ persistence regression tests (Windows) runs-on: windows-latest steps: - name: Checkout @@ -52,3 +52,6 @@ jobs: test/conversation-workspace-races.test.mjs test/conversation-workspace-switch-order.test.mjs test/conversation-workspace-bind-recovery.test.mjs + test/channels/qq/state-store.test.mjs + test/channels/qq/reply-continuity.test.mjs + test/channels/qq/normal-update.test.mjs diff --git a/docs/qq-consumer-continuity.md b/docs/qq-consumer-continuity.md new file mode 100644 index 000000000..c3aecc4a1 --- /dev/null +++ b/docs/qq-consumer-continuity.md @@ -0,0 +1,60 @@ +# QQ consumer continuity across controlled updates + +An exclusive QQ consumer keeps accepted work bound to its original message when +the Provider restarts. The existing account state stores compact reply proofs, +the next native `msg_seq`, and any attempted reply budget. Message text remains +with the consumer. Source proofs contain a hash of that text and the original +account, route, timestamp and reply eligibility. + +Proofs are written before inbound acceptance. Reply attempts are reserved before +the native POST. An uncertain send keeps its spent attempt across restart. A +definite rate-limit refusal releases the attempt and reuses the same sequence +for the existing bounded retry. The normal native reply window and reply budget +continue to apply. + +Proof files are looked up by their known account/message key. The bounded memory +cache does not evict unfinished work from disk. Files are flushed before atomic +rename. On systems where Node supports directory handles, the containing +directories are synchronized too and a synchronization failure rejects the +operation. Windows retains file flushing and atomic replacement because Node +cannot fsync a directory there. This contract covers completed writes and +controlled process replacement, not a power-loss guarantee on every filesystem. + +## Completing a source + +The consumer can return `{ accepted: true, complete: true }` when no work remains, +or use the optional `sourceReleaseVersion: 1` operation: + +```js +const result = await ctx.dshIm.releaseSource(botId, event.reply, { + expectedFingerprint: event.fingerprint, + signal, +}); +``` + +The result is `{ released: true }`. A source with a previous native attempt keeps +its budget through the remaining reply window and returns `retainUntil` in +milliseconds since the epoch. The owner calls the same release operation again +after that time. Redelivery cannot reset a spent budget. Releasing a source does +not erase the consumer's own work or message history. + +## Updating the receiver + +The optional `inboundDrainVersion: 1` methods use the current verified account and +exclusive consumer lease: + +1. Call `quiesceInbound(botId, { expectedFingerprint, signal })` while the lease is + still active. It stops intake, waits for callbacks and canonical acceptance, + then saves the native session/cursor. It returns + `{ stopped: true, resumeCursor: boolean }`. +2. Dispose the old lease after quiescing. Provider shutdown follows the same + ordering before unregistering the public delivery adapter. +3. Call `resumeInbound` to verify the same account, then register the new consumer + with `consumeInbound`. Verification can return + `{ connected: false, accountVerified: true }` while reception waits for its + consumer. A reconnect does not silently reopen a quiesced receiver. + +The saved native session is bound to the account and credential. A rejected +inbound callback prevents a resumable cursor from being recorded. The platform +controls replay availability and retention. A saved cursor does not promise +recovery after abrupt termination or platform replay expiry. diff --git a/plugin-src/host/channels/qq/production.mjs b/plugin-src/host/channels/qq/production.mjs index 3b66051b4..8c7bfe38e 100644 --- a/plugin-src/host/channels/qq/production.mjs +++ b/plugin-src/host/channels/qq/production.mjs @@ -179,6 +179,10 @@ export async function createProductionController(ctx, config = {}, internals = { controller, deliveryAdapter: createDeliveryAdapter({ channel: 'qq', workspaces, coreController, stateFor }), ready: supervisor.ready, + async prepareClose() { + await supervisor.close(); + await controller.close(); + }, async close() { await supervisor.close(); await controller.close(); diff --git a/plugin-src/host/channels/shared/startup.mjs b/plugin-src/host/channels/shared/startup.mjs index 513839a2a..07cce3c88 100644 --- a/plugin-src/host/channels/shared/startup.mjs +++ b/plugin-src/host/channels/shared/startup.mjs @@ -50,9 +50,10 @@ export async function installProductionChannel(ctx, config, { const closeProduction = () => (closing ??= (async () => { try { unregisterSetup?.(); - await unregisterDelivery?.(); + await production?.prepareClose?.(); } finally { - await production?.close(); + try { await unregisterDelivery?.(); } + finally { await production?.close(); } } })()); try { diff --git a/plugin-src/host/delivery-adapter.mjs b/plugin-src/host/delivery-adapter.mjs index cb61fb1ce..829f57050 100644 --- a/plugin-src/host/delivery-adapter.mjs +++ b/plugin-src/host/delivery-adapter.mjs @@ -240,11 +240,26 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta } return Object.freeze({ channel, + releaseSource: (botId, route, options) => { + if (typeof coreController.releaseSource !== 'function') + throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' }); + return coreController.releaseSource(botId, route, options); + }, consumeInbound: (botId, options) => { if (typeof coreController.consumeInbound !== 'function') throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' }); return coreController.consumeInbound(botId, options); }, + quiesceInbound: (botId, options) => { + if (typeof coreController.quiesceInbound !== 'function') + throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' }); + return coreController.quiesceInbound(botId, options); + }, + resumeInbound: (botId, options) => { + if (typeof coreController.resumeInbound !== 'function') + throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' }); + return coreController.resumeInbound(botId, options); + }, reactionChecked: (botId, route, reaction, options) => { if (channel !== 'feishu' || typeof coreController.reactionChecked !== 'function') throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' }); diff --git a/plugin-src/host/delivery-service.mjs b/plugin-src/host/delivery-service.mjs index 2777e36c2..acd0f6c57 100644 --- a/plugin-src/host/delivery-service.mjs +++ b/plugin-src/host/delivery-service.mjs @@ -450,6 +450,57 @@ export class DeliveryService { return dispose; } + /** Stop this receiver after canonical acceptance, before its lease is revoked. + * A saved cursor is a normal-update resume position, not a delivery guarantee. + */ + async quiesceInbound(botId, options = {}) { + const id = botIdOf(botId); + cancellation(options.signal); + if (!/^[a-f0-9]{64}$/.test(options.expectedFingerprint ?? '')) throw deliveryError('bad-request'); + const registration = await this.#checkedRegistrationFor(id); + if (typeof registration.adapter.quiesceInbound !== 'function') throw deliveryError('capability-unavailable'); + this.#assertRegistered(registration); + const result = await registration.adapter.quiesceInbound(id, { + ...options, signal: options.signal ? AbortSignal.any([options.signal, registration.controller.signal]) + : registration.controller.signal, + }); + this.#assertRegistered(registration); + if (result?.stopped !== true || typeof result.resumeCursor !== 'boolean') throw deliveryError('stop-result-unknown'); + return result; + } + + async releaseSource(botId, route, options = {}) { + const id = botIdOf(botId); + cancellation(options.signal); + if (!/^[a-f0-9]{64}$/.test(options.expectedFingerprint ?? '')) throw deliveryError('bad-request'); + const registration = await this.#checkedRegistrationFor(id); + if (typeof registration.adapter.releaseSource !== 'function') throw deliveryError('capability-unavailable'); + this.#assertRegistered(registration); + const result = await registration.adapter.releaseSource(id, structuredClone(route), { + ...options, signal: options.signal ? AbortSignal.any([options.signal, registration.controller.signal]) : registration.controller.signal, + }); + this.#assertRegistered(registration); + cancellation(options.signal); + return result; + } + + /** Reopen an explicitly registered receiver before inspecting its connection. */ + async resumeInbound(botId, options = {}) { + const id = botIdOf(botId); + cancellation(options.signal); + if (!/^[a-f0-9]{64}$/.test(options.expectedFingerprint ?? '')) throw deliveryError('bad-request'); + const registration = await this.#checkedRegistrationFor(id); + if (typeof registration.adapter.resumeInbound !== 'function') throw deliveryError('capability-unavailable'); + this.#assertRegistered(registration); + const result = await registration.adapter.resumeInbound(id, { + ...options, signal: options.signal ? AbortSignal.any([options.signal, registration.controller.signal]) + : registration.controller.signal, + }); + this.#assertRegistered(registration); + if (typeof result?.connected !== 'boolean' || result.accountVerified !== true) throw deliveryError('start-result-unknown'); + return result; + } + async reactionChecked(botId, route, reaction, options = {}) { const id = botIdOf(botId); cancellation(options.signal); diff --git a/plugin-src/host/index.mjs b/plugin-src/host/index.mjs index 7da6b74ad..9c35b53ae 100644 --- a/plugin-src/host/index.mjs +++ b/plugin-src/host/index.mjs @@ -101,6 +101,11 @@ export function createImHostPlugin(internals = {}) { reactionVersion: 1, reactionChecked: (botId, route, reaction, options) => deliveryService.reactionChecked(botId, route, reaction, options), inboundVersion: 1, + inboundDrainVersion: 1, + sourceReleaseVersion: 1, + releaseSource: (botId, route, options) => deliveryService.releaseSource(botId, route, options), + quiesceInbound: (botId, options) => deliveryService.quiesceInbound(botId, options), + resumeInbound: (botId, options) => deliveryService.resumeInbound(botId, options), fileVersion: 1, approvalCardVersion: 1, questionCardVersion: 1, diff --git a/src/channels/qq/external-consumer.mjs b/src/channels/qq/external-consumer.mjs index 7e4fb4a08..0b6bdee18 100644 --- a/src/channels/qq/external-consumer.mjs +++ b/src/channels/qq/external-consumer.mjs @@ -1,12 +1,13 @@ import { isQqAddressedGroupMessage, isQqAddressedMessage, isQqDirectMessage } from './external-addressing.mjs'; import { createHash } from 'node:crypto'; -import { ApiError, getNextMsgSeq, messagePath } from '@tencent-connect/qqbot-nodejs/protocol'; +import { ApiError, messagePath } from '@tencent-connect/qqbot-nodejs/protocol'; import { QqNativeReplyObservations, qqNativeIdentifier as identifier } from './native-reply-observations.mjs'; import { qqSourceAttachments, readQqSourceAttachment, checkedQqImageFile, uploadQqCheckedMedia } from './external-images.mjs'; import { checkedQqGenericFile, qqQuotedMessage } from './external-files.mjs'; import { qqAttachmentLabel, qqReadableAttachments, qqSkippedAttachmentNotes } from './external-attachments.mjs'; import { qqVoiceMessage } from './external-voice.mjs'; import { qqExternalMentions } from './external-mentions.mjs'; +import { createQqReplyProof, qqContentHash } from './state-store.mjs'; export function qqRefusal(code) { return Object.assign(new Error(code), { code }); } @@ -108,7 +109,7 @@ function withReadableAttachments(message, options) { return { ...message, content, attachments: readable.length ? readable : undefined }; } -/** Bounded, process-local source proof, never a second durable Inbox or history. */ +/** Retain native reply proofs; canonical message content belongs to the consumer. */ export class QqExternalConsumer { #bot; #account; @@ -124,7 +125,8 @@ export class QqExternalConsumer { #rateLimitRetryDelaysMs; #sources = new Map(); #posts = new Map(); - constructor({ bot, account, botId, accept, sourceImages = () => false, sourceFiles = () => false, sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false, ordinaryText = () => false, directMessages = () => false, reportNativeObservation = () => {}, reportNativeFrame, nativeUser, rateLimitRetryDelaysMs = RATE_LIMIT_RETRY_DELAYS_MS }) { + #state; + constructor({ bot, account, botId, accept, state, sourceImages = () => false, sourceFiles = () => false, sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false, ordinaryText = () => false, directMessages = () => false, reportNativeObservation = () => {}, reportNativeFrame, nativeUser, rateLimitRetryDelaysMs = RATE_LIMIT_RETRY_DELAYS_MS }) { this.#rateLimitRetryDelaysMs = rateLimitRetryDelaysMs; this.#bot = bot; this.#account = account; this.#botId = botId; this.#accept = accept; this.#observations = new QqNativeReplyObservations({ account, report: reportNativeObservation, @@ -135,6 +137,16 @@ export class QqExternalConsumer { this.#sourceVoiceAudio = sourceVoiceAudio; this.#ordinaryText = ordinaryText; this.#directMessages = directMessages; + this.#state = state; + } + + async #persistSource(source) { + if (!this.#state?.putReplyProof) return; + await this.#state.putReplyProof({ fingerprint: this.#account.fingerprint, + route: source.event.reply, at: source.event.at, kind: source.event.conversation.kind, + mentionedAccount: source.event.mentionedAccount, digest: source.digest, + contentHash: source.contentHash, contentHashAlgorithm: 'sha256-json-string-v1', + attempts: source.attempts, sequence: source.sequence }); } recordNativeReceipt(receipt, signal) { this.#observations.sent(receipt.conversationId, receipt.messageId, signal); @@ -170,32 +182,68 @@ export class QqExternalConsumer { const event = base && voice ? { ...(media?.event ?? base), voice: voice.voice } : media?.event ?? base; if (!event) return; signal.throwIfAborted(); - const prior = this.#sources.get(event.messageId); - if (prior && JSON.stringify(prior.event) !== JSON.stringify(event)) throw qqRefusal('stale-route'); + const prior = this.#sources.get(event.messageId) + ?? this.#state?.replyProof?.(this.#account.fingerprint, event.messageId); + const contentHash = qqContentHash(event.text); + const { digest } = createQqReplyProof({ fingerprint: this.#account.fingerprint, route: event.reply, + at: event.at, kind: event.conversation.kind, mentionedAccount: event.mentionedAccount, + contentHash }); + if (prior && prior.digest !== digest) throw qqRefusal('stale-route'); // Consumer-owned objects never become the Provider's source authority. - if (!prior) this.#sources.set(event.messageId, { event: structuredClone(event), - ...(media ? { files: structuredClone(media.files) } : {}), attempts: 0 }); + if (!this.#sources.has(event.messageId)) { + const source = { event: structuredClone(event), digest, contentHash, + ...(media ? { files: structuredClone(media.files) } : {}), attempts: prior?.attempts ?? 0, sequence: prior?.sequence ?? 0 }; + await this.#persistSource(source); + signal.throwIfAborted(); + this.#sources.set(event.messageId, source); + } while (this.#sources.size > 2000) this.#sources.delete(this.#sources.keys().next().value); // The external consumer acknowledges only after canonical ingestion commits. - return this.#accept(event, signal); + const result = await this.#accept(event, signal); + if (result?.accepted !== true) throw qqRefusal('ingress-not-accepted'); + if (result.complete === true) await this.release(event.reply, signal); + return result; } #source(route, signal) { if (signal?.aborted) throw qqRefusal('cancelled'); - const source = this.#sources.get(route?.messageId); + let source = this.#sources.get(route?.messageId); + const proof = route?.messageId && this.#state?.replyProof?.(this.#account.fingerprint, route.messageId); + if (!source && proof) { + source = { event: { reply: proof.route, at: proof.at, mentionedAccount: proof.mentionedAccount, + conversation: { id: proof.route.conversationId, kind: proof.kind } }, + digest: proof.digest, contentHash: proof.contentHash, attempts: proof.attempts, sequence: proof.sequence }; + this.#sources.set(route.messageId, source); + while (this.#sources.size > 2000) this.#sources.delete(this.#sources.keys().next().value); + } if (!source) throw qqRefusal('source-not-found'); if (Object.keys(route).some(key => !['messageId', 'conversationId', 'actorId'].includes(key)) || ['messageId', 'conversationId', 'actorId'].some(key => source.event.reply[key] !== route[key])) throw qqRefusal('stale-route'); + const persisted = this.#state?.replyProof?.(this.#account.fingerprint, route.messageId); + if (persisted) { + source.attempts = persisted.attempts; + source.sequence = persisted.sequence; + } return source; } - qualify(route, signal) { + #replySource(route, signal, checkBudget = true) { const source = this.#source(route, signal); const direct = source.event.conversation.kind === 'dm'; if (!direct && !source.event.mentionedAccount) throw qqRefusal('capability-unavailable'); if (Date.now() - Date.parse(source.event.at) >= PASSIVE_REPLY_WINDOW_MS[direct ? 'c2c' : 'group']) throw qqRefusal('reply-window-expired'); - if (source.attempts >= PASSIVE_REPLY_BUDGET[direct ? 'c2c' : 'group']) throw qqRefusal('reply-limit-exceeded'); - return structuredClone(source.event.reply); + if (checkBudget && source.attempts >= PASSIVE_REPLY_BUDGET[direct ? 'c2c' : 'group']) throw qqRefusal('reply-limit-exceeded'); + return source; + } + qualify(route, signal) { + return structuredClone(this.#replySource(route, signal).event.reply); + } + async release(route, signal) { + if (signal?.aborted) throw qqRefusal('cancelled'); + const result = this.#state?.releaseReplyProof + ? await this.#state.releaseReplyProof(this.#account.fingerprint, route) : { released: true }; + if (!result.retainUntil) this.#sources.delete(route.messageId); + return result; } async readImage(route, attachment, options = {}) { const source = this.#source(route, options.signal); @@ -222,21 +270,44 @@ export class QqExternalConsumer { const scope = this.#scope(qualified); const previous = this.#posts.get(`${scope}:${conversationId}`) ?? Promise.resolve(); const run = async () => { + let sequence; for (let retry = 0; ; retry++) { + this.#replySource(qualified, signal); assertSendable(); let token; try { token = await this.#bot.api.getToken(); } catch { throw qqRefusal('source-unavailable'); } + this.#replySource(qualified, signal); assertSendable(); - this.#sources.get(qualified.messageId).attempts++; + const source = this.#sources.get(qualified.messageId); + if (this.#state?.reserveReplyAttempt) { + const reserved = await this.#state.reserveReplyAttempt(this.#account.fingerprint, + qualified.messageId, PASSIVE_REPLY_BUDGET[scope], sequence); + sequence = reserved.sequence; + } else { + sequence ??= source.sequence + 1; + source.attempts++; + source.sequence = Math.max(source.sequence, sequence); + } + try { + this.#replySource(qualified, signal, false); + assertSendable(); + } catch (error) { + if (this.#state?.refundReplyAttempt) + await this.#state.refundReplyAttempt(this.#account.fingerprint, qualified.messageId); + else source.attempts--; + throw error; + } try { - return await this.#bot.apiClient.request(token, 'POST', messagePath(scope, conversationId), body); + const response = await this.#bot.apiClient.request(token, 'POST', messagePath(scope, conversationId), { ...body, msg_seq: sequence }); + return response; } catch (error) { const failure = nativeReplyFailure(error); if (failure.code !== 'reply-rate-limited' || retry >= this.#rateLimitRetryDelaysMs.length) throw failure; // A rate-limited post was refused, so it does not spend the passive reply budget. - const source = this.#sources.get(qualified.messageId); - if (source) source.attempts--; + if (this.#state?.refundReplyAttempt) + await this.#state.refundReplyAttempt(this.#account.fingerprint, qualified.messageId); + else source.attempts--; await retryDelay(this.#rateLimitRetryDelaysMs[retry], signal); } } @@ -261,9 +332,7 @@ export class QqExternalConsumer { const fileInfo = await uploadQqCheckedMedia(this.#bot, target, file, bytes, signal, image ? 1 : 4); await verifyAccount(); const response = await this.#post(qualified, - { msg_type: 7, media: { file_info: fileInfo }, msg_id: qualified.messageId, - msg_seq: getNextMsgSeq(qualified.messageId) }, signal, () => { - this.qualify(qualified, signal); + { msg_type: 7, media: { file_info: fileInfo }, msg_id: qualified.messageId }, signal, () => { if (beforeSend() !== true) throw qqRefusal('stale-route'); if (signal?.aborted) throw qqRefusal('cancelled'); }); @@ -275,13 +344,13 @@ export class QqExternalConsumer { const qualified = this.qualify(route, signal); if (typeof text !== 'string' || !text.trim() || text.length > 4000 || mentionUserIds?.length) throw qqRefusal('bad-request'); + const body = { msg_type: 0, content: text, msg_id: qualified.messageId }; // The token is prepared before the fence so revocation and expiry are // checked immediately before the message POST, including on a retry. const response = await this.#post(qualified, - { msg_type: 0, content: text, msg_id: qualified.messageId, msg_seq: getNextMsgSeq(qualified.messageId) }, + body, signal, () => { if (signal?.aborted) throw qqRefusal('cancelled'); - this.qualify(qualified, signal); if (beforeSend !== undefined && beforeSend() !== true) throw qqRefusal('stale-route'); if (signal?.aborted) throw qqRefusal('cancelled'); }); diff --git a/src/channels/qq/qq-controller.mjs b/src/channels/qq/qq-controller.mjs index 19e520542..fb9fafb6f 100644 --- a/src/channels/qq/qq-controller.mjs +++ b/src/channels/qq/qq-controller.mjs @@ -54,6 +54,8 @@ export class QqController { #transitions = new Map(); #revision = 0; #closed = false; + #closing = null; + #quiesced = new Set(); #inboundConsumers = new ExclusiveInboundConsumers(); constructor({ @@ -94,7 +96,8 @@ export class QqController { if (this.#closed) return this.status(); for (const config of this.#configStore.list()) { await this.#withBotTransition(config.botId, async () => { - if (this.#closed || this.#runtimes.get(config.botId)?.status?.ready) return; + if (this.#closed || this.#quiesced.has(config.botId) || this.#runtimes.get(config.botId)?.status?.ready + || this.#runtimes.get(config.botId)?.status?.qqConnectionState === 'awaiting-consumer') return; try { const appSecret = await this.#resolveSecret(config.secretRef); if (!appSecret) { @@ -115,8 +118,9 @@ export class QqController { } async startProvisioning() { - if (this.#closed) throw new Error('QQ controller is closed'); + if (this.#closed || this.#closing) throw new Error('QQ controller is closed'); if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId); + if (this.#closed || this.#closing) throw new Error('QQ controller is closed'); let firstQrResolve; let firstQrReject; const firstQr = new Promise((resolve, reject) => { @@ -194,20 +198,20 @@ export class QqController { } async bindCredentials({ appId, appSecret } = {}) { - if (this.#closed) throw new Error('QQ controller is closed'); + if (this.#closed || this.#closing) throw new Error('QQ controller is closed'); const normalizedAppId = cleanString(appId); const normalizedSecret = cleanString(appSecret); if (!normalizedAppId || !normalizedSecret) { throw new TypeError('QQ AppID and AppSecret are required'); } if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId); - if (this.#closed) throw new Error('QQ controller is closed'); + if (this.#closed || this.#closing) throw new Error('QQ controller is closed'); const identity = deriveQqBotIdentity(normalizedAppId); await this.#withBotTransition(identity.botId, async () => { - if (this.#closed) throw new Error('QQ controller is closed'); + if (this.#closed || this.#closing) throw new Error('QQ controller is closed'); const previousConfig = this.#configStore.getByAppId(normalizedAppId); const previousSecret = await atConnectionStage('credential.read', () => this.#credentials.resolve(identity.secretRef), 'credential-store'); - if (this.#closed) throw new Error('QQ controller is closed'); + if (this.#closed || this.#closing) throw new Error('QQ controller is closed'); const config = { botId: identity.botId, appId: normalizedAppId, @@ -313,23 +317,28 @@ export class QqController { if (this.#closed) throw qqRefusal('provider-unavailable'); if (!this.#configStore.get(botId)) throw qqRefusal('unknown-bot'); const runtime = this.#runtimes.get(botId); - if (!runtime?.status?.ready) throw qqRefusal('bot-not-connected'); - return runtime.describeDeliveryAccount(signal); + if (!runtime) throw qqRefusal('bot-not-connected'); + const account = await runtime.describeDeliveryAccount(signal); + if (this.#closed || this.#runtimes.get(botId) !== runtime) throw qqRefusal('provider-unavailable'); + return account; } async describeDeliveryAccount(botId) { - return this.#withBotTransition(botId, async () => ({ - version: 1, botId, channel: 'qq', account: await this.#deliveryAccount(botId), connected: true, + const account = await this.#deliveryAccount(botId); + const receiverReady = this.#runtimes.get(botId)?.status?.ready === true; + return { + version: 1, botId, channel: 'qq', account, connected: receiverReady, accountVerified: true, receiverReady, capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'proactive-fence-checked', - 'exclusive-text-consumer', 'ordinary-text-consumer', 'direct-message-consumer', 'reply-text-checked', 'reply-context-checked', + 'exclusive-text-consumer', 'inbound-drain-checked', 'ordinary-text-consumer', 'direct-message-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'source-file-checked', 'source-image-checked', 'reply-file-checked', 'reply-image-fence-checked', 'reply-file-receipt-checked', 'source-generic-file-checked', 'reply-file-fence-checked', 'source-voice-transcript-checked', 'source-voice-audio-checked'], - })); + }; } async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceImages = false, sourceFiles = false, sourceVoiceTranscripts = false, sourceVoiceAudio = false, ordinaryText = false, directMessages = false } = {}) { return this.#withBotTransition(botId, async () => { + if (this.#quiesced.has(botId)) await this.#resumeInbound(botId, expectedFingerprint, signal); const account = await this.#deliveryAccount(botId, signal); if (account.fingerprint !== expectedFingerprint) throw qqRefusal('account-changed'); const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceImages, sourceFiles, sourceVoiceTranscripts, sourceVoiceAudio, ordinaryText, directMessages }); @@ -365,6 +374,50 @@ export class QqController { }); } + async releaseSource(botId, route, options = {}) { + const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal); + return checked.runtime.releaseSource(route, { signal: checked.signal }); + } + + async quiesceInbound(botId, options = {}) { + const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal); + this.#quiesced.add(botId); + return checked.runtime.quiesce(); + } + + async #resumeInbound(botId, expectedFingerprint, signal) { + const reopening = this.#quiesced.has(botId); + if (reopening) { + try { + this.#inboundConsumers.signalFor(botId, expectedFingerprint); + throw qqRefusal('consumer-conflict'); + } catch (error) { if (error.code !== 'consumer-unavailable') throw error; } + const config = this.#configStore.get(botId); + if (!config) throw qqRefusal('unknown-bot'); + const secret = await this.#resolveSecret(config.secretRef); + if (!secret) throw qqRefusal('account-unverified'); + signal?.throwIfAborted(); + this.#quiesced.delete(botId); + try { await this.#startRuntime(config, secret); } + catch (error) { this.#quiesced.add(botId); throw error; } + } + try { + const account = await this.#deliveryAccount(botId, signal); + if (account.fingerprint !== expectedFingerprint) throw qqRefusal('account-changed'); + return { connected: this.#runtimes.get(botId)?.status?.ready === true, accountVerified: true }; + } catch (error) { + if (reopening) { + this.#quiesced.add(botId); + await this.#stopRuntime(botId, { drain: false }); + } + throw error; + } + } + + async resumeInbound(botId, options = {}) { + return this.#withBotTransition(botId, () => this.#resumeInbound(botId, options.expectedFingerprint, options.signal)); + } + async replyChecked(botId, route, text, options = {}) { return this.#withBotTransition(botId, async () => { const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal); @@ -394,7 +447,7 @@ export class QqController { await this.#withBotTransition(botId, async () => { const previous = await atConnectionStage('credential.read', () => this.#credentials.resolve(config.secretRef), 'credential-store'); this.#inboundConsumers.remove(botId); - await this.#stopRuntime(botId); + await this.#stopRuntime(botId, { drain: false }); try { await atConnectionStage('credential.remove', () => this.#credentials.unset(config.secretRef), 'credential-store'); await atConnectionStage('account.remove', () => this.#configStore.remove(botId), 'account-config'); @@ -412,6 +465,7 @@ export class QqController { } await this.#deleteState({ botId, config }).catch(error => { warnings.push(this.#diagnostics.report(error, { reuse: true, operation: 'bot.delete', stage: 'state.cleanup', resource: 'account-state', warning: true, publicError: { code: 'cleanup-failed', message: '账号已移除,但本地状态清理失败。' } }).publicError); }); this.#errors.delete(botId); + this.#quiesced.delete(botId); this.#touch(); }); return { ...this.status(), ...(warnings.length ? { warnings } : {}) }; @@ -467,13 +521,22 @@ export class QqController { }; } - async close() { + async close({ drain } = {}) { if (this.#closed) return; - this.#closed = true; - this.#inboundConsumers.close(); - if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId); - await Promise.allSettled([...this.#transitions.values()]); - await Promise.allSettled([...this.#runtimes.keys()].map((botId) => this.#stopRuntime(botId))); + if (this.#closing) return this.#closing; + this.#closing = (async () => { + try { + if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId); + await Promise.allSettled([...this.#transitions.values()]); + const results = await Promise.allSettled([...this.#runtimes.keys()].map(botId => this.#stopRuntime(botId, { drain }))); + const failed = results.find(result => result.status === 'rejected'); + if (failed) throw failed.reason; + } finally { + this.#closed = true; + this.#inboundConsumers.close(); + } + })(); + return this.#closing; } async #completeProvisioning(record, credentials) { @@ -558,9 +621,10 @@ export class QqController { } async #startRuntime(config, appSecret) { - if (this.#closed) throw new Error('QQ controller is closed'); - await this.#stopRuntime(config.botId); - if (this.#closed) throw new Error('QQ controller is closed'); + if (this.#closed || this.#closing) throw new Error('QQ controller is closed'); + if (this.#quiesced.has(config.botId)) throw qqRefusal('provider-unavailable'); + await this.#stopRuntime(config.botId, { drain: false }); + if (this.#closed || this.#closing) throw new Error('QQ controller is closed'); const runtime = await atConnectionStage('runtime.prepare', () => this.#createRuntime({ botId: config.botId, config, appSecret, ...(config.consumerMode === 'external-consumer' ? { externalConsumer: (event, signal) => this.#inboundConsumers.accept(config.botId, event, signal), @@ -577,7 +641,8 @@ export class QqController { } this.#runtimes.set(config.botId, runtime); try { - await runtime.start(); + await runtime.start({ receive: config.consumerMode !== 'external-consumer' + || this.#inboundConsumers.isRegistered(config.botId) }); } catch (error) { await runtime.stop().catch(() => undefined); this.#runtimes.delete(config.botId); @@ -585,12 +650,15 @@ export class QqController { } } - async #stopRuntime(botId) { + async #stopRuntime(botId, { drain } = {}) { const runtime = this.#runtimes.get(botId); - this.#runtimes.delete(botId); - await runtime?.stop().catch((error) => { + try { await runtime?.stop({ drain }); } + catch (error) { this.#logger.warn?.(`[dsh-im:qq] bot ${botId} failed to stop cleanly:`, extractConnectionEvidence(error).details); - }); + if (drain !== false) throw error; + } finally { + if (this.#runtimes.get(botId) === runtime) this.#runtimes.delete(botId); + } } async #resolveSecret(ref) { @@ -604,6 +672,7 @@ export class QqController { } #withBotTransition(botId, operation) { + if (this.#closing) return Promise.reject(qqRefusal('provider-unavailable')); const previous = this.#transitions.get(botId) ?? Promise.resolve(); const current = previous.catch(() => undefined).then(operation); const settled = current.finally(() => { diff --git a/src/channels/qq/qq-runtime.mjs b/src/channels/qq/qq-runtime.mjs index 2083957f5..7b8d1b071 100644 --- a/src/channels/qq/qq-runtime.mjs +++ b/src/channels/qq/qq-runtime.mjs @@ -1,6 +1,7 @@ import { isQqVoiceAttachment } from './voice-attachment.mjs'; import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs'; import { QQBot, contentSanitizer, typingIndicator } from '@tencent-connect/qqbot-nodejs'; +import { createHash } from 'node:crypto'; import { connectionTestTarget, @@ -61,6 +62,14 @@ export class QqRuntime { #directMessages; #rateLimitRetryDelaysMs; #externalBridge = null; + #accepting = false; + #inflight = new Set(); + #admissionFailed = false; + #gatewaySession = null; + #sessionBinding; + #stopping = null; + #draining = false; + #waitingForConsumer = false; constructor({ config, @@ -110,12 +119,12 @@ export class QqRuntime { async describeDeliveryAccount(signal) { signal?.throwIfAborted(); - if (!this.#status.ready || !this.#bot) throw qqRefusal('bot-not-connected'); + if ((!this.#status.ready && !this.#draining && !this.#waitingForConsumer) || !this.#bot) throw qqRefusal('bot-not-connected'); const bot = this.#bot; try { const user = await bot.api.get('/users/@me'); signal?.throwIfAborted(); - if (this.#bot !== bot || !this.#status.ready) throw qqRefusal('bot-not-connected'); + if (this.#bot !== bot || (!this.#status.ready && !this.#draining && !this.#waitingForConsumer)) throw qqRefusal('bot-not-connected'); const account = verifiedQqAccount(this.#config.appId, user); if (this.#status.error?.details?.stage === 'credential.verify') { this.#status.error = null; @@ -153,6 +162,11 @@ export class QqRuntime { return this.#externalBridge.reply(route, text, options); } + releaseSource(route, { signal } = {}) { + if (!this.#externalBridge) throw qqRefusal('consumer-unavailable'); + return this.#externalBridge.release(route, signal); + } + readSourceImage(route, attachment, options) { if (!this.#externalBridge) throw qqRefusal('consumer-unavailable'); return this.#externalBridge.readImage(route, attachment, options); @@ -251,17 +265,21 @@ export class QqRuntime { }, text); } - async start() { + async start({ receive = true } = {}) { if (this.#status.ready && this.#bot) return this.status; if (this.#starting) return this.#starting; - this.#starting = this.#start().finally(() => { + this.#starting = this.#start(receive).finally(() => { this.#starting = null; }); return this.#starting; } - async #start() { + async #start(receive) { await this.stop(); + this.#waitingForConsumer = false; + this.#accepting = true; + this.#admissionFailed = false; + this.#gatewaySession = null; this.#status.startedAt = new Date().toISOString(); this.#status.qqConnectionState = 'connecting'; this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear(); @@ -274,6 +292,7 @@ export class QqRuntime { this.#abortController = controller; const observeTransport = (message) => { if (controller.signal.aborted || this.#abortController !== controller || typeof message !== 'string') return; + if (this.#draining) return false; // SDK 1.0.4 exposes close through its public Logger, not a disconnect event. if (message.startsWith(`[${this.#config.botId}] WebSocket closed:`) || message.startsWith(`[${this.#config.botId}] Connection failed:`) @@ -314,9 +333,29 @@ export class QqRuntime { logger: sdkLogger, transport: 'websocket', tokenPrefetch: 'sync', + ...(this.#config.consumerMode === 'external-consumer' && this.#state.gatewaySession ? { + sessionPersistence: { + load: () => this.#state.gatewaySession(this.#sessionBinding), + save: session => { + if (this.#accepting && this.#abortController === controller) + this.#gatewaySession = structuredClone(session); + }, + clear: () => { + if (!this.#accepting || this.#abortController !== controller) return; + this.#gatewaySession = null; + const write = this.#state.setGatewaySession(this.#sessionBinding, null); + this.#inflight.add(write); + write.then(() => this.#inflight.delete(write), () => { + this.#admissionFailed = true; + this.#inflight.delete(write); + }); + }, + }, + } : {}), // Public option proposed by the maintained, hash-checked SDK build patch. onGatewayObservation: value => { if (!controller.signal.aborted && this.#abortController === controller) { + if (['parse-refused', 'processing-refused'].includes(value?.phase)) this.#admissionFailed = true; transportDiagnostics?.observe(value, controller.signal); if (transportDiagnostics) this.#status.transportObservation = transportDiagnostics.snapshot; } @@ -333,12 +372,16 @@ export class QqRuntime { try { const nativeUser = await bot.api.get('/users/@me'); const account = verifiedQqAccount(this.#config.appId, nativeUser); + this.#sessionBinding = createHash('sha256').update(JSON.stringify([ + this.#config.botId, account.fingerprint, this.#appSecret, + ])).digest('hex'); controller.signal.throwIfAborted(); gatewayDiagnostics = new QqNativeGatewayDiagnostics({ botId: this.#config.botId, account, report: record => this.#logger.info?.('[dsh-im:qq] native gateway diagnostic', record) }); transportDiagnostics = new QqNativeTransportDiagnostics({ account, report: record => this.#logger.info?.('[dsh-im:qq] native transport diagnostic', record) }); this.#externalBridge = new QqExternalConsumer({ bot, account, nativeUser, botId: this.#config.botId, + state: this.#state, accept: this.#externalConsumer, sourceImages: this.#sourceImages, sourceFiles: this.#sourceFiles, @@ -351,7 +394,7 @@ export class QqRuntime { reportNativeFrame: record => this.#logger.info?.('[dsh-im:qq] native reply frame', record), }); } catch (error) { - await this.stop(); + await this.stop({ drain: false }); throw error; } } @@ -370,6 +413,18 @@ export class QqRuntime { // QQ delivers emoji/face messages as opaque `` // tags. Parse them into readable text so the Harness sees what the sender // actually meant instead of an unusable markup fragment. + const trackedAdmission = Symbol('qq-inbound-admission'); + if (this.#config.consumerMode === 'external-consumer') bot.use((ctx, next) => { + if (!this.#accepting) return; + ctx.state[trackedAdmission] = true; + const pending = Promise.resolve().then(next); + this.#inflight.add(pending); + pending.then(() => this.#inflight.delete(pending), () => { + this.#admissionFailed = true; + this.#inflight.delete(pending); + }); + return pending; + }); bot.use(contentSanitizer({ parseFaceTags: true })); if (this.#config.consumerMode !== 'external-consumer') bot.use?.(this.#typingMiddleware({ keepAlive: true, @@ -419,6 +474,7 @@ export class QqRuntime { }; const onMessage = async (_ctx, message) => { if (controller.signal.aborted || this.#bot !== bot) return; + if (!this.#accepting && !_ctx?.state?.[trackedAdmission]) return; const elements = Array.isArray(message?.raw?.msg_elements) ? message.raw.msg_elements : []; const quotedAttachments = elements.slice(0, 2).flatMap(element => Array.isArray(element?.attachments) ? element.attachments.slice(0, 33) : []); @@ -475,7 +531,8 @@ export class QqRuntime { ? this.#externalBridge?.accept(message, controller.signal) : this.#bridge?.accept(message); if (!task) return; - return task.catch((error) => { + const pending = task.catch((error) => { + if (this.#config.consumerMode === 'external-consumer') this.#admissionFailed = true; if (controller.signal.aborted) return; lastInbound.refusalCode = typeof error?.code === 'string' && /^[a-z-]{1,64}$/.test(error.code) ? error.code : 'message-handling-failed'; @@ -487,12 +544,22 @@ export class QqRuntime { extractConnectionEvidence(error).details, ); }); + this.#inflight.add(pending); + pending.then(() => this.#inflight.delete(pending), () => this.#inflight.delete(pending)); + return pending; }; bot.on('ready', onReady); bot.on('resumed', onReady); bot.on('error', onError); bot.on('message', onMessage); + if (!receive && this.#config.consumerMode === 'external-consumer') { + this.#waitingForConsumer = true; + this.#accepting = false; + this.#status.ready = false; + this.#status.qqConnectionState = 'awaiting-consumer'; + return this.status; + } const runTask = Promise.resolve().then(() => bot.start(controller.signal)); this.#runTask = runTask; runTask.catch((error) => { @@ -523,35 +590,63 @@ export class QqRuntime { this.#status.qqConnectionState = 'failed'; this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError; this.#status.lastError = this.#status.error.message; - await this.stop(); + await this.stop({ drain: false }); throw error; } finally { clearTimeout(timer); } } - async stop() { + async stop({ drain = this.#config.consumerMode === 'external-consumer' } = {}) { + if (this.#stopping) return this.#stopping; const bot = this.#bot; + if (!bot) return this.status; const bridge = this.#bridge; const runTask = this.#runTask; - this.#abortController?.abort(); - this.#abortController = null; - this.#bot = null; - this.#bridge = null; - this.#externalBridge = null; - this.#runTask = null; - try { - bot?.stop(); - } catch (error) { - this.#logger.warn?.(`[dsh-im:qq] bot ${this.#config.botId} failed to stop cleanly:`, extractConnectionEvidence(error).details); - } - await Promise.race([ - runTask?.catch(() => undefined) ?? Promise.resolve(), - new Promise((resolve) => setTimeout(resolve, 2_000)), - ]); - await bridge?.waitForIdle(); + const controller = this.#abortController; + this.#accepting = false; + this.#draining = drain; this.#status.ready = false; - this.#status.qqConnectionState = 'idle'; - return this.status; + this.#status.qqConnectionState = drain ? 'draining' : 'idle'; + const session = structuredClone(this.#gatewaySession); + this.#stopping = (async () => { + try { + if (!drain) controller?.abort(); + bot.stop(); + if (drain) { + while (this.#inflight.size) await Promise.allSettled([...this.#inflight]); + if (this.#admissionFailed) throw qqRefusal('admission-unresolved'); + if (session && this.#state.setGatewaySession) + await this.#state.setGatewaySession(this.#sessionBinding, session); + } + } finally { + controller?.abort(); + this.#abortController = null; + this.#bot = null; + this.#bridge = null; + this.#externalBridge = null; + this.#runTask = null; + this.#draining = false; + this.#waitingForConsumer = false; + await Promise.race([ + runTask?.catch(() => undefined) ?? Promise.resolve(), + new Promise(resolve => setTimeout(resolve, 2_000)), + ]); + await bridge?.waitForIdle(); + this.#status.ready = false; + this.#status.qqConnectionState = 'idle'; + } + return this.status; + })(); + try { return await this.#stopping; } + finally { this.#stopping = null; } + } + + async quiesce() { + await this.stop({ drain: true }); + if (this.#admissionFailed) throw qqRefusal('admission-unresolved'); + const saved = this.#state.gatewaySession?.(this.#sessionBinding); + return { stopped: true, resumeCursor: Boolean(saved && this.#gatewaySession + && saved.sessionId === this.#gatewaySession.sessionId && saved.lastSeq === this.#gatewaySession.lastSeq) }; } } diff --git a/src/channels/qq/state-store.mjs b/src/channels/qq/state-store.mjs index 0f754ff78..97a93cf12 100644 --- a/src/channels/qq/state-store.mjs +++ b/src/channels/qq/state-store.mjs @@ -1,11 +1,53 @@ import { deferredStateAccess, normalizeDeferredState } from '../shared/deferred-state.mjs'; -import { randomUUID } from 'node:crypto'; +import { createHash, randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; import fs from 'node:fs/promises'; -import { dirname } from 'node:path'; +import { dirname, join } from 'node:path'; import { qqStateError } from './state-error.mjs'; const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [] }); +export function qqContentHash(text) { + if (typeof text !== 'string') throw new TypeError('QQ source text must be a string'); + return createHash('sha256').update(JSON.stringify(text)).digest('hex'); +} + +/** Create the same compact source proof from native content or its retained hash. */ +export function createQqReplyProof({ fingerprint, route, kind, at, mentionedAccount, contentHash, + contentHashAlgorithm = 'sha256-json-string-v1', attempts = 0, sequence = 0 }) { + if (!/^[a-f0-9]{64}$/.test(contentHash ?? '')) throw new TypeError('Invalid QQ content hash'); + if (contentHashAlgorithm !== 'sha256-json-string-v1') throw new TypeError('Unsupported QQ content hash algorithm'); + if (!route || Object.keys(route).some(key => !['messageId', 'conversationId', 'actorId'].includes(key))) + throw new TypeError('Invalid QQ source route'); + const identity = { route: { messageId: route.messageId, conversationId: route.conversationId, actorId: route.actorId }, + kind, at: new Date(at).toISOString(), mentionedAccount, contentHash, contentHashAlgorithm, + }; + const proof = { fingerprint, ...identity, attempts, sequence, + digest: createHash('sha256').update(JSON.stringify(identity)).digest('hex') }; + if (!validReplyProof(proof)) throw new TypeError('Invalid QQ source proof'); + return proof; +} + +function validReplyProof(value) { + return value && /^[a-f0-9]{64}$/.test(value.fingerprint ?? '') + && /^[a-f0-9]{64}$/.test(value.digest ?? '') + && ['messageId', 'conversationId', 'actorId'].every(key => + typeof value.route?.[key] === 'string' && value.route[key].length > 0) + && ['dm', 'group'].includes(value.kind) + && typeof value.mentionedAccount === 'boolean' + && /^[a-f0-9]{64}$/.test(value.contentHash ?? '') + && value.contentHashAlgorithm === 'sha256-json-string-v1' + && Number.isFinite(Date.parse(value.at)) + && Number.isSafeInteger(value.attempts) && value.attempts >= 0 + && Number.isSafeInteger(value.sequence) && value.sequence >= value.attempts; +} + +function validGatewaySession(value) { + return value && /^[a-f0-9]{64}$/.test(value.binding ?? '') + && typeof value.sessionId === 'string' && value.sessionId.length > 0 + && Number.isSafeInteger(value.lastSeq) && value.lastSeq >= 0; +} + function normalizeState(value) { if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE); const sessions = {}; @@ -21,6 +63,10 @@ function normalizeState(value) { sessions, includeArchivedSessions: value.includeArchivedSessions === true, ...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}), + ...(validGatewaySession(value.gatewaySession) ? { gatewaySession: { + binding: value.gatewaySession.binding, sessionId: value.gatewaySession.sessionId, + lastSeq: value.gatewaySession.lastSeq, + } } : {}), seenMessageIds: Array.isArray(value.seenMessageIds) ? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000) : [], @@ -39,6 +85,32 @@ export class QqStateStore { this.#logger = logger; } + async #syncDirectory(path) { + // Node cannot open directory handles for fsync on Windows. File data is still flushed. + if (process.platform === 'win32') return; + const handle = await fs.open(path, 'r'); + try { await handle.sync(); } + finally { await handle.close(); } + } + + async #writeDurably(path, bytes, exclusive = false) { + const directory = dirname(path); + await fs.mkdir(directory, { recursive: true, mode: 0o700 }); + const boundary = dirname(dirname(this.#path)); + let current = directory; + while (true) { + await this.#syncDirectory(current); + if (current === boundary || current === dirname(current)) break; + current = dirname(current); + } + const temporary = exclusive ? path : `${path}.tmp`; + const handle = await fs.open(temporary, exclusive ? 'wx' : 'w', 0o600); + try { await handle.writeFile(bytes); await handle.sync(); } + finally { await handle.close(); } + if (!exclusive) await fs.rename(temporary, path); + await this.#syncDirectory(directory); + } + async load() { let bytes; try { @@ -59,7 +131,7 @@ export class QqStateStore { try { // Copy the exact bytes before replacing anything. A failed rebuild // leaves both the original and this exclusive backup available. - await fs.writeFile(backup, bytes, { flag: 'wx', mode: 0o600 }); + await this.#writeDurably(backup, bytes, true); } catch (cause) { throw qqStateError('state-backup-failed', cause); } @@ -77,6 +149,112 @@ export class QqStateStore { patchDeferred(id, patch) { return this.#deferred.patch(id, patch); } removeDeferred(id) { return this.#deferred.remove(id); } + #proofPath(fingerprint, messageId) { + if (!/^[a-f0-9]{64}$/.test(fingerprint ?? '') || typeof messageId !== 'string' || !messageId || messageId.length > 512) + throw new TypeError('Invalid QQ proof key'); + return join(`${this.#path}.reply-proofs`, fingerprint, `${createHash('sha256').update(messageId).digest('hex')}.json`); + } + + replyProof(fingerprint, messageId) { + try { + const proof = JSON.parse(readFileSync(this.#proofPath(fingerprint, messageId), 'utf8')); + if (!validReplyProof(proof) || proof.fingerprint !== fingerprint || proof.route.messageId !== messageId) + throw new TypeError('QQ proof identity differs'); + return proof; + } catch (error) { + if (error.code === 'ENOENT') return undefined; + throw qqStateError('state-read-failed', error); + } + } + + replyProofFile(fingerprint, messageId) { return this.#proofPath(fingerprint, messageId); } + + async #updateReplyProof(fingerprint, messageId, update) { + const operation = this.#writeQueue.then(async () => { + const previous = this.replyProof(fingerprint, messageId); + const next = update(previous); + if (next === undefined) return previous; + const path = this.#proofPath(fingerprint, messageId); + try { + if (next === null) { + await fs.rm(path, { force: true }); + let directory = dirname(path); + while (true) { + try { await this.#syncDirectory(directory); break; } + catch (error) { + if (error.code !== 'ENOENT' || directory === dirname(directory)) throw error; + directory = dirname(directory); + } + } + return undefined; + } + if (!validReplyProof(next)) throw new TypeError('Invalid QQ reply proof'); + await this.#writeDurably(path, `${JSON.stringify(next)}\n`); + return next; + } catch (error) { throw qqStateError('state-write-failed', error); } + }); + this.#writeQueue = operation.then(() => undefined, () => undefined); + return operation; + } + + async putReplyProof(value) { + if (!validReplyProof(value)) throw new TypeError('Invalid QQ reply proof'); + await this.#updateReplyProof(value.fingerprint, value.route.messageId, prior => { + if (prior) { + if (prior.digest !== value.digest) + throw Object.assign(new Error('QQ source changed'), { code: 'stale-route' }); + return prior; + } + return structuredClone(value); + }); + } + + async reserveReplyAttempt(fingerprint, messageId, limit, sequence) { + const proof = await this.#updateReplyProof(fingerprint, messageId, proof => { + if (!proof) throw Object.assign(new Error('QQ source unavailable'), { code: 'source-not-found' }); + if (proof.attempts >= limit) throw Object.assign(new Error('QQ reply budget exhausted'), { code: 'reply-limit-exceeded' }); + proof.attempts++; + if (sequence === undefined) sequence = ++proof.sequence; + return proof; + }); + return { attempts: proof.attempts, sequence }; + } + + async refundReplyAttempt(fingerprint, messageId) { + await this.#updateReplyProof(fingerprint, messageId, proof => { + if (proof) proof.attempts = Math.max(0, proof.attempts - 1); + return proof; + }); + } + + async releaseReplyProof(fingerprint, route) { + let retainUntil; + let retained = false; + await this.#updateReplyProof(fingerprint, route.messageId, proof => { + if (!proof) return null; + if (['messageId', 'conversationId', 'actorId'].some(key => proof.route[key] !== route[key])) + throw Object.assign(new Error('QQ source changed'), { code: 'stale-route' }); + retainUntil = Date.parse(proof.at) + (proof.kind === 'dm' ? 3600000 : 300000); + retained = (proof.attempts > 0 || proof.sequence > 0) && retainUntil > Date.now(); + return retained ? { ...proof, completed: true } : null; + }); + return { released: true, ...(retained ? { retainUntil } : {}) }; + } + + gatewaySession(binding) { + const value = this.#state.gatewaySession; + return value?.binding === binding ? { sessionId: value.sessionId, lastSeq: value.lastSeq } : null; + } + + async setGatewaySession(binding, session) { + if (session !== null && !validGatewaySession({ binding, ...session })) + throw new TypeError('Invalid QQ gateway session'); + await this.#persist(state => { + if (session === null) delete state.gatewaySession; + else state.gatewaySession = { binding, sessionId: session.sessionId, lastSeq: session.lastSeq }; + }, 'gatewaySession'); + } + includesArchivedSessions() { return this.#state.includeArchivedSessions === true; } async setIncludeArchivedSessions(include) { @@ -121,23 +299,36 @@ export class QqStateStore { } async remove() { + await this.#writeQueue; + await fs.rm(`${this.#path}.reply-proofs`, { recursive: true, force: true }); try { await fs.unlink(this.#path); } catch (error) { if (error?.code !== 'ENOENT') throw error; } + await this.#syncDirectory(dirname(this.#path)); this.#state = structuredClone(EMPTY_STATE); } - async #persist() { - const snapshot = `${JSON.stringify(this.#state, null, 2)}\n`; + async #persist(update, field) { + let result; + let writing = false; const operation = this.#writeQueue.then(async () => { - await fs.mkdir(dirname(this.#path), { recursive: true, mode: 0o700 }); - const temporary = `${this.#path}.tmp`; - await fs.writeFile(temporary, snapshot, { encoding: 'utf8', mode: 0o600 }); - await fs.rename(temporary, this.#path); + const next = update ? { ...this.#state, [field]: structuredClone(this.#state[field]) } : this.#state; + result = update?.(next); + const snapshot = `${JSON.stringify(next, null, 2)}\n`; + writing = true; + await this.#writeDurably(this.#path, snapshot); + if (update) { + if (Object.hasOwn(next, field)) this.#state[field] = next[field]; + else delete this.#state[field]; + } }); this.#writeQueue = operation.then(() => undefined, () => undefined); - await operation.catch(error => { throw qqStateError('state-write-failed', error); }); + await operation.catch(error => { + if (!writing) throw error; + throw qqStateError('state-write-failed', error); + }); + return result; } } diff --git a/src/channels/shared/exclusive-inbound-consumers.mjs b/src/channels/shared/exclusive-inbound-consumers.mjs index 29ba83ee7..9d517f6ca 100644 --- a/src/channels/shared/exclusive-inbound-consumers.mjs +++ b/src/channels/shared/exclusive-inbound-consumers.mjs @@ -5,6 +5,8 @@ function refusal(code) { export class ExclusiveInboundConsumers { #entries = new Map(); + isRegistered(botId) { return this.#entries.has(botId); } + acceptsFiles(botId) { return this.#entries.get(botId)?.sourceFiles === true; } acceptsImages(botId) { return this.#entries.get(botId)?.sourceImages === true; } acceptsVoiceTranscripts(botId) { return this.#entries.get(botId)?.sourceVoiceTranscripts === true; } @@ -56,7 +58,7 @@ export class ExclusiveInboundConsumers { deliverySignal.throwIfAborted(); if (this.#entries.get(botId) !== entry) throw refusal('consumer-unavailable'); if (result?.accepted !== true) throw refusal('ingress-not-accepted'); - return { accepted: true }; + return { accepted: true, ...(result.complete === true ? { complete: true } : {}) }; } async acceptAction(botId, evidence, signal) { diff --git a/test/channels/qq/checked-files.test.mjs b/test/channels/qq/checked-files.test.mjs index f374f665c..58c702f7e 100644 --- a/test/channels/qq/checked-files.test.mjs +++ b/test/channels/qq/checked-files.test.mjs @@ -67,9 +67,10 @@ async function fixture(t, { sourceImages = false, sourceFiles = true, production }); controller = created.controller; productionAdapter = created.deliveryAdapter; - t.after(() => created.close()); + t.after(async () => { await controller.close({ drain: false }); await created.close(); }); } - t.after(() => controller.close()); + // Negative admission fixtures cancel explicitly instead of requesting a resumable drain. + t.after(() => controller.close({ drain: false })); await controller.initialize(); const service = createDeliveryService(); const unregister = service.registerAdapter(productionAdapter ?? createDeliveryAdapter({ channel: 'qq', diff --git a/test/channels/qq/checked-images.test.mjs b/test/channels/qq/checked-images.test.mjs index 318e31d42..6b746ecf2 100644 --- a/test/channels/qq/checked-images.test.mjs +++ b/test/channels/qq/checked-images.test.mjs @@ -67,9 +67,10 @@ async function fixture(t, { sourceImages = true, production = false } = {}) { }); controller = created.controller; productionAdapter = created.deliveryAdapter; - t.after(() => created.close()); + t.after(async () => { await controller.close({ drain: false }); await created.close(); }); } - t.after(() => controller.close()); + // Negative admission fixtures cancel explicitly instead of requesting a resumable drain. + t.after(() => controller.close({ drain: false })); await controller.initialize(); const service = createDeliveryService(); const unregister = service.registerAdapter(productionAdapter ?? createDeliveryAdapter({ channel: 'qq', diff --git a/test/channels/qq/checked-voice.test.mjs b/test/channels/qq/checked-voice.test.mjs index 6d9e18038..e94ee89e5 100644 --- a/test/channels/qq/checked-voice.test.mjs +++ b/test/channels/qq/checked-voice.test.mjs @@ -67,9 +67,10 @@ async function fixture(t, { sourceImages = false, sourceFiles = false, sourceVoi }); controller = created.controller; productionAdapter = created.deliveryAdapter; - t.after(() => created.close()); + t.after(async () => { await controller.close({ drain: false }); await created.close(); }); } - t.after(() => controller.close()); + // Negative admission fixtures cancel explicitly instead of requesting a resumable drain. + t.after(() => controller.close({ drain: false })); await controller.initialize(); const service = createDeliveryService(); const unregister = service.registerAdapter(productionAdapter ?? createDeliveryAdapter({ channel: 'qq', diff --git a/test/channels/qq/external-consumer.test.mjs b/test/channels/qq/external-consumer.test.mjs index 7e0864262..3c8d370ef 100644 --- a/test/channels/qq/external-consumer.test.mjs +++ b/test/channels/qq/external-consumer.test.mjs @@ -62,7 +62,7 @@ async function fixture(t, logger) { createBot: () => { bot = new PlatformBot(); return bot; }, }), }); - t.after(() => controller.close()); + t.after(() => controller.close({ drain: false })); await controller.initialize(); return { controller, store, botId: identity.botId, bot: () => bot, standaloneRuns: () => standaloneRuns }; } diff --git a/test/channels/qq/normal-update.test.mjs b/test/channels/qq/normal-update.test.mjs new file mode 100644 index 000000000..0634e17a1 --- /dev/null +++ b/test/channels/qq/normal-update.test.mjs @@ -0,0 +1,313 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { once } from 'node:events'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { WebSocketServer } from 'ws'; +import { QQBot } from '@tencent-connect/qqbot-nodejs'; +import { QqRuntime } from '../../../src/channels/qq/qq-runtime.mjs'; +import { QqStateStore } from '../../../src/channels/qq/state-store.mjs'; +import { QqController } from '../../../src/channels/qq/qq-controller.mjs'; +import { QqConfigStore, deriveQqBotIdentity } from '../../../src/channels/qq/config-store.mjs'; +import { Context, Service } from '@deepseek-ai/cordis'; +import { createDeliveryService } from '../../../plugin-src/host/delivery-service.mjs'; +import { createDeliveryAdapter } from '../../../plugin-src/host/delivery-adapter.mjs'; +import { installProductionChannel } from '../../../plugin-src/host/channels/shared/startup.mjs'; +import { managementFetch } from '../../fixtures/management-rpc.mjs'; + +function deferred() { + let resolve; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} + +async function fixture(t) { + const directory = await mkdtemp(join(tmpdir(), 'qq-normal-update-')); + const path = join(directory, 'state.json'); + const handshakes = []; + const offline = []; + const posts = []; + const server = createServer(async (request, response) => { + let body = ''; + for await (const chunk of request) body += chunk; + const data = request.url.includes('getAppAccessToken') ? { access_token: 'fixture-token', expires_in: 7200 } + : request.url === '/gateway' ? { url: `ws://127.0.0.1:${server.address().port}` } + : request.url === '/users/@me' ? { id: 'native-bot', bot: true } + : (posts.push(JSON.parse(body)), { id: `sent-${posts.length}` }); + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify(data)); + }); + const sockets = new WebSocketServer({ server }); + let socket; + sockets.on('connection', client => { + socket = client; + client.send(JSON.stringify({ op: 10, d: { heartbeat_interval: 60000 } })); + client.on('message', bytes => { + const request = JSON.parse(bytes.toString()); + if (![2, 6].includes(request.op)) return; + handshakes.push(request); + client.send(JSON.stringify({ op: 0, t: request.op === 6 ? 'RESUMED' : 'READY', + s: request.op === 6 ? request.d.seq + (offline.length ? 0 : 1) : 1, + d: { session_id: 'gateway-session', user: { id: 'native-bot', bot: true } } })); + if (request.op === 6) for (const payload of offline.splice(0)) client.send(JSON.stringify(payload)); + }); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const url = `http://127.0.0.1:${server.address().port}`; + const originalFetch = globalThis.fetch; + globalThis.fetch = (input, options) => { + assert.equal(new URL(String(input)).origin, url, 'HTTP fixture must stay on loopback'); + return originalFetch(input, options); + }; + const runtimes = []; + t.after(async () => { + for (const runtime of runtimes) await runtime.stop({ drain: false }); + for (const client of sockets.clients) client.terminate(); + await new Promise(resolve => sockets.close(resolve)); + server.closeAllConnections(); + await new Promise(resolve => server.close(resolve)); + globalThis.fetch = originalFetch; + await rm(directory, { recursive: true, force: true }); + }); + const runtime = (state, accept, beforeListener, config = { botId: 'qq-fixture', appId: 'application-one', consumerMode: 'external-consumer' }) => { + const value = new QqRuntime({ config, + appSecret: 'fixture-secret', state, harness: {}, externalConsumer: accept, + logger: { debug() {}, info() {}, warn() {}, error() {} }, connectTimeoutMs: 5000, + createBot: options => { + const bot = new QQBot({ ...options, baseUrl: url, tokenBaseUrl: url }); + if (beforeListener) bot.on('message', beforeListener); + return bot; + } }); + runtimes.push(value); + return value; + }; + const send = (sequence = 2) => socket.send(JSON.stringify({ op: 0, s: sequence, t: 'GROUP_AT_MESSAGE_CREATE', + d: { id: 'original-message', group_openid: 'original-group', author: { member_openid: 'original-member' }, + content: 'question', timestamp: new Date().toISOString() } })); + const queueOffline = () => offline.push({ op: 0, s: 3, t: 'GROUP_AT_MESSAGE_CREATE', + d: { id: 'offline-message', group_openid: 'original-group', author: { member_openid: 'original-member' }, + content: 'received while stopped', timestamp: new Date().toISOString() } }); + return { path, runtime, send, handshakes, posts, queueOffline }; +} + +test('normal shutdown waits for callbacks and canonical acceptance before saving a resumable cursor', async t => { + const fx = await fixture(t); + const priorStarted = deferred(); + const priorContinue = deferred(); + const acceptedStarted = deferred(); + const acceptedContinue = deferred(); + let source; + const state = await new QqStateStore(fx.path).load(); + const runtime = fx.runtime(state, async event => { + source = event; + acceptedStarted.resolve(); + await acceptedContinue.promise; + return { accepted: true }; + }, async () => { priorStarted.resolve(); await priorContinue.promise; }); + await runtime.start(); + fx.send(); + await priorStarted.promise; + let stopped = false; + const stopping = runtime.stop().then(() => { stopped = true; }); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(stopped, false); + priorContinue.resolve(); + await acceptedStarted.promise; + assert.equal(stopped, false); + assert.equal(state.snapshot().gatewaySession, undefined); + assert.equal((await runtime.describeDeliveryAccount()).appId, 'application-one'); + acceptedContinue.resolve(); + await stopping; + assert.equal(state.snapshot().gatewaySession.lastSeq, 2); + fx.queueOffline(); + const restoredState = await new QqStateStore(fx.path).load(); + const replayed = deferred(); + const replayedMessages = []; + const restored = fx.runtime(restoredState, async event => { + replayedMessages.push(event.messageId); replayed.resolve(); return { accepted: true }; + }); + await restored.start(); + await replayed.promise; + assert.deepEqual(replayedMessages, ['offline-message']); + assert.equal(fx.handshakes[1].op, 6); + assert.equal(fx.handshakes[1].d.session_id, 'gateway-session'); + assert.equal(fx.handshakes[1].d.seq, 2); + const receipt = await restored.replyChecked(source.reply, 'later answer', + { signal: new AbortController().signal, beforeSend: () => true, receipt: true }); + assert.equal(receipt.receipt.messageId, 'sent-1'); + assert.equal(fx.posts[0].msg_id, 'original-message'); +}); + +test('canonical rejection swallowed by the SDK still prevents a shutdown checkpoint', async t => { + const fx = await fixture(t); + const handled = deferred(); + const state = await new QqStateStore(fx.path).load(); + const runtime = fx.runtime(state, async () => { handled.resolve(); return { accepted: false }; }); + await runtime.start(); + fx.send(); + await handled.promise; + await assert.rejects(() => runtime.stop(), { code: 'admission-unresolved' }); + assert.equal((await new QqStateStore(fx.path).load()).snapshot().gatewaySession, undefined); + assert.equal(fx.posts.length, 0); +}); + +test('controller close retains the receiver lease and account read until durable admission completes', async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + const config = await new QqConfigStore(`${fx.path}.config`).load(); + const identity = deriveQqBotIdentity('application-one'); + await config.save({ ...identity, appId: 'application-one', ownerUserOpenid: 'owner', consumerMode: 'external-consumer' }); + const controller = new QqController({ configStore: config, qrAuth: { start() {} }, + credentials: { resolve: async () => ({ value: 'fixture-secret' }), set: async () => {}, unset: async () => {} }, + createRuntime: async args => fx.runtime(state, args.externalConsumer, undefined, args.config), + logger: { debug() {}, info() {}, warn() {}, error() {} }, + }); + t.after(() => controller.close({ drain: false })); + await controller.initialize(); + const account = await controller.describeDeliveryAccount(identity.botId); + const admitted = deferred(); + const continueAdmission = deferred(); + let acceptanceSignal; + await controller.consumeInbound(identity.botId, { expectedFingerprint: account.account.fingerprint, + onEvent: async (_event, { signal }) => { + acceptanceSignal = signal; + admitted.resolve(); + await continueAdmission.promise; + assert.equal(signal.aborted, false); + assert.equal((await controller.describeDeliveryAccount(identity.botId)).account.fingerprint, account.account.fingerprint); + return { accepted: true }; + } }); + fx.send(); + await admitted.promise; + const closing = controller.close(); + await assert.rejects(() => controller.startProvisioning(), /closed/); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(acceptanceSignal.aborted, false); + continueAdmission.resolve(); + await closing; + assert.equal(acceptanceSignal.aborted, true); + assert.equal((await new QqStateStore(fx.path).load()).snapshot().gatewaySession.lastSeq, 2); +}); + +test('native dependent disposal drains the original provider before releasing its receiver lease', async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + const config = await new QqConfigStore(`${fx.path}.config`).load(); + const identity = deriveQqBotIdentity('application-one'); + await config.save({ ...identity, appId: 'application-one', ownerUserOpenid: 'owner', consumerMode: 'external-consumer' }); + const controller = new QqController({ configStore: config, qrAuth: { start() {} }, + credentials: { resolve: async () => ({ value: 'fixture-secret' }), set: async () => {}, unset: async () => {} }, + createRuntime: async args => fx.runtime(state, args.externalConsumer, undefined, args.config), + logger: { debug() {}, info() {}, warn() {}, error() {} }, + }); + const delivery = createDeliveryService(); + const adapter = createDeliveryAdapter({ channel: 'qq', coreController: controller, stateFor: async () => state, + workspaces: { has: id => id === identity.botId, listBotIds: () => [identity.botId], listDeliveryTargets: () => [] } }); + const ctx = new Context(); + class Connection extends Service { + constructor(context) { super(context, 'connection'); } + get fetch() { return managementFetch(() => this.ctx.effect(() => () => {}, 'fixture management route')); } + } + new Connection(ctx); + const publicService = { + consumeInbound: (id, options) => delivery.consumeInbound(id, options), + quiesceInbound: (id, options) => delivery.quiesceInbound(id, options), + describeBot: id => delivery.describeBot(id), + }; + const provider = ctx.plugin({ name: 'qq-provider-update-fixture', inject: ['connection'], async apply(child) { + child.provide('dshIm', publicService); + await controller.initialize(); + await installProductionChannel(child, { deliveryService: delivery }, { channel: 'qq', rpcChannel: '/qq', + createProduction: async () => ({ controller, deliveryAdapter: adapter, + prepareClose: () => controller.close(), close: () => controller.close() }), + createHandler: () => async () => ({ ok: true }), + }); + } }); + await provider; + const account = await delivery.describeBot(identity.botId); + const admitted = deferred(); + const commit = deferred(); + const receiver = new AbortController(); + let eventSignal; + let drainReceipt; + const consumer = ctx.plugin({ name: 'qq-consumer-update-fixture', inject: ['dshIm'], async apply(child) { + const service = child.get('dshIm'); + const dispose = await service.consumeInbound(identity.botId, { + expectedFingerprint: account.account.fingerprint, signal: receiver.signal, + onEvent: async (_event, { signal }) => { + eventSignal = signal; + admitted.resolve(); + await commit.promise; + assert.equal(signal.aborted, false); + assert.equal((await service.describeBot(identity.botId)).account.fingerprint, account.account.fingerprint); + return { accepted: true }; + }, + }); + child.effect(() => async () => { + drainReceipt = await service.quiesceInbound(identity.botId, { expectedFingerprint: account.account.fingerprint }); + receiver.abort(); + dispose(); + }, 'drain before removing the consumer'); + } }); + await consumer; + t.after(async () => { commit.resolve(); await consumer.dispose(); await provider.dispose(); }); + fx.send(); + await admitted.promise; + const closing = provider.dispose(); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(eventSignal.aborted, false); + assert.equal(state.snapshot().gatewaySession, undefined); + commit.resolve(); + await closing; + assert.deepEqual(drainReceipt, { stopped: true, resumeCursor: true }); + assert.equal(eventSignal.aborted, true); + assert.equal((await new QqStateStore(fx.path).load()).snapshot().gatewaySession.lastSeq, 2); +}); + +test('a quiesced receiver stays stopped until a new exclusive consumer registers', async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + const config = await new QqConfigStore(`${fx.path}.config`).load(); + const identity = deriveQqBotIdentity('application-one'); + await config.save({ ...identity, appId: 'application-one', ownerUserOpenid: 'owner', consumerMode: 'external-consumer' }); + const controller = new QqController({ configStore: config, qrAuth: { start() {} }, + credentials: { resolve: async () => ({ value: 'fixture-secret' }), set: async () => {}, unset: async () => {} }, + createRuntime: async args => fx.runtime(state, args.externalConsumer, undefined, args.config), + logger: { debug() {}, info() {}, warn() {}, error() {} }, + }); + t.after(() => controller.close({ drain: false })); + await controller.initialize(); + const fingerprint = (await controller.describeDeliveryAccount(identity.botId)).account.fingerprint; + const admitted = deferred(); + let source; + const dispose = await controller.consumeInbound(identity.botId, { expectedFingerprint: fingerprint, + onEvent: async event => { source = event; admitted.resolve(); return { accepted: true }; } }); + fx.send(); + await admitted.promise; + assert.deepEqual(await controller.quiesceInbound(identity.botId, { expectedFingerprint: fingerprint }), + { stopped: true, resumeCursor: true }); + const before = fx.handshakes.length; + await controller.initialize(); + await assert.rejects(() => controller.reconnectBot(identity.botId), { code: 'provider-unavailable' }); + await assert.rejects(() => controller.consumeInbound(identity.botId, + { expectedFingerprint: fingerprint, onEvent: async () => ({ accepted: true }) }), { code: 'consumer-conflict' }); + assert.equal(fx.handshakes.length, before); + dispose(); + assert.deepEqual(await controller.resumeInbound(identity.botId, { expectedFingerprint: fingerprint }), { connected: false, accountVerified: true }); + assert.equal((await controller.describeDeliveryAccount(identity.botId)).connected, false); + await controller.consumeInbound(identity.botId, + { expectedFingerprint: fingerprint, onEvent: async () => ({ accepted: true }) }); + assert.deepEqual(await controller.qualifyReplyChecked(identity.botId, source.reply, + { expectedFingerprint: fingerprint }), source.reply); + assert.ok(fx.handshakes.slice(before).every(value => value.op === 6 && value.d.seq === 2)); + const service = createDeliveryService(); + const unregister = service.registerAdapter(createDeliveryAdapter({ channel: 'qq', coreController: controller, + stateFor: async () => state, workspaces: { has: id => id === identity.botId } })); + t.after(unregister); + assert.deepEqual(await service.releaseSource(identity.botId, source.reply, + { expectedFingerprint: fingerprint }), { released: true }); + assert.equal(state.replyProof(fingerprint, source.messageId), undefined); +}); diff --git a/test/channels/qq/reply-continuity.test.mjs b/test/channels/qq/reply-continuity.test.mjs new file mode 100644 index 000000000..aeddf56d9 --- /dev/null +++ b/test/channels/qq/reply-continuity.test.mjs @@ -0,0 +1,263 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { createHash } from 'node:crypto'; +import { once } from 'node:events'; +import { mkdtemp, mkdir, readFile, rm } from 'node:fs/promises'; +import fs from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import test from 'node:test'; +import { QQBot } from '@tencent-connect/qqbot-nodejs'; +import { QqExternalConsumer, verifiedQqAccount } from '../../../src/channels/qq/external-consumer.mjs'; +import { QqStateStore } from '../../../src/channels/qq/state-store.mjs'; + +async function fixture(t) { + const directory = await mkdtemp(join(tmpdir(), 'qq-reply-continuity-')); + const path = join(directory, 'state.json'); + const posts = []; + let uncertain = false; + const server = createServer(async (request, response) => { + let body = ''; + for await (const chunk of request) body += chunk; + if (request.url.includes('getAppAccessToken')) { + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify({ access_token: 'fixture-token', expires_in: 7200 })); + return; + } + posts.push({ path: request.url, body: JSON.parse(body) }); + if (uncertain) { request.socket.destroy(); return; } + response.setHeader('content-type', 'application/json'); + response.end(JSON.stringify({ id: `reply-${posts.length}` })); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.after(async () => { + server.closeAllConnections(); + await new Promise(resolve => server.close(resolve)); + await rm(directory, { recursive: true, force: true }); + }); + const url = `http://127.0.0.1:${server.address().port}`; + const originalFetch = globalThis.fetch; + globalThis.fetch = (input, options) => { + assert.equal(new URL(String(input)).origin, url, 'HTTP fixture must stay on loopback'); + return originalFetch(input, options); + }; + t.after(() => { globalThis.fetch = originalFetch; }); + const account = verifiedQqAccount('application-one', { id: 'native-bot', bot: true }); + const signal = new AbortController().signal; + let accepted = 0; + const consumer = state => new QqExternalConsumer({ + bot: new QQBot({ appId: account.appId, appSecret: 'fixture-secret', + baseUrl: url, tokenBaseUrl: url, logger: { debug() {}, info() {}, warn() {}, error() {} } }), + botId: 'fixture-bot', account, state, + accept: async () => { accepted++; return { accepted: true }; }, + }); + const message = { + kind: 'group', rawEventType: 'GROUP_AT_MESSAGE_CREATE', messageId: 'original-message', + senderId: 'original-member', groupOpenid: 'original-group', content: 'private canonical body', + timestamp: new Date().toISOString(), + replyTarget: { scope: 'group', targetId: 'original-group', msgId: 'original-message' }, + }; + const route = { messageId: message.messageId, actorId: message.senderId, conversationId: message.groupOpenid }; + return { path, posts, account, signal, consumer, message, route, + accepted: () => accepted, uncertain: () => { uncertain = true; } }; +} + +test('original QQ source and send sequence survive a process-local consumer replacement', async t => { + const fx = await fixture(t); + const firstStore = await new QqStateStore(fx.path).load(); + const first = fx.consumer(firstStore); + await first.accept(fx.message, fx.signal); + await first.reply(fx.route, 'first answer', { signal: fx.signal, beforeSend: () => true }); + const restoredStore = await new QqStateStore(fx.path).load(); + const restored = fx.consumer(restoredStore); + assert.deepEqual(restored.qualify(fx.route, fx.signal), fx.route); + const result = await restored.reply(fx.route, 'later answer', { signal: fx.signal, receipt: true, beforeSend: () => true }); + assert.equal(result.receipt.messageId, 'reply-2'); + assert.deepEqual(fx.posts.map(post => post.body.msg_id), ['original-message', 'original-message']); + assert.deepEqual(fx.posts.map(post => post.body.msg_seq), [1, 2]); + assert.equal(fx.accepted(), 1); + assert.equal((await readFile(fx.path, 'utf8')).includes('private canonical body'), false); + assert.equal(restoredStore.replyProof(fx.account.fingerprint, fx.route.messageId).attempts, 2); + const other = new QqExternalConsumer({ bot: {}, botId: 'fixture-bot', state: restoredStore, + account: verifiedQqAccount('other-application', { id: 'other-bot', bot: true }), accept: async () => ({ accepted: true }) }); + assert.throws(() => other.qualify(fx.route, fx.signal), { code: 'source-not-found' }); +}); + +test('a failed proof write prevents canonical admission and native sending', async t => { + const fx = await fixture(t); + const store = await new QqStateStore(fx.path).load(); + const consumer = fx.consumer(store); + await mkdir(`${fx.path}.reply-proofs/${fx.account.fingerprint}/${createHash('sha256').update(fx.route.messageId).digest('hex')}.json.tmp`, { recursive: true }); + await assert.rejects(() => consumer.accept(fx.message, fx.signal), { code: 'state-write-failed' }); + assert.equal(fx.accepted(), 0); + assert.throws(() => consumer.qualify(fx.route, fx.signal), { code: 'source-not-found' }); + assert.throws(() => fx.consumer(store).qualify(fx.route, fx.signal), { code: 'source-not-found' }); + assert.equal(fx.posts.length, 0); +}); + +test('an uncertain real HTTP send occurs once and its attempted budget survives restart', async t => { + const fx = await fixture(t); + const store = await new QqStateStore(fx.path).load(); + const consumer = fx.consumer(store); + await consumer.accept(fx.message, fx.signal); + fx.uncertain(); + await assert.rejects(() => consumer.reply(fx.route, 'answer', { signal: fx.signal, beforeSend: () => true }), + { code: 'reply-result-unknown' }); + assert.equal(fx.posts.length, 1); + const restored = await new QqStateStore(fx.path).load(); + assert.equal(restored.replyProof(fx.account.fingerprint, fx.route.messageId).attempts, 1); + assert.equal(restored.replyProof(fx.account.fingerprint, fx.route.messageId).sequence, 1); + assert.deepEqual(fx.consumer(restored).qualify(fx.route, fx.signal), fx.route); + assert.equal(fx.posts.length, 1); +}); + +test('concurrent reply reservations allocate distinct durable sequences within the native budget', async t => { + const fx = await fixture(t); + const store = await new QqStateStore(fx.path).load(); + await fx.consumer(store).accept(fx.message, fx.signal); + const outcomes = await Promise.allSettled(Array.from({ length: 6 }, () => + store.reserveReplyAttempt(fx.account.fingerprint, fx.route.messageId, 5))); + assert.deepEqual(outcomes.filter(value => value.status === 'fulfilled').map(value => value.value.sequence), [1, 2, 3, 4, 5]); + assert.equal(outcomes[5].reason.code, 'reply-limit-exceeded'); + const restored = await new QqStateStore(fx.path).load(); + assert.throws(() => fx.consumer(restored).qualify(fx.route, fx.signal), { code: 'reply-limit-exceeded' }); + assert.equal(fx.posts.length, 0); +}); + +test('more than two thousand later messages cannot evict an unfinished original reply after restart', async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + const consumer = fx.consumer(state); + await consumer.accept(fx.message, fx.signal); + for (let index = 0; index < 2001; index++) { + const id = `later-${index}`; + await consumer.accept({ ...fx.message, messageId: id, + replyTarget: { ...fx.message.replyTarget, msgId: id } }, fx.signal); + } + assert.deepEqual(consumer.qualify(fx.route, fx.signal), fx.route); + const restored = fx.consumer(await new QqStateStore(fx.path).load()); + await restored.reply(fx.route, 'the original long task completed', { signal: fx.signal, beforeSend: () => true }); + assert.equal(fx.posts.length, 1); + assert.equal(fx.posts[0].body.msg_id, fx.route.messageId); + assert.equal(JSON.parse(await readFile(fx.path, 'utf8')).replyProofs, undefined); +}); + +test('completed sources keep their native budget through redelivery and expire on the original release call', async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + let consumer = fx.consumer(state); + await consumer.accept(fx.message, fx.signal); + await consumer.reply(fx.route, 'answer', { signal: fx.signal, beforeSend: () => true }); + const released = await consumer.release(fx.route, fx.signal); + assert.ok(released.retainUntil > Date.now()); + consumer = fx.consumer(await new QqStateStore(fx.path).load()); + await consumer.accept(fx.message, fx.signal); + assert.equal(state.replyProof(fx.account.fingerprint, fx.route.messageId).attempts, 1); + const clock = Date.now; + try { + Date.now = () => released.retainUntil + 1; + assert.deepEqual(await consumer.release(fx.route, fx.signal), { released: true }); + assert.equal(state.replyProof(fx.account.fingerprint, fx.route.messageId), undefined); + } finally { Date.now = clock; } +}); + +test('explicitly completed intake without any native attempt releases its proof immediately', async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + const consumer = new QqExternalConsumer({ bot: {}, botId: 'fixture-bot', account: fx.account, state, + accept: async () => ({ accepted: true, complete: true }) }); + await consumer.accept(fx.message, fx.signal); + assert.equal(state.replyProof(fx.account.fingerprint, fx.route.messageId), undefined); + await consumer.accept(fx.message, fx.signal); + assert.equal(state.replyProof(fx.account.fingerprint, fx.route.messageId), undefined); + assert.equal(fx.posts.length, 0); +}); + +test('source and attempt writes flush file data before rename and sync supported directories', async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + const events = []; + const originalOpen = fs.open, originalRename = fs.rename; + t.mock.method(fs, 'open', async (...args) => { + const handle = await originalOpen(...args); + const originalSync = handle.sync.bind(handle); + handle.sync = async () => { await originalSync(); events.push(['sync', String(args[0])]); }; + return handle; + }); + t.mock.method(fs, 'rename', async (from, to) => { await originalRename(from, to); events.push(['rename', to]); }); + await fx.consumer(state).accept(fx.message, fx.signal); + const path = state.replyProofFile(fx.account.fingerprint, fx.route.messageId); + const renamed = events.findIndex(event => event[0] === 'rename' && event[1] === path); + const synced = events.findIndex(event => event[0] === 'sync' && event[1] === `${path}.tmp`); + assert.ok(synced >= 0 && synced < renamed); + if (process.platform !== 'win32') { + assert.ok(events.slice(renamed + 1).some(event => event[0] === 'sync' && event[1] === dirname(path))); + assert.ok(events.some(event => event[0] === 'sync' && event[1] === `${fx.path}.reply-proofs`)); + } + events.length = 0; + await state.reserveReplyAttempt(fx.account.fingerprint, fx.route.messageId, 5); + const expected = process.platform === 'win32' ? ['sync', 'rename'] : ['sync', 'rename', 'sync']; + assert.deepEqual(events.map(event => event[0]).slice(-expected.length), expected); +}); + +test('a directory synchronization failure refuses admission and the retry repeats the durability barrier', + { skip: process.platform === 'win32' }, async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + const path = state.replyProofFile(fx.account.fingerprint, fx.route.messageId); + const directory = dirname(path); + const originalOpen = fs.open; + let fail = true, completedSyncs = 0; + t.mock.method(fs, 'open', async (...args) => { + const handle = await originalOpen(...args); + if (String(args[0]) === directory) { + const originalSync = handle.sync.bind(handle); + handle.sync = async () => { + const exists = await fs.stat(path).then(() => true, () => false); + if (exists && fail) { fail = false; throw new Error('fixture directory sync failure'); } + await originalSync(); if (exists) completedSyncs++; + }; + } + return handle; + }); + await assert.rejects(() => fx.consumer(state).accept(fx.message, fx.signal), { code: 'state-write-failed' }); + assert.equal(fx.accepted(), 0); + await fx.consumer(state).accept(fx.message, fx.signal); + assert.equal(fx.accepted(), 1); + assert.ok(completedSyncs > 0); +}); + +test('ancestor creation and completed-proof deletion retry their failed directory synchronization', + { skip: process.platform === 'win32' }, async t => { + const fx = await fixture(t); + const state = await new QqStateStore(fx.path).load(); + const path = state.replyProofFile(fx.account.fingerprint, fx.route.messageId); + const directory = dirname(path); + const originalOpen = fs.open; + let failAncestor = true, failRemoval = false, ancestorSynced = false, removalSynced = false; + t.mock.method(fs, 'open', async (...args) => { + const handle = await originalOpen(...args), sync = handle.sync.bind(handle); + handle.sync = async () => { + const name = String(args[0]); + if (name === `${fx.path}.reply-proofs` && failAncestor) { + failAncestor = false; throw new Error('fixture ancestor sync failure'); + } + if (name === directory && failRemoval) { + failRemoval = false; throw new Error('fixture deletion sync failure'); + } + await sync(); + if (name === `${fx.path}.reply-proofs`) ancestorSynced = true; + if (name === directory && !(await fs.stat(path).then(() => true, () => false))) removalSynced = true; + }; + return handle; + }); + const consumer = fx.consumer(state); + await assert.rejects(() => consumer.accept(fx.message, fx.signal), { code: 'state-write-failed' }); + assert.equal(fx.accepted(), 0); + await consumer.accept(fx.message, fx.signal); assert.equal(ancestorSynced, true); + failRemoval = true; removalSynced = false; + await assert.rejects(() => consumer.release(fx.route, fx.signal), { code: 'state-write-failed' }); + assert.deepEqual(await consumer.release(fx.route, fx.signal), { released: true }); + assert.equal(removalSynced, true); +}); diff --git a/test/channels/qq/sdk-observation-patch.test.mjs b/test/channels/qq/sdk-observation-patch.test.mjs index 788f249b9..08da0b3cf 100644 --- a/test/channels/qq/sdk-observation-patch.test.mjs +++ b/test/channels/qq/sdk-observation-patch.test.mjs @@ -7,6 +7,7 @@ import test from 'node:test'; import { build } from 'esbuild'; import { WebSocketServer } from 'ws'; import { patchQqObservationSource, qqSdkObservationPatch } from '../../../plugin-src/host/qq-sdk-observation-patch.mjs'; +import { QqStateStore } from '../../../src/channels/qq/state-store.mjs'; const packageRoot = resolve(import.meta.dirname, '../../..'); const json = value => new Response(JSON.stringify(value), { headers: { 'content-type': 'application/json' } }); @@ -51,8 +52,9 @@ test('the production build patch observes real WS messages before decode and pre const records = []; const logs = []; const admitted = []; + const state = await new QqStateStore(join(directory, 'state.json')).load(); const runtime = new QqRuntime({ config: { appId: 'test-app', botId: 'test-bot', consumerMode: 'external-consumer' }, - appSecret: 'private-secret', state: {}, harness: {}, + appSecret: 'private-secret', state, harness: {}, externalConsumer: async event => { admitted.push(event); return { accepted: true }; }, logger: { info: (...args) => { logs.push(args); records.push(...args.filter(value => value?.event)); @@ -62,7 +64,7 @@ test('the production build patch observes real WS messages before decode and pre error: (...args) => logs.push(args), warn() {} }, }); t.after(async () => { - await runtime.stop(); + await runtime.stop({ drain: false }); for (const client of server.clients) client.terminate(); await new Promise(resolve => server.close(resolve)); globalThis.fetch = previousFetch; @@ -77,8 +79,13 @@ test('the production build patch observes real WS messages before decode and pre const deadline = Date.now() + 5_000; while (admitted.length === 0 && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 10)); assert.equal(admitted.length, 1); + socket.send(JSON.stringify({ op: 0, s: 3, t: 'GROUP_AT_MESSAGE_CREATE', d: null })); + const refusedDeadline = Date.now() + 5000; + while (!records.some(value => value.phase === 'processing-refused') && Date.now() < refusedDeadline) + await new Promise(resolve => setTimeout(resolve, 10)); const transport = records.filter(value => value.event === 'qq.native-transport.frame'); assert.ok(transport.some(value => value.phase === 'parse-refused')); + assert.ok(transport.some(value => value.phase === 'processing-refused')); assert.ok(transport.some(value => value.phase === 'decoded' && value.opcode === 'other')); const gateway = records.find(value => value.event === 'qq.native-gateway.frame'); assert.ok(transport.some(value => value.phase === 'decoded' && value.connection === gateway.transport.connection && value.frame === gateway.transport.frame)); @@ -97,4 +104,6 @@ test('the production build patch observes real WS messages before decode and pre assert.equal(admitted.length, 1); for (const text of ['private-secret', 'private-token', 'private-session', 'private-invalid-json', 'private-event', 'private-question', 'private-human']) assert.equal(JSON.stringify(logs).includes(text), false, `diagnostic leaked ${text}`); + await assert.rejects(() => runtime.stop(), { code: 'admission-unresolved' }); + assert.equal((await new QqStateStore(join(directory, 'state.json')).load()).snapshot().gatewaySession, undefined); }); diff --git a/test/channels/qq/state-store.test.mjs b/test/channels/qq/state-store.test.mjs index 556af51a7..8d389909f 100644 --- a/test/channels/qq/state-store.test.mjs +++ b/test/channels/qq/state-store.test.mjs @@ -82,22 +82,22 @@ test('QQ stops recovery when backup fails and uses exclusive private backup writ const f = await fixture(t, bytes); const cause = Object.assign(new Error('disk full'), { code: 'ENOSPC' }); const writes = []; - const write = t.mock.method(fs, 'writeFile', async (path, data, options) => { - writes.push({ path, data, options }); - throw cause; + const originalOpen = fs.open; + const write = t.mock.method(fs, 'open', async (path, flags, mode) => { + if (String(path).includes('.corrupt-')) { writes.push({ path, flags, mode }); throw cause; } + return originalOpen(path, flags, mode); }); await assert.rejects(f.store.load(), error => error.code === 'state-backup-failed' && error.cause === cause); write.mock.restore(); assert.equal(writes.length, 1); assert.match(writes[0].path, /state\.json\.corrupt-/); - assert.equal(writes[0].options.flag, 'wx'); - assert.equal(writes[0].options.mode, 0o600); - assert.deepEqual(writes[0].data, bytes); + assert.equal(writes[0].flags, 'wx'); + assert.equal(writes[0].mode, 0o600); assert.deepEqual(await fs.readFile(f.path), bytes); assert.equal(f.warnings.length, 0); }); -for (const stage of ['writeFile', 'rename']) { +for (const stage of ['open', 'rename']) { test(`QQ retains original and backup when recovery ${stage} fails, then retries`, async (t) => { const bytes = Buffer.alloc(449); const f = await fixture(t, bytes);