feat: adopt async SQLite and improve messaging and runtime diagnostics

This commit is contained in:
手瓜一十雪 committed 2026-10-12 15:44:55 +08:00
1 parent effeb66554
commit e699351f90
171 files changed
+5424 -3176

No files matched your search

+4 -4
View File
@@ -21,7 +21,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -48,7 +48,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -69,7 +69,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -90,7 +90,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
+3 -3
View File
@@ -72,7 +72,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -115,7 +115,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -148,7 +148,7 @@ jobs:
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 24+
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
+4 -4
View File
@@ -18,7 +18,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -64,7 +64,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -94,7 +94,7 @@ jobs:
# Naming convention:
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 24+
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
@@ -161,7 +161,7 @@ jobs:
## 选择下载
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 22.13+;23 系需 23.4+) |
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 24+) |
| --- | --- | --- |
| Windows x64 | \`SnowLuma-${tag}-win-x64.zip\` | \`SnowLuma-${tag}-win-x64-lite.zip\` |
| Linux x64 | \`SnowLuma-${tag}-linux-x64.tar.gz\` | \`SnowLuma-${tag}-linux-x64-lite.tar.gz\` |
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
+1 -1
View File
@@ -1 +1 @@
22.13.0
24.21.0
+1
View File
@@ -20,6 +20,7 @@ This is a pnpm workspace. Package ownership matters more than directory names:
| `packages/protocol` | Packet decoding, typed QQ events, identity resolution, protocol requests and media transfers |
| `packages/onebot` | Action validation and dispatch, event conversion, message storage, HTTP/WebSocket adapters |
| `packages/common` | Shared logging, configuration and utilities without business dependencies |
| `packages/sqlite` | Asynchronous SQLite facade, native loader, prebuild selection and Vite release assets |
| `packages/proto-defs` | Typed protocol schemas |
| `packages/proton` | Compile-time protobuf codecs and build integration |
| `packages/websocket` | WebSocket implementation and native binding integration |
+12 -5
View File
@@ -35,8 +35,15 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
| 路径 | 作用 |
| --- | --- |
| `packages/core` | 核心运行时:协议、桥接、OneBot 适配、WebUI 服务端 |
| `packages/core` | 应用入口、账号级 Bridge 编排、WebUI 服务端和发行构建 |
| `packages/bridge` | QQ 进程发现、Hook 会话和原生传输生命周期 |
| `packages/protocol` | QQ 数据包解码、身份解析、协议请求和媒体传输 |
| `packages/onebot` | OneBot 动作、事件转换、消息存储和传输适配 |
| `packages/common` | 日志、配置和共享工具 |
| `packages/proto-defs`、`packages/proton` | 协议结构定义、编译期 protobuf 编解码和构建集成 |
| `packages/sdk` | 面向第三方开发者的 SDK,会发布到 npm |
| `packages/mcp` | MCP 服务端和生成的动作目录 |
| `packages/ui` | 发布到 npm 的共享 UI 组件 |
| `packages/runtime` | 运行时辅助包 |
| `packages/websocket` | WebSocket 实现 |
| `packages/webui` | 基于 Vite + React 的前端控制台 |
@@ -51,12 +58,12 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
### 系统要求
- **Node.js 22.13+(23 系需 23.4+)**(项目使用默认启用的 `node:sqlite`)
- **pnpm 10.28.0**(项目通过 `packageManager` 与 CI 统一版本)
- **Node.js 24+**
- **pnpm 11.25.0**(项目通过 `packageManager` 与 CI 统一版本)
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
如果系统提供 Corepack,可执行 `corepack enable pnpm`;没有 Corepack 时可执行
`npm install -g pnpm@10.28.0`。进入仓库后,`node --version` 与
`npm install -g pnpm@11.25.0`。进入仓库后,`node --version` 与
`pnpm --version` 应满足上述版本要求,否则安装会直接失败。
### 拉代码、装依赖、跑起来
@@ -177,7 +184,7 @@ git push origin fix/onebot-mention-encoding
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/core/src/onebot/` 下的 `fake-bridge` 类测试。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/onebot/tests/` 中的 Bridge 测试替身。
### 文档
+8
View File
@@ -82,6 +82,14 @@ pnpm test
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
## 媒体读取与归档
`get_msg` 逐个尝试刷新图片、语音和视频的下载地址:获取到新地址就用于本次响应,刷新失败或缺少资源元数据时保留该段原地址,并继续处理其他资源。原地址为空时仍保持为空,单个资源失败不影响整条消息返回。地址更新时同步响应中的 `raw_message`,不改写保存的消息;保留的旧地址仍可能已经过期。
`get_record` 单独向 QQ 获取语音的当前下载地址,资源元数据缺失或远端获取失败时动作返回错误,不使用旧地址或发送时的本地文件兜底。历史记录若没有保存资源引用,无法仅凭文件名恢复下载地址。
SnowLuma 不为这些查询长期保存媒体文件或 Base64 内容,本地保留的是消息及资源元数据;上传、转码仍会使用临时文件。下载地址和 QQ 远端资源都有可用性限制,需要长期归档的消费端应及时下载并自行保存。
## 使用边界与许可
> [!IMPORTANT]
+3 -22
View File
@@ -43,28 +43,9 @@
"typescript": "catalog:",
"typescript-eslint": "^8.58.2"
},
"pnpm": {
"peerDependencyRules": {
"allowedVersions": {
"eslint-plugin-react-hooks>eslint": "10"
}
},
"overrides": {
"esbuild@<0.28.1": "^0.28.1",
"@babel/core@<7.29.6": "^7.29.6",
"qs@<=6.15.3": "^6.16.0",
"fast-uri@<3.1.6": "^3.1.6",
"@hono/node-server@<1.19.15": "^1.19.15",
"hono": "~4.12.34",
"postcss@<=8.5.22": "^8.5.23",
"ip-address@<=10.3.0": "^10.3.1",
"body-parser@<2.3.0": "^2.3.0",
"brace-expansion@<5.0.7": "^5.0.7"
}
},
"packageManager": "pnpm@10.28.0",
"packageManager": "pnpm@11.25.0",
"engines": {
"node": "^22.13.0 || >=23.4.0",
"pnpm": "10.28.0"
"node": ">=24",
"pnpm": "11.25.0"
}
}
+3
View File
@@ -61,5 +61,8 @@
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
},
"engines": {
"node": ">=24"
}
}
+1
View File
@@ -2,4 +2,5 @@ export {
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
type HookProcessStatus, type QqPortLoginInfo
} from './hook-manager';
export { getRuntimeIntegrity, hasLowProcessIntegrity, type RuntimeIntegrity } from './runtime-integrity';
+1
View File
@@ -14,6 +14,7 @@ export interface ManualMapHandle {
}
interface NativeHookAddon {
getRuntimeIntegrity?(): unknown;
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
+7 -9
View File
@@ -24,8 +24,7 @@ const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as con
// logged-in client surfaces roughly this many processes. When no usable
// probe port is found, a count BELOW this implies the target PID is still at
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
// unrelated `qq` processes), so we fall through to deep-link probing rather
// than guess "logged out".
// unrelated `qq` processes), so the passive probe returns no conclusion.
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
export interface QqPortLoginInfo {
@@ -52,7 +51,7 @@ interface PtloginUin {
* the port could not be reached / the body was not a usable pt_get_uins
* response (connect refused, timeout, unparseable). Callers MUST distinguish
* the two: `[]` feeds the logged-in/out decision, `null` means "network
* problem, no answer" and should fall through to the deep-link fallback.
* problem, no answer". Neither outcome triggers interactive probing.
*/
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
return new Promise((resolve) => {
@@ -91,13 +90,13 @@ async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin
});
}
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | null> {
const useHttps = port % 2 !== 0;
const res1 = await fetchPtlogin(port, useHttps);
const res2 = await fetchPtlogin(port, useHttps);
if (res1 === null && res2 === null) return 'fallback';
if (res1 === null && res2 === null) return null;
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
@@ -112,10 +111,9 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
};
}
return 'fallback';
return null;
}
async function getQqProcessCount(): Promise<number> {
try {
if (process.platform === 'win32') {
@@ -203,7 +201,7 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
if (ptPortsToTry.length > 0) {
for (const port of ptPortsToTry) {
const ptResult = await tryPtloginMethod(port);
if (ptResult !== 'fallback') {
if (ptResult !== null) {
return ptResult;
}
}
@@ -212,7 +210,7 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', ports.length, totalPids);
return {
port: ports[0] || 0,
port: ports[0],
uin: '',
identityKnown: false,
};
+74
View File
@@ -0,0 +1,74 @@
import { getNativeHookAddon, getNativeHookLoadError } from './injector';
export interface IntegrityReadError {
status: 'error';
operation: string;
code: number;
}
export interface NativeRuntimeIntegrity {
pid: number;
executablePath: string | null;
process: { status: 'ok'; rid: number } | IntegrityReadError;
file: {
status: 'ok';
label: { rid: number; inherited: boolean; policy: number } | null;
} | IntegrityReadError;
}
export type RuntimeIntegrity =
| { status: 'unsupported' }
| { status: 'unavailable'; error: string }
| ({ status: 'available' } & NativeRuntimeIntegrity);
/** File labels can change after startup; only the actual token decides the warning. */
export function hasLowProcessIntegrity(integrity: RuntimeIntegrity): boolean {
return integrity.status === 'available'
&& integrity.process.status === 'ok'
&& integrity.process.rid < 8192;
}
function record(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function uint32(value: unknown): value is number {
return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff;
}
function readError(value: Record<string, unknown>): boolean {
return value.status === 'error' && typeof value.operation === 'string' && uint32(value.code);
}
function isNativeRuntimeIntegrity(value: unknown): value is NativeRuntimeIntegrity {
if (!record(value) || value.pid !== process.pid ||
!(typeof value.executablePath === 'string' || value.executablePath === null) ||
!record(value.process) || !record(value.file)) return false;
if (!(readError(value.process) || (value.process.status === 'ok' && uint32(value.process.rid)))) return false;
const file = value.file;
return readError(file) || (file.status === 'ok' && (file.label === null || (
record(file.label) && uint32(file.label.rid) && typeof file.label.inherited === 'boolean' && uint32(file.label.policy)
)));
}
let cached: RuntimeIntegrity | undefined;
/** One startup snapshot, shared by the startup log and the WebUI warning. */
export function getRuntimeIntegrity(): RuntimeIntegrity {
if (process.platform !== 'win32') return { status: 'unsupported' };
if (cached) return cached;
try {
const addon = getNativeHookAddon();
if (!addon) throw new Error(getNativeHookLoadError() ?? '原生组件不可用');
if (typeof addon.getRuntimeIntegrity !== 'function') {
throw new Error('当前原生组件不支持完整性诊断,请更新原生组件');
}
const result = addon.getRuntimeIntegrity();
if (!isNativeRuntimeIntegrity(result)) throw new Error('原生完整性诊断返回了无效数据');
cached = { status: 'available', pid: result.pid, executablePath: result.executablePath,
process: result.process, file: result.file };
} catch (error) {
cached = { status: 'unavailable', error: error instanceof Error ? error.message : String(error) };
}
return cached;
}
+5 -3
View File
@@ -35,7 +35,7 @@ describe('probeQqLoginInfo — bounded execution', () => {
callback(null, { stdout: '', stderr: '' });
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '1\n', stderr: '' });
callback(null, { stdout: process.platform === 'win32' ? 'QQ.exe 4242 Console 1 1234 K\n' : '1\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
@@ -49,12 +49,14 @@ describe('probeQqLoginInfo — bounded execution', () => {
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
stdout: process.platform === 'win32'
? 'TCP 127.0.0.1:9218 0.0.0.0:0 LISTENING 4242\n'
: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
stderr: '',
});
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '8\n', stderr: '' });
callback(null, { stdout: process.platform === 'win32' ? 'QQ.exe 4242 Console 1 1234 K\n'.repeat(8) : '8\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { hasLowProcessIntegrity, type NativeRuntimeIntegrity } from '../src/runtime-integrity';
const native = vi.hoisted(() => ({ load: vi.fn(), error: vi.fn() }));
vi.mock('../src/injector', () => ({ getNativeHookAddon: native.load, getNativeHookLoadError: native.error }));
const platform = process.platform;
const sample = (): NativeRuntimeIntegrity => ({
pid: process.pid, executablePath: process.execPath,
process: { status: 'ok', rid: 8192 },
file: { status: 'ok', label: null },
});
beforeEach(() => {
vi.resetModules();
vi.resetAllMocks();
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
});
describe('runtime integrity diagnostics', () => {
it('warns only for a successfully read process token below Medium', () => {
const available = { ...sample(), status: 'available' as const };
for (const rid of [0, 4096]) {
expect(hasLowProcessIntegrity({ ...available, process: { status: 'ok', rid } })).toBe(true);
}
for (const rid of [8192, 8448, 12288, 16384]) {
expect(hasLowProcessIntegrity({ ...available, process: { status: 'ok', rid },
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } } })).toBe(false);
}
expect(hasLowProcessIntegrity({ status: 'unsupported' })).toBe(false);
expect(hasLowProcessIntegrity({ status: 'unavailable', error: 'unavailable' })).toBe(false);
expect(hasLowProcessIntegrity({ ...available,
process: { status: 'error', operation: 'OpenProcessToken', code: 5 } })).toBe(false);
});
it('keeps one startup snapshot for logging and all WebUI polls', async () => {
const read = vi.fn().mockReturnValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrity: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
const first = getRuntimeIntegrity();
expect(first).toMatchObject({ status: 'available', process: { rid: 8192 }, file: { label: null } });
read.mockReturnValue({ ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } } });
expect(getRuntimeIntegrity()).toBe(first);
expect(read).toHaveBeenCalledTimes(1);
});
it.each(['process', 'file'])('retains %s query errors and the other successful result', async (field) => {
native.load.mockReturnValue({ getRuntimeIntegrity: () => ({
...sample(), [field]: { status: 'error', operation: 'Win32Query', code: 5 },
}) });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ status: 'available', [field]: { status: 'error', operation: 'Win32Query', code: 5 } });
});
it('reports old addons as unavailable rather than Medium', async () => {
native.load.mockReturnValue({});
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: expect.stringContaining('不支持') });
});
it('retains the loader error for the startup log', async () => {
native.load.mockReturnValue(null);
native.error.mockReturnValue('dlopen failed: incompatible binary');
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: 'dlopen failed: incompatible binary' });
});
it.each([
null,
{ ...sample(), pid: process.pid + 1 },
{ ...sample(), process: { status: 'ok', rid: -1 } },
{ ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: 'yes', policy: 1 } } },
])('rejects malformed or wrong-process native results', async (result) => {
native.load.mockReturnValue({ getRuntimeIntegrity: () => result });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: expect.stringContaining('无效数据') });
});
it('preserves thrown errors without repeatedly probing on WebUI polls', async () => {
const read = vi.fn().mockImplementationOnce(() => { throw new Error('allocation failed'); }).mockReturnValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrity: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: 'allocation failed' });
expect(getRuntimeIntegrity()).toMatchObject({ status: 'unavailable', error: 'allocation failed' });
expect(read).toHaveBeenCalledTimes(1);
});
it('does not load the addon on non-Windows hosts', async () => {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toEqual({ status: 'unsupported' });
expect(native.load).not.toHaveBeenCalled();
});
});
+3
View File
@@ -86,5 +86,8 @@
"@zxcvbn-ts/core": "^4.1.2",
"@zxcvbn-ts/language-common": "^4.1.3",
"@zxcvbn-ts/language-en": "^4.1.1"
},
"engines": {
"node": ">=24"
}
}
+1 -4
View File
@@ -1,5 +1,6 @@
import fs from 'fs';
import path from 'path';
import { isObject } from './coerce';
export interface RuntimeConfig {
webuiPort?: number;
@@ -299,10 +300,6 @@ function parseBoolValue(raw: unknown): boolean | undefined {
return undefined;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isErrnoCode(error: unknown, code: string): boolean {
return error instanceof Error && 'code' in error && error.code === code;
}
+7 -8
View File
@@ -63,14 +63,13 @@ export class SingleFlightCache<K, V> {
const existing = this.inflight.get(key);
if (existing) return existing;
const task = (async () => {
try {
const value = await this.load(key);
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
return value;
} finally {
this.inflight.delete(key);
}
})();
const value = await this.load(key);
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
return value;
})().finally(() => {
// Run after registration even when load throws synchronously.
this.inflight.delete(key);
});
this.inflight.set(key, task);
return task;
}
@@ -128,4 +128,15 @@ describe('SingleFlightCache', () => {
await cache.get('b');
expect(load).toHaveBeenCalledTimes(5);
});
it('allows retry when a loader throws before returning its promise', async () => {
const load = vi.fn<() => Promise<string>>()
.mockImplementationOnce(() => { throw new Error('failed before request'); })
.mockResolvedValue('recovered');
const cache = createSingleFlightCache({ ttlMs: 1000, load });
await expect(cache.get('key')).rejects.toThrow('failed before request');
await expect(cache.get('key')).resolves.toBe('recovered');
expect(load).toHaveBeenCalledTimes(2);
});
});
+5 -1
View File
@@ -60,6 +60,10 @@
"typescript": "catalog:",
"vite": "catalog:",
"vite-plugin-cp": "^6.0.3",
"vitest": "^4.1.4"
"vitest": "^4.1.4",
"@snowluma/sqlite": "workspace:*"
},
"engines": {
"node": ">=24"
}
}
+5 -11
View File
@@ -6,7 +6,6 @@ import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { protobuf_encode } from '@snowluma/proton';
import { promises as fsp } from 'fs';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
@@ -33,8 +32,6 @@ import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
const log = createLogger('GroupFile');
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
@@ -270,7 +267,7 @@ export class GroupFileApi {
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const bridge = this.ctx;
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
// local disk path and stream-hash it — the (up to 4 GiB) file is never
@@ -384,7 +381,7 @@ export class GroupFileApi {
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const bridge = this.ctx;
// Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is
// never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file
// md510MCheckSum in the same single pass.
@@ -624,8 +621,7 @@ export class GroupFileApi {
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
const selfUid = await resolveSelfUid(this.ctx);
void userId;
return GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
}
@@ -667,8 +663,7 @@ export class GroupFileApi {
}
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
const selfUid = await resolveSelfUid(this.ctx);
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
}
@@ -677,8 +672,7 @@ export class GroupFileApi {
}
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
const selfUid = await resolveSelfUid(this.ctx);
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
}
}
+1 -12
View File
@@ -1,15 +1,4 @@
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
return 0;
}
export { toInt } from '@snowluma/protocol/oidb-services/shared';
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
// (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing
+20 -9
View File
@@ -49,6 +49,8 @@ export class Bridge implements BridgeInterface {
private readonly sysMsgDedup_ = new SysMsgDedup();
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposed_ = false;
private disposePromise_: Promise<void> | null = null;
private readonly pendingPackets_ = new Set<Promise<void>>();
private rosterWarmupStarted_ = false;
private rosterWarmupSettled_ = false;
private rosterWarmupResult_: RosterWarmupResult | null = null;
@@ -131,7 +133,8 @@ export class Bridge implements BridgeInterface {
});
}
dispose(): void {
dispose(): Promise<void> {
if (this.disposePromise_) return this.disposePromise_;
this.disposed_ = true;
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
this.pids_.clear();
@@ -140,13 +143,15 @@ export class Bridge implements BridgeInterface {
this.packetClient_ = null;
this.packetClientPid_ = null;
this.onlineClients_ = null;
try {
this.identity.close();
} finally {
// A close failure must remain visible to the caller, but must not leave
// event subscribers attached to a Bridge that Manager already removed.
this.events.clear();
}
this.disposePromise_ = (async () => {
try {
await Promise.allSettled(this.pendingPackets_);
await this.identity.close();
} finally {
this.events.clear();
}
})();
return this.disposePromise_;
}
/** Legacy two-step setter retained for external compatibility. It assigns
@@ -271,7 +276,11 @@ export class Bridge implements BridgeInterface {
}
onPacket(pkt: PacketInfo): Promise<void> {
return this.pipeline.process(pkt);
if (this.disposed_) return Promise.reject(new Error('Bridge is disposed'));
const work = this.identity.initialization.then(() => this.pipeline.process(pkt));
this.pendingPackets_.add(work);
void work.finally(() => this.pendingPackets_.delete(work)).catch(() => undefined);
return work;
}
rememberUploadedFile(meta: UploadedFileMeta): void {
@@ -414,6 +423,8 @@ export class Bridge implements BridgeInterface {
}
private async runRosterWarmup(): Promise<RosterWarmupResult> {
await this.identity.initialization;
if (this.disposed_) return { friendsLoaded: false, groupsLoaded: false };
const uin = this.identity.uin;
const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false;
+25 -2
View File
@@ -23,6 +23,29 @@ const runtimeLog = createLogger('Bridge.Runtime');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
private readonly closingSessions_ = new Map<string, Promise<void>>();
private readonly closeErrors_: unknown[] = [];
/** Hook callbacks remain synchronous; shutdown awaits every detached account. */
async dispose(): Promise<void> {
for (const [uin, session] of this.sessions_) this.closeSession(uin, session.bridge);
this.sessions_.clear();
this.pidToUin_.clear();
await Promise.allSettled(this.closingSessions_.values());
if (this.closeErrors_.length) throw new AggregateError(this.closeErrors_, 'Bridge persistence shutdown failed');
}
private closeSession(uin: string, bridge: Bridge): void {
const previous = this.closingSessions_.get(uin);
const closing = Promise.all([previous, bridge.dispose()]).then(() => undefined);
this.closingSessions_.set(uin, closing);
void closing.then(() => {
if (this.closingSessions_.get(uin) === closing) this.closingSessions_.delete(uin);
}, error => {
this.closeErrors_.push(error);
log.error('identity close failed: UIN=%s err=%s', uin, error instanceof Error ? (error.stack ?? error.message) : String(error));
});
}
private sessionStartedListeners_: SessionStartedCallback[] = [];
private sessionClosedListeners_: SessionClosedCallback[] = [];
@@ -358,7 +381,7 @@ export class BridgeManager {
log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge);
session.bridge.dispose();
this.closeSession(uin, session.bridge);
return true;
}
@@ -366,7 +389,7 @@ export class BridgeManager {
let session = this.sessions_.get(uin);
if (session) return { session, created: false };
const bridge = new Bridge(IdentityService.openForUin(uin));
const bridge = new Bridge(IdentityService.openForUin(uin, 'data', this.closingSessions_.get(uin)));
session = { bridge };
this.sessions_.set(uin, session);
+7 -1
View File
@@ -1,4 +1,4 @@
import { HookManager } from '@snowluma/bridge';
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import {
@@ -20,6 +20,7 @@ import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
import { bindSystemFaceCatalog } from './sys-face-catalog';
import { readAppVersion, startNativeStageSync, tempStagePath } from './native-stage-sync';
import { logRuntimeIntegrity } from './runtime-integrity-log';
const log = createLogger('App');
@@ -49,6 +50,7 @@ async function main() {
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
});
log.info('SnowLuma starting');
logRuntimeIntegrity(getRuntimeIntegrity());
const stopNativeStageSync = startNativeStageSync({
version: readAppVersion(import.meta.url),
dataDir: 'data',
@@ -147,6 +149,10 @@ async function main() {
exitCode = 1;
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
try { await bridgeManager.dispose(); } catch (error) {
exitCode = 1;
log.error('bridge shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
await closeLogger();
process.exit(exitCode);
};
+1 -1
View File
@@ -237,7 +237,7 @@ export class NotificationManager {
event: 'offline' as const,
time: new Date(this.deps.now()).toISOString(),
};
return { ...(await this.deliver(channel, vars)), found: true };
return { ...await this.deliver(channel, vars), found: true };
}
private record(rec: DeliveryRecord): void {
@@ -0,0 +1,35 @@
import { hasLowProcessIntegrity, type RuntimeIntegrity } from '@snowluma/bridge';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('App');
const LEVEL_NAMES: Record<number, string> = {
0: 'Untrusted', 4096: 'Low', 8192: 'Medium', 8448: 'Medium Plus',
12288: 'High', 16384: 'System', 20480: 'Protected Process',
};
function level(rid: number): string {
return `${LEVEL_NAMES[rid] ?? 'Unknown'} (RID=${rid})`;
}
/** Called once by main(), never by WebUI polling or warning dismissal. */
export function logRuntimeIntegrity(integrity: RuntimeIntegrity): void {
if (integrity.status === 'unsupported') return;
if (integrity.status === 'unavailable') {
log.warn('Node integrity: unknown (%s)', integrity.error);
return;
}
const token = integrity.process;
const file = integrity.file;
const tokenText = token.status === 'ok' ? level(token.rid) : `unknown (${token.operation}, Win32=${token.code})`;
const fileText = file.status === 'error' ? `unknown (${file.operation}, Win32=${file.code})`
: file.label ? `${level(file.label.rid)}, inherited=${file.label.inherited}, policy=${file.label.policy}`
: 'unlabeled';
// "token=" is reserved for credentials by the shared log redactor.
const report = `Node integrity: pid=${integrity.pid}, process=${tokenText}; EXE=${fileText}`;
if (token.status === 'error' || file.status === 'error' || hasLowProcessIntegrity(integrity) ||
(file.label && file.label.rid < 8192)) {
log.warn(report);
} else {
log.info(report);
}
}
+2
View File
@@ -1,6 +1,7 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { getRuntimeIntegrity, hasLowProcessIntegrity } from '@snowluma/bridge';
import {
clearManagedLogs,
configureFileTransport,
@@ -1097,6 +1098,7 @@ export async function initWebUI(
},
runtime: {
pid: process.pid,
lowIntegrity: hasLowProcessIntegrity(getRuntimeIntegrity()),
rss: runtimeMemory.rss,
heapTotal: runtimeMemory.heapTotal,
heapUsed: runtimeMemory.heapUsed,
+1 -4
View File
@@ -1,4 +1,5 @@
import { isRealUin } from '@snowluma/common/uin';
import { isObject } from '@snowluma/common/coerce';
import type { Hono } from 'hono';
import {
StorageAccountOnlineError,
@@ -311,7 +312,3 @@ function cleanupFailureItem(
if ('file' in failure) return failure.file;
return failure.item;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+1 -4
View File
@@ -1,3 +1,4 @@
import { isObject } from '@snowluma/common/coerce';
import type {
LogStoragePolicy,
LogStorageStatus,
@@ -306,7 +307,3 @@ function assertPersistedSettings(
throw new Error('persisted log storage settings do not match the requested values');
}
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+1 -4
View File
@@ -4,6 +4,7 @@
// nested `webuiTls.enabled`.
import type { RuntimeConfig } from '@snowluma/common/runtime';
import { isObject } from '@snowluma/common/coerce';
import { checkListenerExposure } from './listener-exposure';
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
@@ -12,10 +13,6 @@ export type CoerceResult =
| { ok: true; patch: SettingsPatch }
| { ok: false; error: string };
function isObject(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
}
export function coerceSettingsPatch(body: unknown): CoerceResult {
if (!isObject(body)) return { ok: false, error: 'body must be an object' };
const patch: SettingsPatch = {};
+1 -1
View File
@@ -119,7 +119,7 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) return { ...base, error: `github ${res.status}` };
const rel = (await res.json()) as GithubRelease;
const rel = await res.json() as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
if (!tag) return { ...base, error: 'no tag' };
const latest = tag.replace(/^v/, '');
@@ -28,13 +28,13 @@ describe('forward metadata through upload and cached reads', () => {
const forward = new ForwardApi(bridge as any);
const ctx = {
selfId: 10001,
bridge: { apis: {
bridge: { identity: { nickname: 'SnowLuma' }, apis: {
forward,
message: { sendGroup: vi.fn(async () => ({
messageId: 1, sequence: 2, clientSequence: 0, random: 3, timestamp: 1700000000,
})) },
} },
messageStore: { findEvent: () => null, findMedia: () => null },
messageStore: { findEvent: () => null, findMedia: () => null, storeEvent: vi.fn() },
cacheMessageMeta: vi.fn(),
converterCtx: {
selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null,
@@ -0,0 +1,131 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { gunzipSync, gzipSync, inflateSync } from 'node:zlib';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import type { LongMsgResult, RecvLongMsgResp, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MessageElement } from '@snowluma/protocol/events';
import { runNtv2Upload } from '@snowluma/protocol/highway/pipeline';
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { ForwardApi } from '../../src/bridge/apis/forward';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { mockBridge } from './_helpers';
// Keep the image uploader, element builder and Proton codecs real. Only the
// network boundaries are faked, including a source URL that needs an rkey.
vi.mock('@snowluma/protocol/highway/pipeline', async importOriginal => ({
...await importOriginal<typeof import('@snowluma/protocol/highway/pipeline')>(),
runNtv2Upload: vi.fn(),
}));
vi.mock('@snowluma/protocol/highway/utils', async importOriginal => ({
...await importOriginal<typeof import('@snowluma/protocol/highway/utils')>(),
loadBinarySource: vi.fn(async () => { throw new Error('source image URL requires an rkey'); }),
}));
const md5Hex = 'ab'.repeat(16);
const sha1Hex = 'cd'.repeat(20);
const sourceInfo: MsgInfo = {
msgInfoBody: [{
index: {
fileUuid: 'source-group-image',
info: {
fileHash: md5Hex, fileSha1: sha1Hex, fileSize: 1234, fileName: 'image.png',
width: 32, height: 24, type: { type: 1, picFormat: 1001 },
},
},
picture: { domain: 'multimedia.nt.qq.com.cn', urlPath: '/download?appid=1407&fileid=source-group-image' },
}],
};
function packetResult(responseData: Uint8Array) {
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(responseData) };
}
function setup(id: string) {
const sourceBody: PushMsgBody = {
responseHead: { fromUin: 20002, fromUid: 'sender-uid', grp: { groupUin: 12345, memberCard: 'alice' } },
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
body: { richText: { elems: [
{ text: { str: 'picture' } },
{ commonElem: { serviceType: 48, businessType: 20, pbElem: protobuf_encode<MsgInfo>(sourceInfo) } },
] } },
};
const sentLongMessages: SendLongMsgReq[] = [];
const bridge = mockBridge({
resolveUserUid: vi.fn(async () => 'self-uid'),
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
if (command.endsWith('SsoRecvLongMsg')) {
return packetResult(protobuf_encode<RecvLongMsgResp>({ result: { payload: gzipSync(
protobuf_encode<LongMsgResult>({ action: [{ actionCommand: 'MultiMsg', actionData: { msgBody: [sourceBody] } }] }),
) } }));
}
expect(command).toMatch(/SsoSendLongMsg$/);
sentLongMessages.push(protobuf_decode<SendLongMsgReq>(bytes));
return packetResult(protobuf_encode<SendLongMsgResp>({ result: { resId: `new-${id}` } }));
}),
});
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const sendPrivate = vi.fn(async (_userId: number, elements: MessageElement[]) => {
const [card] = await buildSendElems(elements);
expect(card?.richMsg?.serviceId).toBe(35);
const xml = inflateSync(card!.richMsg!.template1!.subarray(1)).toString();
expect(xml).toContain(`m_resid="new-${id}"`);
expect(xml).toContain('alice: picture [图片]');
return { messageId: 1, sequence: 2, clientSequence: 3, random: 4, timestamp: 1700000001 };
});
const ctx = {
selfId: 10001,
bridge: { identity: { nickname: 'SnowLuma' }, apis: { forward, message: { sendPrivate } } },
messageStore: { findEvent: () => ({ message: [{ type: 'forward', data: { id } }] }), storeEvent: vi.fn() },
converterCtx: {
selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null,
messageIdResolver: null, mediaSegmentSink: null,
},
cacheMessageMeta: vi.fn(),
dispatchEvent: vi.fn(),
} as unknown as OneBotInstanceContext;
return { api: buildApiContext(ctx), forward, sendPrivate, sentLongMessages, bridge };
}
describe('single merged-forward media (#437)', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(runNtv2Upload).mockImplementation(async params => ({
msgInfo: { msgInfoBody: [{ index: { fileUuid: 'target-private-image', info: params.uploadInfo[0]!.fileInfo } }] },
}));
});
it('reuploads a decoded group image for self-chat without downloading its unsigned source URL', async () => {
const { api, forward, sentLongMessages, bridge } = setup('image-to-self');
await expect(api.forwardSingleMsg(77, { userId: 10001 })).resolves.toHaveProperty('messageId');
expect(loadBinarySource).not.toHaveBeenCalled();
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
expect(runNtv2Upload).toHaveBeenCalledOnce();
expect(vi.mocked(runNtv2Upload).mock.calls[0]![0]).toMatchObject({
isGroup: false, targetIdOrUid: 'self-uid', oidbCmd: 0x11C5,
uploadInfo: [{ fileInfo: { fileHash: md5Hex, fileSha1: sha1Hex, width: 32, height: 24, fileSize: 1234 } }],
uploads: [{ bytes: new Uint8Array(0) }],
});
expect(sentLongMessages).toHaveLength(1);
expect(sentLongMessages[0]!.info?.type).toBe(1);
const body = protobuf_decode<LongMsgResult>(gunzipSync(sentLongMessages[0]!.info!.payload!));
const elems = body.action![0]!.actionData!.msgBody![0]!.body!.richText!.elems!;
expect(elems.find(e => e.commonElem)?.commonElem?.businessType).toBe(10);
const media = protobuf_decode<MsgInfo>(elems.find(e => e.commonElem)!.commonElem!.pbElem!);
expect(media.msgInfoBody?.[0]?.index?.fileUuid).toBe('target-private-image');
expect(elems.find(e => e.notOnlineImage)?.notOnlineImage?.picMd5).toEqual(Buffer.from(md5Hex, 'hex'));
expect((await forward.fetch('image-to-self'))[0]!.elements[1]!.noByteFallback).toBeUndefined();
});
it('does not send a card or upload a long message when target image upload fails', async () => {
vi.mocked(runNtv2Upload).mockRejectedValueOnce(new Error('image fast-upload not available (server requires bytes)'));
const { api, sendPrivate, sentLongMessages } = setup('image-upload-failure');
await expect(api.forwardSingleMsg(77, { userId: 10001 })).rejects.toThrow('image fast-upload not available');
expect(sendPrivate).not.toHaveBeenCalled();
expect(sentLongMessages).toHaveLength(0);
expect(loadBinarySource).not.toHaveBeenCalled();
});
});
+2 -1
View File
@@ -200,6 +200,7 @@ describe('apis/friend', () => {
it('approves a filtered stranger through Identity without requiring a shared roster', async () => {
const identity = new IdentityService('10001', null);
await identity.initialization;
const bridge = mockBridge();
const fetchProfile = vi.fn(async (uin: number) => ({
uin, uid: uin === 10001 ? 'u_self' : 'u_stranger',
@@ -215,7 +216,7 @@ describe('apis/friend', () => {
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ selfUid: 'u_self', targetUid: 'u_stranger' });
} finally {
identity.close();
await identity.close();
}
});
@@ -112,7 +112,7 @@ describe('Bridge group member identity refresh', () => {
seen.push(event);
});
bridge.onPacket(makePacket());
await bridge.onPacket(makePacket());
const event = await waitForEvent(seen);
expect(profileFetches).toEqual([member.uid]);
@@ -120,7 +120,7 @@ describe('Bridge group member identity refresh', () => {
expect(event.userUin).toBe(member.uin);
});
it('remembers UID mappings from realtime request events', () => {
it('remembers UID mappings from realtime request events', async () => {
const bridge = new Bridge(IdentityService.memory(SELF_UIN));
const events: QQEventVariant[] = [
{
@@ -146,7 +146,7 @@ describe('Bridge group member identity refresh', () => {
];
bridge.registerCmd('test.request_identity', () => events);
bridge.onPacket(makeRequestPacket());
await bridge.onPacket(makeRequestPacket());
expect(bridge.identity.findUidByUin(55555)).toBe('u_friend_request');
expect(bridge.identity.findUidByUin(66666)).toBe('u_group_request');
@@ -29,7 +29,7 @@ function device(overrides: Partial<OnlineDeviceInfo> = {}): OnlineDeviceInfo {
}
describe('Bridge online-device snapshot', () => {
it('distinguishes not-yet-observed from an observed empty snapshot', () => {
it('distinguishes not-yet-observed from an observed empty snapshot', async () => {
const bridge = new Bridge(IdentityService.memory('10001'));
let current: OnlineDeviceInfo[] = [device()];
bridge.registerCmd('test.online_devices', () => [{
@@ -41,15 +41,15 @@ describe('Bridge online-device snapshot', () => {
expect(bridge.getOnlineClients()).toBeNull();
bridge.onPacket(packet(1));
await bridge.onPacket(packet(1));
expect(bridge.getOnlineClients()).toEqual([device()]);
current = [];
bridge.onPacket(packet(2));
await bridge.onPacket(packet(2));
expect(bridge.getOnlineClients()).toEqual([]);
});
it('owns an immutable copy and clears it when the Bridge is disposed', () => {
it('owns an immutable copy and clears it when the Bridge is disposed', async () => {
const bridge = new Bridge(IdentityService.memory('10001'));
const source = device();
bridge.registerCmd('test.online_devices', () => [{
@@ -59,7 +59,7 @@ describe('Bridge online-device snapshot', () => {
devices: [source],
}]);
bridge.onPacket(packet(1));
await bridge.onPacket(packet(1));
const snapshot = bridge.getOnlineClients();
expect(snapshot).not.toBeNull();
expect(snapshot?.[0]).not.toBe(source);
@@ -69,7 +69,7 @@ describe('Bridge online-device snapshot', () => {
source.deviceName = 'MUTATED';
expect(bridge.getOnlineClients()?.[0]?.deviceName).toBe('DESKTOP-TEST');
bridge.dispose();
await bridge.dispose();
expect(bridge.getOnlineClients()).toBeNull();
});
});
@@ -80,7 +80,7 @@ describe('Bridge roster warmup', () => {
expect(identity.findFriend(22222)?.uid).toBe('u_friend');
expect(identity.findGroup(123)?.groupName).toBe('group');
expect(identity.findGroupMember(123, 33333)?.uid).toBe('u_member');
bridge.dispose();
await bridge.dispose();
});
it('does not retry a failed friend list fetch', async () => {
@@ -98,7 +98,7 @@ describe('Bridge roster warmup', () => {
bridge.bindPid(8, sender);
await bridge.whenRosterWarmupSettled();
expect(fetchFriendList).toHaveBeenCalledOnce();
bridge.dispose();
await bridge.dispose();
});
it('discards in-flight warmup writes after dispose', async () => {
@@ -111,7 +111,7 @@ describe('Bridge roster warmup', () => {
bridge.bindPid(7, sender);
const settled = bridge.whenRosterWarmupSettled();
bridge.dispose();
await bridge.dispose();
releaseFriends([makeFriend(22222, 'u_friend', 'friend')]);
await expect(settled).resolves.toEqual({ friendsLoaded: false, groupsLoaded: false });
+10 -10
View File
@@ -186,7 +186,7 @@ describe('formatMessageSegments', () => {
});
describe('formatReply', () => {
it('renders the resolved sender + body preview when the original is in the store', () => {
it('renders the resolved sender + body preview when the original is in the store', async () => {
const store = fakeMessageStore({
42: {
message_type: 'group',
@@ -197,16 +197,16 @@ describe('formatReply', () => {
},
});
const id = fakeIdentity({ members: { '1/100': { uin: 100, card: 'OrigSender' } } });
expect(formatReply(store, id, 42)).toBe('[回复 [OrigSender(100)]: 早安]');
expect(await formatReply(store, id, 42)).toBe('[回复 [OrigSender(100)]: 早安]');
});
it('falls back to [回复:<id>] when the original is missing', () => {
it('falls back to [回复:<id>] when the original is missing', async () => {
const store = fakeMessageStore({});
const id = fakeIdentity();
expect(formatReply(store, id, 9999)).toBe('[回复:9999]');
expect(await formatReply(store, id, 9999)).toBe('[回复:9999]');
});
it('uses the sender baked into the stored event when cache misses', () => {
it('uses the sender baked into the stored event when cache misses', async () => {
const store = fakeMessageStore({
42: {
message_type: 'private',
@@ -216,10 +216,10 @@ describe('formatReply', () => {
},
});
const id = fakeIdentity(); // no cache
expect(formatReply(store, id, 42)).toBe('[回复 [StoredNick(100)]: hi]');
expect(await formatReply(store, id, 42)).toBe('[回复 [StoredNick(100)]: hi]');
});
it('truncates the body preview to 30 chars', () => {
it('truncates the body preview to 30 chars', async () => {
const store = fakeMessageStore({
42: {
message_type: 'private',
@@ -229,16 +229,16 @@ describe('formatReply', () => {
},
});
const id = fakeIdentity();
const out = formatReply(store, id, 42);
const out = await formatReply(store, id, 42);
// Inner text gets truncated to 50 by formatMessageSegments, then to 30 here
expect(out).toContain('...');
expect(out.length).toBeLessThan(80);
});
it('returns the fallback when findEvent throws', () => {
it('returns the fallback when findEvent throws', async () => {
const store = { findEvent: () => { throw new Error('store dead'); } } as any;
const id = fakeIdentity();
expect(formatReply(store, id, 42)).toBe('[回复:42]');
expect(await formatReply(store, id, 42)).toBe('[回复:42]');
});
});
+165 -85
View File
@@ -73,19 +73,45 @@ afterEach(() => {
});
describe('IdentityService', () => {
it('persists friends, groups, and active group members', () => {
it('replays observations accepted during loading and drains them when closed before ready', async () => {
const dbPath = tempDbPath('async-startup');
const previous = new IdentityService(SELF_UIN, dbPath);
previous.rememberFriends([{ uin: 22222, uid: 'u_old', nickname: 'old', remark: '' }]);
await previous.close();
let release!: () => void;
const loading = new Promise<void>(resolve => { release = resolve; });
const identity = new IdentityService(SELF_UIN, dbPath, loading);
const friends = [{ uin: 33333, uid: 'u_new', nickname: 'accepted', remark: '' }];
identity.rememberFriends(friends);
friends[0]!.nickname = 'mutated by caller';
expect(identity.findFriend(33333)?.nickname).toBe('accepted');
const closing = identity.close();
expect(() => identity.rememberFriends([])).toThrow(/closed/);
release();
await closing;
const reopened = new IdentityService(SELF_UIN, dbPath);
try {
await reopened.initialization;
expect(reopened.findFriend(22222)).toBeNull();
expect(reopened.findFriend(33333)?.nickname).toBe('accepted');
} finally { await reopened.close(); }
});
it('persists friends, groups, and active group members', async () => {
const dbPath = tempDbPath('persist');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: 'remark' }]);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_member', 'card')]);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findFriend(22222)?.uid).toBe('u_friend');
expect(identity.findGroup(GROUP_ID)?.groupName).toBe('group');
@@ -93,28 +119,30 @@ describe('IdentityService', () => {
expect(identity.findUidByUin(33333, GROUP_ID)).toBe('u_member');
expect(identity.findUinByUid('u_member', GROUP_ID)).toBe(33333);
identity.close();
await identity.close();
}
});
it('persists group member robot classification across restarts', () => {
it('persists group member robot classification across restarts', async () => {
const dbPath = tempDbPath('persist-robot');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_robot', '', true)]);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBe(true);
identity.close();
await identity.close();
}
});
it('migrates legacy member caches without inventing a robot classification', () => {
it('migrates legacy member caches without inventing a robot classification', async () => {
const dbPath = tempDbPath('migrate-robot');
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const legacy = new DatabaseSync(dbPath);
@@ -164,8 +192,9 @@ describe('IdentityService', () => {
legacy.close();
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
identity.close();
await identity.close();
const migrated = new DatabaseSync(dbPath);
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{ name: string }>;
@@ -173,52 +202,57 @@ describe('IdentityService', () => {
migrated.close();
});
it('keeps updateGroupMember changes after reopening the persistent cache', () => {
it('keeps updateGroupMember changes after reopening the persistent cache', async () => {
const dbPath = tempDbPath('update-member');
const member = makeMember(33333, 'u_member', 'old-card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.updateGroupMember(GROUP_ID, { ...member, card: 'new-card' });
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('new-card');
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('new-card');
identity.close();
await identity.close();
}
});
it('persists an explicitly cleared member card instead of restoring the old value', () => {
it('persists an explicitly cleared member card instead of restoring the old value', async () => {
const dbPath = tempDbPath('clear-member-card');
const member = makeMember(33333, 'u_member', 'old-card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.updateGroupMember(GROUP_ID, { ...member, card: '' });
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('');
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('');
identity.close();
await identity.close();
}
});
it('keeps friend remark updates after reopening the persistent cache', () => {
it('keeps friend remark updates after reopening the persistent cache', async () => {
const dbPath = tempDbPath('update-friend-remark');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
@@ -228,37 +262,40 @@ describe('IdentityService', () => {
expect(identity.updateFriendRemark('u_friend', 22222, 'new-remark')).toBe(true);
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
identity.close();
await identity.close();
}
});
it('keeps exact group remark updates after reopening the persistent cache', () => {
it('keeps exact group remark updates after reopening the persistent cache', async () => {
const dbPath = tempDbPath('update-group-remark');
const remark = ' project group ';
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([{ ...makeGroup(), remark: 'old-remark' }]);
expect(identity.updateGroupRemark(GROUP_ID, remark)).toBe(true);
expect(identity.findGroup(GROUP_ID)?.remark).toBe(remark);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroup(GROUP_ID)?.remark).toBe(remark);
identity.close();
await identity.close();
}
});
it('does not invent a group while applying a remark update', () => {
it('does not invent a group while applying a remark update', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
@@ -266,18 +303,19 @@ describe('IdentityService', () => {
expect(identity.groups).toHaveLength(1);
expect(identity.findGroup(GROUP_ID)?.remark).toBe('');
expect(identity.findGroup(987654321)).toBeNull();
identity.close();
await identity.close();
});
it.each([
['empty', ''],
['whitespace-only', ' '],
['surrounding-whitespace', ' padded remark '],
])('preserves %s friend remarks exactly after reopening', (_label, remark) => {
])('preserves %s friend remarks exactly after reopening', async (_label, remark) => {
const dbPath = tempDbPath('exact-friend-remark');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
@@ -287,13 +325,14 @@ describe('IdentityService', () => {
expect(identity.updateFriendRemark('u_friend', 22222, remark)).toBe(true);
expect(identity.findFriend(22222)?.remark).toBe(remark);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findFriend(22222)?.remark).toBe(remark);
identity.close();
await identity.close();
}
});
@@ -314,6 +353,7 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-recovery');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const releaseLock = holdWriteLock(dbPath);
let closed = false;
@@ -326,6 +366,7 @@ describe('IdentityService', () => {
}]);
expect(identity.findFriend(22222)?.uid).toBe('u_retry');
await expect(identity.flush()).rejects.toThrow(/locked/i);
expect(identity.persistenceStatus).toMatchObject({
state: 'degraded',
pendingWrites: 1,
@@ -336,6 +377,7 @@ describe('IdentityService', () => {
expect(identity.persistenceStatus.nextRetryAt! - Date.now()).toBe(100);
await vi.advanceTimersByTimeAsync(100);
await expect(identity.flush()).rejects.toThrow(/locked/i);
expect(identity.persistenceStatus).toMatchObject({
state: 'degraded',
pendingWrites: 1,
@@ -345,6 +387,7 @@ describe('IdentityService', () => {
releaseLock();
await vi.advanceTimersByTimeAsync(500);
await identity.flush();
expect(identity.persistenceStatus).toMatchObject({
state: 'healthy',
@@ -352,15 +395,16 @@ describe('IdentityService', () => {
retryAttempt: 0,
nextRetryAt: null,
});
identity.close();
await identity.close();
closed = true;
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findFriend(22222)?.uid).toBe('u_retry');
reopened.close();
await reopened.close();
} finally {
releaseLock();
if (!closed) identity.close();
if (!closed) await identity.close();
}
});
@@ -368,6 +412,7 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-order');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const releaseLock = holdWriteLock(dbPath);
let closed = false;
@@ -391,16 +436,17 @@ describe('IdentityService', () => {
releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
closed = true;
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findFriend(11111)).toBeNull();
expect(reopened.findFriend(22222)?.uid).toBe('u_second');
reopened.close();
await reopened.close();
} finally {
releaseLock();
if (!closed) identity.close();
if (!closed) await identity.close();
}
});
@@ -408,6 +454,7 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-snapshot');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const member = makeMember(33333, 'u_member', 'before');
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
@@ -421,14 +468,15 @@ describe('IdentityService', () => {
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('accepted');
releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findGroupMember(GROUP_ID, member.uin)?.card).toBe('accepted');
reopened.close();
await reopened.close();
} finally {
releaseLock();
identity.close();
await identity.close();
}
});
@@ -436,6 +484,7 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('pending-member-group-refresh');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const member = makeMember(33333, 'u_member', 'persisted-card');
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
@@ -450,15 +499,16 @@ describe('IdentityService', () => {
releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findGroup(GROUP_ID)?.groupName).toBe('refreshed-group');
expect(reopened.findGroupMember(GROUP_ID, member.uin)?.card).toBe('pending-card');
reopened.close();
await reopened.close();
} finally {
releaseLock();
identity.close();
await identity.close();
}
});
@@ -466,6 +516,7 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('pending-rebind');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberRequestIdentity({ uid: 'u_old_for_uin', uin: 22001 });
identity.rememberRequestIdentity({ uid: 'u_stable', uin: 22002 });
const releaseLock = holdWriteLock(dbPath);
@@ -481,15 +532,16 @@ describe('IdentityService', () => {
releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findUidByUin(22001)).toBe('u_new_for_uin');
expect(reopened.findUinByUid('u_stable')).toBe(22999);
reopened.close();
await reopened.close();
} finally {
releaseLock();
identity.close();
await identity.close();
}
});
@@ -497,6 +549,7 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-capacity');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const releaseLock = holdWriteLock(dbPath);
try {
@@ -528,7 +581,7 @@ describe('IdentityService', () => {
} finally {
releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
}
});
@@ -536,6 +589,7 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-exhausted');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const releaseLock = holdWriteLock(dbPath);
const seen: Array<{ level: string; message: string }> = [];
const unsubscribe = subscribeLogs((entry) => {
@@ -551,8 +605,10 @@ describe('IdentityService', () => {
}]);
identity.rememberRequestIdentity({ uid: 'u_abandoned_request', uin: 33333 });
await expect(identity.flush()).rejects.toThrow(/locked/i);
for (const delay of [100, 500, 2_000, 10_000, 30_000]) {
await vi.advanceTimersByTimeAsync(delay);
await identity.flush().catch(() => undefined);
}
expect(identity.persistenceStatus).toMatchObject({
@@ -608,9 +664,10 @@ describe('IdentityService', () => {
expect(skipLogs[1]?.message).toMatch(/suppressed=50/);
releaseLock();
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.persistenceStatus).toMatchObject({
state: 'healthy',
suspended: false,
@@ -620,22 +677,24 @@ describe('IdentityService', () => {
expect(reopened.findUinByUid('u_abandoned_request')).toBeNull();
expect(reopened.findUinByUid('u_skipped_after_suspend')).toBeNull();
reopened.rememberRequestIdentity({ uid: 'u_after_restart', uin: 55555 });
reopened.close();
await reopened.close();
const persisted = new IdentityService(SELF_UIN, dbPath);
await persisted.initialization;
expect(persisted.findUinByUid('u_after_restart')).toBe(55555);
persisted.close();
await persisted.close();
} finally {
unsubscribe();
releaseLock();
identity.close();
await identity.close();
}
});
it('flushes pending writes synchronously during close when SQLite has recovered', () => {
it('flushes pending writes during asynchronous close when SQLite has recovered', async () => {
vi.useFakeTimers();
const dbPath = tempDbPath('close-flush');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const releaseLock = holdWriteLock(dbPath);
identity.rememberFriends([{
@@ -647,7 +706,7 @@ describe('IdentityService', () => {
expect(identity.persistenceStatus.pendingWrites).toBe(1);
releaseLock();
identity.close();
await identity.close();
expect(identity.persistenceStatus).toMatchObject({
state: 'closed',
@@ -657,14 +716,16 @@ describe('IdentityService', () => {
});
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findFriend(22222)?.uid).toBe('u_close_flush');
reopened.close();
await reopened.close();
});
it('warns and releases pending retry work when close cannot flush SQLite', () => {
it('warns and releases pending retry work when close cannot flush SQLite', async () => {
vi.useFakeTimers();
const dbPath = tempDbPath('close-pending');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const releaseLock = holdWriteLock(dbPath);
const seen: Array<{ level: string; message: string }> = [];
const unsubscribe = subscribeLogs((entry) => {
@@ -680,7 +741,7 @@ describe('IdentityService', () => {
}]);
expect(identity.persistenceStatus.pendingWrites).toBe(1);
identity.close();
await identity.close();
expect(identity.persistenceStatus).toMatchObject({
state: 'closed',
@@ -697,7 +758,7 @@ describe('IdentityService', () => {
} finally {
unsubscribe();
releaseLock();
identity.close();
await identity.close();
}
});
@@ -705,6 +766,7 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('close-failure');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const releaseLock = holdWriteLock(dbPath);
const database = (identity as unknown as { db: DatabaseSync }).db;
const closeSpy = vi.spyOn(database, 'close').mockImplementationOnce(() => {
@@ -720,7 +782,8 @@ describe('IdentityService', () => {
}]);
expect(identity.persistenceStatus.pendingWrites).toBe(1);
expect(() => identity.close()).toThrow(/injected close failure/);
await expect(identity.flush()).rejects.toThrow(/locked/i);
await expect(identity.close()).rejects.toThrow(/injected close failure/);
expect(identity.persistenceStatus).toMatchObject({
state: 'degraded',
pendingWrites: 1,
@@ -739,29 +802,31 @@ describe('IdentityService', () => {
closeSpy.mockRestore();
releaseLock();
await vi.runOnlyPendingTimersAsync();
await identity.flush();
expect(identity.persistenceStatus).toMatchObject({
state: 'healthy',
pendingWrites: 0,
});
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findFriend(22222)?.uid).toBe('u_close_retry_friend');
expect(reopened.findUinByUid('u_after_close_failure')).toBe(33333);
reopened.close();
await reopened.close();
} finally {
closeSpy.mockRestore();
releaseLock();
identity.close();
await identity.close();
}
});
it('fails fast on every observation entry point after close', () => {
it('fails fast on every observation entry point after close', async () => {
const identity = IdentityService.memory(SELF_UIN);
const member = makeMember(33333, 'u_member', 'before-close');
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.close();
await identity.close();
const profile: UserProfileInfo = {
uin: 44444,
@@ -824,39 +889,41 @@ describe('IdentityService', () => {
expect(identity.findUinByUid('u_request')).toBeNull();
});
it('does not treat identity-only sightings as live group members', () => {
it('does not treat identity-only sightings as live group members', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_seen', uin: 88888 });
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
expect(identity.findUinByUid('u_seen')).toBe(88888);
identity.close();
await identity.close();
});
it('does not hydrate identity-only sightings as live members after reopen', () => {
it('does not hydrate identity-only sightings as live members after reopen', async () => {
const dbPath = tempDbPath('identity-only-not-roster');
const member = makeMember(33333, 'u_member', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_operator', uin: 88888 });
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('card');
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
expect(identity.findUinByUid('u_operator')).toBe(88888);
identity.close();
await identity.close();
}
});
it('records a thin live member on join without inventing roster details', () => {
it('records a thin live member on join without inventing roster details', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const existing = makeMember(33333, 'u_existing', 'card');
@@ -876,23 +943,25 @@ describe('IdentityService', () => {
});
expect(joined?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
identity.close();
await identity.close();
});
it('persists a thin live member on join across reopen', () => {
it('persists a thin live member on join across reopen', async () => {
const dbPath = tempDbPath('join-live-roster');
const existing = makeMember(33333, 'u_existing', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [existing]);
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 });
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const joined = identity.findGroupMember(GROUP_ID, 44444);
expect(joined).toMatchObject({
uin: 44444,
@@ -903,11 +972,11 @@ describe('IdentityService', () => {
});
expect(joined?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
identity.close();
await identity.close();
}
});
it('drops a leaver from the live roster and keeps their identity mapping', () => {
it('drops a leaver from the live roster and keeps their identity mapping', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const member = makeMember(33333, 'u_member', 'card');
@@ -917,71 +986,77 @@ describe('IdentityService', () => {
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
await identity.close();
});
it('keeps a leaver out of the live roster after reopen', () => {
it('keeps a leaver out of the live roster after reopen', async () => {
const dbPath = tempDbPath('leave-live-roster');
const member = makeMember(33333, 'u_member', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
await identity.close();
}
});
it('marks missing members inactive only after a successful full refresh', () => {
it('marks missing members inactive only after a successful full refresh', async () => {
const dbPath = tempDbPath('inactive-refresh');
const first = makeMember(33333, 'u_first');
const second = makeMember(44444, 'u_second');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [first, second]);
identity.rememberGroupMembers(GROUP_ID, [second]);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, first.uin)).toBeNull();
expect(identity.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid);
// Historical identity remains available for UID/UIN resolution.
expect(identity.findUidByUin(first.uin, GROUP_ID)).toBe(first.uid);
identity.close();
await identity.close();
}
});
it('marks missing friends and groups inactive after successful full refreshes', () => {
it('marks missing friends and groups inactive after successful full refreshes', async () => {
const dbPath = tempDbPath('inactive-lists');
const member = makeMember(33333, 'u_member');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: '' }]);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.rememberFriends([]);
identity.rememberGroups([]);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findFriend(22222)).toBeNull();
expect(identity.findGroup(GROUP_ID)).toBeNull();
@@ -989,37 +1064,40 @@ describe('IdentityService', () => {
expect(identity.findUidByUin(22222)).toBe('u_friend');
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
await identity.close();
}
});
it('can mark one member inactive without losing the identity mapping', () => {
it('can mark one member inactive without losing the identity mapping', async () => {
const dbPath = tempDbPath('inactive-event');
const member = makeMember(33333, 'u_member');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUinByUid(member.uid, GROUP_ID)).toBe(member.uin);
identity.close();
await identity.close();
}
});
it('persists identities learned from request events', () => {
it('persists identities learned from request events', async () => {
const dbPath = tempDbPath('request-events');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberRequestIdentity({
uid: 'u_friend_request',
uin: 55555,
@@ -1031,18 +1109,19 @@ describe('IdentityService', () => {
uin: 66666,
source: 'group_request',
});
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findUidByUin(55555)).toBe('u_friend_request');
expect(identity.findUinByUid('u_friend_request')).toBe(55555);
expect(identity.findGroup(GROUP_ID)).toBeNull();
expect(identity.findUidByUin(66666)).toBe('u_group_request');
identity.close();
await identity.close();
}
});
});
@@ -1247,6 +1326,7 @@ describe('IdentityService inbound UID→UIN', () => {
it('does not enter Identity degraded when the inbound fetcher throws', async () => {
const dbPath = tempDbPath('inbound-fetch-throw');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => {
@@ -1257,6 +1337,6 @@ describe('IdentityService inbound UID→UIN', () => {
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
expect(identity.persistenceStatus.state).toBe('healthy');
expect(identity.persistenceStatus.pendingWrites).toBe(0);
identity.close();
await identity.close();
});
});
@@ -0,0 +1,45 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { RuntimeIntegrity } from '@snowluma/bridge';
import { redactLogMessage } from '@snowluma/common/log-summary';
const log = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn() }));
vi.mock('@snowluma/common/logger', () => ({ createLogger: () => log }));
import { logRuntimeIntegrity } from '../src/runtime-integrity-log';
const sample: Extract<RuntimeIntegrity, { status: 'available' }> = {
status: 'available', pid: 123,
executablePath: 'C:\\private\\node.exe',
process: { status: 'ok', rid: 8192 }, file: { status: 'ok', label: null },
};
beforeEach(() => vi.clearAllMocks());
describe('startup integrity log', () => {
it('writes one readable line with the token level and unlabeled file', () => {
logRuntimeIntegrity(sample);
expect(log.info).toHaveBeenCalledExactlyOnceWith('Node integrity: pid=123, process=Medium (RID=8192); EXE=unlabeled');
expect(redactLogMessage(log.info.mock.calls[0]![0])).toContain('process=Medium (RID=8192)');
expect(log.warn).not.toHaveBeenCalled();
expect(log.info.mock.calls.flat().join(' ')).not.toContain('private');
});
it('writes one warning with Low token and inherited EXE details', () => {
logRuntimeIntegrity({ ...sample, process: { status: 'ok', rid: 4096 }, file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } } });
expect(log.warn).toHaveBeenCalledExactlyOnceWith('Node integrity: pid=123, process=Low (RID=4096); EXE=Low (RID=4096), inherited=true, policy=1');
expect(redactLogMessage(log.warn.mock.calls[0]![0])).toContain('process=Low (RID=4096)');
expect(log.info).not.toHaveBeenCalled();
});
it('preserves read failures while still reporting the successful part', () => {
logRuntimeIntegrity({ ...sample, file: { status: 'error', operation: 'GetNamedSecurityInfoW', code: 5 } });
expect(log.warn).toHaveBeenCalledExactlyOnceWith('Node integrity: pid=123, process=Medium (RID=8192); EXE=unknown (GetNamedSecurityInfoW, Win32=5)');
});
it('logs unavailable diagnostics once and skips unsupported platforms', () => {
logRuntimeIntegrity({ status: 'unsupported' });
expect(log.info).not.toHaveBeenCalled();
expect(log.warn).not.toHaveBeenCalled();
logRuntimeIntegrity({ status: 'unavailable', error: 'addon unavailable' });
expect(log.warn).toHaveBeenCalledExactlyOnceWith('Node integrity: unknown (%s)', 'addon unavailable');
});
});
@@ -12,16 +12,15 @@ const {
describe('runtime Node.js preflight', () => {
it('accepts the documented minimum and newer versions', () => {
expect(SUPPORTED_NODE_RANGE).toBe('^22.13.0 || >=23.4.0');
expect(isSupportedNodeVersion('22.13.0')).toBe(true);
expect(isSupportedNodeVersion('22.13.1')).toBe(true);
expect(isSupportedNodeVersion('23.4.0')).toBe(true);
expect(SUPPORTED_NODE_RANGE).toBe('>=24');
expect(isSupportedNodeVersion('24.0.0')).toBe(true);
expect(isSupportedNodeVersion('24.21.0')).toBe(true);
expect(isSupportedNodeVersion('26.0.0')).toBe(true);
});
it('rejects older and malformed versions', () => {
expect(isSupportedNodeVersion('22.12.99')).toBe(false);
expect(isSupportedNodeVersion('23.3.99')).toBe(false);
expect(isSupportedNodeVersion('22.99.99')).toBe(false);
expect(isSupportedNodeVersion('23.99.99')).toBe(false);
expect(isSupportedNodeVersion('21.99.99')).toBe(false);
expect(isSupportedNodeVersion('not-a-version')).toBe(false);
});
+5 -23
View File
@@ -5,6 +5,7 @@ import path from 'path';
import { fileURLToPath } from 'url';
import { defineConfig, PluginOption, UserConfig } from 'vite';
import cp from 'vite-plugin-cp';
import { sqliteBuildPlugin } from '@snowluma/sqlite/vite';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
@@ -24,13 +25,6 @@ const toPosix = (p: string) => p.replace(/\\/g, '/');
// in-tree TS workspace wrapper that routes its native `.node`
// addon through `dist/native/`. Only Node builtins stay external.
//
// `node:sqlite` is an experimental builtin that Node 22.x lines don't
// list in `builtinModules`, so the `nodeModules` sweep below misses it.
// Externalise it explicitly — otherwise Vite bundles it and swaps in a
// browser shell, crashing the hook with `DatabaseSync is not a
// constructor` (the bug PR #68 set out to fix).
const external: string[] = ['node:sqlite', 'sqlite'];
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
const runtimeSrc = toPosix(runtimeDir);
@@ -105,6 +99,7 @@ const BaseConfigPlugin: PluginOption[] = [
// before `cp` so the transform runs on every source file Vite asks
// for, regardless of where `cp` later copies emitted assets.
protobufVitePlugin(),
sqliteBuildPlugin(targetTriple),
cp({
targets: [
...runtimeDistFiles.map((file) => ({
@@ -142,7 +137,7 @@ const BaseConfig = (source_map: boolean = false) => defineConfig({
},
build: {
sourcemap: source_map,
target: 'esnext',
target: 'node24',
minify: false,
lib: {
entry: {
@@ -152,22 +147,9 @@ const BaseConfig = (source_map: boolean = false) => defineConfig({
fileName: (_, entryName) => `${entryName}.mjs`
},
rollupOptions: {
external: [...nodeModules, ...external],
external: nodeModules,
output: {
// better-sqlite3's JS wrapper is pure CJS — its `require('fs')` /
// `require('path')` / `require('bindings')` calls get inlined into
// the ESM bundle as `__require("fs")` shims by rolldown. Those
// shims gate on `typeof require !== "undefined"`, which is true
// in CJS but FALSE in our `.mjs` output, so they fall through to
// a runtime `throw Error("Calling \`require\` ... in an environment
// that doesn't expose the \`require\` function.")` on first call —
// crashing the launcher immediately.
//
// Defining a module-scope `require` via `createRequire(import.meta.url)`
// at the very top of the bundle satisfies the `typeof` check, and
// the shim then transparently delegates every inlined CJS require
// to the real CJS loader. Node 18+ ships `createRequire` in the
// `node:module` builtin, so this is supported on every target.
// Bundled CommonJS dependencies still need Node's native require.
banner: [
"import { createRequire as __snowlumaCreateRequire } from 'node:module';",
"const require = __snowlumaCreateRequire(import.meta.url);",
+2
View File
@@ -47,6 +47,8 @@ Point the server at a running SnowLuma instance's **OneBot HTTP endpoint** (the
Ordinary actions pass the OneBot envelope through verbatim — a logical failure
(`retcode≠0`) comes back as data with its `wording`. Stream protocol failures are
reported as MCP errors because they mean no complete stream result was committed.
Omitted `params` defaults to an empty object; a supplied non-object value is
rejected before calling OneBot.
### Configuration (env)
+1 -1
View File
@@ -51,7 +51,7 @@
"vitest": "^4.1.4"
},
"engines": {
"node": ">=22"
"node": ">=24"
},
"publishConfig": {
"access": "public"
+33 -22
View File
@@ -3773,7 +3773,7 @@
"name": "get_forward_msg",
"aliases": [],
"summary": "获取合并转发消息(id 或 message_id)",
"returns": "{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件,内部字段不固定)。",
"returns": "{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件);reply 保留 id,有内嵌引用内容时附带 message 和可用的 qq/time/seq,可作为转发节点 content 再次发送。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -6483,7 +6483,7 @@
"name": "get_msg",
"aliases": [],
"summary": "获取消息",
"returns": "消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。",
"returns": "消息事件对象(去除 post_type/self_id,附带 real_id);逐个尝试刷新图片、语音和视频 URL,成功使用新地址,失败保留该段原地址并继续返回消息;地址更新时同步 raw_message。",
"readOnly": true,
"params": [
{
@@ -7573,6 +7573,7 @@
"name": "get_record",
"aliases": [],
"summary": "获取语音信息;传 out_format 则服务端转码并附带 base64",
"returns": "语音信息(file/url 为向 QQ 获取的当前下载地址);资源元数据缺失或远端获取失败时返回错误。out_format 指定时附带转码后的 base64。",
"readOnly": true,
"params": [
{
@@ -9192,7 +9193,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -9200,7 +9202,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message_type",
@@ -9264,10 +9267,10 @@
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message_type": {
"type": "string"
@@ -9438,7 +9441,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -9446,7 +9450,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "source",
@@ -9490,10 +9495,10 @@
"x-role": "group_id"
},
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"source": {
"type": "string"
@@ -9841,7 +9846,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -9849,7 +9855,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "source",
@@ -9892,10 +9899,10 @@
"x-role": "user_id"
},
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"source": {
"type": "string"
@@ -12845,7 +12852,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -12853,7 +12861,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "group_id",
@@ -12871,10 +12880,10 @@
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"group_id": {
"type": "integer",
@@ -12898,7 +12907,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -12906,7 +12916,8 @@
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "group_id",
@@ -12924,10 +12935,10 @@
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"group_id": {
"type": "integer",
+33 -22
View File
@@ -3776,7 +3776,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_forward_msg",
"aliases": [],
"summary": "获取合并转发消息(id 或 message_id)",
"returns": "{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件,内部字段不固定)。",
"returns": "{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件);reply 保留 id,有内嵌引用内容时附带 message 和可用的 qq/time/seq,可作为转发节点 content 再次发送。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -6486,7 +6486,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_msg",
"aliases": [],
"summary": "获取消息",
"returns": "消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。",
"returns": "消息事件对象(去除 post_type/self_id,附带 real_id);逐个尝试刷新图片、语音和视频 URL,成功使用新地址,失败保留该段原地址并继续返回消息;地址更新时同步 raw_message。",
"readOnly": true,
"params": [
{
@@ -7576,6 +7576,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_record",
"aliases": [],
"summary": "获取语音信息;传 out_format 则服务端转码并附带 base64",
"returns": "语音信息(file/url 为向 QQ 获取的当前下载地址);资源元数据缺失或远端获取失败时返回错误。out_format 指定时附带转码后的 base64。",
"readOnly": true,
"params": [
{
@@ -9195,7 +9196,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -9203,7 +9205,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message_type",
@@ -9267,10 +9270,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message_type": {
"type": "string"
@@ -9441,7 +9444,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -9449,7 +9453,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "source",
@@ -9493,10 +9498,10 @@ export const ACTIONS: CatalogAction[] = [
"x-role": "group_id"
},
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"source": {
"type": "string"
@@ -9844,7 +9849,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -9852,7 +9858,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "source",
@@ -9895,10 +9902,10 @@ export const ACTIONS: CatalogAction[] = [
"x-role": "user_id"
},
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"source": {
"type": "string"
@@ -12848,7 +12855,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -12856,7 +12864,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "group_id",
@@ -12874,10 +12883,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"group_id": {
"type": "integer",
@@ -12901,7 +12910,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "message",
@@ -12909,7 +12919,8 @@ export const ACTIONS: CatalogAction[] = [
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"desc": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
{
"name": "group_id",
@@ -12927,10 +12938,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"message": {
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
"description": "转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。"
},
"group_id": {
"type": "integer",
+4 -4
View File
@@ -188,10 +188,10 @@ async function execute(args: Record<string, unknown>, ctx: CallCtx, kind: 'read'
return asError(`${action} 是写操作,不能用 query_action;请用 invoke_action(需 SNOWLUMA_MCP_MODE=write)。`);
}
const params =
args.params && typeof args.params === 'object' && !Array.isArray(args.params)
? (args.params as Record<string, unknown>)
: {};
if (args.params !== undefined && (args.params === null || typeof args.params !== 'object' || Array.isArray(args.params))) {
return asError('params 必须是对象。');
}
const params = (args.params ?? {}) as Record<string, unknown>;
let inputFile: string | undefined;
if (args.execution !== undefined) {
if (!args.execution || typeof args.execution !== 'object' || Array.isArray(args.execution)) {
+12
View File
@@ -81,6 +81,18 @@ describe('callTool — docs tools (no client needed)', () => {
});
describe('callTool — query_action (read)', () => {
it.each([null, [], 'invalid', 42, false].map(params => ({ params })))('rejects invalid params without invoking the client ($params)', async ({ params }) => {
let called = false;
const client = fakeClient(() => {
called = true;
return { status: 'ok', retcode: 0, data: null };
});
const res = await callTool('query_action', { action: 'get_status', params }, { mode: 'read', client });
expect(res.isError).toBe(true);
expect(text(res)).toContain('params');
expect(called).toBe(false);
});
it('executes a read-only action and passes the envelope through', async () => {
const res = await callTool('query_action', { action: 'get_status', params: {} }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBeFalsy();
+13 -13
View File
@@ -97,27 +97,27 @@ 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(600_000 + i, true, META.targetId, META.sequence + i, META.eventName, SAMPLE_EVENT);
await store.storeMeta(500_000 + i, META);
await store.storeEvent(600_000 + i, true, META.targetId, META.sequence + i, META.eventName, SAMPLE_EVENT);
}
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);
});
});
+5 -1
View File
@@ -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"
}
}
+28 -22
View File
@@ -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';
@@ -319,6 +320,10 @@ 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(),
@@ -360,7 +365,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');
if (!meta.isGroup || meta.targetId !== p.group_id) {
return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group');
@@ -503,7 +508,7 @@ export const actions = [
.filter((message): message is GroupEssenceMessage => message !== null)
.map((message) => projectEssenceMessage(message, p.group_id));
ctx.cacheMessageMetas(projections.map(({ messageId, meta }) => ({
await ctx.cacheMessageMetas(projections.map(({ messageId, meta }) => ({
messageId,
meta,
})));
@@ -526,7 +531,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(RETCODE.ACTION_FAILED, 'message not found or not a group message');
}
@@ -658,7 +663,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(RETCODE.ACTION_FAILED, 'message not found or not a group message');
}
@@ -680,7 +685,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(RETCODE.ACTION_FAILED, 'message not found or not a private message');
}
@@ -702,7 +707,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');
if (p.target_id && p.target_id !== meta.targetId) {
@@ -771,8 +776,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) => {
@@ -795,8 +800,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) => {
@@ -830,6 +835,7 @@ 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'),
@@ -1003,7 +1009,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();
},
@@ -2472,8 +2478,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(),
@@ -2506,8 +2512,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) => {
@@ -2524,8 +2530,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) => {
@@ -2540,7 +2546,7 @@ 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: {
@@ -2554,7 +2560,7 @@ export const actions = [
if (!id && p.message_id !== undefined) {
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) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
@@ -2736,13 +2742,13 @@ export const actions = [
return { todo, messageId, meta };
});
ctx.cacheMessageMetas(projections.map(({ messageId, meta }) => ({
await ctx.cacheMessageMetas(projections.map(({ messageId, meta }) => ({
messageId,
meta,
})));
return okResponse(projections.map(({ todo, messageId }) => {
const cached = ctx.getMessage(messageId)?.message;
return okResponse(await mapWithConcurrency(projections, 8, async ({ todo, messageId }) => {
const cached = (await ctx.getMessage(messageId))?.message;
return {
message_id: messageId,
message_seq: todo.sequence,
+4 -34
View File
@@ -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';
@@ -18,35 +17,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',
@@ -141,10 +111,10 @@ export const actions = [
name: 'get_msg',
summary: '获取消息',
readOnly: true,
returns: '消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。',
returns: '消息事件对象(去除 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);
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
@@ -153,7 +123,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);
},
}),
@@ -163,7 +133,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(RETCODE.ACTION_FAILED, 'message not found or not retractable');
await ctx.deleteMessage(p.message_id, meta);
return okResponse();
+5 -4
View File
@@ -50,12 +50,13 @@ export interface ApiActionContext {
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getUptimeMs: () => number;
getMessage: (messageId: number) => JsonObject | null;
getMessageMeta: (messageId: number) => MessageMeta | null;
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;
listReadSessions: () => ReadSessionTargets;
) => void | Promise<void>;
listReadSessions: () => ReadSessionTargets | Promise<ReadSessionTargets>;
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean, tempGroupId?: number) => Promise<MessageSendResult>;
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
@@ -219,7 +219,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,
@@ -246,10 +246,10 @@ export const ELEMENT_CODECS = {
log.warn('could not quote the target message');
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 = {
type: 'reply',
@@ -309,7 +309,7 @@ export const ELEMENT_CODECS = {
summary: element.summary ?? '',
};
if (element.flash) data.type = 'flash';
if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
if (ctx.mediaSegmentSink) await ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
return { type: 'image', data };
},
async fromSegment(data) {
@@ -338,7 +338,7 @@ export const ELEMENT_CODECS = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
if (ctx.mediaSegmentSink) await ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
return { type: 'record', data };
},
async fromSegment(data) {
@@ -361,7 +361,7 @@ export const ELEMENT_CODECS = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
if (ctx.mediaSegmentSink) await ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
return { type: 'video', data };
},
async fromSegment(data) {
+2 -2
View File
@@ -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 ───────────────
@@ -44,7 +44,7 @@ async function convertPrivateMessage(
const eventName = event.kind === 'friend_message'
? privateMessageEventName(isSelf, hasCanonicalNtSequence)
: PRIVATE_MESSAGE_EVENT;
const messageId = applyMessageIdResolver(
const messageId = await applyMessageIdResolver(
ctx.messageIdResolver, false, sessionId, messageIdSequence, eventName,
);
const segments = await toSegments(ctx, event.elements, false, sessionId);
@@ -86,7 +86,7 @@ export function convertTempMessage(ctx: ConverterContext, event: TempMessage): P
export async function convertGroupMessage(ctx: ConverterContext, event: GroupMessage): 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, event.msgSeq, GROUP_MESSAGE_EVENT,
);
const segments = await toSegments(ctx, event.elements, true, event.groupId);
@@ -78,8 +78,8 @@ 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,
@@ -94,8 +94,8 @@ 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, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return notice(ctx, event, {
@@ -133,8 +133,8 @@ 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, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return notice(ctx, event, {
@@ -242,8 +242,8 @@ export function convertFriendInputStatus(ctx: ConverterContext, event: FriendInp
});
}
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
const messageId = applyMessageIdResolver(
export async function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): Promise<JsonObject> {
const messageId = await applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return notice(ctx, event, {
@@ -8,45 +8,44 @@ 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) {
let segment: JsonObject;
// 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)', element.type,
err instanceof Error ? err.message : String(err));
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?.(element.type, element, segment.data as JsonObject, isGroup, sessionId);
await ctx.mediaSegmentSink?.(element.type, element, segment.data as JsonObject, isGroup, sessionId);
}
result.push(segment);
if (element.type === 'markdown' && element.text) {
+6 -11
View File
@@ -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,
@@ -17,23 +12,23 @@ 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;
}
const seq = Math.trunc(sequence);
return seq === 0 ? 0 : seq;
}
export function resolveReplyId(
export async function resolveReplyId(
isGroup: boolean,
sessionId: number,
sequence: number,
@@ -41,12 +36,12 @@ 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) return 0;
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;
}
+25 -25
View File
@@ -170,7 +170,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;
}
@@ -196,12 +196,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;
}
@@ -227,9 +227,9 @@ function traceEventTerminal(
]);
}
function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): void {
async function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): 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,
@@ -241,7 +241,7 @@ function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEven
});
}
function cachePrivateMessageMeta(
async function cachePrivateMessageMeta(
ctx: OneBotInstanceContext,
sessionId: number,
messageSequence: number,
@@ -251,7 +251,7 @@ function cachePrivateMessageMeta(
random: number,
sequenceAuthoritative: boolean,
privateDirection: MessageMeta['privateDirection'],
): void {
): Promise<void> {
const isFriendMessage = privateDirection !== undefined;
const hasNtSequence = isFriendMessage
&& sequenceAuthoritative
@@ -264,7 +264,7 @@ function cachePrivateMessageMeta(
sessionId,
eventName,
);
ctx.cacheMessageMeta(messageId, {
await ctx.cacheMessageMeta(messageId, {
isGroup: false,
targetId: sessionId,
sequence: serverSequence,
@@ -277,15 +277,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,
@@ -302,13 +302,13 @@ 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,
@@ -318,7 +318,7 @@ function cacheReaction(
event.time,
);
} else {
ctx.reactionStore.recordRemove(
await ctx.reactionStore.recordRemove(
event.groupId,
event.msgSeq,
event.emojiId,
@@ -327,23 +327,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,
@@ -357,13 +357,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,
@@ -378,14 +378,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,
@@ -404,13 +404,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);
}
+3 -3
View File
@@ -12,12 +12,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) {
throw new Error(`history event has invalid message_id ${String(event.message_id)}`);
@@ -59,7 +59,7 @@ export function persistHistoryEvent(
timestamp: source.time,
} satisfies Parameters<MessageStore['storeMeta']>[1]
: undefined;
store.storeHistoryEvent(
return store.storeHistoryEvent(
messageId,
isGroup,
sessionId,
+61 -63
View File
@@ -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 {
@@ -138,8 +139,8 @@ export class LoginHistorySyncCoordinator {
})),
signal,
);
const groupCandidates = selectGroupCandidates(ref.messageStore, state.groups);
const privateCandidates = selectPrivateCandidates(
const groupCandidates = await selectGroupCandidates(ref.messageStore, state.groups);
const privateCandidates = await selectPrivateCandidates(
ref.messageStore,
state.privateUsers,
);
@@ -156,9 +157,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,
},
@@ -249,76 +250,74 @@ export class LoginHistorySyncCoordinator {
export const loginHistorySyncCoordinator = new LoginHistorySyncCoordinator();
function selectGroupCandidates(
async function selectGroupCandidates(
store: MessageStore,
states: readonly GroupHistorySyncState[],
): GroupCandidate[] {
return states
.flatMap((state): GroupCandidate[] => {
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) return [];
const observedSequence = store.findLatestAuthoritativeSequence(true, state.groupId);
const localSequence = store.findLatestPersistedAuthoritativeSequence(
true,
state.groupId,
);
if (localSequence !== null) {
if (state.latestSeq <= localSequence) return [];
return [{
state,
localSequence,
priority: state.latestSeq - localSequence,
knownGap: true,
}];
}
if (observedSequence !== null) {
return [{
state,
localSequence: null,
priority: state.latestSeq,
knownGap: true,
}];
}
if (state.latestSeq <= state.readSeq) return [];
): Promise<GroupCandidate[]> {
return (await mapWithConcurrency(states, 8, async (state): Promise<GroupCandidate[]> => {
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) return [];
const observedSequence = await store.findLatestAuthoritativeSequence(true, state.groupId);
const localSequence = await store.findLatestPersistedAuthoritativeSequence(
true,
state.groupId,
);
if (localSequence !== null) {
if (state.latestSeq <= localSequence) return [];
return [{
state,
localSequence,
priority: state.latestSeq - localSequence,
knownGap: true,
}];
}
if (observedSequence !== null) {
return [{
state,
localSequence: null,
priority: state.latestSeq - state.readSeq,
knownGap: false,
priority: state.latestSeq,
knownGap: true,
}];
})
}
if (state.latestSeq <= state.readSeq) return [];
return [{
state,
localSequence: null,
priority: state.latestSeq - state.readSeq,
knownGap: false,
}];
})).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[] => {
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) return [];
const observedSequence = store.findLatestAuthoritativeSequence(false, state.userId);
const localSequence = store.findLatestPersistedAuthoritativeSequence(
false,
state.userId,
);
if (localSequence !== null) {
if (state.latestSeq <= localSequence) return [];
return [{
state,
localSequence,
priority: state.latestSeq - localSequence,
knownGap: true,
}];
}
if (!Number.isSafeInteger(state.lastMsgTime) || state.lastMsgTime <= 0) return [];
): Promise<PrivateCandidate[]> {
return (await mapWithConcurrency(states, 8, async (state): Promise<PrivateCandidate[]> => {
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) return [];
const observedSequence = await store.findLatestAuthoritativeSequence(false, state.userId);
const localSequence = await store.findLatestPersistedAuthoritativeSequence(
false,
state.userId,
);
if (localSequence !== null) {
if (state.latestSeq <= localSequence) return [];
return [{
state,
localSequence: null,
priority: state.lastMsgTime,
knownGap: observedSequence !== null,
localSequence,
priority: state.latestSeq - localSequence,
knownGap: true,
}];
})
}
if (!Number.isSafeInteger(state.lastMsgTime) || state.lastMsgTime <= 0) return [];
return [{
state,
localSequence: null,
priority: state.lastMsgTime,
knownGap: observedSequence !== null,
}];
})).flat()
.sort(compareCandidates)
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxPrivateUsers);
}
@@ -403,7 +402,7 @@ async function persistGroupMessage(
+ `messageType=${String(converted?.message_type)}`,
);
}
persistHistoryEvent(ref.messageStore, converted);
await persistHistoryEvent(ref.messageStore, converted);
}
async function persistPrivateMessage(
@@ -432,7 +431,7 @@ async function persistPrivateMessage(
+ `messageType=${String(converted?.message_type)}`,
);
}
if (ref.messageStore.isPrivateMessageRecalled(
if (await ref.messageStore.isPrivateMessageRecalled(
peerUin,
clientSequence,
sentBySelf,
@@ -450,8 +449,7 @@ async function persistPrivateMessage(
if (converted.post_type === 'message_sent' && toHistoryInt(converted.target_id) === 0) {
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> {
+20 -18
View File
@@ -22,6 +22,7 @@ import {
fetchPttText as fetchPttTextAction,
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
refreshMessageMedia,
} from './modules/media-actions';
import {
deleteMessage,
@@ -53,12 +54,12 @@ export interface OneBotInstanceContext {
config: OneBotConfig;
musicSignUrl?: string;
getUptimeMs(): number;
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
cacheMessageMeta(messageId: number, meta: MessageMeta): void | Promise<void>;
dispatchEvent(
event: JsonObject,
source?: 'bridge' | 'send',
startedAt?: number,
): void;
): void | Promise<void>;
}
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
@@ -70,10 +71,11 @@ 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(
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,
@@ -85,7 +87,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
autoEscape,
tempGroupId,
tempGroupId === undefined
? (event) => ref.dispatchEvent(event, 'send')
? async (event) => await ref.dispatchEvent(event, 'send')
: undefined,
),
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
@@ -110,7 +112,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
userId,
messages,
meta,
(event) => ref.dispatchEvent(event, 'send'),
async (event) => await ref.dispatchEvent(event, 'send'),
),
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
@@ -119,33 +121,33 @@ 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');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
if (!hasAuthoritativeSequence(meta)) throw new Error('message has no authoritative QQ sequence');
await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set);
const emojiType = emojiId.length > 3 ? 2 : 1;
if (set) {
reactionStore.recordAdd(
await reactionStore.recordAdd(
meta.targetId, meta.sequence, emojiId, emojiType,
ref.selfId, '', 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');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
if (!hasAuthoritativeSequence(meta)) 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;
@@ -154,7 +156,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
users: Array<{ user_id: number }>;
}> = [];
for (const entry of summary) {
let users = reactionStore.listUsers(meta.targetId, meta.sequence, entry.emojiId, 1000, 0)
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(
@@ -177,13 +179,13 @@ 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');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
if (!hasAuthoritativeSequence(meta)) throw new Error('message has no authoritative QQ sequence');
const raw = reactionStore.listUsers(meta.targetId, meta.sequence, emojiId, count, offset);
const raw = await reactionStore.listUsers(meta.targetId, meta.sequence, emojiId, count, offset);
let users = raw.map(r => ({ uin: r.operatorUin, 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 {
const remote = await bridge.apis.interaction.getEmojiLikes(
+30 -23
View File
@@ -143,14 +143,14 @@ export class OneBotInstance {
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
mediaUrlResolver: (element, isGroup, sessionId) =>
mediaUrlResolver.resolve(element, isGroup, sessionId),
messageIdResolver: (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
messageIdResolver: async (isGroup, sessionId, sequence, eventName, timestamp, replyElements) => {
const resolvedEventName = eventName
|| (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT);
if (!isGroup
&& timestamp !== undefined
&& (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,
@@ -167,8 +167,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,
@@ -182,7 +182,7 @@ 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),
};
this.ctx = ctx;
@@ -190,7 +190,12 @@ export class OneBotInstance {
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
const networkCtx = this.buildNetworkContext();
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,
@@ -334,14 +339,14 @@ 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) {
if (this.storeCloseState[name]) continue;
try {
close();
await close();
this.storeCloseState[name] = true;
} catch (error) {
closeErrors.push(error);
@@ -389,8 +394,11 @@ export class OneBotInstance {
source: 'bridge' | 'send' = 'bridge',
startedAt = Date.now(),
): Promise<void> {
if (!await this.cacheMessageEvent(event)) {
this.traceEventHandoffTerminal(event, startedAt, 'suppressed', 'private_recall');
return;
}
if (source === 'bridge') {
this.cacheMessageEvent(event);
if (this.consumePendingSelfSentEcho(event)) {
this.log.trace(
'duplicate self-message echo suppressed message_id=%d message_seq=%d',
@@ -401,13 +409,12 @@ export class OneBotInstance {
return;
}
} else {
this.cacheMessageEvent(event);
this.rememberPendingSelfSentEcho(event);
}
// The send path already logged the real peer and payload. Logging its
// 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);
if (source === 'bridge') await this.logReceivedMessage(event);
// Built-in `#sl` only consumes events observed from QQ. Action-originated
// messages must not recursively trigger the command handler.
if (source === 'bridge' && this.handleStatusCommand(event)) {
@@ -426,7 +433,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',
@@ -555,7 +562,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) return;
@@ -580,7 +587,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]));
}
@@ -614,11 +621,11 @@ export class OneBotInstance {
}
}
private cacheMessageEvent(event: JsonObject): void {
if (event.post_type !== 'message' && event.post_type !== 'message_sent') return;
private async cacheMessageEvent(event: JsonObject): Promise<boolean> {
if (event.post_type !== 'message' && event.post_type !== 'message_sent') return true;
const messageId = toInt(event.message_id);
if (messageId === 0) return;
if (messageId === 0) return true;
const isGroup = event.message_type === 'group';
const sessionId = isGroup
@@ -633,13 +640,13 @@ export class OneBotInstance {
? privateMessageEventName(event.post_type === 'message_sent', false)
: PRIVATE_MESSAGE_EVENT;
if (sessionId === 0) return;
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
if (sessionId === 0) return true;
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 {
+5 -5
View File
@@ -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,
+16 -16
View File
@@ -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 { foldMediaKey, MediaStore, rollbackMediaTransaction, serializeMediaInfo } from './media-store';
@@ -17,22 +17,22 @@ 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.prepare('SELECT phase, cursor FROM media_migration_state WHERE id = 1')
const state = await destination.prepare('SELECT phase, cursor FROM media_migration_state WHERE id = 1')
.get() as { phase: string; cursor: number };
if (state.phase === 'complete') return;
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)
VALUES (?, ?, ?, ?) ON CONFLICT(type, primary_key) DO NOTHING`);
@@ -41,13 +41,13 @@ export async function migrateLegacyMedia(
const saveState = destination.prepare('UPDATE media_migration_state SET phase = ?, cursor = ? WHERE id = 1');
while (!cancelled() && state.phase !== 'complete') {
const table = state.phase === 'entries' ? 'media_entries' : 'media_keys';
const rows = source.prepare(`SELECT rowid AS migration_rowid, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT ?`)
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<{
migration_rowid: number; type: string; primary_key: string; data: string; last_seen: number; key: string;
}>;
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) {
if (!['image', 'record', 'video'].includes(row.type)) {
@@ -58,15 +58,15 @@ export async function migrateLegacyMedia(
if (!info || typeof info !== 'object' || Array.isArray(info)) {
throw new Error(`invalid legacy media metadata at row ${row.migration_rowid}`);
}
insertEntry.run(row.type, foldMediaKey(row.primary_key), serializeMediaInfo(info), row.last_seen);
await insertEntry.run(row.type, foldMediaKey(row.primary_key), serializeMediaInfo(info), row.last_seen);
} else {
insertKey.run(row.type, foldMediaKey(row.key), foldMediaKey(row.primary_key));
await insertKey.run(row.type, foldMediaKey(row.key), foldMediaKey(row.primary_key));
}
}
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;
state.cursor = nextCursor;
@@ -76,7 +76,7 @@ export async function migrateLegacyMedia(
}
if (!cancelled()) log.info('preserving legacy media metadata: migration complete; source retained');
} finally {
source?.close();
destination.close();
await source?.close();
await destination.close();
}
}
+116 -75
View File
@@ -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,105 +71,146 @@ 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);
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.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)
);
`);
}
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(); }
rememberImage(info: CachedImage): void {
this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
async close(): Promise<void> {
await this.initialization.catch(() => undefined);
await this.db.close();
}
rememberRecord(info: CachedRecord): void {
this.remember(TYPE_RECORD, info, [info.file, info.fileName, info.fileId, 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]);
});
}
rememberVideo(info: CachedVideo): void {
this.remember(TYPE_VIDEO, 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]);
});
}
findImage(key: string, source: MediaLookupSource = 'current'): CachedImage | null {
return this.find(TYPE_IMAGE, key, source);
}
findRecord(key: string, source: MediaLookupSource = 'current'): CachedRecord | null {
return this.find(TYPE_RECORD, key, source);
}
findVideo(key: string, source: MediaLookupSource = 'current'): CachedVideo | null {
return this.find(TYPE_VIDEO, key, source);
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]);
});
}
updateImageUrl(key: string, url: string): void { this.updateUrl(TYPE_IMAGE, key, url); }
updateRecordUrl(key: string, url: string): void { this.updateUrl(TYPE_RECORD, key, url); }
updateVideoUrl(key: string, url: string): void { this.updateUrl(TYPE_VIDEO, key, url); }
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);
});
}
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);
});
}
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);
});
}
async updateImageUrl(key: string, url: string): Promise<void> {
return this.db.serial(async () => {
await this.initialization; await this.updateUrl(TYPE_IMAGE, 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); });
}
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) throw new Error(`cannot store ${type} metadata without an identifier`);
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
// callers cannot mutate the durable record through a returned object.
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) return null;
const cacheKey = `${source}:${type}:${lookup}`;
@@ -177,8 +218,8 @@ export class MediaStore {
if (data === undefined) {
// 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 { data: string } | undefined;
const current = 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) return null;
data = row.data;
}
@@ -195,11 +236,11 @@ 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(type, { ...info, url }, [info.file, info.fileName, info.fileId, url]
await this.remember(type, { ...info, url }, [info.file, info.fileName, info.fileId, url]
.filter((value): value is string => typeof value === 'string'));
}
}
@@ -212,8 +253,8 @@ export function serializeMediaInfo(info: object): string {
return data;
}
export function rollbackMediaTransaction(db: DatabaseSync, error: unknown): never {
try { db.exec('ROLLBACK'); }
export async function rollbackMediaTransaction(db: SqliteDatabase, error: unknown): Promise<never> {
try { await db.exec('ROLLBACK'); }
catch (rollbackError) {
throw new AggregateError([error, rollbackError], 'media write and rollback failed', { cause: error });
}
+21 -12
View File
@@ -1,7 +1,23 @@
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 +28,10 @@ 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));
}
}
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
@@ -32,15 +49,7 @@ 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);
}
}
}
+16
View File
@@ -6,6 +6,22 @@ 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';
}
+56 -16
View File
@@ -11,20 +11,36 @@ 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;
/** 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;
} | null | Promise<{
senderUin: number;
time: number;
random: number;
elements?: MessageElement[];
sequenceAuthoritative?: boolean;
} | null>;
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
resolveContactArk?: (contactType: string, contactId: number) => string | null | Promise<string | null>;
musicSignUrl?: string;
@@ -80,18 +96,6 @@ function isExplicitEmptyTextPlaceholder(segment: MessageSegment): boolean {
&& 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,
@@ -249,9 +253,45 @@ function requireCoordinate(
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>, options?: ParseMessageOptions): 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
@@ -476,7 +516,7 @@ function segmentPayload(seg: MessageSegment): Record<string, unknown> {
// --- Public API ---
export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
export async function parseMessage(message: unknown, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
if (typeof message === 'string') {
if (message.length === 0) throw invalidMessageShape('message must not be empty');
if (autoEscape) {
@@ -516,7 +556,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
// 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);
const elem = await segmentToElement(seg.type, data, options);
@@ -51,7 +51,7 @@ export async function runMessageStoreMigrationWorker(
port.on('message', handleControlMessage);
try {
prepareMessageStoreDatabase(data.dbPath);
await prepareMessageStoreDatabase(data.dbPath);
await migrateLegacyMedia(data.dbPath, () => cancelled);
if (cancelled) return;
port.postMessage({ kind: 'ready' } satisfies MessageStoreMigrationWorkerMessage);
@@ -63,7 +63,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',
@@ -83,7 +83,7 @@ export async function runMessageStoreMigrationWorker(
} satisfies MessageStoreMigrationWorkerMessage);
} finally {
port.off('message', handleControlMessage);
migrator?.close();
await migrator?.close();
}
}
+158 -151
View File
@@ -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,134 +38,141 @@ 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);
if (this.state.phase === 'complete') return this.getStatus();
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);
let rows = await this.readBatch(limit, this.state.cursor);
if (rows.length === 0 && this.state.cursor !== null) {
rows = await this.readBatch(limit, null);
}
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;
}
if (rows.length < limit) {
const remaining = this.countPending();
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(reportPreparation?: (progress: MessageStoreMigrationPreparation) => void): MigrationStateRow {
const existing = this.db.prepare(`
private async loadOrCreateState(reportPreparation?: (progress: MessageStoreMigrationPreparation) => void): Promise<MigrationStateRow> {
const existing = await this.db.prepare(`
SELECT phase, processed, total, cursor
FROM message_store_migration_state
WHERE name = ?
@@ -174,7 +181,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}
@@ -183,7 +190,7 @@ export class MessageStoreMigrator {
if (existing) return existing;
const countStartedAt = performance.now();
const row = this.db.prepare(`
const row = await this.db.prepare(`
SELECT COUNT(*) AS total
FROM messages
WHERE classification_version < ?
@@ -197,7 +204,7 @@ export class MessageStoreMigrator {
total,
cursor: null,
};
this.db.prepare(`
await this.db.prepare(`
INSERT INTO message_store_migration_state
(name, phase, processed, total, cursor, started_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
@@ -205,8 +212,8 @@ export class MessageStoreMigrator {
return state;
}
private countPending(): number {
const row = this.db.prepare(`
private async countPending(): Promise<number> {
const row = await this.db.prepare(`
SELECT COUNT(*) AS total
FROM messages
WHERE classification_version < ?
@@ -214,26 +221,26 @@ export class MessageStoreMigrator {
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(CLASSIFICATION_VERSION, cursor, limit)) as unknown as PendingMessageRow[];
? 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,
@@ -244,15 +251,15 @@ 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.prepare(`
const messagesTableExists = await db.prepare(`
SELECT 1 AS present
FROM sqlite_schema
WHERE type = 'table' AND name = 'messages'
`).get() !== undefined;
db.exec(`
await db.exec(`
CREATE TABLE IF NOT EXISTS messages (
message_hash INTEGER PRIMARY KEY,
is_group INTEGER NOT NULL,
@@ -268,26 +275,26 @@ 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.prepare(`
await createMigrationStateTable(db);
const row = await db.prepare(`
SELECT phase, processed, total
FROM message_store_migration_state
WHERE name = ?
`).get(MIGRATION_NAME) as MessageStoreMigrationStatus | undefined;
if (row) return row;
const pending = db.prepare(`
const pending = await db.prepare(`
SELECT COUNT(*) AS total
FROM messages
WHERE classification_version < ?
@@ -295,56 +302,56 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
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('ALTER TABLE messages ADD COLUMN sequence_authoritative INTEGER NOT NULL DEFAULT 1');
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('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)');
db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)');
db.exec('CREATE INDEX IF NOT EXISTS idx_messages_private_client_seq ON messages(is_group, session_id, client_sequence)');
db.exec('CREATE INDEX IF NOT EXISTS idx_messages_private_client_direction ON messages(is_group, session_id, client_sequence, private_direction)');
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)');
await db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)');
await db.exec('CREATE INDEX IF NOT EXISTS idx_messages_private_client_seq ON messages(is_group, session_id, client_sequence)');
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 {
const tableExists = db.prepare(`
async function hasLegacyPrivateSequenceMigration(db: SqliteDatabase): Promise<boolean> {
const tableExists = await db.prepare(`
SELECT 1 AS present
FROM sqlite_schema
WHERE type = 'table' AND name = 'message_store_migrations'
`).get() !== undefined;
if (!tableExists) return false;
return db.prepare(`
return await db.prepare(`
SELECT 1 AS applied
FROM message_store_migrations
WHERE name = ?
`).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
+78 -38
View File
@@ -1,19 +1,79 @@
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 +87,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('消息不存在或已被撤回');
const segments = Array.isArray(event.message) ? event.message : [];
@@ -42,8 +102,8 @@ export async function fetchPttText(
}
if (!file) throw new Error('消息中不包含语音');
const snapshot = 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');
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 } : await mediaStore.findRecord(file, 'legacy');
if (!cached) throw new Error('语音不在缓存中,无法转写');
const isGroup = event.message_type === 'group' || cached.isGroup;
@@ -81,25 +141,16 @@ 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;
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);
if (fresh) url = fresh;
} catch {
// Best-effort: fall back to the stored URL on any resolver failure.
}
try {
const fresh = await resolveImageUrl(cached, imageUrlResolver);
if (fresh) url = fresh;
} catch (err) {
log.warn('get_image URL refresh failed: %s', err instanceof Error ? err.message : String(err));
}
return {
@@ -115,24 +166,13 @@ 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,
};
+109 -159
View 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';
@@ -23,31 +24,11 @@ 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, type JsonObject, type JsonValue, type MessageMeta } from '../types';
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
@@ -125,12 +106,12 @@ 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 [];
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(true, groupId, limit, anchorSequence, reverseOrder);
const events = await messageStore.listSessionEvents(true, groupId, limit, anchorSequence, reverseOrder);
return events
.filter((event) => {
if (event.message_type !== 'group') return false;
@@ -153,12 +134,12 @@ 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 [];
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(false, userId, limit, anchorSequence, reverseOrder);
const events = await messageStore.listSessionEvents(false, userId, limit, anchorSequence, reverseOrder);
return events
// `session_id` is the conversation peer. Self-sent messages legitimately
// carry the bot's own `user_id`, so filtering by sender would drop them.
@@ -197,14 +178,14 @@ 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.
return getGroupMsgHistory(ref.messageStore, groupId, messageId, count, reverseOrder);
}
anchorSeq = meta.sequence;
} else {
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0;
anchorSeq = await ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0;
}
log.debug(
'group history anchor selected: group=%d source=%s anchorSeq=%d',
@@ -226,7 +207,7 @@ export async function getGroupHistory(
for (const ev of events) {
const json = await convertEvent(ref.converterCtx, ev);
if (!json || json.message_type !== 'group') 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)
}
if (out.length > 0) return out;
@@ -274,13 +255,13 @@ 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)
? await ref.messageStore.findEvent(messageId as number)
: null;
const belongsToPeer = meta?.targetId === userId
|| (meta?.targetId === ref.selfId && toHistoryInt(storedEvent?.target_id) === userId);
@@ -318,10 +299,9 @@ export async function getFriendHistory(
const sentBySelf = ev.senderUin === ref.selfId;
const json = await convertEvent(ref.converterCtx, ev);
if (!json || json.message_type !== 'private') 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.
if (ref.messageStore.isPrivateMessageRecalled(
// Conversion can await media resolution, so check again after it settles.
// Persistence also checks recalls queued while this lookup is in flight.
if (await ref.messageStore.isPrivateMessageRecalled(
userId,
clientSequence,
sentBySelf,
@@ -340,8 +320,9 @@ export async function getFriendHistory(
if (json.post_type === 'message_sent' && toHistoryInt(json.target_id) === 0) {
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(
'friend history server fetch complete: user=%d source=%s anchorSeq=%d requested=%d returned=%d',
@@ -390,7 +371,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,
@@ -402,7 +383,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
const targetId = Number.isInteger(resolvedId) && resolvedId !== 0
? resolvedId as number
: hashMessageIdInt32(replySeq, session, eventName);
if (ref.messageStore.findEvent(targetId)) return; // Tier 0: already have the full event
if (await ref.messageStore.findEvent(targetId)) return; // Tier 0: already have the full event
// Tier 1: fetch the quoted message from the server, keyed under the exact id
// the reply resolves to. Groups can query `replySeq` directly. C2C replies
@@ -439,12 +420,12 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
if (json) {
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,
@@ -457,7 +438,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
random: fetched.msgId,
timestamp: fetched.time,
});
ref.messageStore.storeEvent(
await ref.messageStore.storeEvent(
targetId,
false,
session,
@@ -487,7 +468,7 @@ 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(
await ref.messageStore.storeEvent(
targetId,
isGroup,
session,
@@ -508,7 +489,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
const placeholder = buildBackfillEvent(targetId, replySeq, quotedSender,
reply?.replyTime ?? 0, [{ type: 'text', data: { text: '[引用消息]' } }],
ref.selfId, isGroup, session);
ref.messageStore.storeEvent(
await ref.messageStore.storeEvent(
targetId,
isGroup,
session,
@@ -586,7 +567,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');
if (!hasAuthoritativeSequence(meta)) {
throw new Error('message has no authoritative QQ sequence and cannot be marked as essence');
@@ -595,30 +576,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,
@@ -652,7 +612,7 @@ async function finalizeSend(
targetId,
eventName,
);
ref.cacheMessageMeta(messageId, {
await ref.cacheMessageMeta(messageId, {
isGroup,
targetId,
sequence: receipt.sequence,
@@ -706,29 +666,16 @@ async function cacheSelfSentMessage(
timestamp,
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,
@@ -773,13 +720,12 @@ 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;
// 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,
@@ -814,7 +760,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);
@@ -838,10 +784,10 @@ export async function sendPrivateMessage(
return sendPrivateForwardMessage(ref, userId, privateForwardNodes, undefined, onSelfSent);
}
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
@@ -849,7 +795,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 = typeof event.user_id === 'number'
? event.user_id
@@ -857,7 +803,7 @@ export async function sendPrivateMessage(
const time = 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,
@@ -866,7 +812,7 @@ export async function sendPrivateMessage(
sequenceAuthoritative: meta?.sequenceAuthoritative,
};
}
const meta = ref.messageStore.findMeta(replyMessageId);
const meta = await ref.messageStore.findMeta(replyMessageId);
if (meta) {
return {
senderUin: ref.selfId,
@@ -989,7 +935,7 @@ export async function sendPrivateMessage(
tempGroupId === undefined && onSelfSent !== undefined,
);
lastResult = result;
if (result.echoEvent) onSelfSent?.(result.echoEvent);
if (result.echoEvent) await onSelfSent?.(result.echoEvent);
};
if (nonFileElements.length > 0) {
@@ -1088,13 +1034,13 @@ export async function sendGroupMessage(
return { messageId: result.messageId };
}
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 {
senderUin: typeof event.user_id === 'number'
@@ -1227,7 +1173,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
@@ -1244,7 +1190,7 @@ export async function sendPrivateForwardMessage(
[previewElement],
onSelfSent !== undefined,
);
if (result.echoEvent) onSelfSent?.(result.echoEvent);
if (result.echoEvent) await onSelfSent?.(result.echoEvent);
return { messageId: result.messageId, forwardId };
}
@@ -1274,13 +1220,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}`);
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
@@ -1288,7 +1234,7 @@ export async function forwardSingleMessage(
const parsed = await parseMessage(content, false);
if (parsed.length === 0) throw new Error('message has no content');
const elements = await prepareSingleForwardElements(ref, restoreHistoricalMedia(ref, parsed, messageId), target);
const elements = await prepareSingleForwardElements(ref, await restoreHistoricalMedia(ref, parsed, messageId), target);
let receipt;
let messageIdOut: number;
@@ -1306,7 +1252,7 @@ export async function forwardSingleMessage(
onSelfSent !== undefined,
);
messageIdOut = result.messageId;
if (result.echoEvent) onSelfSent?.(result.echoEvent);
if (result.echoEvent) await onSelfSent?.(result.echoEvent);
}
return { messageId: messageIdOut };
@@ -1320,7 +1266,7 @@ async function prepareSingleForwardElements(
const out: MessageElement[] = [];
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;
}
const resId = element.resId.trim();
@@ -1365,12 +1311,21 @@ async function expandForwardNodeForTarget(
target: { groupId?: number; userId?: number },
depth: number,
): Promise<ForwardNodePayload> {
const forwards = node.elements.filter((element): element is MessageElementOf<'forward'> => (
// 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;
if (forwards.length === 0) 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) throw new Error('nested forward id is missing');
return {
@@ -1381,7 +1336,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;
@@ -1396,21 +1351,21 @@ 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;
const snapshot = snapshots?.[index++];
if (snapshots && (!snapshot || snapshot.type !== element.type)) {
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) {
throw new Error(`historical media metadata does not match message ${messageId}`);
@@ -1418,7 +1373,7 @@ function restoreHistoricalMedia(
return restored;
}
function enrichForForward(ref: OneBotInstanceContext, element: MessageElement, snapshot?: MessageMedia): MessageElement {
async function enrichForForward(ref: OneBotInstanceContext, element: MessageElement, snapshot?: MessageMedia): Promise<MessageElement> {
if (element.type === 'forward') {
throw new Error('merged forward must be regenerated for the target chat');
}
@@ -1444,7 +1399,7 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement, s
}
if (element.type === 'image') {
const cached = snapshot?.type === 'image' ? snapshot : ref.mediaStore.findImage(lookupKey, 'legacy');
const cached = snapshot?.type === 'image' ? snapshot : await ref.mediaStore.findImage(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex || !cached.width || !cached.height || !cached.picFormat) {
throw new Error('historical image metadata is incomplete; fetch the original message again');
}
@@ -1465,7 +1420,7 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement, s
}
if (element.type === 'record') {
const cached = snapshot?.type === 'record' ? snapshot : ref.mediaStore.findRecord(lookupKey, 'legacy');
const cached = snapshot?.type === 'record' ? snapshot : await ref.mediaStore.findRecord(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error('historical voice metadata is incomplete; fetch the original message again');
}
@@ -1484,7 +1439,7 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement, s
}
if (element.type === 'video') {
const cached = snapshot?.type === 'video' ? snapshot : ref.mediaStore.findVideo(lookupKey, 'legacy');
const cached = snapshot?.type === 'video' ? snapshot : await ref.mediaStore.findVideo(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error('historical video metadata is incomplete; fetch the original message again');
}
@@ -1523,7 +1478,7 @@ export async function getForwardMessage(
// exactly issue #74 (`/get_forward_msg` image url 缺少 rkey). Image rkey
// re-signing is scene-aware via the appid in the URL (see instance-rkey).
const segments = await elementsToOneBotSegments(
ref.converterCtx, node.elements, isGroup, sessionId,
ref.converterCtx, node.elements, isGroup, sessionId, { includeReplyContent: true },
);
const sender: JsonObject = {
@@ -1547,7 +1502,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',
};
@@ -1667,15 +1622,17 @@ function isNestedNodeArray(value: JsonValue): boolean {
if (!Array.isArray(value) || value.length === 0) return false;
for (const item of value) {
const seg = asJsonObject(item);
if (!seg || String(seg.type ?? '') !== 'node') return false;
if (!seg || seg.type !== 'node') return false;
}
return true;
}
type ForwardNodeData = JsonObject & Pick<ForwardNodePayload, 'news' | 'title' | 'source' | 'summary' | 'prompt'>;
function assertForwardNodeMetadata(
nodeData: JsonObject,
index: number,
): void {
): asserts nodeData is ForwardNodeData {
for (const [field, value] of Object.entries(nodeData)) {
if (field === 'content' || field === 'message') continue;
if (value === undefined) continue;
@@ -1720,11 +1677,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;
for (const [index, item] of messages.entries()) {
const segment = asJsonObject(item);
@@ -1735,10 +1692,10 @@ 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',
);
@@ -1746,9 +1703,9 @@ 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');
}
@@ -1830,7 +1787,7 @@ async function parseForwardNodes(
);
}
assertForwardNodeMetadata(nodeData, index);
return { segment, nodeData };
return nodeData;
}
// Preserve the existing bare-node compatibility form, but require it to
@@ -1844,21 +1801,20 @@ 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(
'INVALID_FIELD',
@@ -1880,8 +1836,10 @@ async function parseForwardNodes(
'user_id',
);
}
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const elements = restoreHistoricalMedia(ref, await parseMessage(content, false), messageId);
const content = event.message ?? event.raw_message ?? '';
const elements = await restoreHistoricalMedia(ref, await parseMessage(content, false, {
forwardReply: { senderUin: userUin, time: toPositiveInt(event.time) || undefined },
}), messageId);
if (elements.length > 0) {
const messageType = event.message_type === 'group' ? 'group' : 'private';
const groupIdValue = toPositiveInt(event.group_id);
@@ -1910,7 +1868,10 @@ async function parseForwardNodes(
if (userUin <= 0) throw new Error('forward node user_id/uin is required');
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;
@@ -1940,33 +1901,22 @@ 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) {
throw new Error(`forward node content is empty: ${userUin}`);
}
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;
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;
for (const field of ['title', 'source', 'summary', 'prompt'] as const) {
if (nodeData[field] !== undefined) node[field] = nodeData[field];
}
if (time !== undefined) node.time = time;
if (innerForward) node.innerForward = innerForward;
nodes.push(node);
}
+99 -78
View File
@@ -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,64 +79,80 @@ export class ReactionStore {
operatorUin: number,
operatorUid: string,
setAt: number,
): void {
if (!groupId || !msgSeq || !emojiId || !operatorUin) return;
this.stmtUpsert.run(groupId, msgSeq, emojiId, emojiType, operatorUin, operatorUid, setAt);
): Promise<void> {
return this.db.serial(async () => {
await this.initialization;
if (!groupId || !msgSeq || !emojiId || !operatorUin) return;
await this.stmtUpsert.run(groupId, msgSeq, emojiId, emojiType, operatorUin, operatorUid, setAt);
});
}
recordRemove(
async recordRemove(
groupId: number,
msgSeq: number,
emojiId: string,
operatorUin: number,
): void {
if (!groupId || !msgSeq || !emojiId || !operatorUin) return;
this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin);
): Promise<void> {
return this.db.serial(async () => {
await this.initialization;
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();
}
}
+46
View File
@@ -0,0 +1,46 @@
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 }] : [];
}
+4 -20
View File
@@ -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);
}
+10
View File
@@ -67,4 +67,14 @@ 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');
});
});
+1 -130
View File
@@ -10,7 +10,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');
@@ -477,135 +477,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', () => {
+6 -4
View File
@@ -52,17 +52,19 @@ 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 });
}
});
+68 -4
View File
@@ -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];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
@@ -36,9 +37,13 @@ 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;
}
@@ -263,6 +268,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' } }],
@@ -280,6 +286,60 @@ 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');
@@ -291,6 +351,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' } }],
@@ -342,6 +403,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' } }],
@@ -364,6 +426,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: [
@@ -443,6 +506,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,
@@ -483,7 +547,7 @@ describe('forward — nested {type:"node"} content', () => {
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} 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 } },
@@ -530,7 +594,7 @@ describe('forward — nested {type:"node"} content', () => {
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} 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' } },
+181
View File
@@ -0,0 +1,181 @@
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/);
});
});
@@ -286,8 +286,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');
@@ -299,8 +299,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');
});
});
+78 -51
View File
@@ -27,7 +27,7 @@ const image = {
function converter(media: MediaStore): ConverterContext {
const indexer = new MediaIndexer(media);
return { selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null, messageIdResolver: null,
mediaSegmentSink: (...args) => indexer.remember(...args) };
mediaSegmentSink: async (...args) => await indexer.remember(...args) };
}
function context(messages: MessageStore, media: MediaStore) {
const sendGroup = vi.fn(async () => ({ sequence: 234, clientSequence: 0, random: 1, timestamp: 1700000001 }));
@@ -44,7 +44,9 @@ describe('durable historical media', () => {
it.each(['image', 'record', 'video'] as const)('forwards %s after cache churn, alias replacement and reopen', 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', fileName: 'same.png', fileSize: 120,
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: 32, height: 24,
picFormat: 1001, duration: 3, voiceFormat: 1, videoFormat: 0 } as MessageElement;
@@ -54,18 +56,20 @@ describe('durable historical media', () => {
msgSeq: 10, msgId: 10, 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++) {
await elementsToOneBotSegments(converter(media), [{ ...element, md5Hex: 'cc'.repeat(16) }], 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();
messages = new MessageStore(dbPath); media = new MediaStore(dbPath, 2);
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);
await forwardSingleMessage(ref, 42, { groupId: 999 });
@@ -76,33 +80,36 @@ describe('durable historical media', () => {
expect(upload.mock.calls[0]?.[0]).toEqual([expect.objectContaining({
elements: [expect.objectContaining({ type, md5Hex: image.md5Hex, noByteFallback: true })],
})]);
expect(messages.findEvent(42)?.message_id).toBe(42);
} finally { media.close(); messages.close(); }
expect((await messages.findEvent(42))?.message_id).toBe(42);
} finally { await media.close(); await messages.close(); }
});
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 {
const segments = await elementsToOneBotSegments(converter(media), [{ type: 'image',
...image, url: `base64://${'A'.repeat(100000)}`, imageUrl: '', fileId: 'same.png' }], true, 123);
const event = { time: 1, message: segments };
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://');
} finally { db.close(); media.close(); messages.close(); }
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(); 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), [{ type: 'image', fileId: 'test' }], true, 123))
.rejects.toThrow();
});
@@ -110,84 +117,95 @@ 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(converter(media), [{ type: 'image', fileId: image.file }], 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(); }
} finally { 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);
await save({ type: 'image', fileId: image.file, md5Hex: image.md5Hex, width: 0, height: 0 });
await expect(save({ ...complete, md5Hex: 'cc'.repeat(16) })).rejects.toThrow('conflicting');
media.close(); messages.close();
messages = new MessageStore(dbPath); media = new MediaStore(dbPath);
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);
await forwardSingleMessage(ref, 42, { groupId: 999 });
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: image.width, height: image.height,
})]);
} finally { media.close(); messages.close(); }
} finally { 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(converter(media), [
{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 },
], 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([{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 }]);
} finally { media.close(); messages.close(); }
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 { 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);
} finally { db.close(); media.close(); }
await expect(async () => await media.findImage(image.file)).rejects.toThrow('invalid persisted');
expect((await media.size()).images).toBe(1);
} finally { db.close(); await media.close(); }
});
it.each(['image', 'record', 'video'] as const)('keeps migrated %s history independent of new same-named resources', async type => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
await old.initialization;
const element = { type, fileId: 'same.png', fileName: 'same.png', fileSize: 120,
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: 32, height: 24,
picFormat: 1001, duration: 3, voiceFormat: 1, 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',
message: [{ type, data: { file: image.file } }],
});
@@ -196,34 +214,39 @@ describe('durable historical media', () => {
fs.rmSync(legacyPath);
await migrateLegacyMedia(dbPath);
const media = new MediaStore(dbPath);
await media.initialization;
try {
await elementsToOneBotSegments(converter(media), [{ ...element, md5Hex: 'cc'.repeat(16) }], true, 123);
const { ref, sendGroup } = context(messages, media);
await forwardSingleMessage(ref, 42, { groupId: 999 });
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({ md5Hex: image.md5Hex })]);
} finally { media.close(); messages.close(); }
} finally { await media.close(); await messages.close(); }
});
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();
const old = new MediaStore(legacyPath);
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'").run(JSON.stringify({ ...image, file: 'broken' }));
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();
const old = new MediaStore(legacyPath);
await old.initialization; await old.close();
const inline = `base64://${'Z'.repeat(100000)}`;
const source = new DatabaseSync(legacyPath);
source.prepare("INSERT INTO media_entries VALUES ('image', ?, ?, 1)")
@@ -232,25 +255,29 @@ describe('durable historical media', () => {
source.close();
await migrateLegacyMedia(dbPath);
const media = new MediaStore(dbPath);
await media.initialization;
try {
expect(media.findImage(inline)).toMatchObject({ md5Hex: image.md5Hex, url: '', imageUrl: '' });
expect(JSON.stringify(media.findImage(inline))).not.toContain('base64://');
} finally { media.close(); }
expect(await media.findImage(inline)).toMatchObject({ md5Hex: image.md5Hex, url: '', imageUrl: '' });
expect(JSON.stringify(await media.findImage(inline))).not.toContain('base64://');
} finally { await media.close(); }
});
it('resumes a cancelled migration from its committed batch cursor', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
for (let i = 0; i < 205; i++) old.rememberImage({ ...image, file: `entry-${i}` });
old.close();
await old.initialization;
for (let i = 0; i < 205; i++) await old.rememberImage({ ...image, file: `entry-${i}` });
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();
});
});
+30 -16
View File
@@ -1,3 +1,4 @@
import { mapWithConcurrency } from '@snowluma/common/concurrency';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
GROUP_MESSAGE_EVENT,
@@ -56,18 +57,19 @@ 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 () => {
const fetchHistory = vi.fn(async (...args: unknown[]) =>
args[4] === false ? [groupMessage(500), groupMessage(501)] : [groupMessage(499), groupMessage(500)]);
messageStore.storeMeta(-123456789, {
await messageStore.storeMeta(-123456789, {
isGroup: true,
targetId: GROUP_ID,
sequence: 500,
@@ -96,7 +98,7 @@ describe('history direction plumbing', () => {
args[4] === false
? [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,
@@ -130,7 +132,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,
@@ -166,7 +168,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,
@@ -210,11 +212,23 @@ 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);
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);
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);
});
}
const fetchLatestHistory = vi.fn(async () => [
friendMessage(63213, FRIEND_ID, 32742),
friendMessage(63214, SELF_ID, 32743),
@@ -232,12 +246,12 @@ describe('history direction plumbing', () => {
const messages = await getFriendHistory(ref, FRIEND_ID, undefined, 20);
expect(messages.map((message) => message.message_seq)).toEqual([32743]);
expect(messageStore.listSessionEvents(false, FRIEND_ID, 20))
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',
@@ -265,14 +279,14 @@ describe('history direction plumbing', () => {
it('keeps latest-page group requests backward-compatible without an anchor', async () => {
const fetchHistory = vi.fn(async (...args: unknown[]) =>
args[4] === true ? [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(2, true, GROUP_ID, 1799283572, GROUP_MESSAGE_EVENT, {
await messageStore.storeEvent(2, true, GROUP_ID, 1799283572, GROUP_MESSAGE_EVENT, {
post_type: 'message_sent',
message_type: 'group',
group_id: GROUP_ID,
@@ -298,7 +312,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(2, true, GROUP_ID, 1799283572, GROUP_MESSAGE_EVENT, {
await messageStore.storeEvent(2, true, GROUP_ID, 1799283572, GROUP_MESSAGE_EVENT, {
post_type: 'message_sent',
message_type: 'group',
group_id: GROUP_ID,
@@ -322,7 +336,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,
+49 -36
View File
@@ -76,13 +76,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 });
},
};
@@ -132,9 +133,9 @@ function makeBridge(options: {
} as unknown as BridgeInterface;
}
const resources: Array<ReturnType<typeof makeStore>> = [];
afterEach(() => {
for (const resource of resources.splice(0)) resource.close();
const resources: Array<Awaited<ReturnType<typeof makeStore>>> = [];
afterEach(async () => {
for (const resource of resources.splice(0)) await resource.close();
vi.restoreAllMocks();
});
@@ -144,7 +145,7 @@ describe('login history sync', () => {
const coordinator = new LoginHistorySyncCoordinator({
sleep: async (ms) => { delays.push(ms); },
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const bridge = makeBridge();
@@ -201,7 +202,7 @@ describe('login history sync', () => {
groupPage,
privateLatestPage,
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
@@ -241,7 +242,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 });
@@ -262,7 +263,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 = {
@@ -273,7 +274,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({
@@ -303,9 +304,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',
@@ -313,7 +314,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,
@@ -323,8 +324,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({
@@ -354,9 +355,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,
@@ -366,7 +367,7 @@ 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({
@@ -396,9 +397,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,
@@ -469,7 +470,7 @@ describe('login history sync', () => {
})),
groupPage,
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
@@ -503,7 +504,7 @@ describe('login history sync', () => {
})),
groupPage,
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
@@ -527,16 +528,28 @@ describe('login history sync', () => {
.resolves.toHaveLength(1);
});
it('does not restore a private message hidden by a recall tombstone', async () => {
const resource = makeStore();
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);
resource.store.recordPrivateRecall(
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);
});
}
const bridge = makeBridge({
groupCount: 0,
probe: vi.fn(async () => ({
@@ -570,7 +583,7 @@ describe('login history sync', () => {
});
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,
@@ -613,7 +626,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,
@@ -655,8 +668,8 @@ describe('login history sync', () => {
releaseFirst = () => resolve({ groups: [], privateUsers: [] });
}));
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 });
@@ -690,9 +703,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();
@@ -734,7 +747,7 @@ describe('login history sync', () => {
const groupPage = vi.fn(() => new Promise<GroupMessage[]>((resolve) => {
releasePage = () => resolve([groupMessage(30001, 1)]);
}));
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const bridge = makeBridge({
friendCount: 0,
@@ -765,7 +778,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();
@@ -813,7 +826,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();
@@ -315,7 +315,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',
@@ -327,14 +327,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,
@@ -346,18 +346,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],
@@ -369,7 +369,7 @@ describe('buildApiContext message-store passthroughs', () => {
messageStore: { listReadSessions },
});
expect(api.listReadSessions()).toEqual({
expect(await api.listReadSessions()).toEqual({
groupIds: [710101, 710102],
privateUserIds: [50001],
});
@@ -999,7 +999,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' };
+25 -148
View File
@@ -668,177 +668,54 @@ 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' },
}), { updateRecordUrl }),
'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();
});
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');
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();
});
it('refetches a group ptt url and writes it back under the lookup key', async () => {
const mediaNode = { fileUuid: 'group-uuid', storeId: 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');
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();
const url = `https://ptt.example/${isGroup ? 'group' : 'private'}-fresh`;
await expect(getRecordInfo(
fakeBridge({ getPttUrl, getPrivatePttUrl }),
fakeRecordStore(cachedRecord({
url: '',
isGroup: false,
mediaNode,
}), { updateRecordUrl }),
fakeRecordStore(cachedRecord({ isGroup, sessionId: GROUP_ID, 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');
)).resolves.toEqual({ file: url, url, file_size: '4096', file_name: 'voice.silk' });
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('does not write back an empty refetch result', async () => {
const updateRecordUrl = vi.fn();
const getPrivatePttUrl = vi.fn(async () => '');
it('rejects missing resource metadata even when an old URL exists', async () => {
await expect(getRecordInfo(fakeBridge(), fakeRecordStore(cachedRecord()), 'voice.silk'))
.rejects.toThrow('record media metadata is missing');
});
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',
)).resolves.toEqual({
+12 -12
View File
@@ -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,7 @@ 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 +97,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 +116,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();
+63 -59
View File
@@ -87,9 +87,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,
@@ -101,16 +101,16 @@ 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('https://example.com/abc.png');
expect(store.findImage('missing.png')).toBeNull();
expect(store.findImage('')).toBeNull();
store.close();
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(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',
@@ -123,16 +123,16 @@ 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('https://example.com/voice.amr');
expect(store.findRecord('nope')).toBeNull();
store.close();
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(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: '',
@@ -144,20 +144,21 @@ 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('https://refreshed.example.com/voice.amr');
expect(store.findRecord('uuid-base64-fake')?.url).toBe('https://refreshed.example.com/voice.amr');
store.close();
expect((await store.findRecord('silk_test.amr'))?.url).toBe('https://refreshed.example.com/voice.amr');
expect((await store.findRecord('uuid-base64-fake'))?.url).toBe('https://refreshed.example.com/voice.amr');
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,
@@ -168,26 +169,27 @@ 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,
@@ -199,19 +201,19 @@ describe('MediaStore basic semantics', () => {
sessionId: GROUP_ID,
});
}
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(store.findImage('file-0.png')?.fileSize).toBe(0);
for (let i = 0; i < 200; i++) expect((await store.findImage(`file-${i}.png`))?.fileSize).toBe(i);
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,
@@ -226,7 +228,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));
@@ -235,7 +237,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);
@@ -244,10 +246,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,
@@ -259,18 +261,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,
@@ -281,12 +283,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 });
@@ -316,9 +318,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);
@@ -396,16 +399,17 @@ 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,
@@ -417,7 +421,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,
@@ -436,22 +440,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: {
@@ -123,16 +116,26 @@ 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 () => {
@@ -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,14 @@ 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),
@@ -40,6 +42,7 @@ function createControlPort(): {
postMessage(message: MessageStoreMigrationWorkerMessage) {
if (message.kind === 'preparation') preparations.push(message.progress);
else messages.push(message);
for (const check of [...waiters]) check();
},
} as unknown as MessagePort,
messages,
@@ -47,14 +50,26 @@ 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 (
@@ -132,7 +147,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);
@@ -144,12 +159,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,
@@ -160,7 +175,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' });
@@ -174,7 +189,7 @@ describe('runMessageStoreMigrationWorker', () => {
{
kind: 'progress',
status: { phase: 'complete', processed: 0, total: 0 },
elapsedMs: 0,
elapsedMs: expect.any(Number),
},
]);
});
@@ -188,7 +203,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 {
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
@@ -212,11 +227,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;
@@ -224,7 +239,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,
@@ -233,11 +248,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');
@@ -249,10 +264,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;
@@ -262,10 +277,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,
@@ -274,10 +289,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;
@@ -287,7 +302,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',
@@ -298,7 +313,7 @@ describe('runMessageStoreMigrationWorker', () => {
if (last?.kind === 'progress') {
expect(last.elapsedMs).toBeGreaterThanOrEqual(0);
}
expect(inspectMessageStoreMigration(dbPath)).toEqual({
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
phase: 'complete',
processed: 201,
total: 201,
@@ -308,19 +323,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),
},
]);
@@ -333,10 +348,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,
@@ -366,7 +381,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);
@@ -378,13 +393,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
@@ -397,14 +412,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();
});
@@ -416,7 +431,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,3 +1,4 @@
import { SqliteDatabase } from '@snowluma/sqlite';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -13,10 +14,10 @@ describe('message history migration scans', () => {
let db: DatabaseSync;
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);
await prepareMessageStoreDatabase(dbPath);
db = new DatabaseSync(dbPath);
const insert = db.prepare(`INSERT INTO messages
(message_hash, is_group, session_id, sequence, client_sequence, event_name, data, media_data, classification_version)
@@ -32,9 +33,9 @@ describe('message history migration scans', () => {
db.exec('COMMIT');
});
afterEach(() => {
afterEach(async () => {
vi.restoreAllMocks();
migrator?.close();
await migrator?.close();
migrator = undefined;
db.close();
fs.rmSync(directory, { recursive: true, force: true });
@@ -60,15 +61,16 @@ describe('message history migration scans', () => {
}
}
it('uses pending rows for the actual count and ordered batch queries without changing history', () => {
it('uses pending rows for the actual count and ordered batch queries without changing history', async () => {
const before = 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 });
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 });
expectPendingQueryPlans(queries);
expect(db.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1').get()).toEqual({ n: 0 });
expect(db.prepare('SELECT message_hash, data, media_data FROM messages ORDER BY message_hash').all()).toEqual(before);
@@ -79,68 +81,78 @@ 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(); migrator = undefined;
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}`);
migrator = new MessageStoreMigrator(dbPath);
await migrator.initialization;
expect(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(); migrator = undefined;
await migrator.initialization;
await migrator.runBatch(1);
await migrator.close(); migrator = undefined;
const schemaVersion = db.prepare('PRAGMA schema_version').get();
migrator = new MessageStoreMigrator(dbPath);
await migrator.initialization;
expect(db.prepare('PRAGMA schema_version').get()).toEqual(schemaVersion);
expect(migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
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', () => {
it('revisits rows left behind the cursor after a concurrent update prevented classification', async () => {
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 });
await migrator.initialization;
expect(await 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 });
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()).toEqual({ n: 0 });
expect(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(); migrator = undefined;
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');
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.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, sql) {
let failedDb: SqliteDatabase | undefined;
vi.spyOn(SqliteDatabase.prototype, 'exec').mockImplementation(async function (this: SqliteDatabase, sql) {
if (sql.includes(pendingIndex)) { failedDb = this; throw failure; }
return originalExec.call(this, sql);
});
expect(() => { migrator = new MessageStoreMigrator(dbPath); }).toThrow(failure);
await expect(async () => { migrator = new MessageStoreMigrator(dbPath);
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()).toEqual({ n: 3 });
});
});
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more