fix(core): handle group file storage limits

Retry eligible storage failures as temporary files and preserve their storage type for later use. Reject incompatible mixed content before chat publication.

Refs #644
This commit is contained in:
DrSmoothl committed 2026-11-07 15:14:55 +08:00
1 parent 84f4cde85e
commit 8bea681aa2
16 files changed
+750 -104

No files matched your search

@@ -73,6 +73,64 @@ function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
}
describe('actions/forward — file segment inside forward node', () => {
it('rejects cached temporary files mixed with text before building a forward payload', async () => {
buildSendElemsMock.mockClear();
const bridge = mockBridge({
recallUploadedFile: vi.fn(() => ({ scope: 'group', groupId: 12345, busId: 104 })),
});
await expect(
new ForwardApi(bridge as any).upload(
[
{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'text', text: 'caption' },
{ type: 'file', fileId: 'temp' },
],
},
],
12345,
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('disallows temporary fallback when a forward node mixes a new file with text', async () => {
buildSendElemsMock.mockClear();
const bridge = mockBridge();
bridge.apis.groupFile.upload.mockRejectedValueOnce(
new Error('temporary group files require only file or image segments'),
);
await expect(
new ForwardApi(bridge as any).upload(
[
{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'text', text: 'caption' },
{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' },
],
},
],
12345,
),
).rejects.toThrow(/temporary group files/);
expect(bridge.apis.groupFile.upload).toHaveBeenCalledWith(
12345,
'base64://AQID',
'note.txt',
'/',
true,
false,
{ allowTemporary: false },
);
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('rejects a recursive window shake before identity resolution or upload', async () => {
buildSendElemsMock.mockClear();
const resolveUserUid = vi.fn();
@@ -288,7 +346,9 @@ describe('actions/forward — file segment inside forward node', () => {
12345,
);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false, {
allowTemporary: true,
});
expect(publish).not.toHaveBeenCalled();
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([
@@ -513,6 +573,7 @@ describe('actions/forward — file segment inside forward node', () => {
'/',
true,
false,
{ allowTemporary: true },
);
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([
+182 -3
View File
@@ -1,10 +1,12 @@
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import type {
OidbGroupFileCountViewResp,
OidbGroupFileReq,
OidbGroupFileResp,
OidbGroupFileUploadResp,
OidbGroupFileViewResp,
OidbGroupFileFolderResp,
OidbGroupSendFileReq,
@@ -70,6 +72,10 @@ function packResponse(body: Uint8Array) {
};
}
function uploadResponse(upload: OidbGroupFileUploadResp) {
return packResponse(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { upload } }));
}
let STAGED_FILE: string;
describe('apis/group-file', () => {
@@ -138,7 +144,7 @@ describe('apis/group-file', () => {
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
const out = await api.upload(12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-xyz' });
expect(out).toEqual({ fileId: 'fid-xyz', busId: 102 });
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
@@ -224,8 +230,180 @@ describe('apis/group-file', () => {
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/code=999/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it.each([-403, -9801, -98090])(
'retries capacity error %s as a temporary group file',
async (retCode) => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(
uploadResponse({ retCode, retMsg: 'permanent storage full' }),
)
.mockResolvedValueOnce(
uploadResponse({ fileId: 'temporary-file', busId: 104, boolFileExist: true }),
);
const api = new GroupFileApi(bridge as any);
const result = await api.upload(12345, '/path/file.bin', 'doc.bin', '/folder');
expect(result).toMatchObject({ fileId: 'temporary-file', busId: 104 });
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
const requests = bridge.sendRawPacket.mock.calls
.slice(0, 2)
.map(([, bytes]) => protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes).body?.file);
expect(requests[0]).toMatchObject({ busId: 102, targetDirectory: '/folder' });
expect(requests[1]).toEqual({ ...requests[0], busId: 104 });
const publish = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(
bridge.sendRawPacket.mock.calls[2]![1],
);
expect(publish.body?.body?.info).toMatchObject({
fileId: 'temporary-file',
busiType: 104,
});
expect(bridge.rememberUploadedFile).toHaveBeenCalledWith(
expect.objectContaining({ busId: 104, groupId: 12345 }),
);
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
},
);
it('carries the server-selected storage type through bytes, publication and cached reuse', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
uploadResponse({
fileId: 'temporary-file',
busId: 104,
uploadIp: '127.0.0.1',
uploadPort: 8080,
fileKey: new Uint8Array([7]),
checkKey: new Uint8Array([8]),
}),
);
bridge.recallUploadedFile.mockImplementation(
() => bridge.rememberUploadedFile.mock.calls.at(-1)?.[0],
);
const api = new GroupFileApi(bridge as any);
await api.upload(12345, '/path/file.bin');
const ext = protobuf_decode<FileUploadExt>(
vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![5],
);
expect(ext.entry?.busiBuff?.busId).toBe(104);
await api.publish(12345, 'temporary-file');
for (const [, bytes] of bridge.sendRawPacket.mock.calls.slice(1)) {
expect(
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes).body?.body?.info?.busiType,
).toBe(104);
}
});
it('stops after a failed temporary attempt and releases the staged file', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
.mockResolvedValueOnce(
uploadResponse({ retCode: -9801, retMsg: 'temporary storage rejected' }),
);
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/code=-9801/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value;
expect(staged.cleanup).toHaveBeenCalledOnce();
});
it('retains temporary mode when the successful retry omits its storage type', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
.mockResolvedValueOnce(uploadResponse({ fileId: 'temp', boolFileExist: true }));
const api = new GroupFileApi(bridge as any);
const publish = vi.spyOn(api, 'publish').mockResolvedValue();
await expect(api.upload(12345, '/path/file.bin')).resolves.toEqual({
fileId: 'temp',
busId: 104,
});
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
});
it('rejects an unknown server storage type before bytes or publication', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
uploadResponse({ fileId: 'bad', busId: 777, boolFileExist: true }),
);
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/unsupported storage type: 777/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it.each([
{ scope: 'group', groupId: 12345, expected: 104 },
{ scope: 'group', groupId: 54321, expected: 102 },
{ scope: 'private', groupId: undefined, expected: 102 },
] as const)(
'scopes cached storage to the target group for download and reuse (%j)',
async ({ scope, groupId, expected }) => {
const bridge = mockBridge();
bridge.recallUploadedFile.mockReturnValue({
fileId: 'temp',
scope,
groupId,
busId: 104,
});
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
download: {
downloadDns: 'download.example.com',
downloadUrl: new Uint8Array([1]),
},
},
}),
),
);
const api = new GroupFileApi(bridge as any);
await api.getUrl(12345, 'temp');
await api.publish(12345, 'temp');
const requests = bridge.sendRawPacket.mock.calls;
expect(
protobuf_decode<OidbBase<OidbGroupFileReq>>(requests[0]![1]).body?.download?.busId,
).toBe(expected);
expect(
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(requests[1]![1]).body?.body?.info
?.busiType,
).toBe(expected);
},
);
it.each([{ retCode: -403 }, { fileId: 'temp', busId: 104, boolFileExist: true }])(
'rejects a disallowed temporary upload before transferring bytes or publishing (%j)',
async (response) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(uploadResponse(response));
await expect(
new GroupFileApi(bridge as any).upload(
12345,
'/path/file.bin',
'',
'/',
true,
false,
{ allowTemporary: false },
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
},
);
it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
// Reproduces the bug report: OIDB upload + highway PUT alone only
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
@@ -341,11 +519,12 @@ describe('apis/group-file', () => {
const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt');
if (confirmed) {
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm' });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm');
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm', busId: 102 });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm', 102);
} else {
await expect(upload).rejects.toBe(failure);
expect(publishSpy).not.toHaveBeenCalled();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
}
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
+22 -1
View File
@@ -30,7 +30,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
}));
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import type { GroupFileExtra, MsgInfo } from '@snowluma/proto-defs/element';
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
@@ -374,6 +374,27 @@ describe('element-builder / all-message validation preflight', () => {
});
describe('element-builder / file element is no longer carried in elems[]', () => {
it.each([12345, 54321])(
'preserves temporary storage only in a matching group forward (%s)',
async (cachedGroupId) => {
const bridge = {
recallUploadedFile: vi.fn(() => ({
scope: 'group',
groupId: cachedGroupId,
busId: 104,
fileName: 'doc.pdf',
fileSize: 3,
})),
} as any;
const [elem] = await buildSendElems([{ type: 'file', fileId: 'temp' }], {
bridge,
groupId: 12345,
forwardFake: true,
});
const extra = protobuf_decode<GroupFileExtra>(elem!.transElem!.elemValue!.subarray(3));
expect(extra.inner?.info?.busId).toBe(cachedGroupId === 12345 ? 104 : 102);
},
);
// Regression for the `result=79` class: previously the element-builder
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire