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

+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',
],
}]);
});