From 120dda1d9dfe1635d1a3c02442493209a30a0209 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 22 Jul 2026 21:51:33 +0800 Subject: [PATCH 1/6] fix(group-album): fetch all legacy album pages Follow AlbumService cursors in get_group_album_list so the legacy array response contains every album instead of only the first page. Reject missing or repeated cursors when the server reports more data, preventing silent truncation and pagination loops. Add regression coverage for multi-page aggregation and malformed cursors. Fixes #272 --- packages/core/src/bridge/apis/group-album.ts | 38 +++++++- .../core/tests/actions/group-album.test.ts | 92 +++++++++++++++++++ 2 files changed, 128 insertions(+), 2 deletions(-) diff --git a/packages/core/src/bridge/apis/group-album.ts b/packages/core/src/bridge/apis/group-album.ts index e6a6b86a..b4f69804 100644 --- a/packages/core/src/bridge/apis/group-album.ts +++ b/packages/core/src/bridge/apis/group-album.ts @@ -213,8 +213,42 @@ export class GroupAlbumApi { // OneBot compatibility shape used by get_group_album_list. async list(groupId: number): Promise { - const result = await this.fetchAlbumList(groupId, ''); - return result.albumList.map(toLegacyAlbum); + const albumList: GroupAlbumList = []; + const seenCursors = new Set(); + let attachInfo = ''; + let page = 0; + + while (true) { + const result = await this.fetchAlbumList(groupId, attachInfo); + page += 1; + albumList.push(...result.albumList.map(toLegacyAlbum)); + + if (!result.hasMore) { + log.debug( + 'get complete album list: group=%d pages=%d albums=%d', + groupId, + page, + albumList.length, + ); + return albumList; + } + + const nextAttachInfo = result.attachInfo; + if (!nextAttachInfo) { + throw new Error( + `get group album list pagination failed: group=${groupId} page=${page} ` + + 'hasMore=true but cursor is empty', + ); + } + if (seenCursors.has(nextAttachInfo)) { + throw new Error( + `get group album list pagination failed: group=${groupId} repeated cursor at page ${page}`, + ); + } + + seenCursors.add(nextAttachInfo); + attachInfo = nextAttachInfo; + } } // 上传图片到现有相册(HTTP 分片上传)。 diff --git a/packages/core/tests/actions/group-album.test.ts b/packages/core/tests/actions/group-album.test.ts index 19721ab9..b4eef030 100644 --- a/packages/core/tests/actions/group-album.test.ts +++ b/packages/core/tests/actions/group-album.test.ts @@ -108,6 +108,98 @@ describe('apis/group-album', () => { }]); }); + it('fetches every AlbumService page for the legacy album list action', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket + .mockResolvedValueOnce({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + data: { + albumList: [{ + albumId: 'album-1', + name: '第一页', + createTime: 1n, + uploadNumber: 1n, + }], + attachInfo: 'next-cursor', + hasMore: true, + }, + })), + }) + .mockResolvedValueOnce({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + data: { + albumList: [{ + albumId: 'album-2', + name: '第二页', + createTime: 2n, + uploadNumber: 2n, + }], + hasMore: false, + }, + })), + }); + + const result = await new GroupAlbumApi(bridge as never).list(12345); + + expect(result.map((album) => album.id)).toEqual(['album-1', 'album-2']); + expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2); + const secondRequest = protobuf_decode( + bridge.sendRawPacket.mock.calls[1]![1], + ); + expect(secondRequest.data?.cursor).toBe('next-cursor'); + }); + + it('rejects a legacy album page that claims more data without a cursor', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + data: { + albumList: [], + hasMore: true, + }, + })), + }); + + await expect(new GroupAlbumApi(bridge as never).list(12345)) + .rejects.toThrow('hasMore=true but cursor is empty'); + }); + + it('rejects a repeated AlbumService cursor instead of looping or truncating', async () => { + const bridge = mockBridge(); + const repeatedPage = { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + data: { + albumList: [], + attachInfo: 'same-cursor', + hasMore: true, + }, + })), + }; + bridge.sendRawPacket + .mockResolvedValueOnce(repeatedPage) + .mockResolvedValueOnce(repeatedPage); + + await expect(new GroupAlbumApi(bridge as never).list(12345)) + .rejects.toThrow('repeated cursor at page 2'); + expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2); + }); + it('returns the native AlbumService cursor and creator fields for get_qun_album_list', async () => { const bridge = mockBridge(); bridge.sendRawPacket.mockResolvedValueOnce({ From a7b9ba14fb4a414e33acdcd50c8dec6bcd8b7a32 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 23 Jul 2026 12:08:17 +0800 Subject: [PATCH 2/6] fix(onebot): accept empty text placeholders in arrays Fixes #273. --- packages/onebot/src/message-parser.ts | 4 ++ packages/onebot/tests/message-parser.test.ts | 64 ++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 1f92a68f..2ac266c1 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -408,6 +408,10 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti const elements: MessageElement[] = []; for (const seg of message) { const data = segmentPayload(seg); + // Some OneBot clients insert empty text between media as a separator. + // Only the exact empty string is a no-op; malformed and whitespace text + // must still pass through strict element validation. + if (seg.type.trim().toLowerCase() === 'text' && data.text === '') continue; const elem = await segmentToElement(seg.type, data, options); if (elem) elements.push(elem); } diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index 9e4cfbbf..6fd101b8 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -91,6 +91,70 @@ describe('parseMessage', () => { expect(result).toEqual([{ type: 'text', text: 'hello' }]); }); + it('ignores explicit empty text placeholders between sendable segments (issue #273)', async () => { + const result = await parseMessage( + [ + { type: 'image', data: { file: 'https://example.com/first.png' } }, + { type: 'text', data: { text: '' } }, + { type: 'image', data: { file: 'https://example.com/second.png' } }, + ] as any, + false, + ); + + expect(result).toHaveLength(2); + expect(result).toMatchObject([ + { type: 'image', url: 'https://example.com/first.png' }, + { type: 'image', url: 'https://example.com/second.png' }, + ]); + }); + + it('rejects a segment array containing only empty text placeholders', async () => { + await expect(parseMessage( + [ + { type: 'text', data: { text: '' } }, + { type: 'text', data: { text: '' } }, + ] as any, + false, + )).rejects.toMatchObject({ + code: 'MISSING_FIELD', + field: 'message', + }); + }); + + it('keeps a single empty text segment invalid', async () => { + await expect(parseMessage( + { type: 'text', data: { text: '' } } as any, + false, + )).rejects.toMatchObject({ + code: 'MISSING_FIELD', + elementType: 'text', + }); + }); + + it('does not treat missing or null text fields as empty placeholders', async () => { + await expect(parseMessage( + [{ type: 'text', data: {} }] as any, + false, + )).rejects.toMatchObject({ + code: 'MISSING_FIELD', + elementType: 'text', + }); + await expect(parseMessage( + [{ type: 'text', data: { text: null } }] as any, + false, + )).rejects.toMatchObject({ + code: 'MISSING_FIELD', + elementType: 'text', + }); + }); + + it('preserves whitespace-only text segments', async () => { + await expect(parseMessage( + [{ type: 'text', data: { text: ' ' } }] as any, + false, + )).resolves.toEqual([{ type: 'text', text: ' ' }]); + }); + it('rejects object-valued fields instead of stringifying caller input', async () => { await expect(parseMessage( [{ type: 'text', data: { text: { bad: true } } }] as any, From edd2ac278ac7a4d27d9572be0a5789d9aecbd107 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 23 Jul 2026 12:14:01 +0800 Subject: [PATCH 3/6] fix(onebot): trace empty text placeholder normalization Document the compatibility rule in action metadata and regenerate the MCP catalog. --- packages/mcp/src/generated/catalog.json | 52 ++++++++++++------------- packages/mcp/src/generated/catalog.ts | 52 ++++++++++++------------- packages/onebot/src/action-kit.ts | 8 +++- packages/onebot/src/message-parser.ts | 5 ++- 4 files changed, 63 insertions(+), 54 deletions(-) diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index bc211963..1b992676 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -7466,7 +7466,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -7474,7 +7474,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } } ], @@ -7483,10 +7483,10 @@ "type": "object", "properties": { "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, "additionalProperties": true @@ -7635,7 +7635,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -7643,7 +7643,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } } ], @@ -7658,10 +7658,10 @@ "x-role": "group_id" }, "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, "required": [ @@ -7694,7 +7694,7 @@ "type": "message", "required": true, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -7718,7 +7718,7 @@ "x-role": "group_id" }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "auto_escape": { "type": "boolean", @@ -7794,7 +7794,7 @@ "type": "message", "required": true, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -7840,7 +7840,7 @@ "type": "object", "properties": { "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message_type": { "type": "string" @@ -7998,7 +7998,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -8006,7 +8006,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } } ], @@ -8020,10 +8020,10 @@ "x-role": "user_id" }, "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, "required": [ @@ -8055,7 +8055,7 @@ "type": "message", "required": true, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -8087,7 +8087,7 @@ "x-role": "user_id" }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "group_id": { "type": "integer", @@ -10528,7 +10528,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -10536,7 +10536,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -10555,10 +10555,10 @@ "type": "object", "properties": { "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "group_id": { "type": "integer", @@ -10581,7 +10581,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -10589,7 +10589,7 @@ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -10608,10 +10608,10 @@ "type": "object", "properties": { "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "group_id": { "type": "integer", diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 641f2b3c..e88d4b5e 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -7469,7 +7469,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -7477,7 +7477,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } } ], @@ -7486,10 +7486,10 @@ export const ACTIONS: CatalogAction[] = [ "type": "object", "properties": { "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, "additionalProperties": true @@ -7638,7 +7638,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -7646,7 +7646,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } } ], @@ -7661,10 +7661,10 @@ export const ACTIONS: CatalogAction[] = [ "x-role": "group_id" }, "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, "required": [ @@ -7697,7 +7697,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": true, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -7721,7 +7721,7 @@ export const ACTIONS: CatalogAction[] = [ "x-role": "group_id" }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "auto_escape": { "type": "boolean", @@ -7797,7 +7797,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": true, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -7843,7 +7843,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "object", "properties": { "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message_type": { "type": "string" @@ -8001,7 +8001,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -8009,7 +8009,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } } ], @@ -8023,10 +8023,10 @@ export const ACTIONS: CatalogAction[] = [ "x-role": "user_id" }, "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, "required": [ @@ -8058,7 +8058,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": true, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -8090,7 +8090,7 @@ export const ACTIONS: CatalogAction[] = [ "x-role": "user_id" }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "group_id": { "type": "integer", @@ -10531,7 +10531,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -10539,7 +10539,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -10558,10 +10558,10 @@ export const ACTIONS: CatalogAction[] = [ "type": "object", "properties": { "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "group_id": { "type": "integer", @@ -10584,7 +10584,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -10592,7 +10592,7 @@ export const ACTIONS: CatalogAction[] = [ "type": "message", "required": false, "schema": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." } }, { @@ -10611,10 +10611,10 @@ export const ACTIONS: CatalogAction[] = [ "type": "object", "properties": { "messages": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "message": { - "description": "OneBot message: string | segment[] | object" + "description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation." }, "group_id": { "type": "integer", diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index 14bf0efb..1805a2bd 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -323,7 +323,13 @@ export const f = { } } return ok(raw); - }, { type: 'message', required: true, schema: { description: 'OneBot message: string | segment[] | object' } }); + }, { + type: 'message', + required: true, + schema: { + description: 'OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly "" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation.', + }, + }); }, /** Homogeneous array; `.nonEmpty()` rejects []. */ array(el: Field): Field & { nonEmpty(): Field } { diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 2ac266c1..b4968b7c 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -411,7 +411,10 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti // Some OneBot clients insert empty text between media as a separator. // Only the exact empty string is a no-op; malformed and whitespace text // must still pass through strict element validation. - if (seg.type.trim().toLowerCase() === 'text' && data.text === '') continue; + if (seg.type.trim().toLowerCase() === 'text' && data.text === '') { + log.debug('ignored explicit empty text placeholder in message segment array'); + continue; + } const elem = await segmentToElement(seg.type, data, options); if (elem) elements.push(elem); } From b884a1c4790759ab2a57ffd4b1773757f69a84d7 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 23 Jul 2026 12:18:02 +0800 Subject: [PATCH 4/6] fix(onebot): unify message segment type normalization Keep empty-placeholder detection aligned with strict segment parsing. --- packages/onebot/src/message-parser.ts | 14 +++++++++----- packages/onebot/tests/message-parser.test.ts | 13 +++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index b4968b7c..c1cb8074 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -64,6 +64,10 @@ function isSegmentArray(val: unknown): val is MessageSegment[] { ); } +function normalizeSegmentType(type: string): string { + return type.toLowerCase(); +} + function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): string[] { if (typeof message === 'string') { if (autoEscape) return ['text']; @@ -71,7 +75,7 @@ function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): str let lastIndex = 0; for (const match of message.matchAll(CQ_REGEX)) { if (match.index! > lastIndex) types.push('text'); - types.push((match[1] ?? '').toLowerCase()); + types.push(normalizeSegmentType(match[1] ?? '')); lastIndex = match.index! + match[0].length; } if (lastIndex < message.length) types.push('text'); @@ -81,12 +85,12 @@ function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): str return message.flatMap((item) => { if (typeof item !== 'object' || item === null || Array.isArray(item)) return []; const type = (item as { type?: unknown }).type; - return typeof type === 'string' ? [type.toLowerCase()] : []; + return typeof type === 'string' ? [normalizeSegmentType(type)] : []; }); } if (typeof message === 'object' && message !== null) { const type = (message as { type?: unknown }).type; - return typeof type === 'string' ? [type.toLowerCase()] : []; + return typeof type === 'string' ? [normalizeSegmentType(type)] : []; } return []; } @@ -173,7 +177,7 @@ function requireCoordinate( } export async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { - const normalizedType = type.toLowerCase(); + const normalizedType = normalizeSegmentType(type); // Ordinary OneBot segment fields are scalar. Reject objects/arrays before // codecs can stringify them into "[object Object]" and alter caller intent. @@ -411,7 +415,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti // Some OneBot clients insert empty text between media as a separator. // Only the exact empty string is a no-op; malformed and whitespace text // must still pass through strict element validation. - if (seg.type.trim().toLowerCase() === 'text' && data.text === '') { + if (normalizeSegmentType(seg.type) === 'text' && data.text === '') { log.debug('ignored explicit empty text placeholder in message segment array'); continue; } diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index 6fd101b8..10514574 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -148,6 +148,19 @@ describe('parseMessage', () => { }); }); + it('does not treat whitespace-padded segment types as empty text placeholders', async () => { + await expect(parseMessage( + [ + { type: 'image', data: { file: 'https://example.com/image.png' } }, + { type: ' text ', data: { text: '' } }, + ] as any, + false, + )).rejects.toMatchObject({ + code: 'UNKNOWN_TYPE', + elementType: ' text ', + }); + }); + it('preserves whitespace-only text segments', async () => { await expect(parseMessage( [{ type: 'text', data: { text: ' ' } }] as any, From 87a604ecbdf826be3a8950340d458f6f1094577f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 24 Jul 2026 12:58:57 +0800 Subject: [PATCH 5/6] 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. --- README.md | 14 +- packages/common/src/log-file-transport.ts | 905 ++++++++++++++++-- packages/common/src/runtime.ts | 136 ++- packages/common/tests/runtime.test.ts | 78 +- packages/core/src/index.ts | 13 +- packages/core/src/webui/server.ts | 57 ++ packages/core/src/webui/storage-management.ts | 333 +++++++ packages/core/src/webui/storage-routes.ts | 317 ++++++ packages/core/src/webui/storage-settings.ts | 312 ++++++ .../core/tests/log-file-transport.test.ts | 280 +++++- packages/core/tests/logger.test.ts | 25 +- .../core/tests/storage-management.test.ts | 345 +++++++ packages/core/tests/storage-routes.test.ts | 335 +++++++ packages/core/tests/storage-settings.test.ts | 278 ++++++ packages/core/tests/webui-backup.test.ts | 13 +- packages/onebot/package.json | 4 + .../onebot/src/actions/stream-download.ts | 57 +- packages/onebot/src/actions/stream-file.ts | 71 +- packages/onebot/src/stream-storage.ts | 238 +++++ packages/onebot/tests/setup.ts | 26 + packages/onebot/tests/stream-download.test.ts | 45 + packages/onebot/tests/stream-file.test.ts | 27 +- packages/onebot/tests/stream-storage.test.ts | 113 +++ packages/onebot/vitest.config.ts | 1 + .../src/components/pages/settings-page.tsx | 5 +- .../src/components/settings/storage-panel.tsx | 817 ++++++++++++++++ packages/webui/src/lib/api/client.ts | 27 +- packages/webui/src/lib/api/types.ts | 12 + .../webui/src/lib/storage-presentation.ts | 75 ++ packages/webui/src/router/index.tsx | 2 +- packages/webui/src/types.ts | 132 +++ packages/webui/tests/storage-api.test.ts | 108 +++ .../webui/tests/storage-presentation.test.ts | 50 + 33 files changed, 5115 insertions(+), 136 deletions(-) create mode 100644 packages/core/src/webui/storage-management.ts create mode 100644 packages/core/src/webui/storage-routes.ts create mode 100644 packages/core/src/webui/storage-settings.ts create mode 100644 packages/core/tests/storage-management.test.ts create mode 100644 packages/core/tests/storage-routes.test.ts create mode 100644 packages/core/tests/storage-settings.test.ts create mode 100644 packages/onebot/src/stream-storage.ts create mode 100644 packages/onebot/tests/setup.ts create mode 100644 packages/onebot/tests/stream-storage.test.ts create mode 100644 packages/webui/src/components/settings/storage-panel.tsx create mode 100644 packages/webui/src/lib/storage-presentation.ts create mode 100644 packages/webui/tests/storage-api.test.ts create mode 100644 packages/webui/tests/storage-presentation.test.ts diff --git a/README.md b/README.md index 2b16ef54..324652f6 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ SnowLuma 将会话接入、协议解析、身份映射、OneBot 转换和网络 | OneBot 接入 | OneBot v11 动作与事件,支持 WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 | | 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及 JSON / XML 卡片等常见消息元素 | | 多账号运行 | 每个 QQ 账号独立维护会话、身份映射、消息存储与网络适配器 | -| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、密码管理与可定制总览 | +| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、存储管理、密码管理与可定制总览 | | 开发者工具 | 提供 [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) | | 可观察错误 | 关键解析与执行失败会留下明确上下文,不以静默丢弃掩盖问题 | @@ -86,6 +86,18 @@ SNOWLUMA_ACCEPT_PRIVACY=1 +## 日志与存储管理 + +WebUI 的“系统设置 → 存储管理”可查看受管数据占用、调整日志策略,并清理日志、非活动传输临时文件或离线账号的消息、媒体和表情回应数据库。清理范围固定,不包含配置、凭据或其他文件。 + +| 设置 | 默认值 | 环境变量 | +| --- | --- | --- | +| 日志树总量上限 | 1024 MB | `SNOWLUMA_LOG_MAX_TOTAL_MB` | +| 日志保留天数 | 7 天;`0` 表示关闭按日期清理 | `SNOWLUMA_LOG_RETAIN_DAYS` | +| 按账号额外写日志 | 关闭 | `SNOWLUMA_LOG_PER_UIN` | + +环境变量优先于 `config/runtime.json`,对应字段会在 WebUI 中显示为锁定。`SNOWLUMA_LOG_MAX_MB` 仅控制单个日志分卷大小,不是日志树总量上限。 + ## 选择接入方式 | 入口 | 适合场景 | 参考 | diff --git a/packages/common/src/log-file-transport.ts b/packages/common/src/log-file-transport.ts index 8bc96a69..2e03404e 100644 --- a/packages/common/src/log-file-transport.ts +++ b/packages/common/src/log-file-transport.ts @@ -1,18 +1,86 @@ import fs from 'node:fs'; import path from 'node:path'; import { sanitizeLogLine } from './log-sanitize'; +import { + MAX_LOG_RETAIN_DAYS, + MAX_LOG_TOTAL_MB, +} from './runtime'; const DEFAULT_DIR = 'logs'; const DEFAULT_MAX_MB = 50; +const DEFAULT_MAX_TOTAL_MB = 1024; const DEFAULT_RETAIN_DAYS = 7; const FILE_PREFIX = 'snowluma-'; const FILE_SUFFIX = '.log'; const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/; +const ACCOUNT_DIR_RE = /^\d+$/; +const QUOTA_RETRY_MS = 5_000; -function parsePositiveInt(v: string | undefined, dflt: number): number { - if (!v) return dflt; - const n = Number.parseInt(v, 10); - return Number.isFinite(n) && n > 0 ? n : dflt; +export type LogStorageState = 'disabled' | 'healthy' | 'warning' | 'degraded'; + +export interface LogStorageStatus { + state: LogStorageState; + directory: string; + totalBytes: number; + maxTotalBytes: number; + retainDays: number; + perUinEnabled: boolean; + fileCount: number; + activeFileCount: number; + droppedLines: number; + lastError?: string; +} + +export interface LogStoragePolicy { + maxTotalMb: number; + retainDays: number; + perUinEnabled: boolean; +} + +export interface LogCleanupResult { + deletedFiles: number; + freedBytes: number; + failures: Array<{ file: string; message: string }>; + status: LogStorageStatus; +} + +function parseNonNegativeInt( + value: string | undefined, + fallback: number, + max: number, + field?: string, +): number { + if (value === undefined || value.trim() === '') return fallback; + const parsed = Number(value.trim()); + if (Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= max) return parsed; + if (field) { + throw new RangeError(`${field} must be an integer in 0..${String(max)}`); + } + return fallback; +} + +function parseRequiredPositiveInt( + value: string | undefined, + fallback: number, + max: number, + field: string, +): number { + if (value === undefined || value.trim() === '') return fallback; + const parsed = Number(value.trim()); + if (Number.isSafeInteger(parsed) && parsed > 0 && parsed <= max) return parsed; + throw new RangeError(`${field} must be an integer in 1..${String(max)}`); +} + +function parseRequiredBool( + value: string | undefined, + fallback: boolean, + field: string, +): boolean { + if (value === undefined || value.trim() === '') return fallback; + const normalized = value.trim().toLowerCase(); + if (['1', 'true', 'yes', 'on'].includes(normalized)) return true; + if (['0', 'false', 'no', 'off'].includes(normalized)) return false; + throw new TypeError(`${field} must be a boolean`); } function todayString(d: Date = new Date()): string { @@ -35,30 +103,367 @@ interface OpenFile { path: string; } +interface ManagedLogFile { + path: string; + bytes: number; + mtimeMs: number; + date: string; +} + +/** + * Owns the byte budget for the whole managed log tree. Writers reserve bytes + * here before enqueueing them to a WriteStream, so buffered bytes count toward + * the hard limit even before fs.stat can observe them. + */ +class LogQuota { + private readonly files = new Map(); + private readonly active = new Set(); + private usedBytes = 0; + private degraded = false; + private lastError: string | null = null; + private nextRetryAt = 0; + private droppedLines = 0; + private maintenanceSuspensions = 0; + + constructor( + private readonly root: string, + private maxTotalBytes: number, + private retainDays: number, + maintainOnLoad = true, + ) { + this.loadManagedFiles(); + if (maintainOnLoad) { + this.cleanupExpired(); + this.ensureCapacity(0); + } + } + + activate(filePath: string): number | null { + const normalized = path.resolve(filePath); + const known = this.files.get(normalized); + if (known) { + this.active.add(normalized); + return known.bytes; + } + let bytes = 0; + let mtimeMs = Date.now(); + try { + const stat = fs.statSync(normalized); + bytes = stat.size; + mtimeMs = stat.mtimeMs; + } catch (error) { + if (!isMissing(error)) { + this.enterDegraded( + `failed to inspect active log ${normalized}: ${errorMessage(error)}`, + ); + return null; + } + } + const date = FILE_RE.exec(path.basename(normalized))?.[1] ?? todayString(); + this.files.set(normalized, { path: normalized, bytes, mtimeMs, date }); + this.usedBytes += bytes; + this.active.add(normalized); + return bytes; + } + + deactivate(filePath: string): void { + this.active.delete(path.resolve(filePath)); + if (this.maintenanceSuspensions > 0) return; + this.maintainAfterClose(); + } + + suspendMaintenance(): () => void { + this.maintenanceSuspensions += 1; + let resumed = false; + return () => { + if (resumed) return; + resumed = true; + this.maintenanceSuspensions = Math.max(0, this.maintenanceSuspensions - 1); + }; + } + + reserve(filePath: string, bytes: number): boolean { + if (bytes <= 0) return true; + if (this.degraded && !this.retry(false)) { + this.droppedLines += 1; + return false; + } + if (!this.ensureCapacity(bytes)) { + this.droppedLines += 1; + return false; + } + + const normalized = path.resolve(filePath); + const file = this.files.get(normalized); + if (!file) { + if (this.activate(normalized) === null) { + this.droppedLines += 1; + return false; + } + return this.reserve(normalized, bytes); + } + file.bytes += bytes; + file.mtimeMs = Date.now(); + this.usedBytes += bytes; + return true; + } + + writeFailed(filePath: string, error: unknown): void { + this.storageFailed(`write ${filePath}`, error); + } + + storageFailed(operation: string, error: unknown): void { + this.enterDegraded(`${operation}: ${errorMessage(error)}`); + } + + snapshot(): Omit { + return { + state: this.degraded ? 'degraded' : this.lastError ? 'warning' : 'healthy', + totalBytes: this.usedBytes, + fileCount: this.files.size, + activeFileCount: this.active.size, + droppedLines: this.droppedLines, + ...(this.lastError ? { lastError: this.lastError } : {}), + }; + } + + updatePolicy(maxTotalBytes: number, retainDays: number): void { + this.maxTotalBytes = maxTotalBytes; + this.retainDays = retainDays; + this.degraded = false; + this.lastError = null; + this.nextRetryAt = 0; + try { + this.refreshClosedFiles(); + this.cleanupExpired(); + this.ensureCapacity(0); + } catch (error) { + this.enterDegraded(`failed to apply log storage policy: ${errorMessage(error)}`); + throw error; + } + } + + clearClosedFiles(): Omit { + this.refreshClosedFiles(); + let deletedFiles = 0; + let freedBytes = 0; + const failures: LogCleanupResult['failures'] = []; + const candidates = [...this.files.values()] + .filter((file) => !this.active.has(file.path)) + .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); + for (const file of candidates) { + const bytes = file.bytes; + if (this.deleteManagedFile(file, 'capacity')) { + deletedFiles += 1; + freedBytes += bytes; + } else { + failures.push({ + file: path.relative(this.root, file.path), + message: this.lastError ?? 'unknown cleanup error', + }); + } + } + if (failures.length === 0) { + this.degraded = false; + this.lastError = null; + this.nextRetryAt = 0; + } else if (this.usedBytes > this.maxTotalBytes) { + this.enterDegraded( + `managed logs still use ${String(this.usedBytes)} bytes after manual cleanup, ` + + `exceeding the ${String(this.maxTotalBytes)} byte limit`, + ); + } + this.ensureCapacity(0); + return { deletedFiles, freedBytes, failures }; + } + + private retry(force: boolean): boolean { + if (!force && Date.now() < this.nextRetryAt) return false; + this.degraded = false; + this.lastError = null; + try { + this.refreshClosedFiles(); + const recovered = this.ensureCapacity(0); + if (recovered) this.nextRetryAt = 0; + return recovered; + } catch (error) { + this.enterDegraded(`failed to refresh managed logs: ${errorMessage(error)}`); + return false; + } + } + + private maintainAfterClose(): void { + try { + this.refreshClosedFiles(); + this.cleanupExpired(); + if (this.degraded) this.retry(true); + else this.ensureCapacity(0); + } catch (error) { + this.enterDegraded(`failed to maintain managed logs after rotation: ${errorMessage(error)}`); + } + } + + private ensureCapacity(incomingBytes: number): boolean { + if (this.usedBytes + incomingBytes <= this.maxTotalBytes) return true; + + const candidates = [...this.files.values()] + .filter((file) => !this.active.has(file.path)) + .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); + for (const file of candidates) { + if (this.usedBytes + incomingBytes <= this.maxTotalBytes) break; + if (!this.deleteManagedFile(file, 'capacity')) break; + } + + if (this.usedBytes + incomingBytes <= this.maxTotalBytes) return true; + this.enterDegraded( + `managed logs require ${String(this.usedBytes + incomingBytes)} bytes, ` + + `exceeding the ${String(this.maxTotalBytes)} byte limit; no closed log can be reclaimed`, + ); + return false; + } + + private enterDegraded(message: string): void { + const shouldReport = !this.degraded || this.lastError !== message; + this.degraded = true; + this.lastError = message; + this.nextRetryAt = Date.now() + QUOTA_RETRY_MS; + if (shouldReport) reportStorageError(message); + } + + private cleanupExpired(): void { + if (this.retainDays === 0) return; + const cutoff = Date.now() - this.retainDays * 24 * 60 * 60 * 1000; + const expired = [...this.files.values()] + .filter( + (file) => !this.active.has(file.path) && dateOf(file.date).getTime() < cutoff, + ) + .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); + for (const file of expired) { + if (!this.deleteManagedFile(file, 'retention')) break; + } + } + + private deleteManagedFile(file: ManagedLogFile, reason: 'capacity' | 'retention'): boolean { + try { + fs.unlinkSync(file.path); + this.files.delete(file.path); + this.usedBytes = Math.max(0, this.usedBytes - file.bytes); + return true; + } catch (error) { + this.lastError = + `${reason} cleanup failed for ${file.path}: ${error instanceof Error ? error.message : String(error)}`; + reportStorageError(this.lastError); + return false; + } + } + + private loadManagedFiles(): void { + for (const file of listManagedLogFiles(this.root)) { + this.files.set(file.path, file); + this.usedBytes += file.bytes; + } + } + + /** Refresh only closed files; active stream bytes are tracked in-memory and + * may be newer than fs.stat while the WriteStream buffer is still flushing. */ + private refreshClosedFiles(): void { + const disk = new Map(listManagedLogFiles(this.root).map((file) => [file.path, file])); + for (const [filePath, file] of this.files) { + if (this.active.has(filePath)) continue; + const next = disk.get(filePath); + this.usedBytes -= file.bytes; + if (next) { + this.files.set(filePath, next); + this.usedBytes += next.bytes; + disk.delete(filePath); + } else { + this.files.delete(filePath); + } + } + for (const file of disk.values()) { + if (this.files.has(file.path)) continue; + this.files.set(file.path, file); + this.usedBytes += file.bytes; + } + } +} + +function listManagedLogFiles(root: string): ManagedLogFile[] { + const out: ManagedLogFile[] = []; + const readDirectory = (dir: string): fs.Dirent[] | null => { + try { + return fs.readdirSync(dir, { withFileTypes: true }); + } catch (error) { + if (isMissing(error)) return null; + throw new Error( + `failed to read managed log directory ${dir}: ${errorMessage(error)}`, + { cause: error }, + ); + } + }; + const visit = (dir: string, entries: fs.Dirent[]): void => { + for (const entry of entries) { + if (!entry.isFile()) continue; + const match = FILE_RE.exec(entry.name); + if (!match) continue; + const filePath = path.resolve(dir, entry.name); + try { + const stat = fs.statSync(filePath); + out.push({ + path: filePath, + bytes: stat.size, + mtimeMs: stat.mtimeMs, + date: match[1]!, + }); + } catch (error) { + if (isMissing(error)) continue; + throw new Error( + `failed to stat managed log ${filePath}: ${errorMessage(error)}`, + { cause: error }, + ); + } + } + }; + + const rootEntries = readDirectory(root); + if (!rootEntries) return out; + visit(root, rootEntries); + for (const entry of rootEntries) { + if (entry.isDirectory() && ACCOUNT_DIR_RE.test(entry.name)) { + const accountDir = path.join(root, entry.name); + const accountEntries = readDirectory(accountDir); + if (accountEntries) visit(accountDir, accountEntries); + } + } + return out; +} + +function reportStorageError(message: string): void { + process.stderr.write(`[logger.storage] ${message}\n`); +} + /** * Owns one output directory: keeps at most one open WriteStream, handles - * daily rollover, per-file size cap, and retention cleanup. The shared - * top-level dir uses one of these; each per-UIN sub-dir gets its own. + * daily rollover and the per-file size cap. Retention and total-tree quota + * belong to the shared LogQuota, never to each writer independently. */ class FileWriter { private disabled = false; private file: OpenFile | null = null; + private readonly pendingCloses = new Set>(); constructor( private readonly dir: string, private readonly maxBytes: number, - private readonly retainDays: number, + private readonly quota: LogQuota, ) { try { fs.mkdirSync(dir, { recursive: true }); } catch (err) { this.disabled = true; - console.error( - `[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`, - ); + this.quota.storageFailed(`failed to create log directory ${dir}`, err); return; } - this.cleanup(); } get isDisabled(): boolean { @@ -69,45 +474,53 @@ class FileWriter { return this.file?.path ?? null; } - write(data: string, bytes: number): void { - if (this.disabled) return; + async prepare(): Promise { + this.ensureForToday(todayString()); + const stream = this.file?.stream; + if (!stream) { + throw new Error(`failed to prepare log writer in ${this.dir}`); + } + await new Promise((resolve, reject) => { + const opened = () => { + stream.off('error', failed); + resolve(); + }; + const failed = (error: Error) => { + stream.off('open', opened); + reject(error); + }; + stream.once('open', opened); + stream.once('error', failed); + }); + } + + write(data: string, bytes: number): boolean { + if (this.disabled) return false; const today = todayString(); this.ensureForToday(today); - if (!this.file) return; + if (!this.file) return false; if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) { this.rotateBySize(); - if (!this.file) return; + if (!this.file) return false; } + if (!this.quota.reserve(this.file.path, bytes)) return false; this.file.stream.write(data); this.file.bytes += bytes; + return true; } - close(): Promise { - const f = this.file; - this.file = null; - if (!f) return Promise.resolve(); - return new Promise((resolve) => { - try { - f.stream.end(() => resolve()); - } catch { - resolve(); - } - }); + async close(): Promise { + this.closeCurrent(); + await Promise.all(this.pendingCloses); } private ensureForToday(today: string): void { if (this.file && this.file.date === today) return; if (this.file) { - try { - this.file.stream.end(); - } catch { - /* ignore */ - } - this.file = null; - this.cleanup(); + this.closeCurrent(); } // Resume from the highest existing split index for today (so two @@ -120,34 +533,57 @@ class FileWriter { private rotateBySize(): void { if (!this.file) return; const date = this.file.date; - try { - this.file.stream.end(); - } catch { - /* ignore */ - } - let next = this.file.splitIndex + 1; + const previousIndex = this.file.splitIndex; + this.closeCurrent(); + let next = previousIndex + 1; while (fs.existsSync(this.pathFor(date, next))) next++; this.file = this.openFile(date, next); } + private closeCurrent(): void { + const file = this.file; + this.file = null; + if (!file) return; + + let finish!: () => void; + const closed = new Promise((resolve) => { + let settled = false; + finish = () => { + if (settled) return; + settled = true; + this.quota.deactivate(file.path); + resolve(); + }; + }); + this.pendingCloses.add(closed); + void closed.finally(() => this.pendingCloses.delete(closed)); + + file.stream.once('error', finish); + try { + file.stream.end(finish); + } catch (error) { + this.quota.writeFailed(file.path, error); + finish(); + } + } + private openFile(date: string, splitIndex: number): OpenFile | null { const p = this.pathFor(date, splitIndex); + const existingBytes = this.quota.activate(p); + if (existingBytes === null) return null; try { - let bytes = 0; - try { - bytes = fs.statSync(p).size; - } catch { - /* file doesn't exist yet */ - } const stream = fs.createWriteStream(p, { flags: 'a' }); stream.on('error', (err) => { - console.error(`[logger] file write error on ${p}: ${err.message}`); + this.disabled = true; + if (this.file?.stream === stream) this.file = null; + this.quota.deactivate(p); + this.quota.writeFailed(p, err); }); - return { stream, bytes, date, splitIndex, path: p }; + return { stream, bytes: existingBytes, date, splitIndex, path: p }; } catch (err) { - console.error( - `[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`, - ); + this.disabled = true; + this.quota.deactivate(p); + this.quota.storageFailed(`failed to open log file ${p}`, err); return null; } } @@ -156,55 +592,55 @@ class FileWriter { const tail = splitIndex > 0 ? `.${splitIndex}` : ''; return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`); } - - private cleanup(): void { - let entries: string[]; - try { - entries = fs.readdirSync(this.dir); - } catch { - return; - } - const retainMs = this.retainDays * 24 * 60 * 60 * 1000; - const cutoff = Date.now() - retainMs; - for (const name of entries) { - const m = FILE_RE.exec(name); - if (!m) continue; - const dateStr = m[1]!; - if (dateOf(dateStr).getTime() < cutoff) { - try { - fs.unlinkSync(path.join(this.dir, name)); - } catch { - /* ignore */ - } - } - } - } } export class FileTransport { private readonly dir: string; private readonly maxBytes: number; - private readonly retainDays: number; + private maxTotalBytes: number; + private retainDays: number; private readonly enabled: boolean; - private readonly perUinEnabled: boolean; + private perUinEnabled: boolean; + private initializationError: string | null = null; + private nextWriterRetryAt = 0; + private quota: LogQuota | null = null; private shared: FileWriter | null = null; private perUin = new Map(); - constructor() { - this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR; + constructor(policy?: LogStoragePolicy) { + if (policy) validatePolicy(policy); + this.dir = path.resolve(process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR); this.maxBytes = - parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024; - this.retainDays = parsePositiveInt( - process.env.SNOWLUMA_LOG_RETAIN_DAYS, - DEFAULT_RETAIN_DAYS, - ); + parseRequiredPositiveInt( + process.env.SNOWLUMA_LOG_MAX_MB, + DEFAULT_MAX_MB, + MAX_LOG_TOTAL_MB, + 'SNOWLUMA_LOG_MAX_MB', + ) * 1024 * 1024; + this.maxTotalBytes = + (policy?.maxTotalMb + ?? parseRequiredPositiveInt( + process.env.SNOWLUMA_LOG_MAX_TOTAL_MB, + DEFAULT_MAX_TOTAL_MB, + MAX_LOG_TOTAL_MB, + 'SNOWLUMA_LOG_MAX_TOTAL_MB', + )) * 1024 * 1024; + this.retainDays = policy?.retainDays + ?? parseNonNegativeInt( + process.env.SNOWLUMA_LOG_RETAIN_DAYS, + DEFAULT_RETAIN_DAYS, + MAX_LOG_RETAIN_DAYS, + 'SNOWLUMA_LOG_RETAIN_DAYS', + ); this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0'; - this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0'; + this.perUinEnabled = policy?.perUinEnabled + ?? parseRequiredBool( + process.env.SNOWLUMA_LOG_PER_UIN, + false, + 'SNOWLUMA_LOG_PER_UIN', + ); - if (this.enabled) { - const w = new FileWriter(this.dir, this.maxBytes, this.retainDays); - this.shared = w.isDisabled ? null : w; - } + if (this.enabled) this.initialize(); } /** True when no file output will happen (env disable or init failure). */ @@ -222,17 +658,144 @@ export class FileTransport { return this.perUin.get(uin)?.currentPath ?? null; } + getStorageStatus(): LogStorageStatus { + if (!this.quota) { + return { + state: 'disabled', + directory: this.dir, + totalBytes: 0, + maxTotalBytes: this.maxTotalBytes, + retainDays: this.retainDays, + perUinEnabled: this.perUinEnabled, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + ...(this.initializationError ? { lastError: this.initializationError } : {}), + }; + } + return { + ...this.quota.snapshot(), + directory: this.dir, + maxTotalBytes: this.maxTotalBytes, + retainDays: this.retainDays, + perUinEnabled: this.perUinEnabled, + }; + } + + async updatePolicy(policy: LogStoragePolicy): Promise { + validatePolicy(policy); + this.maxTotalBytes = policy.maxTotalMb * 1024 * 1024; + this.retainDays = policy.retainDays; + + const disablingPerUin = this.perUinEnabled && !policy.perUinEnabled; + this.perUinEnabled = policy.perUinEnabled; + if (disablingPerUin) { + const writers = [...this.perUin.values()]; + this.perUin.clear(); + await Promise.all(writers.map((writer) => writer.close())); + } + if (this.quota) this.quota.updatePolicy(this.maxTotalBytes, this.retainDays); + if (this.enabled && (!this.quota || !this.shared || this.shared.isDisabled)) { + await this.recoverSharedWriter(true); + } + return this.getStorageStatus(); + } + + async clearManagedLogs(): Promise { + if (!this.enabled) return this.clearLogsWhileDisabled(); + if (!this.quota) { + try { + this.quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays); + } catch (error) { + this.recordWriterRecoveryFailure(error); + } + } + if (!this.quota) { + return { + deletedFiles: 0, + freedBytes: 0, + failures: this.initializationError + ? [{ file: '.', message: this.initializationError }] + : [], + status: this.getStorageStatus(), + }; + } + + const quota = this.quota; + const accountUins = [...this.perUin.keys()]; + const writers = [ + ...(this.shared ? [this.shared] : []), + ...this.perUin.values(), + ]; + this.shared = null; + this.perUin.clear(); + const resumeMaintenance = quota.suspendMaintenance(); + try { + await Promise.all(writers.map((writer) => writer.close())); + } finally { + resumeMaintenance(); + } + + const result = quota.clearClosedFiles(); + + const shared = new FileWriter(this.dir, this.maxBytes, quota); + try { + await shared.prepare(); + this.shared = shared; + this.initializationError = null; + this.nextWriterRetryAt = 0; + } catch (error) { + this.recordWriterRecoveryFailure(error); + result.failures.push({ + file: '.', + message: this.initializationError ?? 'failed to reopen the shared log writer', + }); + } + if (this.perUinEnabled) { + for (const uin of accountUins) { + const writer = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, quota); + if (writer.isDisabled) continue; + try { + await writer.prepare(); + this.perUin.set(uin, writer); + } catch (error) { + quota.storageFailed(`failed to reopen account log writer for ${String(uin)}`, error); + result.failures.push({ + file: String(uin), + message: `failed to reopen account log writer: ${errorMessage(error)}`, + }); + } + } + } + + return { ...result, status: this.getStorageStatus() }; + } + write(line: string, uin?: number): void { + if (!this.enabled) return; + if (!this.shared || this.shared.isDisabled) { + if (!this.recoverSharedWriterForWrite()) return; + } if (!this.shared) return; const data = sanitizeLogLine(line) + '\n'; const bytes = Buffer.byteLength(data, 'utf8'); - this.shared.write(data, bytes); + if (!this.shared.write(data, bytes)) { + if (this.shared.isDisabled) { + this.shared = null; + this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS; + } + return; + } - if (uin !== undefined && this.perUinEnabled) { + if (uin !== undefined && this.perUinEnabled && this.quota) { let w = this.perUin.get(uin); + if (w?.isDisabled) { + this.perUin.delete(uin); + w = undefined; + } if (!w) { - w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays); + w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.quota); if (w.isDisabled) return; this.perUin.set(uin, w); } @@ -248,17 +811,177 @@ export class FileTransport { this.perUin.clear(); await Promise.all(closes); } + + private async recoverSharedWriter(force: boolean): Promise { + if (!this.enabled) return; + if (!force && Date.now() < this.nextWriterRetryAt) { + throw new Error(this.initializationError ?? 'log writer retry is rate-limited'); + } + if (this.shared?.isDisabled) this.shared = null; + if (!this.quota) this.initialize(); + if (!this.shared && this.quota) { + const writer = new FileWriter(this.dir, this.maxBytes, this.quota); + if (!writer.isDisabled) this.shared = writer; + } + const writer = this.shared; + if (!writer) { + throw new Error(this.initializationError ?? 'failed to create the shared log writer'); + } + try { + await writer.prepare(); + if (writer.isDisabled || !writer.currentPath) { + throw new Error('the shared log writer did not open a file'); + } + this.initializationError = null; + this.nextWriterRetryAt = 0; + } catch (error) { + this.shared = null; + this.recordWriterRecoveryFailure(error); + throw error; + } + } + + private recoverSharedWriterForWrite(): boolean { + if (!this.enabled || Date.now() < this.nextWriterRetryAt) return false; + if (this.shared?.isDisabled) this.shared = null; + if (!this.quota) this.initialize(); + if (!this.shared && this.quota) { + const writer = new FileWriter(this.dir, this.maxBytes, this.quota); + if (!writer.isDisabled) this.shared = writer; + } + if (this.shared) { + this.initializationError = null; + this.nextWriterRetryAt = 0; + return true; + } + return false; + } + + private clearLogsWhileDisabled(): LogCleanupResult { + try { + const quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays, false); + const result = quota.clearClosedFiles(); + const snapshot = quota.snapshot(); + return { + ...result, + status: { + ...snapshot, + state: 'disabled', + directory: this.dir, + maxTotalBytes: this.maxTotalBytes, + retainDays: this.retainDays, + perUinEnabled: this.perUinEnabled, + }, + }; + } catch (error) { + const message = `failed to clear disabled log storage ${this.dir}: ${errorMessage(error)}`; + reportStorageError(message); + return { + deletedFiles: 0, + freedBytes: 0, + failures: [{ file: '.', message }], + status: { + state: 'disabled', + directory: this.dir, + totalBytes: 0, + maxTotalBytes: this.maxTotalBytes, + retainDays: this.retainDays, + perUinEnabled: this.perUinEnabled, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + lastError: message, + }, + }; + } + } + + private recordWriterRecoveryFailure(error: unknown): void { + this.initializationError = + `failed to initialize log storage ${this.dir}: ${errorMessage(error)}`; + this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS; + reportStorageError(this.initializationError); + } + + private initialize(): void { + try { + fs.mkdirSync(this.dir, { recursive: true }); + const quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays); + const writer = new FileWriter(this.dir, this.maxBytes, quota); + if (writer.isDisabled) { + throw new Error(`failed to create shared log writer in ${this.dir}`); + } + this.quota = quota; + this.shared = writer; + this.initializationError = null; + this.nextWriterRetryAt = 0; + } catch (error) { + this.quota = null; + this.shared = null; + this.recordWriterRecoveryFailure(error); + } + } +} + +function validatePolicy(policy: LogStoragePolicy): void { + if ( + !Number.isSafeInteger(policy.maxTotalMb) + || policy.maxTotalMb <= 0 + || policy.maxTotalMb > MAX_LOG_TOTAL_MB + ) { + throw new RangeError( + `maxTotalMb must be an integer in 1..${String(MAX_LOG_TOTAL_MB)}`, + ); + } + if ( + !Number.isSafeInteger(policy.retainDays) + || policy.retainDays < 0 + || policy.retainDays > MAX_LOG_RETAIN_DAYS + ) { + throw new RangeError( + `retainDays must be an integer in 0..${String(MAX_LOG_RETAIN_DAYS)}`, + ); + } + if (typeof policy.perUinEnabled !== 'boolean') { + throw new TypeError('perUinEnabled must be a boolean'); + } } let singleton: FileTransport | null = null; +let configuredPolicy: LogStoragePolicy | null = null; export function getFileTransport(): FileTransport { - if (!singleton) singleton = new FileTransport(); + if (!singleton) singleton = new FileTransport(configuredPolicy ?? undefined); return singleton; } +export async function configureFileTransport(policy: LogStoragePolicy): Promise { + validatePolicy(policy); + configuredPolicy = { ...policy }; + if (!singleton) singleton = new FileTransport(configuredPolicy); + else await singleton.updatePolicy(configuredPolicy); + return singleton.getStorageStatus(); +} + +export function getLogStorageStatus(): LogStorageStatus { + return getFileTransport().getStorageStatus(); +} + +export function clearManagedLogs(): Promise { + return getFileTransport().clearManagedLogs(); +} + /** Reset state between tests. Closes all active file handles. */ export async function _resetFileTransportForTesting(): Promise { if (singleton) await singleton.close(); singleton = null; + configuredPolicy = null; +} + +function isMissing(error: unknown): boolean { + return error instanceof Error && 'code' in error && error.code === 'ENOENT'; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); } diff --git a/packages/common/src/runtime.ts b/packages/common/src/runtime.ts index e6eca30b..40ed443d 100644 --- a/packages/common/src/runtime.ts +++ b/packages/common/src/runtime.ts @@ -16,6 +16,12 @@ export interface RuntimeConfig { /** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY), * consumed by the WebUI's client-ip resolver. '' = trust nobody. */ trustProxy?: string; + /** Aggregate cap for every managed file below the log root. */ + logMaxTotalMb?: number; + /** Calendar-day retention. Zero disables date-based deletion. */ + logRetainDays?: number; + /** Duplicate UIN-scoped lines into logs// in addition to the shared log. */ + logPerUin?: boolean; } const CONFIG_DIR = 'config'; @@ -23,6 +29,13 @@ const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json'); const DEFAULT_WEBUI_PORT = 5099; const DEFAULT_WEBUI_HOST = '0.0.0.0'; +export const DEFAULT_LOG_MAX_TOTAL_MB = 1024; +export const DEFAULT_LOG_RETAIN_DAYS = 7; +export const DEFAULT_LOG_PER_UIN = false; +export const MAX_LOG_TOTAL_MB = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024)); +export const MAX_LOG_RETAIN_DAYS = Math.floor( + Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000), +); /** * Pure on-disk-object → typed config normalization (defaults + validation, @@ -36,6 +49,21 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig { webuiHost: normalizeHost(obj.webuiHost), webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false }, trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '', + logMaxTotalMb: normalizeRequiredInteger( + obj.logMaxTotalMb, + DEFAULT_LOG_MAX_TOTAL_MB, + 1, + MAX_LOG_TOTAL_MB, + 'logMaxTotalMb', + ), + logRetainDays: normalizeRequiredInteger( + obj.logRetainDays, + DEFAULT_LOG_RETAIN_DAYS, + 0, + MAX_LOG_RETAIN_DAYS, + 'logRetainDays', + ), + logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'), }; } @@ -58,6 +86,28 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial | null { } function saveRuntimeConfig(config: RuntimeConfig): void { - fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8'); + const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`; + try { + fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8'); + fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH); + } catch (error) { + try { + fs.unlinkSync(temporaryPath); + } catch (cleanupError) { + if (!isErrnoCode(cleanupError, 'ENOENT')) { + throw new AggregateError( + [error, cleanupError], + 'failed to persist runtime config and remove its temporary file', + ); + } + } + throw error; + } } /** True when the raw on-disk object already matches the normalized config @@ -122,6 +188,9 @@ function sameRuntimeConfig(parsed: Record, n: RuntimeConfig): b && parsed.webuiHost === n.webuiHost && parsedTls === n.webuiTls?.enabled && parsed.trustProxy === n.trustProxy + && parsed.logMaxTotalMb === n.logMaxTotalMb + && parsed.logRetainDays === n.logRetainDays + && parsed.logPerUin === n.logPerUin ); } @@ -155,6 +224,37 @@ function normalizePort(value: unknown, fallback: number): number { return fallback; } +function normalizeRequiredInteger( + value: unknown, + fallback: number, + min: number, + max: number, + field: string, +): number { + if (value === undefined) return fallback; + const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value; + if ( + typeof n === 'number' + && Number.isSafeInteger(n) + && n >= min + && n <= max + ) { + return n; + } + throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`); +} + +function normalizeRequiredBool( + value: unknown, + fallback: boolean, + field: string, +): boolean { + if (value === undefined) return fallback; + const parsed = parseBoolValue(value); + if (parsed !== undefined) return parsed; + throw new TypeError(`${field} must be a boolean`); +} + function normalizeBool(value: unknown, fallback: boolean): boolean { if (typeof value === 'boolean') return value; if (typeof value === 'number') return value !== 0; @@ -166,6 +266,40 @@ function normalizeBool(value: unknown, fallback: boolean): boolean { return fallback; } +function parseRequiredIntegerEnv( + raw: unknown, + min: number, + max: number, + field: string, +): number | undefined { + if (typeof raw !== 'string' || !raw.trim()) return undefined; + const n = Number(raw.trim()); + if (Number.isSafeInteger(n) && n >= min && n <= max) return n; + throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`); +} + +function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined { + if (typeof raw !== 'string' || !raw.trim()) return undefined; + const parsed = parseBoolValue(raw); + if (parsed !== undefined) return parsed; + throw new TypeError(`${field} must be a boolean`); +} + +function parseBoolValue(raw: unknown): boolean | undefined { + if (typeof raw === 'boolean') return raw; + if (raw === 1) return true; + if (raw === 0) return false; + if (typeof raw !== 'string') return undefined; + const value = raw.trim().toLowerCase(); + if (value === 'true' || value === '1' || value === 'yes' || value === 'on') return true; + if (value === 'false' || value === '0' || value === 'no' || value === 'off') return false; + return undefined; +} + function isObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } + +function isErrnoCode(error: unknown, code: string): boolean { + return error instanceof Error && 'code' in error && error.code === code; +} diff --git a/packages/common/tests/runtime.test.ts b/packages/common/tests/runtime.test.ts index 8814c34f..dbf4dba4 100644 --- a/packages/common/tests/runtime.test.ts +++ b/packages/common/tests/runtime.test.ts @@ -1,4 +1,6 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime'; describe('normalizeRuntimeConfig', () => { @@ -9,6 +11,9 @@ describe('normalizeRuntimeConfig', () => { webuiHost: '0.0.0.0', webuiTls: { enabled: false }, trustProxy: '', + logMaxTotalMb: 1024, + logRetainDays: 7, + logPerUin: false, }); }); @@ -19,12 +24,18 @@ describe('normalizeRuntimeConfig', () => { webuiHost: '127.0.0.1', webuiTls: { enabled: true }, trustProxy: '1', + logMaxTotalMb: 2048, + logRetainDays: 0, + logPerUin: true, })).toEqual({ webuiPort: 8080, hookAutoLoad: true, webuiHost: '127.0.0.1', webuiTls: { enabled: true }, trustProxy: '1', + logMaxTotalMb: 2048, + logRetainDays: 0, + logPerUin: true, }); }); @@ -41,6 +52,21 @@ describe('normalizeRuntimeConfig', () => { expect(out.trustProxy).toBe(''); }); + it('fails fast on invalid persisted log settings', () => { + expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 })) + .toThrow(/logMaxTotalMb/); + expect(() => normalizeRuntimeConfig({ logRetainDays: -1 })) + .toThrow(/logRetainDays/); + expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' })) + .toThrow(/logPerUin/); + expect(() => normalizeRuntimeConfig({ logPerUin: '' })) + .toThrow(/logPerUin/); + expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER })) + .toThrow(/logMaxTotalMb/); + expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER })) + .toThrow(/logRetainDays/); + }); + it('coerces webuiTls.enabled loosely and trims a blank host to default', () => { expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true }); expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0'); @@ -65,6 +91,39 @@ describe('resolveRuntimeEnvOverrides', () => { })).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' }); }); + it('parses log storage overrides including retainDays=0', () => { + expect(resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '4096', + SNOWLUMA_LOG_RETAIN_DAYS: '0', + SNOWLUMA_LOG_PER_UIN: '1', + })).toEqual({ + logMaxTotalMb: 4096, + logRetainDays: 0, + logPerUin: true, + }); + }); + + it('fails fast on invalid log storage overrides', () => { + expect(() => resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '0', + })).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/); + expect(() => resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_RETAIN_DAYS: '-1', + })).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/); + expect(() => resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_PER_UIN: 'maybe', + })).toThrow(/SNOWLUMA_LOG_PER_UIN/); + }); + + it('fails fast when converted log storage overrides would be unsafe', () => { + expect(() => resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER), + })).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/); + expect(() => resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER), + })).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/); + }); + it('ignores an out-of-range / non-numeric port env', () => { expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({}); expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({}); @@ -88,11 +147,11 @@ describe('updateRuntimeConfig (fs)', () => { delete process.env.SNOWLUMA_WEBUI_PORT; }); afterEach(async () => { - const fs = await import('fs'); process.chdir(prevCwd); if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT; else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv; fs.rmSync(dir, { recursive: true, force: true }); + vi.restoreAllMocks(); }); it('merges a patch over on-disk values and persists normalized', async () => { @@ -114,4 +173,19 @@ describe('updateRuntimeConfig (fs)', () => { const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8')); expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999 }); + + it('keeps the previous runtime file intact when atomic replacement fails', async () => { + const { updateRuntimeConfig } = await import('../src/runtime'); + updateRuntimeConfig({ logRetainDays: 7 }); + const runtimePath = path.join('config', 'runtime.json'); + const before = fs.readFileSync(runtimePath, 'utf8'); + vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { + throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' }); + }); + + expect(() => updateRuntimeConfig({ logRetainDays: 0 })) + .toThrow(/disk replacement failed/); + expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before); + expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]); + }); }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7996e7d3..9bd2a4e1 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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 diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 45ad1ee8..be2625dc 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -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 { diff --git a/packages/core/src/webui/storage-management.ts b/packages/core/src/webui/storage-management.ts new file mode 100644 index 00000000..4eb4742b --- /dev/null +++ b/packages/core/src/webui/storage-management.ts @@ -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; + +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 { + 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; + 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 { + 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); +} diff --git a/packages/core/src/webui/storage-routes.ts b/packages/core/src/webui/storage-routes.ts new file mode 100644 index 00000000..d1824c90 --- /dev/null +++ b/packages/core/src/webui/storage-routes.ts @@ -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; + 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 = Promise.resolve(); + const serializeMutation = (operation: () => Promise): Promise => { + 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>; + 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 { + 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, 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 { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/packages/core/src/webui/storage-settings.ts b/packages/core/src/webui/storage-settings.ts new file mode 100644 index 00000000..c87af328 --- /dev/null +++ b/packages/core/src/webui/storage-settings.ts @@ -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; + readEffective(): LogStorageStatus; + persist(patch: Partial): RuntimeConfig; + apply(policy: LogStoragePolicy): Promise; +} + +const SETTINGS_FIELDS: LogStorageSettingsField[] = [ + 'logMaxTotalMb', + 'logRetainDays', + 'logPerUin', +]; +const SETTINGS_FIELD_SET = new Set(SETTINGS_FIELDS); + +export class LogStorageSettingsManager { + private updateQueue: Promise = 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 { + const operation = this.updateQueue.then(() => this.performUpdate(body)); + this.updateQueue = operation.then( + () => undefined, + () => undefined, + ); + return operation; + } + + private async performUpdate(body: unknown): Promise { + 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 { + try { + const status = await this.deps.apply(policy); + assertApplied(status, policy); + return []; + } catch (error) { + return [error]; + } + } + + private async rollbackAll( + policy: LogStoragePolicy, + runtime: RuntimeConfig, + ): Promise { + const errors = await this.rollbackRuntime(policy); + try { + this.deps.persist(runtime); + } catch (error) { + errors.push(error); + } + return errors; + } +} + +function coerceLogStorageSettingsPatch(body: unknown): Partial { + 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 = {}; + 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, + 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): Partial { + const patch: Partial = {}; + 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 { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/packages/core/tests/log-file-transport.test.ts b/packages/core/tests/log-file-transport.test.ts index 4bd48404..181b38f4 100644 --- a/packages/core/tests/log-file-transport.test.ts +++ b/packages/core/tests/log-file-transport.test.ts @@ -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 = {}; @@ -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(); }); }); diff --git a/packages/core/tests/logger.test.ts b/packages/core/tests/logger.test.ts index ea5dd1ea..c1ca1531 100644 --- a/packages/core/tests/logger.test.ts +++ b/packages/core/tests/logger.test.ts @@ -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', () => { diff --git a/packages/core/tests/storage-management.test.ts b/packages/core/tests/storage-management.test.ts new file mode 100644 index 00000000..a94c4bf5 --- /dev/null +++ b/packages/core/tests/storage-management.test.ts @@ -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); + }); +}); diff --git a/packages/core/tests/storage-routes.test.ts b/packages/core/tests/storage-routes.test.ts new file mode 100644 index 00000000..d659c5e3 --- /dev/null +++ b/packages/core/tests/storage-routes.test.ts @@ -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 { + 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((resolve) => { + releaseSettings = resolve; + }); + const settingsStarted = new Promise((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' }], + }, + }); + }); +}); diff --git a/packages/core/tests/storage-settings.test.ts b/packages/core/tests/storage-settings.test.ts new file mode 100644 index 00000000..e0bca393 --- /dev/null +++ b/packages/core/tests/storage-settings.test.ts @@ -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[] = []; + 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((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((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]); + }); +}); diff --git a/packages/core/tests/webui-backup.test.ts b/packages/core/tests/webui-backup.test.ts index 446475b9..00c5f552 100644 --- a/packages/core/tests/webui-backup.test.ts +++ b/packages/core/tests/webui-backup.test.ts @@ -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', + ], }]); }); diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 81bd70f3..c7f51cd7 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -91,6 +91,10 @@ "./instance-rkey": { "types": "./src/instance-rkey.ts", "default": "./src/instance-rkey.ts" + }, + "./stream-storage": { + "types": "./src/stream-storage.ts", + "default": "./src/stream-storage.ts" } }, "scripts": { diff --git a/packages/onebot/src/actions/stream-download.ts b/packages/onebot/src/actions/stream-download.ts index b8a476c6..5e45dd94 100644 --- a/packages/onebot/src/actions/stream-download.ts +++ b/packages/onebot/src/actions/stream-download.ts @@ -26,7 +26,7 @@ import { defineStreamAction, f } from '../action-kit'; import type { ApiActionContext } from '../api-handler'; import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types'; import { type StreamSink, StreamStatus } from '../streaming'; -import { STREAM_ROOT } from './stream-file'; +import { STREAM_ROOT, registerActiveStreamItem } from '../stream-storage'; const DEFAULT_CHUNK_BYTES = 64 * 1024; const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size @@ -145,6 +145,8 @@ interface DownloadSource { name: string; size: number; // 0 when unknown iterable: AsyncIterable; + /** Local stream-storage path that must be protected from cleanup while read. */ + managedPath?: string; /** Force the underlying source closed (idle-timeout watchdog / abort). */ abort?: () => void; } @@ -228,7 +230,13 @@ async function resolveDownload( try { real = fs.realpathSync(local); } catch { /* keep lexical */ } if (!isWithinStreamRoot(real)) throw new DownloadError('local downloads are restricted to the stream temp directory'); const rs = fs.createReadStream(real, { highWaterMark: chunkSize }); - return { name: path.basename(real), size: st.size, iterable: rs, abort: () => rs.destroy() }; + return { + name: path.basename(real), + size: st.size, + iterable: rs, + managedPath: real, + abort: () => rs.destroy(), + }; } } @@ -304,22 +312,35 @@ async function runDownload( if (chunkSize > MAX_CHUNK_REQUEST_BYTES) chunkSize = MAX_CHUNK_REQUEST_BYTES; const src = await resolveDownload(target, ctx, prefer, chunkSize); - await sink.send({ - type: StreamStatus.Stream, - data_type: 'file_info', - file_name: src.name, - file_size: src.size, - chunk_size: chunkSize, - }); - const { totalChunks, totalBytes } = await streamChunks(sink, src.iterable, src.size, 'file_chunk', src.abort); - return okResponse({ - type: StreamStatus.Response, - data_type: 'file_complete', - file_name: src.name, - total_chunks: totalChunks, - total_bytes: totalBytes, - message: 'Download completed', - }); + const releaseStorageActivity = src.managedPath + ? registerActiveStreamItem([src.managedPath]) + : undefined; + try { + await sink.send({ + type: StreamStatus.Stream, + data_type: 'file_info', + file_name: src.name, + file_size: src.size, + chunk_size: chunkSize, + }); + const { totalChunks, totalBytes } = await streamChunks( + sink, + src.iterable, + src.size, + 'file_chunk', + src.abort, + ); + return okResponse({ + type: StreamStatus.Response, + data_type: 'file_complete', + file_name: src.name, + total_chunks: totalChunks, + total_bytes: totalBytes, + message: 'Download completed', + }); + } finally { + releaseStorageActivity?.(); + } } // ─────────────────────────── action definitions ─────────────────────────── diff --git a/packages/onebot/src/actions/stream-file.ts b/packages/onebot/src/actions/stream-file.ts index b44d76d5..36d12593 100644 --- a/packages/onebot/src/actions/stream-file.ts +++ b/packages/onebot/src/actions/stream-file.ts @@ -17,7 +17,6 @@ // (no single-request OOM or disk/fd exhaustion); chunk indices are claimed // synchronously (no double-count race); state is namespaced per account. -import os from 'os'; import path from 'path'; import fs from 'fs'; import { createHash } from 'crypto'; @@ -26,12 +25,17 @@ import { defineAction, defineStreamAction, f } from '../action-kit'; import type { ApiActionContext } from '../api-handler'; import { okResponse, type ApiResponse } from '../types'; import { StreamStatus } from '../streaming'; +import { + STREAM_DOWNLOAD_DIR, + STREAM_ROOT, + STREAM_UPLOAD_DIR, + clearInactiveStreamStorage, + registerActiveStreamItem, +} from '../stream-storage'; const log = createLogger('OneBot.Stream'); -export const STREAM_ROOT = path.join(os.tmpdir(), 'snowluma-stream'); -export const STREAM_UPLOAD_DIR = path.join(STREAM_ROOT, 'upload'); -export const STREAM_DOWNLOAD_DIR = path.join(STREAM_ROOT, 'download'); +export { STREAM_DOWNLOAD_DIR, STREAM_ROOT, STREAM_UPLOAD_DIR }; const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; // idle stream reaped after 10 min const DEFAULT_RETENTION_MS = 5 * 60 * 1000; // reassembled file auto-deleted after 5 min @@ -95,6 +99,7 @@ interface UploadState { finalPath: string; fileRetention: number; timeoutId: NodeJS.Timeout; + releaseStorageActivity: () => void; } /** Process-wide. Key is account-namespaced so two accounts (same process) can't @@ -111,11 +116,16 @@ function cleanupUpload(key: string, deleteFinal: boolean): void { const state = uploads.get(key); if (!state) return; clearTimeout(state.timeoutId); - try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch { /* best effort */ } + try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch (error) { + log.warn('failed to delete stream upload chunks %s: %s', state.tempDir, errorMessage(error)); + } if (deleteFinal) { - try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ } + try { fs.rmSync(state.finalPath, { force: true }); } catch (error) { + log.warn('failed to delete stream upload file %s: %s', state.finalPath, errorMessage(error)); + } } uploads.delete(key); + state.releaseStorageActivity(); } function safeFilename(name: string | undefined, id: string): string { @@ -142,6 +152,7 @@ function createUpload(p: UploadParams, account: string): UploadState { fs.mkdirSync(tempDir, { recursive: true }); const key = account ? `${account}:${p.stream_id}` : p.stream_id; + const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]); const state: UploadState = { id: p.stream_id, key, @@ -156,6 +167,7 @@ function createUpload(p: UploadParams, account: string): UploadState { finalPath, fileRetention: p.file_retention, timeoutId: reapTimer(key), + releaseStorageActivity, }; uploads.set(key, state); return state; @@ -200,13 +212,17 @@ async function completeUpload(state: UploadState): Promise { await new Promise((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve()))); } catch (err) { out.destroy(); - try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ } + try { fs.rmSync(state.finalPath, { force: true }); } catch (error) { + log.warn('failed to delete incomplete stream file %s: %s', state.finalPath, errorMessage(error)); + } throw err; } const sha256 = hash.digest('hex'); if (state.expectedSha256 && sha256 !== state.expectedSha256) { - try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ } + try { fs.rmSync(state.finalPath, { force: true }); } catch (error) { + log.warn('failed to delete invalid stream file %s: %s', state.finalPath, errorMessage(error)); + } throw new StreamError(`sha256 mismatch (expected ${state.expectedSha256}, got ${sha256})`); } @@ -337,7 +353,12 @@ const uploadFileStream = defineStreamAction({ function cleanDir(dir: string): number { let removed = 0; let entries: string[]; - try { entries = fs.readdirSync(dir); } catch { return 0; } // dir absent → nothing to clean + try { + entries = fs.readdirSync(dir); + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return 0; + throw error; + } for (const name of entries) { try { fs.rmSync(path.join(dir, name), { recursive: true, force: true }); removed++; } catch (err) { log.warn('failed to remove stream temp %s: %s', path.join(dir, name), err instanceof Error ? err.message : String(err)); @@ -352,14 +373,36 @@ const cleanStreamTempFile = defineAction({ returns: '{ message, removed }', params: {}, run: () => { - const removed = cleanDir(STREAM_UPLOAD_DIR) + cleanDir(STREAM_DOWNLOAD_DIR); - // Active uploads' chunk dirs may have been wiped — drop their state too. - for (const k of [...uploads.keys()]) cleanupUpload(k, false); - return okResponse({ message: 'success', removed }); + const result = clearInactiveStreamStorage(); + for (const failure of result.failures) { + log.warn('failed to remove stream temp %s: %s', failure.item, failure.message); + } + if (result.failures.length > 0) { + throw new StreamError(`failed to remove ${result.failures.length} stream temp item(s)`); + } + return okResponse({ + message: 'success', + removed: result.deletedFiles, + freed_bytes: result.freedBytes, + skipped_active: result.skippedActiveItems, + }); }, }); export const actions = [uploadFileStream, cleanStreamTempFile]; // Exposed for tests. -export const __test = { uploads, handleUpload, cleanDir, validateStreamId, STREAM_UPLOAD_DIR, MAX_CONCURRENT_STREAMS, MAX_CHUNKS }; +export const __test = { + uploads, + handleUpload, + cleanupUpload, + cleanDir, + validateStreamId, + STREAM_UPLOAD_DIR, + MAX_CONCURRENT_STREAMS, + MAX_CHUNKS, +}; + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/packages/onebot/src/stream-storage.ts b/packages/onebot/src/stream-storage.ts new file mode 100644 index 00000000..bf4ed37d --- /dev/null +++ b/packages/onebot/src/stream-storage.ts @@ -0,0 +1,238 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +export interface StreamStorageSnapshot { + totalBytes: number; + fileCount: number; + activeItemCount: number; +} + +export interface StreamStorageCleanupResult { + deletedFiles: number; + freedBytes: number; + skippedActiveItems: number; + failures: Array<{ item: string; message: string }>; +} + +export class StreamStorage { + readonly root: string; + readonly uploadDir: string; + readonly downloadDir: string; + + private readonly activeItems = new Map(); + private nextActiveItemId = 1; + + constructor(root: string) { + this.root = resolveWithExistingAncestor(root); + this.uploadDir = path.join(this.root, 'upload'); + this.downloadDir = path.join(this.root, 'download'); + } + + registerActiveItem(paths: string[]): () => void { + const normalized = paths.map((item) => { + const resolved = path.resolve(item); + if (!isStrictDescendant(this.root, resolved)) { + throw new Error(`active stream path is outside the managed root: ${item}`); + } + return resolved; + }); + const id = this.nextActiveItemId++; + this.activeItems.set(id, normalized); + let released = false; + return () => { + if (released) return; + released = true; + this.activeItems.delete(id); + }; + } + + snapshot(): StreamStorageSnapshot { + if (!this.assertRootDirectoryOrMissing()) { + return { + totalBytes: 0, + fileCount: 0, + activeItemCount: this.activeItems.size, + }; + } + + let totalBytes = 0; + let fileCount = 0; + this.walkFiles(this.root, (stat) => { + totalBytes += stat.size; + fileCount += 1; + }); + return { totalBytes, fileCount, activeItemCount: this.activeItems.size }; + } + + clearInactive(): StreamStorageCleanupResult { + const result: StreamStorageCleanupResult = { + deletedFiles: 0, + freedBytes: 0, + skippedActiveItems: this.activeItems.size, + failures: [], + }; + if (!this.assertRootDirectoryOrMissing()) return result; + + const activePaths = [...this.activeItems.values()].flat(); + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(this.root, { withFileTypes: true }); + } catch (error) { + result.failures.push({ item: '.', message: this.publicErrorMessage(error) }); + return result; + } + for (const entry of entries) { + this.clearNode(path.join(this.root, entry.name), activePaths, result); + } + return result; + } + + private assertRootDirectoryOrMissing(): boolean { + try { + const stat = fs.lstatSync(this.root); + if (!stat.isDirectory()) { + throw new Error(`managed stream root is not a directory: ${this.root}`); + } + return true; + } catch (error) { + if (isMissing(error)) return false; + throw error; + } + } + + private walkFiles(dir: string, visit: (stat: fs.Stats) => void): void { + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + const item = path.join(dir, entry.name); + const stat = fs.lstatSync(item); + if (stat.isDirectory()) this.walkFiles(item, visit); + else visit(stat); + } + } + + private clearNode( + item: string, + activePaths: string[], + result: StreamStorageCleanupResult, + ): void { + const resolved = path.resolve(item); + if (activePaths.some((active) => isSameOrDescendant(active, resolved))) return; + + let stat: fs.Stats; + try { + stat = fs.lstatSync(resolved); + } catch (error) { + if (!isMissing(error)) { + result.failures.push({ + item: this.displayPath(resolved), + message: this.publicErrorMessage(error), + }); + } + return; + } + + if (!stat.isDirectory()) { + try { + fs.unlinkSync(resolved); + result.deletedFiles += 1; + result.freedBytes += stat.size; + } catch (error) { + if (!isMissing(error)) { + result.failures.push({ + item: this.displayPath(resolved), + message: this.publicErrorMessage(error), + }); + } + } + return; + } + + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(resolved, { withFileTypes: true }); + } catch (error) { + result.failures.push({ + item: this.displayPath(resolved), + message: this.publicErrorMessage(error), + }); + return; + } + for (const entry of entries) { + this.clearNode(path.join(resolved, entry.name), activePaths, result); + } + + try { + if (fs.readdirSync(resolved).length === 0) fs.rmdirSync(resolved); + } catch (error) { + if (!isMissing(error)) { + result.failures.push({ + item: this.displayPath(resolved), + message: this.publicErrorMessage(error), + }); + } + } + } + + private displayPath(item: string): string { + const relative = path.relative(this.root, item); + return relative || '.'; + } + + private publicErrorMessage(error: unknown): string { + return errorMessage(error).split(this.root).join('[临时目录]'); + } +} + +function isStrictDescendant(root: string, candidate: string): boolean { + const relative = path.relative(root, candidate); + return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative); +} + +function isSameOrDescendant(root: string, candidate: string): boolean { + return root === candidate || isStrictDescendant(root, candidate); +} + +function isMissing(error: unknown): boolean { + return error instanceof Error && 'code' in error && error.code === 'ENOENT'; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function resolveWithExistingAncestor(input: string): string { + let existing = path.resolve(input); + const suffix: string[] = []; + while (true) { + try { + fs.lstatSync(existing); + break; + } catch (error) { + if (!isMissing(error)) throw error; + const parent = path.dirname(existing); + if (parent === existing) throw error; + suffix.unshift(path.basename(existing)); + existing = parent; + } + } + const canonical = fs.realpathSync(existing); + return path.join(canonical, ...suffix); +} + +export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'snowluma-stream')); +export const STREAM_ROOT = streamStorage.root; +export const STREAM_UPLOAD_DIR = streamStorage.uploadDir; +export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir; + +export function registerActiveStreamItem(paths: string[]): () => void { + return streamStorage.registerActiveItem(paths); +} + +export function snapshotStreamStorage(): StreamStorageSnapshot { + return streamStorage.snapshot(); +} + +export function clearInactiveStreamStorage(): StreamStorageCleanupResult { + return streamStorage.clearInactive(); +} diff --git a/packages/onebot/tests/setup.ts b/packages/onebot/tests/setup.ts new file mode 100644 index 00000000..af47777f --- /dev/null +++ b/packages/onebot/tests/setup.ts @@ -0,0 +1,26 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll } from 'vitest'; + +const originalTempEnv = { + TMPDIR: process.env.TMPDIR, + TMP: process.env.TMP, + TEMP: process.env.TEMP, +}; +const testTempDir = fs.mkdtempSync(path.join( + os.tmpdir(), + `snowluma-onebot-vitest-${process.pid}-${process.env.VITEST_POOL_ID ?? '0'}-`, +)); + +process.env.TMPDIR = testTempDir; +process.env.TMP = testTempDir; +process.env.TEMP = testTempDir; + +afterAll(() => { + for (const [name, value] of Object.entries(originalTempEnv)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + fs.rmSync(testTempDir, { recursive: true, force: true }); +}); diff --git a/packages/onebot/tests/stream-download.test.ts b/packages/onebot/tests/stream-download.test.ts index 0fff50e1..f507b20d 100644 --- a/packages/onebot/tests/stream-download.test.ts +++ b/packages/onebot/tests/stream-download.test.ts @@ -5,6 +5,8 @@ import path from 'path'; import { ApiHandler, type ApiActionContext } from '../src/api-handler'; import { __test } from '../src/actions/stream-download'; import { STREAM_DOWNLOAD_DIR, __test as fileTest } from '../src/actions/stream-file'; +import { clearInactiveStreamStorage } from '../src/stream-storage'; +import type { StreamSink } from '../src/streaming'; const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record); @@ -74,6 +76,49 @@ describe('download_file_stream (local, fenced)', () => { await h.processStreamRequest(JSON.stringify({ action: 'download_file_stream', params: { file: '/etc/passwd' } }), (j) => frames.push(j)); expect(parse(frames).at(-1)).toMatchObject({ status: 'failed', data: { type: 'error' } }); }); + + it('protects a local stream file from cleanup while it is being downloaded', async () => { + fs.mkdirSync(STREAM_DOWNLOAD_DIR, { recursive: true }); + const fp = path.join(STREAM_DOWNLOAD_DIR, 'active.bin'); + fs.writeFileSync(fp, 'active download'); + + let unblock!: () => void; + let reachedFirstFrame!: () => void; + const blocked = new Promise((resolve) => { unblock = resolve; }); + const firstFrame = new Promise((resolve) => { reachedFirstFrame = resolve; }); + let sent = false; + const sink: StreamSink = { + send: async () => { + if (sent) return; + sent = true; + reachedFirstFrame(); + await blocked; + }, + }; + + const running = __test.runDownload( + fp, + 65536, + {} as ApiActionContext, + sink, + 'auto', + ); + await firstFrame; + + try { + const duringDownload = clearInactiveStreamStorage(); + expect(duringDownload.skippedActiveItems).toBeGreaterThanOrEqual(1); + expect(duringDownload.failures).toEqual([]); + expect(fs.existsSync(fp)).toBe(true); + } finally { + unblock(); + await running; + } + const afterDownload = clearInactiveStreamStorage(); + expect(afterDownload.deletedFiles).toBeGreaterThanOrEqual(1); + expect(afterDownload.failures).toEqual([]); + expect(fs.existsSync(fp)).toBe(false); + }); }); describe('SSRF guard', () => { diff --git a/packages/onebot/tests/stream-file.test.ts b/packages/onebot/tests/stream-file.test.ts index a20d688e..ea99ab48 100644 --- a/packages/onebot/tests/stream-file.test.ts +++ b/packages/onebot/tests/stream-file.test.ts @@ -7,7 +7,7 @@ import { createHash } from 'crypto'; import { ApiHandler, type ApiActionContext } from '../src/api-handler'; import { __test, STREAM_UPLOAD_DIR } from '../src/actions/stream-file'; -const { handleUpload, cleanDir, uploads } = __test; +const { handleUpload, cleanupUpload, cleanDir, uploads } = __test; type UP = Parameters[0]; const b64 = (s: string | Buffer): string => Buffer.from(s).toString('base64'); @@ -23,8 +23,8 @@ function mk(p: Partial & { stream_id: string }): UP { } afterEach(() => { + for (const key of [...uploads.keys()]) cleanupUpload(key, true); cleanDir(STREAM_UPLOAD_DIR); - uploads.clear(); }); describe('upload_file_stream', () => { @@ -181,4 +181,27 @@ describe('clean_stream_temp_file', () => { expect(fs.existsSync(outside)).toBe(true); fs.rmSync(outside, { force: true }); }); + + it('preserves active uploads while removing inactive stream files', async () => { + const id = 'active-clean'; + await handleUpload(mk({ + stream_id: id, + total_chunks: 2, + chunk_index: 0, + chunk_data: b64('first'), + })); + const state = uploads.get(id)!; + const activeChunk = path.join(state.tempDir, '0.chunk'); + const stale = path.join(STREAM_UPLOAD_DIR, 'stale.bin'); + fs.writeFileSync(stale, 'stale'); + + const h = new ApiHandler({} as ApiActionContext); + const result = await h.handle('clean_stream_temp_file', {}); + + expect(result.status).toBe('ok'); + expect(result.data).toMatchObject({ skipped_active: 1 }); + expect(uploads.has(id)).toBe(true); + expect(fs.existsSync(activeChunk)).toBe(true); + expect(fs.existsSync(stale)).toBe(false); + }); }); diff --git a/packages/onebot/tests/stream-storage.test.ts b/packages/onebot/tests/stream-storage.test.ts new file mode 100644 index 00000000..d2983a51 --- /dev/null +++ b/packages/onebot/tests/stream-storage.test.ts @@ -0,0 +1,113 @@ +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 { StreamStorage } from '../src/stream-storage'; + +let container: string; +let root: string; +let storage: StreamStorage; + +function writeSized(filePath: string, bytes: number): void { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, Buffer.alloc(bytes)); +} + +beforeEach(() => { + container = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-stream-storage-')); + root = path.join(container, 'managed'); + storage = new StreamStorage(root); +}); + +afterEach(() => { + vi.restoreAllMocks(); + fs.rmSync(container, { recursive: true, force: true }); +}); + +describe('StreamStorage', () => { + it('summarizes only the managed stream root', () => { + writeSized(path.join(storage.uploadDir, 'upload.bin'), 10); + writeSized(path.join(storage.downloadDir, 'download.bin'), 20); + writeSized(path.join(root, '..', `${path.basename(root)}-outside.bin`), 99); + + expect(storage.snapshot()).toEqual({ + totalBytes: 30, + fileCount: 2, + activeItemCount: 0, + }); + }); + + it('clears inactive files while preserving every path of an active transfer', () => { + const activeDir = path.join(storage.uploadDir, 'active'); + const activeChunk = path.join(activeDir, '0.chunk'); + const activeFinal = path.join(storage.uploadDir, 'active__file.bin'); + const staleUpload = path.join(storage.uploadDir, 'stale.bin'); + const staleDownload = path.join(storage.downloadDir, 'stale.bin'); + writeSized(activeChunk, 3); + writeSized(activeFinal, 5); + writeSized(staleUpload, 7); + writeSized(staleDownload, 11); + const release = storage.registerActiveItem([activeDir, activeFinal]); + + expect(storage.clearInactive()).toEqual({ + deletedFiles: 2, + freedBytes: 18, + skippedActiveItems: 1, + failures: [], + }); + expect(fs.existsSync(activeChunk)).toBe(true); + expect(fs.existsSync(activeFinal)).toBe(true); + expect(fs.existsSync(staleUpload)).toBe(false); + expect(fs.existsSync(staleDownload)).toBe(false); + + release(); + expect(storage.clearInactive()).toMatchObject({ + deletedFiles: 2, + freedBytes: 8, + skippedActiveItems: 0, + failures: [], + }); + }); + + it('rejects active paths outside its managed root', () => { + expect(() => storage.registerActiveItem([path.join(root, '..', 'outside')])) + .toThrow(/outside/i); + }); + + it('does not hide canonicalization failures while establishing its root', () => { + vi.spyOn(fs, 'realpathSync').mockImplementationOnce(() => { + throw Object.assign(new Error('canonicalization denied'), { code: 'EACCES' }); + }); + + expect(() => new StreamStorage(path.join(container, 'another-managed'))) + .toThrow(/canonicalization denied/); + }); + + it('does not treat root inspection failures as a missing ancestor', () => { + const candidate = path.join(container, 'inspection-denied'); + const originalLstat = fs.lstatSync.bind(fs); + vi.spyOn(fs, 'lstatSync').mockImplementation((filePath) => { + if (String(filePath) === candidate) { + throw Object.assign(new Error('root inspection denied'), { code: 'EACCES' }); + } + return originalLstat(filePath); + }); + + expect(() => new StreamStorage(candidate)) + .toThrow(/root inspection denied/); + }); + + it('removes a symlink without following it outside the managed root', () => { + const externalDir = path.join(root, '..', `${path.basename(root)}-external`); + const externalFile = path.join(externalDir, 'keep.bin'); + writeSized(externalFile, 12); + fs.mkdirSync(storage.uploadDir, { recursive: true }); + fs.symlinkSync(externalDir, path.join(storage.uploadDir, 'linked')); + + const result = storage.clearInactive(); + + expect(result.deletedFiles).toBe(1); + expect(result.failures).toEqual([]); + expect(fs.existsSync(externalFile)).toBe(true); + }); +}); diff --git a/packages/onebot/vitest.config.ts b/packages/onebot/vitest.config.ts index 88fbd8e3..1517c294 100644 --- a/packages/onebot/vitest.config.ts +++ b/packages/onebot/vitest.config.ts @@ -14,6 +14,7 @@ export default defineConfig({ plugins: [protobufVitePlugin()], test: { include: ['tests/**/*.test.ts'], + setupFiles: ['./tests/setup.ts'], // Per-RoadMap-#5 bench files live in `bench/*.bench.ts`. Use the // vitest `--mode bench` (via `pnpm bench`) to pick them up; default // `test` runs leave them inert. diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index 02edf75a..c35aa9e3 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -3,7 +3,7 @@ import { motion } from 'motion/react'; import { Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon, Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, Server, ShieldCheck, - SlidersHorizontal, Sparkles, Star, Sun, Tag, Upload, Trash2, + SlidersHorizontal, Sparkles, Star, Sun, Tag, Upload, Trash2, HardDrive, } from 'lucide-react'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; @@ -44,6 +44,7 @@ import { settingsRoute, type SettingsTab } from '@/router'; import { NotificationsPanel } from '@/components/settings/notifications-panel'; import { GlobalConfigPanel } from '@/components/settings/global-config-panel'; import { SystemPanel } from '@/components/settings/system-panel'; +import { StoragePanel } from '@/components/settings/storage-panel'; interface TabDef { key: SettingsTab; label: string; icon: typeof Sun } @@ -64,6 +65,7 @@ const TAB_GROUPS: { title: string; tabs: TabDef[] }[] = [ title: 'SnowLuma', tabs: [ { key: 'globalConfig', label: '全局配置', icon: SlidersHorizontal }, + { key: 'storage', label: '存储管理', icon: HardDrive }, { key: 'notifications', label: '通知', icon: Bell }, ], }, @@ -107,6 +109,7 @@ export function SettingsPage() { {tab === 'advanced' && } {tab === 'account' && } {tab === 'system' && } + {tab === 'storage' && } {tab === 'notifications' && } {tab === 'globalConfig' && } {tab === 'about' && } diff --git a/packages/webui/src/components/settings/storage-panel.tsx b/packages/webui/src/components/settings/storage-panel.tsx new file mode 100644 index 00000000..a329807d --- /dev/null +++ b/packages/webui/src/components/settings/storage-panel.tsx @@ -0,0 +1,817 @@ +import { useEffect, useState } from 'react'; +import { + Activity, + AlertTriangle, + Clock3, + Database, + FileClock, + HardDrive, + Image, + Loader2, + Lock, + MessageSquare, + RefreshCw, + Save, + SmilePlus, + Trash2, + Users, + type LucideIcon, +} from 'lucide-react'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog'; +import { Badge, type BadgeProps } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Progress } from '@/components/ui/progress'; +import { ToggleSwitch } from '@/components/ui/toggle-switch'; +import { ConfirmDialog } from '@/components/confirm-dialog'; +import { useFlashMessage } from '@/hooks/use-flash-message'; +import { useApi } from '@/lib/api'; +import { + buildLogSettingsPatch, + formatBytes, + isAllAccountsConfirmation, + logStoragePresentation, + type StorageTone, +} from '@/lib/storage-presentation'; +import { cn } from '@/lib/utils'; +import { + ALL_ACCOUNTS_CONFIRMATION, + type AccountStorageCategory, + type AccountStorageSnapshot, + type LastStorageCleanup, + type LogStorageSettings, + type LogStorageSettingsField, + type StorageCleanupRequest, + type StorageOverviewResponse, +} from '@/types'; + +const CATEGORY_INFO: Record< + AccountStorageCategory, + { label: string; description: string; icon: LucideIcon; bytes: keyof AccountStorageSnapshot } +> = { + messages: { + label: '消息历史', + description: 'OneBot 消息与回复索引', + icon: MessageSquare, + bytes: 'messagesBytes', + }, + media: { + label: '媒体索引', + description: '图片、语音与视频的元数据', + icon: Image, + bytes: 'mediaBytes', + }, + reactions: { + label: '表情回应', + description: '群消息表情回应记录', + icon: SmilePlus, + bytes: 'reactionsBytes', + }, +}; + +const CATEGORIES = Object.keys(CATEGORY_INFO) as AccountStorageCategory[]; + +interface PendingCleanup { + request: Exclude; + title: string; + description: string; +} + +export function StoragePanel() { + const api = useApi(); + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [refreshing, setRefreshing] = useState(false); + const [saving, setSaving] = useState(false); + const [operation, setOperation] = useState(null); + const [maxTotalMb, setMaxTotalMb] = useState(''); + const [retainDays, setRetainDays] = useState(''); + const [perUin, setPerUin] = useState(false); + const [pendingCleanup, setPendingCleanup] = useState(null); + const [allAccountsCategory, setAllAccountsCategory] = + useState(null); + const { msg, flash, setMsg } = useFlashMessage(5000); + + const applyOverview = (overview: StorageOverviewResponse) => { + setData(overview); + setMaxTotalMb(String(overview.settings.effective.logMaxTotalMb)); + setRetainDays(String(overview.settings.effective.logRetainDays)); + setPerUin(overview.settings.effective.logPerUin); + }; + + const load = async (showSpinner = false): Promise => { + if (showSpinner) setRefreshing(true); + try { + const overview = await api.storage.get(); + applyOverview(overview); + return true; + } catch (error) { + setMsg({ + kind: 'err', + text: error instanceof Error ? error.message : '加载存储信息失败', + }); + return false; + } finally { + setLoading(false); + setRefreshing(false); + } + }; + + useEffect(() => { + void load(); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + const isLocked = (field: LogStorageSettingsField): boolean => + data?.settings.envOverrides.includes(field) ?? false; + + const saveSettings = async () => { + if (!data || saving || operation !== null) return; + const nextMaxTotalMb = Number(maxTotalMb); + const nextRetainDays = Number(retainDays); + if (!Number.isSafeInteger(nextMaxTotalMb) || nextMaxTotalMb < 1) { + flash('err', '日志总量上限必须是大于 0 的整数'); + return; + } + if (!Number.isSafeInteger(nextRetainDays) || nextRetainDays < 0) { + flash('err', '保留天数必须是大于或等于 0 的整数'); + return; + } + + const current: LogStorageSettings = { + logMaxTotalMb: nextMaxTotalMb, + logRetainDays: nextRetainDays, + logPerUin: perUin, + }; + const patch = buildLogSettingsPatch( + current, + data.settings.saved, + data.settings.envOverrides, + ); + if (Object.keys(patch).length === 0) { + flash('ok', '没有需要保存的更改'); + return; + } + + setSaving(true); + try { + const result = await api.storage.saveSettings(patch); + applyOverview({ + settings: result.settings, + snapshot: result.snapshot, + lastCleanup: data.lastCleanup, + }); + flash('ok', '日志策略已保存并立即生效'); + } catch (error) { + flash('err', error instanceof Error ? error.message : '保存失败'); + await load(); + } finally { + setSaving(false); + } + }; + + const runCleanup = async (request: StorageCleanupRequest): Promise => { + if (saving || operation !== null) return false; + const key = cleanupKey(request); + setOperation(key); + try { + const result = await api.storage.cleanup(request); + if (result.snapshot) { + setData((previous) => previous + ? { + ...previous, + snapshot: result.snapshot!, + lastCleanup: result.lastCleanup ?? previous.lastCleanup, + } + : previous); + } else { + await load(); + } + const summary = [ + `删除 ${result.cleanup.deletedFiles} 个文件`, + `释放 ${formatBytes(result.cleanup.freedBytes)}`, + ]; + if ('skippedActiveItems' in result.cleanup && result.cleanup.skippedActiveItems > 0) { + summary.push(`跳过 ${result.cleanup.skippedActiveItems} 个活动传输`); + } + if (result.cleanup.failures.length > 0) { + summary.push(`${result.cleanup.failures.length} 项失败`); + } + flash(result.success ? 'ok' : 'err', summary.join(',')); + return result.success; + } catch (error) { + flash('err', error instanceof Error ? error.message : '清理失败'); + await load(); + return false; + } finally { + setOperation(null); + } + }; + + if (loading) { + return ( +
+ + 加载存储信息… +
+ ); + } + + if (!data) { + return ( + + +

存储信息暂时不可用。

+ +
+
+ ); + } + + const { snapshot } = data; + const logPresentation = logStoragePresentation(snapshot.logs); + const onlineCount = snapshot.accounts.filter((account) => account.online).length; + const allCategoryBytes = Object.fromEntries( + CATEGORIES.map((category) => [ + category, + snapshot.accounts.reduce( + (sum, account) => sum + Number(account[CATEGORY_INFO[category].bytes]), + 0, + ), + ]), + ) as Record; + + return ( +
+ {msg && ( +
+ {msg.text} +
+ )} + + + +
+ + + 存储概览 + + + 只统计 SnowLuma 管理的日志、账号数据库和文件传输临时数据。 + +
+ +
+ +
+ + + + +
+ +
+
+
+

日志容量

+

+ {formatBytes(snapshot.logs.totalBytes)} / {formatBytes(snapshot.logs.maxTotalBytes)} +

+
+ + {logPresentation.label} + +
+ +
+ {snapshot.logs.fileCount} 个文件 + {snapshot.logs.activeFileCount} 个活动文件 + 丢弃 {snapshot.logs.droppedLines} 行磁盘日志 +
+ {snapshot.logs.lastError && ( +
+ + {snapshot.logs.lastError} +
+ )} +
+ + {data.lastCleanup && } +
+
+ + + + + + 日志策略 + + + 总量上限始终生效;保留天数设为 0 时仅按总量淘汰。保存后立即应用。 + + + +
+
+ + setMaxTotalMb(event.target.value)} + disabled={isLocked('logMaxTotalMb') || saving || operation !== null} + /> +
+
+ + setRetainDays(event.target.value)} + disabled={isLocked('logRetainDays') || saving || operation !== null} + /> +
+
+ +
+
+

+ 按账号额外写入日志 + +

+

+ 开启后,同一条带账号上下文的日志还会写入账号子目录,占用会增加。 +

+
+ +
+ +
+ +
+
+
+ + + + + + 全局数据清理 + + + 日志清理会轮转活动文件;临时数据清理会自动跳过正在进行的上传和下载。 + + + + setPendingCleanup({ + request: { scope: 'logs' }, + title: '清理全部日志?', + description: 'SnowLuma 会先轮转活动日志,再删除旧日志,只保留新建的空文件。', + })} + /> + setPendingCleanup({ + request: { scope: 'temporary' }, + title: '清理非活动临时数据?', + description: '正在上传或下载的项目会保留,其余 SnowLuma 文件传输临时数据将被删除。', + })} + /> + + + + + + + + 账号数据 + + + 仅清理选中的数据库分类。账号必须离线,配置、凭据和聊天内容导出不在此页面提供。 + + + + {snapshot.accounts.length === 0 ? ( +
+ 尚未发现账号数据库。 +
+ ) : ( + snapshot.accounts.map((account) => ( + { + const info = CATEGORY_INFO[category]; + setPendingCleanup({ + request: { scope: 'account', category, uin: account.uin }, + title: `清理 ${account.nickname || account.uin} 的${info.label}?`, + description: `将删除账号 ${account.uin} 的${info.label}数据库及其边车文件,其他分类和配置不受影响。`, + }); + }} + /> + )) + )} + + {snapshot.accounts.length > 0 && ( +
+
+
+

+ + 全部账号 +

+

+ {onlineCount > 0 + ? `${onlineCount} 个账号仍在线,全部账号清理暂不可用` + : '选择一个分类,并在弹窗中输入确认短语'} +

+
+
+
+ {CATEGORIES.map((category) => ( + + ))} +
+
+ )} +
+
+ + { + if (!open && operation === null) setPendingCleanup(null); + }} + title={pendingCleanup?.title ?? ''} + description={pendingCleanup?.description} + confirmText="确认清理" + destructive + onConfirm={async () => { + if (!pendingCleanup) return; + await runCleanup(pendingCleanup.request); + setPendingCleanup(null); + }} + /> + + { + if (!open && operation === null) setAllAccountsCategory(null); + }} + onConfirm={async (category) => { + await runCleanup({ + scope: 'allAccounts', + category, + confirmation: ALL_ACCOUNTS_CONFIRMATION, + }); + setAllAccountsCategory(null); + }} + /> +
+ ); +} + +function Metric({ label, value }: { label: string; value: string }) { + return ( +
+

{label}

+

{value}

+
+ ); +} + +function EnvironmentBadge({ locked }: { locked: boolean }) { + if (!locked) return null; + return ( + + + 环境变量锁定 + + ); +} + +function CleanupRow({ + icon: Icon, + title, + description, + busy, + disabled, + onClick, +}: { + icon: LucideIcon; + title: string; + description: string; + busy: boolean; + disabled: boolean; + onClick: () => void; +}) { + return ( +
+
+
+ +
+
+

{title}

+

{description}

+
+
+ +
+ ); +} + +function AccountStorageCard({ + account, + operation, + saving, + onRequest, +}: { + account: AccountStorageSnapshot; + operation: string | null; + saving: boolean; + onRequest: (category: AccountStorageCategory) => void; +}) { + return ( +
+
+
+

{account.nickname || `账号 ${account.uin}`}

+

{account.uin}

+
+
+ + {formatBytes(account.totalBytes)} + + + {account.online ? '在线' : '离线'} + +
+
+
+ {CATEGORIES.map((category) => { + const info = CATEGORY_INFO[category]; + const Icon = info.icon; + const bytes = Number(account[info.bytes]); + const key = `account:${account.uin}:${category}`; + return ( +
+
+ +
+

{info.label}

+

+ {info.description} +

+
+
+
+ + {formatBytes(bytes)} + + +
+
+ ); + })} +
+
+ ); +} + +function LastCleanupSummary({ cleanup }: { cleanup: LastStorageCleanup }) { + const label = cleanup.category + ? CATEGORY_INFO[cleanup.category].label + : cleanup.scope === 'logs' + ? '日志' + : '传输临时数据'; + return ( +
+ +
+

+ 最近清理:{label},删除 {cleanup.deletedFiles} 个文件,释放 {formatBytes(cleanup.freedBytes)} + {cleanup.failureCount > 0 ? `,${cleanup.failureCount} 项失败` : ''} + {' · '} + {formatTimestamp(cleanup.at)} +

+ {cleanup.failures.length > 0 && ( +
    + {cleanup.failures.slice(0, 3).map((failure, index) => ( +
  • + {failure.item}:{failure.message} +
  • + ))} + {cleanup.failures.length > 3 && ( +
  • 另有 {cleanup.failures.length - 3} 项失败,请检查服务器日志
  • + )} +
+ )} +
+
+ ); +} + +function AllAccountsCleanupDialog({ + category, + busy, + onOpenChange, + onConfirm, +}: { + category: AccountStorageCategory | null; + busy: boolean; + onOpenChange: (open: boolean) => void; + onConfirm: (category: AccountStorageCategory) => Promise; +}) { + const [confirmation, setConfirmation] = useState(''); + const open = category !== null; + const close = () => { + setConfirmation(''); + onOpenChange(false); + }; + return ( + { + if (!nextOpen && !busy) close(); + }} + > + + + + 清理全部账号的{category ? CATEGORY_INFO[category].label : '数据'}? + + + 该操作会删除所有离线账号的对应数据库及边车文件,无法撤销。请输入 + {ALL_ACCOUNTS_CONFIRMATION} + 继续。 + + +
+ + setConfirmation(event.target.value)} + placeholder={ALL_ACCOUNTS_CONFIRMATION} + autoComplete="off" + disabled={busy} + /> +
+ + setConfirmation('')}> + 取消 + + { + event.preventDefault(); + if (!category || !isAllAccountsConfirmation(confirmation)) return; + void onConfirm(category); + }} + className="bg-destructive text-destructive-foreground hover:bg-destructive/90" + > + {busy ? : } + 确认清理 + + +
+
+ ); +} + +function cleanupKey(request: StorageCleanupRequest): string { + if (request.scope === 'account') return `account:${request.uin}:${request.category}`; + if (request.scope === 'allAccounts') return `allAccounts:${request.category}`; + return request.scope; +} + +function toneBadgeVariant(tone: StorageTone): BadgeProps['variant'] { + if (tone === 'success') return 'success'; + if (tone === 'warning') return 'warning'; + if (tone === 'danger') return 'destructive'; + return 'secondary'; +} + +function toneProgressClass(tone: StorageTone): string { + if (tone === 'danger') return 'bg-destructive'; + if (tone === 'warning') return 'bg-warning'; + if (tone === 'neutral') return 'bg-muted-foreground'; + return 'bg-success'; +} + +function formatTimestamp(value: string): string { + const date = new Date(value); + return Number.isNaN(date.getTime()) ? value : date.toLocaleString(); +} diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 6d483132..98f1aeda 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -1,4 +1,4 @@ -import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, GlobalSettings, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types'; +import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, GlobalSettings, HookProcessInfo, LogEntry, LogLevel, LogStorageSettingsPatch, NotificationDeliveryRecord, NotificationsConfig, QQInfo, StorageCleanupRequest, StorageCleanupResponse, StorageOverviewResponse, StorageSettingsUpdateResponse, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types'; import type { PasswordRule } from '@/components/pages/change-password-page'; import { normalizeOneBotConfig } from '@/lib/onebot-config'; import { @@ -58,6 +58,7 @@ class HttpApiClient implements ApiClient { readonly notifications: ApiClient['notifications']; readonly globalConfig: ApiClient['globalConfig']; readonly systemSettings: ApiClient['systemSettings']; + readonly storage: ApiClient['storage']; readonly debug: ApiClient['debug']; readonly agreements: ApiClient['agreements']; @@ -167,6 +168,30 @@ class HttpApiClient implements ApiClient { this.postJson('/api/system/backup/import', { backup, restoreCredentials }), }; + this.storage = { + get: () => this.getJson('/api/system/storage'), + saveSettings: (patch: LogStorageSettingsPatch) => + this.postJson('/api/system/storage/settings', patch), + cleanup: async (request: StorageCleanupRequest) => { + const response = await this.request('/api/system/storage/cleanup', { + method: 'POST', + body: JSON.stringify(request), + }); + const payload = await readJson(response); + // A cleanup can partially succeed and return HTTP 500 with the exact + // deleted/failed items. Preserve that result so the operator sees the + // real outcome instead of a generic exception. + if (!response.ok && !payload.cleanup) { + throw new ApiError( + response.status, + extractErrorMessage(payload, response.statusText || '清理失败'), + payload.code, + ); + } + return payload; + }, + }; + this.debug = { actions: () => this.getJson<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>('/api/debug/actions'), invoke: (uin: string, action: string, params: Record) => diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 0bff6327..2ee25755 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -16,6 +16,11 @@ import type { OneBotConfig, QQInfo, SystemInfo, + LogStorageSettingsPatch, + StorageCleanupRequest, + StorageCleanupResponse, + StorageOverviewResponse, + StorageSettingsUpdateResponse, SystemSettings, SystemSettingsPatch, SystemSettingsResponse, @@ -168,6 +173,13 @@ export interface ApiClient { importBackup(backup: BackupBundle, restoreCredentials: boolean): Promise; }; + // ---- managed storage (logs / stream temp / per-account databases) ---- + storage: { + get(): Promise; + saveSettings(patch: LogStorageSettingsPatch): Promise; + cleanup(request: StorageCleanupRequest): Promise; + }; + // ---- debug tools (action tester + live event/action stream) ---- debug: { actions(): Promise<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>; diff --git a/packages/webui/src/lib/storage-presentation.ts b/packages/webui/src/lib/storage-presentation.ts new file mode 100644 index 00000000..e909cb47 --- /dev/null +++ b/packages/webui/src/lib/storage-presentation.ts @@ -0,0 +1,75 @@ +import { + ALL_ACCOUNTS_CONFIRMATION, + type LogStorageSettings, + type LogStorageSettingsField, + type LogStorageSettingsPatch, + type LogStorageState, +} from '@/types'; + +export type StorageTone = 'neutral' | 'success' | 'warning' | 'danger'; + +export interface LogStoragePresentation { + label: string; + tone: StorageTone; + percent: number; +} + +export function formatBytes(bytes: number): string { + const safeBytes = Number.isFinite(bytes) ? Math.max(0, bytes) : 0; + if (safeBytes < 1024) return `${Math.round(safeBytes)} B`; + const units = ['KB', 'MB', 'GB', 'TB', 'PB']; + let value = safeBytes / 1024; + let unitIndex = 0; + while (value >= 1024 && unitIndex < units.length - 1) { + value /= 1024; + unitIndex += 1; + } + const rounded = value < 10 && !Number.isInteger(value) + ? Number(value.toFixed(1)) + : Math.round(value); + return `${rounded} ${units[unitIndex]}`; +} + +export function buildLogSettingsPatch( + current: LogStorageSettings, + saved: LogStorageSettings, + lockedFields: LogStorageSettingsField[], +): LogStorageSettingsPatch { + const locked = new Set(lockedFields); + const patch: LogStorageSettingsPatch = {}; + if (!locked.has('logMaxTotalMb') && current.logMaxTotalMb !== saved.logMaxTotalMb) { + patch.logMaxTotalMb = current.logMaxTotalMb; + } + if (!locked.has('logRetainDays') && current.logRetainDays !== saved.logRetainDays) { + patch.logRetainDays = current.logRetainDays; + } + if (!locked.has('logPerUin') && current.logPerUin !== saved.logPerUin) { + patch.logPerUin = current.logPerUin; + } + return patch; +} + +export function logStoragePresentation(input: { + state: LogStorageState; + totalBytes: number; + maxTotalBytes: number; +}): LogStoragePresentation { + const percent = input.maxTotalBytes > 0 + ? Math.max(0, Math.min(100, (input.totalBytes / input.maxTotalBytes) * 100)) + : 0; + if (input.state === 'degraded') { + return { label: '磁盘写入已暂停', tone: 'danger', percent }; + } + if (input.state === 'warning') { + return { label: '清理异常', tone: 'warning', percent }; + } + if (input.state === 'disabled') { + return { label: '文件日志已关闭', tone: 'neutral', percent }; + } + if (percent >= 80) return { label: '接近上限', tone: 'warning', percent }; + return { label: '正常', tone: 'success', percent }; +} + +export function isAllAccountsConfirmation(value: string): boolean { + return value === ALL_ACCOUNTS_CONFIRMATION; +} diff --git a/packages/webui/src/router/index.tsx b/packages/webui/src/router/index.tsx index 3742e9d4..f7ee26e6 100644 --- a/packages/webui/src/router/index.tsx +++ b/packages/webui/src/router/index.tsx @@ -74,7 +74,7 @@ const debugRoute = createRoute({ }); /** Settings sub-tabs — also the contract for the `?tab=` deep link. */ -export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'globalConfig', 'about'] as const; +export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'storage', 'notifications', 'globalConfig', 'about'] as const; export type SettingsTab = (typeof SETTINGS_TABS)[number]; export const settingsRoute = createRoute({ diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 37a64974..7d8c60f3 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -173,6 +173,138 @@ export interface SystemSettingsResponse { restartRequiredToApply: boolean; } +// Storage management under Settings → SnowLuma → 存储管理. +export type LogStorageState = 'disabled' | 'healthy' | 'warning' | 'degraded'; +export interface LogStorageStatus { + state: LogStorageState; + totalBytes: number; + maxTotalBytes: number; + retainDays: number; + perUinEnabled: boolean; + fileCount: number; + activeFileCount: number; + droppedLines: number; + lastError?: string; +} + +export interface LogStorageSettings { + logMaxTotalMb: number; + logRetainDays: number; + logPerUin: boolean; +} +export type LogStorageSettingsField = keyof LogStorageSettings; +export type LogStorageSettingsPatch = Partial; +export interface LogStorageSettingsState { + saved: LogStorageSettings; + effective: LogStorageSettings; + envOverrides: LogStorageSettingsField[]; +} + +export interface TemporaryStorageSnapshot { + totalBytes: number; + fileCount: number; + activeItemCount: number; +} + +export interface AccountStorageSnapshot { + uin: string; + nickname?: string; + online: boolean; + messagesBytes: number; + mediaBytes: number; + reactionsBytes: number; + totalBytes: number; +} + +export interface StorageSnapshot { + logs: LogStorageStatus; + temporary: TemporaryStorageSnapshot; + accounts: AccountStorageSnapshot[]; + totals: { + logsBytes: number; + temporaryBytes: number; + accountDataBytes: number; + managedBytes: number; + }; +} + +export type AccountStorageCategory = 'messages' | 'media' | 'reactions'; +export type StorageCleanupScope = 'logs' | 'temporary' | 'account' | 'allAccounts'; +export interface LastStorageCleanup { + at: string; + scope: StorageCleanupScope; + accountScope: 'global' | 'single' | 'all'; + category?: AccountStorageCategory; + uin?: string; + deletedFiles: number; + freedBytes: number; + failureCount: number; + skippedActiveItems?: number; + failures: StorageCleanupFailure[]; +} + +export interface StorageOverviewResponse { + settings: LogStorageSettingsState; + snapshot: StorageSnapshot; + lastCleanup: LastStorageCleanup | null; +} + +export interface StorageSettingsUpdateResponse { + success: true; + settings: LogStorageSettingsState; + status: LogStorageStatus; + snapshot: StorageSnapshot; +} + +export const ALL_ACCOUNTS_CONFIRMATION = '清理全部账号' as const; + +export type StorageCleanupRequest = + | { scope: 'logs' } + | { scope: 'temporary' } + | { scope: 'account'; category: AccountStorageCategory; uin: string } + | { + scope: 'allAccounts'; + category: AccountStorageCategory; + confirmation: typeof ALL_ACCOUNTS_CONFIRMATION; + }; + +export interface StorageCleanupFailure { + item?: string; + file?: string; + uin?: string; + message: string; +} + +export type StorageCleanupResult = + | { + deletedFiles: number; + freedBytes: number; + failures: StorageCleanupFailure[]; + status: LogStorageStatus; + } + | { + deletedFiles: number; + freedBytes: number; + skippedActiveItems: number; + failures: StorageCleanupFailure[]; + } + | { + category: AccountStorageCategory; + uins: string[]; + deletedFiles: number; + freedBytes: number; + failures: StorageCleanupFailure[]; + }; + +export interface StorageCleanupResponse { + success: boolean; + message?: string; + scope: StorageCleanupScope; + cleanup: StorageCleanupResult; + snapshot?: StorageSnapshot; + lastCleanup?: LastStorageCleanup; +} + // Debug tools (Wave A3; roles + streaming added in the console expansion). /** Semantic role of a param, mirrored from the backend's `FieldRole`. Drives diff --git a/packages/webui/tests/storage-api.test.ts b/packages/webui/tests/storage-api.test.ts new file mode 100644 index 00000000..6c7ea329 --- /dev/null +++ b/packages/webui/tests/storage-api.test.ts @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createApiClient } from '../src/lib/api/client'; + +const tokenStore = { + load: () => 'test-token', + save: () => undefined, +}; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('storage API client', () => { + it('reads the authenticated storage overview', async () => { + const payload = { + settings: { + saved: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false }, + effective: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false }, + envOverrides: [], + }, + snapshot: { + logs: { + state: 'healthy', + totalBytes: 0, + maxTotalBytes: 1024 * 1024 * 1024, + retainDays: 7, + perUinEnabled: false, + fileCount: 1, + activeFileCount: 1, + droppedLines: 0, + }, + temporary: { totalBytes: 0, fileCount: 0, activeItemCount: 0 }, + accounts: [], + totals: { logsBytes: 0, temporaryBytes: 0, accountDataBytes: 0, managedBytes: 0 }, + }, + lastCleanup: null, + }; + const fetchMock = vi.fn(async () => new Response(JSON.stringify(payload), { + status: 200, + headers: { 'content-type': 'application/json' }, + })); + vi.stubGlobal('fetch', fetchMock); + + const client = createApiClient({ tokenStore }); + await expect(client.storage.get()).resolves.toEqual(payload); + expect(fetchMock).toHaveBeenCalledWith('/api/system/storage', { + headers: { Authorization: 'Bearer test-token' }, + }); + }); + + it('posts a partial log-settings patch', async () => { + const fetchMock = vi.fn(async () => new Response(JSON.stringify({ + success: true, + settings: { + saved: { logMaxTotalMb: 1024, logRetainDays: 0, logPerUin: false }, + effective: { logMaxTotalMb: 1024, logRetainDays: 0, logPerUin: false }, + envOverrides: [], + }, + status: { state: 'healthy' }, + snapshot: {}, + }), { status: 200, headers: { 'content-type': 'application/json' } })); + vi.stubGlobal('fetch', fetchMock); + + const client = createApiClient({ tokenStore }); + await client.storage.saveSettings({ logRetainDays: 0 }); + + expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', { + method: 'POST', + body: JSON.stringify({ logRetainDays: 0 }), + headers: { + Authorization: 'Bearer test-token', + 'Content-Type': 'application/json', + }, + }); + }); + + it('returns a structured partial cleanup result from an HTTP 500 response', async () => { + const payload = { + success: false, + message: '部分文件清理失败,请检查失败明细', + scope: 'temporary', + cleanup: { + deletedFiles: 1, + freedBytes: 5, + skippedActiveItems: 0, + failures: [{ item: 'locked.bin', message: 'permission denied' }], + }, + snapshot: {}, + 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' }], + }, + }; + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(payload), { + status: 500, + headers: { 'content-type': 'application/json' }, + }))); + + const client = createApiClient({ tokenStore }); + await expect(client.storage.cleanup({ scope: 'temporary' })).resolves.toEqual(payload); + }); +}); diff --git a/packages/webui/tests/storage-presentation.test.ts b/packages/webui/tests/storage-presentation.test.ts new file mode 100644 index 00000000..b37658f3 --- /dev/null +++ b/packages/webui/tests/storage-presentation.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; +import { + buildLogSettingsPatch, + formatBytes, + isAllAccountsConfirmation, + logStoragePresentation, +} from '../src/lib/storage-presentation'; + +describe('storage presentation helpers', () => { + it('omits environment-locked and unchanged fields from a settings patch', () => { + expect(buildLogSettingsPatch( + { logMaxTotalMb: 2048, logRetainDays: 0, logPerUin: true }, + { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false }, + ['logMaxTotalMb'], + )).toEqual({ + logRetainDays: 0, + logPerUin: true, + }); + }); + + it('prioritizes degraded state over capacity percentage and warns at 80 percent', () => { + expect(logStoragePresentation({ + state: 'degraded', + totalBytes: 10, + maxTotalBytes: 100, + })).toMatchObject({ label: '磁盘写入已暂停', tone: 'danger', percent: 10 }); + expect(logStoragePresentation({ + state: 'healthy', + totalBytes: 80, + maxTotalBytes: 100, + })).toMatchObject({ label: '接近上限', tone: 'warning', percent: 80 }); + expect(logStoragePresentation({ + state: 'healthy', + totalBytes: 20, + maxTotalBytes: 100, + })).toMatchObject({ label: '正常', tone: 'success', percent: 20 }); + }); + + it('formats byte counts without exposing implementation units', () => { + expect(formatBytes(0)).toBe('0 B'); + expect(formatBytes(1536)).toBe('1.5 KB'); + expect(formatBytes(1024 * 1024)).toBe('1 MB'); + }); + + it('requires the exact all-account confirmation phrase', () => { + expect(isAllAccountsConfirmation('清理全部账号')).toBe(true); + expect(isAllAccountsConfirmation(' 清理全部账号 ')).toBe(false); + expect(isAllAccountsConfirmation('确认')).toBe(false); + }); +}); From c64f9d30786ea8401a379fb10a616709d97a47f9 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 24 Jul 2026 14:15:51 +0800 Subject: [PATCH 6/6] chore(release): v1.12.9 --- package.json | 2 +- packages/bridge/package.json | 2 +- packages/common/package.json | 2 +- packages/core/package.json | 2 +- packages/mcp/package.json | 2 +- packages/onebot/package.json | 2 +- packages/proto-defs/package.json | 2 +- packages/protocol/package.json | 2 +- packages/proton/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index 476fc25f..8f49c173 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.12.8", + "version": "1.12.9", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 2da51269..44f3dbec 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.12.8", + "version": "1.12.9", "private": true, "type": "module", "description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).", diff --git a/packages/common/package.json b/packages/common/package.json index 2c6a37bb..64c444c5 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.12.8", + "version": "1.12.9", "private": true, "type": "module", "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", diff --git a/packages/core/package.json b/packages/core/package.json index 57e65bfe..18369d15 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.12.8", + "version": "1.12.9", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 15b14994..0580952e 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.12.8", + "version": "1.12.9", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/onebot/package.json b/packages/onebot/package.json index c7f51cd7..4f0b2054 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.12.8", + "version": "1.12.9", "private": true, "type": "module", "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 91160446..6cc05561 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.12.8", + "version": "1.12.9", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", diff --git a/packages/protocol/package.json b/packages/protocol/package.json index abc09cd4..dab8c4d0 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.12.8", + "version": "1.12.9", "private": true, "type": "module", "description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/protocol/'`.", diff --git a/packages/proton/package.json b/packages/proton/package.json index 02e91c11..d051c471 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.12.8", + "version": "1.12.9", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 869ab384..3ee7ba57 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.12.8", + "version": "1.12.9", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 30f1b6ea..a35e47a1 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.12.8", + "version": "1.12.9", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index ef01a5eb..afb7142b 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.12.8", + "version": "1.12.9", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index ccef9a6e..c5b94229 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.12.8", + "version": "1.12.9", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index b508d9bd..126761e4 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.12.8", + "version": "1.12.9", "type": "module", "scripts": { "dev": "vite",