From e9b74138d10bdab072e0e786e3d788c3f100dd77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Thu, 12 Mar 2026 15:01:34 +0800 Subject: [PATCH] Add configurable timeout calculation for transfers Introduce timeout configuration and automatic timeout estimation for uploads/downloads. Added TimeoutConfig to OneBot config with baseTimeout, upload/downloadSpeedKBps and maxTimeout, plus calculateTimeout and capTimeout helpers. Applied estimation to FileApi.downloadFileById calls (GetFile, BaseDownloadStream) and to message sending (OneBotMsgApi) to compute timeouts from total payload size; sendMsg now accepts an optional timeout override which is capped by maxTimeout. Updated SendMsg payload schema to allow a custom timeout, and updated web UI store, types and config form to expose timeout settings and defaults. --- packages/napcat-onebot/action/file/GetFile.ts | 6 +- packages/napcat-onebot/action/msg/SendMsg.ts | 3 +- .../action/stream/BaseDownloadStream.ts | 8 +- packages/napcat-onebot/api/msg.ts | 56 +++++++----- packages/napcat-onebot/config/config.ts | 26 ++++++ .../src/pages/dashboard/config/onebot.tsx | 88 +++++++++++++++++++ .../src/store/modules/config.ts | 6 ++ .../src/types/onebot_conf.d.ts | 8 ++ 8 files changed, 173 insertions(+), 28 deletions(-) diff --git a/packages/napcat-onebot/action/file/GetFile.ts b/packages/napcat-onebot/action/file/GetFile.ts index 518a7ad24..77ca5db8a 100644 --- a/packages/napcat-onebot/action/file/GetFile.ts +++ b/packages/napcat-onebot/action/file/GetFile.ts @@ -4,6 +4,7 @@ import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid'; import { ActionName } from '@/napcat-onebot/action/router'; import { OB11MessageImage, OB11MessageVideo } from '@/napcat-onebot/types'; import { Static, Type } from '@sinclair/typebox'; +import { calculateTimeout } from '@/napcat-onebot/config/config'; import { FileActionsExamples } from '../example/FileActionsExamples'; @@ -96,7 +97,10 @@ export class GetFileBase extends OneBotAction { // 搜索名字模式 const searchResult = (await this.core.apis.FileApi.searchForFile([payload.file])); if (searchResult) { - const downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, parseInt(searchResult.fileSize)); + const fileSize = parseInt(searchResult.fileSize); + const timeoutConfig = this.obContext.configLoader.configData.timeout; + const estimatedTime = calculateTimeout(timeoutConfig, fileSize, timeoutConfig.downloadSpeedKBps); + const downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, fileSize, estimatedTime); const res: GetFileResponse = { file: downloadPath, url: downloadPath, diff --git a/packages/napcat-onebot/action/msg/SendMsg.ts b/packages/napcat-onebot/action/msg/SendMsg.ts index ba4f26d53..2058bf271 100644 --- a/packages/napcat-onebot/action/msg/SendMsg.ts +++ b/packages/napcat-onebot/action/msg/SendMsg.ts @@ -33,6 +33,7 @@ export const SendMsgPayloadSchema = Type.Object({ news: Type.Optional(Type.Array(Type.Object({ text: Type.String() }), { description: '合并转发新闻' })), summary: Type.Optional(Type.String({ description: '合并转发摘要' })), prompt: Type.Optional(Type.String({ description: '合并转发提示' })), + timeout: Type.Optional(Type.Number({ description: '自定义发送超时(毫秒),覆盖自动计算值' })), }); export type SendMsgPayload = Static; @@ -245,7 +246,7 @@ export class SendMsgBase extends OneBotAction { const { sendElements, deleteAfterSentFiles } = await this.obContext.apis.MsgApi .createSendElements(messages, peer); - const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, sendElements, deleteAfterSentFiles); + const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, sendElements, deleteAfterSentFiles, payload.timeout); return { message_id: returnMsg.id! }; } diff --git a/packages/napcat-onebot/action/stream/BaseDownloadStream.ts b/packages/napcat-onebot/action/stream/BaseDownloadStream.ts index 7e0a07db8..8c3ae83d5 100644 --- a/packages/napcat-onebot/action/stream/BaseDownloadStream.ts +++ b/packages/napcat-onebot/action/stream/BaseDownloadStream.ts @@ -2,6 +2,7 @@ import { OneBotAction, OneBotRequestToolkit } from '@/napcat-onebot/action/OneBo import { StreamPacket, StreamStatus } from './StreamBasic'; import fs from 'fs'; import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid'; +import { calculateTimeout } from '@/napcat-onebot/config/config'; export interface ResolvedFileInfo { downloadPath: string; @@ -64,8 +65,11 @@ export abstract class BaseDownloadStream extends OneBot const searchResult = (await this.core.apis.FileApi.searchForFile([target])); if (searchResult) { - downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, parseInt(searchResult.fileSize)); - fileSize = parseInt(searchResult.fileSize); + const fileSizeNum = parseInt(searchResult.fileSize); + const timeoutConfig = this.obContext.configLoader.configData.timeout; + const estimatedTime = calculateTimeout(timeoutConfig, fileSizeNum, timeoutConfig.downloadSpeedKBps); + downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, fileSizeNum, estimatedTime); + fileSize = fileSizeNum; fileName = searchResult.fileName; return { downloadPath, fileName, fileSize }; } diff --git a/packages/napcat-onebot/api/msg.ts b/packages/napcat-onebot/api/msg.ts index e086bd84e..c4a49c4c6 100644 --- a/packages/napcat-onebot/api/msg.ts +++ b/packages/napcat-onebot/api/msg.ts @@ -37,6 +37,7 @@ import { RequestUtil } from 'napcat-common/src/request'; import fsPromise from 'node:fs/promises'; import { OB11FriendAddNoticeEvent } from '@/napcat-onebot/event/notice/OB11FriendAddNoticeEvent'; import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder'; +import { calculateTimeout, capTimeout } from '@/napcat-onebot/config/config'; import { NapProtoMsg } from 'napcat-protobuf'; import { OB11GroupIncreaseEvent } from '../event/notice/OB11GroupIncreaseEvent'; import { GroupDecreaseSubType, OB11GroupDecreaseEvent } from '../event/notice/OB11GroupDecreaseEvent'; @@ -1241,36 +1242,43 @@ export class OneBotMsgApi { return { sendElements, deleteAfterSentFiles }; } - async sendMsgWithOb11UniqueId (peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[]) { + async sendMsgWithOb11UniqueId (peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[], timeoutOverride?: number) { if (!sendElements.length) { throw new Error('消息体无法解析, 请检查是否发送了不支持的消息类型'); } - const calculateTotalSize = async (elements: SendMessageElement[]): Promise => { - const sizePromises = elements.map(async element => { - switch (element.elementType) { - case ElementType.PTT: - return (await fsPromise.stat(element.pttElement.filePath)).size; - case ElementType.FILE: - return (await fsPromise.stat(element.fileElement.filePath)).size; - case ElementType.VIDEO: - return (await fsPromise.stat(element.videoElement.filePath)).size; - case ElementType.PIC: - return (await fsPromise.stat(element.picElement.sourcePath)).size; - default: - return 0; - } + const timeoutConfig = this.obContext.configLoader.configData.timeout; + + let timeout: number; + if (timeoutOverride !== undefined && timeoutOverride > 0) { + timeout = capTimeout(timeoutConfig, timeoutOverride); + } else { + const calculateTotalSize = async (elements: SendMessageElement[]): Promise => { + const sizePromises = elements.map(async element => { + switch (element.elementType) { + case ElementType.PTT: + return (await fsPromise.stat(element.pttElement.filePath)).size; + case ElementType.FILE: + return (await fsPromise.stat(element.fileElement.filePath)).size; + case ElementType.VIDEO: + return (await fsPromise.stat(element.videoElement.filePath)).size; + case ElementType.PIC: + return (await fsPromise.stat(element.picElement.sourcePath)).size; + default: + return 0; + } + }); + const sizes = await Promise.all(sizePromises); + return sizes.reduce((total, size) => total + size, 0); + }; + + const totalSize = await calculateTotalSize(sendElements).catch(e => { + this.core.context.logger.logError('发送消息计算预计时间异常', e); + return 0; }); - const sizes = await Promise.all(sizePromises); - return sizes.reduce((total, size) => total + size, 0); - }; - const totalSize = await calculateTotalSize(sendElements).catch(e => { - this.core.context.logger.logError('发送消息计算预计时间异常', e); - return 0; - }); - - const timeout = 10000 + (totalSize / 1024 / 256 * 1000); + timeout = calculateTimeout(timeoutConfig, totalSize, timeoutConfig.uploadSpeedKBps); + } try { const returnMsg = await this.core.apis.MsgApi.sendMsg(peer, sendElements, timeout); if (!returnMsg) throw new Error('发送消息失败'); diff --git a/packages/napcat-onebot/config/config.ts b/packages/napcat-onebot/config/config.ts index 8bd9884d9..114654c55 100644 --- a/packages/napcat-onebot/config/config.ts +++ b/packages/napcat-onebot/config/config.ts @@ -78,12 +78,20 @@ const NetworkConfigSchema = Type.Object({ plugins: Type.Array(PluginConfigSchema, { default: [] }), }, { default: {} }); +const TimeoutConfigSchema = Type.Object({ + baseTimeout: Type.Number({ default: 10000 }), + uploadSpeedKBps: Type.Number({ default: 256 }), + downloadSpeedKBps: Type.Number({ default: 256 }), + maxTimeout: Type.Number({ default: 1800000 }), +}, { default: {} }); + export const OneBotConfigSchema = Type.Object({ network: NetworkConfigSchema, musicSignUrl: Type.String({ default: '' }), enableLocalFile2Url: Type.Boolean({ default: false }), parseMultMsg: Type.Boolean({ default: false }), imageDownloadProxy: Type.String({ default: '' }), + timeout: TimeoutConfigSchema, }); export type OneBotConfig = Static; @@ -108,3 +116,21 @@ export function loadConfig (config: Partial): OneBotConfig { } return data as OneBotConfig; } + +export function calculateTimeout ( + config: OneBotConfig['timeout'], + dataSizeBytes: number, + speedKBps: number +): number { + return Math.min( + config.baseTimeout + (dataSizeBytes / 1024 / Math.max(speedKBps, 1) * 1000), + config.maxTimeout + ); +} + +export function capTimeout ( + config: OneBotConfig['timeout'], + timeoutMs: number +): number { + return Math.min(timeoutMs, config.maxTimeout); +} diff --git a/packages/napcat-webui-frontend/src/pages/dashboard/config/onebot.tsx b/packages/napcat-webui-frontend/src/pages/dashboard/config/onebot.tsx index d9a0e34a1..254059d82 100644 --- a/packages/napcat-webui-frontend/src/pages/dashboard/config/onebot.tsx +++ b/packages/napcat-webui-frontend/src/pages/dashboard/config/onebot.tsx @@ -23,6 +23,12 @@ const OneBotConfigCard = () => { enableLocalFile2Url: false, parseMultMsg: false, imageDownloadProxy: '', + timeout: { + baseTimeout: 10000, + uploadSpeedKBps: 256, + downloadSpeedKBps: 256, + maxTimeout: 1800000, + }, }, }); const reset = () => { @@ -30,6 +36,12 @@ const OneBotConfigCard = () => { setOnebotValue('enableLocalFile2Url', config.enableLocalFile2Url); setOnebotValue('parseMultMsg', config.parseMultMsg); setOnebotValue('imageDownloadProxy', config.imageDownloadProxy); + setOnebotValue('timeout', config.timeout ?? { + baseTimeout: 10000, + uploadSpeedKBps: 256, + downloadSpeedKBps: 1000, + maxTimeout: 1800000, + }); }; const onSubmit = handleOnebotSubmit(async (data) => { @@ -122,6 +134,82 @@ const OneBotConfigCard = () => { /> )} /> + ( + field.onChange(parseInt(e.target.value) || 0)} + classNames={{ + inputWrapper: + 'bg-default-100/50 dark:bg-white/5 backdrop-blur-md border border-transparent hover:bg-default-200/50 dark:hover:bg-white/10 transition-all shadow-sm data-[hover=true]:border-default-300', + input: 'bg-transparent text-default-700 placeholder:text-default-400', + }} + /> + )} + /> + ( + field.onChange(parseInt(e.target.value) || 0)} + classNames={{ + inputWrapper: + 'bg-default-100/50 dark:bg-white/5 backdrop-blur-md border border-transparent hover:bg-default-200/50 dark:hover:bg-white/10 transition-all shadow-sm data-[hover=true]:border-default-300', + input: 'bg-transparent text-default-700 placeholder:text-default-400', + }} + /> + )} + /> + ( + field.onChange(parseInt(e.target.value) || 0)} + classNames={{ + inputWrapper: + 'bg-default-100/50 dark:bg-white/5 backdrop-blur-md border border-transparent hover:bg-default-200/50 dark:hover:bg-white/10 transition-all shadow-sm data-[hover=true]:border-default-300', + input: 'bg-transparent text-default-700 placeholder:text-default-400', + }} + /> + )} + /> + ( + field.onChange(parseInt(e.target.value) || 0)} + classNames={{ + inputWrapper: + 'bg-default-100/50 dark:bg-white/5 backdrop-blur-md border border-transparent hover:bg-default-200/50 dark:hover:bg-white/10 transition-all shadow-sm data-[hover=true]:border-default-300', + input: 'bg-transparent text-default-700 placeholder:text-default-400', + }} + /> + )} + /> ; } +interface TimeoutConfig { + baseTimeout: number; + uploadSpeedKBps: number; + downloadSpeedKBps: number; + maxTimeout: number; +} + interface OneBotConfig { network: NetworkConfig; // 网络配置 musicSignUrl: string; // 音乐签名地址 enableLocalFile2Url: boolean; parseMultMsg: boolean; imageDownloadProxy: string; // 图片下载代理地址 + timeout: TimeoutConfig; // 超时预测配置 }