feat: add async SQLite on Node 24 and improve messaging diagnostics (#520)
Move database work off the main thread on Node.js 24 and improve message handling and runtime diagnostics. Preserve migration, restart, and concurrency coverage with the async SQLite driver.
This commit is contained in:
1 parent
20f48d11ec
commit
c7428363cb
170 files changed
+7748
-3913
No files matched your search
@@ -76,4 +76,26 @@ describe('action-docs', () => {
|
||||
expect(md).toContain('`set_group_ban`');
|
||||
expect(md).toContain('| 参数 | 类型 | 必填 | 默认 | 说明 |');
|
||||
});
|
||||
|
||||
it('documents custom reply content on every forward entry point', () => {
|
||||
for (const name of [
|
||||
'upload_forward_msg',
|
||||
'upload_foward_msg',
|
||||
'send_forward_msg',
|
||||
'send_group_forward_msg',
|
||||
'send_private_forward_msg',
|
||||
]) {
|
||||
const action = docs.find((doc) => doc.name === name)!;
|
||||
|
||||
for (const field of ['messages', 'message']) {
|
||||
expect(action.params.find((param) => param.name === field)?.desc).toContain(
|
||||
'reply.data.message',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
expect(docs.find((doc) => doc.name === 'get_forward_msg')?.returns).toContain(
|
||||
'qq/time/seq',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ function requireAction(name: string) {
|
||||
}
|
||||
|
||||
function asCtx(partial: Partial<ApiActionContext>): ApiActionContext {
|
||||
return partial as ApiActionContext;
|
||||
return { refreshMessageMedia: vi.fn(async () => {}), ...partial } as ApiActionContext;
|
||||
}
|
||||
|
||||
const sendMsg = requireAction('send_msg');
|
||||
@@ -88,10 +88,7 @@ describe('send_custom_face', () => {
|
||||
const { ctx, resolveCustomFace, sendPrivateMessage } = context();
|
||||
expect(
|
||||
await action.toHandler(ctx)({ emoji_id: 'a'.repeat(32), user_id: 456 }),
|
||||
).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { message_id: 8 },
|
||||
});
|
||||
).toMatchObject({ status: 'ok', data: { message_id: 8 } });
|
||||
expect(sendPrivateMessage).toHaveBeenCalledWith(456, [image], false);
|
||||
resolveCustomFace.mockRejectedValueOnce(new Error('sticker missing'));
|
||||
await expect(action.toHandler(ctx)({ emoji_id: 'missing', user_id: 456 })).rejects.toThrow(
|
||||
@@ -106,9 +103,7 @@ describe('send_custom_face', () => {
|
||||
const { ctx, resolveCustomFace } = context();
|
||||
expect(
|
||||
await action.toHandler(ctx)({ emoji_id: 'saved-sticker', ...target }),
|
||||
).toMatchObject({
|
||||
retcode: 1400,
|
||||
});
|
||||
).toMatchObject({ retcode: 1400 });
|
||||
expect(resolveCustomFace).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
@@ -514,155 +509,6 @@ describe('get_msg', () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('refreshes image URLs from file, then file_id, and skips unusable segments', async () => {
|
||||
const fileImage: JsonObject = {
|
||||
file: 'ABC.jpg',
|
||||
file_id: 'SHOULD_NOT_WIN.jpg',
|
||||
url: 'https://old.example/ABC.jpg',
|
||||
};
|
||||
const fileIdImage: JsonObject = {
|
||||
file_id: 'BY_FILE_ID.jpg',
|
||||
url: 'https://old.example/file-id.jpg',
|
||||
};
|
||||
const emptyFileImage: JsonObject = {
|
||||
file: '',
|
||||
file_id: 'SHOULD_NOT_USE.jpg',
|
||||
url: 'https://old.example/empty-file.jpg',
|
||||
};
|
||||
const keepEmptyUrl: JsonObject = {
|
||||
file: 'KEEP_EMPTY.jpg',
|
||||
url: 'https://old.example/keep-empty.jpg',
|
||||
};
|
||||
const keepNull: JsonObject = {
|
||||
file: 'KEEP_NULL.jpg',
|
||||
url: 'https://old.example/keep-null.jpg',
|
||||
};
|
||||
const keepNonString: JsonObject = {
|
||||
file: 'KEEP_NONSTRING.jpg',
|
||||
url: 'https://old.example/keep-nonstring.jpg',
|
||||
};
|
||||
const noHandle: JsonObject = {
|
||||
url: 'https://old.example/no-file.jpg',
|
||||
};
|
||||
const stored: JsonObject = {
|
||||
message_id: 777001,
|
||||
message: [
|
||||
null,
|
||||
'skip-me',
|
||||
12,
|
||||
{ type: 'text', data: { text: 'plain' } },
|
||||
{ type: 'image', data: 'not-object' },
|
||||
{ type: 'image' },
|
||||
{ type: 'image', data: emptyFileImage },
|
||||
{ type: 'image', data: noHandle },
|
||||
{ type: 'image', data: fileIdImage },
|
||||
{ type: 'image', data: keepEmptyUrl },
|
||||
{ type: 'image', data: keepNull },
|
||||
{ type: 'image', data: keepNonString },
|
||||
{ type: 'image', data: fileImage },
|
||||
],
|
||||
};
|
||||
const getImageInfo = vi.fn(async (file: string) => {
|
||||
if (file === 'ABC.jpg') {
|
||||
return { url: 'https://new.example/ABC.jpg?rkey=FRESH' };
|
||||
}
|
||||
|
||||
if (file === 'BY_FILE_ID.jpg') {
|
||||
return { url: 'https://new.example/file-id.jpg?rkey=FRESH' };
|
||||
}
|
||||
|
||||
if (file === 'KEEP_EMPTY.jpg') {
|
||||
return { url: '' };
|
||||
}
|
||||
|
||||
if (file === 'KEEP_NULL.jpg') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (file === 'KEEP_NONSTRING.jpg') {
|
||||
return { url: 1 };
|
||||
}
|
||||
|
||||
return { url: 'https://should-not-apply.example/' };
|
||||
});
|
||||
|
||||
const response = await getMsg.toHandler(
|
||||
asCtx({
|
||||
getMessage: () => stored,
|
||||
getImageInfo,
|
||||
}),
|
||||
)({ message_id: 777001 });
|
||||
|
||||
expect(getImageInfo.mock.calls).toEqual([
|
||||
['BY_FILE_ID.jpg'],
|
||||
['KEEP_EMPTY.jpg'],
|
||||
['KEEP_NULL.jpg'],
|
||||
['KEEP_NONSTRING.jpg'],
|
||||
['ABC.jpg'],
|
||||
]);
|
||||
expect(response).toEqual({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: {
|
||||
message_id: 777001,
|
||||
real_id: 777001,
|
||||
message: [
|
||||
null,
|
||||
'skip-me',
|
||||
12,
|
||||
{ type: 'text', data: { text: 'plain' } },
|
||||
{ type: 'image', data: 'not-object' },
|
||||
{ type: 'image' },
|
||||
{ type: 'image', data: emptyFileImage },
|
||||
{ type: 'image', data: noHandle },
|
||||
{ type: 'image', data: fileIdImage },
|
||||
{ type: 'image', data: keepEmptyUrl },
|
||||
{ type: 'image', data: keepNull },
|
||||
{ type: 'image', data: keepNonString },
|
||||
{ type: 'image', data: fileImage },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(fileImage.url).toBe('https://new.example/ABC.jpg?rkey=FRESH');
|
||||
expect(fileIdImage.url).toBe('https://new.example/file-id.jpg?rkey=FRESH');
|
||||
expect(emptyFileImage.url).toBe('https://old.example/empty-file.jpg');
|
||||
expect(keepEmptyUrl.url).toBe('https://old.example/keep-empty.jpg');
|
||||
expect(keepNull.url).toBe('https://old.example/keep-null.jpg');
|
||||
expect(keepNonString.url).toBe('https://old.example/keep-nonstring.jpg');
|
||||
expect(noHandle.url).toBe('https://old.example/no-file.jpg');
|
||||
});
|
||||
|
||||
it('keeps the stored image URL when getImageInfo throws', async () => {
|
||||
const imageData: JsonObject = {
|
||||
file: 'THROW.jpg',
|
||||
url: 'https://old.example/throw.jpg',
|
||||
};
|
||||
const getImageInfo = vi.fn(async () => {
|
||||
throw new Error('rkey fetch failed');
|
||||
});
|
||||
const response = await getMsg.toHandler(
|
||||
asCtx({
|
||||
getMessage: () => ({
|
||||
message_id: 777002,
|
||||
message: [{ type: 'image', data: imageData }],
|
||||
}),
|
||||
getImageInfo,
|
||||
}),
|
||||
)({ message_id: 777002 });
|
||||
|
||||
expect(getImageInfo.mock.calls).toEqual([['THROW.jpg']]);
|
||||
expect(response).toEqual({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: {
|
||||
message_id: 777002,
|
||||
real_id: 777002,
|
||||
message: [{ type: 'image', data: imageData }],
|
||||
},
|
||||
});
|
||||
expect(imageData.url).toBe('https://old.example/throw.jpg');
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete_msg', () => {
|
||||
|
||||
@@ -65,18 +65,27 @@ describe('face animation results', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-face-animation-'));
|
||||
const dbPath = path.join(dir, 'messages.db');
|
||||
let store = new MessageStore(dbPath);
|
||||
await store.initialization;
|
||||
|
||||
try {
|
||||
store.storeEvent(Number(event.message_id), true, 30001, 42, GROUP_MESSAGE_EVENT, event);
|
||||
store.close();
|
||||
await store.storeEvent(
|
||||
Number(event.message_id),
|
||||
true,
|
||||
30001,
|
||||
42,
|
||||
GROUP_MESSAGE_EVENT,
|
||||
event,
|
||||
);
|
||||
await store.close();
|
||||
store = new MessageStore(dbPath);
|
||||
expect(store.findEvent(Number(event.message_id))?.message).toEqual(message);
|
||||
await store.initialization;
|
||||
expect((await store.findEvent(Number(event.message_id)))?.message).toEqual(message);
|
||||
const history = await getGroupMsgHistory(store, 30001, undefined, 20);
|
||||
expect(history).toHaveLength(1);
|
||||
expect(history[0].message).toEqual(message);
|
||||
expect(history[0].raw_message).toBe(event.raw_message);
|
||||
} finally {
|
||||
store.close();
|
||||
await store.close();
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
// inside the real implementation; mocks see only the top call).
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import {
|
||||
@@ -23,7 +24,7 @@ import {
|
||||
} from '../src/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
return new Proxy({ identity: { nickname: 'SnowLuma' }, ...overrides } as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
@@ -39,9 +40,16 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||
uin: '10001',
|
||||
selfId: 10001,
|
||||
bridge,
|
||||
messageStore: { findMedia: () => null, findEvent: () => null } as any,
|
||||
messageStore: { findMedia: () => null, findEvent: () => null, storeEvent: vi.fn() } as any,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
@@ -402,6 +410,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
...ctx.messageStore,
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
|
||||
@@ -419,6 +428,119 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(['image', 'record', 'video'] as const)(
|
||||
'prepares fetched %s fingerprints at every nesting level (#437)',
|
||||
async (type) => {
|
||||
const fingerprint = {
|
||||
fileId: 'source-id',
|
||||
fileSize: 120,
|
||||
md5Hex: 'ab'.repeat(16),
|
||||
sha1Hex: 'cd'.repeat(20),
|
||||
};
|
||||
const media: MessageElement =
|
||||
type === 'image'
|
||||
? { ...fingerprint, type, width: 32, height: 24, picFormat: 1001 }
|
||||
: { ...fingerprint, type, duration: 3 };
|
||||
const leaf: ForwardNodePayload = { userUin: 111, nickname: 'leaf', elements: [media] };
|
||||
// QQ only accepts standalone video nodes; exercise mixed content with
|
||||
// images/voice and use a text sibling for the video case.
|
||||
const sibling: MessageElement =
|
||||
type === 'video' ? { type: 'text', text: 'nested video' } : media;
|
||||
const mixed: ForwardNodePayload = {
|
||||
userUin: 222,
|
||||
nickname: 'mixed',
|
||||
elements: [sibling, { type: 'forward', resId: 'INNER' }],
|
||||
};
|
||||
const outer: ForwardNodePayload[] = [
|
||||
leaf,
|
||||
mixed,
|
||||
{
|
||||
userUin: 333,
|
||||
nickname: 'nested',
|
||||
elements: [{ type: 'forward', resId: 'INNER' }],
|
||||
},
|
||||
];
|
||||
const before = structuredClone(outer);
|
||||
const fetch = vi.fn(async (resId: string) => (resId === 'OUTER' ? outer : [leaf]));
|
||||
const upload = vi.fn(
|
||||
async (_nodes: ForwardNodePayload[], _groupId?: number, _userId?: number) =>
|
||||
'NEW_RES',
|
||||
);
|
||||
const sendPrivate = vi.fn(async () => ({
|
||||
sequence: 1,
|
||||
clientSequence: 2,
|
||||
random: 3,
|
||||
timestamp: 1700000000,
|
||||
}));
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({
|
||||
apis: { forward: { fetch, upload }, message: { sendPrivate } },
|
||||
} as any),
|
||||
);
|
||||
ctx.messageStore.findEvent = () => ({
|
||||
message: [{ type: 'forward', data: { id: 'OUTER' } }],
|
||||
});
|
||||
|
||||
await forwardSingleMessage(ctx, 77, { userId: 10001 });
|
||||
|
||||
const expected = expect.objectContaining({
|
||||
...fingerprint,
|
||||
type,
|
||||
noByteFallback: true,
|
||||
});
|
||||
const finalNodes = upload.mock.calls.at(-1)![0];
|
||||
expect(finalNodes[0]!.elements).toEqual([expected]);
|
||||
expect(finalNodes[1]!.elements[0]).toEqual(type === 'video' ? sibling : expected);
|
||||
expect(finalNodes[2]!.innerForward![0]!.elements).toEqual([expected]);
|
||||
expect(upload.mock.calls[0]![0][0]!.elements).toEqual([expected]);
|
||||
|
||||
for (const [, groupId, userId] of upload.mock.calls) {
|
||||
expect(groupId).toBeUndefined();
|
||||
expect(userId).toBe(10001);
|
||||
}
|
||||
|
||||
expect(outer).toEqual(before);
|
||||
expect(sendPrivate).toHaveBeenCalledOnce();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ type: 'image', imageUrl: 'https://example.com/legacy.png', md5Hex: 'ab'.repeat(16) },
|
||||
{
|
||||
type: 'image',
|
||||
imageUrl: 'https://example.com/partial.png',
|
||||
md5Hex: 'ab'.repeat(16),
|
||||
sha1Hex: 'cd'.repeat(20),
|
||||
width: 0,
|
||||
height: 0,
|
||||
},
|
||||
] satisfies MessageElement[])(
|
||||
'keeps the source upload path for incomplete image fingerprints ($imageUrl)',
|
||||
async (media) => {
|
||||
const upload = vi.fn(async (_nodes: ForwardNodePayload[]) => 'NEW_RES');
|
||||
const fetch = vi.fn(async () => [
|
||||
{ userUin: 111, nickname: 'alice', elements: [media] },
|
||||
]);
|
||||
const sendGroup = vi.fn(async () => ({
|
||||
sequence: 1,
|
||||
clientSequence: 0,
|
||||
random: 2,
|
||||
timestamp: 1700000000,
|
||||
}));
|
||||
const ctx = makeCtx(
|
||||
fakeBridge({ apis: { forward: { fetch, upload }, message: { sendGroup } } } as any),
|
||||
);
|
||||
ctx.messageStore.findEvent = () => ({
|
||||
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
|
||||
});
|
||||
|
||||
await forwardSingleMessage(ctx, 77, { groupId: 12345 });
|
||||
|
||||
expect(upload.mock.calls[0]![0][0]!.elements).toEqual([media]);
|
||||
expect(upload.mock.calls[0]![0][0]!.elements[0]!.noByteFallback).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it('fails a merged-forward single send when the inner tree cannot be fetched (#437)', async () => {
|
||||
const fetch = vi.fn(async () => {
|
||||
throw new Error('download forward message failed');
|
||||
@@ -430,6 +552,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
...ctx.messageStore,
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
|
||||
@@ -492,6 +615,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
...ctx.messageStore,
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
message: [{ type: 'forward', data: { id: 'OUTER' } }],
|
||||
@@ -514,6 +638,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
...ctx.messageStore,
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
message: [
|
||||
@@ -605,6 +730,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
...ctx.messageStore,
|
||||
findMedia: () => null,
|
||||
findEvent: () => ({
|
||||
user_id: 0,
|
||||
@@ -661,7 +787,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
},
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = { findEvent, findMedia: () => null };
|
||||
(ctx as any).messageStore = { ...ctx.messageStore, findEvent, findMedia: () => null };
|
||||
|
||||
await sendGroupForwardMessage(ctx, 12345, [{ type: 'node', data: { id: -123 } }] as any);
|
||||
|
||||
@@ -719,7 +845,7 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
},
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = { findEvent, findMedia: () => null };
|
||||
(ctx as any).messageStore = { ...ctx.messageStore, findEvent, findMedia: () => null };
|
||||
|
||||
await sendGroupForwardMessage(ctx, 12345, [
|
||||
{ type: 'node', data: { id: 7, nickname: 'node-override' } },
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { Elem } from '@snowluma/proto-defs/element';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { decodeRichBody } from '@snowluma/protocol/msg-push/rich-body-decoder';
|
||||
import type { ForwardNodePayload } from '@snowluma/protocol/events';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import type { JsonObject } from '../src/types';
|
||||
import { elementsToOneBotSegments } from '../src/event-converter';
|
||||
import { parseMessage } from '../src/message-parser';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
import {
|
||||
getForwardMessage,
|
||||
sendGroupForwardMessage,
|
||||
sendPrivateForwardMessage,
|
||||
uploadForwardMessage,
|
||||
} from '../src/modules/message-actions';
|
||||
|
||||
const time = 1700000000;
|
||||
|
||||
function fixture(nodes: ForwardNodePayload[] = []) {
|
||||
const upload = vi.fn(async (_nodes: ForwardNodePayload[]) => 'forward-id');
|
||||
const send = vi.fn(async () => ({
|
||||
messageId: 9,
|
||||
sequence: 100,
|
||||
clientSequence: 0,
|
||||
random: 1,
|
||||
timestamp: time,
|
||||
}));
|
||||
const findEvent = vi.fn(() => null);
|
||||
const ctx = {
|
||||
uin: '10001',
|
||||
selfId: 10001,
|
||||
bridge: {
|
||||
identity: { nickname: 'SnowLuma' },
|
||||
apis: {
|
||||
forward: { upload, fetch: vi.fn(async () => nodes) },
|
||||
message: { sendGroup: send, sendPrivate: send },
|
||||
},
|
||||
},
|
||||
messageStore: { findEvent, findMedia: () => null, storeEvent: vi.fn() },
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {},
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
return { ctx, upload, send, findEvent };
|
||||
}
|
||||
|
||||
function node(data: JsonObject): JsonObject {
|
||||
return {
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 20002,
|
||||
nickname: 'sender',
|
||||
time,
|
||||
content: [
|
||||
{ type: 'reply', data },
|
||||
{ type: 'text', data: { text: 'answer' } },
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('custom replies inside merged forwards (#241)', () => {
|
||||
it.each(['group', 'private', 'upload'] as const)(
|
||||
'%s preserves custom quote text on the wire without looking up an id',
|
||||
async (scene) => {
|
||||
const { ctx, upload, findEvent } = fixture();
|
||||
const messages = [
|
||||
node({
|
||||
id: '-123',
|
||||
message: [{ type: 'text', data: { text: '原文\nSnowLuma 😀' } }],
|
||||
qq: '30003',
|
||||
time: String(time - 10),
|
||||
seq: '42',
|
||||
}),
|
||||
];
|
||||
|
||||
if (scene === 'group') {
|
||||
await sendGroupForwardMessage(ctx, 40004, messages);
|
||||
} else if (scene === 'private') {
|
||||
await sendPrivateForwardMessage(ctx, 40004, messages);
|
||||
} else {
|
||||
await uploadForwardMessage(ctx, messages);
|
||||
}
|
||||
|
||||
expect(findEvent).not.toHaveBeenCalledWith(-123);
|
||||
const elements = upload.mock.calls[0]![0][0]!.elements;
|
||||
const wire = await buildSendElems(elements);
|
||||
const src = protobuf_decode<Elem>(protobuf_encode<Elem>(wire[0]!)).srcMsg;
|
||||
expect(src).toMatchObject({ origSeqs: [42], senderUin: 30003n, time: time - 10 });
|
||||
expect(src?.elemsRaw?.map((raw) => protobuf_decode<Elem>(raw).text?.str).join('')).toBe(
|
||||
'原文\nSnowLuma 😀',
|
||||
);
|
||||
expect(wire[1]?.text?.str).toBe('answer');
|
||||
const decoded = decodeRichBody(
|
||||
{
|
||||
richText: {
|
||||
elems: wire.map((element) =>
|
||||
protobuf_decode<Elem>(protobuf_encode<Elem>(element)),
|
||||
),
|
||||
},
|
||||
},
|
||||
scene === 'group',
|
||||
);
|
||||
expect(decoded[0]).toMatchObject({
|
||||
type: 'reply',
|
||||
replySeq: 42,
|
||||
replySenderUin: 30003,
|
||||
replyTime: time - 10,
|
||||
replyElements: [{ type: 'text', text: '原文\nSnowLuma 😀' }],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(
|
||||
[
|
||||
'SnowLuma',
|
||||
{ type: 'text', data: { text: 'SnowLuma' } },
|
||||
[{ type: 'text', data: { text: 'SnowLuma' } }],
|
||||
].map((message) => ({ message })),
|
||||
)('uses node metadata when only message is supplied ($message)', async ({ message }) => {
|
||||
const { ctx, upload } = fixture();
|
||||
await uploadForwardMessage(ctx, [node({ message })]);
|
||||
expect(upload.mock.calls[0]![0][0]?.elements[0]).toMatchObject({
|
||||
type: 'reply',
|
||||
replySeq: 1,
|
||||
replySenderUin: 20002,
|
||||
replyTime: time,
|
||||
replyElements: [{ type: 'text', text: 'SnowLuma' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('round-trips fetched quote content and metadata without a local message record', async () => {
|
||||
const { ctx, upload } = fixture([
|
||||
{
|
||||
userUin: 20002,
|
||||
nickname: 'sender',
|
||||
time,
|
||||
groupId: 40004,
|
||||
messageType: 'group',
|
||||
elements: [
|
||||
{
|
||||
type: 'reply',
|
||||
replySeq: 42,
|
||||
replySenderUin: 30003,
|
||||
replyTime: time - 10,
|
||||
replyElements: [{ type: 'text', text: 'quoted' }],
|
||||
},
|
||||
{ type: 'text', text: 'answer' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
const [fetched] = await getForwardMessage(ctx, 'original');
|
||||
expect((fetched!.message as JsonObject[])[0]?.data).toMatchObject({
|
||||
id: expect.any(String),
|
||||
message: [{ type: 'text', data: { text: 'quoted' } }],
|
||||
qq: '30003',
|
||||
time: String(time - 10),
|
||||
seq: '42',
|
||||
});
|
||||
await uploadForwardMessage(ctx, [
|
||||
{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: fetched!.user_id,
|
||||
nickname: 'sender',
|
||||
content: fetched!.message,
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(upload.mock.calls[0]![0][0]?.elements[0]).toMatchObject({
|
||||
type: 'reply',
|
||||
replySeq: 42,
|
||||
replySenderUin: 30003,
|
||||
replyTime: time - 10,
|
||||
replyElements: [{ type: 'text', text: 'quoted' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('summarizes quoted media without uploading it, and works in nested forwards', async () => {
|
||||
const { ctx, upload } = fixture();
|
||||
await uploadForwardMessage(ctx, [
|
||||
{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 10001,
|
||||
content: [
|
||||
node({
|
||||
message: [
|
||||
{ type: 'text', data: { text: 'photo' } },
|
||||
{ type: 'image', data: { file: 'unavailable.png' } },
|
||||
{ type: 'at', data: { qq: 'all' } },
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(upload.mock.calls[0]![0][0]?.innerForward?.[0]?.elements[0]?.replyElements).toEqual([
|
||||
{ type: 'text', text: 'photo[图片]@全体成员' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps id-only replies when QQ supplies no inline content', async () => {
|
||||
const { ctx } = fixture([
|
||||
{
|
||||
userUin: 20002,
|
||||
nickname: 'sender',
|
||||
time,
|
||||
elements: [
|
||||
{ type: 'reply', replySeq: 42 },
|
||||
{ type: 'text', text: 'answer' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
const [fetched] = await getForwardMessage(ctx, 'original');
|
||||
expect((fetched!.message as JsonObject[])[0]).toEqual({
|
||||
type: 'reply',
|
||||
data: { id: '42' },
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts the full uint32 sequence range and CQ text within a quote', async () => {
|
||||
const { ctx, upload } = fixture();
|
||||
await uploadForwardMessage(ctx, [
|
||||
node({ message: 'hello[CQ:at,qq=all]', seq: 0xffffffff, time: 0 }),
|
||||
]);
|
||||
const wire = await buildSendElems(upload.mock.calls[0]![0][0]!.elements);
|
||||
const src = protobuf_decode<Elem>(protobuf_encode<Elem>(wire[0]!)).srcMsg;
|
||||
expect(src?.origSeqs).toEqual([0xffffffff]);
|
||||
expect(src?.elemsRaw?.map((raw) => protobuf_decode<Elem>(raw).text?.str).join('')).toBe(
|
||||
'hello@全体成员',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ message: [] },
|
||||
{ message: '' },
|
||||
{ message: null },
|
||||
{ message: 123 },
|
||||
{ message: [{ type: 'text', data: { text: {} } }] },
|
||||
{ message: [{ type: 'unknown', data: {} }] },
|
||||
{ message: [{ type: 'music', data: { type: 'qq', id: '1' } }] },
|
||||
{ message: [{ type: 'node', data: { content: 'nested' } }] },
|
||||
{ message: [{ type: 'reply', data: { message: 'nested' } }] },
|
||||
{ message: 'quote', seq: 0 },
|
||||
{ message: 'quote', seq: 0x100000000 },
|
||||
{ message: 'quote', qq: -1 },
|
||||
{ message: 'quote', qq: true },
|
||||
{ message: 'quote', time: 1700000000000 },
|
||||
{ message: 'quote', time: -1 },
|
||||
{ message: 'quote', time: null },
|
||||
{ message: 'quote', time: '' },
|
||||
{ message: 'quote', time: ' ' },
|
||||
{ message: 'quote', time: 1.5 },
|
||||
{ message: 'quote', qq: null },
|
||||
{ message: 'quote', seq: '' },
|
||||
] satisfies JsonObject[])(
|
||||
'rejects invalid custom reply input before uploading (%j)',
|
||||
async (data) => {
|
||||
const { ctx, upload, send } = fixture();
|
||||
await expect(sendGroupForwardMessage(ctx, 40004, [node(data)])).rejects.toThrow();
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('reports malformed custom quotes as BAD_REQUEST at the action boundary', async () => {
|
||||
const { ctx, upload, send } = fixture();
|
||||
const api = new ApiHandler({
|
||||
sendGroupForwardMsg: (groupId, messages) =>
|
||||
sendGroupForwardMessage(ctx, groupId, messages),
|
||||
} as ApiActionContext);
|
||||
const result = await api.handle('send_group_forward_msg', {
|
||||
group_id: 40004,
|
||||
messages: [node({ message: 'quote', seq: 0 })],
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
wording: expect.stringContaining('reply.seq'),
|
||||
});
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps ordinary reply id parsing and ordinary received reply segments unchanged', async () => {
|
||||
expect(await parseMessage([{ type: 'reply', data: { id: 42 } }], false)).toEqual([
|
||||
{ type: 'reply', replySeq: 42 },
|
||||
]);
|
||||
const { ctx } = fixture();
|
||||
expect(
|
||||
await elementsToOneBotSegments(
|
||||
ctx.converterCtx,
|
||||
[
|
||||
{
|
||||
type: 'reply',
|
||||
replySeq: 42,
|
||||
replySenderUin: 30003,
|
||||
replyTime: time,
|
||||
replyElements: [{ type: 'text', text: 'quoted' }],
|
||||
},
|
||||
],
|
||||
true,
|
||||
40004,
|
||||
),
|
||||
).toEqual([{ type: 'reply', data: { id: expect.any(String) } }]);
|
||||
await expect(
|
||||
parseMessage(
|
||||
[
|
||||
{ type: 'reply', data: { message: 'quote' } },
|
||||
{ type: 'text', data: { text: 'answer' } },
|
||||
],
|
||||
false,
|
||||
),
|
||||
).rejects.toThrow(/forward/);
|
||||
});
|
||||
});
|
||||
@@ -300,8 +300,8 @@ describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
|
||||
mediaSegmentSink: null,
|
||||
} as never;
|
||||
|
||||
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', () => {
|
||||
const out = convertGroupMsgEmojiLike(ctx, baseEvent);
|
||||
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', async () => {
|
||||
const out = await convertGroupMsgEmojiLike(ctx, baseEvent);
|
||||
expect(out.post_type).toBe('notice');
|
||||
expect(out.notice_type).toBe('group_msg_emoji_like');
|
||||
expect(out.sub_type).toBe('add');
|
||||
@@ -313,8 +313,8 @@ describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
|
||||
expect(out.likes).toEqual([{ emoji_id: '76', count: 1 }]);
|
||||
});
|
||||
|
||||
it('flips sub_type to remove when isAdd is false', () => {
|
||||
const out = convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
|
||||
it('flips sub_type to remove when isAdd is false', async () => {
|
||||
const out = await convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
|
||||
expect(out.sub_type).toBe('remove');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,7 +57,7 @@ function converter(media: MediaStore): ConverterContext {
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: (...args) => indexer.remember(...args),
|
||||
mediaSegmentSink: async (...args) => await indexer.remember(...args),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,7 +89,9 @@ describe('durable historical media', () => {
|
||||
async (type) => {
|
||||
const { dbPath } = location();
|
||||
let messages = new MessageStore(dbPath);
|
||||
await messages.initialization;
|
||||
let media = new MediaStore(dbPath, 2);
|
||||
await media.initialization;
|
||||
const element = {
|
||||
type,
|
||||
fileId: 'same.png',
|
||||
@@ -119,9 +121,9 @@ describe('durable historical media', () => {
|
||||
elements: [element],
|
||||
});
|
||||
event!.message_id = 42;
|
||||
messages.storeHistoryEvent(42, true, 123, 10, 'GroupMessage', event!);
|
||||
await messages.storeHistoryEvent(42, true, 123, 10, 'GroupMessage', event!);
|
||||
expect(JSON.stringify(event)).not.toContain('md5Hex');
|
||||
expect(JSON.stringify(messages.findEvent(42))).not.toContain('sha1Hex');
|
||||
expect(JSON.stringify(await messages.findEvent(42))).not.toContain('sha1Hex');
|
||||
|
||||
// Repeated names and many new resources must not change the old message.
|
||||
for (let i = 0; i < 80; i++) {
|
||||
@@ -131,14 +133,16 @@ describe('durable historical media', () => {
|
||||
true,
|
||||
123,
|
||||
);
|
||||
media.rememberImage({ ...image, file: `other-${i}`, fileName: `other-${i}` });
|
||||
media.findImage(`other-${i}`);
|
||||
await media.rememberImage({ ...image, file: `other-${i}`, fileName: `other-${i}` });
|
||||
await media.findImage(`other-${i}`);
|
||||
}
|
||||
|
||||
media.close();
|
||||
messages.close();
|
||||
await media.close();
|
||||
await messages.close();
|
||||
messages = new MessageStore(dbPath);
|
||||
await messages.initialization;
|
||||
media = new MediaStore(dbPath, 2);
|
||||
await media.initialization;
|
||||
|
||||
try {
|
||||
const { ref, sendGroup, upload } = context(messages, media);
|
||||
@@ -163,10 +167,10 @@ describe('durable historical media', () => {
|
||||
],
|
||||
}),
|
||||
]);
|
||||
expect(messages.findEvent(42)?.message_id).toBe(42);
|
||||
expect((await messages.findEvent(42))?.message_id).toBe(42);
|
||||
} finally {
|
||||
media.close();
|
||||
messages.close();
|
||||
await media.close();
|
||||
await messages.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -174,7 +178,9 @@ describe('durable historical media', () => {
|
||||
it('stores the body and media snapshot atomically and strips inline bytes', async () => {
|
||||
const { dbPath } = location();
|
||||
const messages = new MessageStore(dbPath);
|
||||
await messages.initialization;
|
||||
const media = new MediaStore(dbPath);
|
||||
await media.initialization;
|
||||
const db = new DatabaseSync(dbPath);
|
||||
|
||||
try {
|
||||
@@ -196,25 +202,26 @@ describe('durable historical media', () => {
|
||||
db.exec(
|
||||
"CREATE TRIGGER fail_media BEFORE INSERT ON messages WHEN NEW.media_data IS NOT NULL BEGIN SELECT RAISE(ABORT, 'test media write failure'); END",
|
||||
);
|
||||
expect(() => messages.storeEvent(1, true, 123, 1, 'GroupMessage', event)).toThrow(
|
||||
'test media write failure',
|
||||
);
|
||||
expect(messages.findEvent(1)).toBeNull();
|
||||
await expect(
|
||||
async () => await messages.storeEvent(1, true, 123, 1, 'GroupMessage', event),
|
||||
).rejects.toThrow('test media write failure');
|
||||
expect(await messages.findEvent(1)).toBeNull();
|
||||
db.exec('DROP TRIGGER fail_media');
|
||||
messages.storeEvent(1, true, 123, 1, 'GroupMessage', event);
|
||||
expect(messages.findMedia(1)?.[0].md5Hex).toBe(image.md5Hex);
|
||||
expect(JSON.stringify(messages.findMedia(1))).not.toContain('base64://');
|
||||
await messages.storeEvent(1, true, 123, 1, 'GroupMessage', event);
|
||||
expect((await messages.findMedia(1))?.[0].md5Hex).toBe(image.md5Hex);
|
||||
expect(JSON.stringify(await messages.findMedia(1))).not.toContain('base64://');
|
||||
} finally {
|
||||
db.close();
|
||||
media.close();
|
||||
messages.close();
|
||||
await media.close();
|
||||
await messages.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('propagates media persistence failures instead of silently skipping segments', async () => {
|
||||
const { dbPath } = location();
|
||||
const media = new MediaStore(dbPath);
|
||||
media.close();
|
||||
await media.initialization;
|
||||
await media.close();
|
||||
await expect(
|
||||
elementsToOneBotSegments(
|
||||
converter(media),
|
||||
@@ -228,7 +235,9 @@ describe('durable historical media', () => {
|
||||
it('does not substitute another same-named resource for an incomplete snapshot', async () => {
|
||||
const { dbPath } = location();
|
||||
const messages = new MessageStore(dbPath);
|
||||
await messages.initialization;
|
||||
const media = new MediaStore(dbPath);
|
||||
await media.initialization;
|
||||
|
||||
try {
|
||||
const segments = await elementsToOneBotSegments(
|
||||
@@ -237,28 +246,30 @@ describe('durable historical media', () => {
|
||||
true,
|
||||
123,
|
||||
);
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
|
||||
media.rememberImage(image);
|
||||
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
|
||||
await media.rememberImage(image);
|
||||
const { ref, sendGroup } = context(messages, media);
|
||||
await expect(forwardSingleMessage(ref, 42, { groupId: 999 })).rejects.toThrow(
|
||||
'metadata is incomplete',
|
||||
);
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
media.close();
|
||||
messages.close();
|
||||
await media.close();
|
||||
await messages.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('preserves complete metadata across an incomplete repeat and rejects conflicting resources', async () => {
|
||||
const { dbPath } = location();
|
||||
let messages = new MessageStore(dbPath);
|
||||
await messages.initialization;
|
||||
let media = new MediaStore(dbPath);
|
||||
await media.initialization;
|
||||
const complete: MessageElement = { type: 'image', ...image, fileId: image.file };
|
||||
|
||||
const save = async (element: MessageElement) => {
|
||||
const segments = await elementsToOneBotSegments(converter(media), [element], true, 123);
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
|
||||
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
|
||||
};
|
||||
|
||||
await save(complete);
|
||||
@@ -270,10 +281,12 @@ describe('durable historical media', () => {
|
||||
height: 0,
|
||||
});
|
||||
await expect(save({ ...complete, md5Hex: 'cc'.repeat(16) })).rejects.toThrow('conflicting');
|
||||
media.close();
|
||||
messages.close();
|
||||
await media.close();
|
||||
await messages.close();
|
||||
messages = new MessageStore(dbPath);
|
||||
await messages.initialization;
|
||||
media = new MediaStore(dbPath);
|
||||
await media.initialization;
|
||||
|
||||
try {
|
||||
const { ref, sendGroup } = context(messages, media);
|
||||
@@ -287,15 +300,17 @@ describe('durable historical media', () => {
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
media.close();
|
||||
messages.close();
|
||||
await media.close();
|
||||
await messages.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not combine disjoint image fingerprints merely because fileId is the same filename', async () => {
|
||||
const { dbPath } = location();
|
||||
const messages = new MessageStore(dbPath);
|
||||
await messages.initialization;
|
||||
const media = new MediaStore(dbPath);
|
||||
await media.initialization;
|
||||
|
||||
try {
|
||||
const original = await elementsToOneBotSegments(
|
||||
@@ -304,43 +319,53 @@ describe('durable historical media', () => {
|
||||
true,
|
||||
123,
|
||||
);
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: original });
|
||||
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: original });
|
||||
const different = await elementsToOneBotSegments(
|
||||
converter(media),
|
||||
[{ type: 'image', fileId: 'photo.jpg', sha1Hex: image.sha1Hex, width: 64 }],
|
||||
true,
|
||||
123,
|
||||
);
|
||||
expect(() =>
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: different }),
|
||||
).toThrow('unverified media association');
|
||||
expect(messages.findMedia(42)).toEqual([
|
||||
await expect(
|
||||
async () =>
|
||||
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
|
||||
message: different,
|
||||
}),
|
||||
).rejects.toThrow('unverified media association');
|
||||
expect(await messages.findMedia(42)).toEqual([
|
||||
{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 },
|
||||
]);
|
||||
} finally {
|
||||
media.close();
|
||||
messages.close();
|
||||
await media.close();
|
||||
await messages.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects corrupt and oversized metadata without deleting history', () => {
|
||||
it('rejects corrupt and oversized metadata without deleting history', async () => {
|
||||
const { dbPath } = location();
|
||||
const media = new MediaStore(dbPath);
|
||||
await media.initialization;
|
||||
const db = new DatabaseSync(dbPath);
|
||||
|
||||
try {
|
||||
expect(() =>
|
||||
media.rememberImage({ ...image, summary: 'x'.repeat(MEDIA_DATA_MAX_CHARS) }),
|
||||
).toThrow('storage limit');
|
||||
media.rememberImage(image);
|
||||
await expect(
|
||||
async () =>
|
||||
await media.rememberImage({
|
||||
...image,
|
||||
summary: 'x'.repeat(MEDIA_DATA_MAX_CHARS),
|
||||
}),
|
||||
).rejects.toThrow('storage limit');
|
||||
await media.rememberImage(image);
|
||||
db.exec("UPDATE media_entries SET data = '{broken'");
|
||||
expect(() => media.findImage(image.file)).toThrow();
|
||||
await expect(async () => await media.findImage(image.file)).rejects.toThrow();
|
||||
db.exec("UPDATE media_entries SET data = 'null'");
|
||||
expect(() => media.findImage(image.file)).toThrow('invalid persisted');
|
||||
expect(media.size().images).toBe(1);
|
||||
await expect(async () => await media.findImage(image.file)).rejects.toThrow(
|
||||
'invalid persisted',
|
||||
);
|
||||
expect((await media.size()).images).toBe(1);
|
||||
} finally {
|
||||
db.close();
|
||||
media.close();
|
||||
await media.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -349,6 +374,7 @@ describe('durable historical media', () => {
|
||||
async (type) => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = new MediaStore(legacyPath);
|
||||
await old.initialization;
|
||||
const element = {
|
||||
type,
|
||||
fileId: 'same.png',
|
||||
@@ -364,10 +390,11 @@ describe('durable historical media', () => {
|
||||
videoFormat: 0,
|
||||
} as MessageElement;
|
||||
await elementsToOneBotSegments(converter(old), [element], true, 123);
|
||||
old.close();
|
||||
await old.close();
|
||||
const source = fs.readFileSync(legacyPath);
|
||||
const messages = new MessageStore(dbPath);
|
||||
messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
|
||||
await messages.initialization;
|
||||
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
|
||||
user_id: 456,
|
||||
message_id: 42,
|
||||
message_type: 'group',
|
||||
@@ -378,6 +405,7 @@ describe('durable historical media', () => {
|
||||
fs.rmSync(legacyPath);
|
||||
await migrateLegacyMedia(dbPath);
|
||||
const media = new MediaStore(dbPath);
|
||||
await media.initialization;
|
||||
|
||||
try {
|
||||
await elementsToOneBotSegments(
|
||||
@@ -392,8 +420,8 @@ describe('durable historical media', () => {
|
||||
expect.objectContaining({ md5Hex: image.md5Hex }),
|
||||
]);
|
||||
} finally {
|
||||
media.close();
|
||||
messages.close();
|
||||
await media.close();
|
||||
await messages.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -401,15 +429,17 @@ describe('durable historical media', () => {
|
||||
it('rolls back a failed legacy batch and resumes after the source is repaired', async () => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = new MediaStore(legacyPath);
|
||||
old.rememberImage(image);
|
||||
old.close();
|
||||
await old.initialization;
|
||||
await old.rememberImage(image);
|
||||
await old.close();
|
||||
const source = new DatabaseSync(legacyPath);
|
||||
source.prepare("INSERT INTO media_entries VALUES ('image', 'broken', ?, 1)").run('{broken');
|
||||
source.close();
|
||||
await expect(migrateLegacyMedia(dbPath)).rejects.toThrow();
|
||||
const destination = new MediaStore(dbPath);
|
||||
expect(destination.size().images).toBe(0);
|
||||
destination.close();
|
||||
await destination.initialization;
|
||||
expect((await destination.size()).images).toBe(0);
|
||||
await destination.close();
|
||||
const repaired = new DatabaseSync(legacyPath);
|
||||
repaired
|
||||
.prepare("UPDATE media_entries SET data = ? WHERE primary_key = 'broken'")
|
||||
@@ -417,14 +447,16 @@ describe('durable historical media', () => {
|
||||
repaired.close();
|
||||
await migrateLegacyMedia(dbPath);
|
||||
const reopened = new MediaStore(dbPath);
|
||||
expect(reopened.size().images).toBe(2);
|
||||
reopened.close();
|
||||
await reopened.initialization;
|
||||
expect((await reopened.size()).images).toBe(2);
|
||||
await reopened.close();
|
||||
});
|
||||
|
||||
it('normalizes legacy inline payloads without discarding their metadata', async () => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = new MediaStore(legacyPath);
|
||||
old.close();
|
||||
await old.initialization;
|
||||
await old.close();
|
||||
const inline = `base64://${'Z'.repeat(100000)}`;
|
||||
const source = new DatabaseSync(legacyPath);
|
||||
source
|
||||
@@ -434,37 +466,41 @@ describe('durable historical media', () => {
|
||||
source.close();
|
||||
await migrateLegacyMedia(dbPath);
|
||||
const media = new MediaStore(dbPath);
|
||||
await media.initialization;
|
||||
|
||||
try {
|
||||
expect(media.findImage(inline)).toMatchObject({
|
||||
expect(await media.findImage(inline)).toMatchObject({
|
||||
md5Hex: image.md5Hex,
|
||||
url: '',
|
||||
imageUrl: '',
|
||||
});
|
||||
expect(JSON.stringify(media.findImage(inline))).not.toContain('base64://');
|
||||
expect(JSON.stringify(await media.findImage(inline))).not.toContain('base64://');
|
||||
} finally {
|
||||
media.close();
|
||||
await media.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('resumes a cancelled migration from its committed batch cursor', async () => {
|
||||
const { dbPath, legacyPath } = location();
|
||||
const old = new MediaStore(legacyPath);
|
||||
await old.initialization;
|
||||
|
||||
for (let i = 0; i < 205; i++) {
|
||||
old.rememberImage({ ...image, file: `entry-${i}` });
|
||||
await old.rememberImage({ ...image, file: `entry-${i}` });
|
||||
}
|
||||
|
||||
old.close();
|
||||
await old.close();
|
||||
let checks = 0;
|
||||
await migrateLegacyMedia(dbPath, () => ++checks > 1);
|
||||
const partial = new MediaStore(dbPath);
|
||||
expect(partial.size().images).toBe(200);
|
||||
partial.close();
|
||||
await partial.initialization;
|
||||
expect((await partial.size()).images).toBe(200);
|
||||
await partial.close();
|
||||
await migrateLegacyMedia(dbPath);
|
||||
const complete = new MediaStore(dbPath);
|
||||
expect(complete.size().images).toBe(205);
|
||||
expect(complete.findImage('entry-204')?.md5Hex).toBe(image.md5Hex);
|
||||
complete.close();
|
||||
await complete.initialization;
|
||||
expect((await complete.size()).images).toBe(205);
|
||||
expect((await complete.findImage('entry-204'))?.md5Hex).toBe(image.md5Hex);
|
||||
await complete.close();
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
GROUP_MESSAGE_EVENT,
|
||||
@@ -60,12 +61,13 @@ function friendMessage(sequence: number, senderUin: number, clientSequence = seq
|
||||
describe('history direction plumbing', () => {
|
||||
let messageStore: MessageStore;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
messageStore = new MessageStore(':memory:');
|
||||
await messageStore.initialization;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
messageStore.close();
|
||||
afterEach(async () => {
|
||||
await messageStore.close();
|
||||
});
|
||||
|
||||
it('returns the group anchor followed by newer server messages', async () => {
|
||||
@@ -74,7 +76,7 @@ describe('history direction plumbing', () => {
|
||||
? [groupMessage(500), groupMessage(501)]
|
||||
: [groupMessage(499), groupMessage(500)],
|
||||
);
|
||||
messageStore.storeMeta(-123456789, {
|
||||
await messageStore.storeMeta(-123456789, {
|
||||
isGroup: true,
|
||||
targetId: GROUP_ID,
|
||||
sequence: 500,
|
||||
@@ -104,7 +106,7 @@ describe('history direction plumbing', () => {
|
||||
? [friendMessage(700, SELF_ID), friendMessage(701, FRIEND_ID)]
|
||||
: [friendMessage(699, FRIEND_ID), friendMessage(700, SELF_ID)],
|
||||
);
|
||||
messageStore.storeMeta(-987654321, {
|
||||
await messageStore.storeMeta(-987654321, {
|
||||
isGroup: false,
|
||||
targetId: FRIEND_ID,
|
||||
sequence: 700,
|
||||
@@ -138,7 +140,7 @@ describe('history direction plumbing', () => {
|
||||
friendMessage(63213, FRIEND_ID, 32742),
|
||||
friendMessage(63214, SELF_ID, 32743),
|
||||
]);
|
||||
messageStore.storeMeta(-222222222, {
|
||||
await messageStore.storeMeta(-222222222, {
|
||||
isGroup: false,
|
||||
targetId: FRIEND_ID,
|
||||
sequence: 99999,
|
||||
@@ -176,7 +178,7 @@ describe('history direction plumbing', () => {
|
||||
{ sender: FRIEND_ID, sequence: 32742 },
|
||||
{ sender: SELF_ID, sequence: 32743 },
|
||||
]);
|
||||
expect(messageStore.findMeta(Number(messages[0]!.message_id))).toMatchObject({
|
||||
expect(await messageStore.findMeta(Number(messages[0]!.message_id))).toMatchObject({
|
||||
sequence: 63213,
|
||||
clientSequence: 32742,
|
||||
sequenceAuthoritative: true,
|
||||
@@ -220,33 +222,56 @@ describe('history direction plumbing', () => {
|
||||
hashMessageIdInt32(63214, FRIEND_ID, PRIVATE_NT_MESSAGE_EVENT),
|
||||
]);
|
||||
expect(new Set(ids).size).toBe(2);
|
||||
expect(ids.map((id) => messageStore.findEvent(id)?.message_id)).toEqual(ids);
|
||||
expect(
|
||||
await mapWithConcurrency(
|
||||
ids,
|
||||
8,
|
||||
async (id) => (await messageStore.findEvent(id))?.message_id,
|
||||
),
|
||||
).toEqual(ids);
|
||||
});
|
||||
|
||||
it('does not return or re-cache a private message covered by a recall tombstone', async () => {
|
||||
messageStore.recordPrivateRecall(FRIEND_ID, 32742, false, 1700000010);
|
||||
const fetchLatestHistory = vi.fn(async () => [
|
||||
friendMessage(63213, FRIEND_ID, 32742),
|
||||
friendMessage(63214, SELF_ID, 32743),
|
||||
]);
|
||||
const ref = {
|
||||
selfId: SELF_ID,
|
||||
bridge: {
|
||||
resolveUserUid: vi.fn(async () => 'u_friend'),
|
||||
apis: { message: { getC2cLatestHistory: fetchLatestHistory } },
|
||||
},
|
||||
messageStore,
|
||||
converterCtx,
|
||||
} as any;
|
||||
it.each(['before reading', 'before persistence'] as const)(
|
||||
'does not return or re-cache a private message recalled %s',
|
||||
async (timing) => {
|
||||
const recall = () =>
|
||||
messageStore.recordPrivateRecall(FRIEND_ID, 32742, false, 1700000010);
|
||||
|
||||
const messages = await getFriendHistory(ref, FRIEND_ID, undefined, 20);
|
||||
if (timing === 'before reading') {
|
||||
await recall();
|
||||
} else {
|
||||
const persist = messageStore.storeHistoryEvent.bind(messageStore);
|
||||
vi.spyOn(messageStore, 'storeHistoryEvent').mockImplementationOnce(
|
||||
async (...args) => {
|
||||
await recall();
|
||||
return persist(...args);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
expect(messages.map((message) => message.message_seq)).toEqual([32743]);
|
||||
expect(messageStore.listSessionEvents(false, FRIEND_ID, 20)).toHaveLength(1);
|
||||
});
|
||||
const fetchLatestHistory = vi.fn(async () => [
|
||||
friendMessage(63213, FRIEND_ID, 32742),
|
||||
friendMessage(63214, SELF_ID, 32743),
|
||||
]);
|
||||
const ref = {
|
||||
selfId: SELF_ID,
|
||||
bridge: {
|
||||
resolveUserUid: vi.fn(async () => 'u_friend'),
|
||||
apis: { message: { getC2cLatestHistory: fetchLatestHistory } },
|
||||
},
|
||||
messageStore,
|
||||
converterCtx,
|
||||
} as any;
|
||||
|
||||
const messages = await getFriendHistory(ref, FRIEND_ID, undefined, 20);
|
||||
|
||||
expect(messages.map((message) => message.message_seq)).toEqual([32743]);
|
||||
expect(await messageStore.listSessionEvents(false, FRIEND_ID, 20)).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
|
||||
it('surfaces an unanchored server failure instead of returning incomplete local history', async () => {
|
||||
messageStore.storeEvent(1, false, FRIEND_ID, 12, PRIVATE_MESSAGE_EVENT, {
|
||||
await messageStore.storeEvent(1, false, FRIEND_ID, 12, PRIVATE_MESSAGE_EVENT, {
|
||||
time: 12,
|
||||
post_type: 'message',
|
||||
message_type: 'private',
|
||||
@@ -282,14 +307,14 @@ describe('history direction plumbing', () => {
|
||||
? [groupMessage(899), groupMessage(900)]
|
||||
: [groupMessage(900), groupMessage(901)],
|
||||
);
|
||||
messageStore.storeEvent(1, true, GROUP_ID, 900, GROUP_MESSAGE_EVENT, {
|
||||
await messageStore.storeEvent(1, true, GROUP_ID, 900, GROUP_MESSAGE_EVENT, {
|
||||
post_type: 'message',
|
||||
message_type: 'group',
|
||||
group_id: GROUP_ID,
|
||||
message_id: 1,
|
||||
message_seq: 900,
|
||||
});
|
||||
messageStore.storeEvent(
|
||||
await messageStore.storeEvent(
|
||||
2,
|
||||
true,
|
||||
GROUP_ID,
|
||||
@@ -323,7 +348,7 @@ describe('history direction plumbing', () => {
|
||||
|
||||
it('does not use an explicitly requested local-only id as a server history anchor', async () => {
|
||||
const fetchHistory = vi.fn(async () => [groupMessage(1799283572)]);
|
||||
messageStore.storeEvent(
|
||||
await messageStore.storeEvent(
|
||||
2,
|
||||
true,
|
||||
GROUP_ID,
|
||||
@@ -355,7 +380,7 @@ describe('history direction plumbing', () => {
|
||||
|
||||
it('rejects a private anchor from a different friend conversation', async () => {
|
||||
const fetchHistory = vi.fn(async () => [friendMessage(800, FRIEND_ID)]);
|
||||
messageStore.storeMeta(-111111111, {
|
||||
await messageStore.storeMeta(-111111111, {
|
||||
isGroup: false,
|
||||
targetId: 987654321,
|
||||
sequence: 800,
|
||||
|
||||
@@ -62,13 +62,14 @@ function converterContext(): ConverterContext {
|
||||
};
|
||||
}
|
||||
|
||||
function makeStore(): { store: MessageStore; close(): void } {
|
||||
async function makeStore(): Promise<{ store: MessageStore; close(): Promise<void> }> {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-history-sync-'));
|
||||
const store = new MessageStore(path.join(dir, 'messages.db'));
|
||||
await store.initialization;
|
||||
return {
|
||||
store,
|
||||
close: () => {
|
||||
store.close();
|
||||
close: async () => {
|
||||
await store.close();
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
@@ -122,10 +123,10 @@ function makeBridge(
|
||||
} as unknown as BridgeInterface;
|
||||
}
|
||||
|
||||
const resources: Array<ReturnType<typeof makeStore>> = [];
|
||||
afterEach(() => {
|
||||
const resources: Array<Awaited<ReturnType<typeof makeStore>>> = [];
|
||||
afterEach(async () => {
|
||||
for (const resource of resources.splice(0)) {
|
||||
resource.close();
|
||||
await resource.close();
|
||||
}
|
||||
|
||||
vi.restoreAllMocks();
|
||||
@@ -139,7 +140,7 @@ describe('login history sync', () => {
|
||||
delays.push(ms);
|
||||
},
|
||||
});
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const bridge = makeBridge();
|
||||
|
||||
@@ -197,7 +198,7 @@ describe('login history sync', () => {
|
||||
groupPage,
|
||||
privateLatestPage,
|
||||
});
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
|
||||
|
||||
@@ -242,7 +243,7 @@ describe('login history sync', () => {
|
||||
friendCount: LOGIN_HISTORY_SYNC_LIMITS.scannedPrivateUsers + 1,
|
||||
probe,
|
||||
});
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
|
||||
|
||||
@@ -266,7 +267,7 @@ describe('login history sync', () => {
|
||||
});
|
||||
|
||||
it('fills a known local gap from its oldest missing sequence', async () => {
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const local = groupMessage(30001, 50);
|
||||
const localEvent = {
|
||||
@@ -277,7 +278,7 @@ describe('login history sync', () => {
|
||||
message_seq: 50,
|
||||
group_id: 30001,
|
||||
};
|
||||
resource.store.storeEvent(123, true, 30001, 50, 'group_message', localEvent);
|
||||
await resource.store.storeEvent(123, true, 30001, 50, 'group_message', localEvent);
|
||||
|
||||
const groupPage = vi.fn(async () => []);
|
||||
const bridge = makeBridge({
|
||||
@@ -304,9 +305,9 @@ describe('login history sync', () => {
|
||||
});
|
||||
|
||||
it('backfills past a newer metadata-only authoritative row', async () => {
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
resource.store.storeEvent(123, true, 30001, 50, 'group_message', {
|
||||
await resource.store.storeEvent(123, true, 30001, 50, 'group_message', {
|
||||
time: 1_700_000_050,
|
||||
post_type: 'message',
|
||||
message_type: 'group',
|
||||
@@ -314,7 +315,7 @@ describe('login history sync', () => {
|
||||
message_seq: 50,
|
||||
group_id: 30001,
|
||||
});
|
||||
resource.store.storeMeta(124, {
|
||||
await resource.store.storeMeta(124, {
|
||||
isGroup: true,
|
||||
targetId: 30001,
|
||||
sequence: 100,
|
||||
@@ -324,8 +325,8 @@ describe('login history sync', () => {
|
||||
random: 0,
|
||||
timestamp: 1_700_000_100,
|
||||
});
|
||||
expect(resource.store.findLatestAuthoritativeSequence(true, 30001)).toBe(100);
|
||||
expect(resource.store.findLatestPersistedAuthoritativeSequence(true, 30001)).toBe(50);
|
||||
expect(await resource.store.findLatestAuthoritativeSequence(true, 30001)).toBe(100);
|
||||
expect(await resource.store.findLatestPersistedAuthoritativeSequence(true, 30001)).toBe(50);
|
||||
|
||||
const groupPage = vi.fn(async () => []);
|
||||
const bridge = makeBridge({
|
||||
@@ -352,9 +353,9 @@ describe('login history sync', () => {
|
||||
});
|
||||
|
||||
it('backfills a metadata-only session even when the server read cursor is current', async () => {
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
resource.store.storeMeta(124, {
|
||||
await resource.store.storeMeta(124, {
|
||||
isGroup: true,
|
||||
targetId: 30001,
|
||||
sequence: 100,
|
||||
@@ -364,7 +365,9 @@ describe('login history sync', () => {
|
||||
random: 0,
|
||||
timestamp: 1_700_000_100,
|
||||
});
|
||||
expect(resource.store.findLatestPersistedAuthoritativeSequence(true, 30001)).toBeNull();
|
||||
expect(
|
||||
await resource.store.findLatestPersistedAuthoritativeSequence(true, 30001),
|
||||
).toBeNull();
|
||||
|
||||
const groupPage = vi.fn(async () => []);
|
||||
const bridge = makeBridge({
|
||||
@@ -391,9 +394,9 @@ describe('login history sync', () => {
|
||||
});
|
||||
|
||||
it('uses the authoritative private sequence for a known local gap', async () => {
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
resource.store.storeEvent(
|
||||
await resource.store.storeEvent(
|
||||
456,
|
||||
false,
|
||||
40001,
|
||||
@@ -472,7 +475,7 @@ describe('login history sync', () => {
|
||||
})),
|
||||
groupPage,
|
||||
});
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
|
||||
|
||||
@@ -507,7 +510,7 @@ describe('login history sync', () => {
|
||||
})),
|
||||
groupPage,
|
||||
});
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
|
||||
|
||||
@@ -535,51 +538,73 @@ describe('login history sync', () => {
|
||||
).resolves.toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not restore a private message hidden by a recall tombstone', async () => {
|
||||
const resource = makeStore();
|
||||
resources.push(resource);
|
||||
const recalled = friendMessage(40001, 1);
|
||||
resource.store.recordPrivateRecall(40001, recalled.clientSeq!, false, recalled.time + 1);
|
||||
const bridge = makeBridge({
|
||||
groupCount: 0,
|
||||
probe: vi.fn(async () => ({
|
||||
groups: [],
|
||||
privateUsers: [
|
||||
{
|
||||
userId: 40001,
|
||||
uid: 'u_40001',
|
||||
readSeq: 0,
|
||||
latestSeq: 1,
|
||||
lastMsgTime: recalled.time,
|
||||
it.each(['before reading', 'before persistence'] as const)(
|
||||
'does not restore or count a private message recalled %s',
|
||||
async (timing) => {
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const recalled = friendMessage(40001, 1);
|
||||
const recall = () =>
|
||||
resource.store.recordPrivateRecall(
|
||||
40001,
|
||||
recalled.clientSeq!,
|
||||
false,
|
||||
recalled.time + 1,
|
||||
);
|
||||
|
||||
if (timing === 'before reading') {
|
||||
await recall();
|
||||
} else {
|
||||
const persist = resource.store.storeHistoryEvent.bind(resource.store);
|
||||
vi.spyOn(resource.store, 'storeHistoryEvent').mockImplementationOnce(
|
||||
async (...args) => {
|
||||
await recall();
|
||||
return persist(...args);
|
||||
},
|
||||
],
|
||||
})),
|
||||
privateLatestPage: vi.fn(async () => [recalled]),
|
||||
});
|
||||
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
|
||||
);
|
||||
}
|
||||
|
||||
const result = await coordinator.schedule(
|
||||
{
|
||||
selfId: SELF_ID,
|
||||
bridge,
|
||||
messageStore: resource.store,
|
||||
converterCtx: converterContext(),
|
||||
},
|
||||
new AbortController().signal,
|
||||
);
|
||||
const bridge = makeBridge({
|
||||
groupCount: 0,
|
||||
probe: vi.fn(async () => ({
|
||||
groups: [],
|
||||
privateUsers: [
|
||||
{
|
||||
userId: 40001,
|
||||
uid: 'u_40001',
|
||||
readSeq: 0,
|
||||
latestSeq: 1,
|
||||
lastMsgTime: recalled.time,
|
||||
},
|
||||
],
|
||||
})),
|
||||
privateLatestPage: vi.fn(async () => [recalled]),
|
||||
});
|
||||
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
fetchedMessages: 1,
|
||||
storedMessages: 0,
|
||||
failedSessions: 0,
|
||||
});
|
||||
await expect(getFriendMsgHistory(resource.store, 40001, undefined, 20)).resolves.toEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
const result = await coordinator.schedule(
|
||||
{
|
||||
selfId: SELF_ID,
|
||||
bridge,
|
||||
messageStore: resource.store,
|
||||
converterCtx: converterContext(),
|
||||
},
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
fetchedMessages: 1,
|
||||
storedMessages: 0,
|
||||
failedSessions: 0,
|
||||
});
|
||||
await expect(
|
||||
getFriendMsgHistory(resource.store, 40001, undefined, 20),
|
||||
).resolves.toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects private history attributed to a different peer', async () => {
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const bridge = makeBridge({
|
||||
groupCount: 0,
|
||||
@@ -629,7 +654,7 @@ describe('login history sync', () => {
|
||||
const mediaUrlResolver = vi.fn(async () => {
|
||||
throw new Error('media resolver must not run');
|
||||
});
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const bridge = makeBridge({
|
||||
friendCount: 0,
|
||||
@@ -682,8 +707,8 @@ describe('login history sync', () => {
|
||||
}),
|
||||
);
|
||||
const secondProbe = vi.fn(async () => ({ groups: [], privateUsers: [] }));
|
||||
const firstStore = makeStore();
|
||||
const secondStore = makeStore();
|
||||
const firstStore = await makeStore();
|
||||
const secondStore = await makeStore();
|
||||
resources.push(firstStore, secondStore);
|
||||
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
|
||||
|
||||
@@ -726,9 +751,9 @@ describe('login history sync', () => {
|
||||
);
|
||||
const cancelledProbe = vi.fn(async () => ({ groups: [], privateUsers: [] }));
|
||||
const thirdProbe = vi.fn(async () => ({ groups: [], privateUsers: [] }));
|
||||
const firstStore = makeStore();
|
||||
const cancelledStore = makeStore();
|
||||
const thirdStore = makeStore();
|
||||
const firstStore = await makeStore();
|
||||
const cancelledStore = await makeStore();
|
||||
const thirdStore = await makeStore();
|
||||
resources.push(firstStore, cancelledStore, thirdStore);
|
||||
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
|
||||
const cancelledController = new AbortController();
|
||||
@@ -782,7 +807,7 @@ describe('login history sync', () => {
|
||||
releasePage = () => resolve([groupMessage(30001, 1)]);
|
||||
}),
|
||||
);
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const bridge = makeBridge({
|
||||
friendCount: 0,
|
||||
@@ -815,7 +840,7 @@ describe('login history sync', () => {
|
||||
});
|
||||
|
||||
it('stops conversion side effects when disposal happens during conversion', async () => {
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const controller = new AbortController();
|
||||
const mediaSegmentSink = vi.fn();
|
||||
@@ -867,7 +892,7 @@ describe('login history sync', () => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
}),
|
||||
});
|
||||
const resource = makeStore();
|
||||
const resource = await makeStore();
|
||||
resources.push(resource);
|
||||
const controller = new AbortController();
|
||||
|
||||
|
||||
@@ -327,7 +327,7 @@ describe('buildApiContext getLoginInfo', () => {
|
||||
});
|
||||
|
||||
describe('buildApiContext message-store passthroughs', () => {
|
||||
it('reads events and metas through the message store', () => {
|
||||
it('reads events and metas through the message store', async () => {
|
||||
const storedEvent = {
|
||||
post_type: 'message',
|
||||
message_type: 'group',
|
||||
@@ -339,14 +339,14 @@ describe('buildApiContext message-store passthroughs', () => {
|
||||
events.set(-55, storedEvent);
|
||||
metas.set(-55, storedMeta);
|
||||
|
||||
expect(api.getMessage(-55)).toEqual({
|
||||
expect(await api.getMessage(-55)).toEqual({
|
||||
post_type: 'message',
|
||||
message_type: 'group',
|
||||
message_id: -55,
|
||||
raw_message: 'stored',
|
||||
});
|
||||
expect(api.getMessage(1)).toBeNull();
|
||||
expect(api.getMessageMeta(-55)).toEqual({
|
||||
expect(await api.getMessage(1)).toBeNull();
|
||||
expect(await api.getMessageMeta(-55)).toEqual({
|
||||
isGroup: true,
|
||||
targetId: GROUP_ID,
|
||||
sequence: 91,
|
||||
@@ -358,18 +358,18 @@ describe('buildApiContext message-store passthroughs', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('stores meta batches on the message store', () => {
|
||||
it('stores meta batches on the message store', async () => {
|
||||
const storeMetas = vi.fn();
|
||||
const { api } = makeRef({ messageStore: { storeMetas } });
|
||||
const entries = [{ messageId: -12, meta: privateMeta({ sequence: 8 }) }];
|
||||
|
||||
api.cacheMessageMetas(entries);
|
||||
await api.cacheMessageMetas(entries);
|
||||
|
||||
expect(storeMetas).toHaveBeenCalledOnce();
|
||||
expect(storeMetas).toHaveBeenCalledWith(entries);
|
||||
});
|
||||
|
||||
it('lists read sessions from the current identity group ids', () => {
|
||||
it('lists read sessions from the current identity group ids', async () => {
|
||||
const listReadSessions = vi.fn(() => ({
|
||||
groupIds: [710101, 710102],
|
||||
privateUserIds: [50001],
|
||||
@@ -381,7 +381,7 @@ describe('buildApiContext message-store passthroughs', () => {
|
||||
messageStore: { listReadSessions },
|
||||
});
|
||||
|
||||
expect(api.listReadSessions()).toEqual({
|
||||
expect(await api.listReadSessions()).toEqual({
|
||||
groupIds: [710101, 710102],
|
||||
privateUserIds: [50001],
|
||||
});
|
||||
@@ -1059,7 +1059,7 @@ describe('buildApiContext media', () => {
|
||||
await expect(api.getImageInfo('missing.jpg')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns cached record info and refetches a missing group ptt url', async () => {
|
||||
it('resolves indexed record info through the group ptt API', async () => {
|
||||
const getPttUrl = vi.fn(async () => 'https://ptt.example/group');
|
||||
const updateRecordUrl = vi.fn();
|
||||
const mediaNode = { fileUuid: 'uuid-1' };
|
||||
|
||||
@@ -776,218 +776,72 @@ describe('getImageInfo', () => {
|
||||
});
|
||||
|
||||
describe('getRecordInfo', () => {
|
||||
it('returns null when the record is not cached', async () => {
|
||||
it('returns null when the record is not indexed', async () => {
|
||||
await expect(
|
||||
getRecordInfo(fakeBridge(), fakeRecordStore(null), 'missing.silk'),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns the stored url without refetching', async () => {
|
||||
const getPttUrl = vi.fn(async () => 'https://ptt.example/should-not-run');
|
||||
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/should-not-run');
|
||||
const updateRecordUrl = vi.fn();
|
||||
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge({ getPttUrl, getPrivatePttUrl }),
|
||||
fakeRecordStore(
|
||||
cachedRecord({
|
||||
url: 'https://ptt.example/cached.silk',
|
||||
mediaNode: { fileUuid: 'uuid-1' },
|
||||
it.each([true, false])(
|
||||
'requests a fresh URL even when one is stored (group=%s)',
|
||||
async (isGroup) => {
|
||||
const mediaNode = { fileUuid: 'voice-uuid', storeId: 1 };
|
||||
const getPttUrl = vi.fn(async () => 'https://ptt.example/group-fresh');
|
||||
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private-fresh');
|
||||
const updateRecordUrl = vi.fn();
|
||||
const url = `https://ptt.example/${isGroup ? 'group' : 'private'}-fresh`;
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge({ getPttUrl, getPrivatePttUrl }),
|
||||
fakeRecordStore(cachedRecord({ isGroup, sessionId: GROUP_ID, mediaNode }), {
|
||||
updateRecordUrl,
|
||||
}),
|
||||
{ updateRecordUrl },
|
||||
'voice.silk',
|
||||
),
|
||||
'voice.silk',
|
||||
),
|
||||
).resolves.toEqual({
|
||||
file: 'https://ptt.example/cached.silk',
|
||||
url: 'https://ptt.example/cached.silk',
|
||||
file_size: '4096',
|
||||
file_name: 'voice.silk',
|
||||
});
|
||||
expect(getPttUrl).not.toHaveBeenCalled();
|
||||
expect(getPrivatePttUrl).not.toHaveBeenCalled();
|
||||
expect(updateRecordUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
).resolves.toEqual({ file: url, url, file_size: '4096', file_name: 'voice.silk' });
|
||||
|
||||
it('does not refetch when the url is empty and there is no mediaNode', async () => {
|
||||
const getPttUrl = vi.fn(async () => 'https://ptt.example/group');
|
||||
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private');
|
||||
if (isGroup) {
|
||||
expect(getPttUrl).toHaveBeenCalledWith(GROUP_ID, mediaNode);
|
||||
expect(getPrivatePttUrl).not.toHaveBeenCalled();
|
||||
} else {
|
||||
expect(getPrivatePttUrl).toHaveBeenCalledWith(mediaNode);
|
||||
expect(getPttUrl).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
expect(updateRecordUrl).toHaveBeenCalledWith('voice.silk', url);
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects missing resource metadata even when an old URL exists', async () => {
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge({ getPttUrl, getPrivatePttUrl }),
|
||||
fakeRecordStore(cachedRecord({ url: '', mediaNode: undefined })),
|
||||
'voice.silk',
|
||||
),
|
||||
).resolves.toEqual({
|
||||
file: 'voice.silk',
|
||||
url: '',
|
||||
file_size: '4096',
|
||||
file_name: 'voice.silk',
|
||||
});
|
||||
expect(getPttUrl).not.toHaveBeenCalled();
|
||||
expect(getPrivatePttUrl).not.toHaveBeenCalled();
|
||||
getRecordInfo(fakeBridge(), fakeRecordStore(cachedRecord()), 'voice.silk'),
|
||||
).rejects.toThrow('record media metadata is missing');
|
||||
});
|
||||
|
||||
it('refetches a group ptt url and writes it back under the lookup key', async () => {
|
||||
const mediaNode = { fileUuid: 'group-uuid', storeId: 1 };
|
||||
const getPttUrl = vi.fn(async () => 'https://ptt.example/group-fresh');
|
||||
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private');
|
||||
const updateRecordUrl = vi.fn();
|
||||
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge({ getPttUrl, getPrivatePttUrl }),
|
||||
fakeRecordStore(
|
||||
cachedRecord({
|
||||
file: 'primary.silk',
|
||||
url: '',
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
mediaNode,
|
||||
}),
|
||||
{ updateRecordUrl },
|
||||
),
|
||||
'alias.silk',
|
||||
),
|
||||
).resolves.toEqual({
|
||||
file: 'https://ptt.example/group-fresh',
|
||||
url: 'https://ptt.example/group-fresh',
|
||||
file_size: '4096',
|
||||
file_name: 'voice.silk',
|
||||
});
|
||||
expect(getPttUrl).toHaveBeenCalledWith(710010, mediaNode);
|
||||
expect(getPrivatePttUrl).not.toHaveBeenCalled();
|
||||
expect(updateRecordUrl).toHaveBeenCalledWith(
|
||||
'alias.silk',
|
||||
'https://ptt.example/group-fresh',
|
||||
);
|
||||
});
|
||||
|
||||
it('refetches a private ptt url from the media node only', async () => {
|
||||
const mediaNode = { fileUuid: 'c2c-uuid' };
|
||||
const getPttUrl = vi.fn(async () => 'https://ptt.example/group');
|
||||
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private-fresh');
|
||||
const updateRecordUrl = vi.fn();
|
||||
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge({ getPttUrl, getPrivatePttUrl }),
|
||||
fakeRecordStore(
|
||||
cachedRecord({
|
||||
url: '',
|
||||
isGroup: false,
|
||||
mediaNode,
|
||||
}),
|
||||
{ updateRecordUrl },
|
||||
),
|
||||
'voice.silk',
|
||||
),
|
||||
).resolves.toEqual({
|
||||
file: 'https://ptt.example/private-fresh',
|
||||
url: 'https://ptt.example/private-fresh',
|
||||
file_size: '4096',
|
||||
file_name: 'voice.silk',
|
||||
});
|
||||
expect(getPrivatePttUrl).toHaveBeenCalledWith(mediaNode);
|
||||
expect(getPttUrl).not.toHaveBeenCalled();
|
||||
expect(updateRecordUrl).toHaveBeenCalledWith(
|
||||
'voice.silk',
|
||||
'https://ptt.example/private-fresh',
|
||||
);
|
||||
});
|
||||
|
||||
it('does not write back an empty refetch result', async () => {
|
||||
const updateRecordUrl = vi.fn();
|
||||
const getPrivatePttUrl = vi.fn(async () => '');
|
||||
|
||||
it('propagates remote errors instead of returning the cached URL', async () => {
|
||||
const failure = new Error('QQ resource expired');
|
||||
const getPrivatePttUrl = vi.fn().mockRejectedValue(failure);
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge({ getPrivatePttUrl }),
|
||||
fakeRecordStore(
|
||||
cachedRecord({
|
||||
url: '',
|
||||
mediaNode: { fileUuid: 'empty-uuid' },
|
||||
}),
|
||||
{ updateRecordUrl },
|
||||
),
|
||||
fakeRecordStore(cachedRecord({ mediaNode: { fileUuid: 'voice-uuid' } })),
|
||||
'voice.silk',
|
||||
),
|
||||
).resolves.toEqual({
|
||||
file: 'voice.silk',
|
||||
url: '',
|
||||
file_size: '4096',
|
||||
file_name: 'voice.silk',
|
||||
});
|
||||
expect(updateRecordUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns the cached file after a refetch Error', async () => {
|
||||
const updateRecordUrl = vi.fn();
|
||||
const getPttUrl = vi.fn(async () => {
|
||||
throw new Error('cdn timeout');
|
||||
});
|
||||
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge({ getPttUrl }),
|
||||
fakeRecordStore(
|
||||
cachedRecord({
|
||||
file: 'keep.silk',
|
||||
url: '',
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
mediaNode: { fileUuid: 'fail-uuid' },
|
||||
}),
|
||||
{ updateRecordUrl },
|
||||
),
|
||||
'keep.silk',
|
||||
),
|
||||
).resolves.toEqual({
|
||||
file: 'keep.silk',
|
||||
url: '',
|
||||
file_size: '4096',
|
||||
file_name: 'voice.silk',
|
||||
});
|
||||
expect(updateRecordUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns the cached file after a non-Error refetch rejection', async () => {
|
||||
const getPrivatePttUrl = vi.fn(async () => {
|
||||
throw 'offline';
|
||||
});
|
||||
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge({ getPrivatePttUrl }),
|
||||
fakeRecordStore(
|
||||
cachedRecord({
|
||||
url: '',
|
||||
isGroup: false,
|
||||
mediaNode: { fileUuid: 'offline-uuid' },
|
||||
}),
|
||||
),
|
||||
'voice.silk',
|
||||
),
|
||||
).resolves.toEqual({
|
||||
file: 'voice.silk',
|
||||
url: '',
|
||||
file_size: '4096',
|
||||
file_name: 'voice.silk',
|
||||
});
|
||||
).rejects.toBe(failure);
|
||||
});
|
||||
|
||||
it('stringifies a missing fileSize as 0 and falls file_name back to file', async () => {
|
||||
await expect(
|
||||
getRecordInfo(
|
||||
fakeBridge(),
|
||||
fakeBridge({
|
||||
getPrivatePttUrl: vi.fn(async () => 'https://ptt.example/named.silk'),
|
||||
}),
|
||||
fakeRecordStore(
|
||||
cachedRecord({
|
||||
file: 'fallback.silk',
|
||||
fileName: '',
|
||||
fileSize: undefined as unknown as number,
|
||||
url: 'https://ptt.example/named.silk',
|
||||
mediaNode: { fileUuid: 'voice-uuid' },
|
||||
}),
|
||||
),
|
||||
'fallback.silk',
|
||||
|
||||
@@ -11,7 +11,7 @@ function makeMediaStore() {
|
||||
}
|
||||
|
||||
describe('MediaIndexer', () => {
|
||||
it('image: maps element fields into rememberImage with file fallback to fileId', () => {
|
||||
it('image: maps element fields into rememberImage with file fallback to fileId', async () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
@@ -27,7 +27,7 @@ describe('MediaIndexer', () => {
|
||||
height: 600,
|
||||
picFormat: 1000,
|
||||
};
|
||||
indexer.remember('image', element, { url: 'http://x', file: '' }, true, 99999);
|
||||
await indexer.remember('image', element, { url: 'http://x', file: '' }, true, 99999);
|
||||
|
||||
expect(store.rememberImage).toHaveBeenCalledOnce();
|
||||
const arg = store.rememberImage.mock.calls[0]![0];
|
||||
@@ -48,7 +48,7 @@ describe('MediaIndexer', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('record: maps element fields into rememberRecord with file fallback chain', () => {
|
||||
it('record: maps element fields into rememberRecord with file fallback chain', async () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
@@ -63,7 +63,7 @@ describe('MediaIndexer', () => {
|
||||
sha1Hex: 's',
|
||||
voiceFormat: 1,
|
||||
};
|
||||
indexer.remember('record', element, { url: 'http://r', file: '' }, false, 12345);
|
||||
await indexer.remember('record', element, { url: 'http://r', file: '' }, false, 12345);
|
||||
|
||||
const arg = store.rememberRecord.mock.calls[0]![0];
|
||||
expect(arg.file).toBe('voice.amr'); // data.file '' → element.fileName
|
||||
@@ -74,7 +74,7 @@ describe('MediaIndexer', () => {
|
||||
expect(arg.voiceFormat).toBe(1);
|
||||
});
|
||||
|
||||
it('video: maps element fields into rememberVideo', () => {
|
||||
it('video: maps element fields into rememberVideo', async () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = {
|
||||
@@ -87,7 +87,13 @@ describe('MediaIndexer', () => {
|
||||
height: 1080,
|
||||
videoFormat: 2,
|
||||
};
|
||||
indexer.remember('video', element, { url: 'http://v', file: 'override.mp4' }, true, 11111);
|
||||
await indexer.remember(
|
||||
'video',
|
||||
element,
|
||||
{ url: 'http://v', file: 'override.mp4' },
|
||||
true,
|
||||
11111,
|
||||
);
|
||||
|
||||
const arg = store.rememberVideo.mock.calls[0]![0];
|
||||
expect(arg.file).toBe('override.mp4'); // data.file used when non-empty
|
||||
@@ -97,18 +103,18 @@ describe('MediaIndexer', () => {
|
||||
expect(arg.videoFormat).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back to element.fileId when data.file AND element.fileName are missing (record)', () => {
|
||||
it('falls back to element.fileId when data.file AND element.fileName are missing (record)', async () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
const element: MessageElement = { type: 'record', fileId: 'only-fid' };
|
||||
indexer.remember('record', element, { url: '', file: '' }, false, 1);
|
||||
await indexer.remember('record', element, { url: '', file: '' }, false, 1);
|
||||
expect(store.rememberRecord.mock.calls[0]![0].file).toBe('only-fid');
|
||||
});
|
||||
|
||||
it('defaults missing numeric fields to 0 / missing strings to ""', () => {
|
||||
it('defaults missing numeric fields to 0 / missing strings to ""', async () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
indexer.remember('image', { type: 'image' }, { url: '', file: '' }, false, 0);
|
||||
await indexer.remember('image', { type: 'image' }, { url: '', file: '' }, false, 0);
|
||||
const arg = store.rememberImage.mock.calls[0]![0];
|
||||
expect(arg.fileSize).toBe(0);
|
||||
expect(arg.subType).toBe(0);
|
||||
@@ -116,10 +122,10 @@ describe('MediaIndexer', () => {
|
||||
expect(arg.imageUrl).toBe('');
|
||||
});
|
||||
|
||||
it('only the matching rememberX is called', () => {
|
||||
it('only the matching rememberX is called', async () => {
|
||||
const store = makeMediaStore();
|
||||
const indexer = new MediaIndexer(store as any);
|
||||
indexer.remember('image', { type: 'image' }, { url: '', file: 'a' }, true, 1);
|
||||
await indexer.remember('image', { type: 'image' }, { url: '', file: 'a' }, true, 1);
|
||||
expect(store.rememberImage).toHaveBeenCalledOnce();
|
||||
expect(store.rememberRecord).not.toHaveBeenCalled();
|
||||
expect(store.rememberVideo).not.toHaveBeenCalled();
|
||||
|
||||
@@ -96,9 +96,9 @@ describe('MediaStore basic semantics', () => {
|
||||
return max !== undefined ? new MediaStore(dbPath, max) : new MediaStore(dbPath);
|
||||
}
|
||||
|
||||
it('indexes images by file, fileName, and url', () => {
|
||||
it('indexes images by file, fileName, and url', async () => {
|
||||
const store = open('img-keys');
|
||||
store.rememberImage({
|
||||
await store.rememberImage({
|
||||
file: 'abc.png',
|
||||
url: 'https://example.com/abc.png',
|
||||
fileSize: 4242,
|
||||
@@ -110,18 +110,18 @@ describe('MediaStore basic semantics', () => {
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
|
||||
expect(store.findImage('abc.png')?.fileSize).toBe(4242);
|
||||
expect(store.findImage('https://example.com/abc.png')?.url).toBe(
|
||||
expect((await store.findImage('abc.png'))?.fileSize).toBe(4242);
|
||||
expect((await store.findImage('https://example.com/abc.png'))?.url).toBe(
|
||||
'https://example.com/abc.png',
|
||||
);
|
||||
expect(store.findImage('missing.png')).toBeNull();
|
||||
expect(store.findImage('')).toBeNull();
|
||||
store.close();
|
||||
expect(await store.findImage('missing.png')).toBeNull();
|
||||
expect(await store.findImage('')).toBeNull();
|
||||
await store.close();
|
||||
});
|
||||
|
||||
it('indexes records by file, fileName, fileId, and url', () => {
|
||||
it('indexes records by file, fileName, fileId, and url', async () => {
|
||||
const store = open('rec-keys');
|
||||
store.rememberRecord({
|
||||
await store.rememberRecord({
|
||||
file: 'silk_test.amr',
|
||||
fileId: 'uuid-base64-fake',
|
||||
url: 'https://example.com/voice.amr',
|
||||
@@ -134,18 +134,18 @@ describe('MediaStore basic semantics', () => {
|
||||
sessionId: PEER_UIN,
|
||||
});
|
||||
|
||||
expect(store.findRecord('silk_test.amr')?.duration).toBe(3);
|
||||
expect(store.findRecord('uuid-base64-fake')?.fileId).toBe('uuid-base64-fake');
|
||||
expect(store.findRecord('https://example.com/voice.amr')?.url).toBe(
|
||||
expect((await store.findRecord('silk_test.amr'))?.duration).toBe(3);
|
||||
expect((await store.findRecord('uuid-base64-fake'))?.fileId).toBe('uuid-base64-fake');
|
||||
expect((await store.findRecord('https://example.com/voice.amr'))?.url).toBe(
|
||||
'https://example.com/voice.amr',
|
||||
);
|
||||
expect(store.findRecord('nope')).toBeNull();
|
||||
store.close();
|
||||
expect(await store.findRecord('nope')).toBeNull();
|
||||
await store.close();
|
||||
});
|
||||
|
||||
it('updates URLs in place across all alias keys', () => {
|
||||
it('updates URLs in place across all alias keys', async () => {
|
||||
const store = open('url-update');
|
||||
store.rememberRecord({
|
||||
await store.rememberRecord({
|
||||
file: 'silk_test.amr',
|
||||
fileId: 'uuid-base64-fake',
|
||||
url: '',
|
||||
@@ -157,24 +157,25 @@ describe('MediaStore basic semantics', () => {
|
||||
isGroup: false,
|
||||
sessionId: PEER_UIN,
|
||||
});
|
||||
store.updateRecordUrl('silk_test.amr', 'https://refreshed.example.com/voice.amr');
|
||||
await store.updateRecordUrl('silk_test.amr', 'https://refreshed.example.com/voice.amr');
|
||||
|
||||
expect(store.findRecord('silk_test.amr')?.url).toBe(
|
||||
expect((await store.findRecord('silk_test.amr'))?.url).toBe(
|
||||
'https://refreshed.example.com/voice.amr',
|
||||
);
|
||||
expect(store.findRecord('uuid-base64-fake')?.url).toBe(
|
||||
expect((await store.findRecord('uuid-base64-fake'))?.url).toBe(
|
||||
'https://refreshed.example.com/voice.amr',
|
||||
);
|
||||
store.close();
|
||||
await store.close();
|
||||
});
|
||||
|
||||
it('survives close+reopen against the same db path', () => {
|
||||
it('survives close+reopen against the same db path', async () => {
|
||||
const dbPath = tempDbPath('persist');
|
||||
dbs.push(dbPath);
|
||||
|
||||
{
|
||||
const store = new MediaStore(dbPath);
|
||||
store.rememberImage({
|
||||
await store.initialization;
|
||||
await store.rememberImage({
|
||||
file: 'abc.png',
|
||||
url: 'https://example.com/abc.png',
|
||||
fileSize: 99,
|
||||
@@ -185,27 +186,28 @@ describe('MediaStore basic semantics', () => {
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
store.close();
|
||||
await store.close();
|
||||
}
|
||||
|
||||
{
|
||||
const store = new MediaStore(dbPath);
|
||||
const found = store.findImage('abc.png');
|
||||
await store.initialization;
|
||||
const found = await store.findImage('abc.png');
|
||||
expect(found).not.toBeNull();
|
||||
expect(found!.fileSize).toBe(99);
|
||||
// Alias index must also persist.
|
||||
expect(store.findImage('https://example.com/abc.png')?.fileSize).toBe(99);
|
||||
store.close();
|
||||
expect((await store.findImage('https://example.com/abc.png'))?.fileSize).toBe(99);
|
||||
await store.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('retains durable entries beyond the memory cache cap', () => {
|
||||
it('retains durable entries beyond the memory cache cap', async () => {
|
||||
// Lookups can be evicted from memory, but historical metadata survives.
|
||||
const cap = 80;
|
||||
const store = open('evict', cap);
|
||||
|
||||
for (let i = 0; i < 200; i++) {
|
||||
store.rememberImage({
|
||||
await store.rememberImage({
|
||||
file: `file-${i}.png`,
|
||||
url: `https://example.com/${i}.png`,
|
||||
fileSize: i,
|
||||
@@ -218,23 +220,23 @@ describe('MediaStore basic semantics', () => {
|
||||
});
|
||||
}
|
||||
|
||||
const { images } = store.size();
|
||||
const { images } = await store.size();
|
||||
expect(images).toBe(200);
|
||||
|
||||
for (let i = 0; i < 200; i++) {
|
||||
expect(store.findImage(`file-${i}.png`)?.fileSize).toBe(i);
|
||||
expect((await store.findImage(`file-${i}.png`))?.fileSize).toBe(i);
|
||||
}
|
||||
|
||||
expect(store.findImage('file-0.png')?.fileSize).toBe(0);
|
||||
expect((await store.findImage('file-0.png'))?.fileSize).toBe(0);
|
||||
// Most recent entries should still be present.
|
||||
expect(store.findImage('file-199.png')?.fileSize).toBe(199);
|
||||
store.close();
|
||||
expect((await store.findImage('file-199.png'))?.fileSize).toBe(199);
|
||||
await store.close();
|
||||
});
|
||||
|
||||
it('does not persist inline base64 as a key or JSON payload (#463)', () => {
|
||||
it('does not persist inline base64 as a key or JSON payload (#463)', async () => {
|
||||
const store = open('inline-b64');
|
||||
const payload = `base64://${'A'.repeat(8192)}`;
|
||||
store.rememberImage({
|
||||
await store.rememberImage({
|
||||
file: payload,
|
||||
url: payload,
|
||||
fileSize: 99,
|
||||
@@ -249,7 +251,7 @@ describe('MediaStore basic semantics', () => {
|
||||
height: 600,
|
||||
});
|
||||
|
||||
const found = store.findImage(payload);
|
||||
const found = await store.findImage(payload);
|
||||
expect(found).not.toBeNull();
|
||||
expect(found!.fileSize).toBe(99);
|
||||
expect(found!.md5Hex).toBe('aa'.repeat(16));
|
||||
@@ -258,7 +260,7 @@ describe('MediaStore basic semantics', () => {
|
||||
expect(found!.file.startsWith('inline:')).toBe(true);
|
||||
expect(found!.file.includes('base64://')).toBe(false);
|
||||
|
||||
store.close();
|
||||
await store.close();
|
||||
const rows = inspectMediaDb(dbs[dbs.length - 1]!);
|
||||
expect(rows.longestKey).toBeLessThanOrEqual(MEDIA_KEY_MAX_CHARS);
|
||||
expect(rows.longestData).toBeLessThanOrEqual(MEDIA_DATA_MAX_CHARS);
|
||||
@@ -267,10 +269,10 @@ describe('MediaStore basic semantics', () => {
|
||||
expect(rows.concatenated).not.toContain('A'.repeat(64));
|
||||
});
|
||||
|
||||
it('folds oversized non-inline keys the same way', () => {
|
||||
it('folds oversized non-inline keys the same way', async () => {
|
||||
const store = open('long-url');
|
||||
const url = `https://cdn.example/${'a'.repeat(3000)}.png`;
|
||||
store.rememberImage({
|
||||
await store.rememberImage({
|
||||
file: 'short.png',
|
||||
url,
|
||||
fileSize: 12,
|
||||
@@ -282,18 +284,18 @@ describe('MediaStore basic semantics', () => {
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
|
||||
expect(store.findImage('short.png')?.fileSize).toBe(12);
|
||||
expect(store.findImage(url)?.fileSize).toBe(12);
|
||||
expect(store.findImage('short.png')?.url).toBe('');
|
||||
store.close();
|
||||
expect((await store.findImage('short.png'))?.fileSize).toBe(12);
|
||||
expect((await store.findImage(url))?.fileSize).toBe(12);
|
||||
expect((await store.findImage('short.png'))?.url).toBe('');
|
||||
await store.close();
|
||||
const rows = inspectMediaDb(dbs[dbs.length - 1]!);
|
||||
expect(rows.longestKey).toBeLessThanOrEqual(MEDIA_KEY_MAX_CHARS);
|
||||
expect(rows.concatenated).not.toContain('a'.repeat(64));
|
||||
});
|
||||
|
||||
it('ignores an inline URL refresh so eviction cannot be re-poisoned', () => {
|
||||
it('ignores an inline URL refresh so eviction cannot be re-poisoned', async () => {
|
||||
const store = open('no-inline-refresh');
|
||||
store.rememberImage({
|
||||
await store.rememberImage({
|
||||
file: 'abc.png',
|
||||
url: 'https://example.com/abc.png',
|
||||
fileSize: 7,
|
||||
@@ -304,12 +306,12 @@ describe('MediaStore basic semantics', () => {
|
||||
isGroup: true,
|
||||
sessionId: GROUP_ID,
|
||||
});
|
||||
store.updateImageUrl('abc.png', `base64://${'B'.repeat(100)}`);
|
||||
expect(store.findImage('abc.png')?.url).toBe('https://example.com/abc.png');
|
||||
store.close();
|
||||
await store.updateImageUrl('abc.png', `base64://${'B'.repeat(100)}`);
|
||||
expect((await store.findImage('abc.png'))?.url).toBe('https://example.com/abc.png');
|
||||
await store.close();
|
||||
});
|
||||
|
||||
it('does not destructively purge existing metadata on open', () => {
|
||||
it('does not destructively purge existing metadata on open', async () => {
|
||||
const dbPath = tempDbPath('legacy-overflow');
|
||||
dbs.push(dbPath);
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
@@ -340,9 +342,10 @@ describe('MediaStore basic semantics', () => {
|
||||
raw.close();
|
||||
|
||||
const store = new MediaStore(dbPath);
|
||||
expect(store.findImage(poisonKey)).toBeNull();
|
||||
expect(store.size().images).toBe(1);
|
||||
store.close();
|
||||
await store.initialization;
|
||||
expect(await store.findImage(poisonKey)).toBeNull();
|
||||
expect((await store.size()).images).toBe(1);
|
||||
await store.close();
|
||||
const rows = inspectMediaDb(dbPath);
|
||||
expect(rows.entryCount).toBe(1);
|
||||
expect(rows.keyCount).toBe(1);
|
||||
@@ -432,17 +435,18 @@ describe('convertEvent media segment sink → MediaStore wiring', () => {
|
||||
dbs.push(dbPath);
|
||||
|
||||
const store = new MediaStore(dbPath);
|
||||
await store.initialization;
|
||||
const ctx: ConverterContext = {
|
||||
selfId: SELF_ID,
|
||||
imageUrlResolver: (element) => element.imageUrl ?? '',
|
||||
mediaUrlResolver: async (element) => element.url ?? '',
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: (type, element, data, isGroup, sessionId) => {
|
||||
mediaSegmentSink: async (type, element, data, isGroup, sessionId) => {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
|
||||
if (type === 'image') {
|
||||
store.rememberImage({
|
||||
await store.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
@@ -454,7 +458,7 @@ describe('convertEvent media segment sink → MediaStore wiring', () => {
|
||||
sessionId,
|
||||
});
|
||||
} else {
|
||||
store.rememberRecord({
|
||||
await store.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
@@ -473,22 +477,22 @@ describe('convertEvent media segment sink → MediaStore wiring', () => {
|
||||
await convertEvent(ctx, makeGroupMessage([imageElement()]));
|
||||
await convertEvent(ctx, makeFriendMessage([recordElement()]));
|
||||
|
||||
const img = store.findImage('abc.png');
|
||||
const img = await store.findImage('abc.png');
|
||||
expect(img).not.toBeNull();
|
||||
expect(img!.url).toBe('https://example.com/abc.png');
|
||||
expect(img!.fileSize).toBe(4242);
|
||||
expect(img!.isGroup).toBe(true);
|
||||
expect(img!.sessionId).toBe(GROUP_ID);
|
||||
|
||||
const rec = store.findRecord('silk_test.amr');
|
||||
const rec = await store.findRecord('silk_test.amr');
|
||||
expect(rec).not.toBeNull();
|
||||
expect(rec!.fileId).toBe('uuid-base64-fake');
|
||||
expect(rec!.duration).toBe(3);
|
||||
expect(rec!.isGroup).toBe(false);
|
||||
expect(rec!.sessionId).toBe(PEER_UIN);
|
||||
// Alias lookup by fileUuid still works.
|
||||
expect(store.findRecord('uuid-base64-fake')?.fileName).toBe('silk_test.amr');
|
||||
store.close();
|
||||
expect((await store.findRecord('uuid-base64-fake'))?.fileName).toBe('silk_test.amr');
|
||||
await store.close();
|
||||
});
|
||||
|
||||
it('does not invoke the sink when no media segments are present', async () => {
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import { MediaUrlResolver } from '../src/media-url-resolver';
|
||||
import { RKeyCache } from '../src/instance-rkey';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
|
||||
// Minimal stand-ins for the two collaborators. Each test wires whatever
|
||||
// subset of Bridge methods the element type exercises.
|
||||
//
|
||||
// MediaUrlResolver now reaches `bridge.apis.groupFile.{getUrl,
|
||||
// getPrivateUrl, getPttUrl, getPrivatePttUrl, getVideoUrl,
|
||||
// getPrivateVideoUrl}` per the #6 Api-on-ctx refactor. The helper here
|
||||
// builds an `apis.groupFile` stub directly so tests can keep asserting
|
||||
// "which file/url helper got called" without going through the
|
||||
// `mockBridge` shared fixture.
|
||||
function makeBridge(overrides: Record<string, ReturnType<typeof vi.fn>> = {}) {
|
||||
return {
|
||||
apis: {
|
||||
@@ -132,19 +125,44 @@ describe('MediaUrlResolver — short-circuits and resilience', () => {
|
||||
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('bridge throws: swallowed, rkey still applied', async () => {
|
||||
const bridge = makeBridge({
|
||||
getUrl: vi.fn(async () => {
|
||||
throw new Error('network down');
|
||||
}),
|
||||
});
|
||||
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') });
|
||||
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
|
||||
const element: MessageElement = { type: 'file', fileId: 'fid' };
|
||||
const out = await resolver.resolve(element, true, 12345);
|
||||
expect(out).toBe('rkey-fallback');
|
||||
expect(element.url).toBeUndefined(); // bridge threw before assignment
|
||||
});
|
||||
it.each([
|
||||
['file', true, 'getUrl'],
|
||||
['file', false, 'getPrivateUrl'],
|
||||
['record', true, 'getPttUrl'],
|
||||
['record', false, 'getPrivatePttUrl'],
|
||||
['video', true, 'getVideoUrl'],
|
||||
['video', false, 'getPrivateVideoUrl'],
|
||||
] as const)(
|
||||
'%s group=%s: reports URL failure and preserves the media',
|
||||
async (type, isGroup, method) => {
|
||||
const bridge = makeBridge({
|
||||
[method]: vi.fn().mockRejectedValue(new Error('network down')),
|
||||
});
|
||||
const resolver = new MediaUrlResolver(bridge as any, new RKeyCache());
|
||||
const element: MessageElement = {
|
||||
type,
|
||||
fileId: 'fid',
|
||||
fileHash: 'hash',
|
||||
mediaNode: MEDIA_NODE,
|
||||
};
|
||||
const original = structuredClone(element);
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
|
||||
try {
|
||||
await expect(resolver.resolve(element, isGroup, 12345)).resolves.toBe('');
|
||||
expect(element).toEqual(original);
|
||||
expect(entries).toContainEqual(
|
||||
expect.objectContaining({
|
||||
level: 'warn',
|
||||
message: expect.stringMatching(/media URL resolution failed.*network down/),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('always calls rkey.resolveMediaUrl at the end', async () => {
|
||||
const bridge = makeBridge();
|
||||
|
||||
@@ -15,6 +15,7 @@ function instanceContext(
|
||||
sendPrivate: ReturnType<typeof vi.fn> = vi.fn(),
|
||||
): OneBotInstanceContext {
|
||||
const bridge = {
|
||||
identity: { nickname: 'SnowLuma' },
|
||||
apis: { message: { sendGroup, sendPrivate } },
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
} as unknown as BridgeInterface;
|
||||
@@ -27,9 +28,17 @@ function instanceContext(
|
||||
resolveReplySequence: () => 0,
|
||||
findEvent: () => null,
|
||||
findMeta: () => null,
|
||||
storeEvent: vi.fn(),
|
||||
} as never,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as never,
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
|
||||
@@ -29,10 +29,12 @@ function createControlPort(): {
|
||||
preparations: MessageStoreMigrationPreparation[];
|
||||
send(message: unknown): void;
|
||||
listenerCount(): number;
|
||||
waitForMessages(count: number): Promise<void>;
|
||||
} {
|
||||
const messages: MessageStoreMigrationWorkerMessage[] = [];
|
||||
const preparations: MessageStoreMigrationPreparation[] = [];
|
||||
const events = new EventEmitter();
|
||||
const waiters: Array<() => void> = [];
|
||||
return {
|
||||
port: {
|
||||
on: events.on.bind(events),
|
||||
@@ -43,6 +45,10 @@ function createControlPort(): {
|
||||
} else {
|
||||
messages.push(message);
|
||||
}
|
||||
|
||||
for (const check of [...waiters]) {
|
||||
check();
|
||||
}
|
||||
},
|
||||
} as unknown as MessagePort,
|
||||
messages,
|
||||
@@ -50,14 +56,34 @@ function createControlPort(): {
|
||||
send(message: unknown) {
|
||||
events.emit('message', message);
|
||||
},
|
||||
waitForMessages(count) {
|
||||
return new Promise<void>((resolve) => {
|
||||
const check = () => {
|
||||
if (messages.length < count) {
|
||||
return;
|
||||
}
|
||||
|
||||
const index = waiters.indexOf(check);
|
||||
|
||||
if (index >= 0) {
|
||||
waiters.splice(index, 1);
|
||||
}
|
||||
|
||||
resolve();
|
||||
};
|
||||
|
||||
waiters.push(check);
|
||||
check();
|
||||
});
|
||||
},
|
||||
listenerCount() {
|
||||
return events.listenerCount('message');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function seedUnclassified(dbPath: string, count: number): void {
|
||||
prepareMessageStoreDatabase(dbPath);
|
||||
async function seedUnclassified(dbPath: string, count: number): Promise<void> {
|
||||
await prepareMessageStoreDatabase(dbPath);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
const insert = db.prepare(`
|
||||
INSERT INTO messages (
|
||||
@@ -146,7 +172,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const close = vi.spyOn(MessageStoreMigrator.prototype, 'close');
|
||||
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
expect(control.messages).toEqual([{ kind: 'ready' }]);
|
||||
expect(control.listenerCount()).toBe(1);
|
||||
|
||||
@@ -158,12 +184,12 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
{
|
||||
kind: 'progress',
|
||||
status: { phase: 'complete', processed: 0, total: 0 },
|
||||
elapsedMs: 0,
|
||||
elapsedMs: expect.any(Number),
|
||||
},
|
||||
]);
|
||||
expect(control.listenerCount()).toBe(0);
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
phase: 'complete',
|
||||
processed: 0,
|
||||
total: 0,
|
||||
@@ -174,7 +200,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
|
||||
control.send('go');
|
||||
control.send({ kind: 'start' });
|
||||
@@ -188,7 +214,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
{
|
||||
kind: 'progress',
|
||||
status: { phase: 'complete', processed: 0, total: 0 },
|
||||
elapsedMs: 0,
|
||||
elapsedMs: expect.any(Number),
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -202,7 +228,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const unsubscribe = subscribeLogs((entry) => logs.push(entry.scope));
|
||||
vi.stubEnv('SNOWLUMA_LOG_FILE', '1');
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 1);
|
||||
await seedUnclassified(dbPath, 1);
|
||||
const control = createControlPort();
|
||||
|
||||
try {
|
||||
@@ -231,11 +257,11 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
|
||||
it('returns after cancel without posting progress', async () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 1);
|
||||
await seedUnclassified(dbPath, 1);
|
||||
const control = createControlPort();
|
||||
const runBatch = vi.spyOn(MessageStoreMigrator.prototype, 'runBatch');
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
|
||||
control.send('cancel');
|
||||
await running;
|
||||
@@ -243,7 +269,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
expect(control.messages).toEqual([{ kind: 'ready' }]);
|
||||
expect(runBatch).not.toHaveBeenCalled();
|
||||
expect(control.listenerCount()).toBe(0);
|
||||
expect(inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
phase: 'migrating',
|
||||
processed: 0,
|
||||
total: 1,
|
||||
@@ -252,11 +278,11 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
|
||||
it('treats start then cancel in the same turn as a cancel', async () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 1);
|
||||
await seedUnclassified(dbPath, 1);
|
||||
const control = createControlPort();
|
||||
const runBatch = vi.spyOn(MessageStoreMigrator.prototype, 'runBatch');
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
|
||||
control.send('start');
|
||||
control.send('cancel');
|
||||
@@ -268,10 +294,10 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
|
||||
it('migrates pending rows in one batch and posts complete progress', async () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 1);
|
||||
await seedUnclassified(dbPath, 1);
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
|
||||
control.send('start');
|
||||
await running;
|
||||
@@ -281,10 +307,10 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
{
|
||||
kind: 'progress',
|
||||
status: { phase: 'complete', processed: 1, total: 1 },
|
||||
elapsedMs: 0,
|
||||
elapsedMs: expect.any(Number),
|
||||
},
|
||||
]);
|
||||
expect(inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
phase: 'complete',
|
||||
processed: 1,
|
||||
total: 1,
|
||||
@@ -293,10 +319,10 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
|
||||
it('posts a second progress after the batch pause when more than 200 rows remain', async () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 201);
|
||||
await seedUnclassified(dbPath, 201);
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
|
||||
control.send('start');
|
||||
await running;
|
||||
@@ -306,7 +332,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
expect(control.messages[1]).toEqual({
|
||||
kind: 'progress',
|
||||
status: { phase: 'migrating', processed: 200, total: 201 },
|
||||
elapsedMs: 0,
|
||||
elapsedMs: expect.any(Number),
|
||||
});
|
||||
expect(control.messages[2]).toMatchObject({
|
||||
kind: 'progress',
|
||||
@@ -319,7 +345,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
expect(last.elapsedMs).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
|
||||
expect(inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
phase: 'complete',
|
||||
processed: 201,
|
||||
total: 201,
|
||||
@@ -329,19 +355,19 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
it('stops after cancel between batches', async () => {
|
||||
vi.useFakeTimers();
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 201);
|
||||
await seedUnclassified(dbPath, 201);
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
|
||||
control.send('start');
|
||||
await Promise.resolve();
|
||||
await control.waitForMessages(2);
|
||||
expect(control.messages).toEqual([
|
||||
{ kind: 'ready' },
|
||||
{
|
||||
kind: 'progress',
|
||||
status: { phase: 'migrating', processed: 200, total: 201 },
|
||||
elapsedMs: 0,
|
||||
elapsedMs: expect.any(Number),
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -354,10 +380,10 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
{
|
||||
kind: 'progress',
|
||||
status: { phase: 'migrating', processed: 200, total: 201 },
|
||||
elapsedMs: 0,
|
||||
elapsedMs: expect.any(Number),
|
||||
},
|
||||
]);
|
||||
expect(inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
|
||||
phase: 'migrating',
|
||||
processed: 200,
|
||||
total: 201,
|
||||
@@ -389,7 +415,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
expect(control.messages).toEqual([{ kind: 'ready' }]);
|
||||
|
||||
const db = new DatabaseSync(dbPath);
|
||||
@@ -401,13 +427,13 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
|
||||
expect(control.messages).toEqual([
|
||||
{ kind: 'ready' },
|
||||
{ kind: 'failed', message: 'no such table: main.messages' },
|
||||
{ kind: 'failed', message: expect.stringContaining('no such table: main.messages') },
|
||||
]);
|
||||
});
|
||||
|
||||
it('posts failed when a batch update is aborted', async () => {
|
||||
const dbPath = path.join(tmpDir, 'messages.db');
|
||||
seedUnclassified(dbPath, 1);
|
||||
await seedUnclassified(dbPath, 1);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec(`
|
||||
CREATE TRIGGER fail_classify BEFORE UPDATE ON messages
|
||||
@@ -420,14 +446,14 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
const control = createControlPort();
|
||||
const close = vi.spyOn(MessageStoreMigrator.prototype, 'close');
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
|
||||
control.send('start');
|
||||
await running;
|
||||
|
||||
expect(control.messages).toEqual([
|
||||
{ kind: 'ready' },
|
||||
{ kind: 'failed', message: 'classified row rejected' },
|
||||
{ kind: 'failed', message: expect.stringContaining('classified row rejected') },
|
||||
]);
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -439,7 +465,7 @@ describe('runMessageStoreMigrationWorker', () => {
|
||||
});
|
||||
const control = createControlPort();
|
||||
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
|
||||
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
|
||||
await control.waitForMessages(1);
|
||||
|
||||
control.send('start');
|
||||
await running;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { SqliteDatabase } from '@snowluma/sqlite';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { MessageStoreMigrator, prepareMessageStoreDatabase } from '../src/message-store-migration';
|
||||
|
||||
@@ -10,14 +10,14 @@ const pendingIndex = 'idx_messages_pending_classification_v1';
|
||||
describe('message history migration scans', () => {
|
||||
let directory: string;
|
||||
let dbPath: string;
|
||||
let db: DatabaseSync;
|
||||
let db: SqliteDatabase;
|
||||
let migrator: MessageStoreMigrator | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
directory = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-migration-scans-'));
|
||||
dbPath = path.join(directory, 'messages.db');
|
||||
prepareMessageStoreDatabase(dbPath);
|
||||
db = new DatabaseSync(dbPath);
|
||||
await prepareMessageStoreDatabase(dbPath);
|
||||
db = new SqliteDatabase(dbPath);
|
||||
const insert = db.prepare(`INSERT INTO messages
|
||||
(message_hash, is_group, session_id, sequence, client_sequence, event_name, data, media_data, classification_version)
|
||||
VALUES (?, 0, 42, 1, 1, 'message.private', ?, ?, ?)`);
|
||||
@@ -27,10 +27,10 @@ describe('message history migration scans', () => {
|
||||
sub_type: 'friend',
|
||||
message: [{ type: 'text', data: { text: 'x'.repeat(3000) } }],
|
||||
});
|
||||
db.exec('BEGIN');
|
||||
await db.exec('BEGIN');
|
||||
|
||||
for (let hash = -500; hash <= 500; hash++) {
|
||||
insert.run(
|
||||
await insert.run(
|
||||
hash,
|
||||
data,
|
||||
'{"retained":"snapshot"}',
|
||||
@@ -38,14 +38,14 @@ describe('message history migration scans', () => {
|
||||
);
|
||||
}
|
||||
|
||||
db.exec('COMMIT');
|
||||
await db.exec('COMMIT');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
migrator?.close();
|
||||
await migrator?.close();
|
||||
migrator = undefined;
|
||||
db.close();
|
||||
await db.close();
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
@@ -59,9 +59,9 @@ describe('message history migration scans', () => {
|
||||
];
|
||||
}
|
||||
|
||||
function expectPendingQueryPlans(queries: string[]): void {
|
||||
async function expectPendingQueryPlans(queries: string[]): Promise<void> {
|
||||
expect(queries).toHaveLength(3);
|
||||
const planDb = new DatabaseSync(dbPath);
|
||||
const planDb = new SqliteDatabase(dbPath, { readOnly: true });
|
||||
|
||||
try {
|
||||
for (const sql of queries) {
|
||||
@@ -70,9 +70,7 @@ describe('message history migration scans', () => {
|
||||
? [1, -400, 1]
|
||||
: [1, 1]
|
||||
: [1];
|
||||
const details = planDb
|
||||
.prepare(`EXPLAIN QUERY PLAN ${sql}`)
|
||||
.all(...args)
|
||||
const details = (await planDb.prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...args))
|
||||
.map((row) => String(row.detail))
|
||||
.join('\n');
|
||||
expect(details).toContain(pendingIndex);
|
||||
@@ -83,34 +81,37 @@ describe('message history migration scans', () => {
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
planDb.close();
|
||||
await planDb.close();
|
||||
}
|
||||
}
|
||||
|
||||
it('uses pending rows for the actual count and ordered batch queries without changing history', () => {
|
||||
const before = db
|
||||
it('uses pending rows for the actual count and ordered batch queries without changing history', async () => {
|
||||
const before = await db
|
||||
.prepare('SELECT message_hash, data, media_data FROM messages ORDER BY message_hash')
|
||||
.all();
|
||||
const prepare = vi.spyOn(DatabaseSync.prototype, 'prepare');
|
||||
const prepare = vi.spyOn(SqliteDatabase.prototype, 'prepare');
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
await migrator.initialization;
|
||||
const queries = capturedPendingQueries(prepare.mock.calls.map(([sql]) => sql));
|
||||
expectPendingQueryPlans(queries);
|
||||
expect(migrator.getStatus()).toEqual({ phase: 'migrating', processed: 0, total: 3 });
|
||||
expect(migrator.runBatch(2)).toEqual({ phase: 'migrating', processed: 2, total: 3 });
|
||||
expect(migrator.runBatch(2)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
expectPendingQueryPlans(queries);
|
||||
await expectPendingQueryPlans(queries);
|
||||
expect(await migrator.getStatus()).toEqual({ phase: 'migrating', processed: 0, total: 3 });
|
||||
expect(await migrator.runBatch(2)).toEqual({ phase: 'migrating', processed: 2, total: 3 });
|
||||
expect(await migrator.runBatch(2)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
await expectPendingQueryPlans(queries);
|
||||
expect(
|
||||
db.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1').get(),
|
||||
await db
|
||||
.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1')
|
||||
.get(),
|
||||
).toEqual({ n: 0 });
|
||||
expect(
|
||||
db
|
||||
await db
|
||||
.prepare(
|
||||
'SELECT message_hash, data, media_data FROM messages ORDER BY message_hash',
|
||||
)
|
||||
.all(),
|
||||
).toEqual(before);
|
||||
expect(
|
||||
db
|
||||
await db
|
||||
.prepare(
|
||||
'SELECT message_hash, private_direction FROM messages WHERE message_hash IN (-400, 0, 400) ORDER BY message_hash',
|
||||
)
|
||||
@@ -122,75 +123,84 @@ describe('message history migration scans', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('adds the index when resuming a migration started by an older version', () => {
|
||||
it('adds the index when resuming a migration started by an older version', async () => {
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
expect(migrator.runBatch(1)).toEqual({ phase: 'migrating', processed: 1, total: 3 });
|
||||
migrator.close();
|
||||
await migrator.initialization;
|
||||
expect(await migrator.runBatch(1)).toEqual({ phase: 'migrating', processed: 1, total: 3 });
|
||||
await migrator.close();
|
||||
migrator = undefined;
|
||||
db.exec(`DROP INDEX IF EXISTS ${pendingIndex}`);
|
||||
await db.exec(`DROP INDEX IF EXISTS ${pendingIndex}`);
|
||||
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
await migrator.initialization;
|
||||
expect(
|
||||
db
|
||||
await db
|
||||
.prepare('SELECT name FROM sqlite_schema WHERE type = ? AND name = ?')
|
||||
.get('index', pendingIndex),
|
||||
).toEqual({ name: pendingIndex });
|
||||
expect(migrator.getStatus()).toEqual({ phase: 'migrating', processed: 1, total: 3 });
|
||||
expect(migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
expect(await migrator.getStatus()).toEqual({ phase: 'migrating', processed: 1, total: 3 });
|
||||
expect(await migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
});
|
||||
|
||||
it('does not rebuild an existing pending index when an interrupted migration resumes', () => {
|
||||
it('does not rebuild an existing pending index when an interrupted migration resumes', async () => {
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
migrator.runBatch(1);
|
||||
migrator.close();
|
||||
await migrator.initialization;
|
||||
await migrator.runBatch(1);
|
||||
await migrator.close();
|
||||
migrator = undefined;
|
||||
const schemaVersion = db.prepare('PRAGMA schema_version').get();
|
||||
const schemaVersion = await db.prepare('PRAGMA schema_version').get();
|
||||
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
expect(db.prepare('PRAGMA schema_version').get()).toEqual(schemaVersion);
|
||||
expect(migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
await migrator.initialization;
|
||||
expect(await db.prepare('PRAGMA schema_version').get()).toEqual(schemaVersion);
|
||||
expect(await migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
});
|
||||
|
||||
it('revisits rows left behind the cursor after a concurrent update prevented classification', () => {
|
||||
db.exec(`CREATE TRIGGER defer_first BEFORE UPDATE ON messages
|
||||
it('revisits rows left behind the cursor after a concurrent update prevented classification', async () => {
|
||||
await db.exec(`CREATE TRIGGER defer_first BEFORE UPDATE ON messages
|
||||
WHEN OLD.message_hash = -400 BEGIN SELECT RAISE(IGNORE); END`);
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
expect(migrator.runBatch(1)).toEqual({ phase: 'migrating', processed: 0, total: 3 });
|
||||
db.exec('DROP TRIGGER defer_first');
|
||||
expect(migrator.runBatch(2)).toEqual({ phase: 'migrating', processed: 2, total: 3 });
|
||||
expect(migrator.runBatch(2)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
await migrator.initialization;
|
||||
expect(await migrator.runBatch(1)).toEqual({ phase: 'migrating', processed: 0, total: 3 });
|
||||
await db.exec('DROP TRIGGER defer_first');
|
||||
expect(await migrator.runBatch(2)).toEqual({ phase: 'migrating', processed: 2, total: 3 });
|
||||
expect(await migrator.runBatch(2)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
expect(
|
||||
db.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1').get(),
|
||||
await db
|
||||
.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1')
|
||||
.get(),
|
||||
).toEqual({ n: 0 });
|
||||
expect(db.prepare('SELECT COUNT(*) AS n FROM messages').get()).toEqual({ n: 1001 });
|
||||
expect(await db.prepare('SELECT COUNT(*) AS n FROM messages').get()).toEqual({ n: 1001 });
|
||||
});
|
||||
|
||||
it('skips index creation and pending counts when an older version already completed migration', () => {
|
||||
it('skips index creation and pending counts when an older version already completed migration', async () => {
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
migrator.runBatch(10);
|
||||
migrator.close();
|
||||
await migrator.initialization;
|
||||
await migrator.runBatch(10);
|
||||
await migrator.close();
|
||||
migrator = undefined;
|
||||
db.exec(`DROP INDEX IF EXISTS ${pendingIndex}`);
|
||||
const exec = vi.spyOn(DatabaseSync.prototype, 'exec');
|
||||
const prepare = vi.spyOn(DatabaseSync.prototype, 'prepare');
|
||||
await db.exec(`DROP INDEX IF EXISTS ${pendingIndex}`);
|
||||
const exec = vi.spyOn(SqliteDatabase.prototype, 'exec');
|
||||
const prepare = vi.spyOn(SqliteDatabase.prototype, 'prepare');
|
||||
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
expect(migrator.runBatch(10)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
await migrator.initialization;
|
||||
expect(await migrator.runBatch(10)).toEqual({ phase: 'complete', processed: 3, total: 3 });
|
||||
expect(exec.mock.calls.some(([sql]) => /CREATE\s+INDEX/i.test(sql))).toBe(false);
|
||||
expect(prepare.mock.calls.some(([sql]) => sql.includes('COUNT(*)'))).toBe(false);
|
||||
expect(
|
||||
db
|
||||
await db
|
||||
.prepare('SELECT name FROM sqlite_schema WHERE type = ? AND name = ?')
|
||||
.get('index', pendingIndex),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('propagates preparation failure and closes the failed migration connection', () => {
|
||||
const originalExec = DatabaseSync.prototype.exec;
|
||||
it('propagates preparation failure and closes the failed migration connection', async () => {
|
||||
const originalExec = SqliteDatabase.prototype.exec;
|
||||
const failure = new Error('pending index unavailable');
|
||||
let failedDb: DatabaseSync | undefined;
|
||||
vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (
|
||||
this: DatabaseSync,
|
||||
let failedDb: SqliteDatabase | undefined;
|
||||
vi.spyOn(SqliteDatabase.prototype, 'exec').mockImplementation(async function (
|
||||
this: SqliteDatabase,
|
||||
sql,
|
||||
) {
|
||||
if (sql.includes(pendingIndex)) {
|
||||
@@ -201,13 +211,18 @@ describe('message history migration scans', () => {
|
||||
return originalExec.call(this, sql);
|
||||
});
|
||||
|
||||
expect(() => {
|
||||
await expect(async () => {
|
||||
migrator = new MessageStoreMigrator(dbPath);
|
||||
}).toThrow(failure);
|
||||
await migrator.initialization;
|
||||
}).rejects.toThrow(failure);
|
||||
expect(failedDb).toBeDefined();
|
||||
expect(() => failedDb!.prepare('SELECT 1')).toThrow(/not open/);
|
||||
await migrator!.close();
|
||||
migrator = undefined;
|
||||
await expect(failedDb!.exec('SELECT 1')).rejects.toThrow(/closing/);
|
||||
expect(
|
||||
db.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1').get(),
|
||||
await db
|
||||
.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1')
|
||||
.get(),
|
||||
).toEqual({ n: 3 });
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -29,7 +29,10 @@ async function sendQuote(isGroup: boolean, original: JsonValue | null) {
|
||||
const ref = {
|
||||
uin: '10001',
|
||||
selfId: 10001,
|
||||
bridge: { apis: { message: { sendGroup: send, sendPrivate: send } } },
|
||||
bridge: {
|
||||
identity: { nickname: 'SnowLuma' },
|
||||
apis: { message: { sendGroup: send, sendPrivate: send } },
|
||||
},
|
||||
messageStore: {
|
||||
findEvent: () =>
|
||||
original === null ? null : { user_id: sender, time, message: original },
|
||||
@@ -41,6 +44,14 @@ async function sendQuote(isGroup: boolean, original: JsonValue | null) {
|
||||
sequenceAuthoritative: true,
|
||||
}),
|
||||
resolveReplySequence: () => sequence,
|
||||
storeEvent: vi.fn(),
|
||||
},
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {},
|
||||
|
||||
@@ -17,7 +17,7 @@ const SELF_ID = 3961840894;
|
||||
const PEER_ID = 2705892349;
|
||||
|
||||
function productionResolver(store: MessageStore): ConverterContext['messageIdResolver'] {
|
||||
return (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
|
||||
return async (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
|
||||
const resolvedEventName = eventName || (isGroup ? 'group_message' : PRIVATE_MESSAGE_EVENT);
|
||||
|
||||
if (
|
||||
@@ -26,7 +26,7 @@ function productionResolver(store: MessageStore): ConverterContext['messageIdRes
|
||||
(resolvedEventName === PRIVATE_MESSAGE_EVENT ||
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)
|
||||
) {
|
||||
const storedId = store.resolvePrivateReplyMessageId(
|
||||
const storedId = await store.resolvePrivateReplyMessageId(
|
||||
sessionId,
|
||||
sequence,
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
||||
@@ -53,13 +53,14 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
let dir: string;
|
||||
let store: MessageStore;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-reply-id-'));
|
||||
store = new MessageStore(path.join(dir, 'messages.db'));
|
||||
await store.initialization;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
store.close();
|
||||
afterEach(async () => {
|
||||
await store.close();
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
@@ -70,7 +71,7 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
[101, [{ type: 'text', data: { text: 'the quoted text' } }]],
|
||||
[102, [{ type: 'record', data: { file: 'voice.amr' } }]],
|
||||
] as const) {
|
||||
store.storeMeta(id, {
|
||||
await store.storeMeta(id, {
|
||||
isGroup: false,
|
||||
targetId: PEER_ID,
|
||||
sequence: id,
|
||||
@@ -81,7 +82,7 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
random: id,
|
||||
timestamp: sentAt,
|
||||
});
|
||||
store.storeEvent(id, false, PEER_ID, id, PRIVATE_NT_MESSAGE_EVENT, {
|
||||
await store.storeEvent(id, false, PEER_ID, id, PRIVATE_NT_MESSAGE_EVENT, {
|
||||
time: sentAt,
|
||||
post_type: 'message_sent',
|
||||
message_type: 'private',
|
||||
@@ -90,14 +91,15 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
});
|
||||
}
|
||||
|
||||
store.close();
|
||||
await store.close();
|
||||
store = new MessageStore(path.join(dir, 'messages.db'));
|
||||
await store.initialization;
|
||||
const ctx: ConverterContext = {
|
||||
selfId: SELF_ID,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
messageIdResolver: productionResolver(store),
|
||||
messageIdResolver: await productionResolver(store),
|
||||
};
|
||||
const event: FriendMessage = {
|
||||
kind: 'friend_message',
|
||||
@@ -152,7 +154,7 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
hashMessageIdInt32(fixture.quoteSeq, PEER_ID, PRIVATE_SENT_MESSAGE_EVENT),
|
||||
);
|
||||
|
||||
store.storeMeta(sendId, {
|
||||
await store.storeMeta(sendId, {
|
||||
isGroup: false,
|
||||
targetId: PEER_ID,
|
||||
sequence: fixture.ntSeq,
|
||||
@@ -169,7 +171,7 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
messageIdResolver: productionResolver(store),
|
||||
messageIdResolver: await productionResolver(store),
|
||||
};
|
||||
|
||||
const event: FriendMessage = {
|
||||
@@ -211,7 +213,7 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
const sendId = hashMessageIdInt32(ntSeq, PEER_ID, PRIVATE_NT_MESSAGE_EVENT);
|
||||
expect(sendId).not.toBe(hashMessageIdInt32(quoteSeq, PEER_ID, PRIVATE_SENT_MESSAGE_EVENT));
|
||||
|
||||
store.storeMeta(sendId, {
|
||||
await store.storeMeta(sendId, {
|
||||
isGroup: false,
|
||||
targetId: PEER_ID,
|
||||
sequence: ntSeq,
|
||||
@@ -228,7 +230,7 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
messageIdResolver: productionResolver(store),
|
||||
messageIdResolver: await productionResolver(store),
|
||||
};
|
||||
|
||||
const event: FriendMessage = {
|
||||
@@ -268,7 +270,7 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
const quoteTime = sentAt + 2;
|
||||
const sendId = hashMessageIdInt32(ntSeq, PEER_ID, PRIVATE_NT_MESSAGE_EVENT);
|
||||
|
||||
store.storeMeta(sendId, {
|
||||
await store.storeMeta(sendId, {
|
||||
isGroup: false,
|
||||
targetId: PEER_ID,
|
||||
sequence: ntSeq,
|
||||
@@ -285,7 +287,7 @@ describe('private reply id matches send receipt (#417, #433)', () => {
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
messageIdResolver: productionResolver(store),
|
||||
messageIdResolver: await productionResolver(store),
|
||||
};
|
||||
|
||||
const event: FriendMessage = {
|
||||
|
||||
@@ -32,6 +32,13 @@ function makeContext(messageApi: Record<string, ReturnType<typeof vi.fn>>): OneB
|
||||
} as never,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as never,
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
tempSessions: new TempSessionStore(),
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
|
||||
@@ -7,7 +7,7 @@ describe('ReactionStore', () => {
|
||||
const testDbPath = path.join('data', 'test', 'reactions-test.db');
|
||||
let store: ReactionStore;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
try {
|
||||
fs.unlinkSync(testDbPath);
|
||||
} catch {
|
||||
@@ -27,10 +27,11 @@ describe('ReactionStore', () => {
|
||||
}
|
||||
|
||||
store = new ReactionStore(testDbPath);
|
||||
await store.initialization;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
store.close();
|
||||
afterEach(async () => {
|
||||
await store.close();
|
||||
|
||||
try {
|
||||
fs.unlinkSync(testDbPath);
|
||||
@@ -51,72 +52,72 @@ describe('ReactionStore', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('records an add and exposes it via listUsers / countUsers', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 12345, 'u_abc', 1700000000);
|
||||
const users = store.listUsers(100, 4001, '124');
|
||||
it('records an add and exposes it via listUsers / countUsers', async () => {
|
||||
await store.recordAdd(100, 4001, '124', 1, 12345, 'u_abc', 1700000000);
|
||||
const users = await store.listUsers(100, 4001, '124');
|
||||
expect(users).toEqual([{ operatorUin: 12345, operatorUid: 'u_abc', setAt: 1700000000 }]);
|
||||
expect(store.countUsers(100, 4001, '124')).toBe(1);
|
||||
expect(await store.countUsers(100, 4001, '124')).toBe(1);
|
||||
});
|
||||
|
||||
it('upserts on duplicate (group, msg, emoji, operator)', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 12345, 'u_old', 1700000000);
|
||||
store.recordAdd(100, 4001, '124', 1, 12345, 'u_new', 1700000500);
|
||||
const users = store.listUsers(100, 4001, '124');
|
||||
it('upserts on duplicate (group, msg, emoji, operator)', async () => {
|
||||
await store.recordAdd(100, 4001, '124', 1, 12345, 'u_old', 1700000000);
|
||||
await store.recordAdd(100, 4001, '124', 1, 12345, 'u_new', 1700000500);
|
||||
const users = await store.listUsers(100, 4001, '124');
|
||||
expect(users).toHaveLength(1);
|
||||
expect(users[0]?.operatorUid).toBe('u_new');
|
||||
expect(users[0]?.setAt).toBe(1700000500);
|
||||
});
|
||||
|
||||
it('removes the right row only', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 12345, 'u_a', 1700000000);
|
||||
store.recordAdd(100, 4001, '124', 1, 67890, 'u_b', 1700000100);
|
||||
store.recordRemove(100, 4001, '124', 12345);
|
||||
const users = store.listUsers(100, 4001, '124');
|
||||
it('removes the right row only', async () => {
|
||||
await store.recordAdd(100, 4001, '124', 1, 12345, 'u_a', 1700000000);
|
||||
await store.recordAdd(100, 4001, '124', 1, 67890, 'u_b', 1700000100);
|
||||
await store.recordRemove(100, 4001, '124', 12345);
|
||||
const users = await store.listUsers(100, 4001, '124');
|
||||
expect(users).toHaveLength(1);
|
||||
expect(users[0]?.operatorUin).toBe(67890);
|
||||
});
|
||||
|
||||
it('isolates by group / msg / emoji', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 1, 'u', 1);
|
||||
store.recordAdd(100, 4001, '76', 1, 1, 'u', 1);
|
||||
store.recordAdd(100, 4002, '124', 1, 1, 'u', 1);
|
||||
store.recordAdd(200, 4001, '124', 1, 1, 'u', 1);
|
||||
expect(store.countUsers(100, 4001, '124')).toBe(1);
|
||||
expect(store.countUsers(100, 4001, '76')).toBe(1);
|
||||
expect(store.countUsers(100, 4002, '124')).toBe(1);
|
||||
expect(store.countUsers(200, 4001, '124')).toBe(1);
|
||||
expect(store.countUsers(100, 4001, '999')).toBe(0);
|
||||
it('isolates by group / msg / emoji', async () => {
|
||||
await store.recordAdd(100, 4001, '124', 1, 1, 'u', 1);
|
||||
await store.recordAdd(100, 4001, '76', 1, 1, 'u', 1);
|
||||
await store.recordAdd(100, 4002, '124', 1, 1, 'u', 1);
|
||||
await store.recordAdd(200, 4001, '124', 1, 1, 'u', 1);
|
||||
expect(await store.countUsers(100, 4001, '124')).toBe(1);
|
||||
expect(await store.countUsers(100, 4001, '76')).toBe(1);
|
||||
expect(await store.countUsers(100, 4002, '124')).toBe(1);
|
||||
expect(await store.countUsers(200, 4001, '124')).toBe(1);
|
||||
expect(await store.countUsers(100, 4001, '999')).toBe(0);
|
||||
});
|
||||
|
||||
it('paginates listUsers via limit + offset, ordering by set_at ASC', () => {
|
||||
it('paginates listUsers via limit + offset, ordering by set_at ASC', async () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
store.recordAdd(100, 4001, '124', 1, 1000 + i, `u_${i}`, 1700000000 + i);
|
||||
await store.recordAdd(100, 4001, '124', 1, 1000 + i, `u_${i}`, 1700000000 + i);
|
||||
}
|
||||
|
||||
const page1 = store.listUsers(100, 4001, '124', 2, 0);
|
||||
const page2 = store.listUsers(100, 4001, '124', 2, 2);
|
||||
const page1 = await store.listUsers(100, 4001, '124', 2, 0);
|
||||
const page2 = await store.listUsers(100, 4001, '124', 2, 2);
|
||||
expect(page1.map((u) => u.operatorUin)).toEqual([1000, 1001]);
|
||||
expect(page2.map((u) => u.operatorUin)).toEqual([1002, 1003]);
|
||||
});
|
||||
|
||||
it('summarizeMessage groups by emoji_id', () => {
|
||||
store.recordAdd(100, 4001, '124', 1, 1, 'u1', 1);
|
||||
store.recordAdd(100, 4001, '124', 1, 2, 'u2', 2);
|
||||
store.recordAdd(100, 4001, '76', 1, 3, 'u3', 10);
|
||||
const summary = store
|
||||
.summarizeMessage(100, 4001)
|
||||
.sort((a, b) => a.emojiId.localeCompare(b.emojiId));
|
||||
it('summarizeMessage groups by emoji_id', async () => {
|
||||
await store.recordAdd(100, 4001, '124', 1, 1, 'u1', 1);
|
||||
await store.recordAdd(100, 4001, '124', 1, 2, 'u2', 2);
|
||||
await store.recordAdd(100, 4001, '76', 1, 3, 'u3', 10);
|
||||
const summary = (await store.summarizeMessage(100, 4001)).sort((a, b) =>
|
||||
a.emojiId.localeCompare(b.emojiId),
|
||||
);
|
||||
expect(summary).toEqual([
|
||||
{ emojiId: '124', emojiType: 1, count: 2, lastSetAt: 2 },
|
||||
{ emojiId: '76', emojiType: 1, count: 1, lastSetAt: 10 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('ignores incomplete records (no-op instead of throwing)', () => {
|
||||
store.recordAdd(0, 4001, '124', 1, 1, 'u', 1); // group 0
|
||||
store.recordAdd(100, 0, '124', 1, 1, 'u', 1); // msg 0
|
||||
store.recordAdd(100, 4001, '', 1, 1, 'u', 1); // empty emoji
|
||||
store.recordAdd(100, 4001, '124', 1, 0, 'u', 1); // uin 0
|
||||
expect(store.countUsers(100, 4001, '124')).toBe(0);
|
||||
it('ignores incomplete records (no-op instead of throwing)', async () => {
|
||||
await store.recordAdd(0, 4001, '124', 1, 1, 'u', 1); // group 0
|
||||
await store.recordAdd(100, 0, '124', 1, 1, 'u', 1); // msg 0
|
||||
await store.recordAdd(100, 4001, '', 1, 1, 'u', 1); // empty emoji
|
||||
await store.recordAdd(100, 4001, '124', 1, 0, 'u', 1); // uin 0
|
||||
expect(await store.countUsers(100, 4001, '124')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -100,12 +100,19 @@ function makeContext(receiptOrReceipts: Receipt | Receipt[] = RECEIPT): {
|
||||
event: JsonObject,
|
||||
) => {
|
||||
events.set(messageId, event);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
mediaStore: {},
|
||||
reactionStore: {},
|
||||
tempSessions: new TempSessionStore(),
|
||||
converterCtx: {},
|
||||
converterCtx: {
|
||||
selfId: SELF_ID,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
config: {
|
||||
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
|
||||
} as OneBotConfig,
|
||||
@@ -117,7 +124,7 @@ function makeContext(receiptOrReceipts: Receipt | Receipt[] = RECEIPT): {
|
||||
}
|
||||
|
||||
interface InstanceHarness {
|
||||
dispatch(event: JsonObject, source: 'send' | 'bridge'): void;
|
||||
dispatch(event: JsonObject, source: 'send' | 'bridge'): Promise<void>;
|
||||
emitEvent: ReturnType<typeof vi.fn<(event: JsonObject) => Promise<void>>>;
|
||||
stored: Map<number, JsonObject>;
|
||||
}
|
||||
@@ -161,6 +168,7 @@ function makeInstanceHarness(
|
||||
event: JsonObject,
|
||||
) => {
|
||||
stored.set(messageId, event);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
networkManager: { emitEvent },
|
||||
@@ -171,7 +179,7 @@ function makeInstanceHarness(
|
||||
});
|
||||
const dispatch = (
|
||||
instance as unknown as {
|
||||
dispatchEvent(event: JsonObject, source: 'send' | 'bridge'): void;
|
||||
dispatchEvent(event: JsonObject, source: 'send' | 'bridge'): Promise<void>;
|
||||
}
|
||||
).dispatchEvent.bind(instance);
|
||||
return { dispatch, emitEvent, stored };
|
||||
@@ -196,6 +204,29 @@ function privateSentEvent(overrides: JsonObject = {}): JsonObject {
|
||||
}
|
||||
|
||||
describe('OneBot self-sent events', () => {
|
||||
it('does not publish an event suppressed by the persistence recall check', async () => {
|
||||
const { dispatch, emitEvent } = makeInstanceHarness();
|
||||
// The event's cache operation is the final authority after asynchronous
|
||||
// conversion: a recall may have committed while media was resolving.
|
||||
const event = privateSentEvent();
|
||||
const original = OneBotInstance.prototype;
|
||||
const cache = vi
|
||||
.spyOn(
|
||||
original as unknown as {
|
||||
cacheMessageEvent(event: JsonObject): Promise<boolean>;
|
||||
},
|
||||
'cacheMessageEvent',
|
||||
)
|
||||
.mockResolvedValueOnce(false);
|
||||
|
||||
try {
|
||||
await dispatch(event, 'bridge');
|
||||
expect(emitEvent).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
cache.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports upload_private_file as a private self-sent message', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext();
|
||||
const handler = new ApiHandler(buildApiContext(ctx));
|
||||
@@ -310,6 +341,35 @@ describe('OneBot self-sent events', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('reports storage failure without failing or repeating an already successful send', async () => {
|
||||
const { ctx, dispatchEvent, events } = makeContext();
|
||||
vi.spyOn(ctx.messageStore, 'storeEvent').mockImplementation(() => {
|
||||
throw new Error('disk full');
|
||||
});
|
||||
const handler = new ApiHandler(buildApiContext(ctx));
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
|
||||
try {
|
||||
const response = await handler.handle('send_private_msg', {
|
||||
user_id: PEER_ID,
|
||||
message: 'hello',
|
||||
});
|
||||
expect(response).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
expect(ctx.bridge.apis.message.sendPrivate).toHaveBeenCalledOnce();
|
||||
expect(events.size).toBe(0);
|
||||
expect(dispatchEvent).not.toHaveBeenCalled();
|
||||
expect(entries).toContainEqual(
|
||||
expect.objectContaining({
|
||||
level: 'warn',
|
||||
message: expect.stringMatching(/failed to cache self-sent message.*disk full/),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('[#288] reports a private forward built through an action', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext();
|
||||
const api = buildApiContext(ctx);
|
||||
@@ -565,7 +625,7 @@ describe('OneBot self-sent events', () => {
|
||||
).toEqual(['first-file', 'second-file']);
|
||||
});
|
||||
|
||||
it('does not report a later QQ echo after the action event', () => {
|
||||
it('does not report a later QQ echo after the action event', async () => {
|
||||
const { dispatch, emitEvent, stored } = makeInstanceHarness();
|
||||
const sentEvent = privateSentEvent();
|
||||
const qqEcho: JsonObject = {
|
||||
@@ -574,14 +634,14 @@ describe('OneBot self-sent events', () => {
|
||||
sender: { user_id: SELF_ID, nickname: 'Server profile' },
|
||||
};
|
||||
|
||||
dispatch(sentEvent, 'send');
|
||||
dispatch(qqEcho, 'bridge');
|
||||
await dispatch(sentEvent, 'send');
|
||||
await dispatch(qqEcho, 'bridge');
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledOnce();
|
||||
expect(stored.get(987654)?.raw_message).toBe('canonical echo');
|
||||
});
|
||||
|
||||
it('records one truthful handoff terminal for reporting, duplicate suppression, and status suppression', () => {
|
||||
it('records one truthful handoff terminal for reporting, duplicate suppression, and status suppression', async () => {
|
||||
const previousLevel = getLogLevel();
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
@@ -590,13 +650,13 @@ describe('OneBot self-sent events', () => {
|
||||
try {
|
||||
const logger = createLogger('Event').child({ uin: SELF_ID });
|
||||
const reporting = makeInstanceHarness({ logger });
|
||||
runWithRequestId(6001, () => reporting.dispatch(privateSentEvent(), 'send'));
|
||||
await runWithRequestId(6001, () => reporting.dispatch(privateSentEvent(), 'send'));
|
||||
expect(reporting.emitEvent).toHaveBeenCalledOnce();
|
||||
|
||||
const duplicate = makeInstanceHarness({ logger });
|
||||
runWithRequestId(6002, () => {
|
||||
duplicate.dispatch(privateSentEvent(), 'send');
|
||||
duplicate.dispatch(privateSentEvent({ raw_message: 'canonical' }), 'bridge');
|
||||
await runWithRequestId(6002, async () => {
|
||||
await duplicate.dispatch(privateSentEvent(), 'send');
|
||||
await duplicate.dispatch(privateSentEvent({ raw_message: 'canonical' }), 'bridge');
|
||||
});
|
||||
expect(duplicate.emitEvent).toHaveBeenCalledOnce();
|
||||
|
||||
@@ -604,7 +664,7 @@ describe('OneBot self-sent events', () => {
|
||||
logger,
|
||||
statusCommand: { enabled: true, swallow: true, cooldownSeconds: 5, trigger: '#sl' },
|
||||
});
|
||||
runWithRequestId(6003, () =>
|
||||
await runWithRequestId(6003, () =>
|
||||
status.dispatch(
|
||||
privateSentEvent({
|
||||
post_type: 'message',
|
||||
@@ -701,7 +761,7 @@ describe('OneBot self-sent events', () => {
|
||||
expect(dispatchEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not suppress a bridge echo that was cached but never reported', () => {
|
||||
it('does not suppress a bridge echo that was cached but never reported', async () => {
|
||||
const { dispatch, emitEvent, stored } = makeInstanceHarness();
|
||||
const cached: JsonObject = {
|
||||
time: RECEIPT.timestamp,
|
||||
@@ -719,18 +779,18 @@ describe('OneBot self-sent events', () => {
|
||||
};
|
||||
stored.set(7654321, cached);
|
||||
|
||||
dispatch({ ...cached, raw_message: 'canonical echo' }, 'bridge');
|
||||
await dispatch({ ...cached, raw_message: 'canonical echo' }, 'bridge');
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledOnce();
|
||||
expect(stored.get(7654321)?.raw_message).toBe('canonical echo');
|
||||
});
|
||||
|
||||
it('does not suppress a hash collision from another conversation', () => {
|
||||
it('does not suppress a hash collision from another conversation', async () => {
|
||||
const { dispatch, emitEvent } = makeInstanceHarness();
|
||||
const sentEvent = privateSentEvent();
|
||||
|
||||
dispatch(sentEvent, 'send');
|
||||
dispatch({ ...sentEvent, target_id: PEER_ID + 1 }, 'bridge');
|
||||
await dispatch(sentEvent, 'send');
|
||||
await dispatch({ ...sentEvent, target_id: PEER_ID + 1 }, 'bridge');
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import { ApiHandler } from '../src/api-handler';
|
||||
import { elementsToOneBotSegments } from '../src/event-converter';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
|
||||
import { MediaIndexer } from '../src/media-indexer';
|
||||
import { MediaStore } from '../src/media-store';
|
||||
import { MessageStore } from '../src/message-store';
|
||||
import { sendGroupMessage, sendPrivateMessage } from '../src/modules/message-actions';
|
||||
import { segmentsToRawMessage } from '../src/helper/cq';
|
||||
|
||||
const cleanups: Array<() => void | Promise<void>> = [];
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
function fixture() {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'self-sent-media-'));
|
||||
cleanups.push(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const dbPath = path.join(directory, 'messages.db');
|
||||
const groupFile = {
|
||||
getPttUrl: vi.fn(async () => 'https://media.example/group-record?rkey=fresh'),
|
||||
getPrivatePttUrl: vi.fn(async () => 'https://media.example/private-record?rkey=fresh'),
|
||||
getVideoUrl: vi.fn(async () => 'https://media.example/group-video?rkey=fresh'),
|
||||
getPrivateVideoUrl: vi.fn(async () => 'https://media.example/private-video?rkey=fresh'),
|
||||
};
|
||||
let sequence = 1;
|
||||
const send = vi.fn(async (_target: number, elements: MessageElement[]) => {
|
||||
for (const [index, element] of elements.entries()) {
|
||||
if (element.type !== 'record' && element.type !== 'video') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The protocol upload writes the resource reference onto the sent element.
|
||||
Object.assign(element, {
|
||||
fileId: `${element.type}-${sequence}-${index}`,
|
||||
fileName: `${element.type}.media`,
|
||||
fileSize: 3,
|
||||
md5Hex: 'aa'.repeat(16),
|
||||
sha1Hex: 'bb'.repeat(20),
|
||||
mediaNode: { fileUuid: `${element.type}-${sequence}-${index}`, storeId: 1 },
|
||||
});
|
||||
}
|
||||
|
||||
return { sequence: sequence++, clientSequence: 1, random: 1, timestamp: 1700000000 };
|
||||
});
|
||||
|
||||
async function open() {
|
||||
const messageStore = new MessageStore(dbPath);
|
||||
await messageStore.initialization;
|
||||
const mediaStore = new MediaStore(dbPath);
|
||||
await mediaStore.initialization;
|
||||
const indexer = new MediaIndexer(mediaStore);
|
||||
|
||||
const close = async () => {
|
||||
await mediaStore.close();
|
||||
await messageStore.close();
|
||||
};
|
||||
|
||||
cleanups.push(close);
|
||||
const ref = {
|
||||
selfId: 10001,
|
||||
uin: '10001',
|
||||
messageStore,
|
||||
mediaStore,
|
||||
bridge: {
|
||||
identity: { nickname: 'self' },
|
||||
apis: { message: { sendPrivate: send, sendGroup: send }, groupFile },
|
||||
},
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: async (...args: Parameters<MediaIndexer['remember']>) =>
|
||||
await indexer.remember(...args),
|
||||
},
|
||||
cacheMessageMeta: messageStore.storeMeta.bind(messageStore),
|
||||
} as unknown as OneBotInstanceContext;
|
||||
return {
|
||||
ref,
|
||||
handler: new ApiHandler(buildApiContext(ref)),
|
||||
close: async () => {
|
||||
cleanups.splice(cleanups.indexOf(close), 1);
|
||||
await close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { open, groupFile, directory };
|
||||
}
|
||||
|
||||
describe('self-sent remote media', () => {
|
||||
it.each([
|
||||
['error', 'https://original.example/failed.jpg'],
|
||||
['empty', 'https://original.example/failed.jpg'],
|
||||
['error', ''],
|
||||
['empty', ''],
|
||||
] as const)(
|
||||
'keeps the message image URL when refresh returns %s (original=%s)',
|
||||
async (outcome, originalUrl) => {
|
||||
const { open } = fixture();
|
||||
const { ref, handler } = await open();
|
||||
|
||||
for (const file of ['failed.jpg', 'fresh.jpg']) {
|
||||
await ref.mediaStore.rememberImage({
|
||||
file,
|
||||
fileName: file,
|
||||
fileSize: 1,
|
||||
subType: 0,
|
||||
summary: '',
|
||||
isGroup: true,
|
||||
sessionId: 20002,
|
||||
imageUrl: `https://resource.example/${file}`,
|
||||
url: `https://cached.example/${file}`,
|
||||
});
|
||||
}
|
||||
|
||||
const resolver = vi.fn();
|
||||
|
||||
if (outcome === 'error') {
|
||||
resolver.mockRejectedValueOnce(new Error('QQ resource expired'));
|
||||
} else {
|
||||
resolver.mockResolvedValueOnce('');
|
||||
}
|
||||
|
||||
resolver.mockResolvedValueOnce('https://fresh.example/fresh.jpg');
|
||||
ref.converterCtx.imageUrlResolver = resolver;
|
||||
const message = [
|
||||
{ type: 'image', data: { file: 'failed.jpg', url: originalUrl } },
|
||||
{ type: 'image', data: { file_id: 'fresh.jpg', url: '' } },
|
||||
{
|
||||
type: 'image',
|
||||
data: { file: 'missing.jpg', url: 'https://original.example/missing.jpg' },
|
||||
},
|
||||
];
|
||||
await ref.messageStore.storeEvent(42, true, 20002, 42, 'GroupMessage', {
|
||||
message_id: 42,
|
||||
message,
|
||||
raw_message: segmentsToRawMessage(message),
|
||||
});
|
||||
const original = await ref.messageStore.findEvent(42);
|
||||
|
||||
expect(await handler.handle('get_msg', { message_id: 42 })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message: [
|
||||
{ type: 'image', data: { file: 'failed.jpg', url: originalUrl } },
|
||||
{
|
||||
type: 'image',
|
||||
data: { file_id: 'fresh.jpg', url: 'https://fresh.example/fresh.jpg' },
|
||||
},
|
||||
{
|
||||
type: 'image',
|
||||
data: {
|
||||
file: 'missing.jpg',
|
||||
url: 'https://original.example/missing.jpg',
|
||||
},
|
||||
},
|
||||
],
|
||||
raw_message: `[CQ:image,file=failed.jpg,url=${originalUrl}][CQ:image,file=,url=https://fresh.example/fresh.jpg][CQ:image,file=missing.jpg,url=https://original.example/missing.jpg]`,
|
||||
},
|
||||
});
|
||||
expect(resolver).toHaveBeenCalledTimes(2);
|
||||
expect(await ref.messageStore.findEvent(42)).toEqual(original);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ type: 'record', isGroup: false, method: 'getPrivatePttUrl' },
|
||||
{ type: 'record', isGroup: true, method: 'getPttUrl' },
|
||||
{ type: 'video', isGroup: false, method: 'getPrivateVideoUrl' },
|
||||
{ type: 'video', isGroup: true, method: 'getVideoUrl' },
|
||||
] as const)(
|
||||
'refreshes $type (group=$isGroup) from its own snapshot after restart',
|
||||
async ({ type, isGroup, method }) => {
|
||||
const { open, groupFile } = fixture();
|
||||
let account = await open();
|
||||
const send = isGroup ? sendGroupMessage : sendPrivateMessage;
|
||||
const { messageId } = await send(
|
||||
account.ref,
|
||||
20002,
|
||||
[{ type, data: { file: 'base64://AQID' } }],
|
||||
false,
|
||||
);
|
||||
const snapshot = (await account.ref.messageStore.findMedia(messageId))![0]!;
|
||||
expect(snapshot.mediaNode).toEqual({ fileUuid: `${type}-1-0`, storeId: 1 });
|
||||
expect(
|
||||
JSON.stringify(await account.ref.messageStore.findEvent(messageId)),
|
||||
).not.toContain('base64://');
|
||||
expect(JSON.stringify(snapshot)).not.toContain('base64://');
|
||||
expect(groupFile[method]).not.toHaveBeenCalled();
|
||||
await account.close();
|
||||
account = await open();
|
||||
|
||||
// A later upload with the same display filename must not replace the old reference.
|
||||
await send(
|
||||
account.ref,
|
||||
20002,
|
||||
[{ type, data: { file: 'https://upload.example/source' } }],
|
||||
false,
|
||||
);
|
||||
const response = await account.handler.handle('get_msg', { message_id: messageId });
|
||||
const url = `https://media.example/${isGroup ? 'group' : 'private'}-${type}?rkey=fresh`;
|
||||
expect(response).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message: [{ type, data: { file: `${type}.media`, url } }],
|
||||
raw_message: `[CQ:${type},file=${type}.media,url=${url}]`,
|
||||
},
|
||||
});
|
||||
expect(groupFile[method].mock.calls).toEqual([
|
||||
isGroup ? [20002, snapshot.mediaNode] : [snapshot.mediaNode],
|
||||
]);
|
||||
expect((await account.ref.messageStore.findMedia(messageId))![0]).toEqual(snapshot);
|
||||
expect(JSON.stringify(response)).not.toContain('mediaNode');
|
||||
expect((await account.ref.messageStore.findEvent(messageId))!.message).toEqual([
|
||||
{ type, data: { file: `${type}.media`, url: '' } },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('get_record refreshes the remote URL after the local upload source is removed', async () => {
|
||||
const { open, groupFile, directory } = fixture();
|
||||
const { ref, handler } = await open();
|
||||
const source = path.join(directory, 'original.media');
|
||||
fs.writeFileSync(source, 'media');
|
||||
await sendGroupMessage(ref, 20002, [{ type: 'record', data: { file: source } }], false);
|
||||
fs.unlinkSync(source);
|
||||
const remote = groupFile.getPttUrl;
|
||||
|
||||
for (const key of ['first', 'second']) {
|
||||
remote.mockResolvedValueOnce(`https://media.example/record?rkey=${key}`);
|
||||
const result = await handler.handle('get_record', { file: 'record.media' });
|
||||
expect(result).toMatchObject({
|
||||
status: 'ok',
|
||||
data: { url: `https://media.example/record?rkey=${key}` },
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain('original.media');
|
||||
}
|
||||
|
||||
expect(remote).toHaveBeenCalledTimes(2);
|
||||
expect(remote).toHaveBeenCalledWith(20002, { fileUuid: 'record-1-0', storeId: 1 });
|
||||
});
|
||||
it('returns a historical message unchanged without requiring media metadata', async () => {
|
||||
const { open, groupFile } = fixture();
|
||||
const { ref, handler } = await open();
|
||||
await sendPrivateMessage(
|
||||
ref,
|
||||
20002,
|
||||
[{ type: 'record', data: { file: 'base64://AQID' } }],
|
||||
false,
|
||||
);
|
||||
await ref.messageStore.storeEvent(42, false, 20002, 42, 'private_message_sent', {
|
||||
message_id: 42,
|
||||
message_type: 'private',
|
||||
message: [
|
||||
{
|
||||
type: 'record',
|
||||
data: { file: 'record.media', url: 'https://old.example/voice' },
|
||||
},
|
||||
],
|
||||
raw_message: '[CQ:record,file=record.media,url=https://old.example/voice]',
|
||||
});
|
||||
expect(await handler.handle('get_msg', { message_id: 42 })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message: [
|
||||
{
|
||||
type: 'record',
|
||||
data: { file: 'record.media', url: 'https://old.example/voice' },
|
||||
},
|
||||
],
|
||||
raw_message: '[CQ:record,file=record.media,url=https://old.example/voice]',
|
||||
},
|
||||
});
|
||||
expect(groupFile.getPrivatePttUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('indexes self-sent voice for get_record and requests a fresh URL on each read', async () => {
|
||||
const { open, groupFile } = fixture();
|
||||
const { ref, handler } = await open();
|
||||
await sendPrivateMessage(
|
||||
ref,
|
||||
20002,
|
||||
[{ type: 'record', data: { file: 'base64://AQID' } }],
|
||||
false,
|
||||
);
|
||||
let file = 'record.media';
|
||||
|
||||
for (const key of ['first', 'second']) {
|
||||
groupFile.getPrivatePttUrl.mockResolvedValueOnce(
|
||||
`https://media.example/voice?rkey=${key}`,
|
||||
);
|
||||
expect(await handler.handle('get_record', { file })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
file: `https://media.example/voice?rkey=${key}`,
|
||||
url: `https://media.example/voice?rkey=${key}`,
|
||||
},
|
||||
});
|
||||
file = `https://media.example/voice?rkey=${key}`;
|
||||
}
|
||||
|
||||
expect(groupFile.getPrivatePttUrl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('get_record reports remote failure without using the upload source', async () => {
|
||||
const { open, groupFile } = fixture();
|
||||
const { ref, handler } = await open();
|
||||
await sendPrivateMessage(
|
||||
ref,
|
||||
20002,
|
||||
[{ type: 'record', data: { file: 'https://upload.example/source' } }],
|
||||
false,
|
||||
);
|
||||
groupFile.getPrivatePttUrl.mockRejectedValueOnce(new Error('QQ resource expired'));
|
||||
expect(await handler.handle('get_record', { file: 'record.media' })).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 100,
|
||||
wording: 'QQ resource expired',
|
||||
});
|
||||
});
|
||||
|
||||
it.each(['record', 'video'] as const)(
|
||||
'keeps a failed %s URL and refreshes subsequent media without losing text',
|
||||
async (type) => {
|
||||
const { open, groupFile } = fixture();
|
||||
const { ref, handler } = await open();
|
||||
const remote = type === 'record' ? groupFile.getPttUrl : groupFile.getVideoUrl;
|
||||
const segments = await elementsToOneBotSegments(
|
||||
ref.converterCtx,
|
||||
[
|
||||
{ type: 'text', text: 'before ' },
|
||||
{
|
||||
type,
|
||||
fileName: 'expired.media',
|
||||
url: 'https://old.example/expired',
|
||||
mediaNode: { fileUuid: 'expired' },
|
||||
},
|
||||
{ type: 'text', text: ' between ' },
|
||||
{
|
||||
type: 'image',
|
||||
fileId: 'photo.jpg',
|
||||
imageUrl: 'https://old.example/photo.jpg',
|
||||
},
|
||||
{
|
||||
type,
|
||||
fileName: 'available.media',
|
||||
url: 'https://old.example/available',
|
||||
mediaNode: { fileUuid: 'available' },
|
||||
},
|
||||
{ type, fileName: 'empty.media', url: '' },
|
||||
{ type: 'text', text: ' after' },
|
||||
],
|
||||
true,
|
||||
20002,
|
||||
);
|
||||
await ref.messageStore.storeEvent(42, true, 20002, 42, 'GroupMessage', {
|
||||
message_id: 42,
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
});
|
||||
const original = await ref.messageStore.findEvent(42);
|
||||
const entries: LogEntry[] = [];
|
||||
cleanups.push(subscribeLogs((entry) => entries.push(entry)));
|
||||
remote.mockRejectedValueOnce(new Error('QQ resource expired'));
|
||||
remote.mockResolvedValueOnce('https://media.example/available?rkey=fresh');
|
||||
|
||||
expect(await handler.handle('get_msg', { message_id: 42 })).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
message: [
|
||||
{ type: 'text', data: { text: 'before ' } },
|
||||
{
|
||||
type,
|
||||
data: { file: 'expired.media', url: 'https://old.example/expired' },
|
||||
},
|
||||
{ type: 'text', data: { text: ' between ' } },
|
||||
{
|
||||
type: 'image',
|
||||
data: { file: 'photo.jpg', url: 'https://old.example/photo.jpg' },
|
||||
},
|
||||
{
|
||||
type,
|
||||
data: {
|
||||
file: 'available.media',
|
||||
url: 'https://media.example/available?rkey=fresh',
|
||||
},
|
||||
},
|
||||
{ type, data: { file: 'empty.media', url: '' } },
|
||||
{ type: 'text', data: { text: ' after' } },
|
||||
],
|
||||
raw_message: `before [CQ:${type},file=expired.media,url=https://old.example/expired] between [CQ:image,file=photo.jpg,url=https://old.example/photo.jpg][CQ:${type},file=available.media,url=https://media.example/available?rkey=fresh][CQ:${type},file=empty.media,url=] after`,
|
||||
},
|
||||
});
|
||||
expect(remote.mock.calls).toEqual([
|
||||
[20002, { fileUuid: 'expired' }],
|
||||
[20002, { fileUuid: 'available' }],
|
||||
]);
|
||||
expect(
|
||||
entries.some(
|
||||
(entry) =>
|
||||
entry.level === 'warn' &&
|
||||
entry.message.includes('message_id=42') &&
|
||||
entry.message.includes(`type=${type}`) &&
|
||||
entry.message.includes('QQ resource expired'),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(await ref.messageStore.findEvent(42)).toEqual(original);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -22,7 +22,7 @@ import { MessageStore } from '../src/message-store';
|
||||
import { sendGroupMessage } from '../src/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
return new Proxy({ identity: { nickname: 'SnowLuma' }, ...overrides } as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
@@ -34,16 +34,25 @@ function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
}
|
||||
|
||||
function makeCtx(bridge: BridgeInterface, messageStore?: MessageStore): OneBotInstanceContext {
|
||||
const store = messageStore ?? ({ findEvent: () => null, resolveReplySequence: () => 0 } as any);
|
||||
const store =
|
||||
messageStore ??
|
||||
({ findEvent: () => null, resolveReplySequence: () => 0, storeEvent: vi.fn() } as any);
|
||||
return {
|
||||
uin: '10001',
|
||||
selfId: 10001,
|
||||
bridge,
|
||||
messageStore: store,
|
||||
cacheMessageMeta: messageStore
|
||||
? (messageId, meta) => messageStore.storeMeta(messageId, meta)
|
||||
? async (messageId, meta) => await messageStore.storeMeta(messageId, meta)
|
||||
: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
@@ -97,6 +106,7 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
|
||||
it('keeps an OIDB-only group file id separate from a QQ server sequence (#254)', async () => {
|
||||
const messageStore = new MessageStore(':memory:');
|
||||
await messageStore.initialization;
|
||||
|
||||
try {
|
||||
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
|
||||
@@ -123,19 +133,22 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
);
|
||||
|
||||
expect(result.messageId).not.toBe(0);
|
||||
expect(messageStore.findMeta(result.messageId)).toMatchObject({
|
||||
expect(await messageStore.findMeta(result.messageId)).toMatchObject({
|
||||
sequence: 0,
|
||||
sequenceAuthoritative: false,
|
||||
});
|
||||
expect(messageStore.findEvent(result.messageId)).toMatchObject({ message_seq: 0 });
|
||||
expect(messageStore.findLatestAuthoritativeSequence(true, 12345)).toBeNull();
|
||||
expect(await messageStore.findEvent(result.messageId)).toMatchObject({
|
||||
message_seq: 0,
|
||||
});
|
||||
expect(await messageStore.findLatestAuthoritativeSequence(true, 12345)).toBeNull();
|
||||
} finally {
|
||||
messageStore.close();
|
||||
await messageStore.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('skips an OIDB-only group-file reply and sends the remaining content (#254)', async () => {
|
||||
const messageStore = new MessageStore(':memory:');
|
||||
await messageStore.initialization;
|
||||
|
||||
try {
|
||||
const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt);
|
||||
@@ -175,12 +188,13 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
).resolves.toMatchObject({ messageId: expect.any(Number) });
|
||||
expect(sendGroup).toHaveBeenCalledWith(12345, [{ type: 'text', text: 'received' }]);
|
||||
} finally {
|
||||
messageStore.close();
|
||||
await messageStore.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('skips a local-only reply id even when its full event was not cached', async () => {
|
||||
const messageStore = new MessageStore(':memory:');
|
||||
await messageStore.initialization;
|
||||
|
||||
try {
|
||||
const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt);
|
||||
@@ -190,7 +204,7 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
resolveUserUid: vi.fn(),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge, messageStore);
|
||||
messageStore.storeMeta(77, {
|
||||
await messageStore.storeMeta(77, {
|
||||
isGroup: true,
|
||||
targetId: 12345,
|
||||
sequence: 0,
|
||||
@@ -214,12 +228,13 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
).resolves.toMatchObject({ messageId: expect.any(Number) });
|
||||
expect(sendGroup).toHaveBeenCalledWith(12345, [{ type: 'text', text: 'received' }]);
|
||||
} finally {
|
||||
messageStore.close();
|
||||
await messageStore.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not apply local-only reply metadata from another group', async () => {
|
||||
const messageStore = new MessageStore(':memory:');
|
||||
await messageStore.initialization;
|
||||
|
||||
try {
|
||||
const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt);
|
||||
@@ -229,7 +244,7 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
resolveUserUid: vi.fn(),
|
||||
} as any);
|
||||
const ctx = makeCtx(bridge, messageStore);
|
||||
messageStore.storeMeta(77, {
|
||||
await messageStore.storeMeta(77, {
|
||||
isGroup: true,
|
||||
targetId: 99999,
|
||||
sequence: 0,
|
||||
@@ -255,7 +270,7 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
{ type: 'text', text: 'direct sequence' },
|
||||
]);
|
||||
} finally {
|
||||
messageStore.close();
|
||||
await messageStore.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -341,10 +356,7 @@ describe('send_group_msg with {type:"file"} segment', () => {
|
||||
_name: string,
|
||||
_folder: string,
|
||||
_doUpload: boolean,
|
||||
) => ({
|
||||
fileId: 'auto-fid',
|
||||
fileHash: null,
|
||||
}),
|
||||
) => ({ fileId: 'auto-fid', fileHash: null }),
|
||||
);
|
||||
const publish = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
|
||||
@@ -19,7 +19,7 @@ import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import { sendPrivateMessage } from '../src/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
return new Proxy({ identity: { nickname: 'SnowLuma' }, ...overrides } as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
@@ -33,10 +33,18 @@ function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
selfId: 10001,
|
||||
bridge,
|
||||
messageStore: { findEvent: () => null } as any,
|
||||
messageStore: { findEvent: () => null, storeEvent: vi.fn() } as any,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import { sendPrivateMessage } from '../src/modules/message-actions';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
return new Proxy({ identity: { nickname: 'SnowLuma' }, ...overrides } as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
@@ -43,9 +43,17 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||
findEvent: () => null,
|
||||
findMeta: () => null,
|
||||
resolveReplySequence: () => 42,
|
||||
storeEvent: vi.fn(),
|
||||
} as any,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import { sendGroupMessage, videoNeedsFileFallback } from '../src/modules/message
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
return new Proxy({ identity: { nickname: 'SnowLuma' }, ...overrides } as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
@@ -31,10 +31,22 @@ function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
selfId: 10001,
|
||||
bridge,
|
||||
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any,
|
||||
messageStore: {
|
||||
findEvent: () => null,
|
||||
resolveReplySequence: () => 0,
|
||||
storeEvent: vi.fn(),
|
||||
} as any,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as any,
|
||||
converterCtx: {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
},
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
@@ -51,10 +63,7 @@ describe('send_group_msg large-video fallback', () => {
|
||||
_name: string,
|
||||
_folder: string,
|
||||
_doUpload: boolean,
|
||||
) => ({
|
||||
fileId: 'auto-fid',
|
||||
fileHash: null,
|
||||
}),
|
||||
) => ({ fileId: 'auto-fid', fileHash: null }),
|
||||
);
|
||||
const publish = vi.fn();
|
||||
const bridge = fakeBridge({
|
||||
|
||||
Reference in new issue
Block a user