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

+12 -1
View File
@@ -1,6 +1,12 @@
import { HookManager } from '@snowluma/bridge';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import {
DEFAULT_LOG_MAX_TOTAL_MB,
DEFAULT_LOG_PER_UIN,
DEFAULT_LOG_RETAIN_DAYS,
loadRuntimeConfig,
} from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
@@ -28,6 +34,11 @@ process.on('uncaughtException', (error) => {
});
async function main() {
await configureFileTransport({
maxTotalMb: runtimeConfig.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
retainDays: runtimeConfig.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
});
log.info('SnowLuma starting');
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
+57
View File
@@ -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);
}
+317
View File
@@ -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);
}
+312
View File
@@ -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);
}
+279 -1
View File
@@ -13,7 +13,9 @@ const ENV_KEYS = [
'SNOWLUMA_LOG_FILE',
'SNOWLUMA_LOG_DIR',
'SNOWLUMA_LOG_MAX_MB',
'SNOWLUMA_LOG_MAX_TOTAL_MB',
'SNOWLUMA_LOG_RETAIN_DAYS',
'SNOWLUMA_LOG_PER_UIN',
] as const;
const savedEnv: Record<string, string | undefined> = {};
@@ -35,7 +37,9 @@ beforeEach(() => {
SNOWLUMA_LOG_DIR: tmpDir,
SNOWLUMA_LOG_FILE: '1',
SNOWLUMA_LOG_MAX_MB: '1',
SNOWLUMA_LOG_MAX_TOTAL_MB: '2',
SNOWLUMA_LOG_RETAIN_DAYS: '7',
SNOWLUMA_LOG_PER_UIN: '0',
});
});
@@ -84,6 +88,41 @@ describe('FileTransport', () => {
expect(split).toBeDefined();
});
it('keeps the whole managed log tree within the aggregate byte limit', async () => {
const t = new FileTransport();
const oneKB = 'x'.repeat(1023); // +1 byte newline = 1024
for (let i = 0; i < 4096; i++) t.write(oneKB);
await t.close();
const totalBytes = listLogFiles(tmpDir)
.map((name) => fs.statSync(path.join(tmpDir, name)).size)
.reduce((sum, bytes) => sum + bytes, 0);
expect(totalBytes).toBeLessThanOrEqual(2 * 1024 * 1024);
});
it('enters one observable degraded state instead of retrying every dropped line', async () => {
setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '1' });
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const t = new FileTransport();
const oneKB = 'x'.repeat(1023);
for (let i = 0; i < 1024; i++) t.write(oneKB);
for (let i = 0; i < 10; i++) t.write('dropped');
expect(t.getStorageStatus()).toMatchObject({
state: 'degraded',
maxTotalBytes: 1024 * 1024,
droppedLines: 10,
});
const quotaErrors = stderr.mock.calls
.map(([message]) => String(message))
.filter((message) => message.includes('no closed log can be reclaimed'));
expect(quotaErrors).toHaveLength(1);
await t.close();
stderr.mockRestore();
});
it('opens a new file when the day rolls over mid-process', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0));
@@ -112,6 +151,162 @@ describe('FileTransport', () => {
expect(fs.existsSync(stalePath)).toBe(false);
});
it('runs retention again after a writer closes during rotation or shutdown', async () => {
const t = new FileTransport();
t.write('open the active writer');
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
fs.writeFileSync(stalePath, 'stale\n');
await t.close();
expect(fs.existsSync(stalePath)).toBe(false);
});
it('retainDays=0 disables date cleanup while keeping the byte limit active', async () => {
setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '0' });
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
fs.writeFileSync(stalePath, 'stale\n');
const t = new FileTransport();
await t.close();
expect(fs.existsSync(stalePath)).toBe(true);
expect(t.getStorageStatus().maxTotalBytes).toBe(2 * 1024 * 1024);
});
it('never deletes an active log when a retention update makes its date stale', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date(2026, 0, 1, 12, 0, 0));
const activePath = path.join(tmpDir, 'snowluma-2026-01-01.log');
fs.writeFileSync(activePath, 'existing\n');
const t = new FileTransport();
t.write('still active');
expect(t.currentPath).toBe(activePath);
vi.setSystemTime(new Date(2026, 0, 3, 12, 0, 0));
await t.updatePolicy({
maxTotalMb: 2,
retainDays: 1,
perUinEnabled: false,
});
expect(fs.existsSync(activePath)).toBe(true);
expect(t.getStorageStatus().activeFileCount).toBe(1);
await t.close();
});
it('applies a lower aggregate limit immediately across shared and account logs', async () => {
setEnv({
SNOWLUMA_LOG_MAX_TOTAL_MB: '4',
SNOWLUMA_LOG_RETAIN_DAYS: '0',
});
const oldPath = path.join(tmpDir, 'snowluma-2026-07-24.log');
const accountDir = path.join(tmpDir, '12345');
const newerPath = path.join(accountDir, 'snowluma-2026-07-24.log');
fs.mkdirSync(accountDir);
fs.writeFileSync(oldPath, Buffer.alloc(700 * 1024));
fs.writeFileSync(newerPath, Buffer.alloc(700 * 1024));
const oldTime = new Date('2026-07-24T01:00:00Z');
const newTime = new Date('2026-07-24T02:00:00Z');
fs.utimesSync(oldPath, oldTime, oldTime);
fs.utimesSync(newerPath, newTime, newTime);
const t = new FileTransport();
const status = await t.updatePolicy({
maxTotalMb: 1,
retainDays: 0,
perUinEnabled: false,
});
expect(fs.existsSync(oldPath)).toBe(false);
expect(fs.existsSync(newerPath)).toBe(true);
expect(status).toMatchObject({
state: 'healthy',
maxTotalBytes: 1024 * 1024,
totalBytes: 700 * 1024,
});
await t.close();
});
it('disables per-account writer creation before awaiting old writer shutdown', async () => {
setEnv({ SNOWLUMA_LOG_PER_UIN: '1' });
const t = new FileTransport();
t.write('before policy update', 12345);
expect(t.perUinPath(12345)).not.toBeNull();
const updating = t.updatePolicy({
maxTotalMb: 2,
retainDays: 7,
perUinEnabled: false,
});
t.write('during policy update', 12345);
expect(t.perUinPath(12345)).toBeNull();
await updating;
expect(t.getStorageStatus().perUinEnabled).toBe(false);
await t.close();
});
it('rejects policies whose unit conversion would exceed safe integer bytes', async () => {
const t = new FileTransport();
await expect(t.updatePolicy({
maxTotalMb: Number.MAX_SAFE_INTEGER,
retainDays: 7,
perUinEnabled: false,
})).rejects.toThrow(/maxTotalMb/);
await expect(t.updatePolicy({
maxTotalMb: 2,
retainDays: Number.MAX_SAFE_INTEGER,
perUinEnabled: false,
})).rejects.toThrow(/retainDays/);
await t.close();
});
it('fails fast on invalid direct log-storage environment values', () => {
setEnv({ SNOWLUMA_LOG_MAX_MB: '0' });
expect(() => new FileTransport()).toThrow(/SNOWLUMA_LOG_MAX_MB/);
setEnv({ SNOWLUMA_LOG_MAX_MB: '1' });
setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '0' });
expect(() => new FileTransport()).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '2', SNOWLUMA_LOG_RETAIN_DAYS: '-1' });
expect(() => new FileTransport()).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '7', SNOWLUMA_LOG_PER_UIN: 'maybe' });
expect(() => new FileTransport()).toThrow(/SNOWLUMA_LOG_PER_UIN/);
});
it('exposes initialization failures in storage status', async () => {
const invalidRoot = path.join(tmpDir, 'not-a-directory');
fs.writeFileSync(invalidRoot, 'occupied');
setEnv({ SNOWLUMA_LOG_DIR: invalidRoot });
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const t = new FileTransport();
expect(t.getStorageStatus()).toMatchObject({
state: 'disabled',
lastError: expect.stringMatching(/failed to initialize log storage/),
});
await t.close();
stderr.mockRestore();
});
it('clears active shared and account logs by rotating them into fresh empty files', async () => {
setEnv({ SNOWLUMA_LOG_PER_UIN: '1' });
const t = new FileTransport();
t.write('shared and account', 12345);
const result = await t.clearManagedLogs();
expect(result.deletedFiles).toBe(2);
expect(result.freedBytes).toBeGreaterThan(0);
expect(result.failures).toEqual([]);
expect(fs.statSync(t.currentPath!).size).toBe(0);
expect(fs.statSync(t.perUinPath(12345)!).size).toBe(0);
await t.close();
});
it('keeps files inside the retention window', async () => {
const recent = new Date();
recent.setDate(recent.getDate() - 2);
@@ -135,6 +330,88 @@ describe('FileTransport', () => {
expect(listLogFiles(tmpDir)).toHaveLength(0);
});
it('clears existing managed logs even when file output is disabled', async () => {
const managed = path.join(tmpDir, 'snowluma-2020-01-01.log');
const unrelated = path.join(tmpDir, 'keep.txt');
fs.writeFileSync(managed, 'managed\n');
fs.writeFileSync(unrelated, 'unrelated\n');
setEnv({ SNOWLUMA_LOG_FILE: '0' });
const t = new FileTransport();
const result = await t.clearManagedLogs();
expect(result).toMatchObject({
deletedFiles: 1,
failures: [],
status: { state: 'disabled', totalBytes: 0, fileCount: 0 },
});
expect(fs.existsSync(managed)).toBe(false);
expect(fs.existsSync(unrelated)).toBe(true);
await t.close();
});
it('automatically retries initialization after the log root becomes writable', async () => {
vi.useFakeTimers();
const invalidRoot = path.join(tmpDir, 'blocked-root');
fs.writeFileSync(invalidRoot, 'occupied');
setEnv({ SNOWLUMA_LOG_DIR: invalidRoot });
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const t = new FileTransport();
expect(t.getStorageStatus().state).toBe('disabled');
fs.unlinkSync(invalidRoot);
fs.mkdirSync(invalidRoot);
vi.advanceTimersByTime(5_000);
t.write('recovered');
await t.close();
expect(listLogFiles(invalidRoot)).toHaveLength(1);
expect(fs.readFileSync(path.join(invalidRoot, listLogFiles(invalidRoot)[0]!), 'utf8'))
.toBe('recovered\n');
stderr.mockRestore();
});
it('reopens the shared writer after a write-stream open failure', async () => {
vi.useFakeTimers();
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => {
throw Object.assign(new Error('open failed'), { code: 'EIO' });
});
const t = new FileTransport();
t.write('dropped while opening');
expect(t.getStorageStatus().state).toBe('degraded');
vi.advanceTimersByTime(5_000);
t.write('written after recovery');
await t.close();
const files = listLogFiles(tmpDir);
expect(files).toHaveLength(1);
expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8'))
.toBe('written after recovery\n');
stderr.mockRestore();
});
it('can clear managed logs before the failed writer retry delay expires', async () => {
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => {
throw Object.assign(new Error('open failed'), { code: 'EIO' });
});
const t = new FileTransport();
t.write('dropped while opening');
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
fs.writeFileSync(stalePath, 'stale\n');
const result = await t.clearManagedLogs();
expect(result.failures).toEqual([]);
expect(fs.existsSync(stalePath)).toBe(false);
expect(t.currentPath).not.toBeNull();
await t.close();
stderr.mockRestore();
});
it('appends to the existing today file across restarts', async () => {
const a = new FileTransport();
a.write('before restart');
@@ -150,10 +427,11 @@ describe('FileTransport', () => {
.toBe('before restart\nafter restart\n');
});
it('exposes the current file path while open', () => {
it('exposes the current file path while open', async () => {
const t = new FileTransport();
t.write('x');
expect(t.currentPath).not.toBeNull();
expect(t.currentPath!).toMatch(/snowluma-\d{4}-\d{2}-\d{2}\.log$/);
await t.close();
});
});
+24 -1
View File
@@ -12,7 +12,10 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { _resetFileTransportForTesting } from '@snowluma/common/log-file-transport';
import {
_resetFileTransportForTesting,
configureFileTransport,
} from '@snowluma/common/log-file-transport';
let tmpDir: string;
const ENV_KEYS = [
@@ -20,6 +23,7 @@ const ENV_KEYS = [
'SNOWLUMA_LOG_PER_UIN',
'SNOWLUMA_LOG_DIR',
'SNOWLUMA_LOG_MAX_MB',
'SNOWLUMA_LOG_MAX_TOTAL_MB',
'SNOWLUMA_LOG_RETAIN_DAYS',
'SNOWLUMA_LOG_LEVEL',
'NO_COLOR',
@@ -41,6 +45,7 @@ beforeEach(async () => {
SNOWLUMA_LOG_FILE: '1',
SNOWLUMA_LOG_PER_UIN: '1',
SNOWLUMA_LOG_MAX_MB: '5',
SNOWLUMA_LOG_MAX_TOTAL_MB: '100',
SNOWLUMA_LOG_RETAIN_DAYS: '7',
NO_COLOR: '1',
});
@@ -177,6 +182,24 @@ describe('createLogger', () => {
const entries = fs.readdirSync(tmpDir);
expect(entries).toHaveLength(0);
});
it('applies the runtime storage policy through the singleton before writing', async () => {
const status = await configureFileTransport({
maxTotalMb: 3,
retainDays: 0,
perUinEnabled: false,
});
expect(status).toMatchObject({
maxTotalBytes: 3 * 1024 * 1024,
retainDays: 0,
perUinEnabled: false,
});
createLogger('Bridge').child({ uin: 24680 }).info('runtime policy');
await _resetFileTransportForTesting();
expect(fs.existsSync(path.join(tmpDir, '24680'))).toBe(false);
});
});
describe('setLogLevel / getLogLevel — runtime level toggle', () => {
@@ -0,0 +1,345 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
StorageAccountOnlineError,
StorageManagementInputError,
StorageManagementService,
type TemporaryStorageAdapter,
} from '../src/webui/storage-management';
import type { LogStorageStatus } from '@snowluma/common/log-file-transport';
let root: string;
let dataDir: string;
const healthyLogs: LogStorageStatus = {
state: 'healthy',
directory: '/must/not/leak',
totalBytes: 100,
maxTotalBytes: 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 2,
activeFileCount: 1,
droppedLines: 0,
};
const temporary: TemporaryStorageAdapter = {
snapshot: () => ({ totalBytes: 20, fileCount: 2, activeItemCount: 1 }),
clearInactive: () => ({ deletedFiles: 0, freedBytes: 0, skippedActiveItems: 1, failures: [] }),
};
function writeSized(filePath: string, bytes: number): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, Buffer.alloc(bytes));
}
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-storage-'));
dataDir = path.join(root, 'data');
});
afterEach(() => {
vi.restoreAllMocks();
fs.rmSync(root, { recursive: true, force: true });
});
describe('StorageManagementService', () => {
it('summarizes allowlisted account databases and their SQLite sidecars', () => {
const accountDir = path.join(dataDir, '12345');
writeSized(path.join(accountDir, 'messages.db'), 10);
writeSized(path.join(accountDir, 'messages.db-wal'), 2);
writeSized(path.join(accountDir, 'messages.db-shm'), 3);
writeSized(path.join(accountDir, 'media.db'), 4);
writeSized(path.join(accountDir, 'reactions.db'), 5);
writeSized(path.join(accountDir, 'unmanaged.bin'), 999);
writeSized(path.join(dataDir, 'not-an-account', 'messages.db'), 888);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [{ uin: '12345', nickname: 'Alice' }],
});
expect(service.snapshot()).toEqual({
logs: {
state: 'healthy',
totalBytes: 100,
maxTotalBytes: 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 2,
activeFileCount: 1,
droppedLines: 0,
},
temporary: { totalBytes: 20, fileCount: 2, activeItemCount: 1 },
accounts: [{
uin: '12345',
nickname: 'Alice',
online: true,
messagesBytes: 15,
mediaBytes: 4,
reactionsBytes: 5,
totalBytes: 24,
}],
totals: {
logsBytes: 100,
temporaryBytes: 20,
accountDataBytes: 24,
managedBytes: 144,
},
});
});
it('redacts the managed log directory from observable error messages', () => {
const service = new StorageManagementService({
dataDir,
getLogStatus: () => ({
...healthyLogs,
state: 'degraded',
lastError: 'write /must/not/leak/snowluma-2026-07-24.log: disk full',
}),
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(service.snapshot().logs.lastError)
.toBe('write [日志目录]/snowluma-2026-07-24.log: disk full');
});
it('clears only the selected database category for an offline account', () => {
const accountDir = path.join(dataDir, '12345');
writeSized(path.join(accountDir, 'messages.db'), 10);
writeSized(path.join(accountDir, 'messages.db-wal'), 2);
writeSized(path.join(accountDir, 'messages.db-shm'), 3);
writeSized(path.join(accountDir, 'media.db'), 4);
writeSized(path.join(accountDir, 'unmanaged.bin'), 99);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(service.clearAccountData('messages', '12345')).toEqual({
category: 'messages',
uins: ['12345'],
deletedFiles: 3,
freedBytes: 15,
failures: [],
});
expect(fs.existsSync(path.join(accountDir, 'messages.db'))).toBe(false);
expect(fs.existsSync(path.join(accountDir, 'media.db'))).toBe(true);
expect(fs.existsSync(path.join(accountDir, 'unmanaged.bin'))).toBe(true);
});
it('rejects online account cleanup before deleting any database file', () => {
const accountDir = path.join(dataDir, '12345');
const messages = path.join(accountDir, 'messages.db');
writeSized(messages, 10);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [{ uin: '12345', nickname: 'Alice' }],
});
expect(() => service.clearAccountData('messages', '12345'))
.toThrow(StorageAccountOnlineError);
expect(fs.existsSync(messages)).toBe(true);
});
it('rejects unsupported categories and invalid UINs', () => {
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(() => service.clearAccountData('../config', '12345'))
.toThrow(StorageManagementInputError);
expect(() => service.clearAccountData('messages', '../12345'))
.toThrow(StorageManagementInputError);
});
it('preflights every account before clearing a category across all accounts', () => {
const firstMessages = path.join(dataDir, '12345', 'messages.db');
const secondMessages = path.join(dataDir, '67890', 'messages.db');
writeSized(firstMessages, 10);
writeSized(secondMessages, 20);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [{ uin: '67890', nickname: 'Bob' }],
});
expect(() => service.clearAllAccountData('messages'))
.toThrow(StorageAccountOnlineError);
expect(fs.existsSync(firstMessages)).toBe(true);
expect(fs.existsSync(secondMessages)).toBe(true);
});
it('never follows an account-directory symlink outside the managed data root', () => {
const externalDir = path.join(root, 'external');
const externalMessages = path.join(externalDir, 'messages.db');
writeSized(externalMessages, 10);
fs.mkdirSync(dataDir, { recursive: true });
fs.symlinkSync(externalDir, path.join(dataDir, '12345'));
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(service.clearAccountData('messages', '12345')).toEqual({
category: 'messages',
uins: ['12345'],
deletedFiles: 0,
freedBytes: 0,
failures: [],
});
expect(fs.existsSync(externalMessages)).toBe(true);
});
it('never follows a managed data-root symlink outside SnowLuma storage', () => {
const externalDir = path.join(root, 'external');
const externalMessages = path.join(externalDir, '12345', 'messages.db');
writeSized(externalMessages, 10);
fs.symlinkSync(externalDir, dataDir);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(() => service.clearAllAccountData('messages'))
.toThrow(/data root/i);
expect(fs.existsSync(externalMessages)).toBe(true);
});
it('does not expose account database absolute paths in cleanup failures', () => {
const messages = path.join(dataDir, '12345', 'messages.db');
writeSized(messages, 10);
const originalLstat = fs.lstatSync.bind(fs);
vi.spyOn(fs, 'lstatSync').mockImplementation((filePath) => {
if (String(filePath) === messages) {
throw Object.assign(
new Error(`EACCES: permission denied, lstat '${messages}'`),
{ code: 'EACCES' },
);
}
return originalLstat(filePath);
});
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
const result = service.clearAccountData('messages', '12345');
expect(result.failures).toHaveLength(1);
expect(result.failures[0]).toMatchObject({ uin: '12345', file: 'messages.db' });
expect(result.failures[0]?.message).not.toContain(root);
expect(result.failures[0]?.message).toContain('[账号数据库]');
});
it('clears logs without exposing their absolute directory', async () => {
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => ({
deletedFiles: 4,
freedBytes: 90,
failures: [{
file: 'snowluma-2026-07-24.log',
message: 'unlink /must/not/leak/snowluma-2026-07-24.log: permission denied',
}],
status: { ...healthyLogs, totalBytes: 10, fileCount: 1 },
}),
temporary,
listOnlineAccounts: () => [],
});
await expect(service.clearLogs()).resolves.toEqual({
deletedFiles: 4,
freedBytes: 90,
failures: [{
file: 'snowluma-2026-07-24.log',
message: 'unlink [日志目录]/snowluma-2026-07-24.log: permission denied',
}],
status: {
state: 'healthy',
totalBytes: 10,
maxTotalBytes: 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 1,
activeFileCount: 1,
droppedLines: 0,
},
});
});
it('clears only inactive temporary stream data through its adapter', () => {
const clearResult = {
deletedFiles: 3,
freedBytes: 42,
skippedActiveItems: 2,
failures: [],
};
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary: {
snapshot: temporary.snapshot,
clearInactive: () => clearResult,
},
listOnlineAccounts: () => [],
});
expect(service.clearTemporary()).toBe(clearResult);
});
});
+335
View File
@@ -0,0 +1,335 @@
import { Hono } from 'hono';
import { describe, expect, it } from 'vitest';
import { StorageAccountOnlineError } from '../src/webui/storage-management';
import {
ALL_ACCOUNTS_CONFIRMATION,
registerStorageRoutes,
type StorageRouteDependencies,
} from '../src/webui/storage-routes';
import { StorageSettingsTransactionError } from '../src/webui/storage-settings';
const settingsState = {
saved: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
effective: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
envOverrides: [],
};
const snapshot = {
logs: {
state: 'healthy' as const,
totalBytes: 100,
maxTotalBytes: 1024 * 1024 * 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 1,
activeFileCount: 1,
droppedLines: 0,
},
temporary: { totalBytes: 20, fileCount: 2, activeItemCount: 0 },
accounts: [],
totals: {
logsBytes: 100,
temporaryBytes: 20,
accountDataBytes: 0,
managedBytes: 120,
},
};
function createDependencies(
overrides: Partial<StorageRouteDependencies> = {},
): StorageRouteDependencies {
return {
storage: {
snapshot: () => snapshot,
clearLogs: async () => ({
deletedFiles: 1,
freedBytes: 90,
failures: [],
status: { ...snapshot.logs, totalBytes: 10 },
}),
clearTemporary: () => ({
deletedFiles: 2,
freedBytes: 20,
skippedActiveItems: 0,
failures: [],
}),
clearAccountData: (category, uin) => ({
category: category as 'messages' | 'media' | 'reactions',
uins: [uin],
deletedFiles: 1,
freedBytes: 10,
failures: [],
}),
clearAllAccountData: (category) => ({
category: category as 'messages' | 'media' | 'reactions',
uins: ['12345', '67890'],
deletedFiles: 2,
freedBytes: 20,
failures: [],
}),
},
settings: {
read: () => settingsState,
update: async () => ({
settings: settingsState,
status: snapshot.logs,
}),
},
audit: () => undefined,
reportError: () => undefined,
now: () => new Date('2026-07-24T04:00:00.000Z'),
...overrides,
};
}
function createApp(deps: StorageRouteDependencies): Hono {
const app = new Hono();
registerStorageRoutes(app, deps);
return app;
}
describe('storage management routes', () => {
it('returns settings and a path-free storage snapshot', async () => {
const response = await createApp(createDependencies()).request('/api/system/storage');
expect(response.status).toBe(200);
const body = await response.json();
expect(body).toEqual({ settings: settingsState, snapshot, lastCleanup: null });
expect(JSON.stringify(body)).not.toContain('/private/');
});
it('updates log settings and returns the refreshed snapshot', async () => {
let received: unknown;
const deps = createDependencies({
settings: {
read: () => settingsState,
update: async (body) => {
received = body;
return { settings: settingsState, status: snapshot.logs };
},
},
});
const response = await createApp(deps).request('/api/system/storage/settings', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ logRetainDays: 0 }),
});
expect(response.status).toBe(200);
expect(received).toEqual({ logRetainDays: 0 });
await expect(response.json()).resolves.toMatchObject({
success: true,
settings: settingsState,
snapshot,
});
});
it('reports both the failed settings operation and every failed rollback', async () => {
const operationError = new Error('apply failed');
const rollbackError = new Error('rollback failed');
const reports: Array<{ operation: string; error: unknown }> = [];
const deps = createDependencies({
settings: {
read: () => settingsState,
update: async () => {
throw new StorageSettingsTransactionError(
'transaction failed',
operationError,
[rollbackError],
);
},
},
reportError: (operation, error) => reports.push({ operation, error }),
});
const response = await createApp(deps).request('/api/system/storage/settings', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ logRetainDays: 0 }),
});
expect(response.status).toBe(500);
expect(reports).toEqual([
{ operation: 'update log storage settings', error: expect.any(StorageSettingsTransactionError) },
{ operation: 'update log storage settings operation', error: operationError },
{ operation: 'rollback log storage settings step=1', error: rollbackError },
]);
});
it('serializes settings changes and cleanup operations', async () => {
let releaseSettings!: () => void;
let notifySettingsStarted!: () => void;
const settingsGate = new Promise<void>((resolve) => {
releaseSettings = resolve;
});
const settingsStarted = new Promise<void>((resolve) => {
notifySettingsStarted = resolve;
});
let cleanupCalls = 0;
const deps = createDependencies({
settings: {
read: () => settingsState,
update: async () => {
notifySettingsStarted();
await settingsGate;
return { settings: settingsState, status: snapshot.logs };
},
},
});
deps.storage.clearTemporary = () => {
cleanupCalls += 1;
return {
deletedFiles: 0,
freedBytes: 0,
skippedActiveItems: 0,
failures: [],
};
};
const app = createApp(deps);
const settingsRequest = app.request('/api/system/storage/settings', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ logRetainDays: 0 }),
});
await settingsStarted;
const cleanupRequest = app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ scope: 'temporary' }),
});
await Promise.resolve();
expect(cleanupCalls).toBe(0);
releaseSettings();
await expect(settingsRequest).resolves.toMatchObject({ status: 200 });
await expect(cleanupRequest).resolves.toMatchObject({ status: 200 });
expect(cleanupCalls).toBe(1);
});
it('rejects arbitrary paths, unknown scopes, and missing cleanup fields', async () => {
const app = createApp(createDependencies());
for (const body of [
{ scope: 'logs', path: '/etc' },
{ scope: 'everything' },
{ scope: 'account', category: 'messages', uin: '../12345' },
{ scope: 'account', category: '../config', uin: '12345' },
{ scope: 'account', category: 'messages' },
]) {
const response = await app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
expect(response.status, JSON.stringify(body)).toBe(400);
}
});
it('requires the fixed second confirmation for all-account cleanup', async () => {
const app = createApp(createDependencies());
const rejected = await app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
scope: 'allAccounts',
category: 'messages',
confirmation: 'yes',
}),
});
expect(rejected.status).toBe(400);
const accepted = await app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
scope: 'allAccounts',
category: 'messages',
confirmation: ALL_ACCOUNTS_CONFIRMATION,
}),
});
expect(accepted.status).toBe(200);
await expect(accepted.json()).resolves.toMatchObject({
success: true,
scope: 'allAccounts',
cleanup: { uins: ['12345', '67890'], deletedFiles: 2 },
});
});
it('maps an online-account preflight failure to conflict', async () => {
const deps = createDependencies();
deps.storage.clearAccountData = () => {
throw new StorageAccountOnlineError(['12345']);
};
const response = await createApp(deps).request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ scope: 'account', category: 'messages', uin: '12345' }),
});
expect(response.status).toBe(409);
await expect(response.json()).resolves.toMatchObject({
success: false,
onlineUins: ['12345'],
});
});
it('returns HTTP 500 with the structured partial result when deletion fails', async () => {
const audits: unknown[] = [];
const reports: Array<{ operation: string; error: unknown }> = [];
const deps = createDependencies({
audit: (event) => audits.push(event),
reportError: (operation, error) => reports.push({ operation, error }),
});
deps.storage.clearTemporary = () => ({
deletedFiles: 1,
freedBytes: 5,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
});
const app = createApp(deps);
const response = await app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ scope: 'temporary' }),
});
expect(response.status).toBe(500);
await expect(response.json()).resolves.toMatchObject({
success: false,
cleanup: {
deletedFiles: 1,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
lastCleanup: {
failureCount: 1,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
snapshot,
});
expect(audits).toEqual([{
scope: 'temporary',
accountScope: 'global',
deletedFiles: 1,
freedBytes: 5,
failureCount: 1,
}]);
expect(reports).toEqual([{
operation: 'clean storage scope=temporary item=locked.bin',
error: expect.objectContaining({ message: 'permission denied' }),
}]);
const refreshed = await app.request('/api/system/storage');
await expect(refreshed.json()).resolves.toMatchObject({
lastCleanup: {
at: '2026-07-24T04:00:00.000Z',
scope: 'temporary',
accountScope: 'global',
deletedFiles: 1,
freedBytes: 5,
failureCount: 1,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
});
});
});
@@ -0,0 +1,278 @@
import { describe, expect, it } from 'vitest';
import type { LogStoragePolicy, LogStorageStatus } from '@snowluma/common/log-file-transport';
import type { RuntimeConfig } from '@snowluma/common/runtime';
import {
LogStorageSettingsManager,
StorageSettingsInputError,
StorageSettingsLockedError,
StorageSettingsTransactionError,
} from '../src/webui/storage-settings';
const persisted: RuntimeConfig = {
webuiPort: 5099,
hookAutoLoad: false,
webuiHost: '0.0.0.0',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
logRetainDays: 7,
logPerUin: false,
};
const persistedPolicy: LogStoragePolicy = {
maxTotalMb: 1024,
retainDays: 7,
perUinEnabled: false,
};
function status(
policy: LogStoragePolicy,
state: LogStorageStatus['state'] = 'healthy',
): LogStorageStatus {
return {
state,
directory: '/private/logs',
totalBytes: state === 'degraded' ? policy.maxTotalMb * 1024 * 1024 + 1 : 0,
maxTotalBytes: policy.maxTotalMb * 1024 * 1024,
retainDays: policy.retainDays,
perUinEnabled: policy.perUinEnabled,
fileCount: 0,
activeFileCount: 0,
droppedLines: 0,
...(state === 'healthy' ? {} : { lastError: 'quota could not be enforced' }),
};
}
describe('LogStorageSettingsManager', () => {
it('reports persisted, effective, and environment-locked settings separately', () => {
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({ logRetainDays: 0, logPerUin: true }),
readEffective: () => status({
maxTotalMb: 1024,
retainDays: 0,
perUinEnabled: true,
}),
persist: () => {
throw new Error('not used');
},
apply: async (policy) => status(policy),
});
expect(manager.read()).toEqual({
saved: {
logMaxTotalMb: 1024,
logRetainDays: 7,
logPerUin: false,
},
effective: {
logMaxTotalMb: 1024,
logRetainDays: 0,
logPerUin: true,
},
envOverrides: ['logRetainDays', 'logPerUin'],
});
});
it('reports the actual live policy separately from externally changed disk values', () => {
const manager = new LogStorageSettingsManager({
readPersisted: () => ({ ...persisted, logRetainDays: 30 }),
readEnvOverrides: () => ({}),
readEffective: () => status(persistedPolicy),
persist: () => {
throw new Error('not used');
},
apply: async (policy) => status(policy),
});
expect(manager.read()).toMatchObject({
saved: { logRetainDays: 30 },
effective: { logRetainDays: 7 },
});
});
it('strictly rejects malformed, unknown, and empty patches', async () => {
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({}),
readEffective: () => status(persistedPolicy),
persist: () => persisted,
apply: async (policy) => status(policy),
});
await expect(manager.update(null)).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({})).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({ unknown: 1 })).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({ logMaxTotalMb: 0 })).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({ logRetainDays: -1 })).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({ logPerUin: 1 })).rejects.toThrow(StorageSettingsInputError);
});
it('rejects edits to fields pinned by environment variables', async () => {
let applied = false;
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({ logMaxTotalMb: 2048 }),
readEffective: () => status({
maxTotalMb: 2048,
retainDays: 7,
perUinEnabled: false,
}),
persist: () => persisted,
apply: async (policy) => {
applied = true;
return status(policy);
},
});
await expect(manager.update({ logMaxTotalMb: 512 }))
.rejects.toThrow(StorageSettingsLockedError);
expect(applied).toBe(false);
});
it('applies before persisting and returns the new effective settings', async () => {
const order: string[] = [];
let current = persisted;
const manager = new LogStorageSettingsManager({
readPersisted: () => current,
readEnvOverrides: () => ({}),
readEffective: () => status({
maxTotalMb: current.logMaxTotalMb ?? 1024,
retainDays: current.logRetainDays ?? 7,
perUinEnabled: current.logPerUin ?? false,
}),
persist: (patch) => {
order.push('persist');
current = { ...current, ...patch };
return current;
},
apply: async (policy) => {
order.push('apply');
return status(policy);
},
});
await expect(manager.update({
logMaxTotalMb: 512,
logRetainDays: 0,
logPerUin: true,
})).resolves.toMatchObject({
settings: {
saved: {
logMaxTotalMb: 512,
logRetainDays: 0,
logPerUin: true,
},
effective: {
logMaxTotalMb: 512,
logRetainDays: 0,
logPerUin: true,
},
},
status: {
state: 'healthy',
maxTotalBytes: 512 * 1024 * 1024,
},
});
expect(order).toEqual(['apply', 'persist']);
});
it('does not persist a policy that cannot be enforced and rolls runtime state back', async () => {
const applied: LogStoragePolicy[] = [];
let persistCalls = 0;
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({}),
readEffective: () => status(persistedPolicy),
persist: () => {
persistCalls += 1;
return persisted;
},
apply: async (policy) => {
applied.push(policy);
return status(policy, applied.length === 1 ? 'degraded' : 'healthy');
},
});
await expect(manager.update({ logMaxTotalMb: 1 }))
.rejects.toThrow(StorageSettingsTransactionError);
expect(persistCalls).toBe(0);
expect(applied).toEqual([
{ maxTotalMb: 1, retainDays: 7, perUinEnabled: false },
{ maxTotalMb: 1024, retainDays: 7, perUinEnabled: false },
]);
});
it('restores both runtime state and persisted settings when persistence fails', async () => {
const applied: LogStoragePolicy[] = [];
const persistedPatches: Partial<RuntimeConfig>[] = [];
let persistCalls = 0;
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({}),
readEffective: () => status(persistedPolicy),
persist: (patch) => {
persistedPatches.push(patch);
persistCalls += 1;
if (persistCalls === 1) throw new Error('disk full');
return persisted;
},
apply: async (policy) => {
applied.push(policy);
return status(policy);
},
});
await expect(manager.update({ logRetainDays: 30 }))
.rejects.toThrow(StorageSettingsTransactionError);
expect(applied).toEqual([
{ maxTotalMb: 1024, retainDays: 30, perUinEnabled: false },
{ maxTotalMb: 1024, retainDays: 7, perUinEnabled: false },
]);
expect(persistedPatches).toEqual([
{ logRetainDays: 30 },
persisted,
]);
});
it('serializes concurrent updates so invocation order remains authoritative', async () => {
let current = persisted;
let livePolicy = persistedPolicy;
const applied: LogStoragePolicy[] = [];
const releases: Array<() => void> = [];
let notifySecondStarted!: () => void;
const secondStarted = new Promise<void>((resolve) => {
notifySecondStarted = resolve;
});
const manager = new LogStorageSettingsManager({
readPersisted: () => current,
readEnvOverrides: () => ({}),
readEffective: () => status(livePolicy),
persist: (patch) => {
current = { ...current, ...patch };
return current;
},
apply: async (policy) => {
applied.push(policy);
if (applied.length === 2) notifySecondStarted();
await new Promise<void>((resolve) => releases.push(resolve));
livePolicy = policy;
return status(policy);
},
});
const first = manager.update({ logRetainDays: 30 });
const second = manager.update({ logRetainDays: 60 });
await Promise.resolve();
expect(applied).toHaveLength(1);
releases.shift()?.();
await secondStarted;
expect(applied).toHaveLength(2);
releases.shift()?.();
await Promise.all([first, second]);
expect(current.logRetainDays).toBe(60);
expect(applied.map((policy) => policy.retainDays)).toEqual([30, 60]);
});
});
+12 -1
View File
@@ -114,10 +114,21 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
webuiHost: '0.0.0.0',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
logRetainDays: 7,
logPerUin: false,
});
expect(prepared.migrated).toEqual([{
name: 'runtime.json',
fields: ['$.hookAutoLoad', '$.trustProxy', '$.webuiHost', '$.webuiTls'],
fields: [
'$.hookAutoLoad',
'$.logMaxTotalMb',
'$.logPerUin',
'$.logRetainDays',
'$.trustProxy',
'$.webuiHost',
'$.webuiTls',
],
}]);
});