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
@@ -95,19 +95,26 @@ describe('messageStore — SQLite writes per send', () => {
|
||||
// branch which is a different cost profile.
|
||||
let id1 = 100_000;
|
||||
let id2 = 200_000;
|
||||
bench('storeMeta', () => {
|
||||
store.storeMeta(id1++, META);
|
||||
bench('storeMeta', async () => {
|
||||
await store.storeMeta(id1++, META);
|
||||
});
|
||||
bench('storeEvent (JSON payload ~250 bytes)', () => {
|
||||
store.storeEvent(id2++, true, META.targetId, META.sequence, META.eventName, SAMPLE_EVENT);
|
||||
bench('storeEvent (JSON payload ~250 bytes)', async () => {
|
||||
await store.storeEvent(
|
||||
id2++,
|
||||
true,
|
||||
META.targetId,
|
||||
META.sequence,
|
||||
META.eventName,
|
||||
SAMPLE_EVENT,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('messageStore — read paths', () => {
|
||||
describe('messageStore — read paths', async () => {
|
||||
// Seed a small set of records so findEvent / findMeta have hits.
|
||||
for (let i = 0; i < 100; i++) {
|
||||
store.storeMeta(500_000 + i, META);
|
||||
store.storeEvent(
|
||||
await store.storeMeta(500_000 + i, META);
|
||||
await store.storeEvent(
|
||||
600_000 + i,
|
||||
true,
|
||||
META.targetId,
|
||||
@@ -117,13 +124,13 @@ describe('messageStore — read paths', () => {
|
||||
);
|
||||
}
|
||||
|
||||
bench('findMeta (hit)', () => {
|
||||
store.findMeta(500_050);
|
||||
bench('findMeta (hit)', async () => {
|
||||
await store.findMeta(500_050);
|
||||
});
|
||||
bench('findMeta (miss)', () => {
|
||||
store.findMeta(9_999_999);
|
||||
bench('findMeta (miss)', async () => {
|
||||
await store.findMeta(9_999_999);
|
||||
});
|
||||
bench('findEvent (hit, JSON.parse on read)', () => {
|
||||
store.findEvent(600_050);
|
||||
bench('findEvent (hit, JSON.parse on read)', async () => {
|
||||
await store.findEvent(600_050);
|
||||
});
|
||||
});
|
||||
@@ -112,12 +112,16 @@
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
"@snowluma/websocket": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { FriendDressError } from '@snowluma/protocol/web/friend-dress';
|
||||
@@ -398,6 +399,13 @@ function primitiveText(value: unknown): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
const forwardMessagesField = f
|
||||
.message()
|
||||
.optional()
|
||||
.describe(
|
||||
'转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。',
|
||||
);
|
||||
|
||||
const forwardPreviewParams = {
|
||||
source: f.string().optional(),
|
||||
summary: f.string().optional(),
|
||||
@@ -451,7 +459,7 @@ async function groupTodoRun(
|
||||
ctx: ApiActionContext,
|
||||
op: (groupId: number, msgSeq: bigint) => Promise<void>,
|
||||
) {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
@@ -624,7 +632,7 @@ export const actions = [
|
||||
.filter((message): message is GroupEssenceMessage => message !== null)
|
||||
.map((message) => projectEssenceMessage(message, p.group_id));
|
||||
|
||||
ctx.cacheMessageMetas(
|
||||
await ctx.cacheMessageMetas(
|
||||
projections.map(({ messageId, meta }) => ({
|
||||
messageId,
|
||||
meta,
|
||||
@@ -649,7 +657,7 @@ export const actions = [
|
||||
is_set: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
return failedResponse(
|
||||
@@ -829,7 +837,7 @@ export const actions = [
|
||||
group_id: f.groupId().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
return failedResponse(
|
||||
@@ -858,7 +866,7 @@ export const actions = [
|
||||
user_id: f.userId().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta || meta.isGroup) {
|
||||
return failedResponse(
|
||||
@@ -887,7 +895,7 @@ export const actions = [
|
||||
target_id: f.uint().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
@@ -989,8 +997,8 @@ export const actions = [
|
||||
name: 'upload_forward_msg',
|
||||
summary: '上传转发消息',
|
||||
params: {
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
group_id: f.groupId().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
@@ -1021,8 +1029,8 @@ export const actions = [
|
||||
name: 'upload_foward_msg',
|
||||
summary: '上传转发消息(别名拼写)',
|
||||
params: {
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
group_id: f.groupId().optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
@@ -1072,6 +1080,8 @@ export const actions = [
|
||||
name: 'get_record',
|
||||
summary: '获取语音信息;传 out_format 则服务端转码并附带 base64',
|
||||
readOnly: true,
|
||||
returns:
|
||||
'语音信息(file/url 为向 QQ 获取的当前下载地址);资源元数据缺失或远端获取失败时返回错误。out_format 指定时附带转码后的 base64。',
|
||||
params: {
|
||||
file: f.string().default('').role('record'),
|
||||
file_id: f.string().default('').role('file_id'),
|
||||
@@ -1264,7 +1274,7 @@ export const actions = [
|
||||
summary: '标记全部已读',
|
||||
params: {},
|
||||
run: async (_p, ctx) => {
|
||||
const sessions = ctx.listReadSessions();
|
||||
const sessions = await ctx.listReadSessions();
|
||||
await ctx.bridge.apis.message.markAllRead(sessions.groupIds, sessions.privateUserIds);
|
||||
return okResponse();
|
||||
},
|
||||
@@ -2911,8 +2921,8 @@ export const actions = [
|
||||
// group_id/user_id are routing hints, not identity: 0 means "this branch
|
||||
// does not apply" and must not error. int({min:0}) optional, not groupId.
|
||||
params: {
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
message_type: f.string().optional(),
|
||||
group_id: f.int({ min: 0 }).optional(),
|
||||
user_id: f.int({ min: 0 }).optional(),
|
||||
@@ -2969,8 +2979,8 @@ export const actions = [
|
||||
summary: '发送群合并转发',
|
||||
returns: '{ message_id, res_id, forward_id }',
|
||||
params: {
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
...forwardPreviewParams,
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
@@ -2999,8 +3009,8 @@ export const actions = [
|
||||
returns: '{ message_id, res_id, forward_id }',
|
||||
params: {
|
||||
user_id: f.userId(),
|
||||
messages: f.message().optional(),
|
||||
message: f.message().optional(),
|
||||
messages: forwardMessagesField,
|
||||
message: forwardMessagesField,
|
||||
...forwardPreviewParams,
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
@@ -3027,7 +3037,8 @@ export const actions = [
|
||||
name: 'get_forward_msg',
|
||||
summary: '获取合并转发消息(id 或 message_id)',
|
||||
readOnly: true,
|
||||
returns: '{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件,内部字段不固定)。',
|
||||
returns:
|
||||
'{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件);reply 保留 id,有内嵌引用内容时附带 message 和可用的 qq/time/seq,可作为转发节点 content 再次发送。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -3047,7 +3058,7 @@ export const actions = [
|
||||
const numericMessageId = integerFromDecimalString(p.message_id);
|
||||
|
||||
if (numericMessageId > 0) {
|
||||
const event = ctx.getMessage(numericMessageId);
|
||||
const event = await ctx.getMessage(numericMessageId);
|
||||
const segments = Array.isArray(event?.message) ? event.message : [];
|
||||
|
||||
for (const seg of segments) {
|
||||
@@ -3306,7 +3317,7 @@ export const actions = [
|
||||
return { todo, messageId, meta };
|
||||
});
|
||||
|
||||
ctx.cacheMessageMetas(
|
||||
await ctx.cacheMessageMetas(
|
||||
projections.map(({ messageId, meta }) => ({
|
||||
messageId,
|
||||
meta,
|
||||
@@ -3314,8 +3325,8 @@ export const actions = [
|
||||
);
|
||||
|
||||
return okResponse(
|
||||
projections.map(({ todo, messageId }) => {
|
||||
const cached = ctx.getMessage(messageId)?.message;
|
||||
await mapWithConcurrency(projections, 8, async ({ todo, messageId }) => {
|
||||
const cached = (await ctx.getMessage(messageId))?.message;
|
||||
return {
|
||||
message_id: messageId,
|
||||
message_seq: todo.sequence,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import type { ApiActionContext } from '../api-handler';
|
||||
import { defineAction, groupAction, f, type Field } from '../action-kit';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
@@ -21,60 +20,6 @@ function sendMsgOptionalGroupId(): Field<number | undefined> {
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
/**
|
||||
* Re-sign image URLs in a stored message event at read time. `get_msg`
|
||||
* returns a copy persisted when the message first arrived, and image rkeys
|
||||
* expire — so walk the segment array and refresh each image URL through
|
||||
* `ctx.getImageInfo`, which mints a current rkey. Best-effort and in-place;
|
||||
* `findEvent` returns a fresh parse, so mutating the array is safe.
|
||||
*/
|
||||
async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise<void> {
|
||||
const segments = event.message;
|
||||
|
||||
if (!Array.isArray(segments)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const seg of segments) {
|
||||
if (!seg || typeof seg !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const segment = seg as { type?: unknown; data?: Record<string, JsonValue> };
|
||||
|
||||
if (segment.type !== 'image') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = segment.data;
|
||||
|
||||
if (!data || typeof data !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const file =
|
||||
typeof data.file === 'string'
|
||||
? data.file
|
||||
: typeof data.file_id === 'string'
|
||||
? data.file_id
|
||||
: '';
|
||||
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const info = await ctx.getImageInfo(file);
|
||||
|
||||
if (info && typeof info.url === 'string' && info.url) {
|
||||
data.url = info.url;
|
||||
}
|
||||
} catch {
|
||||
// Keep the stored URL when the refresh fails.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'send_custom_face',
|
||||
@@ -204,10 +149,10 @@ export const actions = [
|
||||
summary: '获取消息',
|
||||
readOnly: true,
|
||||
returns:
|
||||
'消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。',
|
||||
'消息事件对象(去除 post_type/self_id,附带 real_id);逐个尝试刷新图片、语音和视频 URL,成功使用新地址,失败保留该段原地址并继续返回消息;地址更新时同步 raw_message。',
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const data = ctx.getMessage(p.message_id);
|
||||
const data = await ctx.getMessage(p.message_id);
|
||||
|
||||
if (!data) {
|
||||
log.warn('[get_msg] miss message_id=%d', p.message_id);
|
||||
@@ -218,7 +163,7 @@ export const actions = [
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? p.message_id) as JsonValue;
|
||||
await refreshStoredImageUrls(result, ctx);
|
||||
await ctx.refreshMessageMedia(p.message_id, result);
|
||||
return okResponse(result);
|
||||
},
|
||||
}),
|
||||
@@ -228,7 +173,7 @@ export const actions = [
|
||||
summary: '撤回消息',
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
const meta = await ctx.getMessageMeta(p.message_id);
|
||||
|
||||
if (!meta) {
|
||||
return failedResponse(
|
||||
|
||||
@@ -55,10 +55,13 @@ export interface ApiActionContext {
|
||||
getLoginInfo: () => { userId: number; nickname: string };
|
||||
isOnline: () => boolean;
|
||||
getUptimeMs: () => number;
|
||||
getMessage: (messageId: number) => JsonObject | null;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null;
|
||||
cacheMessageMetas: (entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>) => void;
|
||||
listReadSessions: () => ReadSessionTargets;
|
||||
getMessage: (messageId: number) => JsonObject | null | Promise<JsonObject | null>;
|
||||
refreshMessageMedia: (messageId: number, event: JsonObject) => Promise<void>;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null | Promise<MessageMeta | null>;
|
||||
cacheMessageMetas: (
|
||||
entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>,
|
||||
) => void | Promise<void>;
|
||||
listReadSessions: () => ReadSessionTargets | Promise<ReadSessionTargets>;
|
||||
sendPrivateMessage: (
|
||||
userId: number,
|
||||
message: JsonValue,
|
||||
|
||||
@@ -295,7 +295,7 @@ export const ELEMENT_CODECS = {
|
||||
const eventName = ctx.isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: privateMessageEventName(sentBySelf, false);
|
||||
const id = resolveReplyId(
|
||||
const id = await resolveReplyId(
|
||||
ctx.isGroup,
|
||||
ctx.sessionId,
|
||||
element.replySeq ?? 0,
|
||||
@@ -328,10 +328,10 @@ export const ELEMENT_CODECS = {
|
||||
return null;
|
||||
}
|
||||
|
||||
const meta = options?.resolveReplyMeta?.(id) ?? null;
|
||||
const meta = (await options?.resolveReplyMeta?.(id)) ?? null;
|
||||
|
||||
if (options?.resolveReplySequence) {
|
||||
const resolved = options.resolveReplySequence(id);
|
||||
const resolved = await options.resolveReplySequence(id);
|
||||
|
||||
if (typeof resolved === 'number' && resolved > 0) {
|
||||
const element: MessageElement = {
|
||||
@@ -400,7 +400,7 @@ export const ELEMENT_CODECS = {
|
||||
}
|
||||
|
||||
if (ctx.mediaSegmentSink) {
|
||||
ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
|
||||
await ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
|
||||
}
|
||||
|
||||
return { type: 'image', data };
|
||||
@@ -437,7 +437,7 @@ export const ELEMENT_CODECS = {
|
||||
};
|
||||
|
||||
if (ctx.mediaSegmentSink) {
|
||||
ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
|
||||
await ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
|
||||
}
|
||||
|
||||
return { type: 'record', data };
|
||||
@@ -468,7 +468,7 @@ export const ELEMENT_CODECS = {
|
||||
};
|
||||
|
||||
if (ctx.mediaSegmentSink) {
|
||||
ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
|
||||
await ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
|
||||
}
|
||||
|
||||
return { type: 'video', data };
|
||||
|
||||
@@ -40,7 +40,7 @@ export type MessageIdResolver = (
|
||||
eventName: string,
|
||||
timestamp?: number,
|
||||
replyElements?: readonly MessageElement[],
|
||||
) => number;
|
||||
) => number | Promise<number>;
|
||||
|
||||
export type MediaSegmentSink = (
|
||||
mediaType: 'image' | 'record' | 'video',
|
||||
@@ -48,7 +48,7 @@ export type MediaSegmentSink = (
|
||||
data: JsonObject,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
) => void;
|
||||
) => void | Promise<void>;
|
||||
|
||||
// ─────────────── context ───────────────
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ async function convertPrivateMessage(
|
||||
event.kind === 'friend_message'
|
||||
? privateMessageEventName(isSelf, hasCanonicalNtSequence)
|
||||
: PRIVATE_MESSAGE_EVENT;
|
||||
const messageId = applyMessageIdResolver(
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
false,
|
||||
sessionId,
|
||||
@@ -104,7 +104,7 @@ export async function convertGroupMessage(
|
||||
): Promise<JsonObject> {
|
||||
const isSelf = event.senderUin === ctx.selfId;
|
||||
const postType = isSelf ? 'message_sent' : 'message';
|
||||
const messageId = applyMessageIdResolver(
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
true,
|
||||
event.groupId,
|
||||
|
||||
@@ -84,8 +84,11 @@ export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): Jso
|
||||
});
|
||||
}
|
||||
|
||||
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
export async function convertFriendRecall(
|
||||
ctx: ConverterContext,
|
||||
event: FriendRecall,
|
||||
): Promise<JsonObject> {
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
false,
|
||||
event.userUin,
|
||||
@@ -100,8 +103,11 @@ export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall):
|
||||
});
|
||||
}
|
||||
|
||||
export function convertGroupRecall(ctx: ConverterContext, event: GroupRecall): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
export async function convertGroupRecall(
|
||||
ctx: ConverterContext,
|
||||
event: GroupRecall,
|
||||
): Promise<JsonObject> {
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
true,
|
||||
event.groupId,
|
||||
@@ -143,8 +149,11 @@ export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonO
|
||||
});
|
||||
}
|
||||
|
||||
export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
export async function convertGroupEssence(
|
||||
ctx: ConverterContext,
|
||||
event: GroupEssence,
|
||||
): Promise<JsonObject> {
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
true,
|
||||
event.groupId,
|
||||
@@ -265,11 +274,11 @@ export function convertFriendInputStatus(
|
||||
});
|
||||
}
|
||||
|
||||
export function convertGroupMsgEmojiLike(
|
||||
export async function convertGroupMsgEmojiLike(
|
||||
ctx: ConverterContext,
|
||||
event: GroupMsgEmojiLike,
|
||||
): JsonObject {
|
||||
const messageId = applyMessageIdResolver(
|
||||
): Promise<JsonObject> {
|
||||
const messageId = await applyMessageIdResolver(
|
||||
ctx.messageIdResolver,
|
||||
true,
|
||||
event.groupId,
|
||||
|
||||
@@ -8,29 +8,14 @@ import { attachMessageMedia } from '../message-media';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
function toSegmentContext(
|
||||
ctx: ConverterContext,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): ToSegmentContext {
|
||||
return {
|
||||
isGroup,
|
||||
sessionId,
|
||||
selfId: ctx.selfId,
|
||||
imageUrlResolver: ctx.imageUrlResolver,
|
||||
mediaUrlResolver: ctx.mediaUrlResolver,
|
||||
messageIdResolver: ctx.messageIdResolver,
|
||||
mediaSegmentSink: ctx.mediaSegmentSink,
|
||||
};
|
||||
}
|
||||
|
||||
export async function elementsToOneBotSegments(
|
||||
ctx: ConverterContext,
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
options: { includeReplyContent?: boolean } = {},
|
||||
): Promise<JsonArray> {
|
||||
const segmentCtx = toSegmentContext(ctx, isGroup, sessionId);
|
||||
const segmentCtx: ToSegmentContext = { ...ctx, isGroup, sessionId, mediaSegmentSink: null };
|
||||
const result: JsonArray = [];
|
||||
|
||||
for (const element of elements) {
|
||||
@@ -39,7 +24,7 @@ export async function elementsToOneBotSegments(
|
||||
// One malformed element shouldn't drop the whole message — skip it (with a
|
||||
// breadcrumb) and keep converting the rest.
|
||||
try {
|
||||
segment = await elementToSegment(element, { ...segmentCtx, mediaSegmentSink: null });
|
||||
segment = await elementToSegment(element, segmentCtx);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'segment convert skipped type=%s (%s)',
|
||||
@@ -49,11 +34,43 @@ export async function elementsToOneBotSegments(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Forward quotes often refer to messages outside the local account's
|
||||
// history. Carry their inline content so consumers can resend the node.
|
||||
if (
|
||||
options.includeReplyContent &&
|
||||
element.type === 'reply' &&
|
||||
element.replyElements?.length
|
||||
) {
|
||||
const message = await elementsToOneBotSegments(
|
||||
ctx,
|
||||
element.replyElements.filter((quoted) => quoted.type !== 'reply'),
|
||||
isGroup,
|
||||
sessionId,
|
||||
);
|
||||
|
||||
if (message.length > 0) {
|
||||
const data = segment.data as JsonObject;
|
||||
data.message = message;
|
||||
|
||||
if (element.replySenderUin) {
|
||||
data.qq = String(element.replySenderUin);
|
||||
}
|
||||
|
||||
if (element.replyTime !== undefined) {
|
||||
data.time = String(element.replyTime);
|
||||
}
|
||||
|
||||
if (element.replySeq) {
|
||||
data.seq = String(element.replySeq);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Persistence failures must propagate, not masquerade as bad wire elements.
|
||||
attachMessageMedia(segment, element);
|
||||
|
||||
if (element.type === 'image' || element.type === 'record' || element.type === 'video') {
|
||||
ctx.mediaSegmentSink?.(
|
||||
await ctx.mediaSegmentSink?.(
|
||||
element.type,
|
||||
element,
|
||||
segment.data as JsonObject,
|
||||
|
||||
@@ -2,11 +2,6 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
|
||||
import type { MessageIdResolver } from './index';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
|
||||
export function parseSelfId(instanceUin: string): number {
|
||||
const parsed = Number.parseInt(instanceUin, 10);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
export function isSameActor(
|
||||
leftUin: number,
|
||||
leftUid: string | undefined,
|
||||
@@ -20,16 +15,16 @@ export function isSameActor(
|
||||
return Boolean(leftUid) && leftUid === rightUid;
|
||||
}
|
||||
|
||||
export function applyMessageIdResolver(
|
||||
export async function applyMessageIdResolver(
|
||||
resolver: MessageIdResolver | null,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
eventName: string,
|
||||
timestamp?: number,
|
||||
): number {
|
||||
): Promise<number> {
|
||||
if (resolver) {
|
||||
const resolved = resolver(isGroup, sessionId, sequence, eventName, timestamp);
|
||||
const resolved = await resolver(isGroup, sessionId, sequence, eventName, timestamp);
|
||||
|
||||
if (Number.isInteger(resolved) && resolved !== 0) {
|
||||
return resolved;
|
||||
@@ -40,7 +35,7 @@ export function applyMessageIdResolver(
|
||||
return seq === 0 ? 0 : seq;
|
||||
}
|
||||
|
||||
export function resolveReplyId(
|
||||
export async function resolveReplyId(
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
@@ -48,7 +43,7 @@ export function resolveReplyId(
|
||||
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
|
||||
timestamp?: number,
|
||||
replyElements?: readonly MessageElement[],
|
||||
): number {
|
||||
): Promise<number> {
|
||||
const seq = Math.trunc(sequence);
|
||||
|
||||
if (seq === 0) {
|
||||
@@ -56,7 +51,14 @@ export function resolveReplyId(
|
||||
}
|
||||
|
||||
if (resolver) {
|
||||
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp, replyElements);
|
||||
const resolved = await resolver(
|
||||
isGroup,
|
||||
sessionId,
|
||||
seq,
|
||||
eventName,
|
||||
timestamp,
|
||||
replyElements,
|
||||
);
|
||||
|
||||
if (Number.isInteger(resolved) && resolved !== 0) {
|
||||
return resolved;
|
||||
|
||||
@@ -199,7 +199,7 @@ async function convertAndDispatch(
|
||||
renderParamsVerbose(converted),
|
||||
]);
|
||||
|
||||
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) {
|
||||
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
|
||||
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_before_backfill');
|
||||
return;
|
||||
}
|
||||
@@ -227,12 +227,12 @@ async function convertAndDispatch(
|
||||
|
||||
// Backfill can await several network/media operations. Re-check immediately
|
||||
// before dispatch so a recall that arrived during that gap wins the race.
|
||||
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) {
|
||||
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
|
||||
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_after_backfill');
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.dispatchEvent(converted, 'bridge', state.startedAt);
|
||||
await ctx.dispatchEvent(converted, 'bridge', state.startedAt);
|
||||
state.handedOff = true;
|
||||
}
|
||||
|
||||
@@ -261,12 +261,12 @@ function traceEventTerminal(
|
||||
]);
|
||||
}
|
||||
|
||||
function cacheGroupMessageMeta(
|
||||
async function cacheGroupMessageMeta(
|
||||
ctx: OneBotInstanceContext,
|
||||
event: Extract<QQEventVariant, { kind: 'group_message' }>,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
await ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
targetId: event.groupId,
|
||||
sequence: event.msgSeq,
|
||||
@@ -278,7 +278,7 @@ function cacheGroupMessageMeta(
|
||||
});
|
||||
}
|
||||
|
||||
function cachePrivateMessageMeta(
|
||||
async function cachePrivateMessageMeta(
|
||||
ctx: OneBotInstanceContext,
|
||||
sessionId: number,
|
||||
messageSequence: number,
|
||||
@@ -288,7 +288,7 @@ function cachePrivateMessageMeta(
|
||||
random: number,
|
||||
sequenceAuthoritative: boolean,
|
||||
privateDirection: MessageMeta['privateDirection'],
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const isFriendMessage = privateDirection !== undefined;
|
||||
const hasNtSequence = isFriendMessage && sequenceAuthoritative && serverSequence > 0;
|
||||
const eventName = isFriendMessage
|
||||
@@ -299,7 +299,7 @@ function cachePrivateMessageMeta(
|
||||
sessionId,
|
||||
eventName,
|
||||
);
|
||||
ctx.cacheMessageMeta(messageId, {
|
||||
await ctx.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
targetId: sessionId,
|
||||
sequence: serverSequence,
|
||||
@@ -312,15 +312,15 @@ function cachePrivateMessageMeta(
|
||||
});
|
||||
}
|
||||
|
||||
function isFriendMessageRecalled(
|
||||
async function isFriendMessageRecalled(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'friend_message' }>,
|
||||
): boolean {
|
||||
): Promise<boolean> {
|
||||
const peerUin = event.peerUin ?? event.senderUin;
|
||||
const clientSequence = event.clientSeq ?? event.msgSeq;
|
||||
const sentBySelf = event.senderUin === ctx.selfId;
|
||||
const recalled = ctx.messageStore.isPrivateMessageRecalled(
|
||||
const recalled = await ctx.messageStore.isPrivateMessageRecalled(
|
||||
peerUin,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
@@ -339,16 +339,16 @@ function isFriendMessageRecalled(
|
||||
return recalled;
|
||||
}
|
||||
|
||||
function cacheReaction(
|
||||
async function cacheReaction(
|
||||
ctx: OneBotInstanceContext,
|
||||
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
if (!event.groupId || !event.msgSeq || !event.emojiId || !event.operatorUin) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.isAdd) {
|
||||
ctx.reactionStore.recordAdd(
|
||||
await ctx.reactionStore.recordAdd(
|
||||
event.groupId,
|
||||
event.msgSeq,
|
||||
event.emojiId,
|
||||
@@ -358,7 +358,7 @@ function cacheReaction(
|
||||
event.time,
|
||||
);
|
||||
} else {
|
||||
ctx.reactionStore.recordRemove(
|
||||
await ctx.reactionStore.recordRemove(
|
||||
event.groupId,
|
||||
event.msgSeq,
|
||||
event.emojiId,
|
||||
@@ -367,23 +367,23 @@ function cacheReaction(
|
||||
}
|
||||
}
|
||||
|
||||
function handleGroupMessage(
|
||||
async function handleGroupMessage(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'group_message' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
cacheGroupMessageMeta(ctx, event);
|
||||
await cacheGroupMessageMeta(ctx, event);
|
||||
return convertAndDispatch(ctx, log, event, state);
|
||||
}
|
||||
|
||||
function handleFriendMessage(
|
||||
async function handleFriendMessage(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'friend_message' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
cachePrivateMessageMeta(
|
||||
await cachePrivateMessageMeta(
|
||||
ctx,
|
||||
event.peerUin ?? event.senderUin,
|
||||
event.msgSeq,
|
||||
@@ -397,13 +397,13 @@ function handleFriendMessage(
|
||||
return convertAndDispatch(ctx, log, event, state);
|
||||
}
|
||||
|
||||
function handleTempMessage(
|
||||
async function handleTempMessage(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'temp_message' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
cachePrivateMessageMeta(
|
||||
await cachePrivateMessageMeta(
|
||||
ctx,
|
||||
event.senderUin,
|
||||
event.msgSeq,
|
||||
@@ -418,14 +418,14 @@ function handleTempMessage(
|
||||
return convertAndDispatch(ctx, log, event, state);
|
||||
}
|
||||
|
||||
function handleFriendRecall(
|
||||
async function handleFriendRecall(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'friend_recall' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
const clientSequence = event.clientSeq ?? event.msgSeq;
|
||||
const recalled = ctx.messageStore.recordPrivateRecall(
|
||||
const recalled = await ctx.messageStore.recordPrivateRecall(
|
||||
event.userUin,
|
||||
clientSequence,
|
||||
event.recalledBySelf === true,
|
||||
@@ -442,13 +442,13 @@ function handleFriendRecall(
|
||||
return convertAndDispatch(ctx, log, event, state, messageIdOverride);
|
||||
}
|
||||
|
||||
function handleGroupMsgEmojiLike(
|
||||
async function handleGroupMsgEmojiLike(
|
||||
ctx: OneBotInstanceContext,
|
||||
log: Logger,
|
||||
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
|
||||
state: EventTraceState,
|
||||
): Promise<void> {
|
||||
cacheReaction(ctx, event);
|
||||
await cacheReaction(ctx, event);
|
||||
return convertAndDispatch(ctx, log, event, state);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,12 +9,12 @@ import type { JsonObject } from './types';
|
||||
* Private history needs the conversation peer explicitly because `user_id`
|
||||
* names the sender and therefore equals the bot account on outgoing messages.
|
||||
*/
|
||||
export function persistHistoryEvent(
|
||||
export async function persistHistoryEvent(
|
||||
store: MessageStore,
|
||||
event: JsonObject,
|
||||
privatePeerId?: number,
|
||||
source?: FriendMessage,
|
||||
): void {
|
||||
): Promise<boolean> {
|
||||
const messageId = toHistoryInt(event.message_id);
|
||||
|
||||
if (!Number.isSafeInteger(messageId) || messageId === 0) {
|
||||
@@ -63,7 +63,7 @@ export function persistHistoryEvent(
|
||||
timestamp: source.time,
|
||||
} satisfies Parameters<MessageStore['storeMeta']>[1])
|
||||
: undefined;
|
||||
store.storeHistoryEvent(messageId, isGroup, sessionId, sequence, eventName, event, {
|
||||
return store.storeHistoryEvent(messageId, isGroup, sessionId, sequence, eventName, event, {
|
||||
sequenceAuthoritative,
|
||||
meta,
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import {
|
||||
@@ -136,8 +137,11 @@ export class LoginHistorySyncCoordinator {
|
||||
})),
|
||||
signal,
|
||||
);
|
||||
const groupCandidates = selectGroupCandidates(ref.messageStore, state.groups);
|
||||
const privateCandidates = selectPrivateCandidates(ref.messageStore, state.privateUsers);
|
||||
const groupCandidates = await selectGroupCandidates(ref.messageStore, state.groups);
|
||||
const privateCandidates = await selectPrivateCandidates(
|
||||
ref.messageStore,
|
||||
state.privateUsers,
|
||||
);
|
||||
// URL resolvers may issue additional QQ requests for rkeys or media
|
||||
// download addresses. Automatic backfill must stay inside its one-probe
|
||||
// plus six-page packet budget, so persist only URLs already present in the
|
||||
@@ -151,9 +155,9 @@ export class LoginHistorySyncCoordinator {
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
mediaSegmentSink: mediaSegmentSink
|
||||
? (mediaType, element, data, isGroup, sessionId) => {
|
||||
? async (mediaType, element, data, isGroup, sessionId) => {
|
||||
throwIfAborted(signal);
|
||||
mediaSegmentSink(mediaType, element, data, isGroup, sessionId);
|
||||
await mediaSegmentSink(mediaType, element, data, isGroup, sessionId);
|
||||
}
|
||||
: null,
|
||||
},
|
||||
@@ -257,18 +261,21 @@ export class LoginHistorySyncCoordinator {
|
||||
|
||||
export const loginHistorySyncCoordinator = new LoginHistorySyncCoordinator();
|
||||
|
||||
function selectGroupCandidates(
|
||||
async function selectGroupCandidates(
|
||||
store: MessageStore,
|
||||
states: readonly GroupHistorySyncState[],
|
||||
): GroupCandidate[] {
|
||||
return states
|
||||
.flatMap((state): GroupCandidate[] => {
|
||||
): Promise<GroupCandidate[]> {
|
||||
return (
|
||||
await mapWithConcurrency(states, 8, async (state): Promise<GroupCandidate[]> => {
|
||||
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const observedSequence = store.findLatestAuthoritativeSequence(true, state.groupId);
|
||||
const localSequence = store.findLatestPersistedAuthoritativeSequence(
|
||||
const observedSequence = await store.findLatestAuthoritativeSequence(
|
||||
true,
|
||||
state.groupId,
|
||||
);
|
||||
const localSequence = await store.findLatestPersistedAuthoritativeSequence(
|
||||
true,
|
||||
state.groupId,
|
||||
);
|
||||
@@ -312,22 +319,27 @@ function selectGroupCandidates(
|
||||
},
|
||||
];
|
||||
})
|
||||
)
|
||||
.flat()
|
||||
.sort(compareCandidates)
|
||||
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxGroups);
|
||||
}
|
||||
|
||||
function selectPrivateCandidates(
|
||||
async function selectPrivateCandidates(
|
||||
store: MessageStore,
|
||||
states: readonly PrivateHistorySyncState[],
|
||||
): PrivateCandidate[] {
|
||||
return states
|
||||
.flatMap((state): PrivateCandidate[] => {
|
||||
): Promise<PrivateCandidate[]> {
|
||||
return (
|
||||
await mapWithConcurrency(states, 8, async (state): Promise<PrivateCandidate[]> => {
|
||||
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const observedSequence = store.findLatestAuthoritativeSequence(false, state.userId);
|
||||
const localSequence = store.findLatestPersistedAuthoritativeSequence(
|
||||
const observedSequence = await store.findLatestAuthoritativeSequence(
|
||||
false,
|
||||
state.userId,
|
||||
);
|
||||
const localSequence = await store.findLatestPersistedAuthoritativeSequence(
|
||||
false,
|
||||
state.userId,
|
||||
);
|
||||
@@ -360,6 +372,8 @@ function selectPrivateCandidates(
|
||||
},
|
||||
];
|
||||
})
|
||||
)
|
||||
.flat()
|
||||
.sort(compareCandidates)
|
||||
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxPrivateUsers);
|
||||
}
|
||||
@@ -452,7 +466,7 @@ async function persistGroupMessage(
|
||||
);
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, converted);
|
||||
await persistHistoryEvent(ref.messageStore, converted);
|
||||
}
|
||||
|
||||
async function persistPrivateMessage(
|
||||
@@ -489,7 +503,12 @@ async function persistPrivateMessage(
|
||||
}
|
||||
|
||||
if (
|
||||
ref.messageStore.isPrivateMessageRecalled(peerUin, clientSequence, sentBySelf, message.time)
|
||||
await ref.messageStore.isPrivateMessageRecalled(
|
||||
peerUin,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
message.time,
|
||||
)
|
||||
) {
|
||||
log.debug(
|
||||
'login history sync omitted recalled private message: UIN=%d peer=%d clientSeq=%d self=%s',
|
||||
@@ -505,8 +524,7 @@ async function persistPrivateMessage(
|
||||
converted.target_id = peerUin;
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, converted, peerUin, message);
|
||||
return true;
|
||||
return persistHistoryEvent(ref.messageStore, converted, peerUin, message);
|
||||
}
|
||||
|
||||
function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
fetchPttText as fetchPttTextAction,
|
||||
getImageInfo as getCachedImageInfo,
|
||||
getRecordInfo as getCachedRecordInfo,
|
||||
refreshMessageMedia,
|
||||
} from './modules/media-actions';
|
||||
import {
|
||||
deleteMessage,
|
||||
@@ -58,8 +59,12 @@ export interface OneBotInstanceContext {
|
||||
config: OneBotConfig;
|
||||
musicSignUrl?: string;
|
||||
getUptimeMs(): number;
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
|
||||
dispatchEvent(event: JsonObject, source?: 'bridge' | 'send', startedAt?: number): void;
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void | Promise<void>;
|
||||
dispatchEvent(
|
||||
event: JsonObject,
|
||||
source?: 'bridge' | 'send',
|
||||
startedAt?: number,
|
||||
): void | Promise<void>;
|
||||
}
|
||||
|
||||
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
@@ -71,11 +76,14 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getLoginInfo: () => getLoginInfo(ref),
|
||||
isOnline: () => true,
|
||||
getUptimeMs: () => ref.getUptimeMs(),
|
||||
getMessage: (messageId) => messageStore.findEvent(messageId),
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
cacheMessageMetas: (entries) => messageStore.storeMetas(entries),
|
||||
listReadSessions: () =>
|
||||
messageStore.listReadSessions(bridge.identity.groups.map((group) => group.groupId)),
|
||||
getMessage: async (messageId) => await messageStore.findEvent(messageId),
|
||||
refreshMessageMedia: (messageId, event) => refreshMessageMedia(ref, messageId, event),
|
||||
getMessageMeta: async (messageId) => await messageStore.findMeta(messageId),
|
||||
cacheMessageMetas: async (entries) => await messageStore.storeMetas(entries),
|
||||
listReadSessions: async () =>
|
||||
await messageStore.listReadSessions(
|
||||
bridge.identity.groups.map((group) => group.groupId),
|
||||
),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) =>
|
||||
@@ -85,7 +93,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
message,
|
||||
autoEscape,
|
||||
tempGroupId,
|
||||
tempGroupId === undefined ? (event) => ref.dispatchEvent(event, 'send') : undefined,
|
||||
tempGroupId === undefined
|
||||
? async (event) => await ref.dispatchEvent(event, 'send')
|
||||
: undefined,
|
||||
),
|
||||
sendGroupMessage: (groupId, message, autoEscape) =>
|
||||
sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
@@ -109,8 +119,12 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
sendGroupForwardMsg: (groupId, messages, meta) =>
|
||||
sendGroupForwardMessage(ref, groupId, messages, meta),
|
||||
sendPrivateForwardMsg: (userId, messages, meta) =>
|
||||
sendPrivateForwardMessage(ref, userId, messages, meta, (event) =>
|
||||
ref.dispatchEvent(event, 'send'),
|
||||
sendPrivateForwardMessage(
|
||||
ref,
|
||||
userId,
|
||||
messages,
|
||||
meta,
|
||||
async (event) => await ref.dispatchEvent(event, 'send'),
|
||||
),
|
||||
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
|
||||
getForwardMsg: (resId) => getForwardMessage(ref, resId),
|
||||
@@ -120,13 +134,13 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
messageId,
|
||||
target,
|
||||
target.userId !== undefined
|
||||
? (event) => ref.dispatchEvent(event, 'send')
|
||||
? async (event) => await ref.dispatchEvent(event, 'send')
|
||||
: undefined,
|
||||
),
|
||||
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
|
||||
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
|
||||
setMsgEmojiLike: async (messageId, emojiId, set) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta) {
|
||||
throw new Error('message not found');
|
||||
@@ -144,7 +158,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
const emojiType = emojiId.length > 3 ? 2 : 1;
|
||||
|
||||
if (set) {
|
||||
reactionStore.recordAdd(
|
||||
await reactionStore.recordAdd(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
emojiId,
|
||||
@@ -154,11 +168,11 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
Math.floor(Date.now() / 1000),
|
||||
);
|
||||
} else {
|
||||
reactionStore.recordRemove(meta.targetId, meta.sequence, emojiId, ref.selfId);
|
||||
await reactionStore.recordRemove(meta.targetId, meta.sequence, emojiId, ref.selfId);
|
||||
}
|
||||
},
|
||||
fetchEmojiLikeSummary: async (messageId) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta) {
|
||||
throw new Error('message not found');
|
||||
@@ -172,7 +186,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
throw new Error('message has no authoritative QQ sequence');
|
||||
}
|
||||
|
||||
const summary = reactionStore.summarizeMessage(meta.targetId, meta.sequence);
|
||||
const summary = await reactionStore.summarizeMessage(meta.targetId, meta.sequence);
|
||||
const out: Array<{
|
||||
emoji_id: string;
|
||||
emoji_type: number;
|
||||
@@ -182,9 +196,15 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
}> = [];
|
||||
|
||||
for (const entry of summary) {
|
||||
let users = reactionStore
|
||||
.listUsers(meta.targetId, meta.sequence, entry.emojiId, 1000, 0)
|
||||
.map((user) => ({ user_id: user.operatorUin }));
|
||||
let users = (
|
||||
await reactionStore.listUsers(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
entry.emojiId,
|
||||
1000,
|
||||
0,
|
||||
)
|
||||
).map((user) => ({ user_id: user.operatorUin }));
|
||||
|
||||
try {
|
||||
const remote = await bridge.apis.interaction.getEmojiLikes(
|
||||
@@ -214,7 +234,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
return out;
|
||||
},
|
||||
fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta) {
|
||||
throw new Error('message not found');
|
||||
@@ -228,7 +248,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
throw new Error('message has no authoritative QQ sequence');
|
||||
}
|
||||
|
||||
const raw = reactionStore.listUsers(
|
||||
const raw = await reactionStore.listUsers(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
emojiId,
|
||||
@@ -240,7 +260,11 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
uid: r.operatorUid,
|
||||
setAt: r.setAt,
|
||||
}));
|
||||
const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId);
|
||||
const cachedCount = await reactionStore.countUsers(
|
||||
meta.targetId,
|
||||
meta.sequence,
|
||||
emojiId,
|
||||
);
|
||||
let serverCount = cachedCount;
|
||||
|
||||
try {
|
||||
|
||||
@@ -161,7 +161,7 @@ export class OneBotInstance {
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
||||
mediaUrlResolver: (element, isGroup, sessionId) =>
|
||||
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
||||
messageIdResolver: (
|
||||
messageIdResolver: async (
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
@@ -178,7 +178,7 @@ export class OneBotInstance {
|
||||
(resolvedEventName === PRIVATE_MESSAGE_EVENT ||
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)
|
||||
) {
|
||||
const storedId = this.messageStore.resolvePrivateReplyMessageId(
|
||||
const storedId = await this.messageStore.resolvePrivateReplyMessageId(
|
||||
sessionId,
|
||||
sequence,
|
||||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
|
||||
@@ -199,8 +199,8 @@ export class OneBotInstance {
|
||||
: resolvedEventName,
|
||||
);
|
||||
},
|
||||
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
|
||||
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
|
||||
mediaSegmentSink: async (mediaType, element, data, isGroup, sessionId) =>
|
||||
await mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
|
||||
};
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: this.uin,
|
||||
@@ -214,7 +214,8 @@ export class OneBotInstance {
|
||||
config,
|
||||
musicSignUrl: globalSettings.musicSignUrl,
|
||||
getUptimeMs: () => Math.max(0, Date.now() - this.startedAt),
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
cacheMessageMeta: async (messageId, meta) =>
|
||||
await this.cacheMessageMeta(messageId, meta),
|
||||
dispatchEvent: (event, source = 'bridge', startedAt) =>
|
||||
this.dispatchEvent(event, source, startedAt),
|
||||
};
|
||||
@@ -225,7 +226,12 @@ export class OneBotInstance {
|
||||
this.networkManager = new OneBotNetworkManager((desired) =>
|
||||
this.createNetworkAdapter(desired, networkCtx),
|
||||
);
|
||||
this.networkReady = this.networkManager.reconcile(config);
|
||||
this.networkReady = Promise.all([
|
||||
bridge.identity.initialization,
|
||||
this.messageStore.initialization,
|
||||
this.mediaStore.initialization,
|
||||
this.reactionStore.initialization,
|
||||
]).then(() => this.networkManager.reconcile(config));
|
||||
this.lifecycleTail = this.networkReady.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
@@ -400,9 +406,9 @@ export class OneBotInstance {
|
||||
// reconcile and every transport have actually closed.
|
||||
const closeErrors: unknown[] = [];
|
||||
const stores = [
|
||||
['message', () => this.messageStore.close()],
|
||||
['media', () => this.mediaStore.close()],
|
||||
['reaction', () => this.reactionStore.close()],
|
||||
['message', async () => await this.messageStore.close()],
|
||||
['media', async () => await this.mediaStore.close()],
|
||||
['reaction', async () => await this.reactionStore.close()],
|
||||
] as const;
|
||||
|
||||
for (const [name, close] of stores) {
|
||||
@@ -411,7 +417,7 @@ export class OneBotInstance {
|
||||
}
|
||||
|
||||
try {
|
||||
close();
|
||||
await close();
|
||||
this.storeCloseState[name] = true;
|
||||
} catch (error) {
|
||||
closeErrors.push(error);
|
||||
@@ -466,9 +472,12 @@ export class OneBotInstance {
|
||||
source: 'bridge' | 'send' = 'bridge',
|
||||
startedAt = Date.now(),
|
||||
): Promise<void> {
|
||||
if (source === 'bridge') {
|
||||
this.cacheMessageEvent(event);
|
||||
if (!(await this.cacheMessageEvent(event))) {
|
||||
this.traceEventHandoffTerminal(event, startedAt, 'suppressed', 'private_recall');
|
||||
return;
|
||||
}
|
||||
|
||||
if (source === 'bridge') {
|
||||
if (this.consumePendingSelfSentEcho(event)) {
|
||||
this.log.trace(
|
||||
'duplicate self-message echo suppressed message_id=%d message_seq=%d',
|
||||
@@ -484,7 +493,6 @@ export class OneBotInstance {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
this.cacheMessageEvent(event);
|
||||
this.rememberPendingSelfSentEcho(event);
|
||||
}
|
||||
|
||||
@@ -492,7 +500,7 @@ export class OneBotInstance {
|
||||
// synthetic event here would produce a second, less accurate "received"
|
||||
// line whose private user_id points at the bot itself.
|
||||
if (source === 'bridge') {
|
||||
this.logReceivedMessage(event);
|
||||
await this.logReceivedMessage(event);
|
||||
}
|
||||
|
||||
// Built-in `#sl` only consumes events observed from QQ. Action-originated
|
||||
@@ -518,7 +526,7 @@ export class OneBotInstance {
|
||||
event: JsonObject,
|
||||
startedAt: number,
|
||||
outcome: 'suppressed' | 'reporting_started',
|
||||
reason?: 'duplicate_self_echo' | 'status_command',
|
||||
reason?: 'duplicate_self_echo' | 'status_command' | 'private_recall',
|
||||
): void {
|
||||
this.log.trace(() => [
|
||||
'event_terminal post_type=%s outcome=%s%s ms=%d',
|
||||
@@ -702,7 +710,7 @@ export class OneBotInstance {
|
||||
return rejected;
|
||||
}
|
||||
|
||||
private logReceivedMessage(event: JsonObject): void {
|
||||
private async logReceivedMessage(event: JsonObject): Promise<void> {
|
||||
const isSelf = event.post_type === 'message_sent';
|
||||
|
||||
if (event.post_type !== 'message' && !isSelf) {
|
||||
@@ -738,7 +746,7 @@ export class OneBotInstance {
|
||||
|
||||
if (type === 'reply') {
|
||||
const replyId = toInt(data.id);
|
||||
renderedParts.push(formatReply(this.messageStore, identity, replyId));
|
||||
renderedParts.push(await formatReply(this.messageStore, identity, replyId));
|
||||
} else {
|
||||
renderedParts.push(formatMessageSegments([seg as JsonValue]));
|
||||
}
|
||||
@@ -781,15 +789,15 @@ export class OneBotInstance {
|
||||
}
|
||||
}
|
||||
|
||||
private cacheMessageEvent(event: JsonObject): void {
|
||||
private async cacheMessageEvent(event: JsonObject): Promise<boolean> {
|
||||
if (event.post_type !== 'message' && event.post_type !== 'message_sent') {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
|
||||
if (messageId === 0) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
const isGroup = event.message_type === 'group';
|
||||
@@ -806,18 +814,25 @@ export class OneBotInstance {
|
||||
: PRIVATE_MESSAGE_EVENT;
|
||||
|
||||
if (sessionId === 0) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
|
||||
return this.messageStore.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
);
|
||||
}
|
||||
|
||||
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
|
||||
private async cacheMessageMeta(messageId: number, meta: MessageMeta): Promise<void> {
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.messageStore.storeMeta(messageId, meta);
|
||||
await this.messageStore.storeMeta(messageId, meta);
|
||||
}
|
||||
|
||||
private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject {
|
||||
|
||||
@@ -7,18 +7,18 @@ export type MediaType = 'image' | 'record' | 'video';
|
||||
export class MediaIndexer {
|
||||
constructor(private readonly mediaStore: MediaStore) {}
|
||||
|
||||
remember(
|
||||
async remember(
|
||||
mediaType: MediaType,
|
||||
element: MessageElement,
|
||||
data: JsonObject,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const url = typeof data.url === 'string' ? data.url : '';
|
||||
const file = typeof data.file === 'string' ? data.file : '';
|
||||
|
||||
if (mediaType === 'image') {
|
||||
this.mediaStore.rememberImage({
|
||||
await this.mediaStore.rememberImage({
|
||||
file: file || element.fileId || '',
|
||||
url,
|
||||
fileSize: element.fileSize ?? 0,
|
||||
@@ -38,7 +38,7 @@ export class MediaIndexer {
|
||||
}
|
||||
|
||||
if (mediaType === 'record') {
|
||||
this.mediaStore.rememberRecord({
|
||||
await this.mediaStore.rememberRecord({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
@@ -57,7 +57,7 @@ export class MediaIndexer {
|
||||
}
|
||||
|
||||
// video
|
||||
this.mediaStore.rememberVideo({
|
||||
await this.mediaStore.rememberVideo({
|
||||
file: file || element.fileName || element.fileId || '',
|
||||
fileId: element.fileId ?? '',
|
||||
url,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { SqliteDatabase } from '@snowluma/sqlite';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
import {
|
||||
@@ -22,17 +22,17 @@ export async function migrateLegacyMedia(
|
||||
cancelled: () => boolean = () => false,
|
||||
): Promise<void> {
|
||||
const store = new MediaStore(messageDbPath);
|
||||
store.close();
|
||||
await store.close();
|
||||
const destination = openSqliteDb(messageDbPath);
|
||||
let source: DatabaseSync | undefined;
|
||||
let source: SqliteDatabase | undefined;
|
||||
|
||||
try {
|
||||
destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
|
||||
await destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1), phase TEXT NOT NULL, cursor INTEGER NOT NULL
|
||||
); INSERT OR IGNORE INTO media_migration_state VALUES (1, 'entries', 0)`);
|
||||
const state = destination
|
||||
const state = (await destination
|
||||
.prepare('SELECT phase, cursor FROM media_migration_state WHERE id = 1')
|
||||
.get() as { phase: string; cursor: number };
|
||||
.get()) as { phase: string; cursor: number };
|
||||
|
||||
if (state.phase === 'complete') {
|
||||
return;
|
||||
@@ -41,11 +41,13 @@ export async function migrateLegacyMedia(
|
||||
const sourcePath = path.join(path.dirname(messageDbPath), 'media.db');
|
||||
|
||||
if (!fs.existsSync(sourcePath)) {
|
||||
destination.exec("UPDATE media_migration_state SET phase = 'complete' WHERE id = 1");
|
||||
await destination.exec(
|
||||
"UPDATE media_migration_state SET phase = 'complete' WHERE id = 1",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
source = new DatabaseSync(sourcePath, { readOnly: true });
|
||||
source = new SqliteDatabase(sourcePath, { readOnly: true });
|
||||
log.info('preserving legacy media metadata: migration started');
|
||||
const insertEntry =
|
||||
destination.prepare(`INSERT INTO legacy_media_entries (type, primary_key, data, last_seen)
|
||||
@@ -59,11 +61,11 @@ export async function migrateLegacyMedia(
|
||||
|
||||
while (!cancelled() && state.phase !== 'complete') {
|
||||
const table = state.phase === 'entries' ? 'media_entries' : 'media_keys';
|
||||
const rows = source
|
||||
const rows = (await source
|
||||
.prepare(
|
||||
`SELECT rowid AS migration_rowid, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT ?`,
|
||||
)
|
||||
.all(state.cursor, BATCH_SIZE) as Array<{
|
||||
.all(state.cursor, BATCH_SIZE)) as Array<{
|
||||
migration_rowid: number;
|
||||
type: string;
|
||||
primary_key: string;
|
||||
@@ -74,7 +76,7 @@ export async function migrateLegacyMedia(
|
||||
const nextPhase =
|
||||
rows.length === 0 ? (state.phase === 'entries' ? 'keys' : 'complete') : state.phase;
|
||||
const nextCursor = rows.at(-1)?.migration_rowid ?? 0;
|
||||
destination.exec('BEGIN IMMEDIATE');
|
||||
await destination.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
for (const row of rows) {
|
||||
@@ -93,14 +95,14 @@ export async function migrateLegacyMedia(
|
||||
);
|
||||
}
|
||||
|
||||
insertEntry.run(
|
||||
await insertEntry.run(
|
||||
row.type,
|
||||
foldMediaKey(row.primary_key),
|
||||
serializeMediaInfo(info),
|
||||
row.last_seen,
|
||||
);
|
||||
} else {
|
||||
insertKey.run(
|
||||
await insertKey.run(
|
||||
row.type,
|
||||
foldMediaKey(row.key),
|
||||
foldMediaKey(row.primary_key),
|
||||
@@ -108,10 +110,10 @@ export async function migrateLegacyMedia(
|
||||
}
|
||||
}
|
||||
|
||||
saveState.run(nextPhase, nextCursor);
|
||||
destination.exec('COMMIT');
|
||||
await saveState.run(nextPhase, nextCursor);
|
||||
await destination.exec('COMMIT');
|
||||
} catch (error) {
|
||||
rollbackMediaTransaction(destination, error);
|
||||
await rollbackMediaTransaction(destination, error);
|
||||
}
|
||||
|
||||
state.phase = nextPhase;
|
||||
@@ -129,7 +131,7 @@ export async function migrateLegacyMedia(
|
||||
log.info('preserving legacy media metadata: migration complete; source retained');
|
||||
}
|
||||
} finally {
|
||||
source?.close();
|
||||
destination.close();
|
||||
await source?.close();
|
||||
await destination.close();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import { SqliteDatabase, type SqliteStatement } from '@snowluma/sqlite';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
|
||||
export interface CachedImage {
|
||||
@@ -71,107 +71,163 @@ const INLINE_MEDIA_SOURCE = /^(base64:\/\/|data:)/i;
|
||||
* Only the in-memory lookup cache is bounded; history dependencies never expire.
|
||||
*/
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly db: SqliteDatabase;
|
||||
private readonly cache = new Map<string, string>();
|
||||
private readonly upsertEntry: StatementSync;
|
||||
private readonly upsertKey: StatementSync;
|
||||
private readonly findEntry: StatementSync;
|
||||
private readonly findLegacyEntry: StatementSync;
|
||||
private upsertEntry!: SqliteStatement;
|
||||
private upsertKey!: SqliteStatement;
|
||||
private findEntry!: SqliteStatement;
|
||||
private findLegacyEntry!: SqliteStatement;
|
||||
|
||||
readonly initialization: Promise<void>;
|
||||
|
||||
constructor(
|
||||
dbPath: string,
|
||||
private readonly maxCachedEntries = DEFAULT_KEEP_ENTRIES,
|
||||
) {
|
||||
this.db = openSqliteDb(dbPath);
|
||||
this.initialization = this.db.serial(async () => {
|
||||
for (const prefix of ['', 'legacy_']) {
|
||||
await this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}media_entries (
|
||||
type TEXT NOT NULL, primary_key TEXT NOT NULL, data TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL, PRIMARY KEY (type, primary_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}media_keys (
|
||||
type TEXT NOT NULL, key TEXT NOT NULL, primary_key TEXT NOT NULL,
|
||||
PRIMARY KEY (type, key)
|
||||
);
|
||||
`);
|
||||
}
|
||||
|
||||
for (const prefix of ['', 'legacy_']) {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}media_entries (
|
||||
type TEXT NOT NULL, primary_key TEXT NOT NULL, data TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL, PRIMARY KEY (type, primary_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS ${prefix}media_keys (
|
||||
type TEXT NOT NULL, key TEXT NOT NULL, primary_key TEXT NOT NULL,
|
||||
PRIMARY KEY (type, key)
|
||||
);
|
||||
this.upsertEntry = this.db.prepare(`
|
||||
INSERT INTO media_entries (type, primary_key, data, last_seen) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(type, primary_key) DO UPDATE SET data = excluded.data, last_seen = excluded.last_seen
|
||||
`);
|
||||
}
|
||||
|
||||
this.upsertEntry = this.db.prepare(`
|
||||
INSERT INTO media_entries (type, primary_key, data, last_seen) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(type, primary_key) DO UPDATE SET data = excluded.data, last_seen = excluded.last_seen
|
||||
`);
|
||||
this.upsertKey = this.db.prepare(`
|
||||
INSERT INTO media_keys (type, key, primary_key) VALUES (?, ?, ?)
|
||||
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key
|
||||
`);
|
||||
this.findEntry = this.db.prepare(`
|
||||
SELECT data FROM media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
this.findLegacyEntry = this.db.prepare(`
|
||||
SELECT data FROM legacy_media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM legacy_media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
this.upsertKey = this.db.prepare(`
|
||||
INSERT INTO media_keys (type, key, primary_key) VALUES (?, ?, ?)
|
||||
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key
|
||||
`);
|
||||
this.findEntry = this.db.prepare(`
|
||||
SELECT data FROM media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
this.findLegacyEntry = this.db.prepare(`
|
||||
SELECT data FROM legacy_media_entries WHERE type = ? AND primary_key = COALESCE(
|
||||
(SELECT primary_key FROM legacy_media_keys WHERE type = ? AND key = ?), ?
|
||||
)
|
||||
`);
|
||||
});
|
||||
void this.initialization.catch(() => undefined);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.cache.clear();
|
||||
this.db.close();
|
||||
async close(): Promise<void> {
|
||||
await this.initialization.catch(() => undefined);
|
||||
await this.db.close();
|
||||
}
|
||||
|
||||
rememberImage(info: CachedImage): void {
|
||||
this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
|
||||
async rememberImage(info: CachedImage): Promise<void> {
|
||||
info = structuredClone(info);
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
|
||||
});
|
||||
}
|
||||
|
||||
rememberRecord(info: CachedRecord): void {
|
||||
this.remember(TYPE_RECORD, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
async rememberRecord(info: CachedRecord): Promise<void> {
|
||||
info = structuredClone(info);
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.remember(TYPE_RECORD, info, [
|
||||
info.file,
|
||||
info.fileName,
|
||||
info.fileId,
|
||||
info.url,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
rememberVideo(info: CachedVideo): void {
|
||||
this.remember(TYPE_VIDEO, info, [info.file, info.fileName, info.fileId, info.url]);
|
||||
async rememberVideo(info: CachedVideo): Promise<void> {
|
||||
info = structuredClone(info);
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.remember(TYPE_VIDEO, info, [
|
||||
info.file,
|
||||
info.fileName,
|
||||
info.fileId,
|
||||
info.url,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
findImage(key: string, source: MediaLookupSource = 'current'): CachedImage | null {
|
||||
return this.find(TYPE_IMAGE, key, source);
|
||||
async findImage(
|
||||
key: string,
|
||||
source: MediaLookupSource = 'current',
|
||||
): Promise<CachedImage | null> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
return await this.find(TYPE_IMAGE, key, source);
|
||||
});
|
||||
}
|
||||
findRecord(key: string, source: MediaLookupSource = 'current'): CachedRecord | null {
|
||||
return this.find(TYPE_RECORD, key, source);
|
||||
async findRecord(
|
||||
key: string,
|
||||
source: MediaLookupSource = 'current',
|
||||
): Promise<CachedRecord | null> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
return await this.find(TYPE_RECORD, key, source);
|
||||
});
|
||||
}
|
||||
findVideo(key: string, source: MediaLookupSource = 'current'): CachedVideo | null {
|
||||
return this.find(TYPE_VIDEO, key, source);
|
||||
async findVideo(
|
||||
key: string,
|
||||
source: MediaLookupSource = 'current',
|
||||
): Promise<CachedVideo | null> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
return await this.find(TYPE_VIDEO, key, source);
|
||||
});
|
||||
}
|
||||
|
||||
updateImageUrl(key: string, url: string): void {
|
||||
this.updateUrl(TYPE_IMAGE, key, url);
|
||||
async updateImageUrl(key: string, url: string): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.updateUrl(TYPE_IMAGE, key, url);
|
||||
});
|
||||
}
|
||||
updateRecordUrl(key: string, url: string): void {
|
||||
this.updateUrl(TYPE_RECORD, key, url);
|
||||
async updateRecordUrl(key: string, url: string): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.updateUrl(TYPE_RECORD, key, url);
|
||||
});
|
||||
}
|
||||
updateVideoUrl(key: string, url: string): void {
|
||||
this.updateUrl(TYPE_VIDEO, key, url);
|
||||
async updateVideoUrl(key: string, url: string): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
await this.updateUrl(TYPE_VIDEO, key, url);
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts durable records, not the bounded lookup cache. */
|
||||
size(): { images: number; records: number; videos: number } {
|
||||
const counts = this.db
|
||||
.prepare(
|
||||
`SELECT type, COUNT(*) AS n FROM (
|
||||
SELECT type FROM media_entries UNION ALL SELECT type FROM legacy_media_entries
|
||||
) GROUP BY type`,
|
||||
)
|
||||
.all() as Array<{ type: string; n: number }>;
|
||||
const count = (type: string) => counts.find((row) => row.type === type)?.n ?? 0;
|
||||
return {
|
||||
images: count(TYPE_IMAGE),
|
||||
records: count(TYPE_RECORD),
|
||||
videos: count(TYPE_VIDEO),
|
||||
};
|
||||
async size(): Promise<{ images: number; records: number; videos: number }> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const counts = (await this.db
|
||||
.prepare(
|
||||
`SELECT type, COUNT(*) AS n FROM (
|
||||
SELECT type FROM media_entries UNION ALL SELECT type FROM legacy_media_entries
|
||||
) GROUP BY type`,
|
||||
)
|
||||
.all()) as Array<{ type: string; n: number }>;
|
||||
const count = (type: string) => counts.find((row) => row.type === type)?.n ?? 0;
|
||||
return {
|
||||
images: await count(TYPE_IMAGE),
|
||||
records: await count(TYPE_RECORD),
|
||||
videos: await count(TYPE_VIDEO),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private remember(type: string, info: object, aliases: string[]): void {
|
||||
private async remember(type: string, info: object, aliases: string[]): Promise<void> {
|
||||
const primary = pickPrimary(aliases);
|
||||
|
||||
if (!primary) {
|
||||
@@ -179,18 +235,18 @@ export class MediaStore {
|
||||
}
|
||||
|
||||
const data = serializeMediaInfo(info);
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
await this.db.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
this.upsertEntry.run(type, primary, data, Math.floor(Date.now() / 1000));
|
||||
await this.upsertEntry.run(type, primary, data, Math.floor(Date.now() / 1000));
|
||||
|
||||
for (const key of new Set(aliases.filter(Boolean).map(foldMediaKey))) {
|
||||
this.upsertKey.run(type, key, primary);
|
||||
await this.upsertKey.run(type, key, primary);
|
||||
}
|
||||
|
||||
this.db.exec('COMMIT');
|
||||
await this.db.exec('COMMIT');
|
||||
} catch (error) {
|
||||
rollbackMediaTransaction(this.db, error);
|
||||
await rollbackMediaTransaction(this.db, error);
|
||||
}
|
||||
|
||||
// Alias remapping can invalidate any cached lookup. JSON strings ensure
|
||||
@@ -198,7 +254,11 @@ export class MediaStore {
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
private find<T>(type: string, key: string, source: MediaLookupSource = 'current'): T | null {
|
||||
private async find<T>(
|
||||
type: string,
|
||||
key: string,
|
||||
source: MediaLookupSource = 'current',
|
||||
): Promise<T | null> {
|
||||
const lookup = foldMediaKey(key);
|
||||
|
||||
if (!lookup) {
|
||||
@@ -212,8 +272,11 @@ export class MediaStore {
|
||||
// Legacy history has no per-message snapshots. Its frozen migration
|
||||
// index must never resolve through a later, mutable filename alias.
|
||||
const current =
|
||||
source === 'current' ? this.findEntry.get(type, type, lookup, lookup) : undefined;
|
||||
const row = (current ?? this.findLegacyEntry.get(type, type, lookup, lookup)) as
|
||||
source === 'current'
|
||||
? await this.findEntry.get(type, type, lookup, lookup)
|
||||
: undefined;
|
||||
const row = (current ??
|
||||
(await this.findLegacyEntry.get(type, type, lookup, lookup))) as
|
||||
{ data: string } | undefined;
|
||||
|
||||
if (!row) {
|
||||
@@ -240,18 +303,18 @@ export class MediaStore {
|
||||
return result as T;
|
||||
}
|
||||
|
||||
private updateUrl(type: string, key: string, url: string): void {
|
||||
private async updateUrl(type: string, key: string, url: string): Promise<void> {
|
||||
if (!url || mustFoldMediaKey(url)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const info = this.find<Record<string, unknown>>(type, key);
|
||||
const info = await this.find<Record<string, unknown>>(type, key);
|
||||
|
||||
if (!info || info.url === url) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.remember(
|
||||
await this.remember(
|
||||
type,
|
||||
{ ...info, url },
|
||||
[info.file, info.fileName, info.fileId, url].filter(
|
||||
@@ -271,9 +334,9 @@ export function serializeMediaInfo(info: object): string {
|
||||
return data;
|
||||
}
|
||||
|
||||
export function rollbackMediaTransaction(db: DatabaseSync, error: unknown): never {
|
||||
export async function rollbackMediaTransaction(db: SqliteDatabase, error: unknown): Promise<never> {
|
||||
try {
|
||||
db.exec('ROLLBACK');
|
||||
await db.exec('ROLLBACK');
|
||||
} catch (rollbackError) {
|
||||
throw new AggregateError([error, rollbackError], 'media write and rollback failed', {
|
||||
cause: error,
|
||||
|
||||
@@ -1,7 +1,30 @@
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import type { RKeyCache } from './instance-rkey';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
export function resolveRemoteMediaUrl(
|
||||
bridge: BridgeInterface,
|
||||
type: 'record' | 'video',
|
||||
node: MessageElement['mediaNode'],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
): Promise<string> {
|
||||
if (!node) {
|
||||
throw new Error(`${type} media metadata is missing`);
|
||||
}
|
||||
|
||||
const api = bridge.apis.groupFile;
|
||||
|
||||
if (type === 'record') {
|
||||
return isGroup ? api.getPttUrl(sessionId, node) : api.getPrivatePttUrl(node);
|
||||
}
|
||||
|
||||
return isGroup ? api.getVideoUrl(sessionId, node) : api.getPrivateVideoUrl(node);
|
||||
}
|
||||
|
||||
export class MediaUrlResolver {
|
||||
constructor(
|
||||
private readonly bridge: BridgeInterface,
|
||||
@@ -12,9 +35,14 @@ export class MediaUrlResolver {
|
||||
if (!element.url) {
|
||||
try {
|
||||
await this.populateUrl(element, isGroup, sessionId);
|
||||
} catch {
|
||||
// Best-effort: a URL fetch hiccup should never block the
|
||||
// outgoing segment. The RKey pass below still runs.
|
||||
} catch (err) {
|
||||
// Preserve the media segment when its download URL is unavailable.
|
||||
log.warn(
|
||||
'media URL resolution failed type=%s is_group=%s: %s',
|
||||
element.type,
|
||||
isGroup,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,20 +70,13 @@ export class MediaUrlResolver {
|
||||
}
|
||||
|
||||
if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
|
||||
if (isGroup) {
|
||||
element.url =
|
||||
element.type === 'record'
|
||||
? await this.bridge.apis.groupFile.getPttUrl(sessionId, element.mediaNode)
|
||||
: await this.bridge.apis.groupFile.getVideoUrl(
|
||||
sessionId,
|
||||
element.mediaNode,
|
||||
);
|
||||
} else {
|
||||
element.url =
|
||||
element.type === 'record'
|
||||
? await this.bridge.apis.groupFile.getPrivatePttUrl(element.mediaNode)
|
||||
: await this.bridge.apis.groupFile.getPrivateVideoUrl(element.mediaNode);
|
||||
}
|
||||
element.url = await resolveRemoteMediaUrl(
|
||||
this.bridge,
|
||||
element.type,
|
||||
element.mediaNode,
|
||||
isGroup,
|
||||
sessionId,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,28 @@ export type MessageMedia = Extract<MessageElement, { type: 'image' | 'record' |
|
||||
const mediaSnapshot = Symbol('message media snapshot');
|
||||
type MediaSegment = JsonObject & { [mediaSnapshot]?: MessageMedia };
|
||||
|
||||
/** Snapshot queued writes, including metadata that is deliberately absent from JSON. */
|
||||
export function snapshotMessageEvent(event: JsonObject): JsonObject {
|
||||
const snapshot = structuredClone(event);
|
||||
|
||||
if (Array.isArray(event.message) && Array.isArray(snapshot.message)) {
|
||||
for (const [index, segment] of event.message.entries()) {
|
||||
if (!segment || typeof segment !== 'object' || Array.isArray(segment)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const media = (segment as MediaSegment)[mediaSnapshot];
|
||||
const copied = snapshot.message[index];
|
||||
|
||||
if (media && copied && typeof copied === 'object') {
|
||||
Object.defineProperty(copied, mediaSnapshot, { value: structuredClone(media) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function isMessageMedia(element: MessageElement): element is MessageMedia {
|
||||
return element.type === 'image' || element.type === 'record' || element.type === 'video';
|
||||
}
|
||||
|
||||
@@ -11,20 +11,39 @@ import {
|
||||
import { parseFromCQString } from './helper/cq';
|
||||
import { getElementCodec, intOr } from './event-converter/element-codecs';
|
||||
import type { JsonValue } from './types';
|
||||
import { assertReplyPreviewType, elementsToReplyPreview } from './reply-preview';
|
||||
|
||||
const log = createLogger('MsgParser');
|
||||
|
||||
export { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
|
||||
interface ForwardReplyContext {
|
||||
senderUin: number;
|
||||
time?: number;
|
||||
}
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
resolveReplyMeta?: (replyMessageId: number) => {
|
||||
senderUin: number;
|
||||
time: number;
|
||||
random: number;
|
||||
elements?: MessageElement[];
|
||||
sequenceAuthoritative?: boolean;
|
||||
} | null;
|
||||
/** Custom quote defaults, supplied only while parsing a merged-forward node. */
|
||||
forwardReply?: ForwardReplyContext;
|
||||
/** Internal: quote content cannot nest replies or invoke action-like codecs. */
|
||||
replyPreview?: boolean;
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null | Promise<number | null>;
|
||||
resolveReplyMeta?: (replyMessageId: number) =>
|
||||
| {
|
||||
senderUin: number;
|
||||
time: number;
|
||||
random: number;
|
||||
elements?: MessageElement[];
|
||||
sequenceAuthoritative?: boolean;
|
||||
}
|
||||
| null
|
||||
| Promise<{
|
||||
senderUin: number;
|
||||
time: number;
|
||||
random: number;
|
||||
elements?: MessageElement[];
|
||||
sequenceAuthoritative?: boolean;
|
||||
} | null>;
|
||||
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
|
||||
resolveContactArk?: (
|
||||
contactType: string,
|
||||
@@ -95,15 +114,6 @@ function isExplicitEmptyTextPlaceholder(segment: MessageSegment): boolean {
|
||||
return normalizeSegmentType(segment.type) === 'text' && segmentPayload(segment).text === '';
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the OneBot payload is a forward: every effective segment is
|
||||
* `node` (explicit empty-text placeholders ignored). `send_msg` routes
|
||||
* this list through the forward upload path instead of parseMessage.
|
||||
*/
|
||||
export function isExclusiveForwardNodeMessage(message: JsonValue, autoEscape: boolean): boolean {
|
||||
return exclusiveForwardNodeList(message, autoEscape) !== null;
|
||||
}
|
||||
|
||||
/** Node segments from an exclusive forward payload, or null if it is not one. */
|
||||
export function exclusiveForwardNodeList(
|
||||
message: JsonValue,
|
||||
@@ -318,6 +328,55 @@ function requireCoordinate(data: Record<string, unknown>, field: 'lat' | 'lon'):
|
||||
return text;
|
||||
}
|
||||
|
||||
function replyInteger(
|
||||
data: Record<string, unknown>,
|
||||
field: string,
|
||||
defaultValue: number,
|
||||
max: number,
|
||||
min = 1,
|
||||
): number {
|
||||
const raw = data[field];
|
||||
const value = raw === undefined ? defaultValue : intOr(raw);
|
||||
|
||||
if (raw === null || (typeof raw === 'string' && !raw.trim()) || value < min || value > max) {
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
`reply.${field} must be an integer between ${min} and ${max}`,
|
||||
'reply',
|
||||
field,
|
||||
);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
async function parseForwardReply(
|
||||
data: Record<string, unknown>,
|
||||
context: ForwardReplyContext,
|
||||
): Promise<MessageElement> {
|
||||
const { message, ...metadata } = data;
|
||||
assertScalarSegmentData('reply', metadata);
|
||||
const replySenderUin = replyInteger(data, 'qq', context.senderUin, Number.MAX_SAFE_INTEGER);
|
||||
const replyTime = replyInteger(
|
||||
data,
|
||||
'time',
|
||||
context.time ?? Math.floor(Date.now() / 1000),
|
||||
0xffffffff,
|
||||
0,
|
||||
);
|
||||
// A synthetic quote has no live message to navigate to; QQ still needs a
|
||||
// positive origSeqs entry to render its inline preview.
|
||||
const replySeq = replyInteger(data, 'seq', 1, 0xffffffff);
|
||||
const elements = await parseMessage(message, false, { replyPreview: true });
|
||||
return validatedOutboundElement({
|
||||
type: 'reply',
|
||||
replySeq,
|
||||
replySenderUin,
|
||||
replyTime,
|
||||
replyElements: elementsToReplyPreview(elements),
|
||||
});
|
||||
}
|
||||
|
||||
export async function segmentToElement(
|
||||
type: string,
|
||||
data: Record<string, unknown>,
|
||||
@@ -325,6 +384,23 @@ export async function segmentToElement(
|
||||
): Promise<MessageElement | null> {
|
||||
const normalizedType = normalizeSegmentType(type);
|
||||
|
||||
if (options?.replyPreview) {
|
||||
assertReplyPreviewType(normalizedType);
|
||||
}
|
||||
|
||||
if (normalizedType === 'reply' && Object.hasOwn(data, 'message')) {
|
||||
if (!options?.forwardReply) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'reply.message is only supported inside a forward node',
|
||||
'reply',
|
||||
'message',
|
||||
);
|
||||
}
|
||||
|
||||
return parseForwardReply(data, options.forwardReply);
|
||||
}
|
||||
|
||||
// Ordinary OneBot segment fields are scalar. JSON deliberately accepts its
|
||||
// object-valued data/config compatibility fields; every other object/array
|
||||
// is rejected before a codec can coerce it and alter caller intent. Forward
|
||||
@@ -593,7 +669,7 @@ function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||
// --- Public API ---
|
||||
|
||||
export async function parseMessage(
|
||||
message: JsonValue,
|
||||
message: unknown,
|
||||
autoEscape: boolean,
|
||||
options?: ParseMessageOptions,
|
||||
): Promise<MessageElement[]> {
|
||||
@@ -658,7 +734,7 @@ export async function parseMessage(
|
||||
|
||||
// Single segment object
|
||||
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
|
||||
const seg = message as unknown as MessageSegment;
|
||||
const seg = message as MessageSegment;
|
||||
|
||||
if (typeof seg.type === 'string' && seg.type.trim()) {
|
||||
const data = segmentPayload(seg);
|
||||
|
||||
@@ -65,7 +65,7 @@ export async function runMessageStoreMigrationWorker(
|
||||
port.on('message', handleControlMessage);
|
||||
|
||||
try {
|
||||
prepareMessageStoreDatabase(data.dbPath);
|
||||
await prepareMessageStoreDatabase(data.dbPath);
|
||||
await migrateLegacyMedia(data.dbPath, () => cancelled);
|
||||
|
||||
if (cancelled) {
|
||||
@@ -88,7 +88,7 @@ export async function runMessageStoreMigrationWorker(
|
||||
let lastProgressAt: number | null = null;
|
||||
|
||||
while (!cancelled) {
|
||||
const status = migrator.runBatch(DEFAULT_BATCH_SIZE);
|
||||
const status = await migrator.runBatch(DEFAULT_BATCH_SIZE);
|
||||
const progressAt = performance.now();
|
||||
port.postMessage({
|
||||
kind: 'progress',
|
||||
@@ -110,7 +110,7 @@ export async function runMessageStoreMigrationWorker(
|
||||
} satisfies MessageStoreMigrationWorkerMessage);
|
||||
} finally {
|
||||
port.off('message', handleControlMessage);
|
||||
migrator?.close();
|
||||
await migrator?.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import { SqliteDatabase, type SqliteStatement } from '@snowluma/sqlite';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
|
||||
const CLASSIFICATION_VERSION = 1;
|
||||
@@ -38,149 +38,158 @@ interface PendingMessageRow {
|
||||
}
|
||||
|
||||
export class MessageStoreMigrator {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly selectInitialBatch: StatementSync;
|
||||
private readonly selectNextBatch: StatementSync;
|
||||
private readonly updateRow: StatementSync;
|
||||
private readonly updateState: StatementSync;
|
||||
private state: MigrationStateRow;
|
||||
private readonly db: SqliteDatabase;
|
||||
private selectInitialBatch!: SqliteStatement;
|
||||
private selectNextBatch!: SqliteStatement;
|
||||
private updateRow!: SqliteStatement;
|
||||
private updateState!: SqliteStatement;
|
||||
private state!: MigrationStateRow;
|
||||
|
||||
readonly initialization: Promise<void>;
|
||||
|
||||
constructor(
|
||||
dbPath: string,
|
||||
reportPreparation?: (progress: MessageStoreMigrationPreparation) => void,
|
||||
) {
|
||||
this.db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
|
||||
|
||||
try {
|
||||
createMigrationStateTable(this.db);
|
||||
this.state = this.loadOrCreateState(reportPreparation);
|
||||
this.initialization = this.db.serial(async () => {
|
||||
await createMigrationStateTable(this.db);
|
||||
this.state = await this.loadOrCreateState(reportPreparation);
|
||||
this.selectInitialBatch = this.db.prepare(`
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
this.selectNextBatch = this.db.prepare(`
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ? AND message_hash > ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
|
||||
FROM messages
|
||||
WHERE classification_version < ? AND message_hash > ?
|
||||
ORDER BY message_hash ASC
|
||||
LIMIT ?
|
||||
`);
|
||||
this.updateRow = this.db.prepare(`
|
||||
UPDATE messages
|
||||
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
|
||||
WHERE message_hash = ?
|
||||
AND classification_version < ?
|
||||
AND is_group = ?
|
||||
AND sequence = ?
|
||||
AND sequence_authoritative = ?
|
||||
AND client_sequence = ?
|
||||
AND private_direction = ?
|
||||
AND random = ?
|
||||
AND data IS ?
|
||||
`);
|
||||
UPDATE messages
|
||||
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
|
||||
WHERE message_hash = ?
|
||||
AND classification_version < ?
|
||||
AND is_group = ?
|
||||
AND sequence = ?
|
||||
AND sequence_authoritative = ?
|
||||
AND client_sequence = ?
|
||||
AND private_direction = ?
|
||||
AND random = ?
|
||||
AND data IS ?
|
||||
`);
|
||||
this.updateState = this.db.prepare(`
|
||||
UPDATE message_store_migration_state
|
||||
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
|
||||
WHERE name = ?
|
||||
`);
|
||||
} catch (error) {
|
||||
this.db.close();
|
||||
throw error;
|
||||
}
|
||||
UPDATE message_store_migration_state
|
||||
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
|
||||
WHERE name = ?
|
||||
`);
|
||||
});
|
||||
void this.initialization.catch(() => undefined);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
async close(): Promise<void> {
|
||||
await this.initialization.catch(() => undefined);
|
||||
await this.db.close();
|
||||
}
|
||||
|
||||
getStatus(): MessageStoreMigrationStatus {
|
||||
return publicStatus(this.state);
|
||||
async getStatus(): Promise<MessageStoreMigrationStatus> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
return publicStatus(this.state);
|
||||
});
|
||||
}
|
||||
|
||||
runBatch(batchSize: number): MessageStoreMigrationStatus {
|
||||
const limit = normalizeBatchSize(batchSize);
|
||||
async runBatch(batchSize: number): Promise<MessageStoreMigrationStatus> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const limit = normalizeBatchSize(batchSize);
|
||||
|
||||
if (this.state.phase === 'complete') {
|
||||
return this.getStatus();
|
||||
}
|
||||
|
||||
let rows = this.readBatch(limit, this.state.cursor);
|
||||
|
||||
if (rows.length === 0 && this.state.cursor !== null) {
|
||||
rows = this.readBatch(limit, null);
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
const remaining = this.countPending();
|
||||
this.persistState({
|
||||
...this.state,
|
||||
phase: remaining === 0 ? 'complete' : 'migrating',
|
||||
processed: remaining === 0 ? this.state.total : this.state.total - remaining,
|
||||
cursor: null,
|
||||
});
|
||||
return this.getStatus();
|
||||
}
|
||||
|
||||
const lastMessageHash = rows[rows.length - 1].message_hash;
|
||||
const classified = rows.map((row) => ({ row, classification: classifyLegacyMessage(row) }));
|
||||
let updatedRows = 0;
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
for (const { row, classification } of classified) {
|
||||
const result = this.updateRow.run(
|
||||
classification.sequenceAuthoritative ? 1 : 0,
|
||||
classification.privateDirection,
|
||||
CLASSIFICATION_VERSION,
|
||||
row.message_hash,
|
||||
CLASSIFICATION_VERSION,
|
||||
row.is_group,
|
||||
row.sequence,
|
||||
row.sequence_authoritative,
|
||||
row.client_sequence,
|
||||
row.private_direction,
|
||||
row.random,
|
||||
row.data,
|
||||
);
|
||||
updatedRows += Number(result.changes);
|
||||
if (this.state.phase === 'complete') {
|
||||
return this.getStatus();
|
||||
}
|
||||
|
||||
const nextState: MigrationStateRow = {
|
||||
...this.state,
|
||||
processed: Math.min(this.state.total, this.state.processed + updatedRows),
|
||||
cursor: lastMessageHash,
|
||||
};
|
||||
this.writeState(nextState);
|
||||
this.db.exec('COMMIT');
|
||||
this.state = nextState;
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
let rows = await this.readBatch(limit, this.state.cursor);
|
||||
|
||||
if (rows.length < limit) {
|
||||
const remaining = this.countPending();
|
||||
if (rows.length === 0 && this.state.cursor !== null) {
|
||||
rows = await this.readBatch(limit, null);
|
||||
}
|
||||
|
||||
if (remaining === 0) {
|
||||
this.persistState({
|
||||
if (rows.length === 0) {
|
||||
const remaining = await this.countPending();
|
||||
await this.persistState({
|
||||
...this.state,
|
||||
phase: 'complete',
|
||||
processed: this.state.total,
|
||||
phase: remaining === 0 ? 'complete' : 'migrating',
|
||||
processed: remaining === 0 ? this.state.total : this.state.total - remaining,
|
||||
cursor: null,
|
||||
});
|
||||
return this.getStatus();
|
||||
}
|
||||
}
|
||||
|
||||
return this.getStatus();
|
||||
const lastMessageHash = rows[rows.length - 1].message_hash;
|
||||
const classified = rows.map((row) => ({
|
||||
row,
|
||||
classification: classifyLegacyMessage(row),
|
||||
}));
|
||||
let updatedRows = 0;
|
||||
await this.db.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
for (const { row, classification } of classified) {
|
||||
const result = await this.updateRow.run(
|
||||
classification.sequenceAuthoritative ? 1 : 0,
|
||||
classification.privateDirection,
|
||||
CLASSIFICATION_VERSION,
|
||||
row.message_hash,
|
||||
CLASSIFICATION_VERSION,
|
||||
row.is_group,
|
||||
row.sequence,
|
||||
row.sequence_authoritative,
|
||||
row.client_sequence,
|
||||
row.private_direction,
|
||||
row.random,
|
||||
row.data,
|
||||
);
|
||||
updatedRows += Number(result.changes);
|
||||
}
|
||||
|
||||
const nextState: MigrationStateRow = {
|
||||
...this.state,
|
||||
processed: Math.min(this.state.total, this.state.processed + updatedRows),
|
||||
cursor: lastMessageHash,
|
||||
};
|
||||
await this.writeState(nextState);
|
||||
await this.db.exec('COMMIT');
|
||||
this.state = nextState;
|
||||
} catch (error) {
|
||||
await this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (rows.length < limit) {
|
||||
const remaining = await this.countPending();
|
||||
|
||||
if (remaining === 0) {
|
||||
await this.persistState({
|
||||
...this.state,
|
||||
phase: 'complete',
|
||||
processed: this.state.total,
|
||||
cursor: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return this.getStatus();
|
||||
});
|
||||
}
|
||||
|
||||
private loadOrCreateState(
|
||||
private async loadOrCreateState(
|
||||
reportPreparation?: (progress: MessageStoreMigrationPreparation) => void,
|
||||
): MigrationStateRow {
|
||||
const existing = this.db
|
||||
): Promise<MigrationStateRow> {
|
||||
const existing = (await this.db
|
||||
.prepare(
|
||||
`
|
||||
SELECT phase, processed, total, cursor
|
||||
@@ -188,7 +197,7 @@ export class MessageStoreMigrator {
|
||||
WHERE name = ?
|
||||
`,
|
||||
)
|
||||
.get(MIGRATION_NAME) as MigrationStateRow | undefined;
|
||||
.get(MIGRATION_NAME)) as MigrationStateRow | undefined;
|
||||
|
||||
if (existing?.phase === 'complete') {
|
||||
return existing;
|
||||
@@ -196,7 +205,7 @@ export class MessageStoreMigrator {
|
||||
|
||||
reportPreparation?.({ stage: 'started' });
|
||||
const preparationStartedAt = performance.now();
|
||||
this.db.exec(`
|
||||
await this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS ${PENDING_INDEX_NAME}
|
||||
ON messages(message_hash, classification_version)
|
||||
WHERE classification_version < ${CLASSIFICATION_VERSION}
|
||||
@@ -211,7 +220,7 @@ export class MessageStoreMigrator {
|
||||
}
|
||||
|
||||
const countStartedAt = performance.now();
|
||||
const row = this.db
|
||||
const row = (await this.db
|
||||
.prepare(
|
||||
`
|
||||
SELECT COUNT(*) AS total
|
||||
@@ -219,7 +228,7 @@ export class MessageStoreMigrator {
|
||||
WHERE classification_version < ?
|
||||
`,
|
||||
)
|
||||
.get(CLASSIFICATION_VERSION) as { total: number };
|
||||
.get(CLASSIFICATION_VERSION)) as { total: number };
|
||||
const total = Number(row.total);
|
||||
reportPreparation?.({
|
||||
stage: 'counted',
|
||||
@@ -233,7 +242,7 @@ export class MessageStoreMigrator {
|
||||
total,
|
||||
cursor: null,
|
||||
};
|
||||
this.db
|
||||
await this.db
|
||||
.prepare(
|
||||
`
|
||||
INSERT INTO message_store_migration_state
|
||||
@@ -245,8 +254,8 @@ export class MessageStoreMigrator {
|
||||
return state;
|
||||
}
|
||||
|
||||
private countPending(): number {
|
||||
const row = this.db
|
||||
private async countPending(): Promise<number> {
|
||||
const row = (await this.db
|
||||
.prepare(
|
||||
`
|
||||
SELECT COUNT(*) AS total
|
||||
@@ -254,35 +263,35 @@ export class MessageStoreMigrator {
|
||||
WHERE classification_version < ?
|
||||
`,
|
||||
)
|
||||
.get(CLASSIFICATION_VERSION) as { total: number };
|
||||
.get(CLASSIFICATION_VERSION)) as { total: number };
|
||||
return Number(row.total);
|
||||
}
|
||||
|
||||
private readBatch(limit: number, cursor: number | null): PendingMessageRow[] {
|
||||
private async readBatch(limit: number, cursor: number | null): Promise<PendingMessageRow[]> {
|
||||
return (cursor === null
|
||||
? this.selectInitialBatch.all(CLASSIFICATION_VERSION, limit)
|
||||
: this.selectNextBatch.all(
|
||||
? await this.selectInitialBatch.all(CLASSIFICATION_VERSION, limit)
|
||||
: await this.selectNextBatch.all(
|
||||
CLASSIFICATION_VERSION,
|
||||
cursor,
|
||||
limit,
|
||||
)) as unknown as PendingMessageRow[];
|
||||
}
|
||||
|
||||
private persistState(state: MigrationStateRow): void {
|
||||
this.db.exec('BEGIN IMMEDIATE');
|
||||
private async persistState(state: MigrationStateRow): Promise<void> {
|
||||
await this.db.exec('BEGIN IMMEDIATE');
|
||||
|
||||
try {
|
||||
this.writeState(state);
|
||||
this.db.exec('COMMIT');
|
||||
await this.writeState(state);
|
||||
await this.db.exec('COMMIT');
|
||||
this.state = state;
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
await this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private writeState(state: MigrationStateRow): void {
|
||||
this.updateState.run(
|
||||
private async writeState(state: MigrationStateRow): Promise<void> {
|
||||
await this.updateState.run(
|
||||
state.phase,
|
||||
state.processed,
|
||||
state.total,
|
||||
@@ -293,12 +302,12 @@ export class MessageStoreMigrator {
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareMessageStoreDatabase(dbPath: string): void {
|
||||
export async function prepareMessageStoreDatabase(dbPath: string): Promise<void> {
|
||||
const db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
|
||||
|
||||
try {
|
||||
const messagesTableExists =
|
||||
db
|
||||
(await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT 1 AS present
|
||||
@@ -306,8 +315,8 @@ export function prepareMessageStoreDatabase(dbPath: string): void {
|
||||
WHERE type = 'table' AND name = 'messages'
|
||||
`,
|
||||
)
|
||||
.get() !== undefined;
|
||||
db.exec(`
|
||||
.get()) !== undefined;
|
||||
await db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
message_hash INTEGER PRIMARY KEY,
|
||||
is_group INTEGER NOT NULL,
|
||||
@@ -323,22 +332,24 @@ export function prepareMessageStoreDatabase(dbPath: string): void {
|
||||
classification_version INTEGER NOT NULL DEFAULT 1
|
||||
)
|
||||
`);
|
||||
prepareMessageStoreSchema(db);
|
||||
await prepareMessageStoreSchema(db);
|
||||
|
||||
if (!messagesTableExists) {
|
||||
createMessageStoreIndexes(db);
|
||||
await createMessageStoreIndexes(db);
|
||||
}
|
||||
} finally {
|
||||
db.close();
|
||||
await db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrationStatus {
|
||||
export async function inspectMessageStoreMigration(
|
||||
dbPath: string,
|
||||
): Promise<MessageStoreMigrationStatus> {
|
||||
const db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
|
||||
|
||||
try {
|
||||
createMigrationStateTable(db);
|
||||
const row = db
|
||||
await createMigrationStateTable(db);
|
||||
const row = (await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT phase, processed, total
|
||||
@@ -346,13 +357,13 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
|
||||
WHERE name = ?
|
||||
`,
|
||||
)
|
||||
.get(MIGRATION_NAME) as MessageStoreMigrationStatus | undefined;
|
||||
.get(MIGRATION_NAME)) as MessageStoreMigrationStatus | undefined;
|
||||
|
||||
if (row) {
|
||||
return row;
|
||||
}
|
||||
|
||||
const pending = db
|
||||
const pending = (await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT COUNT(*) AS total
|
||||
@@ -360,62 +371,66 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
|
||||
WHERE classification_version < ?
|
||||
`,
|
||||
)
|
||||
.get(CLASSIFICATION_VERSION) as { total: number };
|
||||
.get(CLASSIFICATION_VERSION)) as { total: number };
|
||||
const total = Number(pending.total);
|
||||
return { phase: total === 0 ? 'complete' : 'migrating', processed: 0, total };
|
||||
} finally {
|
||||
db.close();
|
||||
await db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareMessageStoreSchema(db: DatabaseSync): void {
|
||||
const before = db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>;
|
||||
export async function prepareMessageStoreSchema(db: SqliteDatabase): Promise<void> {
|
||||
const before = (await db.prepare('PRAGMA table_info(messages)').all()) as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
const existingColumns = new Set(before.map((column) => column.name));
|
||||
|
||||
if (!existingColumns.has('media_data')) {
|
||||
db.exec('ALTER TABLE messages ADD COLUMN media_data TEXT');
|
||||
await db.exec('ALTER TABLE messages ADD COLUMN media_data TEXT');
|
||||
}
|
||||
|
||||
const existingRowsAreCurrent =
|
||||
existingColumns.has('sequence_authoritative') &&
|
||||
existingColumns.has('private_direction') &&
|
||||
hasLegacyPrivateSequenceMigration(db);
|
||||
(await hasLegacyPrivateSequenceMigration(db));
|
||||
|
||||
if (!existingColumns.has('sequence_authoritative')) {
|
||||
db.exec(
|
||||
await db.exec(
|
||||
'ALTER TABLE messages ADD COLUMN sequence_authoritative INTEGER NOT NULL DEFAULT 1',
|
||||
);
|
||||
}
|
||||
|
||||
if (!existingColumns.has('private_direction')) {
|
||||
db.exec('ALTER TABLE messages ADD COLUMN private_direction INTEGER NOT NULL DEFAULT -1');
|
||||
await db.exec(
|
||||
'ALTER TABLE messages ADD COLUMN private_direction INTEGER NOT NULL DEFAULT -1',
|
||||
);
|
||||
}
|
||||
|
||||
if (!existingColumns.has('classification_version')) {
|
||||
db.exec(
|
||||
await db.exec(
|
||||
`ALTER TABLE messages ADD COLUMN classification_version INTEGER NOT NULL DEFAULT ${existingRowsAreCurrent ? CLASSIFICATION_VERSION : 0}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function createMessageStoreIndexes(db: DatabaseSync): void {
|
||||
db.exec(
|
||||
export async function createMessageStoreIndexes(db: SqliteDatabase): Promise<void> {
|
||||
await db.exec(
|
||||
'CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)',
|
||||
);
|
||||
db.exec(
|
||||
await db.exec(
|
||||
'CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)',
|
||||
);
|
||||
db.exec(
|
||||
await db.exec(
|
||||
'CREATE INDEX IF NOT EXISTS idx_messages_private_client_seq ON messages(is_group, session_id, client_sequence)',
|
||||
);
|
||||
db.exec(
|
||||
await db.exec(
|
||||
'CREATE INDEX IF NOT EXISTS idx_messages_private_client_direction ON messages(is_group, session_id, client_sequence, private_direction)',
|
||||
);
|
||||
}
|
||||
|
||||
function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
|
||||
async function hasLegacyPrivateSequenceMigration(db: SqliteDatabase): Promise<boolean> {
|
||||
const tableExists =
|
||||
db
|
||||
(await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT 1 AS present
|
||||
@@ -423,14 +438,14 @@ function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
|
||||
WHERE type = 'table' AND name = 'message_store_migrations'
|
||||
`,
|
||||
)
|
||||
.get() !== undefined;
|
||||
.get()) !== undefined;
|
||||
|
||||
if (!tableExists) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
db
|
||||
(await db
|
||||
.prepare(
|
||||
`
|
||||
SELECT 1 AS applied
|
||||
@@ -438,12 +453,12 @@ function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
|
||||
WHERE name = ?
|
||||
`,
|
||||
)
|
||||
.get(LEGACY_PRIVATE_SEQUENCE_MIGRATION) !== undefined
|
||||
.get(LEGACY_PRIVATE_SEQUENCE_MIGRATION)) !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
function createMigrationStateTable(db: DatabaseSync): void {
|
||||
db.exec(`
|
||||
async function createMigrationStateTable(db: SqliteDatabase): Promise<void> {
|
||||
await db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS message_store_migration_state (
|
||||
name TEXT PRIMARY KEY,
|
||||
phase TEXT NOT NULL,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,19 +1,137 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { ImageUrlResolver } from '../event-converter';
|
||||
import type { MediaStore } from '../media-store';
|
||||
import type { CachedImage, MediaStore } from '../media-store';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import { resolveRemoteMediaUrl } from '../media-url-resolver';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import {
|
||||
deliverPttTransText,
|
||||
failPttTransWaiter,
|
||||
pttTransKey,
|
||||
waitPttTransText,
|
||||
} from './ptt-trans-waiter';
|
||||
import type { JsonObject } from '../types';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
type StoredMediaSegment = JsonObject & { type: 'image' | 'record' | 'video'; data: JsonObject };
|
||||
|
||||
function isStoredMediaSegment(segment: JsonValue): segment is StoredMediaSegment {
|
||||
return (
|
||||
segment !== null &&
|
||||
typeof segment === 'object' &&
|
||||
!Array.isArray(segment) &&
|
||||
(segment.type === 'image' || segment.type === 'record' || segment.type === 'video') &&
|
||||
segment.data !== null &&
|
||||
typeof segment.data === 'object' &&
|
||||
!Array.isArray(segment.data)
|
||||
);
|
||||
}
|
||||
|
||||
export async function refreshMessageMedia(
|
||||
ref: Pick<OneBotInstanceContext, 'bridge' | 'messageStore' | 'mediaStore' | 'converterCtx'>,
|
||||
messageId: number,
|
||||
event: JsonObject,
|
||||
): Promise<void> {
|
||||
if (!Array.isArray(event.message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const segments = event.message.filter(isStoredMediaSegment);
|
||||
const voiceVideoSegments = segments.filter((segment) => segment.type !== 'image');
|
||||
const media =
|
||||
voiceVideoSegments.length > 0
|
||||
? (await ref.messageStore.findMedia(messageId))?.filter(
|
||||
(element) => element.type !== 'image',
|
||||
)
|
||||
: null;
|
||||
const meta = voiceVideoSegments.length > 0 ? await ref.messageStore.findMeta(messageId) : null;
|
||||
// Validate the ordered association once; a filename lookup can select another upload.
|
||||
const voiceVideo =
|
||||
meta &&
|
||||
media &&
|
||||
media.length === voiceVideoSegments.length &&
|
||||
media.every((element, index) => element.type === voiceVideoSegments[index]!.type)
|
||||
? { media, meta }
|
||||
: null;
|
||||
|
||||
if (voiceVideoSegments.length > 0 && !voiceVideo) {
|
||||
log.warn('[get_msg] media metadata missing or inconsistent message_id=%d', messageId);
|
||||
}
|
||||
|
||||
let voiceVideoIndex = 0;
|
||||
let changed = false;
|
||||
|
||||
for (const [index, segment] of segments.entries()) {
|
||||
try {
|
||||
let url: string | null;
|
||||
|
||||
if (segment.type === 'image') {
|
||||
const file =
|
||||
typeof segment.data.file === 'string'
|
||||
? segment.data.file
|
||||
: segment.data.file_id;
|
||||
|
||||
if (typeof file !== 'string' || !file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
url = await resolveImageUrl(
|
||||
await ref.mediaStore.findImage(file),
|
||||
ref.converterCtx.imageUrlResolver,
|
||||
);
|
||||
} else {
|
||||
if (!voiceVideo) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const element = voiceVideo.media[voiceVideoIndex++]!;
|
||||
url = await resolveRemoteMediaUrl(
|
||||
ref.bridge,
|
||||
element.type,
|
||||
element.mediaNode,
|
||||
voiceVideo.meta.isGroup,
|
||||
voiceVideo.meta.targetId,
|
||||
);
|
||||
}
|
||||
|
||||
if (url && url !== segment.data.url) {
|
||||
segment.data.url = url;
|
||||
changed = true;
|
||||
}
|
||||
} catch (err) {
|
||||
// Refresh failure preserves this message's URL, never a different cached URL.
|
||||
log.warn(
|
||||
'[get_msg] media URL refresh failed message_id=%d type=%s media_index=%d: %s',
|
||||
messageId,
|
||||
segment.type,
|
||||
index,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
event.raw_message = segmentsToRawMessage(event.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveImageUrl(
|
||||
cached: CachedImage | null,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
): Promise<string | null> {
|
||||
if (!cached?.imageUrl || !resolver) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return resolver(
|
||||
{ type: 'image', imageUrl: cached.imageUrl, subType: cached.subType },
|
||||
cached.isGroup,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Voice-to-text for a received ptt (issue #79 / NapCat `fetch_ptt_text`).
|
||||
* Resolves the message's `record` segment to its cached fingerprint
|
||||
@@ -27,7 +145,7 @@ export async function fetchPttText(
|
||||
selfId: number,
|
||||
messageId: number,
|
||||
): Promise<{ text: string }> {
|
||||
const event = messageStore.findEvent(messageId);
|
||||
const event = await messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new Error('消息不存在或已被撤回');
|
||||
@@ -59,16 +177,16 @@ export async function fetchPttText(
|
||||
throw new Error('消息中不包含语音');
|
||||
}
|
||||
|
||||
const snapshot = messageStore
|
||||
.findMedia(messageId)
|
||||
?.find((element) => element.type === 'record');
|
||||
const snapshot = (await messageStore.findMedia(messageId))?.find(
|
||||
(element) => element.type === 'record',
|
||||
);
|
||||
const cached = snapshot
|
||||
? {
|
||||
...snapshot,
|
||||
isGroup: event.message_type === 'group',
|
||||
sessionId: Number(event.group_id) || selfId,
|
||||
}
|
||||
: mediaStore.findRecord(file, 'legacy');
|
||||
: await mediaStore.findRecord(file, 'legacy');
|
||||
|
||||
if (!cached) {
|
||||
throw new Error('语音不在缓存中,无法转写');
|
||||
@@ -114,7 +232,7 @@ export async function getImageInfo(
|
||||
file: string,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
const cached = await mediaStore.findImage(file);
|
||||
|
||||
if (!cached) {
|
||||
return null;
|
||||
@@ -122,27 +240,17 @@ export async function getImageInfo(
|
||||
|
||||
let url = cached.url || cached.imageUrl || '';
|
||||
|
||||
// Re-sign with a current rkey at lookup time. The stored `url` was signed
|
||||
// when the message first arrived and its rkey may have since expired — the
|
||||
// CDN then rejects the download with
|
||||
// `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw
|
||||
// (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which
|
||||
// re-signs on every getImageUrl call instead of handing back a baked URL.
|
||||
if (imageUrlResolver && cached.imageUrl) {
|
||||
try {
|
||||
const element: MessageElement = {
|
||||
type: 'image',
|
||||
imageUrl: cached.imageUrl,
|
||||
subType: cached.subType,
|
||||
};
|
||||
const fresh = await imageUrlResolver(element, cached.isGroup);
|
||||
try {
|
||||
const fresh = await resolveImageUrl(cached, imageUrlResolver);
|
||||
|
||||
if (fresh) {
|
||||
url = fresh;
|
||||
}
|
||||
} catch {
|
||||
// Best-effort: fall back to the stored URL on any resolver failure.
|
||||
if (fresh) {
|
||||
url = fresh;
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'get_image URL refresh failed: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -158,34 +266,23 @@ export async function getRecordInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findRecord(file);
|
||||
const cached = await mediaStore.findRecord(file);
|
||||
|
||||
if (!cached) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let url = cached.url;
|
||||
|
||||
if (!url && cached.mediaNode) {
|
||||
try {
|
||||
url = cached.isGroup
|
||||
? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode)
|
||||
: await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode);
|
||||
|
||||
if (url) {
|
||||
mediaStore.updateRecordUrl(file, url);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'get_record url refetch failed: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const url = await resolveRemoteMediaUrl(
|
||||
bridge,
|
||||
'record',
|
||||
cached.mediaNode,
|
||||
cached.isGroup,
|
||||
cached.sessionId,
|
||||
);
|
||||
await mediaStore.updateRecordUrl(file, url);
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url: url || '',
|
||||
file: url,
|
||||
url,
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { isMessageMedia, type MessageMedia } from '../message-media';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
} from '../message-parser';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import { sameSelfSentMessage } from '../self-sent-event';
|
||||
import { replyPreviewElements } from '../reply-preview';
|
||||
import {
|
||||
hasAuthoritativeSequence,
|
||||
type JsonArray,
|
||||
@@ -36,49 +38,6 @@ import {
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
function replyPreviewElements(message: unknown): MessageElement[] {
|
||||
if (!Array.isArray(message)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
image: '[图片]',
|
||||
record: '[语音]',
|
||||
video: '[视频]',
|
||||
file: '[文件]',
|
||||
face: '[表情]',
|
||||
mface: '[表情]',
|
||||
forward: '[聊天记录]',
|
||||
json: '[卡片]',
|
||||
xml: '[卡片]',
|
||||
markdown: '[Markdown]',
|
||||
};
|
||||
const parts: string[] = [];
|
||||
|
||||
for (const segment of message) {
|
||||
if (!segment || typeof segment !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = segment.data;
|
||||
|
||||
if (!data || typeof data !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segment.type === 'text' && typeof data.text === 'string') {
|
||||
parts.push(data.text);
|
||||
} else if (segment.type === 'at') {
|
||||
parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
|
||||
} else if (typeof segment.type === 'string' && labels[segment.type]) {
|
||||
parts.push(labels[segment.type]);
|
||||
}
|
||||
}
|
||||
|
||||
const text = parts.join('');
|
||||
return text ? [{ type: 'text', text }] : [];
|
||||
}
|
||||
|
||||
// A video larger than QQ's Highway video ceiling can't be sent through the
|
||||
// element pipeline — it must fall back to a regular file upload. The fallback
|
||||
// is decided at the OneBot layer (not element-builder) because building a
|
||||
@@ -167,7 +126,7 @@ export async function getGroupMsgHistory(
|
||||
let anchorSequence: number | undefined;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = messageStore.findMeta(messageId as number);
|
||||
const meta = await messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
|
||||
return [];
|
||||
@@ -176,7 +135,7 @@ export async function getGroupMsgHistory(
|
||||
anchorSequence = meta.sequence;
|
||||
}
|
||||
|
||||
const events = messageStore.listSessionEvents(
|
||||
const events = await messageStore.listSessionEvents(
|
||||
true,
|
||||
groupId,
|
||||
limit,
|
||||
@@ -212,7 +171,7 @@ export async function getFriendMsgHistory(
|
||||
let anchorSequence: number | undefined;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = messageStore.findMeta(messageId as number);
|
||||
const meta = await messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || meta.isGroup || meta.targetId !== userId) {
|
||||
return [];
|
||||
@@ -221,7 +180,7 @@ export async function getFriendMsgHistory(
|
||||
anchorSequence = meta.sequence;
|
||||
}
|
||||
|
||||
const events = messageStore.listSessionEvents(
|
||||
const events = await messageStore.listSessionEvents(
|
||||
false,
|
||||
userId,
|
||||
limit,
|
||||
@@ -272,7 +231,7 @@ export async function getGroupHistory(
|
||||
let anchorSeq = 0;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = ref.messageStore.findMeta(messageId as number);
|
||||
const meta = await ref.messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
|
||||
// Anchor we don't know — best effort from the local store.
|
||||
@@ -281,7 +240,7 @@ export async function getGroupHistory(
|
||||
|
||||
anchorSeq = meta.sequence;
|
||||
} else {
|
||||
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0;
|
||||
anchorSeq = (await ref.messageStore.findLatestAuthoritativeSequence(true, groupId)) ?? 0;
|
||||
}
|
||||
|
||||
log.debug(
|
||||
@@ -309,7 +268,7 @@ export async function getGroupHistory(
|
||||
continue;
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
|
||||
await persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
|
||||
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
|
||||
}
|
||||
|
||||
@@ -365,13 +324,15 @@ export async function getFriendHistory(
|
||||
let anchorSeq = 0;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = ref.messageStore.findMeta(messageId as number);
|
||||
const meta = await ref.messageStore.findMeta(messageId as number);
|
||||
// Older self-sent rows may be keyed by selfId. Only accept one of those
|
||||
// when its stored target_id proves that it belongs to this peer; otherwise
|
||||
// a message_id from another private conversation could select the wrong
|
||||
// server sequence.
|
||||
const storedEvent =
|
||||
meta?.targetId === ref.selfId ? ref.messageStore.findEvent(messageId as number) : null;
|
||||
meta?.targetId === ref.selfId
|
||||
? await ref.messageStore.findEvent(messageId as number)
|
||||
: null;
|
||||
const belongsToPeer =
|
||||
meta?.targetId === userId ||
|
||||
(meta?.targetId === ref.selfId && toHistoryInt(storedEvent?.target_id) === userId);
|
||||
@@ -422,11 +383,15 @@ export async function getFriendHistory(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Conversion can await media resolution, so consult the tombstone only
|
||||
// after it settles. From this check through persistence/return there is no
|
||||
// async gap in which a recall could race past us.
|
||||
// Conversion can await media resolution, so check again after it settles.
|
||||
// Persistence also checks recalls queued while this lookup is in flight.
|
||||
if (
|
||||
ref.messageStore.isPrivateMessageRecalled(userId, clientSequence, sentBySelf, ev.time)
|
||||
await ref.messageStore.isPrivateMessageRecalled(
|
||||
userId,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
ev.time,
|
||||
)
|
||||
) {
|
||||
log.debug(
|
||||
'friend history omitted recalled message: user=%d clientSeq=%d self=%s',
|
||||
@@ -443,8 +408,9 @@ export async function getFriendHistory(
|
||||
json.target_id = userId;
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, json, userId, ev);
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
if (await persistHistoryEvent(ref.messageStore, json, userId, ev)) {
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
}
|
||||
}
|
||||
|
||||
log.debug(
|
||||
@@ -505,7 +471,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: privateMessageEventName(quotedSender === ref.selfId, false);
|
||||
const resolvedId = ref.converterCtx.messageIdResolver?.(
|
||||
const resolvedId = await ref.converterCtx.messageIdResolver?.(
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
@@ -517,7 +483,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
? (resolvedId as number)
|
||||
: hashMessageIdInt32(replySeq, session, eventName);
|
||||
|
||||
if (ref.messageStore.findEvent(targetId)) {
|
||||
if (await ref.messageStore.findEvent(targetId)) {
|
||||
return;
|
||||
} // Tier 0: already have the full event
|
||||
|
||||
@@ -568,12 +534,19 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
json.message_id = targetId;
|
||||
|
||||
if (fetched.kind === 'group_message') {
|
||||
ref.messageStore.storeEvent(targetId, true, session, replySeq, eventName, json);
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
true,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
json,
|
||||
);
|
||||
} else {
|
||||
const serverSequence = fetched.ntMsgSeq ?? 0;
|
||||
const sequenceAuthoritative =
|
||||
fetched.sequenceAuthoritative !== false && serverSequence > 0;
|
||||
ref.messageStore.storeMeta(targetId, {
|
||||
await ref.messageStore.storeMeta(targetId, {
|
||||
isGroup: false,
|
||||
targetId: session,
|
||||
sequence: serverSequence,
|
||||
@@ -585,16 +558,14 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
random: fetched.msgId,
|
||||
timestamp: fetched.time,
|
||||
});
|
||||
ref.messageStore.storeEvent(
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
false,
|
||||
session,
|
||||
serverSequence,
|
||||
eventName,
|
||||
json,
|
||||
{
|
||||
sequenceAuthoritative,
|
||||
},
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -632,9 +603,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
// Inline quote metadata proves what was displayed, but not that replySeq
|
||||
// still names a server-backed roam message. Keep it queryable via
|
||||
// get_msg without letting it become a history/recall/reply anchor.
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback, {
|
||||
sequenceAuthoritative: false,
|
||||
});
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
fallback,
|
||||
{ sequenceAuthoritative: false },
|
||||
);
|
||||
return;
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
@@ -657,9 +634,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
isGroup,
|
||||
session,
|
||||
);
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder, {
|
||||
sequenceAuthoritative: false,
|
||||
});
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
placeholder,
|
||||
{ sequenceAuthoritative: false },
|
||||
);
|
||||
}
|
||||
|
||||
// Build a stored-message event for a backfilled reply target (Tier 2/3).
|
||||
@@ -743,7 +726,7 @@ export async function setEssenceMessage(
|
||||
messageId: number,
|
||||
enable: boolean,
|
||||
): Promise<void> {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
throw new Error('message not found or not a group message');
|
||||
@@ -757,30 +740,9 @@ export async function setEssenceMessage(
|
||||
}
|
||||
|
||||
/**
|
||||
* Build + store a synthetic OneBot event for a just-sent message so
|
||||
* `/get_msg` can find it.
|
||||
*
|
||||
* The QQ server doesn't always echo self-sent messages back on the
|
||||
* receive channel — Lagrange and NapCat both work around this by
|
||||
* writing a local copy at send time (Lagrange persists into Realm DB
|
||||
* inside `SendMessageOperation`; NapCat caches in-memory via its msg
|
||||
* service). Without it, callers that hit `/get_msg` with a freshly-
|
||||
* returned `message_id` get "message not found" even though the recall
|
||||
* path works fine (recall uses the lighter `cacheMessageMeta` already).
|
||||
*
|
||||
* Stored event has `post_type: 'message_sent'` so OneBot clients that
|
||||
* inspect it through `/get_msg` can distinguish their own outbound
|
||||
* messages from incoming ones.
|
||||
*/
|
||||
/**
|
||||
* The shared "record a self-sent message" tail: derive the OneBot message id
|
||||
* from (sequence, target, event), then cache both the meta and the self-sent
|
||||
* copy. Centralizes the `isGroup ↔ eventName ↔ hashMessageIdInt32 event
|
||||
* constant` coupling that was hand-paired in six send/forward paths — a
|
||||
* mismatch there silently produced a wrong message_id or wrong event
|
||||
* attribution. Returns the derived message id and, for an eligible plain C2C
|
||||
* Action send, an event for the OneBot dispatch path when QQ has not already
|
||||
* supplied the canonical echo.
|
||||
* Derive the same message id for send/receive paths and persist the sent
|
||||
* message for get_msg, since QQ does not always echo it. Eligible C2C sends
|
||||
* also return a message_sent event when no canonical echo has arrived.
|
||||
*/
|
||||
async function finalizeSend(
|
||||
ref: OneBotInstanceContext,
|
||||
@@ -810,7 +772,7 @@ async function finalizeSend(
|
||||
: Number.isInteger(opaqueMessageId) && opaqueMessageId !== 0
|
||||
? opaqueMessageId
|
||||
: hashMessageIdInt32(isGroup ? 0 : receipt.clientSequence, targetId, eventName);
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
await ref.cacheMessageMeta(messageId, {
|
||||
isGroup,
|
||||
targetId,
|
||||
sequence: receipt.sequence,
|
||||
@@ -865,35 +827,16 @@ async function cacheSelfSentMessage(
|
||||
elements,
|
||||
} = options;
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Defensive: tests may mock `ref.messageStore` without the full MessageStore
|
||||
// surface. Production always has it. Without storage, recall still works via
|
||||
// cacheMessageMeta, but `/get_msg` and the synthetic event are unavailable.
|
||||
const storeEvent = (ref.messageStore as { storeEvent?: typeof ref.messageStore.storeEvent })
|
||||
.storeEvent;
|
||||
|
||||
if (typeof storeEvent !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
// We deliberately pass no URL resolvers — for a synthetic self-sent
|
||||
// event the file/url fields in segments are best-effort (they're
|
||||
// already what the OneBot caller passed in). Image/video URLs would
|
||||
// need a real resolver to render in `/get_msg`, but the existing
|
||||
// resolver is async and bound to the receive pipeline; skipping it
|
||||
// means /get_msg returns the segment with the original `file` path
|
||||
// and an empty `url`, which is what Lagrange does too.
|
||||
// Persist upload metadata without another QQ request on the send path.
|
||||
// get_msg / get_record resolve remote media URLs when the consumer reads.
|
||||
const segments = (await elementsToOneBotSegments(
|
||||
{
|
||||
selfId: ref.selfId,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
mediaSegmentSink: ref.converterCtx.mediaSegmentSink,
|
||||
},
|
||||
elements,
|
||||
isGroup,
|
||||
@@ -939,7 +882,7 @@ async function cacheSelfSentMessage(
|
||||
// QQ can win the race between the send receipt and local event
|
||||
// construction. Keep its richer canonical event and let the already-run
|
||||
// bridge dispatch remain the single downstream notification.
|
||||
const existing = ref.messageStore.findEvent(messageId);
|
||||
const existing = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (existing && sameSelfSentMessage(existing, event)) {
|
||||
return null;
|
||||
@@ -947,17 +890,14 @@ async function cacheSelfSentMessage(
|
||||
|
||||
// Persist before dispatch so `/get_msg` is immediately consistent for a
|
||||
// client reacting to the synthetic message_sent notification.
|
||||
storeEvent.call(
|
||||
ref.messageStore,
|
||||
await ref.messageStore.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
{
|
||||
sequenceAuthoritative,
|
||||
},
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
return event;
|
||||
} catch (err) {
|
||||
@@ -999,7 +939,7 @@ export async function sendPrivateMessage(
|
||||
/** When set, reply into this group's temp session instead of friend c2c. */
|
||||
tempGroupId?: number,
|
||||
/** Reports each actual friend message as soon as its authoritative receipt arrives. */
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<MessageSendResult> {
|
||||
// A temp-session reply is only allowed into a session the peer opened.
|
||||
const isTempReply = tempGroupId !== undefined && ref.tempSessions.has(userId, tempGroupId);
|
||||
@@ -1030,10 +970,10 @@ export async function sendPrivateMessage(
|
||||
}
|
||||
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
resolveReplySequence: async (replyMessageId) => {
|
||||
return await ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
resolveReplyMeta: async (replyMessageId) => {
|
||||
// Prefer the cached event (it carries the REAL sender). When only
|
||||
// meta exists — typically because the message we're replying to was
|
||||
// sent by the bot itself and never round-tripped through dispatch
|
||||
@@ -1041,7 +981,7 @@ export async function sendPrivateMessage(
|
||||
// selfId. The previous code used `meta.targetId` here, which is the
|
||||
// conversation PEER and shows the wrong "回复 @某人" in QQ for any
|
||||
// self-reply.
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
const event = await ref.messageStore.findEvent(replyMessageId);
|
||||
|
||||
if (event) {
|
||||
const senderUin =
|
||||
@@ -1052,7 +992,7 @@ export async function sendPrivateMessage(
|
||||
typeof event.time === 'number'
|
||||
? event.time
|
||||
: parseInt(String(event.time || '0'), 10);
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
return {
|
||||
senderUin,
|
||||
time,
|
||||
@@ -1062,7 +1002,7 @@ export async function sendPrivateMessage(
|
||||
};
|
||||
}
|
||||
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
|
||||
if (meta) {
|
||||
return {
|
||||
@@ -1209,7 +1149,7 @@ export async function sendPrivateMessage(
|
||||
lastResult = result;
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1346,17 +1286,17 @@ export async function sendGroupMessage(
|
||||
}
|
||||
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
resolveReplySequence: async (replyMessageId) => {
|
||||
return await ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
resolveReplyMeta: async (replyMessageId) => {
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
|
||||
if (!meta || !meta.isGroup || meta.targetId !== groupId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
const event = await ref.messageStore.findEvent(replyMessageId);
|
||||
|
||||
if (event) {
|
||||
return {
|
||||
@@ -1527,7 +1467,7 @@ export async function sendPrivateForwardMessage(
|
||||
userId: number,
|
||||
messages: JsonValue,
|
||||
meta?: ForwardPreviewMeta,
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages, { userId });
|
||||
// userId is plumbed through so inner image/record/video can be uploaded
|
||||
@@ -1546,7 +1486,7 @@ export async function sendPrivateForwardMessage(
|
||||
);
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
|
||||
return { messageId: result.messageId, forwardId };
|
||||
@@ -1577,13 +1517,13 @@ export async function forwardSingleMessage(
|
||||
ref: OneBotInstanceContext,
|
||||
messageId: number,
|
||||
target: { groupId?: number; userId?: number },
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<{ messageId: number }> {
|
||||
if (!target.groupId && !target.userId) {
|
||||
throw new Error('forward target group_id or user_id is required');
|
||||
}
|
||||
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new Error(`message not found: ${messageId}`);
|
||||
@@ -1599,7 +1539,7 @@ export async function forwardSingleMessage(
|
||||
|
||||
const elements = await prepareSingleForwardElements(
|
||||
ref,
|
||||
restoreHistoricalMedia(ref, parsed, messageId),
|
||||
await restoreHistoricalMedia(ref, parsed, messageId),
|
||||
target,
|
||||
);
|
||||
|
||||
@@ -1628,7 +1568,7 @@ export async function forwardSingleMessage(
|
||||
messageIdOut = result.messageId;
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1644,7 +1584,7 @@ async function prepareSingleForwardElements(
|
||||
|
||||
for (const element of elements) {
|
||||
if (element.type !== 'forward') {
|
||||
out.push(isMessageMedia(element) ? element : enrichForForward(ref, element));
|
||||
out.push(isMessageMedia(element) ? element : await enrichForForward(ref, element));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1710,15 +1650,30 @@ async function expandForwardNodeForTarget(
|
||||
target: { groupId?: number; userId?: number },
|
||||
depth: number,
|
||||
): Promise<ForwardNodePayload> {
|
||||
const forwards = node.elements.filter(
|
||||
// Fetched nodes already carry protocol media metadata, but their URLs may
|
||||
// lack an rkey (or only be a file UUID). Reuse complete fingerprints in the
|
||||
// target's upload scene, just as historical single-message forwarding does.
|
||||
// Legacy/incomplete images still need the existing byte-source upload path.
|
||||
const preparedElements = await mapWithConcurrency(node.elements, 8, async (element) => {
|
||||
if (!isMessageMedia(element) || !element.md5Hex || !element.sha1Hex) {
|
||||
return element;
|
||||
}
|
||||
|
||||
if (element.type === 'image' && (!element.width || !element.height || !element.picFormat)) {
|
||||
return element;
|
||||
}
|
||||
|
||||
return await enrichForForward(ref, element, element);
|
||||
});
|
||||
const forwards = preparedElements.filter(
|
||||
(element): element is MessageElementOf<'forward'> => element.type === 'forward',
|
||||
);
|
||||
|
||||
if (forwards.length === 0) {
|
||||
return node;
|
||||
return { ...node, elements: preparedElements };
|
||||
}
|
||||
|
||||
if (forwards.length === node.elements.length && forwards.length === 1) {
|
||||
if (forwards.length === preparedElements.length && forwards.length === 1) {
|
||||
const innerId = forwards[0]!.resId.trim();
|
||||
|
||||
if (!innerId) {
|
||||
@@ -1734,7 +1689,7 @@ async function expandForwardNodeForTarget(
|
||||
|
||||
const elements: MessageElement[] = [];
|
||||
|
||||
for (const element of node.elements) {
|
||||
for (const element of preparedElements) {
|
||||
if (element.type !== 'forward') {
|
||||
elements.push(element);
|
||||
continue;
|
||||
@@ -1761,18 +1716,18 @@ async function expandForwardNodeForTarget(
|
||||
return { ...node, elements };
|
||||
}
|
||||
|
||||
function restoreHistoricalMedia(
|
||||
async function restoreHistoricalMedia(
|
||||
ref: OneBotInstanceContext,
|
||||
elements: MessageElement[],
|
||||
messageId: number,
|
||||
): MessageElement[] {
|
||||
): Promise<MessageElement[]> {
|
||||
if (!elements.some(isMessageMedia)) {
|
||||
return elements;
|
||||
}
|
||||
|
||||
const snapshots = ref.messageStore.findMedia(messageId);
|
||||
const snapshots = await ref.messageStore.findMedia(messageId);
|
||||
let index = 0;
|
||||
const restored = elements.map((element) => {
|
||||
const restored = await mapWithConcurrency(elements, 8, async (element) => {
|
||||
if (!isMessageMedia(element)) {
|
||||
return element;
|
||||
}
|
||||
@@ -1783,7 +1738,7 @@ function restoreHistoricalMedia(
|
||||
throw new Error(`historical media metadata does not match message ${messageId}`);
|
||||
}
|
||||
|
||||
return enrichForForward(ref, element, snapshot);
|
||||
return await enrichForForward(ref, element, snapshot);
|
||||
});
|
||||
|
||||
if (snapshots && index !== snapshots.length) {
|
||||
@@ -1793,11 +1748,11 @@ function restoreHistoricalMedia(
|
||||
return restored;
|
||||
}
|
||||
|
||||
function enrichForForward(
|
||||
async function enrichForForward(
|
||||
ref: OneBotInstanceContext,
|
||||
element: MessageElement,
|
||||
snapshot?: MessageMedia,
|
||||
): MessageElement {
|
||||
): Promise<MessageElement> {
|
||||
if (element.type === 'forward') {
|
||||
throw new Error('merged forward must be regenerated for the target chat');
|
||||
}
|
||||
@@ -1833,7 +1788,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'image') {
|
||||
const cached =
|
||||
snapshot?.type === 'image' ? snapshot : ref.mediaStore.findImage(lookupKey, 'legacy');
|
||||
snapshot?.type === 'image'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findImage(lookupKey, 'legacy');
|
||||
|
||||
if (
|
||||
!cached ||
|
||||
@@ -1866,7 +1823,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'record') {
|
||||
const cached =
|
||||
snapshot?.type === 'record' ? snapshot : ref.mediaStore.findRecord(lookupKey, 'legacy');
|
||||
snapshot?.type === 'record'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findRecord(lookupKey, 'legacy');
|
||||
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
|
||||
throw new Error(
|
||||
@@ -1890,7 +1849,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'video') {
|
||||
const cached =
|
||||
snapshot?.type === 'video' ? snapshot : ref.mediaStore.findVideo(lookupKey, 'legacy');
|
||||
snapshot?.type === 'video'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findVideo(lookupKey, 'legacy');
|
||||
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
|
||||
throw new Error(
|
||||
@@ -1939,6 +1900,7 @@ export async function getForwardMessage(
|
||||
node.elements,
|
||||
isGroup,
|
||||
sessionId,
|
||||
{ includeReplyContent: true },
|
||||
);
|
||||
|
||||
const sender: JsonObject = {
|
||||
@@ -1966,7 +1928,7 @@ export async function getForwardMessage(
|
||||
raw_message: '',
|
||||
font: 14,
|
||||
sub_type: isGroup ? 'normal' : 'friend',
|
||||
message: segments as unknown as JsonValue,
|
||||
message: segments,
|
||||
message_format: 'array',
|
||||
post_type: 'message',
|
||||
};
|
||||
@@ -2111,7 +2073,7 @@ function isNestedNodeArray(value: JsonValue): boolean {
|
||||
for (const item of value) {
|
||||
const seg = asJsonObject(item);
|
||||
|
||||
if (!seg || String(seg.type ?? '') !== 'node') {
|
||||
if (!seg || seg.type !== 'node') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2119,7 +2081,13 @@ function isNestedNodeArray(value: JsonValue): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function assertForwardNodeMetadata(nodeData: JsonObject, index: number): void {
|
||||
type ForwardNodeData = JsonObject &
|
||||
Pick<ForwardNodePayload, 'news' | 'title' | 'source' | 'summary' | 'prompt'>;
|
||||
|
||||
function assertForwardNodeMetadata(
|
||||
nodeData: JsonObject,
|
||||
index: number,
|
||||
): asserts nodeData is ForwardNodeData {
|
||||
for (const [field, value] of Object.entries(nodeData)) {
|
||||
if (field === 'content' || field === 'message') {
|
||||
continue;
|
||||
@@ -2190,11 +2158,11 @@ function isForwardNewsArray(value: JsonValue): value is Array<{ text: string }>
|
||||
return true;
|
||||
}
|
||||
|
||||
function assertForwardMessageInputPolicies(
|
||||
async function assertForwardMessageInputPolicies(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
depth = 0,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
if (!Array.isArray(messages) || depth >= MAX_FORWARD_DEPTH) {
|
||||
return;
|
||||
}
|
||||
@@ -2217,11 +2185,11 @@ function assertForwardMessageInputPolicies(
|
||||
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
|
||||
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (event) {
|
||||
assertOutboundMessageInput(
|
||||
(event.message ?? event.raw_message ?? '') as JsonValue,
|
||||
event.message ?? event.raw_message ?? '',
|
||||
false,
|
||||
'forward',
|
||||
);
|
||||
@@ -2230,10 +2198,10 @@ function assertForwardMessageInputPolicies(
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
const content = nodeData.content ?? nodeData.message ?? '';
|
||||
|
||||
if (isNestedNodeArray(content)) {
|
||||
assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||
await assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||
} else {
|
||||
assertOutboundMessageInput(content, false, 'forward');
|
||||
}
|
||||
@@ -2323,7 +2291,7 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
assertForwardNodeMetadata(nodeData, index);
|
||||
return { segment, nodeData };
|
||||
return nodeData;
|
||||
}
|
||||
|
||||
// Preserve the existing bare-node compatibility form, but require it to
|
||||
@@ -2338,22 +2306,22 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
assertForwardNodeMetadata(segment, index);
|
||||
return { segment, nodeData: segment };
|
||||
return segment;
|
||||
});
|
||||
|
||||
// Scan the complete raw tree before parsing any earlier node. Some segment
|
||||
// codecs perform identity lookups or HTTP signing, so discovering an
|
||||
// unsupported message combination during the normal loop would already be
|
||||
// too late.
|
||||
assertForwardMessageInputPolicies(ref, messages, depth);
|
||||
await assertForwardMessageInputPolicies(ref, messages, depth);
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
|
||||
for (const { nodeData } of prepared) {
|
||||
for (const nodeData of prepared) {
|
||||
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
|
||||
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new MessageElementValidationError(
|
||||
@@ -2385,10 +2353,15 @@ async function parseForwardNodes(
|
||||
);
|
||||
}
|
||||
|
||||
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||
const elements = restoreHistoricalMedia(
|
||||
const content = event.message ?? event.raw_message ?? '';
|
||||
const elements = await restoreHistoricalMedia(
|
||||
ref,
|
||||
await parseMessage(content, false),
|
||||
await parseMessage(content, false, {
|
||||
forwardReply: {
|
||||
senderUin: userUin,
|
||||
time: toPositiveInt(event.time) || undefined,
|
||||
},
|
||||
}),
|
||||
messageId,
|
||||
);
|
||||
|
||||
@@ -2424,7 +2397,10 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
const content = nodeData.content ?? nodeData.message ?? '';
|
||||
// Preserve the node-time policy for both the node and its custom quotes.
|
||||
const nodeTime = toPositiveInt(nodeData.time);
|
||||
const time = nodeTime > 0 && nodeTime < 0xffffffff ? nodeTime : undefined;
|
||||
|
||||
let elements: MessageElement[];
|
||||
let innerForward: ForwardNodePayload[] | undefined;
|
||||
@@ -2455,7 +2431,9 @@ async function parseForwardNodes(
|
||||
// uuid in hand.
|
||||
elements = [];
|
||||
} else {
|
||||
elements = await parseMessage(content, false);
|
||||
elements = await parseMessage(content, false, {
|
||||
forwardReply: { senderUin: userUin, time },
|
||||
});
|
||||
}
|
||||
|
||||
if (!innerForward && elements.length === 0) {
|
||||
@@ -2464,41 +2442,18 @@ async function parseForwardNodes(
|
||||
|
||||
const node: ForwardNodePayload = { userUin, nickname, elements };
|
||||
|
||||
// Forward optional preview news lines (OneBot `data.news`) onto the
|
||||
// payload so nested-forward bubble previews can prefer caller-supplied
|
||||
// lines over auto-generated ones. Only accepted when the array shape
|
||||
// is valid (already asserted by assertForwardNodeMetadata).
|
||||
if (isForwardNewsArray(nodeData.news)) {
|
||||
if (nodeData.news !== undefined) {
|
||||
node.news = nodeData.news.map((item) => ({ text: item.text }));
|
||||
}
|
||||
|
||||
// Forward optional OneBot bubble-preview metadata so nested-forward
|
||||
// cards can prefer caller-supplied titles/source/summary/prompt over
|
||||
// auto-derived ones (types already asserted above).
|
||||
if (nodeData.title !== undefined && typeof nodeData.title === 'string') {
|
||||
node.title = nodeData.title;
|
||||
for (const field of ['title', 'source', 'summary', 'prompt'] as const) {
|
||||
if (nodeData[field] !== undefined) {
|
||||
node[field] = nodeData[field];
|
||||
}
|
||||
}
|
||||
|
||||
if (nodeData.source !== undefined && typeof nodeData.source === 'string') {
|
||||
node.source = nodeData.source;
|
||||
}
|
||||
|
||||
if (nodeData.summary !== undefined && typeof nodeData.summary === 'string') {
|
||||
node.summary = nodeData.summary;
|
||||
}
|
||||
|
||||
if (nodeData.prompt !== undefined && typeof nodeData.prompt === 'string') {
|
||||
node.prompt = nodeData.prompt;
|
||||
}
|
||||
|
||||
// Honour an explicit per-node display time (OneBot `data.time`, unix
|
||||
// seconds) so a custom forward can set/back-date each node's timestamp
|
||||
// (#209). The wire field is uint32, so reject a millisecond value or any
|
||||
// out-of-range input (it would overflow/throw) and fall back to now.
|
||||
const nodeTime = toPositiveInt(nodeData.time);
|
||||
|
||||
if (nodeTime > 0 && nodeTime < 0xffffffff) {
|
||||
node.time = nodeTime;
|
||||
if (time !== undefined) {
|
||||
node.time = time;
|
||||
}
|
||||
|
||||
if (innerForward) {
|
||||
|
||||
@@ -1,56 +1,61 @@
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import { SqliteDatabase, type SqliteStatement } from '@snowluma/sqlite';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
|
||||
export class ReactionStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtUpsert: StatementSync;
|
||||
private readonly stmtRemove: StatementSync;
|
||||
private readonly stmtList: StatementSync;
|
||||
private readonly stmtCount: StatementSync;
|
||||
private readonly stmtCountByEmoji: StatementSync;
|
||||
private readonly db: SqliteDatabase;
|
||||
private stmtUpsert!: SqliteStatement;
|
||||
private stmtRemove!: SqliteStatement;
|
||||
private stmtList!: SqliteStatement;
|
||||
private stmtCount!: SqliteStatement;
|
||||
private stmtCountByEmoji!: SqliteStatement;
|
||||
|
||||
readonly initialization: Promise<void>;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
this.db = openSqliteDb(dbPath);
|
||||
this.initSchema();
|
||||
this.initialization = this.db.serial(async () => {
|
||||
await this.initSchema();
|
||||
|
||||
this.stmtUpsert = this.db.prepare(
|
||||
`INSERT INTO reactions
|
||||
(group_id, msg_seq, emoji_id, emoji_type, operator_uin, operator_uid, set_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(group_id, msg_seq, emoji_id, operator_uin) DO UPDATE SET
|
||||
emoji_type = excluded.emoji_type,
|
||||
operator_uid = excluded.operator_uid,
|
||||
set_at = excluded.set_at`,
|
||||
);
|
||||
this.stmtUpsert = this.db.prepare(
|
||||
`INSERT INTO reactions
|
||||
(group_id, msg_seq, emoji_id, emoji_type, operator_uin, operator_uid, set_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(group_id, msg_seq, emoji_id, operator_uin) DO UPDATE SET
|
||||
emoji_type = excluded.emoji_type,
|
||||
operator_uid = excluded.operator_uid,
|
||||
set_at = excluded.set_at`,
|
||||
);
|
||||
|
||||
this.stmtRemove = this.db.prepare(
|
||||
`DELETE FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ? AND operator_uin = ?`,
|
||||
);
|
||||
this.stmtRemove = this.db.prepare(
|
||||
`DELETE FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ? AND operator_uin = ?`,
|
||||
);
|
||||
|
||||
this.stmtList = this.db.prepare(
|
||||
`SELECT operator_uin, operator_uid, set_at
|
||||
FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?
|
||||
ORDER BY set_at ASC
|
||||
LIMIT ? OFFSET ?`,
|
||||
);
|
||||
this.stmtList = this.db.prepare(
|
||||
`SELECT operator_uin, operator_uid, set_at
|
||||
FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?
|
||||
ORDER BY set_at ASC
|
||||
LIMIT ? OFFSET ?`,
|
||||
);
|
||||
|
||||
this.stmtCount = this.db.prepare(
|
||||
`SELECT COUNT(*) AS n FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?`,
|
||||
);
|
||||
this.stmtCount = this.db.prepare(
|
||||
`SELECT COUNT(*) AS n FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?`,
|
||||
);
|
||||
|
||||
this.stmtCountByEmoji = this.db.prepare(
|
||||
`SELECT emoji_id, emoji_type, COUNT(*) AS n, MAX(set_at) AS last_at
|
||||
FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ?
|
||||
GROUP BY emoji_id`,
|
||||
);
|
||||
this.stmtCountByEmoji = this.db.prepare(
|
||||
`SELECT emoji_id, emoji_type, COUNT(*) AS n, MAX(set_at) AS last_at
|
||||
FROM reactions
|
||||
WHERE group_id = ? AND msg_seq = ?
|
||||
GROUP BY emoji_id`,
|
||||
);
|
||||
});
|
||||
void this.initialization.catch(() => undefined);
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db.exec(`
|
||||
private async initSchema(): Promise<void> {
|
||||
await this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS reactions (
|
||||
group_id INTEGER NOT NULL,
|
||||
msg_seq INTEGER NOT NULL,
|
||||
@@ -66,7 +71,7 @@ export class ReactionStore {
|
||||
`);
|
||||
}
|
||||
|
||||
recordAdd(
|
||||
async recordAdd(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
emojiId: string,
|
||||
@@ -74,68 +79,100 @@ export class ReactionStore {
|
||||
operatorUin: number,
|
||||
operatorUid: string,
|
||||
setAt: number,
|
||||
): void {
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
|
||||
return;
|
||||
}
|
||||
): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
|
||||
this.stmtUpsert.run(groupId, msgSeq, emojiId, emojiType, operatorUin, operatorUid, setAt);
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.stmtUpsert.run(
|
||||
groupId,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
emojiType,
|
||||
operatorUin,
|
||||
operatorUid,
|
||||
setAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
recordRemove(groupId: number, msgSeq: number, emojiId: string, operatorUin: number): void {
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
|
||||
return;
|
||||
}
|
||||
async recordRemove(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
emojiId: string,
|
||||
operatorUin: number,
|
||||
): Promise<void> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
|
||||
this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin);
|
||||
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin);
|
||||
});
|
||||
}
|
||||
|
||||
listUsers(
|
||||
async listUsers(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
emojiId: string,
|
||||
limit = 20,
|
||||
offset = 0,
|
||||
): Array<{ operatorUin: number; operatorUid: string; setAt: number }> {
|
||||
const rows = this.stmtList.all(
|
||||
groupId,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
Math.max(1, Math.min(limit, 500)),
|
||||
Math.max(0, offset),
|
||||
) as Array<{ operator_uin: number; operator_uid: string; set_at: number }>;
|
||||
return rows.map((r) => ({
|
||||
operatorUin: r.operator_uin,
|
||||
operatorUid: r.operator_uid,
|
||||
setAt: r.set_at,
|
||||
}));
|
||||
): Promise<Array<{ operatorUin: number; operatorUid: string; setAt: number }>> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const rows = (await this.stmtList.all(
|
||||
groupId,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
Math.max(1, Math.min(limit, 500)),
|
||||
Math.max(0, offset),
|
||||
)) as Array<{ operator_uin: number; operator_uid: string; set_at: number }>;
|
||||
return rows.map((r) => ({
|
||||
operatorUin: r.operator_uin,
|
||||
operatorUid: r.operator_uid,
|
||||
setAt: r.set_at,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
countUsers(groupId: number, msgSeq: number, emojiId: string): number {
|
||||
const row = this.stmtCount.get(groupId, msgSeq, emojiId) as { n: number } | undefined;
|
||||
return row?.n ?? 0;
|
||||
async countUsers(groupId: number, msgSeq: number, emojiId: string): Promise<number> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const row = (await this.stmtCount.get(groupId, msgSeq, emojiId)) as
|
||||
{ n: number } | undefined;
|
||||
return row?.n ?? 0;
|
||||
});
|
||||
}
|
||||
|
||||
/** Summary of all cached reactions on a message, grouped by emoji. */
|
||||
summarizeMessage(
|
||||
async summarizeMessage(
|
||||
groupId: number,
|
||||
msgSeq: number,
|
||||
): Array<{ emojiId: string; emojiType: number; count: number; lastSetAt: number }> {
|
||||
const rows = this.stmtCountByEmoji.all(groupId, msgSeq) as Array<{
|
||||
emoji_id: string;
|
||||
emoji_type: number;
|
||||
n: number;
|
||||
last_at: number;
|
||||
}>;
|
||||
return rows.map((r) => ({
|
||||
emojiId: r.emoji_id,
|
||||
emojiType: r.emoji_type,
|
||||
count: r.n,
|
||||
lastSetAt: r.last_at,
|
||||
}));
|
||||
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastSetAt: number }>> {
|
||||
return this.db.serial(async () => {
|
||||
await this.initialization;
|
||||
const rows = (await this.stmtCountByEmoji.all(groupId, msgSeq)) as Array<{
|
||||
emoji_id: string;
|
||||
emoji_type: number;
|
||||
n: number;
|
||||
last_at: number;
|
||||
}>;
|
||||
return rows.map((r) => ({
|
||||
emojiId: r.emoji_id,
|
||||
emojiType: r.emoji_type,
|
||||
count: r.n,
|
||||
lastSetAt: r.last_at,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
async close(): Promise<void> {
|
||||
await this.initialization.catch(() => undefined);
|
||||
await this.db.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
|
||||
const labels: Readonly<Record<string, string>> = {
|
||||
image: '[图片]',
|
||||
record: '[语音]',
|
||||
video: '[视频]',
|
||||
file: '[文件]',
|
||||
face: '[表情]',
|
||||
mface: '[表情]',
|
||||
forward: '[聊天记录]',
|
||||
json: '[卡片]',
|
||||
xml: '[卡片]',
|
||||
markdown: '[Markdown]',
|
||||
};
|
||||
|
||||
function previewLabel(type: string): string {
|
||||
if (!Object.hasOwn(labels, type)) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
`message segment "${type}" is not supported in a reply preview`,
|
||||
type,
|
||||
);
|
||||
}
|
||||
|
||||
return labels[type]!;
|
||||
}
|
||||
|
||||
export function assertReplyPreviewType(type: string): void {
|
||||
if (type !== 'text' && type !== 'at') {
|
||||
previewLabel(type);
|
||||
}
|
||||
}
|
||||
|
||||
/** Quotes carry display text; media must not be uploaded again for a preview. */
|
||||
export function elementsToReplyPreview(elements: readonly MessageElement[]): MessageElement[] {
|
||||
const text = elements
|
||||
.map((element) => {
|
||||
if (element.type === 'text') {
|
||||
return element.text;
|
||||
}
|
||||
|
||||
if (element.type === 'at') {
|
||||
return element.targetUin === 0 ? '@全体成员' : `@${element.targetUin}`;
|
||||
}
|
||||
|
||||
return previewLabel(element.type);
|
||||
})
|
||||
.join('');
|
||||
return [{ type: 'text', text }];
|
||||
}
|
||||
|
||||
export function replyPreviewElements(message: unknown): MessageElement[] {
|
||||
if (!Array.isArray(message)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
|
||||
for (const segment of message) {
|
||||
if (!segment || typeof segment !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = segment.data;
|
||||
|
||||
if (!data || typeof data !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segment.type === 'text' && typeof data.text === 'string') {
|
||||
parts.push(data.text);
|
||||
} else if (segment.type === 'at') {
|
||||
parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
|
||||
} else if (typeof segment.type === 'string' && Object.hasOwn(labels, segment.type)) {
|
||||
parts.push(labels[segment.type]!);
|
||||
}
|
||||
}
|
||||
|
||||
const text = parts.join('');
|
||||
return text ? [{ type: 'text', text }] : [];
|
||||
}
|
||||
@@ -1,22 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { SqliteDatabase } from '@snowluma/sqlite';
|
||||
|
||||
/**
|
||||
* Open a SQLite database with the store-wide defaults: ensure the parent
|
||||
* directory exists, then open with WAL journaling + NORMAL synchronous — the
|
||||
* durability/throughput balance the message / media / reaction stores all
|
||||
* want. The caller owns schema init and any path munging.
|
||||
*
|
||||
* Concentrates the bootstrap each store previously hand-copied verbatim, so a
|
||||
* PRAGMA / journal-mode / busy-timeout change lands in one place instead of
|
||||
* three.
|
||||
*/
|
||||
export function openSqliteDb(dbPath: string): DatabaseSync {
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA synchronous = NORMAL');
|
||||
db.exec('PRAGMA busy_timeout = 1000');
|
||||
return db;
|
||||
/** Opens asynchronously with the shared WAL, durability and busy-timeout defaults. */
|
||||
export function openSqliteDb(dbPath: string): SqliteDatabase {
|
||||
return new SqliteDatabase(dbPath);
|
||||
}
|
||||
@@ -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