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:
33 files changed
+5115
-136
No files matched your search
@@ -1,6 +1,11 @@
|
||||
import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
|
||||
import {
|
||||
clearManagedLogs,
|
||||
configureFileTransport,
|
||||
getLogStorageStatus,
|
||||
} from '@snowluma/common/log-file-transport';
|
||||
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
|
||||
import {
|
||||
loadOneBotConfig,
|
||||
@@ -9,6 +14,10 @@ import {
|
||||
} from '@snowluma/onebot/config';
|
||||
import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config';
|
||||
import type { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import {
|
||||
clearInactiveStreamStorage,
|
||||
snapshotStreamStorage,
|
||||
} from '@snowluma/onebot/stream-storage';
|
||||
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
|
||||
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
|
||||
import { execSync } from 'child_process';
|
||||
@@ -55,6 +64,9 @@ import {
|
||||
import { getUpdateInfo } from './update-check';
|
||||
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
|
||||
import type { NotificationManager } from '../notifications/manager';
|
||||
import { StorageManagementService } from './storage-management';
|
||||
import { registerStorageRoutes } from './storage-routes';
|
||||
import { LogStorageSettingsManager } from './storage-settings';
|
||||
|
||||
const log = createLogger('WebUI');
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -524,6 +536,27 @@ export async function initWebUI(
|
||||
}
|
||||
|
||||
const app = new Hono();
|
||||
const storageManagement = new StorageManagementService({
|
||||
dataDir: 'data',
|
||||
getLogStatus: getLogStorageStatus,
|
||||
clearLogs: clearManagedLogs,
|
||||
temporary: {
|
||||
snapshot: snapshotStreamStorage,
|
||||
clearInactive: clearInactiveStreamStorage,
|
||||
},
|
||||
// Connection statuses include active and still-retiring generations.
|
||||
// A retiring instance may still hold SQLite handles after disappearing
|
||||
// from getInstances(), so it must continue to block destructive cleanup.
|
||||
listOnlineAccounts: () => oneBotManager.getConnectionStatuses()
|
||||
.map((account) => ({ uin: account.uin, nickname: account.nickname })),
|
||||
});
|
||||
const logStorageSettings = new LogStorageSettingsManager({
|
||||
readPersisted: readRuntimeConfig,
|
||||
readEnvOverrides: () => resolveRuntimeEnvOverrides(process.env),
|
||||
readEffective: getLogStorageStatus,
|
||||
persist: updateRuntimeConfig,
|
||||
apply: configureFileTransport,
|
||||
});
|
||||
|
||||
// ─── Anti-indexing ───────────────────────────────────────────────────────
|
||||
// The WebUI is an admin surface that has no business showing up in
|
||||
@@ -889,6 +922,30 @@ export async function initWebUI(
|
||||
});
|
||||
});
|
||||
|
||||
registerStorageRoutes(app, {
|
||||
storage: storageManagement,
|
||||
settings: logStorageSettings,
|
||||
audit: (event) => {
|
||||
log.info(
|
||||
'storage cleanup scope=%s accountScope=%s category=%s uin=%s deletedFiles=%d freedBytes=%d failures=%d',
|
||||
event.scope,
|
||||
event.accountScope,
|
||||
event.category ?? '-',
|
||||
event.uin ?? '-',
|
||||
event.deletedFiles,
|
||||
event.freedBytes,
|
||||
event.failureCount,
|
||||
);
|
||||
},
|
||||
reportError: (operation, error) => {
|
||||
log.error(
|
||||
'%s failed: %s',
|
||||
operation,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
app.post('/api/system/tls/cert', async (c) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type {
|
||||
LogCleanupResult,
|
||||
LogStorageStatus,
|
||||
} from '@snowluma/common/log-file-transport';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
|
||||
export interface TemporaryStorageSnapshot {
|
||||
totalBytes: number;
|
||||
fileCount: number;
|
||||
activeItemCount: number;
|
||||
}
|
||||
|
||||
export interface TemporaryCleanupResult {
|
||||
deletedFiles: number;
|
||||
freedBytes: number;
|
||||
skippedActiveItems: number;
|
||||
failures: Array<{ item: string; message: string }>;
|
||||
}
|
||||
|
||||
export interface TemporaryStorageAdapter {
|
||||
snapshot(): TemporaryStorageSnapshot;
|
||||
clearInactive(): TemporaryCleanupResult;
|
||||
}
|
||||
|
||||
export interface OnlineStorageAccount {
|
||||
uin: string;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export interface AccountStorageSnapshot {
|
||||
uin: string;
|
||||
nickname?: string;
|
||||
online: boolean;
|
||||
messagesBytes: number;
|
||||
mediaBytes: number;
|
||||
reactionsBytes: number;
|
||||
totalBytes: number;
|
||||
}
|
||||
|
||||
export type PublicLogStorageStatus = Omit<LogStorageStatus, 'directory'>;
|
||||
|
||||
export function publicLogStorageStatus(status: LogStorageStatus): PublicLogStorageStatus {
|
||||
const { directory, ...publicStatus } = status;
|
||||
if (!publicStatus.lastError) return publicStatus;
|
||||
return {
|
||||
...publicStatus,
|
||||
lastError: redactFilesystemPath(publicStatus.lastError, directory, '[日志目录]'),
|
||||
};
|
||||
}
|
||||
|
||||
export interface PublicLogCleanupResult extends Omit<LogCleanupResult, 'status'> {
|
||||
status: PublicLogStorageStatus;
|
||||
}
|
||||
|
||||
export interface StorageSnapshot {
|
||||
logs: PublicLogStorageStatus;
|
||||
temporary: TemporaryStorageSnapshot;
|
||||
accounts: AccountStorageSnapshot[];
|
||||
totals: {
|
||||
logsBytes: number;
|
||||
temporaryBytes: number;
|
||||
accountDataBytes: number;
|
||||
managedBytes: number;
|
||||
};
|
||||
}
|
||||
|
||||
export type AccountStorageCategory = 'messages' | 'media' | 'reactions';
|
||||
|
||||
export interface AccountDataCleanupResult {
|
||||
category: AccountStorageCategory;
|
||||
uins: string[];
|
||||
deletedFiles: number;
|
||||
freedBytes: number;
|
||||
failures: Array<{ uin: string; file: string; message: string }>;
|
||||
}
|
||||
|
||||
export class StorageManagementInputError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'StorageManagementInputError';
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageAccountOnlineError extends Error {
|
||||
constructor(readonly uins: string[]) {
|
||||
super(`account data cleanup requires offline accounts: ${uins.join(', ')}`);
|
||||
this.name = 'StorageAccountOnlineError';
|
||||
}
|
||||
}
|
||||
|
||||
export interface StorageManagementDependencies {
|
||||
dataDir: string;
|
||||
getLogStatus(): LogStorageStatus;
|
||||
clearLogs(): Promise<LogCleanupResult>;
|
||||
temporary: TemporaryStorageAdapter;
|
||||
listOnlineAccounts(): OnlineStorageAccount[];
|
||||
}
|
||||
|
||||
const DATABASE_FILES = {
|
||||
messages: ['messages.db', 'messages.db-wal', 'messages.db-shm', 'messages.db-journal'],
|
||||
media: ['media.db', 'media.db-wal', 'media.db-shm', 'media.db-journal'],
|
||||
reactions: ['reactions.db', 'reactions.db-wal', 'reactions.db-shm', 'reactions.db-journal'],
|
||||
} as const;
|
||||
|
||||
export class StorageManagementService {
|
||||
constructor(private readonly deps: StorageManagementDependencies) {}
|
||||
|
||||
snapshot(): StorageSnapshot {
|
||||
const logStatus = this.deps.getLogStatus();
|
||||
const logs = publicLogStorageStatus(logStatus);
|
||||
const temporary = this.deps.temporary.snapshot();
|
||||
const accounts = this.accountSnapshots();
|
||||
const accountDataBytes = accounts.reduce((sum, account) => sum + account.totalBytes, 0);
|
||||
return {
|
||||
logs,
|
||||
temporary,
|
||||
accounts,
|
||||
totals: {
|
||||
logsBytes: logs.totalBytes,
|
||||
temporaryBytes: temporary.totalBytes,
|
||||
accountDataBytes,
|
||||
managedBytes: logs.totalBytes + temporary.totalBytes + accountDataBytes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async clearLogs(): Promise<PublicLogCleanupResult> {
|
||||
const result = await this.deps.clearLogs();
|
||||
return {
|
||||
...result,
|
||||
failures: result.failures.map((failure) => ({
|
||||
...failure,
|
||||
message: redactFilesystemPath(
|
||||
failure.message,
|
||||
result.status.directory,
|
||||
'[日志目录]',
|
||||
),
|
||||
})),
|
||||
status: publicLogStorageStatus(result.status),
|
||||
};
|
||||
}
|
||||
|
||||
clearTemporary(): TemporaryCleanupResult {
|
||||
return this.deps.temporary.clearInactive();
|
||||
}
|
||||
|
||||
clearAccountData(category: string, uin: string): AccountDataCleanupResult {
|
||||
const validatedCategory = validateAccountStorageCategory(category);
|
||||
if (!isRealUin(uin)) {
|
||||
throw new StorageManagementInputError(`invalid UIN: ${uin}`);
|
||||
}
|
||||
return this.clearAccountDataForUins(validatedCategory, [uin]);
|
||||
}
|
||||
|
||||
clearAllAccountData(category: string): AccountDataCleanupResult {
|
||||
const validatedCategory = validateAccountStorageCategory(category);
|
||||
const uins = listDirectoryNames(this.deps.dataDir)
|
||||
.filter((name) => isRealUin(name))
|
||||
.sort((a, b) => Number(a) - Number(b));
|
||||
return this.clearAccountDataForUins(validatedCategory, uins);
|
||||
}
|
||||
|
||||
private clearAccountDataForUins(
|
||||
category: AccountStorageCategory,
|
||||
uins: string[],
|
||||
): AccountDataCleanupResult {
|
||||
const hasManagedRoot = assertManagedDataRootOrMissing(this.deps.dataDir);
|
||||
const onlineUins = new Set(
|
||||
this.deps.listOnlineAccounts()
|
||||
.map((account) => account.uin)
|
||||
.filter((uin) => isRealUin(uin)),
|
||||
);
|
||||
const blockedUins = uins.filter((uin) => onlineUins.has(uin));
|
||||
if (blockedUins.length > 0) throw new StorageAccountOnlineError(blockedUins);
|
||||
|
||||
const failures: AccountDataCleanupResult['failures'] = [];
|
||||
let deletedFiles = 0;
|
||||
let freedBytes = 0;
|
||||
if (!hasManagedRoot) {
|
||||
return { category, uins, deletedFiles, freedBytes, failures };
|
||||
}
|
||||
for (const uin of uins) {
|
||||
const dir = path.join(this.deps.dataDir, uin);
|
||||
if (!isManagedDirectory(dir)) continue;
|
||||
for (const name of DATABASE_FILES[category]) {
|
||||
const filePath = path.join(dir, name);
|
||||
let bytes: number;
|
||||
try {
|
||||
const stat = fs.lstatSync(filePath);
|
||||
if (!stat.isFile()) continue;
|
||||
bytes = stat.size;
|
||||
} catch (error) {
|
||||
if (isMissing(error)) continue;
|
||||
failures.push({
|
||||
uin,
|
||||
file: name,
|
||||
message: redactFilesystemPath(
|
||||
errorMessage(error),
|
||||
filePath,
|
||||
'[账号数据库]',
|
||||
),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
fs.unlinkSync(filePath);
|
||||
deletedFiles += 1;
|
||||
freedBytes += bytes;
|
||||
} catch (error) {
|
||||
if (isMissing(error)) continue;
|
||||
failures.push({
|
||||
uin,
|
||||
file: name,
|
||||
message: redactFilesystemPath(
|
||||
errorMessage(error),
|
||||
filePath,
|
||||
'[账号数据库]',
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return { category, uins, deletedFiles, freedBytes, failures };
|
||||
}
|
||||
|
||||
private accountSnapshots(): AccountStorageSnapshot[] {
|
||||
const online = new Map(
|
||||
this.deps.listOnlineAccounts()
|
||||
.filter((account) => isRealUin(account.uin))
|
||||
.map((account) => [account.uin, account.nickname]),
|
||||
);
|
||||
const uins = new Set(online.keys());
|
||||
for (const name of listDirectoryNames(this.deps.dataDir)) {
|
||||
if (isRealUin(name)) uins.add(name);
|
||||
}
|
||||
|
||||
return [...uins]
|
||||
.sort((a, b) => Number(a) - Number(b))
|
||||
.map((uin) => {
|
||||
const dir = path.join(this.deps.dataDir, uin);
|
||||
const managedDirectory = isManagedDirectory(dir);
|
||||
const messagesBytes = managedDirectory
|
||||
? sumAllowlistedFiles(dir, DATABASE_FILES.messages)
|
||||
: 0;
|
||||
const mediaBytes = managedDirectory
|
||||
? sumAllowlistedFiles(dir, DATABASE_FILES.media)
|
||||
: 0;
|
||||
const reactionsBytes = managedDirectory
|
||||
? sumAllowlistedFiles(dir, DATABASE_FILES.reactions)
|
||||
: 0;
|
||||
const nickname = online.get(uin);
|
||||
return {
|
||||
uin,
|
||||
...(nickname ? { nickname } : {}),
|
||||
online: online.has(uin),
|
||||
messagesBytes,
|
||||
mediaBytes,
|
||||
reactionsBytes,
|
||||
totalBytes: messagesBytes + mediaBytes + reactionsBytes,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function listDirectoryNames(dir: string): string[] {
|
||||
if (!assertManagedDataRootOrMissing(dir)) return [];
|
||||
try {
|
||||
return fs.readdirSync(dir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => entry.name);
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function assertManagedDataRootOrMissing(dir: string): boolean {
|
||||
try {
|
||||
const stat = fs.lstatSync(dir);
|
||||
if (!stat.isDirectory()) {
|
||||
throw new Error('managed data root must be a real directory');
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function sumAllowlistedFiles(dir: string, names: readonly string[]): number {
|
||||
let total = 0;
|
||||
for (const name of names) {
|
||||
const filePath = path.join(dir, name);
|
||||
try {
|
||||
const stat = fs.lstatSync(filePath);
|
||||
if (stat.isFile()) total += stat.size;
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
|
||||
}
|
||||
|
||||
function isManagedDirectory(dir: string): boolean {
|
||||
try {
|
||||
return fs.lstatSync(dir).isDirectory();
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function validateAccountStorageCategory(value: string): AccountStorageCategory {
|
||||
if (value === 'messages' || value === 'media' || value === 'reactions') return value;
|
||||
throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function redactFilesystemPath(message: string, filePath: string, label: string): string {
|
||||
const absolute = path.resolve(filePath);
|
||||
return message
|
||||
.split(absolute).join(label)
|
||||
.split(filePath).join(label);
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import type { Hono } from 'hono';
|
||||
import {
|
||||
StorageAccountOnlineError,
|
||||
StorageManagementInputError,
|
||||
type AccountDataCleanupResult,
|
||||
type AccountStorageCategory,
|
||||
type PublicLogCleanupResult,
|
||||
type StorageManagementService,
|
||||
type StorageSnapshot,
|
||||
type TemporaryCleanupResult,
|
||||
} from './storage-management';
|
||||
import {
|
||||
StorageSettingsInputError,
|
||||
StorageSettingsLockedError,
|
||||
StorageSettingsTransactionError,
|
||||
type LogStorageSettingsManager,
|
||||
} from './storage-settings';
|
||||
|
||||
export const ALL_ACCOUNTS_CONFIRMATION = '清理全部账号';
|
||||
|
||||
type StorageCleanupRequest =
|
||||
| { scope: 'logs' }
|
||||
| { scope: 'temporary' }
|
||||
| { scope: 'account'; category: AccountStorageCategory; uin: string }
|
||||
| {
|
||||
scope: 'allAccounts';
|
||||
category: AccountStorageCategory;
|
||||
confirmation: typeof ALL_ACCOUNTS_CONFIRMATION;
|
||||
};
|
||||
|
||||
type StorageCleanupResult =
|
||||
| PublicLogCleanupResult
|
||||
| TemporaryCleanupResult
|
||||
| AccountDataCleanupResult;
|
||||
|
||||
export interface StorageCleanupAuditEvent {
|
||||
scope: StorageCleanupRequest['scope'];
|
||||
accountScope: 'global' | 'single' | 'all';
|
||||
category?: AccountStorageCategory;
|
||||
uin?: string;
|
||||
deletedFiles: number;
|
||||
freedBytes: number;
|
||||
failureCount: number;
|
||||
}
|
||||
|
||||
export interface LastStorageCleanup extends StorageCleanupAuditEvent {
|
||||
at: string;
|
||||
skippedActiveItems?: number;
|
||||
failures: Array<{ item: string; message: string }>;
|
||||
}
|
||||
|
||||
export interface StorageRouteDependencies {
|
||||
storage: Pick<
|
||||
StorageManagementService,
|
||||
'snapshot'
|
||||
| 'clearLogs'
|
||||
| 'clearTemporary'
|
||||
| 'clearAccountData'
|
||||
| 'clearAllAccountData'
|
||||
>;
|
||||
settings: Pick<LogStorageSettingsManager, 'read' | 'update'>;
|
||||
audit(event: StorageCleanupAuditEvent): void;
|
||||
reportError(operation: string, error: unknown): void;
|
||||
now?: () => Date;
|
||||
}
|
||||
|
||||
export function registerStorageRoutes(app: Hono, deps: StorageRouteDependencies): void {
|
||||
let lastCleanup: LastStorageCleanup | null = null;
|
||||
let mutationQueue: Promise<void> = Promise.resolve();
|
||||
const serializeMutation = <T>(operation: () => Promise<T>): Promise<T> => {
|
||||
const result = mutationQueue.then(operation);
|
||||
mutationQueue = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
};
|
||||
|
||||
app.get('/api/system/storage', (c) => {
|
||||
try {
|
||||
return c.json({
|
||||
settings: deps.settings.read(),
|
||||
snapshot: deps.storage.snapshot(),
|
||||
lastCleanup,
|
||||
});
|
||||
} catch (error) {
|
||||
deps.reportError('read storage snapshot', error);
|
||||
return c.json({ success: false, message: '读取存储信息失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/system/storage/settings', async (c) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
|
||||
let result: Awaited<ReturnType<LogStorageSettingsManager['update']>>;
|
||||
try {
|
||||
result = await serializeMutation(() => deps.settings.update(body));
|
||||
} catch (error) {
|
||||
if (error instanceof StorageSettingsInputError) {
|
||||
return c.json({ success: false, message: error.message }, 400);
|
||||
}
|
||||
if (error instanceof StorageSettingsLockedError) {
|
||||
return c.json({
|
||||
success: false,
|
||||
message: '这些设置已由环境变量锁定',
|
||||
lockedFields: error.fields,
|
||||
}, 409);
|
||||
}
|
||||
deps.reportError('update log storage settings', error);
|
||||
if (error instanceof StorageSettingsTransactionError) {
|
||||
deps.reportError('update log storage settings operation', error.operationError);
|
||||
error.rollbackErrors.forEach((rollbackError, index) => {
|
||||
deps.reportError(
|
||||
`rollback log storage settings step=${String(index + 1)}`,
|
||||
rollbackError,
|
||||
);
|
||||
});
|
||||
return c.json({
|
||||
success: false,
|
||||
message: error.rollbackErrors.length > 0
|
||||
? '保存失败且回滚不完整,请立即检查服务器日志'
|
||||
: '保存失败,原设置已恢复',
|
||||
}, 500);
|
||||
}
|
||||
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
|
||||
try {
|
||||
return c.json({
|
||||
success: true,
|
||||
settings: result.settings,
|
||||
status: result.status,
|
||||
snapshot: deps.storage.snapshot(),
|
||||
});
|
||||
} catch (error) {
|
||||
deps.reportError('refresh storage snapshot after settings update', error);
|
||||
return c.json({
|
||||
success: false,
|
||||
message: '设置已生效,但刷新存储统计失败,请检查服务器日志',
|
||||
settings: result.settings,
|
||||
status: result.status,
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/system/storage/cleanup', async (c) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
|
||||
let request: StorageCleanupRequest;
|
||||
try {
|
||||
request = parseCleanupRequest(body);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '请求格式错误';
|
||||
return c.json({ success: false, message }, 400);
|
||||
}
|
||||
|
||||
let cleanup: StorageCleanupResult;
|
||||
try {
|
||||
cleanup = await serializeMutation(() => executeCleanup(deps.storage, request));
|
||||
} catch (error) {
|
||||
if (error instanceof StorageAccountOnlineError) {
|
||||
return c.json({
|
||||
success: false,
|
||||
message: '账号在线,必须先下线后才能清理数据库',
|
||||
onlineUins: error.uins,
|
||||
}, 409);
|
||||
}
|
||||
if (error instanceof StorageManagementInputError) {
|
||||
return c.json({ success: false, message: error.message }, 400);
|
||||
}
|
||||
deps.reportError(`clean storage scope=${request.scope}`, error);
|
||||
return c.json({ success: false, message: '清理失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
|
||||
const auditEvent: StorageCleanupAuditEvent = {
|
||||
scope: request.scope,
|
||||
accountScope: accountScope(request),
|
||||
...('category' in request ? { category: request.category } : {}),
|
||||
...(request.scope === 'account' ? { uin: request.uin } : {}),
|
||||
deletedFiles: cleanup.deletedFiles,
|
||||
freedBytes: cleanup.freedBytes,
|
||||
failureCount: cleanup.failures.length,
|
||||
};
|
||||
deps.audit(auditEvent);
|
||||
for (const failure of cleanup.failures) {
|
||||
deps.reportError(
|
||||
`clean storage scope=${request.scope} item=${cleanupFailureItem(failure)}`,
|
||||
new Error(failure.message),
|
||||
);
|
||||
}
|
||||
lastCleanup = {
|
||||
at: (deps.now?.() ?? new Date()).toISOString(),
|
||||
...auditEvent,
|
||||
...('skippedActiveItems' in cleanup
|
||||
? { skippedActiveItems: cleanup.skippedActiveItems }
|
||||
: {}),
|
||||
failures: cleanup.failures.map((failure) => ({
|
||||
item: cleanupFailureItem(failure),
|
||||
message: failure.message,
|
||||
})),
|
||||
};
|
||||
|
||||
let snapshot: StorageSnapshot;
|
||||
try {
|
||||
snapshot = deps.storage.snapshot();
|
||||
} catch (error) {
|
||||
deps.reportError(`refresh storage snapshot after cleanup scope=${request.scope}`, error);
|
||||
return c.json({
|
||||
success: false,
|
||||
message: '清理已执行,但刷新存储统计失败,请检查服务器日志',
|
||||
scope: request.scope,
|
||||
cleanup,
|
||||
lastCleanup,
|
||||
}, 500);
|
||||
}
|
||||
|
||||
const success = cleanup.failures.length === 0;
|
||||
return c.json({
|
||||
success,
|
||||
...(success ? {} : { message: '部分文件清理失败,请检查失败明细' }),
|
||||
scope: request.scope,
|
||||
cleanup,
|
||||
snapshot,
|
||||
lastCleanup,
|
||||
}, success ? 200 : 500);
|
||||
});
|
||||
}
|
||||
|
||||
function parseCleanupRequest(body: unknown): StorageCleanupRequest {
|
||||
if (!isObject(body) || typeof body.scope !== 'string') {
|
||||
throw new StorageManagementInputError('scope is required');
|
||||
}
|
||||
|
||||
if (body.scope === 'logs' || body.scope === 'temporary') {
|
||||
assertExactKeys(body, ['scope']);
|
||||
return { scope: body.scope };
|
||||
}
|
||||
|
||||
if (body.scope === 'account') {
|
||||
assertExactKeys(body, ['scope', 'category', 'uin']);
|
||||
const category = parseCategory(body.category);
|
||||
if (typeof body.uin !== 'string' || !isRealUin(body.uin)) {
|
||||
throw new StorageManagementInputError('invalid UIN');
|
||||
}
|
||||
return { scope: 'account', category, uin: body.uin };
|
||||
}
|
||||
|
||||
if (body.scope === 'allAccounts') {
|
||||
assertExactKeys(body, ['scope', 'category', 'confirmation']);
|
||||
const category = parseCategory(body.category);
|
||||
if (body.confirmation !== ALL_ACCOUNTS_CONFIRMATION) {
|
||||
throw new StorageManagementInputError('all-account cleanup requires confirmation');
|
||||
}
|
||||
return {
|
||||
scope: 'allAccounts',
|
||||
category,
|
||||
confirmation: ALL_ACCOUNTS_CONFIRMATION,
|
||||
};
|
||||
}
|
||||
|
||||
throw new StorageManagementInputError(`unsupported cleanup scope: ${body.scope}`);
|
||||
}
|
||||
|
||||
async function executeCleanup(
|
||||
storage: StorageRouteDependencies['storage'],
|
||||
request: StorageCleanupRequest,
|
||||
): Promise<StorageCleanupResult> {
|
||||
if (request.scope === 'logs') return storage.clearLogs();
|
||||
if (request.scope === 'temporary') return storage.clearTemporary();
|
||||
if (request.scope === 'account') {
|
||||
return storage.clearAccountData(request.category, request.uin);
|
||||
}
|
||||
return storage.clearAllAccountData(request.category);
|
||||
}
|
||||
|
||||
function parseCategory(value: unknown): AccountStorageCategory {
|
||||
if (value === 'messages' || value === 'media' || value === 'reactions') return value;
|
||||
throw new StorageManagementInputError('unsupported account storage category');
|
||||
}
|
||||
|
||||
function assertExactKeys(body: Record<string, unknown>, allowed: string[]): void {
|
||||
const allowedSet = new Set(allowed);
|
||||
const unknown = Object.keys(body).filter((key) => !allowedSet.has(key));
|
||||
const missing = allowed.filter((key) => !(key in body));
|
||||
if (unknown.length > 0 || missing.length > 0) {
|
||||
throw new StorageManagementInputError('cleanup request has unexpected or missing fields');
|
||||
}
|
||||
}
|
||||
|
||||
function accountScope(request: StorageCleanupRequest): StorageCleanupAuditEvent['accountScope'] {
|
||||
if (request.scope === 'account') return 'single';
|
||||
if (request.scope === 'allAccounts') return 'all';
|
||||
return 'global';
|
||||
}
|
||||
|
||||
function cleanupFailureItem(
|
||||
failure: StorageCleanupResult['failures'][number],
|
||||
): string {
|
||||
if ('uin' in failure) return `${failure.uin}/${failure.file}`;
|
||||
if ('file' in failure) return failure.file;
|
||||
return failure.item;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
import type {
|
||||
LogStoragePolicy,
|
||||
LogStorageStatus,
|
||||
} from '@snowluma/common/log-file-transport';
|
||||
import {
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
DEFAULT_LOG_PER_UIN,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
type RuntimeConfig,
|
||||
} from '@snowluma/common/runtime';
|
||||
import {
|
||||
publicLogStorageStatus,
|
||||
type PublicLogStorageStatus,
|
||||
} from './storage-management';
|
||||
|
||||
export type LogStorageSettingsField =
|
||||
| 'logMaxTotalMb'
|
||||
| 'logRetainDays'
|
||||
| 'logPerUin';
|
||||
|
||||
export interface LogStorageSettings {
|
||||
logMaxTotalMb: number;
|
||||
logRetainDays: number;
|
||||
logPerUin: boolean;
|
||||
}
|
||||
|
||||
export interface LogStorageSettingsState {
|
||||
saved: LogStorageSettings;
|
||||
effective: LogStorageSettings;
|
||||
envOverrides: LogStorageSettingsField[];
|
||||
}
|
||||
|
||||
export interface LogStorageSettingsUpdateResult {
|
||||
settings: LogStorageSettingsState;
|
||||
status: PublicLogStorageStatus;
|
||||
}
|
||||
|
||||
export class StorageSettingsInputError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'StorageSettingsInputError';
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageSettingsLockedError extends Error {
|
||||
constructor(readonly fields: LogStorageSettingsField[]) {
|
||||
super(`settings are locked by environment variables: ${fields.join(', ')}`);
|
||||
this.name = 'StorageSettingsLockedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageSettingsTransactionError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly operationError: unknown,
|
||||
readonly rollbackErrors: unknown[],
|
||||
) {
|
||||
super(message, { cause: operationError });
|
||||
this.name = 'StorageSettingsTransactionError';
|
||||
}
|
||||
}
|
||||
|
||||
export interface LogStorageSettingsDependencies {
|
||||
readPersisted(): RuntimeConfig;
|
||||
readEnvOverrides(): Partial<RuntimeConfig>;
|
||||
readEffective(): LogStorageStatus;
|
||||
persist(patch: Partial<RuntimeConfig>): RuntimeConfig;
|
||||
apply(policy: LogStoragePolicy): Promise<LogStorageStatus>;
|
||||
}
|
||||
|
||||
const SETTINGS_FIELDS: LogStorageSettingsField[] = [
|
||||
'logMaxTotalMb',
|
||||
'logRetainDays',
|
||||
'logPerUin',
|
||||
];
|
||||
const SETTINGS_FIELD_SET = new Set<string>(SETTINGS_FIELDS);
|
||||
|
||||
export class LogStorageSettingsManager {
|
||||
private updateQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(private readonly deps: LogStorageSettingsDependencies) {}
|
||||
|
||||
read(): LogStorageSettingsState {
|
||||
return settingsState(
|
||||
this.deps.readPersisted(),
|
||||
this.deps.readEnvOverrides(),
|
||||
settingsFromStatus(this.deps.readEffective()),
|
||||
);
|
||||
}
|
||||
|
||||
update(body: unknown): Promise<LogStorageSettingsUpdateResult> {
|
||||
const operation = this.updateQueue.then(() => this.performUpdate(body));
|
||||
this.updateQueue = operation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return operation;
|
||||
}
|
||||
|
||||
private async performUpdate(body: unknown): Promise<LogStorageSettingsUpdateResult> {
|
||||
const patch = coerceLogStorageSettingsPatch(body);
|
||||
const previousRuntime = this.deps.readPersisted();
|
||||
const envOverrides = this.deps.readEnvOverrides();
|
||||
const previous = settingsState(
|
||||
previousRuntime,
|
||||
envOverrides,
|
||||
settingsFromStatus(this.deps.readEffective()),
|
||||
);
|
||||
const locked = SETTINGS_FIELDS.filter(
|
||||
(field) => field in patch && field in envOverrides,
|
||||
);
|
||||
if (locked.length > 0) throw new StorageSettingsLockedError(locked);
|
||||
|
||||
const nextSaved = { ...previous.saved, ...patch };
|
||||
const nextEffective = { ...previous.effective, ...patch };
|
||||
const previousPolicy = toPolicy(previous.effective);
|
||||
const nextPolicy = toPolicy(nextEffective);
|
||||
|
||||
let status: LogStorageStatus;
|
||||
try {
|
||||
status = await this.deps.apply(nextPolicy);
|
||||
assertApplied(status, nextPolicy);
|
||||
} catch (error) {
|
||||
const rollbackErrors = await this.rollbackRuntime(previousPolicy);
|
||||
throw new StorageSettingsTransactionError(
|
||||
rollbackErrors.length > 0
|
||||
? 'failed to apply log settings and runtime rollback was incomplete'
|
||||
: 'failed to apply log settings; runtime state was rolled back',
|
||||
error,
|
||||
rollbackErrors,
|
||||
);
|
||||
}
|
||||
|
||||
let persistedRuntime: RuntimeConfig;
|
||||
try {
|
||||
persistedRuntime = this.deps.persist(patch);
|
||||
assertPersistedSettings(persistedRuntime, nextSaved);
|
||||
} catch (error) {
|
||||
const rollbackErrors = await this.rollbackAll(previousPolicy, previousRuntime);
|
||||
throw new StorageSettingsTransactionError(
|
||||
rollbackErrors.length > 0
|
||||
? 'failed to persist log settings and rollback was incomplete'
|
||||
: 'failed to persist log settings; previous settings were restored',
|
||||
error,
|
||||
rollbackErrors,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
settings: settingsState(
|
||||
persistedRuntime,
|
||||
envOverrides,
|
||||
settingsFromStatus(status),
|
||||
),
|
||||
status: publicLogStorageStatus(status),
|
||||
};
|
||||
}
|
||||
|
||||
private async rollbackRuntime(policy: LogStoragePolicy): Promise<unknown[]> {
|
||||
try {
|
||||
const status = await this.deps.apply(policy);
|
||||
assertApplied(status, policy);
|
||||
return [];
|
||||
} catch (error) {
|
||||
return [error];
|
||||
}
|
||||
}
|
||||
|
||||
private async rollbackAll(
|
||||
policy: LogStoragePolicy,
|
||||
runtime: RuntimeConfig,
|
||||
): Promise<unknown[]> {
|
||||
const errors = await this.rollbackRuntime(policy);
|
||||
try {
|
||||
this.deps.persist(runtime);
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
|
||||
function coerceLogStorageSettingsPatch(body: unknown): Partial<LogStorageSettings> {
|
||||
if (!isObject(body)) throw new StorageSettingsInputError('body must be an object');
|
||||
const keys = Object.keys(body);
|
||||
if (keys.length === 0) throw new StorageSettingsInputError('at least one setting is required');
|
||||
const unknown = keys.filter((key) => !SETTINGS_FIELD_SET.has(key));
|
||||
if (unknown.length > 0) {
|
||||
throw new StorageSettingsInputError(`unknown setting: ${unknown.join(', ')}`);
|
||||
}
|
||||
|
||||
const patch: Partial<LogStorageSettings> = {};
|
||||
if ('logMaxTotalMb' in body) {
|
||||
const value = body.logMaxTotalMb;
|
||||
if (
|
||||
typeof value !== 'number'
|
||||
|| !Number.isSafeInteger(value)
|
||||
|| value < 1
|
||||
|| value > MAX_LOG_TOTAL_MB
|
||||
) {
|
||||
throw new StorageSettingsInputError(
|
||||
`logMaxTotalMb must be an integer in 1..${MAX_LOG_TOTAL_MB}`,
|
||||
);
|
||||
}
|
||||
patch.logMaxTotalMb = value;
|
||||
}
|
||||
if ('logRetainDays' in body) {
|
||||
const value = body.logRetainDays;
|
||||
if (
|
||||
typeof value !== 'number'
|
||||
|| !Number.isSafeInteger(value)
|
||||
|| value < 0
|
||||
|| value > MAX_LOG_RETAIN_DAYS
|
||||
) {
|
||||
throw new StorageSettingsInputError(
|
||||
`logRetainDays must be an integer in 0..${MAX_LOG_RETAIN_DAYS}`,
|
||||
);
|
||||
}
|
||||
patch.logRetainDays = value;
|
||||
}
|
||||
if ('logPerUin' in body) {
|
||||
if (typeof body.logPerUin !== 'boolean') {
|
||||
throw new StorageSettingsInputError('logPerUin must be a boolean');
|
||||
}
|
||||
patch.logPerUin = body.logPerUin;
|
||||
}
|
||||
return patch;
|
||||
}
|
||||
|
||||
function settingsState(
|
||||
runtime: RuntimeConfig,
|
||||
envOverrides: Partial<RuntimeConfig>,
|
||||
liveEffective?: LogStorageSettings,
|
||||
): LogStorageSettingsState {
|
||||
const saved = settingsFromRuntime(runtime);
|
||||
const envOverridesList = SETTINGS_FIELDS.filter((field) => field in envOverrides);
|
||||
const effective = liveEffective ?? {
|
||||
...saved,
|
||||
...settingsPatchFromRuntime(envOverrides),
|
||||
};
|
||||
return { saved, effective, envOverrides: envOverridesList };
|
||||
}
|
||||
|
||||
function settingsFromStatus(status: LogStorageStatus): LogStorageSettings {
|
||||
const maxTotalMb = status.maxTotalBytes / (1024 * 1024);
|
||||
if (!Number.isSafeInteger(maxTotalMb)) {
|
||||
throw new Error('live log storage limit is not an integer number of megabytes');
|
||||
}
|
||||
return {
|
||||
logMaxTotalMb: maxTotalMb,
|
||||
logRetainDays: status.retainDays,
|
||||
logPerUin: status.perUinEnabled,
|
||||
};
|
||||
}
|
||||
|
||||
function settingsFromRuntime(runtime: RuntimeConfig): LogStorageSettings {
|
||||
return {
|
||||
logMaxTotalMb: runtime.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
logRetainDays: runtime.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
|
||||
logPerUin: runtime.logPerUin ?? DEFAULT_LOG_PER_UIN,
|
||||
};
|
||||
}
|
||||
|
||||
function settingsPatchFromRuntime(runtime: Partial<RuntimeConfig>): Partial<LogStorageSettings> {
|
||||
const patch: Partial<LogStorageSettings> = {};
|
||||
if (runtime.logMaxTotalMb !== undefined) patch.logMaxTotalMb = runtime.logMaxTotalMb;
|
||||
if (runtime.logRetainDays !== undefined) patch.logRetainDays = runtime.logRetainDays;
|
||||
if (runtime.logPerUin !== undefined) patch.logPerUin = runtime.logPerUin;
|
||||
return patch;
|
||||
}
|
||||
|
||||
function toPolicy(settings: LogStorageSettings): LogStoragePolicy {
|
||||
return {
|
||||
maxTotalMb: settings.logMaxTotalMb,
|
||||
retainDays: settings.logRetainDays,
|
||||
perUinEnabled: settings.logPerUin,
|
||||
};
|
||||
}
|
||||
|
||||
function assertApplied(status: LogStorageStatus, policy: LogStoragePolicy): void {
|
||||
const expectedBytes = policy.maxTotalMb * 1024 * 1024;
|
||||
if (
|
||||
status.state === 'warning'
|
||||
|| status.state === 'degraded'
|
||||
|| status.lastError !== undefined
|
||||
|| status.maxTotalBytes !== expectedBytes
|
||||
|| status.retainDays !== policy.retainDays
|
||||
|| status.perUinEnabled !== policy.perUinEnabled
|
||||
) {
|
||||
throw new Error(status.lastError ?? 'log storage policy did not become effective');
|
||||
}
|
||||
}
|
||||
|
||||
function assertPersistedSettings(
|
||||
runtime: RuntimeConfig,
|
||||
expected: LogStorageSettings,
|
||||
): void {
|
||||
const actual = settingsFromRuntime(runtime);
|
||||
if (
|
||||
actual.logMaxTotalMb !== expected.logMaxTotalMb
|
||||
|| actual.logRetainDays !== expected.logRetainDays
|
||||
|| actual.logPerUin !== expected.logPerUin
|
||||
) {
|
||||
throw new Error('persisted log storage settings do not match the requested values');
|
||||
}
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
Reference in new issue
Block a user