feat(storage): add managed storage controls

Enforce a global log quota with configurable retention and observable degradation. Add authenticated storage reporting and safe cleanup controls to the settings UI. Protect active stream transfers and isolate parallel test resources.
This commit is contained in:
DrSmoothl committed 2026-07-24 12:58:57 +08:00
1 parent b884a1c479
commit 87a604ecbd
33 files changed
+5115 -136

No files matched your search

+39 -18
View File
@@ -26,7 +26,7 @@ import { defineStreamAction, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types';
import { type StreamSink, StreamStatus } from '../streaming';
import { STREAM_ROOT } from './stream-file';
import { STREAM_ROOT, registerActiveStreamItem } from '../stream-storage';
const DEFAULT_CHUNK_BYTES = 64 * 1024;
const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size
@@ -145,6 +145,8 @@ interface DownloadSource {
name: string;
size: number; // 0 when unknown
iterable: AsyncIterable<Uint8Array>;
/** Local stream-storage path that must be protected from cleanup while read. */
managedPath?: string;
/** Force the underlying source closed (idle-timeout watchdog / abort). */
abort?: () => void;
}
@@ -228,7 +230,13 @@ async function resolveDownload(
try { real = fs.realpathSync(local); } catch { /* keep lexical */ }
if (!isWithinStreamRoot(real)) throw new DownloadError('local downloads are restricted to the stream temp directory');
const rs = fs.createReadStream(real, { highWaterMark: chunkSize });
return { name: path.basename(real), size: st.size, iterable: rs, abort: () => rs.destroy() };
return {
name: path.basename(real),
size: st.size,
iterable: rs,
managedPath: real,
abort: () => rs.destroy(),
};
}
}
@@ -304,22 +312,35 @@ async function runDownload(
if (chunkSize > MAX_CHUNK_REQUEST_BYTES) chunkSize = MAX_CHUNK_REQUEST_BYTES;
const src = await resolveDownload(target, ctx, prefer, chunkSize);
await sink.send({
type: StreamStatus.Stream,
data_type: 'file_info',
file_name: src.name,
file_size: src.size,
chunk_size: chunkSize,
});
const { totalChunks, totalBytes } = await streamChunks(sink, src.iterable, src.size, 'file_chunk', src.abort);
return okResponse({
type: StreamStatus.Response,
data_type: 'file_complete',
file_name: src.name,
total_chunks: totalChunks,
total_bytes: totalBytes,
message: 'Download completed',
});
const releaseStorageActivity = src.managedPath
? registerActiveStreamItem([src.managedPath])
: undefined;
try {
await sink.send({
type: StreamStatus.Stream,
data_type: 'file_info',
file_name: src.name,
file_size: src.size,
chunk_size: chunkSize,
});
const { totalChunks, totalBytes } = await streamChunks(
sink,
src.iterable,
src.size,
'file_chunk',
src.abort,
);
return okResponse({
type: StreamStatus.Response,
data_type: 'file_complete',
file_name: src.name,
total_chunks: totalChunks,
total_bytes: totalBytes,
message: 'Download completed',
});
} finally {
releaseStorageActivity?.();
}
}
// ─────────────────────────── action definitions ───────────────────────────
+57 -14
View File
@@ -17,7 +17,6 @@
// (no single-request OOM or disk/fd exhaustion); chunk indices are claimed
// synchronously (no double-count race); state is namespaced per account.
import os from 'os';
import path from 'path';
import fs from 'fs';
import { createHash } from 'crypto';
@@ -26,12 +25,17 @@ import { defineAction, defineStreamAction, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse } from '../types';
import { StreamStatus } from '../streaming';
import {
STREAM_DOWNLOAD_DIR,
STREAM_ROOT,
STREAM_UPLOAD_DIR,
clearInactiveStreamStorage,
registerActiveStreamItem,
} from '../stream-storage';
const log = createLogger('OneBot.Stream');
export const STREAM_ROOT = path.join(os.tmpdir(), 'snowluma-stream');
export const STREAM_UPLOAD_DIR = path.join(STREAM_ROOT, 'upload');
export const STREAM_DOWNLOAD_DIR = path.join(STREAM_ROOT, 'download');
export { STREAM_DOWNLOAD_DIR, STREAM_ROOT, STREAM_UPLOAD_DIR };
const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; // idle stream reaped after 10 min
const DEFAULT_RETENTION_MS = 5 * 60 * 1000; // reassembled file auto-deleted after 5 min
@@ -95,6 +99,7 @@ interface UploadState {
finalPath: string;
fileRetention: number;
timeoutId: NodeJS.Timeout;
releaseStorageActivity: () => void;
}
/** Process-wide. Key is account-namespaced so two accounts (same process) can't
@@ -111,11 +116,16 @@ function cleanupUpload(key: string, deleteFinal: boolean): void {
const state = uploads.get(key);
if (!state) return;
clearTimeout(state.timeoutId);
try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch { /* best effort */ }
try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch (error) {
log.warn('failed to delete stream upload chunks %s: %s', state.tempDir, errorMessage(error));
}
if (deleteFinal) {
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete stream upload file %s: %s', state.finalPath, errorMessage(error));
}
}
uploads.delete(key);
state.releaseStorageActivity();
}
function safeFilename(name: string | undefined, id: string): string {
@@ -142,6 +152,7 @@ function createUpload(p: UploadParams, account: string): UploadState {
fs.mkdirSync(tempDir, { recursive: true });
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]);
const state: UploadState = {
id: p.stream_id,
key,
@@ -156,6 +167,7 @@ function createUpload(p: UploadParams, account: string): UploadState {
finalPath,
fileRetention: p.file_retention,
timeoutId: reapTimer(key),
releaseStorageActivity,
};
uploads.set(key, state);
return state;
@@ -200,13 +212,17 @@ async function completeUpload(state: UploadState): Promise<ApiResponse> {
await new Promise<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve())));
} catch (err) {
out.destroy();
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete incomplete stream file %s: %s', state.finalPath, errorMessage(error));
}
throw err;
}
const sha256 = hash.digest('hex');
if (state.expectedSha256 && sha256 !== state.expectedSha256) {
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete invalid stream file %s: %s', state.finalPath, errorMessage(error));
}
throw new StreamError(`sha256 mismatch (expected ${state.expectedSha256}, got ${sha256})`);
}
@@ -337,7 +353,12 @@ const uploadFileStream = defineStreamAction({
function cleanDir(dir: string): number {
let removed = 0;
let entries: string[];
try { entries = fs.readdirSync(dir); } catch { return 0; } // dir absent → nothing to clean
try {
entries = fs.readdirSync(dir);
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return 0;
throw error;
}
for (const name of entries) {
try { fs.rmSync(path.join(dir, name), { recursive: true, force: true }); removed++; } catch (err) {
log.warn('failed to remove stream temp %s: %s', path.join(dir, name), err instanceof Error ? err.message : String(err));
@@ -352,14 +373,36 @@ const cleanStreamTempFile = defineAction({
returns: '{ message, removed }',
params: {},
run: () => {
const removed = cleanDir(STREAM_UPLOAD_DIR) + cleanDir(STREAM_DOWNLOAD_DIR);
// Active uploads' chunk dirs may have been wiped — drop their state too.
for (const k of [...uploads.keys()]) cleanupUpload(k, false);
return okResponse({ message: 'success', removed });
const result = clearInactiveStreamStorage();
for (const failure of result.failures) {
log.warn('failed to remove stream temp %s: %s', failure.item, failure.message);
}
if (result.failures.length > 0) {
throw new StreamError(`failed to remove ${result.failures.length} stream temp item(s)`);
}
return okResponse({
message: 'success',
removed: result.deletedFiles,
freed_bytes: result.freedBytes,
skipped_active: result.skippedActiveItems,
});
},
});
export const actions = [uploadFileStream, cleanStreamTempFile];
// Exposed for tests.
export const __test = { uploads, handleUpload, cleanDir, validateStreamId, STREAM_UPLOAD_DIR, MAX_CONCURRENT_STREAMS, MAX_CHUNKS };
export const __test = {
uploads,
handleUpload,
cleanupUpload,
cleanDir,
validateStreamId,
STREAM_UPLOAD_DIR,
MAX_CONCURRENT_STREAMS,
MAX_CHUNKS,
};
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+238
View File
@@ -0,0 +1,238 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
export interface StreamStorageSnapshot {
totalBytes: number;
fileCount: number;
activeItemCount: number;
}
export interface StreamStorageCleanupResult {
deletedFiles: number;
freedBytes: number;
skippedActiveItems: number;
failures: Array<{ item: string; message: string }>;
}
export class StreamStorage {
readonly root: string;
readonly uploadDir: string;
readonly downloadDir: string;
private readonly activeItems = new Map<number, string[]>();
private nextActiveItemId = 1;
constructor(root: string) {
this.root = resolveWithExistingAncestor(root);
this.uploadDir = path.join(this.root, 'upload');
this.downloadDir = path.join(this.root, 'download');
}
registerActiveItem(paths: string[]): () => void {
const normalized = paths.map((item) => {
const resolved = path.resolve(item);
if (!isStrictDescendant(this.root, resolved)) {
throw new Error(`active stream path is outside the managed root: ${item}`);
}
return resolved;
});
const id = this.nextActiveItemId++;
this.activeItems.set(id, normalized);
let released = false;
return () => {
if (released) return;
released = true;
this.activeItems.delete(id);
};
}
snapshot(): StreamStorageSnapshot {
if (!this.assertRootDirectoryOrMissing()) {
return {
totalBytes: 0,
fileCount: 0,
activeItemCount: this.activeItems.size,
};
}
let totalBytes = 0;
let fileCount = 0;
this.walkFiles(this.root, (stat) => {
totalBytes += stat.size;
fileCount += 1;
});
return { totalBytes, fileCount, activeItemCount: this.activeItems.size };
}
clearInactive(): StreamStorageCleanupResult {
const result: StreamStorageCleanupResult = {
deletedFiles: 0,
freedBytes: 0,
skippedActiveItems: this.activeItems.size,
failures: [],
};
if (!this.assertRootDirectoryOrMissing()) return result;
const activePaths = [...this.activeItems.values()].flat();
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(this.root, { withFileTypes: true });
} catch (error) {
result.failures.push({ item: '.', message: this.publicErrorMessage(error) });
return result;
}
for (const entry of entries) {
this.clearNode(path.join(this.root, entry.name), activePaths, result);
}
return result;
}
private assertRootDirectoryOrMissing(): boolean {
try {
const stat = fs.lstatSync(this.root);
if (!stat.isDirectory()) {
throw new Error(`managed stream root is not a directory: ${this.root}`);
}
return true;
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
}
private walkFiles(dir: string, visit: (stat: fs.Stats) => void): void {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const item = path.join(dir, entry.name);
const stat = fs.lstatSync(item);
if (stat.isDirectory()) this.walkFiles(item, visit);
else visit(stat);
}
}
private clearNode(
item: string,
activePaths: string[],
result: StreamStorageCleanupResult,
): void {
const resolved = path.resolve(item);
if (activePaths.some((active) => isSameOrDescendant(active, resolved))) return;
let stat: fs.Stats;
try {
stat = fs.lstatSync(resolved);
} catch (error) {
if (!isMissing(error)) {
result.failures.push({
item: this.displayPath(resolved),
message: this.publicErrorMessage(error),
});
}
return;
}
if (!stat.isDirectory()) {
try {
fs.unlinkSync(resolved);
result.deletedFiles += 1;
result.freedBytes += stat.size;
} catch (error) {
if (!isMissing(error)) {
result.failures.push({
item: this.displayPath(resolved),
message: this.publicErrorMessage(error),
});
}
}
return;
}
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(resolved, { withFileTypes: true });
} catch (error) {
result.failures.push({
item: this.displayPath(resolved),
message: this.publicErrorMessage(error),
});
return;
}
for (const entry of entries) {
this.clearNode(path.join(resolved, entry.name), activePaths, result);
}
try {
if (fs.readdirSync(resolved).length === 0) fs.rmdirSync(resolved);
} catch (error) {
if (!isMissing(error)) {
result.failures.push({
item: this.displayPath(resolved),
message: this.publicErrorMessage(error),
});
}
}
}
private displayPath(item: string): string {
const relative = path.relative(this.root, item);
return relative || '.';
}
private publicErrorMessage(error: unknown): string {
return errorMessage(error).split(this.root).join('[临时目录]');
}
}
function isStrictDescendant(root: string, candidate: string): boolean {
const relative = path.relative(root, candidate);
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
}
function isSameOrDescendant(root: string, candidate: string): boolean {
return root === candidate || isStrictDescendant(root, candidate);
}
function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function resolveWithExistingAncestor(input: string): string {
let existing = path.resolve(input);
const suffix: string[] = [];
while (true) {
try {
fs.lstatSync(existing);
break;
} catch (error) {
if (!isMissing(error)) throw error;
const parent = path.dirname(existing);
if (parent === existing) throw error;
suffix.unshift(path.basename(existing));
existing = parent;
}
}
const canonical = fs.realpathSync(existing);
return path.join(canonical, ...suffix);
}
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'snowluma-stream'));
export const STREAM_ROOT = streamStorage.root;
export const STREAM_UPLOAD_DIR = streamStorage.uploadDir;
export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir;
export function registerActiveStreamItem(paths: string[]): () => void {
return streamStorage.registerActiveItem(paths);
}
export function snapshotStreamStorage(): StreamStorageSnapshot {
return streamStorage.snapshot();
}
export function clearInactiveStreamStorage(): StreamStorageCleanupResult {
return streamStorage.clearInactive();
}