From bd40ac35226c230c9f410cddbde36a9d4596de24 Mon Sep 17 00:00:00 2001 From: KazusaUwU Date: Sun, 1 Nov 2026 20:29:01 +0800 Subject: [PATCH] feat(protocol): make highway media download limits configurable (#632) Bound the two hardcoded limits of the shared HTTP media download engine (`loadBinarySource` / `stageSourceToDisk`) with deployment-wide environment settings, following the existing `positiveIntEnv` convention: - SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS (default 60000): one download attempt. - SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES (default 1073741824): the implicit cap on a binary source buffered in memory. Both defaults are unchanged, so an unconfigured deployment behaves exactly as before, and unusable values are logged and ignored. Callers that pass their own ceiling keep it: group/private files and flash transfer still use 4 GiB, inline `base64://` / `data:` flash sources keep the 1 GiB buffered-load ceiling, and video upload has its own limit. Documented in HIGHWAY_UPLOADS.md. --- packages/protocol/HIGHWAY_UPLOADS.md | 23 +++++++ .../protocol/src/highway/download-settings.ts | 54 ++++++++++++++++ packages/protocol/src/highway/utils.ts | 26 +++++--- .../protocol/tests/download-settings.test.ts | 61 +++++++++++++++++++ 4 files changed, 155 insertions(+), 9 deletions(-) create mode 100644 packages/protocol/src/highway/download-settings.ts create mode 100644 packages/protocol/tests/download-settings.test.ts diff --git a/packages/protocol/HIGHWAY_UPLOADS.md b/packages/protocol/HIGHWAY_UPLOADS.md index 6c61f825..6d921df0 100644 --- a/packages/protocol/HIGHWAY_UPLOADS.md +++ b/packages/protocol/HIGHWAY_UPLOADS.md @@ -35,3 +35,26 @@ excluding cached uploads, before drawing performance conclusions. Regression tests use isolated transports and cover concurrency bounds, out-of-order acknowledgements, a stalled early chunk, retry exhaustion, backpressure and cleanup. They do not establish real QQ delivery or upload throughput. + +## Media download limits + +Two deployment-wide knobs bound HTTP media downloads in `highway/utils.ts`. They are +environment variables rather than per-account OneBot settings because every caller +reaches the same download engine (`loadBinarySource` / `stageSourceToDisk`): + +```sh +# One HTTP attempt, in milliseconds. Default 60000. +SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS=180000 +# Cap on one binary source buffered in memory, in bytes. Default 1073741824 (1 GiB). +SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES=2147483648 +``` + +Both default to their previous hardcoded values, so an unconfigured deployment +behaves exactly as before. Invalid values are logged and ignored, falling back to the +default. Callers that already pass an explicit ceiling keep it: group/private files +and flash transfer still use 4 GiB, and inline `base64://` / `data:` flash sources +keep the 1 GiB buffered-load ceiling. + +`SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS` is not related to +`SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS` (used by the `download_file` OneBot action): the +former bounds highway media downloads, the latter the action's own file staging. diff --git a/packages/protocol/src/highway/download-settings.ts b/packages/protocol/src/highway/download-settings.ts new file mode 100644 index 00000000..27f2c616 --- /dev/null +++ b/packages/protocol/src/highway/download-settings.ts @@ -0,0 +1,54 @@ +import { positiveIntEnv } from '@snowluma/common/env'; + +/** Default timeout for one HTTP media download attempt (ms). */ +export const DEFAULT_HTTP_DOWNLOAD_TIMEOUT_MS = 60_000; + +/** Default cap on one binary load that is buffered in memory (bytes). */ +export const DEFAULT_MAX_BINARY_DOWNLOAD_BYTES = 1024 * 1024 * 1024; + +/** Node's timer ceiling; a larger value would be silently clamped anyway. */ +const MAX_TIMER_MS = 2_147_483_647; + +/** + * Deliberate ceiling for the configurable cap. It is not a Node limit (Node 24 + * reports `buffer.constants.MAX_LENGTH` as `Number.MAX_SAFE_INTEGER`); buffering a + * single download larger than this is not a realistic media source and would + * exhaust the process long before it completes. + */ +const MAX_BINARY_DOWNLOAD_BYTES = 4 * 1024 * 1024 * 1024; + +/** + * Timeout for one HTTP media download attempt. + * + * Deployment-wide rather than per-adapter because every caller reaches this + * through the same download engine (`loadBinarySource` / `stageSourceToDisk`), + * and it is configured the same way as the other transport timeouts + * (`SNOWLUMA_PACKET_TIMEOUT_MS`, `SNOWLUMA_HOOK_ACK_TIMEOUT_MS`) instead of + * growing the per-account OneBot config surface. + * + * The 60 s default is generous for images but tight for a large media file over + * a slow link, where the abort is reported as a generic fetch failure. + * + * Not to be confused with `SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS`, which bounds the + * `download_file` OneBot action's own staging. + */ +export function httpDownloadTimeoutMs(env: NodeJS.ProcessEnv = process.env): number { + return positiveIntEnv('SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS', DEFAULT_HTTP_DOWNLOAD_TIMEOUT_MS, { + env, + max: MAX_TIMER_MS, + }); +} + +/** + * Cap on one binary source loaded fully into memory. + * + * Applies to the helpers whose size bound is implicit (image, voice, avatar, + * custom face, group-notice image). Callers that pass their own ceiling — group + * files, flash transfer, video — keep it, so raising this never lifts those. + */ +export function maxBinaryDownloadBytes(env: NodeJS.ProcessEnv = process.env): number { + return positiveIntEnv('SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES', DEFAULT_MAX_BINARY_DOWNLOAD_BYTES, { + env, + max: MAX_BINARY_DOWNLOAD_BYTES, + }); +} diff --git a/packages/protocol/src/highway/utils.ts b/packages/protocol/src/highway/utils.ts index c5f79b77..94c0265a 100644 --- a/packages/protocol/src/highway/utils.ts +++ b/packages/protocol/src/highway/utils.ts @@ -2,6 +2,11 @@ import { createHash } from 'crypto'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; +import { + DEFAULT_MAX_BINARY_DOWNLOAD_BYTES, + httpDownloadTimeoutMs, + maxBinaryDownloadBytes, +} from './download-settings'; export interface LoadedBinary { bytes: Uint8Array; @@ -16,8 +21,12 @@ export interface LoadedBinary { * directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private * file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's * file protocol legitimately supports up to 4 GiB. + * + * The effective default is `SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES` (see + * `download-settings`); this constant is the documented 1 GiB floor reused by + * the static flash-transfer ceiling below. */ -const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB +const DEFAULT_MAX_BINARY_SIZE = DEFAULT_MAX_BINARY_DOWNLOAD_BYTES; /** Hard ceiling QQ's file protocol supports — used by group/private files. */ export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB /** Local / HTTP flash sources. Official fileset max is unknown; reuse the @@ -27,7 +36,6 @@ export const FLASH_TRANSFER_MAX_BYTES = FILE_UPLOAD_MAX_BYTES; /** Inline `base64://` / `data:` flash sources still decode into RAM inside * `stageSourceToDisk`, so they keep the 1 GiB buffered-load ceiling. */ export const FLASH_TRANSFER_INLINE_MAX_BYTES = DEFAULT_MAX_BINARY_SIZE; -const FETCH_TIMEOUT_MS = 60_000; /** * Browser-like User-Agent for remote media downloads. Many image / CDN @@ -152,11 +160,11 @@ export interface DownloadSink { /** * Shared HTTP download engine for both the buffered and the disk-streaming * paths — the single owner of the observable download behavior: browser UA + - * Accept, redirect follow, 60s timeout, incremental `maxBytes` enforcement - * (declared Content-Length AND streamed total, `noRetry`-tagged), and one - * Referer retry on a non-size failure. Bytes are delivered chunk-by-chunk to a - * caller-provided sink so the same length-checking transport feeds either RAM - * or disk. + * Accept, redirect follow, the configurable download timeout, incremental + * `maxBytes` enforcement (declared Content-Length AND streamed total, + * `noRetry`-tagged), and one Referer retry on a non-size failure. Bytes are + * delivered chunk-by-chunk to a caller-provided sink so the same + * length-checking transport feeds either RAM or disk. */ export async function downloadHttp( source: string, @@ -170,7 +178,7 @@ export async function downloadHttp( const resp = await fetch(source, { headers, redirect: 'follow', - signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + signal: AbortSignal.timeout(httpDownloadTimeoutMs()), }); if (!resp.ok) { @@ -261,7 +269,7 @@ export async function downloadHttp( export async function loadBinarySource( source: string, resourceName: string, - maxBytes: number = DEFAULT_MAX_BINARY_SIZE, + maxBytes: number = maxBinaryDownloadBytes(), ): Promise { if (!source) { throw new Error(`${resourceName} source is empty`); diff --git a/packages/protocol/tests/download-settings.test.ts b/packages/protocol/tests/download-settings.test.ts new file mode 100644 index 00000000..ea9b3a84 --- /dev/null +++ b/packages/protocol/tests/download-settings.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { + DEFAULT_HTTP_DOWNLOAD_TIMEOUT_MS, + DEFAULT_MAX_BINARY_DOWNLOAD_BYTES, + httpDownloadTimeoutMs, + maxBinaryDownloadBytes, +} from '../src/highway/download-settings'; +import { downloadHttp } from '../src/highway/utils'; + +const memorySink = (): { + write: () => void; + done: () => undefined; + discard: () => void; +} => ({ write: () => undefined, done: () => undefined, discard: () => undefined }); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('highway download settings', () => { + it('keeps the documented defaults when nothing is configured', () => { + expect(httpDownloadTimeoutMs({})).toBe(60_000); + expect(maxBinaryDownloadBytes({})).toBe(1024 * 1024 * 1024); + expect(DEFAULT_HTTP_DOWNLOAD_TIMEOUT_MS).toBe(60_000); + expect(DEFAULT_MAX_BINARY_DOWNLOAD_BYTES).toBe(1024 * 1024 * 1024); + }); + + it('reads both knobs from the environment', () => { + expect(httpDownloadTimeoutMs({ SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS: '180000' })).toBe( + 180_000, + ); + expect( + maxBinaryDownloadBytes({ SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES: String(2 ** 31) }), + ).toBe(2 ** 31); + }); + + it('ignores unusable values instead of failing the download', () => { + expect(httpDownloadTimeoutMs({ SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS: '0' })).toBe(60_000); + expect(httpDownloadTimeoutMs({ SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS: 'soon' })).toBe(60_000); + expect(maxBinaryDownloadBytes({ SNOWLUMA_MAX_BINARY_DOWNLOAD_BYTES: '-5' })).toBe( + DEFAULT_MAX_BINARY_DOWNLOAD_BYTES, + ); + }); + + it('feeds the configured timeout into the fetch signal', async () => { + vi.stubEnv('SNOWLUMA_HTTP_DOWNLOAD_TIMEOUT_MS', '1234'); + const timeoutSpy = vi.spyOn(AbortSignal, 'timeout'); + const fetchStub = vi.fn( + async () => new Response(new Uint8Array([1, 2, 3]), { status: 200 }), + ); + vi.stubGlobal('fetch', fetchStub); + + await downloadHttp('https://example.test/media.bin', 'media', 1024, memorySink); + + expect(timeoutSpy).toHaveBeenCalledWith(1234); + expect(fetchStub).toHaveBeenCalledTimes(1); + }); +});