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.
This commit is contained in:
1 parent
df0795f2c5
commit
e9b74138d1
8 files changed
+173
-28
No files matched your search
@@ -4,6 +4,7 @@ import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
|
|||||||
import { ActionName } from '@/napcat-onebot/action/router';
|
import { ActionName } from '@/napcat-onebot/action/router';
|
||||||
import { OB11MessageImage, OB11MessageVideo } from '@/napcat-onebot/types';
|
import { OB11MessageImage, OB11MessageVideo } from '@/napcat-onebot/types';
|
||||||
import { Static, Type } from '@sinclair/typebox';
|
import { Static, Type } from '@sinclair/typebox';
|
||||||
|
import { calculateTimeout } from '@/napcat-onebot/config/config';
|
||||||
|
|
||||||
import { FileActionsExamples } from '../example/FileActionsExamples';
|
import { FileActionsExamples } from '../example/FileActionsExamples';
|
||||||
|
|
||||||
@@ -96,7 +97,10 @@ export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> {
|
|||||||
// 搜索名字模式
|
// 搜索名字模式
|
||||||
const searchResult = (await this.core.apis.FileApi.searchForFile([payload.file]));
|
const searchResult = (await this.core.apis.FileApi.searchForFile([payload.file]));
|
||||||
if (searchResult) {
|
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 = {
|
const res: GetFileResponse = {
|
||||||
file: downloadPath,
|
file: downloadPath,
|
||||||
url: downloadPath,
|
url: downloadPath,
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ export const SendMsgPayloadSchema = Type.Object({
|
|||||||
news: Type.Optional(Type.Array(Type.Object({ text: Type.String() }), { description: '合并转发新闻' })),
|
news: Type.Optional(Type.Array(Type.Object({ text: Type.String() }), { description: '合并转发新闻' })),
|
||||||
summary: Type.Optional(Type.String({ description: '合并转发摘要' })),
|
summary: Type.Optional(Type.String({ description: '合并转发摘要' })),
|
||||||
prompt: Type.Optional(Type.String({ description: '合并转发提示' })),
|
prompt: Type.Optional(Type.String({ description: '合并转发提示' })),
|
||||||
|
timeout: Type.Optional(Type.Number({ description: '自定义发送超时(毫秒),覆盖自动计算值' })),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type SendMsgPayload = Static<typeof SendMsgPayloadSchema>;
|
export type SendMsgPayload = Static<typeof SendMsgPayloadSchema>;
|
||||||
@@ -245,7 +246,7 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
|
|||||||
|
|
||||||
const { sendElements, deleteAfterSentFiles } = await this.obContext.apis.MsgApi
|
const { sendElements, deleteAfterSentFiles } = await this.obContext.apis.MsgApi
|
||||||
.createSendElements(messages, peer);
|
.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! };
|
return { message_id: returnMsg.id! };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { OneBotAction, OneBotRequestToolkit } from '@/napcat-onebot/action/OneBo
|
|||||||
import { StreamPacket, StreamStatus } from './StreamBasic';
|
import { StreamPacket, StreamStatus } from './StreamBasic';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
|
import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
|
||||||
|
import { calculateTimeout } from '@/napcat-onebot/config/config';
|
||||||
|
|
||||||
export interface ResolvedFileInfo {
|
export interface ResolvedFileInfo {
|
||||||
downloadPath: string;
|
downloadPath: string;
|
||||||
@@ -64,8 +65,11 @@ export abstract class BaseDownloadStream<PayloadType, ResultType> extends OneBot
|
|||||||
|
|
||||||
const searchResult = (await this.core.apis.FileApi.searchForFile([target]));
|
const searchResult = (await this.core.apis.FileApi.searchForFile([target]));
|
||||||
if (searchResult) {
|
if (searchResult) {
|
||||||
downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, parseInt(searchResult.fileSize));
|
const fileSizeNum = parseInt(searchResult.fileSize);
|
||||||
fileSize = 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;
|
fileName = searchResult.fileName;
|
||||||
return { downloadPath, fileName, fileSize };
|
return { downloadPath, fileName, fileSize };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import { RequestUtil } from 'napcat-common/src/request';
|
|||||||
import fsPromise from 'node:fs/promises';
|
import fsPromise from 'node:fs/promises';
|
||||||
import { OB11FriendAddNoticeEvent } from '@/napcat-onebot/event/notice/OB11FriendAddNoticeEvent';
|
import { OB11FriendAddNoticeEvent } from '@/napcat-onebot/event/notice/OB11FriendAddNoticeEvent';
|
||||||
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
|
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
|
||||||
|
import { calculateTimeout, capTimeout } from '@/napcat-onebot/config/config';
|
||||||
import { NapProtoMsg } from 'napcat-protobuf';
|
import { NapProtoMsg } from 'napcat-protobuf';
|
||||||
import { OB11GroupIncreaseEvent } from '../event/notice/OB11GroupIncreaseEvent';
|
import { OB11GroupIncreaseEvent } from '../event/notice/OB11GroupIncreaseEvent';
|
||||||
import { GroupDecreaseSubType, OB11GroupDecreaseEvent } from '../event/notice/OB11GroupDecreaseEvent';
|
import { GroupDecreaseSubType, OB11GroupDecreaseEvent } from '../event/notice/OB11GroupDecreaseEvent';
|
||||||
@@ -1241,36 +1242,43 @@ export class OneBotMsgApi {
|
|||||||
return { sendElements, deleteAfterSentFiles };
|
return { sendElements, deleteAfterSentFiles };
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendMsgWithOb11UniqueId (peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[]) {
|
async sendMsgWithOb11UniqueId (peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[], timeoutOverride?: number) {
|
||||||
if (!sendElements.length) {
|
if (!sendElements.length) {
|
||||||
throw new Error('消息体无法解析, 请检查是否发送了不支持的消息类型');
|
throw new Error('消息体无法解析, 请检查是否发送了不支持的消息类型');
|
||||||
}
|
}
|
||||||
|
|
||||||
const calculateTotalSize = async (elements: SendMessageElement[]): Promise<number> => {
|
const timeoutConfig = this.obContext.configLoader.configData.timeout;
|
||||||
const sizePromises = elements.map(async element => {
|
|
||||||
switch (element.elementType) {
|
let timeout: number;
|
||||||
case ElementType.PTT:
|
if (timeoutOverride !== undefined && timeoutOverride > 0) {
|
||||||
return (await fsPromise.stat(element.pttElement.filePath)).size;
|
timeout = capTimeout(timeoutConfig, timeoutOverride);
|
||||||
case ElementType.FILE:
|
} else {
|
||||||
return (await fsPromise.stat(element.fileElement.filePath)).size;
|
const calculateTotalSize = async (elements: SendMessageElement[]): Promise<number> => {
|
||||||
case ElementType.VIDEO:
|
const sizePromises = elements.map(async element => {
|
||||||
return (await fsPromise.stat(element.videoElement.filePath)).size;
|
switch (element.elementType) {
|
||||||
case ElementType.PIC:
|
case ElementType.PTT:
|
||||||
return (await fsPromise.stat(element.picElement.sourcePath)).size;
|
return (await fsPromise.stat(element.pttElement.filePath)).size;
|
||||||
default:
|
case ElementType.FILE:
|
||||||
return 0;
|
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 => {
|
timeout = calculateTimeout(timeoutConfig, totalSize, timeoutConfig.uploadSpeedKBps);
|
||||||
this.core.context.logger.logError('发送消息计算预计时间异常', e);
|
}
|
||||||
return 0;
|
|
||||||
});
|
|
||||||
|
|
||||||
const timeout = 10000 + (totalSize / 1024 / 256 * 1000);
|
|
||||||
try {
|
try {
|
||||||
const returnMsg = await this.core.apis.MsgApi.sendMsg(peer, sendElements, timeout);
|
const returnMsg = await this.core.apis.MsgApi.sendMsg(peer, sendElements, timeout);
|
||||||
if (!returnMsg) throw new Error('发送消息失败');
|
if (!returnMsg) throw new Error('发送消息失败');
|
||||||
|
|||||||
@@ -78,12 +78,20 @@ const NetworkConfigSchema = Type.Object({
|
|||||||
plugins: Type.Array(PluginConfigSchema, { default: [] }),
|
plugins: Type.Array(PluginConfigSchema, { default: [] }),
|
||||||
}, { 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({
|
export const OneBotConfigSchema = Type.Object({
|
||||||
network: NetworkConfigSchema,
|
network: NetworkConfigSchema,
|
||||||
musicSignUrl: Type.String({ default: '' }),
|
musicSignUrl: Type.String({ default: '' }),
|
||||||
enableLocalFile2Url: Type.Boolean({ default: false }),
|
enableLocalFile2Url: Type.Boolean({ default: false }),
|
||||||
parseMultMsg: Type.Boolean({ default: false }),
|
parseMultMsg: Type.Boolean({ default: false }),
|
||||||
imageDownloadProxy: Type.String({ default: '' }),
|
imageDownloadProxy: Type.String({ default: '' }),
|
||||||
|
timeout: TimeoutConfigSchema,
|
||||||
});
|
});
|
||||||
|
|
||||||
export type OneBotConfig = Static<typeof OneBotConfigSchema>;
|
export type OneBotConfig = Static<typeof OneBotConfigSchema>;
|
||||||
@@ -108,3 +116,21 @@ export function loadConfig (config: Partial<OneBotConfig>): OneBotConfig {
|
|||||||
}
|
}
|
||||||
return data as 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);
|
||||||
|
}
|
||||||
@@ -23,6 +23,12 @@ const OneBotConfigCard = () => {
|
|||||||
enableLocalFile2Url: false,
|
enableLocalFile2Url: false,
|
||||||
parseMultMsg: false,
|
parseMultMsg: false,
|
||||||
imageDownloadProxy: '',
|
imageDownloadProxy: '',
|
||||||
|
timeout: {
|
||||||
|
baseTimeout: 10000,
|
||||||
|
uploadSpeedKBps: 256,
|
||||||
|
downloadSpeedKBps: 256,
|
||||||
|
maxTimeout: 1800000,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const reset = () => {
|
const reset = () => {
|
||||||
@@ -30,6 +36,12 @@ const OneBotConfigCard = () => {
|
|||||||
setOnebotValue('enableLocalFile2Url', config.enableLocalFile2Url);
|
setOnebotValue('enableLocalFile2Url', config.enableLocalFile2Url);
|
||||||
setOnebotValue('parseMultMsg', config.parseMultMsg);
|
setOnebotValue('parseMultMsg', config.parseMultMsg);
|
||||||
setOnebotValue('imageDownloadProxy', config.imageDownloadProxy);
|
setOnebotValue('imageDownloadProxy', config.imageDownloadProxy);
|
||||||
|
setOnebotValue('timeout', config.timeout ?? {
|
||||||
|
baseTimeout: 10000,
|
||||||
|
uploadSpeedKBps: 256,
|
||||||
|
downloadSpeedKBps: 1000,
|
||||||
|
maxTimeout: 1800000,
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const onSubmit = handleOnebotSubmit(async (data) => {
|
const onSubmit = handleOnebotSubmit(async (data) => {
|
||||||
@@ -122,6 +134,82 @@ const OneBotConfigCard = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name='timeout.baseTimeout'
|
||||||
|
render={({ field }) => (
|
||||||
|
<Input
|
||||||
|
{...field}
|
||||||
|
type='number'
|
||||||
|
label='基础超时时间(毫秒)'
|
||||||
|
placeholder='10000'
|
||||||
|
value={field.value?.toString() ?? ''}
|
||||||
|
onChange={(e) => 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',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name='timeout.uploadSpeedKBps'
|
||||||
|
render={({ field }) => (
|
||||||
|
<Input
|
||||||
|
{...field}
|
||||||
|
type='number'
|
||||||
|
label='预估上传速度(KB/s)'
|
||||||
|
placeholder='256'
|
||||||
|
value={field.value?.toString() ?? ''}
|
||||||
|
onChange={(e) => 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',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name='timeout.downloadSpeedKBps'
|
||||||
|
render={({ field }) => (
|
||||||
|
<Input
|
||||||
|
{...field}
|
||||||
|
type='number'
|
||||||
|
label='预估下载速度(KB/s)'
|
||||||
|
placeholder='1000'
|
||||||
|
value={field.value?.toString() ?? ''}
|
||||||
|
onChange={(e) => 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',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name='timeout.maxTimeout'
|
||||||
|
render={({ field }) => (
|
||||||
|
<Input
|
||||||
|
{...field}
|
||||||
|
type='number'
|
||||||
|
label='最大超时时间(毫秒)'
|
||||||
|
placeholder='1800000'
|
||||||
|
value={field.value?.toString() ?? ''}
|
||||||
|
onChange={(e) => 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',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
<SaveButtons
|
<SaveButtons
|
||||||
onSubmit={onSubmit}
|
onSubmit={onSubmit}
|
||||||
reset={reset}
|
reset={reset}
|
||||||
|
|||||||
@@ -19,6 +19,12 @@ const initialState: ConfigState = {
|
|||||||
enableLocalFile2Url: false,
|
enableLocalFile2Url: false,
|
||||||
parseMultMsg: true,
|
parseMultMsg: true,
|
||||||
imageDownloadProxy: '',
|
imageDownloadProxy: '',
|
||||||
|
timeout: {
|
||||||
|
baseTimeout: 10000,
|
||||||
|
uploadSpeedKBps: 256,
|
||||||
|
downloadSpeedKBps: 256,
|
||||||
|
maxTimeout: 1800000,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -56,10 +56,18 @@ interface NetworkConfig {
|
|||||||
websocketClients: Array<WebsocketClientConfig>;
|
websocketClients: Array<WebsocketClientConfig>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface TimeoutConfig {
|
||||||
|
baseTimeout: number;
|
||||||
|
uploadSpeedKBps: number;
|
||||||
|
downloadSpeedKBps: number;
|
||||||
|
maxTimeout: number;
|
||||||
|
}
|
||||||
|
|
||||||
interface OneBotConfig {
|
interface OneBotConfig {
|
||||||
network: NetworkConfig; // 网络配置
|
network: NetworkConfig; // 网络配置
|
||||||
musicSignUrl: string; // 音乐签名地址
|
musicSignUrl: string; // 音乐签名地址
|
||||||
enableLocalFile2Url: boolean;
|
enableLocalFile2Url: boolean;
|
||||||
parseMultMsg: boolean;
|
parseMultMsg: boolean;
|
||||||
imageDownloadProxy: string; // 图片下载代理地址
|
imageDownloadProxy: string; // 图片下载代理地址
|
||||||
|
timeout: TimeoutConfig; // 超时预测配置
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user