Compare commits

...
Author SHA1 Message Date
DrSmoothl adf6b6a3b4 test(protocol): isolate upload staging fixtures
Give cleanup tests a dedicated staging directory so they cannot remove files used by parallel upload tests.

Refs #520
2026-10-13 10:08:20 +08:00
DrSmoothl 5a0b26648c test(onebot): use async connections in migration fixtures
Use the production SQLite driver for concurrent migration checks while preserving history, index, and restart assertions.

Refs #520
2026-10-13 10:08:15 +08:00
DrSmoothl a50df4e526 style(webui): preserve hook lint suppression after formatting
Keep the existing dependency annotation on the line checked by ESLint.
2026-10-13 10:00:55 +08:00
DrSmoothl 505b4772d6 test(core): align lock fixtures with async persistence
Exercise persistence failures and retries with the production database connection, and finish fixture writes before acquiring test locks.

Refs #520
2026-10-13 10:00:55 +08:00
DrSmoothl 927e03d435 test(sqlite): verify real lock contention across platforms
Use consistent database connections and prove write contention before checking event-loop responsiveness. Keep cleanup deterministic when an assertion fails.

Refs #520
2026-10-13 09:57:25 +08:00
DrSmoothl 056188d63d chore: resolve async SQLite merge conflicts
Integrate the current development branch, preserve the album comment fixes, and align the changes with repository formatting and dependency tooling.
2026-10-13 09:55:16 +08:00
手瓜一十雪 e699351f90 feat: adopt async SQLite and improve messaging and runtime diagnostics 2026-10-12 15:44:55 +08:00
170 changed files with 7747 additions and 3912 deletions

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` 应满足上述版本要求,否则安装会直接失败。
### 拉代码、装依赖、跑起来
@@ -197,7 +204,7 @@ Prettier,并按需开启保存时格式化。
- 单测放在被测代码同包的 `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
@@ -48,28 +48,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"
}
}
+5
View File
@@ -7,3 +7,8 @@ export {
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 -8
View File
@@ -28,8 +28,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 {
@@ -56,7 +55,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) => {
@@ -101,14 +100,14 @@ 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';
return null;
}
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
@@ -124,7 +123,7 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
};
}
return 'fallback';
return null;
}
async function getQqProcessCount(): Promise<number> {
@@ -242,7 +241,7 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
for (const port of ptPortsToTry) {
const ptResult = await tryPtloginMethod(port);
if (ptResult !== 'fallback') {
if (ptResult !== null) {
return ptResult;
}
}
@@ -252,7 +251,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,
};
+123
View File
@@ -0,0 +1,123 @@
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;
}
+15 -3
View File
@@ -37,7 +37,10 @@ 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({
@@ -51,12 +54,21 @@ 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,152 @@
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;
@@ -395,10 +396,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;
}
+9 -10
View File
@@ -71,18 +71,17 @@ export class SingleFlightCache<K, V> {
}
const task = (async () => {
try {
const value = await this.load(key);
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);
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;
}
@@ -147,4 +147,18 @@ 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 -13
View File
@@ -10,7 +10,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';
@@ -40,10 +39,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 {
@@ -296,7 +291,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
@@ -430,7 +425,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.
@@ -724,8 +719,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 });
}
@@ -784,8 +778,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 });
}
@@ -794,8 +787,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 -17
View File
@@ -1,20 +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
+30 -10
View File
@@ -37,6 +37,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;
@@ -142,7 +144,11 @@ 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();
@@ -151,14 +157,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
@@ -303,7 +310,14 @@ 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 {
@@ -500,6 +514,12 @@ 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;
+42 -2
View File
@@ -19,6 +19,44 @@ 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[] = [];
@@ -378,7 +416,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;
}
@@ -389,7 +427,9 @@ export class BridgeManager {
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);
+13 -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');
@@ -51,6 +52,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',
@@ -196,6 +198,16 @@ async function main() {
);
}
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);
};
@@ -0,0 +1,55 @@
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,
@@ -1384,6 +1385,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,
@@ -367,7 +368,3 @@ function cleanupFailureItem(failure: StorageCleanupResult['failures'][number]):
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 } from '@snowluma/common/log-file-transport';
import {
DEFAULT_LOG_MAX_TOTAL_MB,
@@ -322,7 +323,3 @@ function assertPersistedSettings(runtime: RuntimeConfig, expected: LogStorageSet
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<
@@ -12,10 +13,6 @@ export type SettingsPatch = Partial<
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' };
@@ -38,6 +38,7 @@ describe('forward metadata through upload and cached reads', () => {
const ctx = {
selfId: 10001,
bridge: {
identity: { nickname: 'SnowLuma' },
apis: {
forward,
message: {
@@ -51,7 +52,7 @@ describe('forward metadata through upload and cached reads', () => {
},
},
},
messageStore: { findEvent: () => null, findMedia: () => null },
messageStore: { findEvent: () => null, findMedia: () => null, storeEvent: vi.fn() },
cacheMessageMeta: vi.fn(),
converterCtx: {
selfId: 10001,
@@ -104,9 +105,7 @@ describe('forward metadata through upload and cached reads', () => {
if (nested) {
expect(
(await api.getForwardMsg(`metadata-true-${enrich}-1`))[0]!.sender,
).toMatchObject({
title: 'inner title',
});
).toMatchObject({ title: 'inner title' });
}
const fetched = await forward.fetch(forwardId!);
@@ -0,0 +1,225 @@
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
@@ -233,6 +233,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,
@@ -250,7 +251,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();
}
});
@@ -121,7 +121,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]);
@@ -129,7 +129,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[] = [
{
@@ -155,7 +155,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', () => [
@@ -43,15 +43,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', () => [
@@ -63,7 +63,7 @@ describe('Bridge online-device snapshot', () => {
},
]);
bridge.onPacket(packet(1));
await bridge.onPacket(packet(1));
const snapshot = bridge.getOnlineClients();
expect(snapshot).not.toBeNull();
expect(snapshot?.[0]).not.toBe(source);
@@ -73,7 +73,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();
});
});
@@ -103,7 +103,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 () => {
@@ -125,7 +125,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 () => {
@@ -140,7 +140,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
@@ -203,7 +203,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',
@@ -214,16 +214,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',
@@ -233,10 +233,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',
@@ -246,20 +246,20 @@ 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]');
});
});
+209 -120
View File
@@ -3,6 +3,7 @@ import fs from 'fs';
import { DatabaseSync } from 'node:sqlite';
import path from 'path';
import { subscribeLogs } from '@snowluma/common/logger';
import { SqliteDatabase } from '@snowluma/sqlite';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
@@ -31,20 +32,19 @@ function cleanupDb(dbPath: string): void {
}
}
function holdWriteLock(dbPath: string): () => void {
const locker = new DatabaseSync(dbPath);
locker.exec('PRAGMA busy_timeout = 0');
locker.exec('BEGIN IMMEDIATE');
async function holdWriteLock(dbPath: string): Promise<() => Promise<void>> {
const locker = new SqliteDatabase(dbPath, { busyTimeout: 0 });
await locker.exec('BEGIN IMMEDIATE');
let released = false;
return () => {
return async () => {
if (released) {
return;
}
released = true;
locker.exec('ROLLBACK');
locker.close();
await locker.exec('ROLLBACK');
await locker.close();
};
}
@@ -84,21 +84,52 @@ 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');
@@ -106,28 +137,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);
@@ -177,8 +210,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<{
@@ -188,52 +222,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,
@@ -245,37 +284,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()]);
@@ -283,18 +325,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,
@@ -306,13 +349,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();
}
});
@@ -334,7 +378,8 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-recovery');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
let closed = false;
try {
@@ -348,6 +393,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,
@@ -358,6 +404,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,
@@ -365,8 +412,9 @@ describe('IdentityService', () => {
});
expect(identity.persistenceStatus.nextRetryAt! - Date.now()).toBe(500);
releaseLock();
await releaseLock();
await vi.advanceTimersByTimeAsync(500);
await identity.flush();
expect(identity.persistenceStatus).toMatchObject({
state: 'healthy',
@@ -374,17 +422,18 @@ 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();
await releaseLock();
if (!closed) {
identity.close();
await identity.close();
}
}
});
@@ -393,7 +442,8 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-order');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
let closed = false;
try {
@@ -418,20 +468,21 @@ describe('IdentityService', () => {
expect(identity.findFriend(11111)).toBeNull();
expect(identity.findFriend(22222)?.uid).toBe('u_second');
releaseLock();
await 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();
await releaseLock();
if (!closed) {
identity.close();
await identity.close();
}
}
});
@@ -440,10 +491,12 @@ 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]);
const releaseLock = holdWriteLock(dbPath);
await identity.flush();
const releaseLock = await holdWriteLock(dbPath);
const observed = { ...member, card: 'accepted' };
try {
@@ -451,16 +504,17 @@ describe('IdentityService', () => {
observed.card = 'caller-mutated';
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('accepted');
releaseLock();
await 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 releaseLock();
await identity.close();
}
});
@@ -468,10 +522,12 @@ 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]);
const releaseLock = holdWriteLock(dbPath);
await identity.flush();
const releaseLock = await holdWriteLock(dbPath);
try {
identity.updateGroupMember(GROUP_ID, { ...member, card: 'pending-card' });
@@ -480,17 +536,18 @@ describe('IdentityService', () => {
expect(identity.findGroup(GROUP_ID)?.groupName).toBe('refreshed-group');
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('pending-card');
releaseLock();
await 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 releaseLock();
await identity.close();
}
});
@@ -498,9 +555,11 @@ 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);
await identity.flush();
const releaseLock = await holdWriteLock(dbPath);
try {
identity.rememberRequestIdentity({ uid: 'u_new_for_uin', uin: 22001 });
@@ -511,17 +570,18 @@ describe('IdentityService', () => {
expect(identity.findUinByUid('u_old_for_uin')).toBeNull();
expect(identity.findUidByUin(22002)).toBeNull();
releaseLock();
await 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 releaseLock();
await identity.close();
}
});
@@ -529,7 +589,8 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-capacity');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
try {
const capacity = identity.persistenceStatus.queueCapacity;
@@ -561,9 +622,9 @@ describe('IdentityService', () => {
});
expect(identity.persistenceStatus.lastError).toMatch(/queue full/i);
} finally {
releaseLock();
await releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
}
});
@@ -571,7 +632,8 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-exhausted');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
const seen: Array<{ level: string; message: string }> = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'Identity' && entry.uin === Number(SELF_UIN)) {
@@ -590,8 +652,11 @@ 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({
@@ -655,10 +720,11 @@ describe('IdentityService', () => {
expect(skipLogs).toHaveLength(2);
expect(skipLogs[1]?.message).toMatch(/suppressed=50/);
releaseLock();
identity.close();
await releaseLock();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.persistenceStatus).toMatchObject({
state: 'healthy',
suspended: false,
@@ -668,23 +734,25 @@ 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 releaseLock();
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);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
identity.rememberFriends([
{
@@ -696,8 +764,8 @@ describe('IdentityService', () => {
]);
expect(identity.persistenceStatus.pendingWrites).toBe(1);
releaseLock();
identity.close();
await releaseLock();
await identity.close();
expect(identity.persistenceStatus).toMatchObject({
state: 'closed',
@@ -707,15 +775,17 @@ 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);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
const seen: Array<{ level: string; message: string }> = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'Identity' && entry.uin === Number(SELF_UIN)) {
@@ -734,7 +804,7 @@ describe('IdentityService', () => {
]);
expect(identity.persistenceStatus.pendingWrites).toBe(1);
identity.close();
await identity.close();
expect(identity.persistenceStatus).toMatchObject({
state: 'closed',
@@ -754,8 +824,8 @@ describe('IdentityService', () => {
);
} finally {
unsubscribe();
releaseLock();
identity.close();
await releaseLock();
await identity.close();
}
});
@@ -763,8 +833,9 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('close-failure');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
const database = (identity as unknown as { db: DatabaseSync }).db;
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
const database = (identity as unknown as { db: SqliteDatabase }).db;
const closeSpy = vi.spyOn(database, 'close').mockImplementationOnce(() => {
throw new Error('injected close failure');
});
@@ -780,7 +851,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,
@@ -799,31 +871,33 @@ describe('IdentityService', () => {
expect(identity.persistenceStatus.pendingWrites).toBe(2);
closeSpy.mockRestore();
releaseLock();
await 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 releaseLock();
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,
@@ -916,39 +990,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');
@@ -968,23 +1044,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,
@@ -995,11 +1073,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');
@@ -1009,61 +1087,66 @@ 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: '' },
]);
@@ -1071,11 +1154,12 @@ describe('IdentityService', () => {
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();
@@ -1083,37 +1167,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,
@@ -1125,18 +1212,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();
}
});
});
@@ -1369,6 +1457,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 () => {
@@ -1379,6 +1468,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,63 @@
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',
);
});
});
@@ -10,16 +10,15 @@ const { SUPPORTED_NODE_RANGE, isSupportedNodeVersion } =
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);
@@ -108,6 +102,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) => ({
@@ -146,7 +141,7 @@ const BaseConfig = (source_map: boolean = false) =>
},
build: {
sourcemap: source_map,
target: 'esnext',
target: 'node24',
minify: false,
lib: {
entry: {
@@ -156,22 +151,9 @@ const BaseConfig = (source_map: boolean = false) =>
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",
+8 -4
View File
@@ -252,10 +252,14 @@ async function execute(
);
}
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) {
+19
View File
@@ -101,6 +101,25 @@ 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',
+20 -13
View File
@@ -95,19 +95,26 @@ describe('messageStore — SQLite writes per send', () => {
// branch which is a different cost profile.
let id1 = 100_000;
let id2 = 200_000;
bench('storeMeta', () => {
store.storeMeta(id1++, META);
bench('storeMeta', async () => {
await store.storeMeta(id1++, META);
});
bench('storeEvent (JSON payload ~250 bytes)', () => {
store.storeEvent(id2++, true, META.targetId, META.sequence, META.eventName, SAMPLE_EVENT);
bench('storeEvent (JSON payload ~250 bytes)', async () => {
await store.storeEvent(
id2++,
true,
META.targetId,
META.sequence,
META.eventName,
SAMPLE_EVENT,
);
});
});
describe('messageStore — read paths', () => {
describe('messageStore — read paths', async () => {
// Seed a small set of records so findEvent / findMeta have hits.
for (let i = 0; i < 100; i++) {
store.storeMeta(500_000 + i, META);
store.storeEvent(
await store.storeMeta(500_000 + i, META);
await store.storeEvent(
600_000 + i,
true,
META.targetId,
@@ -117,13 +124,13 @@ describe('messageStore — read paths', () => {
);
}
bench('findMeta (hit)', () => {
store.findMeta(500_050);
bench('findMeta (hit)', async () => {
await store.findMeta(500_050);
});
bench('findMeta (miss)', () => {
store.findMeta(9_999_999);
bench('findMeta (miss)', async () => {
await store.findMeta(9_999_999);
});
bench('findEvent (hit, JSON.parse on read)', () => {
store.findEvent(600_050);
bench('findEvent (hit, JSON.parse on read)', async () => {
await store.findEvent(600_050);
});
});
+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"
}
}
+33 -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';
@@ -398,6 +399,13 @@ function primitiveText(value: unknown): string {
return '';
}
const forwardMessagesField = f
.message()
.optional()
.describe(
'转发节点数组;节点 content 内的 reply.data.message 可提供自定义引用内容(字符串或消息段),qq/time/seq 可选;仅用于转发内引用预览。',
);
const forwardPreviewParams = {
source: f.string().optional(),
summary: f.string().optional(),
@@ -451,7 +459,7 @@ async function groupTodoRun(
ctx: ApiActionContext,
op: (groupId: number, msgSeq: bigint) => Promise<void>,
) {
const meta = ctx.getMessageMeta(p.message_id);
const meta = await ctx.getMessageMeta(p.message_id);
if (!meta) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
@@ -624,7 +632,7 @@ export const actions = [
.filter((message): message is GroupEssenceMessage => message !== null)
.map((message) => projectEssenceMessage(message, p.group_id));
ctx.cacheMessageMetas(
await ctx.cacheMessageMetas(
projections.map(({ messageId, meta }) => ({
messageId,
meta,
@@ -649,7 +657,7 @@ export const actions = [
is_set: f.bool().default(true),
},
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
const meta = await ctx.getMessageMeta(p.message_id);
if (!meta || !meta.isGroup) {
return failedResponse(
@@ -829,7 +837,7 @@ export const actions = [
group_id: f.groupId().optional(),
},
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
const meta = await ctx.getMessageMeta(p.message_id);
if (!meta || !meta.isGroup) {
return failedResponse(
@@ -858,7 +866,7 @@ export const actions = [
user_id: f.userId().optional(),
},
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
const meta = await ctx.getMessageMeta(p.message_id);
if (!meta || meta.isGroup) {
return failedResponse(
@@ -887,7 +895,7 @@ export const actions = [
target_id: f.uint().optional(),
},
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
const meta = await ctx.getMessageMeta(p.message_id);
if (!meta) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
@@ -989,8 +997,8 @@ export const actions = [
name: 'upload_forward_msg',
summary: '上传转发消息',
params: {
messages: f.message().optional(),
message: f.message().optional(),
messages: forwardMessagesField,
message: forwardMessagesField,
group_id: f.groupId().optional(),
},
run: async (p, ctx) => {
@@ -1021,8 +1029,8 @@ export const actions = [
name: 'upload_foward_msg',
summary: '上传转发消息(别名拼写)',
params: {
messages: f.message().optional(),
message: f.message().optional(),
messages: forwardMessagesField,
message: forwardMessagesField,
group_id: f.groupId().optional(),
},
run: async (p, ctx) => {
@@ -1072,6 +1080,8 @@ export const actions = [
name: 'get_record',
summary: '获取语音信息;传 out_format 则服务端转码并附带 base64',
readOnly: true,
returns:
'语音信息(file/url 为向 QQ 获取的当前下载地址);资源元数据缺失或远端获取失败时返回错误。out_format 指定时附带转码后的 base64。',
params: {
file: f.string().default('').role('record'),
file_id: f.string().default('').role('file_id'),
@@ -1264,7 +1274,7 @@ export const actions = [
summary: '标记全部已读',
params: {},
run: async (_p, ctx) => {
const sessions = ctx.listReadSessions();
const sessions = await ctx.listReadSessions();
await ctx.bridge.apis.message.markAllRead(sessions.groupIds, sessions.privateUserIds);
return okResponse();
},
@@ -2911,8 +2921,8 @@ export const actions = [
// group_id/user_id are routing hints, not identity: 0 means "this branch
// does not apply" and must not error. int({min:0}) optional, not groupId.
params: {
messages: f.message().optional(),
message: f.message().optional(),
messages: forwardMessagesField,
message: forwardMessagesField,
message_type: f.string().optional(),
group_id: f.int({ min: 0 }).optional(),
user_id: f.int({ min: 0 }).optional(),
@@ -2969,8 +2979,8 @@ export const actions = [
summary: '发送群合并转发',
returns: '{ message_id, res_id, forward_id }',
params: {
messages: f.message().optional(),
message: f.message().optional(),
messages: forwardMessagesField,
message: forwardMessagesField,
...forwardPreviewParams,
},
run: async (p, ctx) => {
@@ -2999,8 +3009,8 @@ export const actions = [
returns: '{ message_id, res_id, forward_id }',
params: {
user_id: f.userId(),
messages: f.message().optional(),
message: f.message().optional(),
messages: forwardMessagesField,
message: forwardMessagesField,
...forwardPreviewParams,
},
run: async (p, ctx) => {
@@ -3027,7 +3037,8 @@ export const actions = [
name: 'get_forward_msg',
summary: '获取合并转发消息(id 或 message_id)',
readOnly: true,
returns: '{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件,内部字段不固定)。',
returns:
'{ messages }:转发内的消息节点数组(每项为 OneBot 消息事件);reply 保留 id,有内嵌引用内容时附带 message 和可用的 qq/time/seq,可作为转发节点 content 再次发送。',
returnsSchema: {
type: 'object',
properties: {
@@ -3047,7 +3058,7 @@ export const actions = [
const numericMessageId = integerFromDecimalString(p.message_id);
if (numericMessageId > 0) {
const event = ctx.getMessage(numericMessageId);
const event = await ctx.getMessage(numericMessageId);
const segments = Array.isArray(event?.message) ? event.message : [];
for (const seg of segments) {
@@ -3306,7 +3317,7 @@ export const actions = [
return { todo, messageId, meta };
});
ctx.cacheMessageMetas(
await ctx.cacheMessageMetas(
projections.map(({ messageId, meta }) => ({
messageId,
meta,
@@ -3314,8 +3325,8 @@ export const actions = [
);
return okResponse(
projections.map(({ todo, messageId }) => {
const cached = ctx.getMessage(messageId)?.message;
await mapWithConcurrency(projections, 8, async ({ todo, messageId }) => {
const cached = (await ctx.getMessage(messageId))?.message;
return {
message_id: messageId,
message_seq: todo.sequence,
+4 -59
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';
@@ -21,60 +20,6 @@ function sendMsgOptionalGroupId(): Field<number | undefined> {
const log = createLogger('OneBot');
/**
* Re-sign image URLs in a stored message event at read time. `get_msg`
* returns a copy persisted when the message first arrived, and image rkeys
* expire — so walk the segment array and refresh each image URL through
* `ctx.getImageInfo`, which mints a current rkey. Best-effort and in-place;
* `findEvent` returns a fresh parse, so mutating the array is safe.
*/
async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise<void> {
const segments = event.message;
if (!Array.isArray(segments)) {
return;
}
for (const seg of segments) {
if (!seg || typeof seg !== 'object') {
continue;
}
const segment = seg as { type?: unknown; data?: Record<string, JsonValue> };
if (segment.type !== 'image') {
continue;
}
const data = segment.data;
if (!data || typeof data !== 'object') {
continue;
}
const file =
typeof data.file === 'string'
? data.file
: typeof data.file_id === 'string'
? data.file_id
: '';
if (!file) {
continue;
}
try {
const info = await ctx.getImageInfo(file);
if (info && typeof info.url === 'string' && info.url) {
data.url = info.url;
}
} catch {
// Keep the stored URL when the refresh fails.
}
}
}
export const actions = [
defineAction({
name: 'send_custom_face',
@@ -204,10 +149,10 @@ export const actions = [
summary: '获取消息',
readOnly: true,
returns:
'消息事件对象(首次收到时存储的副本,已去除 post_type/self_id、附带 real_id 字段并刷新图片 URL)。',
'消息事件对象(去除 post_type/self_id,附带 real_id);逐个尝试刷新图片、语音和视频 URL,成功使用新地址,失败保留该段原地址并继续返回消息;地址更新时同步 raw_message。',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const data = ctx.getMessage(p.message_id);
const data = await ctx.getMessage(p.message_id);
if (!data) {
log.warn('[get_msg] miss message_id=%d', p.message_id);
@@ -218,7 +163,7 @@ export const actions = [
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? p.message_id) as JsonValue;
await refreshStoredImageUrls(result, ctx);
await ctx.refreshMessageMedia(p.message_id, result);
return okResponse(result);
},
}),
@@ -228,7 +173,7 @@ export const actions = [
summary: '撤回消息',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
const meta = await ctx.getMessageMeta(p.message_id);
if (!meta) {
return failedResponse(
+7 -4
View File
@@ -55,10 +55,13 @@ export interface ApiActionContext {
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getUptimeMs: () => number;
getMessage: (messageId: number) => JsonObject | null;
getMessageMeta: (messageId: number) => MessageMeta | null;
cacheMessageMetas: (entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>) => void;
listReadSessions: () => ReadSessionTargets;
getMessage: (messageId: number) => JsonObject | null | Promise<JsonObject | null>;
refreshMessageMedia: (messageId: number, event: JsonObject) => Promise<void>;
getMessageMeta: (messageId: number) => MessageMeta | null | Promise<MessageMeta | null>;
cacheMessageMetas: (
entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>,
) => void | Promise<void>;
listReadSessions: () => ReadSessionTargets | Promise<ReadSessionTargets>;
sendPrivateMessage: (
userId: number,
message: JsonValue,
@@ -295,7 +295,7 @@ export const ELEMENT_CODECS = {
const eventName = ctx.isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(sentBySelf, false);
const id = resolveReplyId(
const id = await resolveReplyId(
ctx.isGroup,
ctx.sessionId,
element.replySeq ?? 0,
@@ -328,10 +328,10 @@ export const ELEMENT_CODECS = {
return null;
}
const meta = options?.resolveReplyMeta?.(id) ?? null;
const meta = (await options?.resolveReplyMeta?.(id)) ?? null;
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
const resolved = await options.resolveReplySequence(id);
if (typeof resolved === 'number' && resolved > 0) {
const element: MessageElement = {
@@ -400,7 +400,7 @@ export const ELEMENT_CODECS = {
}
if (ctx.mediaSegmentSink) {
ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
await ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
}
return { type: 'image', data };
@@ -437,7 +437,7 @@ export const ELEMENT_CODECS = {
};
if (ctx.mediaSegmentSink) {
ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
await ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId);
}
return { type: 'record', data };
@@ -468,7 +468,7 @@ export const ELEMENT_CODECS = {
};
if (ctx.mediaSegmentSink) {
ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
await ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId);
}
return { type: 'video', data };
+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 ───────────────
@@ -46,7 +46,7 @@ async function convertPrivateMessage(
event.kind === 'friend_message'
? privateMessageEventName(isSelf, hasCanonicalNtSequence)
: PRIVATE_MESSAGE_EVENT;
const messageId = applyMessageIdResolver(
const messageId = await applyMessageIdResolver(
ctx.messageIdResolver,
false,
sessionId,
@@ -104,7 +104,7 @@ export async function convertGroupMessage(
): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
const messageId = await applyMessageIdResolver(
ctx.messageIdResolver,
true,
event.groupId,
@@ -84,8 +84,11 @@ export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): Jso
});
}
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
const messageId = applyMessageIdResolver(
export async function convertFriendRecall(
ctx: ConverterContext,
event: FriendRecall,
): Promise<JsonObject> {
const messageId = await applyMessageIdResolver(
ctx.messageIdResolver,
false,
event.userUin,
@@ -100,8 +103,11 @@ export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall):
});
}
export function convertGroupRecall(ctx: ConverterContext, event: GroupRecall): JsonObject {
const messageId = applyMessageIdResolver(
export async function convertGroupRecall(
ctx: ConverterContext,
event: GroupRecall,
): Promise<JsonObject> {
const messageId = await applyMessageIdResolver(
ctx.messageIdResolver,
true,
event.groupId,
@@ -143,8 +149,11 @@ export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonO
});
}
export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): JsonObject {
const messageId = applyMessageIdResolver(
export async function convertGroupEssence(
ctx: ConverterContext,
event: GroupEssence,
): Promise<JsonObject> {
const messageId = await applyMessageIdResolver(
ctx.messageIdResolver,
true,
event.groupId,
@@ -265,11 +274,11 @@ export function convertFriendInputStatus(
});
}
export function convertGroupMsgEmojiLike(
export async function convertGroupMsgEmojiLike(
ctx: ConverterContext,
event: GroupMsgEmojiLike,
): JsonObject {
const messageId = applyMessageIdResolver(
): Promise<JsonObject> {
const messageId = await applyMessageIdResolver(
ctx.messageIdResolver,
true,
event.groupId,
@@ -8,29 +8,14 @@ import { attachMessageMedia } from '../message-media';
const log = createLogger('OneBot');
function toSegmentContext(
ctx: ConverterContext,
isGroup: boolean,
sessionId: number,
): ToSegmentContext {
return {
isGroup,
sessionId,
selfId: ctx.selfId,
imageUrlResolver: ctx.imageUrlResolver,
mediaUrlResolver: ctx.mediaUrlResolver,
messageIdResolver: ctx.messageIdResolver,
mediaSegmentSink: ctx.mediaSegmentSink,
};
}
export async function elementsToOneBotSegments(
ctx: ConverterContext,
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
options: { includeReplyContent?: boolean } = {},
): Promise<JsonArray> {
const segmentCtx = toSegmentContext(ctx, isGroup, sessionId);
const segmentCtx: ToSegmentContext = { ...ctx, isGroup, sessionId, mediaSegmentSink: null };
const result: JsonArray = [];
for (const element of elements) {
@@ -39,7 +24,7 @@ export async function elementsToOneBotSegments(
// One malformed element shouldn't drop the whole message — skip it (with a
// breadcrumb) and keep converting the rest.
try {
segment = await elementToSegment(element, { ...segmentCtx, mediaSegmentSink: null });
segment = await elementToSegment(element, segmentCtx);
} catch (err) {
log.warn(
'segment convert skipped type=%s (%s)',
@@ -49,11 +34,43 @@ export async function elementsToOneBotSegments(
continue;
}
// Forward quotes often refer to messages outside the local account's
// history. Carry their inline content so consumers can resend the node.
if (
options.includeReplyContent &&
element.type === 'reply' &&
element.replyElements?.length
) {
const message = await elementsToOneBotSegments(
ctx,
element.replyElements.filter((quoted) => quoted.type !== 'reply'),
isGroup,
sessionId,
);
if (message.length > 0) {
const data = segment.data as JsonObject;
data.message = message;
if (element.replySenderUin) {
data.qq = String(element.replySenderUin);
}
if (element.replyTime !== undefined) {
data.time = String(element.replyTime);
}
if (element.replySeq) {
data.seq = String(element.replySeq);
}
}
}
// Persistence failures must propagate, not masquerade as bad wire elements.
attachMessageMedia(segment, element);
if (element.type === 'image' || element.type === 'record' || element.type === 'video') {
ctx.mediaSegmentSink?.(
await ctx.mediaSegmentSink?.(
element.type,
element,
segment.data as JsonObject,
+13 -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,
@@ -20,16 +15,16 @@ export function isSameActor(
return Boolean(leftUid) && leftUid === rightUid;
}
export function applyMessageIdResolver(
export async function applyMessageIdResolver(
resolver: MessageIdResolver | null,
isGroup: boolean,
sessionId: number,
sequence: number,
eventName: string,
timestamp?: number,
): number {
): Promise<number> {
if (resolver) {
const resolved = resolver(isGroup, sessionId, sequence, eventName, timestamp);
const resolved = await resolver(isGroup, sessionId, sequence, eventName, timestamp);
if (Number.isInteger(resolved) && resolved !== 0) {
return resolved;
@@ -40,7 +35,7 @@ export function applyMessageIdResolver(
return seq === 0 ? 0 : seq;
}
export function resolveReplyId(
export async function resolveReplyId(
isGroup: boolean,
sessionId: number,
sequence: number,
@@ -48,7 +43,7 @@ export function resolveReplyId(
eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT,
timestamp?: number,
replyElements?: readonly MessageElement[],
): number {
): Promise<number> {
const seq = Math.trunc(sequence);
if (seq === 0) {
@@ -56,7 +51,14 @@ export function resolveReplyId(
}
if (resolver) {
const resolved = resolver(isGroup, sessionId, seq, eventName, timestamp, replyElements);
const resolved = await resolver(
isGroup,
sessionId,
seq,
eventName,
timestamp,
replyElements,
);
if (Number.isInteger(resolved) && resolved !== 0) {
return resolved;
+26 -26
View File
@@ -199,7 +199,7 @@ async function convertAndDispatch(
renderParamsVerbose(converted),
]);
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) {
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_before_backfill');
return;
}
@@ -227,12 +227,12 @@ async function convertAndDispatch(
// Backfill can await several network/media operations. Re-check immediately
// before dispatch so a recall that arrived during that gap wins the race.
if (event.kind === 'friend_message' && isFriendMessageRecalled(ctx, log, event)) {
if (event.kind === 'friend_message' && (await isFriendMessageRecalled(ctx, log, event))) {
traceEventTerminal(log, event.kind, state, 'dropped', 'recalled_after_backfill');
return;
}
ctx.dispatchEvent(converted, 'bridge', state.startedAt);
await ctx.dispatchEvent(converted, 'bridge', state.startedAt);
state.handedOff = true;
}
@@ -261,12 +261,12 @@ function traceEventTerminal(
]);
}
function cacheGroupMessageMeta(
async function cacheGroupMessageMeta(
ctx: OneBotInstanceContext,
event: Extract<QQEventVariant, { kind: 'group_message' }>,
): void {
): Promise<void> {
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
ctx.cacheMessageMeta(messageId, {
await ctx.cacheMessageMeta(messageId, {
isGroup: true,
targetId: event.groupId,
sequence: event.msgSeq,
@@ -278,7 +278,7 @@ function cacheGroupMessageMeta(
});
}
function cachePrivateMessageMeta(
async function cachePrivateMessageMeta(
ctx: OneBotInstanceContext,
sessionId: number,
messageSequence: number,
@@ -288,7 +288,7 @@ function cachePrivateMessageMeta(
random: number,
sequenceAuthoritative: boolean,
privateDirection: MessageMeta['privateDirection'],
): void {
): Promise<void> {
const isFriendMessage = privateDirection !== undefined;
const hasNtSequence = isFriendMessage && sequenceAuthoritative && serverSequence > 0;
const eventName = isFriendMessage
@@ -299,7 +299,7 @@ function cachePrivateMessageMeta(
sessionId,
eventName,
);
ctx.cacheMessageMeta(messageId, {
await ctx.cacheMessageMeta(messageId, {
isGroup: false,
targetId: sessionId,
sequence: serverSequence,
@@ -312,15 +312,15 @@ function cachePrivateMessageMeta(
});
}
function isFriendMessageRecalled(
async function isFriendMessageRecalled(
ctx: OneBotInstanceContext,
log: Logger,
event: Extract<QQEventVariant, { kind: 'friend_message' }>,
): boolean {
): Promise<boolean> {
const peerUin = event.peerUin ?? event.senderUin;
const clientSequence = event.clientSeq ?? event.msgSeq;
const sentBySelf = event.senderUin === ctx.selfId;
const recalled = ctx.messageStore.isPrivateMessageRecalled(
const recalled = await ctx.messageStore.isPrivateMessageRecalled(
peerUin,
clientSequence,
sentBySelf,
@@ -339,16 +339,16 @@ function isFriendMessageRecalled(
return recalled;
}
function cacheReaction(
async function cacheReaction(
ctx: OneBotInstanceContext,
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
): void {
): Promise<void> {
if (!event.groupId || !event.msgSeq || !event.emojiId || !event.operatorUin) {
return;
}
if (event.isAdd) {
ctx.reactionStore.recordAdd(
await ctx.reactionStore.recordAdd(
event.groupId,
event.msgSeq,
event.emojiId,
@@ -358,7 +358,7 @@ function cacheReaction(
event.time,
);
} else {
ctx.reactionStore.recordRemove(
await ctx.reactionStore.recordRemove(
event.groupId,
event.msgSeq,
event.emojiId,
@@ -367,23 +367,23 @@ function cacheReaction(
}
}
function handleGroupMessage(
async function handleGroupMessage(
ctx: OneBotInstanceContext,
log: Logger,
event: Extract<QQEventVariant, { kind: 'group_message' }>,
state: EventTraceState,
): Promise<void> {
cacheGroupMessageMeta(ctx, event);
await cacheGroupMessageMeta(ctx, event);
return convertAndDispatch(ctx, log, event, state);
}
function handleFriendMessage(
async function handleFriendMessage(
ctx: OneBotInstanceContext,
log: Logger,
event: Extract<QQEventVariant, { kind: 'friend_message' }>,
state: EventTraceState,
): Promise<void> {
cachePrivateMessageMeta(
await cachePrivateMessageMeta(
ctx,
event.peerUin ?? event.senderUin,
event.msgSeq,
@@ -397,13 +397,13 @@ function handleFriendMessage(
return convertAndDispatch(ctx, log, event, state);
}
function handleTempMessage(
async function handleTempMessage(
ctx: OneBotInstanceContext,
log: Logger,
event: Extract<QQEventVariant, { kind: 'temp_message' }>,
state: EventTraceState,
): Promise<void> {
cachePrivateMessageMeta(
await cachePrivateMessageMeta(
ctx,
event.senderUin,
event.msgSeq,
@@ -418,14 +418,14 @@ function handleTempMessage(
return convertAndDispatch(ctx, log, event, state);
}
function handleFriendRecall(
async function handleFriendRecall(
ctx: OneBotInstanceContext,
log: Logger,
event: Extract<QQEventVariant, { kind: 'friend_recall' }>,
state: EventTraceState,
): Promise<void> {
const clientSequence = event.clientSeq ?? event.msgSeq;
const recalled = ctx.messageStore.recordPrivateRecall(
const recalled = await ctx.messageStore.recordPrivateRecall(
event.userUin,
clientSequence,
event.recalledBySelf === true,
@@ -442,13 +442,13 @@ function handleFriendRecall(
return convertAndDispatch(ctx, log, event, state, messageIdOverride);
}
function handleGroupMsgEmojiLike(
async function handleGroupMsgEmojiLike(
ctx: OneBotInstanceContext,
log: Logger,
event: Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>,
state: EventTraceState,
): Promise<void> {
cacheReaction(ctx, event);
await cacheReaction(ctx, event);
return convertAndDispatch(ctx, log, event, state);
}
+3 -3
View File
@@ -9,12 +9,12 @@ import type { JsonObject } from './types';
* Private history needs the conversation peer explicitly because `user_id`
* names the sender and therefore equals the bot account on outgoing messages.
*/
export function persistHistoryEvent(
export async function persistHistoryEvent(
store: MessageStore,
event: JsonObject,
privatePeerId?: number,
source?: FriendMessage,
): void {
): Promise<boolean> {
const messageId = toHistoryInt(event.message_id);
if (!Number.isSafeInteger(messageId) || messageId === 0) {
@@ -63,7 +63,7 @@ export function persistHistoryEvent(
timestamp: source.time,
} satisfies Parameters<MessageStore['storeMeta']>[1])
: undefined;
store.storeHistoryEvent(messageId, isGroup, sessionId, sequence, eventName, event, {
return store.storeHistoryEvent(messageId, isGroup, sessionId, sequence, eventName, event, {
sequenceAuthoritative,
meta,
});
+38 -20
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 {
@@ -136,8 +137,11 @@ export class LoginHistorySyncCoordinator {
})),
signal,
);
const groupCandidates = selectGroupCandidates(ref.messageStore, state.groups);
const privateCandidates = selectPrivateCandidates(ref.messageStore, state.privateUsers);
const groupCandidates = await selectGroupCandidates(ref.messageStore, state.groups);
const privateCandidates = await selectPrivateCandidates(
ref.messageStore,
state.privateUsers,
);
// URL resolvers may issue additional QQ requests for rkeys or media
// download addresses. Automatic backfill must stay inside its one-probe
// plus six-page packet budget, so persist only URLs already present in the
@@ -151,9 +155,9 @@ export class LoginHistorySyncCoordinator {
imageUrlResolver: null,
mediaUrlResolver: null,
mediaSegmentSink: mediaSegmentSink
? (mediaType, element, data, isGroup, sessionId) => {
? async (mediaType, element, data, isGroup, sessionId) => {
throwIfAborted(signal);
mediaSegmentSink(mediaType, element, data, isGroup, sessionId);
await mediaSegmentSink(mediaType, element, data, isGroup, sessionId);
}
: null,
},
@@ -257,18 +261,21 @@ export class LoginHistorySyncCoordinator {
export const loginHistorySyncCoordinator = new LoginHistorySyncCoordinator();
function selectGroupCandidates(
async function selectGroupCandidates(
store: MessageStore,
states: readonly GroupHistorySyncState[],
): GroupCandidate[] {
return states
.flatMap((state): GroupCandidate[] => {
): Promise<GroupCandidate[]> {
return (
await mapWithConcurrency(states, 8, async (state): Promise<GroupCandidate[]> => {
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) {
return [];
}
const observedSequence = store.findLatestAuthoritativeSequence(true, state.groupId);
const localSequence = store.findLatestPersistedAuthoritativeSequence(
const observedSequence = await store.findLatestAuthoritativeSequence(
true,
state.groupId,
);
const localSequence = await store.findLatestPersistedAuthoritativeSequence(
true,
state.groupId,
);
@@ -312,22 +319,27 @@ function selectGroupCandidates(
},
];
})
)
.flat()
.sort(compareCandidates)
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxGroups);
}
function selectPrivateCandidates(
async function selectPrivateCandidates(
store: MessageStore,
states: readonly PrivateHistorySyncState[],
): PrivateCandidate[] {
return states
.flatMap((state): PrivateCandidate[] => {
): Promise<PrivateCandidate[]> {
return (
await mapWithConcurrency(states, 8, async (state): Promise<PrivateCandidate[]> => {
if (!Number.isSafeInteger(state.latestSeq) || state.latestSeq <= 0) {
return [];
}
const observedSequence = store.findLatestAuthoritativeSequence(false, state.userId);
const localSequence = store.findLatestPersistedAuthoritativeSequence(
const observedSequence = await store.findLatestAuthoritativeSequence(
false,
state.userId,
);
const localSequence = await store.findLatestPersistedAuthoritativeSequence(
false,
state.userId,
);
@@ -360,6 +372,8 @@ function selectPrivateCandidates(
},
];
})
)
.flat()
.sort(compareCandidates)
.slice(0, LOGIN_HISTORY_SYNC_LIMITS.maxPrivateUsers);
}
@@ -452,7 +466,7 @@ async function persistGroupMessage(
);
}
persistHistoryEvent(ref.messageStore, converted);
await persistHistoryEvent(ref.messageStore, converted);
}
async function persistPrivateMessage(
@@ -489,7 +503,12 @@ async function persistPrivateMessage(
}
if (
ref.messageStore.isPrivateMessageRecalled(peerUin, clientSequence, sentBySelf, message.time)
await ref.messageStore.isPrivateMessageRecalled(
peerUin,
clientSequence,
sentBySelf,
message.time,
)
) {
log.debug(
'login history sync omitted recalled private message: UIN=%d peer=%d clientSeq=%d self=%s',
@@ -505,8 +524,7 @@ async function persistPrivateMessage(
converted.target_id = peerUin;
}
persistHistoryEvent(ref.messageStore, converted, peerUin, message);
return true;
return persistHistoryEvent(ref.messageStore, converted, peerUin, message);
}
function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
+46 -22
View File
@@ -22,6 +22,7 @@ import {
fetchPttText as fetchPttTextAction,
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
refreshMessageMedia,
} from './modules/media-actions';
import {
deleteMessage,
@@ -58,8 +59,12 @@ export interface OneBotInstanceContext {
config: OneBotConfig;
musicSignUrl?: string;
getUptimeMs(): number;
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
dispatchEvent(event: JsonObject, source?: 'bridge' | 'send', startedAt?: number): void;
cacheMessageMeta(messageId: number, meta: MessageMeta): void | Promise<void>;
dispatchEvent(
event: JsonObject,
source?: 'bridge' | 'send',
startedAt?: number,
): void | Promise<void>;
}
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
@@ -71,11 +76,14 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true,
getUptimeMs: () => ref.getUptimeMs(),
getMessage: (messageId) => messageStore.findEvent(messageId),
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
cacheMessageMetas: (entries) => messageStore.storeMetas(entries),
listReadSessions: () =>
messageStore.listReadSessions(bridge.identity.groups.map((group) => group.groupId)),
getMessage: async (messageId) => await messageStore.findEvent(messageId),
refreshMessageMedia: (messageId, event) => refreshMessageMedia(ref, messageId, event),
getMessageMeta: async (messageId) => await messageStore.findMeta(messageId),
cacheMessageMetas: async (entries) => await messageStore.storeMetas(entries),
listReadSessions: async () =>
await messageStore.listReadSessions(
bridge.identity.groups.map((group) => group.groupId),
),
canSendImage: () => true,
canSendRecord: () => true,
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) =>
@@ -85,7 +93,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
message,
autoEscape,
tempGroupId,
tempGroupId === undefined ? (event) => ref.dispatchEvent(event, 'send') : undefined,
tempGroupId === undefined
? async (event) => await ref.dispatchEvent(event, 'send')
: undefined,
),
sendGroupMessage: (groupId, message, autoEscape) =>
sendGroupMessage(ref, groupId, message, autoEscape),
@@ -109,8 +119,12 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendGroupForwardMsg: (groupId, messages, meta) =>
sendGroupForwardMessage(ref, groupId, messages, meta),
sendPrivateForwardMsg: (userId, messages, meta) =>
sendPrivateForwardMessage(ref, userId, messages, meta, (event) =>
ref.dispatchEvent(event, 'send'),
sendPrivateForwardMessage(
ref,
userId,
messages,
meta,
async (event) => await ref.dispatchEvent(event, 'send'),
),
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
@@ -120,13 +134,13 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
messageId,
target,
target.userId !== undefined
? (event) => ref.dispatchEvent(event, 'send')
? async (event) => await ref.dispatchEvent(event, 'send')
: undefined,
),
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId);
const meta = await messageStore.findMeta(messageId);
if (!meta) {
throw new Error('message not found');
@@ -144,7 +158,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const emojiType = emojiId.length > 3 ? 2 : 1;
if (set) {
reactionStore.recordAdd(
await reactionStore.recordAdd(
meta.targetId,
meta.sequence,
emojiId,
@@ -154,11 +168,11 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
Math.floor(Date.now() / 1000),
);
} else {
reactionStore.recordRemove(meta.targetId, meta.sequence, emojiId, ref.selfId);
await reactionStore.recordRemove(meta.targetId, meta.sequence, emojiId, ref.selfId);
}
},
fetchEmojiLikeSummary: async (messageId) => {
const meta = messageStore.findMeta(messageId);
const meta = await messageStore.findMeta(messageId);
if (!meta) {
throw new Error('message not found');
@@ -172,7 +186,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
throw new Error('message has no authoritative QQ sequence');
}
const summary = reactionStore.summarizeMessage(meta.targetId, meta.sequence);
const summary = await reactionStore.summarizeMessage(meta.targetId, meta.sequence);
const out: Array<{
emoji_id: string;
emoji_type: number;
@@ -182,9 +196,15 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
}> = [];
for (const entry of summary) {
let users = reactionStore
.listUsers(meta.targetId, meta.sequence, entry.emojiId, 1000, 0)
.map((user) => ({ user_id: user.operatorUin }));
let users = (
await reactionStore.listUsers(
meta.targetId,
meta.sequence,
entry.emojiId,
1000,
0,
)
).map((user) => ({ user_id: user.operatorUin }));
try {
const remote = await bridge.apis.interaction.getEmojiLikes(
@@ -214,7 +234,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
return out;
},
fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => {
const meta = messageStore.findMeta(messageId);
const meta = await messageStore.findMeta(messageId);
if (!meta) {
throw new Error('message not found');
@@ -228,7 +248,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
throw new Error('message has no authoritative QQ sequence');
}
const raw = reactionStore.listUsers(
const raw = await reactionStore.listUsers(
meta.targetId,
meta.sequence,
emojiId,
@@ -240,7 +260,11 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
uid: r.operatorUid,
setAt: r.setAt,
}));
const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId);
const cachedCount = await reactionStore.countUsers(
meta.targetId,
meta.sequence,
emojiId,
);
let serverCount = cachedCount;
try {
+39 -24
View File
@@ -161,7 +161,7 @@ export class OneBotInstance {
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
mediaUrlResolver: (element, isGroup, sessionId) =>
mediaUrlResolver.resolve(element, isGroup, sessionId),
messageIdResolver: (
messageIdResolver: async (
isGroup,
sessionId,
sequence,
@@ -178,7 +178,7 @@ export class OneBotInstance {
(resolvedEventName === PRIVATE_MESSAGE_EVENT ||
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT)
) {
const storedId = this.messageStore.resolvePrivateReplyMessageId(
const storedId = await this.messageStore.resolvePrivateReplyMessageId(
sessionId,
sequence,
resolvedEventName === PRIVATE_SENT_MESSAGE_EVENT,
@@ -199,8 +199,8 @@ export class OneBotInstance {
: resolvedEventName,
);
},
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
mediaSegmentSink: async (mediaType, element, data, isGroup, sessionId) =>
await mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
};
const ctx: OneBotInstanceContext = {
uin: this.uin,
@@ -214,7 +214,8 @@ export class OneBotInstance {
config,
musicSignUrl: globalSettings.musicSignUrl,
getUptimeMs: () => Math.max(0, Date.now() - this.startedAt),
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
cacheMessageMeta: async (messageId, meta) =>
await this.cacheMessageMeta(messageId, meta),
dispatchEvent: (event, source = 'bridge', startedAt) =>
this.dispatchEvent(event, source, startedAt),
};
@@ -225,7 +226,12 @@ export class OneBotInstance {
this.networkManager = new OneBotNetworkManager((desired) =>
this.createNetworkAdapter(desired, networkCtx),
);
this.networkReady = this.networkManager.reconcile(config);
this.networkReady = Promise.all([
bridge.identity.initialization,
this.messageStore.initialization,
this.mediaStore.initialization,
this.reactionStore.initialization,
]).then(() => this.networkManager.reconcile(config));
this.lifecycleTail = this.networkReady.then(
() => undefined,
() => undefined,
@@ -400,9 +406,9 @@ export class OneBotInstance {
// reconcile and every transport have actually closed.
const closeErrors: unknown[] = [];
const stores = [
['message', () => this.messageStore.close()],
['media', () => this.mediaStore.close()],
['reaction', () => this.reactionStore.close()],
['message', async () => await this.messageStore.close()],
['media', async () => await this.mediaStore.close()],
['reaction', async () => await this.reactionStore.close()],
] as const;
for (const [name, close] of stores) {
@@ -411,7 +417,7 @@ export class OneBotInstance {
}
try {
close();
await close();
this.storeCloseState[name] = true;
} catch (error) {
closeErrors.push(error);
@@ -466,9 +472,12 @@ export class OneBotInstance {
source: 'bridge' | 'send' = 'bridge',
startedAt = Date.now(),
): Promise<void> {
if (source === 'bridge') {
this.cacheMessageEvent(event);
if (!(await this.cacheMessageEvent(event))) {
this.traceEventHandoffTerminal(event, startedAt, 'suppressed', 'private_recall');
return;
}
if (source === 'bridge') {
if (this.consumePendingSelfSentEcho(event)) {
this.log.trace(
'duplicate self-message echo suppressed message_id=%d message_seq=%d',
@@ -484,7 +493,6 @@ export class OneBotInstance {
return;
}
} else {
this.cacheMessageEvent(event);
this.rememberPendingSelfSentEcho(event);
}
@@ -492,7 +500,7 @@ export class OneBotInstance {
// synthetic event here would produce a second, less accurate "received"
// line whose private user_id points at the bot itself.
if (source === 'bridge') {
this.logReceivedMessage(event);
await this.logReceivedMessage(event);
}
// Built-in `#sl` only consumes events observed from QQ. Action-originated
@@ -518,7 +526,7 @@ export class OneBotInstance {
event: JsonObject,
startedAt: number,
outcome: 'suppressed' | 'reporting_started',
reason?: 'duplicate_self_echo' | 'status_command',
reason?: 'duplicate_self_echo' | 'status_command' | 'private_recall',
): void {
this.log.trace(() => [
'event_terminal post_type=%s outcome=%s%s ms=%d',
@@ -702,7 +710,7 @@ export class OneBotInstance {
return rejected;
}
private logReceivedMessage(event: JsonObject): void {
private async logReceivedMessage(event: JsonObject): Promise<void> {
const isSelf = event.post_type === 'message_sent';
if (event.post_type !== 'message' && !isSelf) {
@@ -738,7 +746,7 @@ export class OneBotInstance {
if (type === 'reply') {
const replyId = toInt(data.id);
renderedParts.push(formatReply(this.messageStore, identity, replyId));
renderedParts.push(await formatReply(this.messageStore, identity, replyId));
} else {
renderedParts.push(formatMessageSegments([seg as JsonValue]));
}
@@ -781,15 +789,15 @@ export class OneBotInstance {
}
}
private cacheMessageEvent(event: JsonObject): void {
private async cacheMessageEvent(event: JsonObject): Promise<boolean> {
if (event.post_type !== 'message' && event.post_type !== 'message_sent') {
return;
return true;
}
const messageId = toInt(event.message_id);
if (messageId === 0) {
return;
return true;
}
const isGroup = event.message_type === 'group';
@@ -806,18 +814,25 @@ export class OneBotInstance {
: PRIVATE_MESSAGE_EVENT;
if (sessionId === 0) {
return;
return true;
}
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
return this.messageStore.storeEvent(
messageId,
isGroup,
sessionId,
sequence,
eventName,
event,
);
}
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
private async cacheMessageMeta(messageId: number, meta: MessageMeta): Promise<void> {
if (!Number.isInteger(messageId) || messageId === 0) {
return;
}
this.messageStore.storeMeta(messageId, meta);
await this.messageStore.storeMeta(messageId, meta);
}
private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject {
+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,
+20 -18
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 {
@@ -22,17 +22,17 @@ export async function migrateLegacyMedia(
cancelled: () => boolean = () => false,
): Promise<void> {
const store = new MediaStore(messageDbPath);
store.close();
await store.close();
const destination = openSqliteDb(messageDbPath);
let source: DatabaseSync | undefined;
let source: SqliteDatabase | undefined;
try {
destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
await destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
id INTEGER PRIMARY KEY CHECK (id = 1), phase TEXT NOT NULL, cursor INTEGER NOT NULL
); INSERT OR IGNORE INTO media_migration_state VALUES (1, 'entries', 0)`);
const state = destination
const state = (await destination
.prepare('SELECT phase, cursor FROM media_migration_state WHERE id = 1')
.get() as { phase: string; cursor: number };
.get()) as { phase: string; cursor: number };
if (state.phase === 'complete') {
return;
@@ -41,11 +41,13 @@ export async function migrateLegacyMedia(
const sourcePath = path.join(path.dirname(messageDbPath), 'media.db');
if (!fs.existsSync(sourcePath)) {
destination.exec("UPDATE media_migration_state SET phase = 'complete' WHERE id = 1");
await destination.exec(
"UPDATE media_migration_state SET phase = 'complete' WHERE id = 1",
);
return;
}
source = new DatabaseSync(sourcePath, { readOnly: true });
source = new SqliteDatabase(sourcePath, { readOnly: true });
log.info('preserving legacy media metadata: migration started');
const insertEntry =
destination.prepare(`INSERT INTO legacy_media_entries (type, primary_key, data, last_seen)
@@ -59,11 +61,11 @@ export async function migrateLegacyMedia(
while (!cancelled() && state.phase !== 'complete') {
const table = state.phase === 'entries' ? 'media_entries' : 'media_keys';
const rows = source
const rows = (await source
.prepare(
`SELECT rowid AS migration_rowid, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT ?`,
)
.all(state.cursor, BATCH_SIZE) as Array<{
.all(state.cursor, BATCH_SIZE)) as Array<{
migration_rowid: number;
type: string;
primary_key: string;
@@ -74,7 +76,7 @@ export async function migrateLegacyMedia(
const nextPhase =
rows.length === 0 ? (state.phase === 'entries' ? 'keys' : 'complete') : state.phase;
const nextCursor = rows.at(-1)?.migration_rowid ?? 0;
destination.exec('BEGIN IMMEDIATE');
await destination.exec('BEGIN IMMEDIATE');
try {
for (const row of rows) {
@@ -93,14 +95,14 @@ export async function migrateLegacyMedia(
);
}
insertEntry.run(
await insertEntry.run(
row.type,
foldMediaKey(row.primary_key),
serializeMediaInfo(info),
row.last_seen,
);
} else {
insertKey.run(
await insertKey.run(
row.type,
foldMediaKey(row.key),
foldMediaKey(row.primary_key),
@@ -108,10 +110,10 @@ export async function migrateLegacyMedia(
}
}
saveState.run(nextPhase, nextCursor);
destination.exec('COMMIT');
await saveState.run(nextPhase, nextCursor);
await destination.exec('COMMIT');
} catch (error) {
rollbackMediaTransaction(destination, error);
await rollbackMediaTransaction(destination, error);
}
state.phase = nextPhase;
@@ -129,7 +131,7 @@ export async function migrateLegacyMedia(
log.info('preserving legacy media metadata: migration complete; source retained');
}
} finally {
source?.close();
destination.close();
await source?.close();
await destination.close();
}
}
+148 -85
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,107 +71,163 @@ const INLINE_MEDIA_SOURCE = /^(base64:\/\/|data:)/i;
* Only the in-memory lookup cache is bounded; history dependencies never expire.
*/
export class MediaStore {
private readonly db: DatabaseSync;
private readonly db: SqliteDatabase;
private readonly cache = new Map<string, string>();
private readonly upsertEntry: StatementSync;
private readonly upsertKey: StatementSync;
private readonly findEntry: StatementSync;
private readonly findLegacyEntry: StatementSync;
private upsertEntry!: SqliteStatement;
private upsertKey!: SqliteStatement;
private findEntry!: SqliteStatement;
private findLegacyEntry!: SqliteStatement;
readonly initialization: Promise<void>;
constructor(
dbPath: string,
private readonly maxCachedEntries = DEFAULT_KEEP_ENTRIES,
) {
this.db = openSqliteDb(dbPath);
this.initialization = this.db.serial(async () => {
for (const prefix of ['', 'legacy_']) {
await this.db.exec(`
CREATE TABLE IF NOT EXISTS ${prefix}media_entries (
type TEXT NOT NULL, primary_key TEXT NOT NULL, data TEXT NOT NULL,
last_seen INTEGER NOT NULL, PRIMARY KEY (type, primary_key)
);
CREATE TABLE IF NOT EXISTS ${prefix}media_keys (
type TEXT NOT NULL, key TEXT NOT NULL, primary_key TEXT NOT NULL,
PRIMARY KEY (type, key)
);
`);
}
for (const prefix of ['', 'legacy_']) {
this.db.exec(`
CREATE TABLE IF NOT EXISTS ${prefix}media_entries (
type TEXT NOT NULL, primary_key TEXT NOT NULL, data TEXT NOT NULL,
last_seen INTEGER NOT NULL, PRIMARY KEY (type, primary_key)
);
CREATE TABLE IF NOT EXISTS ${prefix}media_keys (
type TEXT NOT NULL, key TEXT NOT NULL, primary_key TEXT NOT NULL,
PRIMARY KEY (type, key)
);
this.upsertEntry = this.db.prepare(`
INSERT INTO media_entries (type, primary_key, data, last_seen) VALUES (?, ?, ?, ?)
ON CONFLICT(type, primary_key) DO UPDATE SET data = excluded.data, last_seen = excluded.last_seen
`);
}
this.upsertEntry = this.db.prepare(`
INSERT INTO media_entries (type, primary_key, data, last_seen) VALUES (?, ?, ?, ?)
ON CONFLICT(type, primary_key) DO UPDATE SET data = excluded.data, last_seen = excluded.last_seen
`);
this.upsertKey = this.db.prepare(`
INSERT INTO media_keys (type, key, primary_key) VALUES (?, ?, ?)
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key
`);
this.findEntry = this.db.prepare(`
SELECT data FROM media_entries WHERE type = ? AND primary_key = COALESCE(
(SELECT primary_key FROM media_keys WHERE type = ? AND key = ?), ?
)
`);
this.findLegacyEntry = this.db.prepare(`
SELECT data FROM legacy_media_entries WHERE type = ? AND primary_key = COALESCE(
(SELECT primary_key FROM legacy_media_keys WHERE type = ? AND key = ?), ?
)
`);
this.upsertKey = this.db.prepare(`
INSERT INTO media_keys (type, key, primary_key) VALUES (?, ?, ?)
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key
`);
this.findEntry = this.db.prepare(`
SELECT data FROM media_entries WHERE type = ? AND primary_key = COALESCE(
(SELECT primary_key FROM media_keys WHERE type = ? AND key = ?), ?
)
`);
this.findLegacyEntry = this.db.prepare(`
SELECT data FROM legacy_media_entries WHERE type = ? AND primary_key = COALESCE(
(SELECT primary_key FROM legacy_media_keys WHERE type = ? AND key = ?), ?
)
`);
});
void this.initialization.catch(() => undefined);
}
close(): void {
this.cache.clear();
this.db.close();
async close(): Promise<void> {
await this.initialization.catch(() => undefined);
await this.db.close();
}
rememberImage(info: CachedImage): void {
this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
async rememberImage(info: CachedImage): Promise<void> {
info = structuredClone(info);
return this.db.serial(async () => {
await this.initialization;
await this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
});
}
rememberRecord(info: CachedRecord): void {
this.remember(TYPE_RECORD, info, [info.file, info.fileName, info.fileId, info.url]);
async rememberRecord(info: CachedRecord): Promise<void> {
info = structuredClone(info);
return this.db.serial(async () => {
await this.initialization;
await this.remember(TYPE_RECORD, info, [
info.file,
info.fileName,
info.fileId,
info.url,
]);
});
}
rememberVideo(info: CachedVideo): void {
this.remember(TYPE_VIDEO, info, [info.file, info.fileName, info.fileId, info.url]);
async rememberVideo(info: CachedVideo): Promise<void> {
info = structuredClone(info);
return this.db.serial(async () => {
await this.initialization;
await this.remember(TYPE_VIDEO, info, [
info.file,
info.fileName,
info.fileId,
info.url,
]);
});
}
findImage(key: string, source: MediaLookupSource = 'current'): CachedImage | null {
return this.find(TYPE_IMAGE, key, source);
async findImage(
key: string,
source: MediaLookupSource = 'current',
): Promise<CachedImage | null> {
return this.db.serial(async () => {
await this.initialization;
return await this.find(TYPE_IMAGE, key, source);
});
}
findRecord(key: string, source: MediaLookupSource = 'current'): CachedRecord | null {
return this.find(TYPE_RECORD, key, source);
async findRecord(
key: string,
source: MediaLookupSource = 'current',
): Promise<CachedRecord | null> {
return this.db.serial(async () => {
await this.initialization;
return await this.find(TYPE_RECORD, key, source);
});
}
findVideo(key: string, source: MediaLookupSource = 'current'): CachedVideo | null {
return this.find(TYPE_VIDEO, key, source);
async findVideo(
key: string,
source: MediaLookupSource = 'current',
): Promise<CachedVideo | null> {
return this.db.serial(async () => {
await this.initialization;
return await this.find(TYPE_VIDEO, key, source);
});
}
updateImageUrl(key: string, url: string): void {
this.updateUrl(TYPE_IMAGE, key, url);
async updateImageUrl(key: string, url: string): Promise<void> {
return this.db.serial(async () => {
await this.initialization;
await this.updateUrl(TYPE_IMAGE, key, url);
});
}
updateRecordUrl(key: string, url: string): void {
this.updateUrl(TYPE_RECORD, key, url);
async updateRecordUrl(key: string, url: string): Promise<void> {
return this.db.serial(async () => {
await this.initialization;
await this.updateUrl(TYPE_RECORD, key, url);
});
}
updateVideoUrl(key: string, url: string): void {
this.updateUrl(TYPE_VIDEO, key, url);
async updateVideoUrl(key: string, url: string): Promise<void> {
return this.db.serial(async () => {
await this.initialization;
await this.updateUrl(TYPE_VIDEO, key, url);
});
}
/** Counts durable records, not the bounded lookup cache. */
size(): { images: number; records: number; videos: number } {
const counts = this.db
.prepare(
`SELECT type, COUNT(*) AS n FROM (
SELECT type FROM media_entries UNION ALL SELECT type FROM legacy_media_entries
) GROUP BY type`,
)
.all() as Array<{ type: string; n: number }>;
const count = (type: string) => counts.find((row) => row.type === type)?.n ?? 0;
return {
images: count(TYPE_IMAGE),
records: count(TYPE_RECORD),
videos: count(TYPE_VIDEO),
};
async size(): Promise<{ images: number; records: number; videos: number }> {
return this.db.serial(async () => {
await this.initialization;
const counts = (await this.db
.prepare(
`SELECT type, COUNT(*) AS n FROM (
SELECT type FROM media_entries UNION ALL SELECT type FROM legacy_media_entries
) GROUP BY type`,
)
.all()) as Array<{ type: string; n: number }>;
const count = (type: string) => counts.find((row) => row.type === type)?.n ?? 0;
return {
images: await count(TYPE_IMAGE),
records: await count(TYPE_RECORD),
videos: await count(TYPE_VIDEO),
};
});
}
private remember(type: string, info: object, aliases: string[]): void {
private async remember(type: string, info: object, aliases: string[]): Promise<void> {
const primary = pickPrimary(aliases);
if (!primary) {
@@ -179,18 +235,18 @@ export class MediaStore {
}
const data = serializeMediaInfo(info);
this.db.exec('BEGIN IMMEDIATE');
await this.db.exec('BEGIN IMMEDIATE');
try {
this.upsertEntry.run(type, primary, data, Math.floor(Date.now() / 1000));
await this.upsertEntry.run(type, primary, data, Math.floor(Date.now() / 1000));
for (const key of new Set(aliases.filter(Boolean).map(foldMediaKey))) {
this.upsertKey.run(type, key, primary);
await this.upsertKey.run(type, key, primary);
}
this.db.exec('COMMIT');
await this.db.exec('COMMIT');
} catch (error) {
rollbackMediaTransaction(this.db, error);
await rollbackMediaTransaction(this.db, error);
}
// Alias remapping can invalidate any cached lookup. JSON strings ensure
@@ -198,7 +254,11 @@ export class MediaStore {
this.cache.clear();
}
private find<T>(type: string, key: string, source: MediaLookupSource = 'current'): T | null {
private async find<T>(
type: string,
key: string,
source: MediaLookupSource = 'current',
): Promise<T | null> {
const lookup = foldMediaKey(key);
if (!lookup) {
@@ -212,8 +272,11 @@ export class MediaStore {
// Legacy history has no per-message snapshots. Its frozen migration
// index must never resolve through a later, mutable filename alias.
const current =
source === 'current' ? this.findEntry.get(type, type, lookup, lookup) : undefined;
const row = (current ?? this.findLegacyEntry.get(type, type, lookup, lookup)) as
source === 'current'
? await this.findEntry.get(type, type, lookup, lookup)
: undefined;
const row = (current ??
(await this.findLegacyEntry.get(type, type, lookup, lookup))) as
{ data: string } | undefined;
if (!row) {
@@ -240,18 +303,18 @@ export class MediaStore {
return result as T;
}
private updateUrl(type: string, key: string, url: string): void {
private async updateUrl(type: string, key: string, url: string): Promise<void> {
if (!url || mustFoldMediaKey(url)) {
return;
}
const info = this.find<Record<string, unknown>>(type, key);
const info = await this.find<Record<string, unknown>>(type, key);
if (!info || info.url === url) {
return;
}
this.remember(
await this.remember(
type,
{ ...info, url },
[info.file, info.fileName, info.fileId, url].filter(
@@ -271,9 +334,9 @@ export function serializeMediaInfo(info: object): string {
return data;
}
export function rollbackMediaTransaction(db: DatabaseSync, error: unknown): never {
export async function rollbackMediaTransaction(db: SqliteDatabase, error: unknown): Promise<never> {
try {
db.exec('ROLLBACK');
await db.exec('ROLLBACK');
} catch (rollbackError) {
throw new AggregateError([error, rollbackError], 'media write and rollback failed', {
cause: error,
+38 -17
View File
@@ -1,7 +1,30 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { createLogger } from '@snowluma/common/logger';
import type { MessageElement } from '@snowluma/protocol/events';
import type { RKeyCache } from './instance-rkey';
const log = createLogger('OneBot');
export function resolveRemoteMediaUrl(
bridge: BridgeInterface,
type: 'record' | 'video',
node: MessageElement['mediaNode'],
isGroup: boolean,
sessionId: number,
): Promise<string> {
if (!node) {
throw new Error(`${type} media metadata is missing`);
}
const api = bridge.apis.groupFile;
if (type === 'record') {
return isGroup ? api.getPttUrl(sessionId, node) : api.getPrivatePttUrl(node);
}
return isGroup ? api.getVideoUrl(sessionId, node) : api.getPrivateVideoUrl(node);
}
export class MediaUrlResolver {
constructor(
private readonly bridge: BridgeInterface,
@@ -12,9 +35,14 @@ export class MediaUrlResolver {
if (!element.url) {
try {
await this.populateUrl(element, isGroup, sessionId);
} catch {
// Best-effort: a URL fetch hiccup should never block the
// outgoing segment. The RKey pass below still runs.
} catch (err) {
// Preserve the media segment when its download URL is unavailable.
log.warn(
'media URL resolution failed type=%s is_group=%s: %s',
element.type,
isGroup,
err instanceof Error ? err.message : String(err),
);
}
}
@@ -42,20 +70,13 @@ export class MediaUrlResolver {
}
if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
if (isGroup) {
element.url =
element.type === 'record'
? await this.bridge.apis.groupFile.getPttUrl(sessionId, element.mediaNode)
: await this.bridge.apis.groupFile.getVideoUrl(
sessionId,
element.mediaNode,
);
} else {
element.url =
element.type === 'record'
? await this.bridge.apis.groupFile.getPrivatePttUrl(element.mediaNode)
: await this.bridge.apis.groupFile.getPrivateVideoUrl(element.mediaNode);
}
element.url = await resolveRemoteMediaUrl(
this.bridge,
element.type,
element.mediaNode,
isGroup,
sessionId,
);
}
}
}
+22
View File
@@ -6,6 +6,28 @@ export type MessageMedia = Extract<MessageElement, { type: 'image' | 'record' |
const mediaSnapshot = Symbol('message media snapshot');
type MediaSegment = JsonObject & { [mediaSnapshot]?: MessageMedia };
/** Snapshot queued writes, including metadata that is deliberately absent from JSON. */
export function snapshotMessageEvent(event: JsonObject): JsonObject {
const snapshot = structuredClone(event);
if (Array.isArray(event.message) && Array.isArray(snapshot.message)) {
for (const [index, segment] of event.message.entries()) {
if (!segment || typeof segment !== 'object' || Array.isArray(segment)) {
continue;
}
const media = (segment as MediaSegment)[mediaSnapshot];
const copied = snapshot.message[index];
if (media && copied && typeof copied === 'object') {
Object.defineProperty(copied, mediaSnapshot, { value: structuredClone(media) });
}
}
}
return snapshot;
}
export function isMessageMedia(element: MessageElement): element is MessageMedia {
return element.type === 'image' || element.type === 'record' || element.type === 'video';
}
+95 -19
View File
@@ -11,20 +11,39 @@ import {
import { parseFromCQString } from './helper/cq';
import { getElementCodec, intOr } from './event-converter/element-codecs';
import type { JsonValue } from './types';
import { assertReplyPreviewType, elementsToReplyPreview } from './reply-preview';
const log = createLogger('MsgParser');
export { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
interface ForwardReplyContext {
senderUin: number;
time?: number;
}
export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null;
resolveReplyMeta?: (replyMessageId: number) => {
senderUin: number;
time: number;
random: number;
elements?: MessageElement[];
sequenceAuthoritative?: boolean;
} | null;
/** Custom quote defaults, supplied only while parsing a merged-forward node. */
forwardReply?: ForwardReplyContext;
/** Internal: quote content cannot nest replies or invoke action-like codecs. */
replyPreview?: boolean;
resolveReplySequence?: (replyMessageId: number) => number | null | Promise<number | null>;
resolveReplyMeta?: (replyMessageId: number) =>
| {
senderUin: number;
time: number;
random: number;
elements?: MessageElement[];
sequenceAuthoritative?: boolean;
}
| null
| Promise<{
senderUin: number;
time: number;
random: number;
elements?: MessageElement[];
sequenceAuthoritative?: boolean;
} | null>;
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
resolveContactArk?: (
contactType: string,
@@ -95,15 +114,6 @@ function isExplicitEmptyTextPlaceholder(segment: MessageSegment): boolean {
return normalizeSegmentType(segment.type) === 'text' && segmentPayload(segment).text === '';
}
/**
* True when the OneBot payload is a forward: every effective segment is
* `node` (explicit empty-text placeholders ignored). `send_msg` routes
* this list through the forward upload path instead of parseMessage.
*/
export function isExclusiveForwardNodeMessage(message: JsonValue, autoEscape: boolean): boolean {
return exclusiveForwardNodeList(message, autoEscape) !== null;
}
/** Node segments from an exclusive forward payload, or null if it is not one. */
export function exclusiveForwardNodeList(
message: JsonValue,
@@ -318,6 +328,55 @@ function requireCoordinate(data: Record<string, unknown>, field: 'lat' | 'lon'):
return text;
}
function replyInteger(
data: Record<string, unknown>,
field: string,
defaultValue: number,
max: number,
min = 1,
): number {
const raw = data[field];
const value = raw === undefined ? defaultValue : intOr(raw);
if (raw === null || (typeof raw === 'string' && !raw.trim()) || value < min || value > max) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`reply.${field} must be an integer between ${min} and ${max}`,
'reply',
field,
);
}
return value;
}
async function parseForwardReply(
data: Record<string, unknown>,
context: ForwardReplyContext,
): Promise<MessageElement> {
const { message, ...metadata } = data;
assertScalarSegmentData('reply', metadata);
const replySenderUin = replyInteger(data, 'qq', context.senderUin, Number.MAX_SAFE_INTEGER);
const replyTime = replyInteger(
data,
'time',
context.time ?? Math.floor(Date.now() / 1000),
0xffffffff,
0,
);
// A synthetic quote has no live message to navigate to; QQ still needs a
// positive origSeqs entry to render its inline preview.
const replySeq = replyInteger(data, 'seq', 1, 0xffffffff);
const elements = await parseMessage(message, false, { replyPreview: true });
return validatedOutboundElement({
type: 'reply',
replySeq,
replySenderUin,
replyTime,
replyElements: elementsToReplyPreview(elements),
});
}
export async function segmentToElement(
type: string,
data: Record<string, unknown>,
@@ -325,6 +384,23 @@ export async function segmentToElement(
): Promise<MessageElement | null> {
const normalizedType = normalizeSegmentType(type);
if (options?.replyPreview) {
assertReplyPreviewType(normalizedType);
}
if (normalizedType === 'reply' && Object.hasOwn(data, 'message')) {
if (!options?.forwardReply) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'reply.message is only supported inside a forward node',
'reply',
'message',
);
}
return parseForwardReply(data, options.forwardReply);
}
// Ordinary OneBot segment fields are scalar. JSON deliberately accepts its
// object-valued data/config compatibility fields; every other object/array
// is rejected before a codec can coerce it and alter caller intent. Forward
@@ -593,7 +669,7 @@ function segmentPayload(seg: MessageSegment): Record<string, unknown> {
// --- Public API ---
export async function parseMessage(
message: JsonValue,
message: unknown,
autoEscape: boolean,
options?: ParseMessageOptions,
): Promise<MessageElement[]> {
@@ -658,7 +734,7 @@ export async function parseMessage(
// Single segment object
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
const seg = message as unknown as MessageSegment;
const seg = message as MessageSegment;
if (typeof seg.type === 'string' && seg.type.trim()) {
const data = segmentPayload(seg);
@@ -65,7 +65,7 @@ export async function runMessageStoreMigrationWorker(
port.on('message', handleControlMessage);
try {
prepareMessageStoreDatabase(data.dbPath);
await prepareMessageStoreDatabase(data.dbPath);
await migrateLegacyMedia(data.dbPath, () => cancelled);
if (cancelled) {
@@ -88,7 +88,7 @@ export async function runMessageStoreMigrationWorker(
let lastProgressAt: number | null = null;
while (!cancelled) {
const status = migrator.runBatch(DEFAULT_BATCH_SIZE);
const status = await migrator.runBatch(DEFAULT_BATCH_SIZE);
const progressAt = performance.now();
port.postMessage({
kind: 'progress',
@@ -110,7 +110,7 @@ export async function runMessageStoreMigrationWorker(
} satisfies MessageStoreMigrationWorkerMessage);
} finally {
port.off('message', handleControlMessage);
migrator?.close();
await migrator?.close();
}
}
+181 -166
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,149 +38,158 @@ interface PendingMessageRow {
}
export class MessageStoreMigrator {
private readonly db: DatabaseSync;
private readonly selectInitialBatch: StatementSync;
private readonly selectNextBatch: StatementSync;
private readonly updateRow: StatementSync;
private readonly updateState: StatementSync;
private state: MigrationStateRow;
private readonly db: SqliteDatabase;
private selectInitialBatch!: SqliteStatement;
private selectNextBatch!: SqliteStatement;
private updateRow!: SqliteStatement;
private updateState!: SqliteStatement;
private state!: MigrationStateRow;
readonly initialization: Promise<void>;
constructor(
dbPath: string,
reportPreparation?: (progress: MessageStoreMigrationPreparation) => void,
) {
this.db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
try {
createMigrationStateTable(this.db);
this.state = this.loadOrCreateState(reportPreparation);
this.initialization = this.db.serial(async () => {
await createMigrationStateTable(this.db);
this.state = await this.loadOrCreateState(reportPreparation);
this.selectInitialBatch = this.db.prepare(`
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
FROM messages
WHERE classification_version < ?
ORDER BY message_hash ASC
LIMIT ?
`);
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
FROM messages
WHERE classification_version < ?
ORDER BY message_hash ASC
LIMIT ?
`);
this.selectNextBatch = this.db.prepare(`
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
FROM messages
WHERE classification_version < ? AND message_hash > ?
ORDER BY message_hash ASC
LIMIT ?
`);
SELECT message_hash, is_group, sequence, sequence_authoritative, client_sequence, private_direction, random, data
FROM messages
WHERE classification_version < ? AND message_hash > ?
ORDER BY message_hash ASC
LIMIT ?
`);
this.updateRow = this.db.prepare(`
UPDATE messages
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
WHERE message_hash = ?
AND classification_version < ?
AND is_group = ?
AND sequence = ?
AND sequence_authoritative = ?
AND client_sequence = ?
AND private_direction = ?
AND random = ?
AND data IS ?
`);
UPDATE messages
SET sequence_authoritative = ?, private_direction = ?, classification_version = ?
WHERE message_hash = ?
AND classification_version < ?
AND is_group = ?
AND sequence = ?
AND sequence_authoritative = ?
AND client_sequence = ?
AND private_direction = ?
AND random = ?
AND data IS ?
`);
this.updateState = this.db.prepare(`
UPDATE message_store_migration_state
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
WHERE name = ?
`);
} catch (error) {
this.db.close();
throw error;
}
UPDATE message_store_migration_state
SET phase = ?, processed = ?, total = ?, cursor = ?, updated_at = ?
WHERE name = ?
`);
});
void this.initialization.catch(() => undefined);
}
close(): void {
this.db.close();
async close(): Promise<void> {
await this.initialization.catch(() => undefined);
await this.db.close();
}
getStatus(): MessageStoreMigrationStatus {
return publicStatus(this.state);
async getStatus(): Promise<MessageStoreMigrationStatus> {
return this.db.serial(async () => {
await this.initialization;
return publicStatus(this.state);
});
}
runBatch(batchSize: number): MessageStoreMigrationStatus {
const limit = normalizeBatchSize(batchSize);
async runBatch(batchSize: number): Promise<MessageStoreMigrationStatus> {
return this.db.serial(async () => {
await this.initialization;
const limit = normalizeBatchSize(batchSize);
if (this.state.phase === 'complete') {
return this.getStatus();
}
let rows = this.readBatch(limit, this.state.cursor);
if (rows.length === 0 && this.state.cursor !== null) {
rows = this.readBatch(limit, null);
}
if (rows.length === 0) {
const remaining = this.countPending();
this.persistState({
...this.state,
phase: remaining === 0 ? 'complete' : 'migrating',
processed: remaining === 0 ? this.state.total : this.state.total - remaining,
cursor: null,
});
return this.getStatus();
}
const lastMessageHash = rows[rows.length - 1].message_hash;
const classified = rows.map((row) => ({ row, classification: classifyLegacyMessage(row) }));
let updatedRows = 0;
this.db.exec('BEGIN IMMEDIATE');
try {
for (const { row, classification } of classified) {
const result = this.updateRow.run(
classification.sequenceAuthoritative ? 1 : 0,
classification.privateDirection,
CLASSIFICATION_VERSION,
row.message_hash,
CLASSIFICATION_VERSION,
row.is_group,
row.sequence,
row.sequence_authoritative,
row.client_sequence,
row.private_direction,
row.random,
row.data,
);
updatedRows += Number(result.changes);
if (this.state.phase === 'complete') {
return this.getStatus();
}
const nextState: MigrationStateRow = {
...this.state,
processed: Math.min(this.state.total, this.state.processed + updatedRows),
cursor: lastMessageHash,
};
this.writeState(nextState);
this.db.exec('COMMIT');
this.state = nextState;
} catch (error) {
this.db.exec('ROLLBACK');
throw error;
}
let rows = await this.readBatch(limit, this.state.cursor);
if (rows.length < limit) {
const remaining = this.countPending();
if (rows.length === 0 && this.state.cursor !== null) {
rows = await this.readBatch(limit, null);
}
if (remaining === 0) {
this.persistState({
if (rows.length === 0) {
const remaining = await this.countPending();
await this.persistState({
...this.state,
phase: 'complete',
processed: this.state.total,
phase: remaining === 0 ? 'complete' : 'migrating',
processed: remaining === 0 ? this.state.total : this.state.total - remaining,
cursor: null,
});
return this.getStatus();
}
}
return this.getStatus();
const lastMessageHash = rows[rows.length - 1].message_hash;
const classified = rows.map((row) => ({
row,
classification: classifyLegacyMessage(row),
}));
let updatedRows = 0;
await this.db.exec('BEGIN IMMEDIATE');
try {
for (const { row, classification } of classified) {
const result = await this.updateRow.run(
classification.sequenceAuthoritative ? 1 : 0,
classification.privateDirection,
CLASSIFICATION_VERSION,
row.message_hash,
CLASSIFICATION_VERSION,
row.is_group,
row.sequence,
row.sequence_authoritative,
row.client_sequence,
row.private_direction,
row.random,
row.data,
);
updatedRows += Number(result.changes);
}
const nextState: MigrationStateRow = {
...this.state,
processed: Math.min(this.state.total, this.state.processed + updatedRows),
cursor: lastMessageHash,
};
await this.writeState(nextState);
await this.db.exec('COMMIT');
this.state = nextState;
} catch (error) {
await this.db.exec('ROLLBACK');
throw error;
}
if (rows.length < limit) {
const remaining = await this.countPending();
if (remaining === 0) {
await this.persistState({
...this.state,
phase: 'complete',
processed: this.state.total,
cursor: null,
});
}
}
return this.getStatus();
});
}
private loadOrCreateState(
private async loadOrCreateState(
reportPreparation?: (progress: MessageStoreMigrationPreparation) => void,
): MigrationStateRow {
const existing = this.db
): Promise<MigrationStateRow> {
const existing = (await this.db
.prepare(
`
SELECT phase, processed, total, cursor
@@ -188,7 +197,7 @@ export class MessageStoreMigrator {
WHERE name = ?
`,
)
.get(MIGRATION_NAME) as MigrationStateRow | undefined;
.get(MIGRATION_NAME)) as MigrationStateRow | undefined;
if (existing?.phase === 'complete') {
return existing;
@@ -196,7 +205,7 @@ export class MessageStoreMigrator {
reportPreparation?.({ stage: 'started' });
const preparationStartedAt = performance.now();
this.db.exec(`
await this.db.exec(`
CREATE INDEX IF NOT EXISTS ${PENDING_INDEX_NAME}
ON messages(message_hash, classification_version)
WHERE classification_version < ${CLASSIFICATION_VERSION}
@@ -211,7 +220,7 @@ export class MessageStoreMigrator {
}
const countStartedAt = performance.now();
const row = this.db
const row = (await this.db
.prepare(
`
SELECT COUNT(*) AS total
@@ -219,7 +228,7 @@ export class MessageStoreMigrator {
WHERE classification_version < ?
`,
)
.get(CLASSIFICATION_VERSION) as { total: number };
.get(CLASSIFICATION_VERSION)) as { total: number };
const total = Number(row.total);
reportPreparation?.({
stage: 'counted',
@@ -233,7 +242,7 @@ export class MessageStoreMigrator {
total,
cursor: null,
};
this.db
await this.db
.prepare(
`
INSERT INTO message_store_migration_state
@@ -245,8 +254,8 @@ export class MessageStoreMigrator {
return state;
}
private countPending(): number {
const row = this.db
private async countPending(): Promise<number> {
const row = (await this.db
.prepare(
`
SELECT COUNT(*) AS total
@@ -254,35 +263,35 @@ export class MessageStoreMigrator {
WHERE classification_version < ?
`,
)
.get(CLASSIFICATION_VERSION) as { total: number };
.get(CLASSIFICATION_VERSION)) as { total: number };
return Number(row.total);
}
private readBatch(limit: number, cursor: number | null): PendingMessageRow[] {
private async readBatch(limit: number, cursor: number | null): Promise<PendingMessageRow[]> {
return (cursor === null
? this.selectInitialBatch.all(CLASSIFICATION_VERSION, limit)
: this.selectNextBatch.all(
? await this.selectInitialBatch.all(CLASSIFICATION_VERSION, limit)
: await this.selectNextBatch.all(
CLASSIFICATION_VERSION,
cursor,
limit,
)) as unknown as PendingMessageRow[];
}
private persistState(state: MigrationStateRow): void {
this.db.exec('BEGIN IMMEDIATE');
private async persistState(state: MigrationStateRow): Promise<void> {
await this.db.exec('BEGIN IMMEDIATE');
try {
this.writeState(state);
this.db.exec('COMMIT');
await this.writeState(state);
await this.db.exec('COMMIT');
this.state = state;
} catch (error) {
this.db.exec('ROLLBACK');
await this.db.exec('ROLLBACK');
throw error;
}
}
private writeState(state: MigrationStateRow): void {
this.updateState.run(
private async writeState(state: MigrationStateRow): Promise<void> {
await this.updateState.run(
state.phase,
state.processed,
state.total,
@@ -293,12 +302,12 @@ export class MessageStoreMigrator {
}
}
export function prepareMessageStoreDatabase(dbPath: string): void {
export async function prepareMessageStoreDatabase(dbPath: string): Promise<void> {
const db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
try {
const messagesTableExists =
db
(await db
.prepare(
`
SELECT 1 AS present
@@ -306,8 +315,8 @@ export function prepareMessageStoreDatabase(dbPath: string): void {
WHERE type = 'table' AND name = 'messages'
`,
)
.get() !== undefined;
db.exec(`
.get()) !== undefined;
await db.exec(`
CREATE TABLE IF NOT EXISTS messages (
message_hash INTEGER PRIMARY KEY,
is_group INTEGER NOT NULL,
@@ -323,22 +332,24 @@ export function prepareMessageStoreDatabase(dbPath: string): void {
classification_version INTEGER NOT NULL DEFAULT 1
)
`);
prepareMessageStoreSchema(db);
await prepareMessageStoreSchema(db);
if (!messagesTableExists) {
createMessageStoreIndexes(db);
await createMessageStoreIndexes(db);
}
} finally {
db.close();
await db.close();
}
}
export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrationStatus {
export async function inspectMessageStoreMigration(
dbPath: string,
): Promise<MessageStoreMigrationStatus> {
const db = openSqliteDb(dbPath.replace(/\.json$/, '.db'));
try {
createMigrationStateTable(db);
const row = db
await createMigrationStateTable(db);
const row = (await db
.prepare(
`
SELECT phase, processed, total
@@ -346,13 +357,13 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
WHERE name = ?
`,
)
.get(MIGRATION_NAME) as MessageStoreMigrationStatus | undefined;
.get(MIGRATION_NAME)) as MessageStoreMigrationStatus | undefined;
if (row) {
return row;
}
const pending = db
const pending = (await db
.prepare(
`
SELECT COUNT(*) AS total
@@ -360,62 +371,66 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
WHERE classification_version < ?
`,
)
.get(CLASSIFICATION_VERSION) as { total: number };
.get(CLASSIFICATION_VERSION)) as { total: number };
const total = Number(pending.total);
return { phase: total === 0 ? 'complete' : 'migrating', processed: 0, total };
} finally {
db.close();
await db.close();
}
}
export function prepareMessageStoreSchema(db: DatabaseSync): void {
const before = db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>;
export async function prepareMessageStoreSchema(db: SqliteDatabase): Promise<void> {
const before = (await db.prepare('PRAGMA table_info(messages)').all()) as Array<{
name: string;
}>;
const existingColumns = new Set(before.map((column) => column.name));
if (!existingColumns.has('media_data')) {
db.exec('ALTER TABLE messages ADD COLUMN media_data TEXT');
await db.exec('ALTER TABLE messages ADD COLUMN media_data TEXT');
}
const existingRowsAreCurrent =
existingColumns.has('sequence_authoritative') &&
existingColumns.has('private_direction') &&
hasLegacyPrivateSequenceMigration(db);
(await hasLegacyPrivateSequenceMigration(db));
if (!existingColumns.has('sequence_authoritative')) {
db.exec(
await db.exec(
'ALTER TABLE messages ADD COLUMN sequence_authoritative INTEGER NOT NULL DEFAULT 1',
);
}
if (!existingColumns.has('private_direction')) {
db.exec('ALTER TABLE messages ADD COLUMN private_direction INTEGER NOT NULL DEFAULT -1');
await db.exec(
'ALTER TABLE messages ADD COLUMN private_direction INTEGER NOT NULL DEFAULT -1',
);
}
if (!existingColumns.has('classification_version')) {
db.exec(
await db.exec(
`ALTER TABLE messages ADD COLUMN classification_version INTEGER NOT NULL DEFAULT ${existingRowsAreCurrent ? CLASSIFICATION_VERSION : 0}`,
);
}
}
export function createMessageStoreIndexes(db: DatabaseSync): void {
db.exec(
export async function createMessageStoreIndexes(db: SqliteDatabase): Promise<void> {
await db.exec(
'CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)',
);
db.exec(
await db.exec(
'CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)',
);
db.exec(
await db.exec(
'CREATE INDEX IF NOT EXISTS idx_messages_private_client_seq ON messages(is_group, session_id, client_sequence)',
);
db.exec(
await db.exec(
'CREATE INDEX IF NOT EXISTS idx_messages_private_client_direction ON messages(is_group, session_id, client_sequence, private_direction)',
);
}
function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
async function hasLegacyPrivateSequenceMigration(db: SqliteDatabase): Promise<boolean> {
const tableExists =
db
(await db
.prepare(
`
SELECT 1 AS present
@@ -423,14 +438,14 @@ function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
WHERE type = 'table' AND name = 'message_store_migrations'
`,
)
.get() !== undefined;
.get()) !== undefined;
if (!tableExists) {
return false;
}
return (
db
(await db
.prepare(
`
SELECT 1 AS applied
@@ -438,12 +453,12 @@ function hasLegacyPrivateSequenceMigration(db: DatabaseSync): boolean {
WHERE name = ?
`,
)
.get(LEGACY_PRIVATE_SEQUENCE_MIGRATION) !== undefined
.get(LEGACY_PRIVATE_SEQUENCE_MIGRATION)) !== undefined
);
}
function createMigrationStateTable(db: DatabaseSync): void {
db.exec(`
async function createMigrationStateTable(db: SqliteDatabase): Promise<void> {
await db.exec(`
CREATE TABLE IF NOT EXISTS message_store_migration_state (
name TEXT PRIMARY KEY,
phase TEXT NOT NULL,
File diff suppressed because it is too large. Load diff
+148 -51
View File
@@ -1,19 +1,137 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/protocol/events';
import { createLogger } from '@snowluma/common/logger';
import type { ImageUrlResolver } from '../event-converter';
import type { MediaStore } from '../media-store';
import type { CachedImage, MediaStore } from '../media-store';
import type { MessageStore } from '../message-store';
import type { OneBotInstanceContext } from '../instance-context';
import { resolveRemoteMediaUrl } from '../media-url-resolver';
import { segmentsToRawMessage } from '../helper/cq';
import {
deliverPttTransText,
failPttTransWaiter,
pttTransKey,
waitPttTransText,
} from './ptt-trans-waiter';
import type { JsonObject } from '../types';
import type { JsonObject, JsonValue } from '../types';
const log = createLogger('OneBot');
type StoredMediaSegment = JsonObject & { type: 'image' | 'record' | 'video'; data: JsonObject };
function isStoredMediaSegment(segment: JsonValue): segment is StoredMediaSegment {
return (
segment !== null &&
typeof segment === 'object' &&
!Array.isArray(segment) &&
(segment.type === 'image' || segment.type === 'record' || segment.type === 'video') &&
segment.data !== null &&
typeof segment.data === 'object' &&
!Array.isArray(segment.data)
);
}
export async function refreshMessageMedia(
ref: Pick<OneBotInstanceContext, 'bridge' | 'messageStore' | 'mediaStore' | 'converterCtx'>,
messageId: number,
event: JsonObject,
): Promise<void> {
if (!Array.isArray(event.message)) {
return;
}
const segments = event.message.filter(isStoredMediaSegment);
const voiceVideoSegments = segments.filter((segment) => segment.type !== 'image');
const media =
voiceVideoSegments.length > 0
? (await ref.messageStore.findMedia(messageId))?.filter(
(element) => element.type !== 'image',
)
: null;
const meta = voiceVideoSegments.length > 0 ? await ref.messageStore.findMeta(messageId) : null;
// Validate the ordered association once; a filename lookup can select another upload.
const voiceVideo =
meta &&
media &&
media.length === voiceVideoSegments.length &&
media.every((element, index) => element.type === voiceVideoSegments[index]!.type)
? { media, meta }
: null;
if (voiceVideoSegments.length > 0 && !voiceVideo) {
log.warn('[get_msg] media metadata missing or inconsistent message_id=%d', messageId);
}
let voiceVideoIndex = 0;
let changed = false;
for (const [index, segment] of segments.entries()) {
try {
let url: string | null;
if (segment.type === 'image') {
const file =
typeof segment.data.file === 'string'
? segment.data.file
: segment.data.file_id;
if (typeof file !== 'string' || !file) {
continue;
}
url = await resolveImageUrl(
await ref.mediaStore.findImage(file),
ref.converterCtx.imageUrlResolver,
);
} else {
if (!voiceVideo) {
continue;
}
const element = voiceVideo.media[voiceVideoIndex++]!;
url = await resolveRemoteMediaUrl(
ref.bridge,
element.type,
element.mediaNode,
voiceVideo.meta.isGroup,
voiceVideo.meta.targetId,
);
}
if (url && url !== segment.data.url) {
segment.data.url = url;
changed = true;
}
} catch (err) {
// Refresh failure preserves this message's URL, never a different cached URL.
log.warn(
'[get_msg] media URL refresh failed message_id=%d type=%s media_index=%d: %s',
messageId,
segment.type,
index,
err instanceof Error ? err.message : String(err),
);
}
}
if (changed) {
event.raw_message = segmentsToRawMessage(event.message);
}
}
async function resolveImageUrl(
cached: CachedImage | null,
resolver?: ImageUrlResolver | null,
): Promise<string | null> {
if (!cached?.imageUrl || !resolver) {
return null;
}
return resolver(
{ type: 'image', imageUrl: cached.imageUrl, subType: cached.subType },
cached.isGroup,
);
}
/**
* Voice-to-text for a received ptt (issue #79 / NapCat `fetch_ptt_text`).
* Resolves the message's `record` segment to its cached fingerprint
@@ -27,7 +145,7 @@ export async function fetchPttText(
selfId: number,
messageId: number,
): Promise<{ text: string }> {
const event = messageStore.findEvent(messageId);
const event = await messageStore.findEvent(messageId);
if (!event) {
throw new Error('消息不存在或已被撤回');
@@ -59,16 +177,16 @@ export async function fetchPttText(
throw new Error('消息中不包含语音');
}
const snapshot = messageStore
.findMedia(messageId)
?.find((element) => element.type === 'record');
const snapshot = (await messageStore.findMedia(messageId))?.find(
(element) => element.type === 'record',
);
const cached = snapshot
? {
...snapshot,
isGroup: event.message_type === 'group',
sessionId: Number(event.group_id) || selfId,
}
: mediaStore.findRecord(file, 'legacy');
: await mediaStore.findRecord(file, 'legacy');
if (!cached) {
throw new Error('语音不在缓存中,无法转写');
@@ -114,7 +232,7 @@ export async function getImageInfo(
file: string,
imageUrlResolver?: ImageUrlResolver | null,
): Promise<JsonObject | null> {
const cached = mediaStore.findImage(file);
const cached = await mediaStore.findImage(file);
if (!cached) {
return null;
@@ -122,27 +240,17 @@ export async function getImageInfo(
let url = cached.url || cached.imageUrl || '';
// Re-sign with a current rkey at lookup time. The stored `url` was signed
// when the message first arrived and its rkey may have since expired — the
// CDN then rejects the download with
// `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw
// (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which
// re-signs on every getImageUrl call instead of handing back a baked URL.
if (imageUrlResolver && cached.imageUrl) {
try {
const element: MessageElement = {
type: 'image',
imageUrl: cached.imageUrl,
subType: cached.subType,
};
const fresh = await imageUrlResolver(element, cached.isGroup);
try {
const fresh = await resolveImageUrl(cached, imageUrlResolver);
if (fresh) {
url = fresh;
}
} catch {
// Best-effort: fall back to the stored URL on any resolver failure.
if (fresh) {
url = fresh;
}
} catch (err) {
log.warn(
'get_image URL refresh failed: %s',
err instanceof Error ? err.message : String(err),
);
}
return {
@@ -158,34 +266,23 @@ export async function getRecordInfo(
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findRecord(file);
const cached = await mediaStore.findRecord(file);
if (!cached) {
return null;
}
let url = cached.url;
if (!url && cached.mediaNode) {
try {
url = cached.isGroup
? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode)
: await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode);
if (url) {
mediaStore.updateRecordUrl(file, url);
}
} catch (err) {
log.warn(
'get_record url refetch failed: %s',
err instanceof Error ? err.message : String(err),
);
}
}
const url = await resolveRemoteMediaUrl(
bridge,
'record',
cached.mediaNode,
cached.isGroup,
cached.sessionId,
);
await mediaStore.updateRecordUrl(file, url);
return {
file: url || cached.file,
url: url || '',
file: url,
url,
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
+164 -209
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';
@@ -26,6 +27,7 @@ import {
} from '../message-parser';
import type { MessageStore } from '../message-store';
import { sameSelfSentMessage } from '../self-sent-event';
import { replyPreviewElements } from '../reply-preview';
import {
hasAuthoritativeSequence,
type JsonArray,
@@ -36,49 +38,6 @@ import {
const log = createLogger('OneBot');
function replyPreviewElements(message: unknown): MessageElement[] {
if (!Array.isArray(message)) {
return [];
}
const labels: Record<string, string> = {
image: '[图片]',
record: '[语音]',
video: '[视频]',
file: '[文件]',
face: '[表情]',
mface: '[表情]',
forward: '[聊天记录]',
json: '[卡片]',
xml: '[卡片]',
markdown: '[Markdown]',
};
const parts: string[] = [];
for (const segment of message) {
if (!segment || typeof segment !== 'object') {
continue;
}
const data = segment.data;
if (!data || typeof data !== 'object') {
continue;
}
if (segment.type === 'text' && typeof data.text === 'string') {
parts.push(data.text);
} else if (segment.type === 'at') {
parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
} else if (typeof segment.type === 'string' && labels[segment.type]) {
parts.push(labels[segment.type]);
}
}
const text = parts.join('');
return text ? [{ type: 'text', text }] : [];
}
// A video larger than QQ's Highway video ceiling can't be sent through the
// element pipeline — it must fall back to a regular file upload. The fallback
// is decided at the OneBot layer (not element-builder) because building a
@@ -167,7 +126,7 @@ export async function getGroupMsgHistory(
let anchorSequence: number | undefined;
if (hasAnchor) {
const meta = messageStore.findMeta(messageId as number);
const meta = await messageStore.findMeta(messageId as number);
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
return [];
@@ -176,7 +135,7 @@ export async function getGroupMsgHistory(
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(
const events = await messageStore.listSessionEvents(
true,
groupId,
limit,
@@ -212,7 +171,7 @@ export async function getFriendMsgHistory(
let anchorSequence: number | undefined;
if (hasAnchor) {
const meta = messageStore.findMeta(messageId as number);
const meta = await messageStore.findMeta(messageId as number);
if (!hasAuthoritativeSequence(meta) || meta.isGroup || meta.targetId !== userId) {
return [];
@@ -221,7 +180,7 @@ export async function getFriendMsgHistory(
anchorSequence = meta.sequence;
}
const events = messageStore.listSessionEvents(
const events = await messageStore.listSessionEvents(
false,
userId,
limit,
@@ -272,7 +231,7 @@ export async function getGroupHistory(
let anchorSeq = 0;
if (hasAnchor) {
const meta = ref.messageStore.findMeta(messageId as number);
const meta = await ref.messageStore.findMeta(messageId as number);
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
// Anchor we don't know — best effort from the local store.
@@ -281,7 +240,7 @@ export async function getGroupHistory(
anchorSeq = meta.sequence;
} else {
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0;
anchorSeq = (await ref.messageStore.findLatestAuthoritativeSequence(true, groupId)) ?? 0;
}
log.debug(
@@ -309,7 +268,7 @@ export async function getGroupHistory(
continue;
}
persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
await persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
}
@@ -365,13 +324,15 @@ export async function getFriendHistory(
let anchorSeq = 0;
if (hasAnchor) {
const meta = ref.messageStore.findMeta(messageId as number);
const meta = await ref.messageStore.findMeta(messageId as number);
// Older self-sent rows may be keyed by selfId. Only accept one of those
// when its stored target_id proves that it belongs to this peer; otherwise
// a message_id from another private conversation could select the wrong
// server sequence.
const storedEvent =
meta?.targetId === ref.selfId ? ref.messageStore.findEvent(messageId as number) : null;
meta?.targetId === ref.selfId
? await ref.messageStore.findEvent(messageId as number)
: null;
const belongsToPeer =
meta?.targetId === userId ||
(meta?.targetId === ref.selfId && toHistoryInt(storedEvent?.target_id) === userId);
@@ -422,11 +383,15 @@ export async function getFriendHistory(
continue;
}
// Conversion can await media resolution, so consult the tombstone only
// after it settles. From this check through persistence/return there is no
// async gap in which a recall could race past us.
// Conversion can await media resolution, so check again after it settles.
// Persistence also checks recalls queued while this lookup is in flight.
if (
ref.messageStore.isPrivateMessageRecalled(userId, clientSequence, sentBySelf, ev.time)
await ref.messageStore.isPrivateMessageRecalled(
userId,
clientSequence,
sentBySelf,
ev.time,
)
) {
log.debug(
'friend history omitted recalled message: user=%d clientSeq=%d self=%s',
@@ -443,8 +408,9 @@ export async function getFriendHistory(
json.target_id = userId;
}
persistHistoryEvent(ref.messageStore, json, userId, ev);
out.push(sanitizeMessageEventForApi(json));
if (await persistHistoryEvent(ref.messageStore, json, userId, ev)) {
out.push(sanitizeMessageEventForApi(json));
}
}
log.debug(
@@ -505,7 +471,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
const eventName = isGroup
? GROUP_MESSAGE_EVENT
: privateMessageEventName(quotedSender === ref.selfId, false);
const resolvedId = ref.converterCtx.messageIdResolver?.(
const resolvedId = await ref.converterCtx.messageIdResolver?.(
isGroup,
session,
replySeq,
@@ -517,7 +483,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
? (resolvedId as number)
: hashMessageIdInt32(replySeq, session, eventName);
if (ref.messageStore.findEvent(targetId)) {
if (await ref.messageStore.findEvent(targetId)) {
return;
} // Tier 0: already have the full event
@@ -568,12 +534,19 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
json.message_id = targetId;
if (fetched.kind === 'group_message') {
ref.messageStore.storeEvent(targetId, true, session, replySeq, eventName, json);
await ref.messageStore.storeEvent(
targetId,
true,
session,
replySeq,
eventName,
json,
);
} else {
const serverSequence = fetched.ntMsgSeq ?? 0;
const sequenceAuthoritative =
fetched.sequenceAuthoritative !== false && serverSequence > 0;
ref.messageStore.storeMeta(targetId, {
await ref.messageStore.storeMeta(targetId, {
isGroup: false,
targetId: session,
sequence: serverSequence,
@@ -585,16 +558,14 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
random: fetched.msgId,
timestamp: fetched.time,
});
ref.messageStore.storeEvent(
await ref.messageStore.storeEvent(
targetId,
false,
session,
serverSequence,
eventName,
json,
{
sequenceAuthoritative,
},
{ sequenceAuthoritative },
);
}
@@ -632,9 +603,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
// Inline quote metadata proves what was displayed, but not that replySeq
// still names a server-backed roam message. Keep it queryable via
// get_msg without letting it become a history/recall/reply anchor.
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback, {
sequenceAuthoritative: false,
});
await ref.messageStore.storeEvent(
targetId,
isGroup,
session,
replySeq,
eventName,
fallback,
{ sequenceAuthoritative: false },
);
return;
} catch (err) {
log.warn(
@@ -657,9 +634,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
isGroup,
session,
);
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder, {
sequenceAuthoritative: false,
});
await ref.messageStore.storeEvent(
targetId,
isGroup,
session,
replySeq,
eventName,
placeholder,
{ sequenceAuthoritative: false },
);
}
// Build a stored-message event for a backfilled reply target (Tier 2/3).
@@ -743,7 +726,7 @@ export async function setEssenceMessage(
messageId: number,
enable: boolean,
): Promise<void> {
const meta = messageStore.findMeta(messageId);
const meta = await messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) {
throw new Error('message not found or not a group message');
@@ -757,30 +740,9 @@ export async function setEssenceMessage(
}
/**
* Build + store a synthetic OneBot event for a just-sent message so
* `/get_msg` can find it.
*
* The QQ server doesn't always echo self-sent messages back on the
* receive channel — Lagrange and NapCat both work around this by
* writing a local copy at send time (Lagrange persists into Realm DB
* inside `SendMessageOperation`; NapCat caches in-memory via its msg
* service). Without it, callers that hit `/get_msg` with a freshly-
* returned `message_id` get "message not found" even though the recall
* path works fine (recall uses the lighter `cacheMessageMeta` already).
*
* Stored event has `post_type: 'message_sent'` so OneBot clients that
* inspect it through `/get_msg` can distinguish their own outbound
* messages from incoming ones.
*/
/**
* The shared "record a self-sent message" tail: derive the OneBot message id
* from (sequence, target, event), then cache both the meta and the self-sent
* copy. Centralizes the `isGroup ↔ eventName ↔ hashMessageIdInt32 event
* constant` coupling that was hand-paired in six send/forward paths — a
* mismatch there silently produced a wrong message_id or wrong event
* attribution. Returns the derived message id and, for an eligible plain C2C
* Action send, an event for the OneBot dispatch path when QQ has not already
* supplied the canonical echo.
* Derive the same message id for send/receive paths and persist the sent
* message for get_msg, since QQ does not always echo it. Eligible C2C sends
* also return a message_sent event when no canonical echo has arrived.
*/
async function finalizeSend(
ref: OneBotInstanceContext,
@@ -810,7 +772,7 @@ async function finalizeSend(
: Number.isInteger(opaqueMessageId) && opaqueMessageId !== 0
? opaqueMessageId
: hashMessageIdInt32(isGroup ? 0 : receipt.clientSequence, targetId, eventName);
ref.cacheMessageMeta(messageId, {
await ref.cacheMessageMeta(messageId, {
isGroup,
targetId,
sequence: receipt.sequence,
@@ -865,35 +827,16 @@ async function cacheSelfSentMessage(
elements,
} = options;
if (!Number.isInteger(messageId) || messageId === 0) {
return null;
}
// Defensive: tests may mock `ref.messageStore` without the full MessageStore
// surface. Production always has it. Without storage, recall still works via
// cacheMessageMeta, but `/get_msg` and the synthetic event are unavailable.
const storeEvent = (ref.messageStore as { storeEvent?: typeof ref.messageStore.storeEvent })
.storeEvent;
if (typeof storeEvent !== 'function') {
return null;
}
try {
// We deliberately pass no URL resolvers — for a synthetic self-sent
// event the file/url fields in segments are best-effort (they're
// already what the OneBot caller passed in). Image/video URLs would
// need a real resolver to render in `/get_msg`, but the existing
// resolver is async and bound to the receive pipeline; skipping it
// means /get_msg returns the segment with the original `file` path
// and an empty `url`, which is what Lagrange does too.
// Persist upload metadata without another QQ request on the send path.
// get_msg / get_record resolve remote media URLs when the consumer reads.
const segments = (await elementsToOneBotSegments(
{
selfId: ref.selfId,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
mediaSegmentSink: ref.converterCtx.mediaSegmentSink,
},
elements,
isGroup,
@@ -939,7 +882,7 @@ async function cacheSelfSentMessage(
// QQ can win the race between the send receipt and local event
// construction. Keep its richer canonical event and let the already-run
// bridge dispatch remain the single downstream notification.
const existing = ref.messageStore.findEvent(messageId);
const existing = await ref.messageStore.findEvent(messageId);
if (existing && sameSelfSentMessage(existing, event)) {
return null;
@@ -947,17 +890,14 @@ async function cacheSelfSentMessage(
// Persist before dispatch so `/get_msg` is immediately consistent for a
// client reacting to the synthetic message_sent notification.
storeEvent.call(
ref.messageStore,
await ref.messageStore.storeEvent(
messageId,
isGroup,
sessionId,
sequence,
eventName,
event,
{
sequenceAuthoritative,
},
{ sequenceAuthoritative },
);
return event;
} catch (err) {
@@ -999,7 +939,7 @@ export async function sendPrivateMessage(
/** When set, reply into this group's temp session instead of friend c2c. */
tempGroupId?: number,
/** Reports each actual friend message as soon as its authoritative receipt arrives. */
onSelfSent?: (event: JsonObject) => void,
onSelfSent?: (event: JsonObject) => void | Promise<void>,
): Promise<MessageSendResult> {
// A temp-session reply is only allowed into a session the peer opened.
const isTempReply = tempGroupId !== undefined && ref.tempSessions.has(userId, tempGroupId);
@@ -1030,10 +970,10 @@ export async function sendPrivateMessage(
}
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
resolveReplySequence: async (replyMessageId) => {
return await ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
resolveReplyMeta: async (replyMessageId) => {
// Prefer the cached event (it carries the REAL sender). When only
// meta exists — typically because the message we're replying to was
// sent by the bot itself and never round-tripped through dispatch
@@ -1041,7 +981,7 @@ export async function sendPrivateMessage(
// selfId. The previous code used `meta.targetId` here, which is the
// conversation PEER and shows the wrong "回复 @某人" in QQ for any
// self-reply.
const event = ref.messageStore.findEvent(replyMessageId);
const event = await ref.messageStore.findEvent(replyMessageId);
if (event) {
const senderUin =
@@ -1052,7 +992,7 @@ export async function sendPrivateMessage(
typeof event.time === 'number'
? event.time
: parseInt(String(event.time || '0'), 10);
const meta = ref.messageStore.findMeta(replyMessageId);
const meta = await ref.messageStore.findMeta(replyMessageId);
return {
senderUin,
time,
@@ -1062,7 +1002,7 @@ export async function sendPrivateMessage(
};
}
const meta = ref.messageStore.findMeta(replyMessageId);
const meta = await ref.messageStore.findMeta(replyMessageId);
if (meta) {
return {
@@ -1209,7 +1149,7 @@ export async function sendPrivateMessage(
lastResult = result;
if (result.echoEvent) {
onSelfSent?.(result.echoEvent);
await onSelfSent?.(result.echoEvent);
}
};
@@ -1346,17 +1286,17 @@ export async function sendGroupMessage(
}
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
resolveReplySequence: async (replyMessageId) => {
return await ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const meta = ref.messageStore.findMeta(replyMessageId);
resolveReplyMeta: async (replyMessageId) => {
const meta = await ref.messageStore.findMeta(replyMessageId);
if (!meta || !meta.isGroup || meta.targetId !== groupId) {
return null;
}
const event = ref.messageStore.findEvent(replyMessageId);
const event = await ref.messageStore.findEvent(replyMessageId);
if (event) {
return {
@@ -1527,7 +1467,7 @@ export async function sendPrivateForwardMessage(
userId: number,
messages: JsonValue,
meta?: ForwardPreviewMeta,
onSelfSent?: (event: JsonObject) => void,
onSelfSent?: (event: JsonObject) => void | Promise<void>,
): Promise<{ messageId: number; forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages, { userId });
// userId is plumbed through so inner image/record/video can be uploaded
@@ -1546,7 +1486,7 @@ export async function sendPrivateForwardMessage(
);
if (result.echoEvent) {
onSelfSent?.(result.echoEvent);
await onSelfSent?.(result.echoEvent);
}
return { messageId: result.messageId, forwardId };
@@ -1577,13 +1517,13 @@ export async function forwardSingleMessage(
ref: OneBotInstanceContext,
messageId: number,
target: { groupId?: number; userId?: number },
onSelfSent?: (event: JsonObject) => void,
onSelfSent?: (event: JsonObject) => void | Promise<void>,
): Promise<{ messageId: number }> {
if (!target.groupId && !target.userId) {
throw new Error('forward target group_id or user_id is required');
}
const event = ref.messageStore.findEvent(messageId);
const event = await ref.messageStore.findEvent(messageId);
if (!event) {
throw new Error(`message not found: ${messageId}`);
@@ -1599,7 +1539,7 @@ export async function forwardSingleMessage(
const elements = await prepareSingleForwardElements(
ref,
restoreHistoricalMedia(ref, parsed, messageId),
await restoreHistoricalMedia(ref, parsed, messageId),
target,
);
@@ -1628,7 +1568,7 @@ export async function forwardSingleMessage(
messageIdOut = result.messageId;
if (result.echoEvent) {
onSelfSent?.(result.echoEvent);
await onSelfSent?.(result.echoEvent);
}
}
@@ -1644,7 +1584,7 @@ async function prepareSingleForwardElements(
for (const element of elements) {
if (element.type !== 'forward') {
out.push(isMessageMedia(element) ? element : enrichForForward(ref, element));
out.push(isMessageMedia(element) ? element : await enrichForForward(ref, element));
continue;
}
@@ -1710,15 +1650,30 @@ async function expandForwardNodeForTarget(
target: { groupId?: number; userId?: number },
depth: number,
): Promise<ForwardNodePayload> {
const forwards = node.elements.filter(
// Fetched nodes already carry protocol media metadata, but their URLs may
// lack an rkey (or only be a file UUID). Reuse complete fingerprints in the
// target's upload scene, just as historical single-message forwarding does.
// Legacy/incomplete images still need the existing byte-source upload path.
const preparedElements = await mapWithConcurrency(node.elements, 8, async (element) => {
if (!isMessageMedia(element) || !element.md5Hex || !element.sha1Hex) {
return element;
}
if (element.type === 'image' && (!element.width || !element.height || !element.picFormat)) {
return element;
}
return await enrichForForward(ref, element, element);
});
const forwards = preparedElements.filter(
(element): element is MessageElementOf<'forward'> => element.type === 'forward',
);
if (forwards.length === 0) {
return node;
return { ...node, elements: preparedElements };
}
if (forwards.length === node.elements.length && forwards.length === 1) {
if (forwards.length === preparedElements.length && forwards.length === 1) {
const innerId = forwards[0]!.resId.trim();
if (!innerId) {
@@ -1734,7 +1689,7 @@ async function expandForwardNodeForTarget(
const elements: MessageElement[] = [];
for (const element of node.elements) {
for (const element of preparedElements) {
if (element.type !== 'forward') {
elements.push(element);
continue;
@@ -1761,18 +1716,18 @@ async function expandForwardNodeForTarget(
return { ...node, elements };
}
function restoreHistoricalMedia(
async function restoreHistoricalMedia(
ref: OneBotInstanceContext,
elements: MessageElement[],
messageId: number,
): MessageElement[] {
): Promise<MessageElement[]> {
if (!elements.some(isMessageMedia)) {
return elements;
}
const snapshots = ref.messageStore.findMedia(messageId);
const snapshots = await ref.messageStore.findMedia(messageId);
let index = 0;
const restored = elements.map((element) => {
const restored = await mapWithConcurrency(elements, 8, async (element) => {
if (!isMessageMedia(element)) {
return element;
}
@@ -1783,7 +1738,7 @@ function restoreHistoricalMedia(
throw new Error(`historical media metadata does not match message ${messageId}`);
}
return enrichForForward(ref, element, snapshot);
return await enrichForForward(ref, element, snapshot);
});
if (snapshots && index !== snapshots.length) {
@@ -1793,11 +1748,11 @@ function restoreHistoricalMedia(
return restored;
}
function enrichForForward(
async function enrichForForward(
ref: OneBotInstanceContext,
element: MessageElement,
snapshot?: MessageMedia,
): MessageElement {
): Promise<MessageElement> {
if (element.type === 'forward') {
throw new Error('merged forward must be regenerated for the target chat');
}
@@ -1833,7 +1788,9 @@ function enrichForForward(
if (element.type === 'image') {
const cached =
snapshot?.type === 'image' ? snapshot : ref.mediaStore.findImage(lookupKey, 'legacy');
snapshot?.type === 'image'
? snapshot
: await ref.mediaStore.findImage(lookupKey, 'legacy');
if (
!cached ||
@@ -1866,7 +1823,9 @@ function enrichForForward(
if (element.type === 'record') {
const cached =
snapshot?.type === 'record' ? snapshot : ref.mediaStore.findRecord(lookupKey, 'legacy');
snapshot?.type === 'record'
? snapshot
: await ref.mediaStore.findRecord(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error(
@@ -1890,7 +1849,9 @@ function enrichForForward(
if (element.type === 'video') {
const cached =
snapshot?.type === 'video' ? snapshot : ref.mediaStore.findVideo(lookupKey, 'legacy');
snapshot?.type === 'video'
? snapshot
: await ref.mediaStore.findVideo(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error(
@@ -1939,6 +1900,7 @@ export async function getForwardMessage(
node.elements,
isGroup,
sessionId,
{ includeReplyContent: true },
);
const sender: JsonObject = {
@@ -1966,7 +1928,7 @@ export async function getForwardMessage(
raw_message: '',
font: 14,
sub_type: isGroup ? 'normal' : 'friend',
message: segments as unknown as JsonValue,
message: segments,
message_format: 'array',
post_type: 'message',
};
@@ -2111,7 +2073,7 @@ function isNestedNodeArray(value: JsonValue): boolean {
for (const item of value) {
const seg = asJsonObject(item);
if (!seg || String(seg.type ?? '') !== 'node') {
if (!seg || seg.type !== 'node') {
return false;
}
}
@@ -2119,7 +2081,13 @@ function isNestedNodeArray(value: JsonValue): boolean {
return true;
}
function assertForwardNodeMetadata(nodeData: JsonObject, index: number): void {
type ForwardNodeData = JsonObject &
Pick<ForwardNodePayload, 'news' | 'title' | 'source' | 'summary' | 'prompt'>;
function assertForwardNodeMetadata(
nodeData: JsonObject,
index: number,
): asserts nodeData is ForwardNodeData {
for (const [field, value] of Object.entries(nodeData)) {
if (field === 'content' || field === 'message') {
continue;
@@ -2190,11 +2158,11 @@ function isForwardNewsArray(value: JsonValue): value is Array<{ text: string }>
return true;
}
function assertForwardMessageInputPolicies(
async function assertForwardMessageInputPolicies(
ref: OneBotInstanceContext,
messages: JsonValue,
depth = 0,
): void {
): Promise<void> {
if (!Array.isArray(messages) || depth >= MAX_FORWARD_DEPTH) {
return;
}
@@ -2217,11 +2185,11 @@ function assertForwardMessageInputPolicies(
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
if (messageId !== 0) {
const event = ref.messageStore.findEvent(messageId);
const event = await ref.messageStore.findEvent(messageId);
if (event) {
assertOutboundMessageInput(
(event.message ?? event.raw_message ?? '') as JsonValue,
event.message ?? event.raw_message ?? '',
false,
'forward',
);
@@ -2230,10 +2198,10 @@ function assertForwardMessageInputPolicies(
continue;
}
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
const content = nodeData.content ?? nodeData.message ?? '';
if (isNestedNodeArray(content)) {
assertForwardMessageInputPolicies(ref, content, depth + 1);
await assertForwardMessageInputPolicies(ref, content, depth + 1);
} else {
assertOutboundMessageInput(content, false, 'forward');
}
@@ -2323,7 +2291,7 @@ async function parseForwardNodes(
}
assertForwardNodeMetadata(nodeData, index);
return { segment, nodeData };
return nodeData;
}
// Preserve the existing bare-node compatibility form, but require it to
@@ -2338,22 +2306,22 @@ async function parseForwardNodes(
}
assertForwardNodeMetadata(segment, index);
return { segment, nodeData: segment };
return segment;
});
// Scan the complete raw tree before parsing any earlier node. Some segment
// codecs perform identity lookups or HTTP signing, so discovering an
// unsupported message combination during the normal loop would already be
// too late.
assertForwardMessageInputPolicies(ref, messages, depth);
await assertForwardMessageInputPolicies(ref, messages, depth);
const nodes: ForwardNodePayload[] = [];
for (const { nodeData } of prepared) {
for (const nodeData of prepared) {
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
if (messageId !== 0) {
const event = ref.messageStore.findEvent(messageId);
const event = await ref.messageStore.findEvent(messageId);
if (!event) {
throw new MessageElementValidationError(
@@ -2385,10 +2353,15 @@ async function parseForwardNodes(
);
}
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const elements = restoreHistoricalMedia(
const content = event.message ?? event.raw_message ?? '';
const elements = await restoreHistoricalMedia(
ref,
await parseMessage(content, false),
await parseMessage(content, false, {
forwardReply: {
senderUin: userUin,
time: toPositiveInt(event.time) || undefined,
},
}),
messageId,
);
@@ -2424,7 +2397,10 @@ async function parseForwardNodes(
}
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
const content = nodeData.content ?? nodeData.message ?? '';
// Preserve the node-time policy for both the node and its custom quotes.
const nodeTime = toPositiveInt(nodeData.time);
const time = nodeTime > 0 && nodeTime < 0xffffffff ? nodeTime : undefined;
let elements: MessageElement[];
let innerForward: ForwardNodePayload[] | undefined;
@@ -2455,7 +2431,9 @@ async function parseForwardNodes(
// uuid in hand.
elements = [];
} else {
elements = await parseMessage(content, false);
elements = await parseMessage(content, false, {
forwardReply: { senderUin: userUin, time },
});
}
if (!innerForward && elements.length === 0) {
@@ -2464,41 +2442,18 @@ async function parseForwardNodes(
const node: ForwardNodePayload = { userUin, nickname, elements };
// Forward optional preview news lines (OneBot `data.news`) onto the
// payload so nested-forward bubble previews can prefer caller-supplied
// lines over auto-generated ones. Only accepted when the array shape
// is valid (already asserted by assertForwardNodeMetadata).
if (isForwardNewsArray(nodeData.news)) {
if (nodeData.news !== undefined) {
node.news = nodeData.news.map((item) => ({ text: item.text }));
}
// Forward optional OneBot bubble-preview metadata so nested-forward
// cards can prefer caller-supplied titles/source/summary/prompt over
// auto-derived ones (types already asserted above).
if (nodeData.title !== undefined && typeof nodeData.title === 'string') {
node.title = nodeData.title;
for (const field of ['title', 'source', 'summary', 'prompt'] as const) {
if (nodeData[field] !== undefined) {
node[field] = nodeData[field];
}
}
if (nodeData.source !== undefined && typeof nodeData.source === 'string') {
node.source = nodeData.source;
}
if (nodeData.summary !== undefined && typeof nodeData.summary === 'string') {
node.summary = nodeData.summary;
}
if (nodeData.prompt !== undefined && typeof nodeData.prompt === 'string') {
node.prompt = nodeData.prompt;
}
// Honour an explicit per-node display time (OneBot `data.time`, unix
// seconds) so a custom forward can set/back-date each node's timestamp
// (#209). The wire field is uint32, so reject a millisecond value or any
// out-of-range input (it would overflow/throw) and fall back to now.
const nodeTime = toPositiveInt(nodeData.time);
if (nodeTime > 0 && nodeTime < 0xffffffff) {
node.time = nodeTime;
if (time !== undefined) {
node.time = time;
}
if (innerForward) {
+121 -84
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,68 +79,100 @@ export class ReactionStore {
operatorUin: number,
operatorUid: string,
setAt: number,
): void {
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
return;
}
): Promise<void> {
return this.db.serial(async () => {
await this.initialization;
this.stmtUpsert.run(groupId, msgSeq, emojiId, emojiType, operatorUin, operatorUid, setAt);
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
return;
}
await this.stmtUpsert.run(
groupId,
msgSeq,
emojiId,
emojiType,
operatorUin,
operatorUid,
setAt,
);
});
}
recordRemove(groupId: number, msgSeq: number, emojiId: string, operatorUin: number): void {
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
return;
}
async recordRemove(
groupId: number,
msgSeq: number,
emojiId: string,
operatorUin: number,
): Promise<void> {
return this.db.serial(async () => {
await this.initialization;
this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin);
if (!groupId || !msgSeq || !emojiId || !operatorUin) {
return;
}
await this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin);
});
}
listUsers(
async listUsers(
groupId: number,
msgSeq: number,
emojiId: string,
limit = 20,
offset = 0,
): Array<{ operatorUin: number; operatorUid: string; setAt: number }> {
const rows = this.stmtList.all(
groupId,
msgSeq,
emojiId,
Math.max(1, Math.min(limit, 500)),
Math.max(0, offset),
) as Array<{ operator_uin: number; operator_uid: string; set_at: number }>;
return rows.map((r) => ({
operatorUin: r.operator_uin,
operatorUid: r.operator_uid,
setAt: r.set_at,
}));
): Promise<Array<{ operatorUin: number; operatorUid: string; setAt: number }>> {
return this.db.serial(async () => {
await this.initialization;
const rows = (await this.stmtList.all(
groupId,
msgSeq,
emojiId,
Math.max(1, Math.min(limit, 500)),
Math.max(0, offset),
)) as Array<{ operator_uin: number; operator_uid: string; set_at: number }>;
return rows.map((r) => ({
operatorUin: r.operator_uin,
operatorUid: r.operator_uid,
setAt: r.set_at,
}));
});
}
countUsers(groupId: number, msgSeq: number, emojiId: string): number {
const row = this.stmtCount.get(groupId, msgSeq, emojiId) as { n: number } | undefined;
return row?.n ?? 0;
async countUsers(groupId: number, msgSeq: number, emojiId: string): Promise<number> {
return this.db.serial(async () => {
await this.initialization;
const row = (await this.stmtCount.get(groupId, msgSeq, emojiId)) as
{ n: number } | undefined;
return row?.n ?? 0;
});
}
/** Summary of all cached reactions on a message, grouped by emoji. */
summarizeMessage(
async summarizeMessage(
groupId: number,
msgSeq: number,
): Array<{ emojiId: string; emojiType: number; count: number; lastSetAt: number }> {
const rows = this.stmtCountByEmoji.all(groupId, msgSeq) as Array<{
emoji_id: string;
emoji_type: number;
n: number;
last_at: number;
}>;
return rows.map((r) => ({
emojiId: r.emoji_id,
emojiType: r.emoji_type,
count: r.n,
lastSetAt: r.last_at,
}));
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastSetAt: number }>> {
return this.db.serial(async () => {
await this.initialization;
const rows = (await this.stmtCountByEmoji.all(groupId, msgSeq)) as Array<{
emoji_id: string;
emoji_type: number;
n: number;
last_at: number;
}>;
return rows.map((r) => ({
emojiId: r.emoji_id,
emojiType: r.emoji_type,
count: r.n,
lastSetAt: r.last_at,
}));
});
}
close(): void {
this.db.close();
async close(): Promise<void> {
await this.initialization.catch(() => undefined);
await this.db.close();
}
}
+82
View File
@@ -0,0 +1,82 @@
import type { MessageElement } from '@snowluma/protocol/events';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
const labels: Readonly<Record<string, string>> = {
image: '[图片]',
record: '[语音]',
video: '[视频]',
file: '[文件]',
face: '[表情]',
mface: '[表情]',
forward: '[聊天记录]',
json: '[卡片]',
xml: '[卡片]',
markdown: '[Markdown]',
};
function previewLabel(type: string): string {
if (!Object.hasOwn(labels, type)) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
`message segment "${type}" is not supported in a reply preview`,
type,
);
}
return labels[type]!;
}
export function assertReplyPreviewType(type: string): void {
if (type !== 'text' && type !== 'at') {
previewLabel(type);
}
}
/** Quotes carry display text; media must not be uploaded again for a preview. */
export function elementsToReplyPreview(elements: readonly MessageElement[]): MessageElement[] {
const text = elements
.map((element) => {
if (element.type === 'text') {
return element.text;
}
if (element.type === 'at') {
return element.targetUin === 0 ? '@全体成员' : `@${element.targetUin}`;
}
return previewLabel(element.type);
})
.join('');
return [{ type: 'text', text }];
}
export function replyPreviewElements(message: unknown): MessageElement[] {
if (!Array.isArray(message)) {
return [];
}
const parts: string[] = [];
for (const segment of message) {
if (!segment || typeof segment !== 'object') {
continue;
}
const data = segment.data;
if (!data || typeof data !== 'object') {
continue;
}
if (segment.type === 'text' && typeof data.text === 'string') {
parts.push(data.text);
} else if (segment.type === 'at') {
parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
} else if (typeof segment.type === 'string' && Object.hasOwn(labels, segment.type)) {
parts.push(labels[segment.type]!);
}
}
const text = parts.join('');
return text ? [{ type: 'text', text }] : [];
}
+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);
}
+22
View File
@@ -76,4 +76,26 @@ describe('action-docs', () => {
expect(md).toContain('`set_group_ban`');
expect(md).toContain('| 参数 | 类型 | 必填 | 默认 | 说明 |');
});
it('documents custom reply content on every forward entry point', () => {
for (const name of [
'upload_forward_msg',
'upload_foward_msg',
'send_forward_msg',
'send_group_forward_msg',
'send_private_forward_msg',
]) {
const action = docs.find((doc) => doc.name === name)!;
for (const field of ['messages', 'message']) {
expect(action.params.find((param) => param.name === field)?.desc).toContain(
'reply.data.message',
);
}
}
expect(docs.find((doc) => doc.name === 'get_forward_msg')?.returns).toContain(
'qq/time/seq',
);
});
});
+3 -157
View File
@@ -14,7 +14,7 @@ function requireAction(name: string) {
}
function asCtx(partial: Partial<ApiActionContext>): ApiActionContext {
return partial as ApiActionContext;
return { refreshMessageMedia: vi.fn(async () => {}), ...partial } as ApiActionContext;
}
const sendMsg = requireAction('send_msg');
@@ -88,10 +88,7 @@ describe('send_custom_face', () => {
const { ctx, resolveCustomFace, sendPrivateMessage } = context();
expect(
await action.toHandler(ctx)({ emoji_id: 'a'.repeat(32), user_id: 456 }),
).toMatchObject({
status: 'ok',
data: { message_id: 8 },
});
).toMatchObject({ status: 'ok', data: { message_id: 8 } });
expect(sendPrivateMessage).toHaveBeenCalledWith(456, [image], false);
resolveCustomFace.mockRejectedValueOnce(new Error('sticker missing'));
await expect(action.toHandler(ctx)({ emoji_id: 'missing', user_id: 456 })).rejects.toThrow(
@@ -106,9 +103,7 @@ describe('send_custom_face', () => {
const { ctx, resolveCustomFace } = context();
expect(
await action.toHandler(ctx)({ emoji_id: 'saved-sticker', ...target }),
).toMatchObject({
retcode: 1400,
});
).toMatchObject({ retcode: 1400 });
expect(resolveCustomFace).not.toHaveBeenCalled();
},
);
@@ -514,155 +509,6 @@ describe('get_msg', () => {
},
});
});
it('refreshes image URLs from file, then file_id, and skips unusable segments', async () => {
const fileImage: JsonObject = {
file: 'ABC.jpg',
file_id: 'SHOULD_NOT_WIN.jpg',
url: 'https://old.example/ABC.jpg',
};
const fileIdImage: JsonObject = {
file_id: 'BY_FILE_ID.jpg',
url: 'https://old.example/file-id.jpg',
};
const emptyFileImage: JsonObject = {
file: '',
file_id: 'SHOULD_NOT_USE.jpg',
url: 'https://old.example/empty-file.jpg',
};
const keepEmptyUrl: JsonObject = {
file: 'KEEP_EMPTY.jpg',
url: 'https://old.example/keep-empty.jpg',
};
const keepNull: JsonObject = {
file: 'KEEP_NULL.jpg',
url: 'https://old.example/keep-null.jpg',
};
const keepNonString: JsonObject = {
file: 'KEEP_NONSTRING.jpg',
url: 'https://old.example/keep-nonstring.jpg',
};
const noHandle: JsonObject = {
url: 'https://old.example/no-file.jpg',
};
const stored: JsonObject = {
message_id: 777001,
message: [
null,
'skip-me',
12,
{ type: 'text', data: { text: 'plain' } },
{ type: 'image', data: 'not-object' },
{ type: 'image' },
{ type: 'image', data: emptyFileImage },
{ type: 'image', data: noHandle },
{ type: 'image', data: fileIdImage },
{ type: 'image', data: keepEmptyUrl },
{ type: 'image', data: keepNull },
{ type: 'image', data: keepNonString },
{ type: 'image', data: fileImage },
],
};
const getImageInfo = vi.fn(async (file: string) => {
if (file === 'ABC.jpg') {
return { url: 'https://new.example/ABC.jpg?rkey=FRESH' };
}
if (file === 'BY_FILE_ID.jpg') {
return { url: 'https://new.example/file-id.jpg?rkey=FRESH' };
}
if (file === 'KEEP_EMPTY.jpg') {
return { url: '' };
}
if (file === 'KEEP_NULL.jpg') {
return null;
}
if (file === 'KEEP_NONSTRING.jpg') {
return { url: 1 };
}
return { url: 'https://should-not-apply.example/' };
});
const response = await getMsg.toHandler(
asCtx({
getMessage: () => stored,
getImageInfo,
}),
)({ message_id: 777001 });
expect(getImageInfo.mock.calls).toEqual([
['BY_FILE_ID.jpg'],
['KEEP_EMPTY.jpg'],
['KEEP_NULL.jpg'],
['KEEP_NONSTRING.jpg'],
['ABC.jpg'],
]);
expect(response).toEqual({
status: 'ok',
retcode: 0,
data: {
message_id: 777001,
real_id: 777001,
message: [
null,
'skip-me',
12,
{ type: 'text', data: { text: 'plain' } },
{ type: 'image', data: 'not-object' },
{ type: 'image' },
{ type: 'image', data: emptyFileImage },
{ type: 'image', data: noHandle },
{ type: 'image', data: fileIdImage },
{ type: 'image', data: keepEmptyUrl },
{ type: 'image', data: keepNull },
{ type: 'image', data: keepNonString },
{ type: 'image', data: fileImage },
],
},
});
expect(fileImage.url).toBe('https://new.example/ABC.jpg?rkey=FRESH');
expect(fileIdImage.url).toBe('https://new.example/file-id.jpg?rkey=FRESH');
expect(emptyFileImage.url).toBe('https://old.example/empty-file.jpg');
expect(keepEmptyUrl.url).toBe('https://old.example/keep-empty.jpg');
expect(keepNull.url).toBe('https://old.example/keep-null.jpg');
expect(keepNonString.url).toBe('https://old.example/keep-nonstring.jpg');
expect(noHandle.url).toBe('https://old.example/no-file.jpg');
});
it('keeps the stored image URL when getImageInfo throws', async () => {
const imageData: JsonObject = {
file: 'THROW.jpg',
url: 'https://old.example/throw.jpg',
};
const getImageInfo = vi.fn(async () => {
throw new Error('rkey fetch failed');
});
const response = await getMsg.toHandler(
asCtx({
getMessage: () => ({
message_id: 777002,
message: [{ type: 'image', data: imageData }],
}),
getImageInfo,
}),
)({ message_id: 777002 });
expect(getImageInfo.mock.calls).toEqual([['THROW.jpg']]);
expect(response).toEqual({
status: 'ok',
retcode: 0,
data: {
message_id: 777002,
real_id: 777002,
message: [{ type: 'image', data: imageData }],
},
});
expect(imageData.url).toBe('https://old.example/throw.jpg');
});
});
describe('delete_msg', () => {
+13 -4
View File
@@ -65,18 +65,27 @@ describe('face animation results', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-face-animation-'));
const dbPath = path.join(dir, 'messages.db');
let store = new MessageStore(dbPath);
await store.initialization;
try {
store.storeEvent(Number(event.message_id), true, 30001, 42, GROUP_MESSAGE_EVENT, event);
store.close();
await store.storeEvent(
Number(event.message_id),
true,
30001,
42,
GROUP_MESSAGE_EVENT,
event,
);
await store.close();
store = new MessageStore(dbPath);
expect(store.findEvent(Number(event.message_id))?.message).toEqual(message);
await store.initialization;
expect((await store.findEvent(Number(event.message_id)))?.message).toEqual(message);
const history = await getGroupMsgHistory(store, 30001, undefined, 20);
expect(history).toHaveLength(1);
expect(history[0].message).toEqual(message);
expect(history[0].raw_message).toBe(event.raw_message);
} finally {
store.close();
await store.close();
fs.rmSync(dir, { recursive: true, force: true });
}
});
+130 -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];
@@ -39,9 +40,16 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
uin: '10001',
selfId: 10001,
bridge,
messageStore: { findMedia: () => null, findEvent: () => null } as any,
messageStore: { findMedia: () => null, findEvent: () => null, storeEvent: vi.fn() } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
converterCtx: {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
@@ -402,6 +410,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
...ctx.messageStore,
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
@@ -419,6 +428,119 @@ describe('forward — nested {type:"node"} content', () => {
]);
});
it.each(['image', 'record', 'video'] as const)(
'prepares fetched %s fingerprints at every nesting level (#437)',
async (type) => {
const fingerprint = {
fileId: 'source-id',
fileSize: 120,
md5Hex: 'ab'.repeat(16),
sha1Hex: 'cd'.repeat(20),
};
const media: MessageElement =
type === 'image'
? { ...fingerprint, type, width: 32, height: 24, picFormat: 1001 }
: { ...fingerprint, type, duration: 3 };
const leaf: ForwardNodePayload = { userUin: 111, nickname: 'leaf', elements: [media] };
// QQ only accepts standalone video nodes; exercise mixed content with
// images/voice and use a text sibling for the video case.
const sibling: MessageElement =
type === 'video' ? { type: 'text', text: 'nested video' } : media;
const mixed: ForwardNodePayload = {
userUin: 222,
nickname: 'mixed',
elements: [sibling, { type: 'forward', resId: 'INNER' }],
};
const outer: ForwardNodePayload[] = [
leaf,
mixed,
{
userUin: 333,
nickname: 'nested',
elements: [{ type: 'forward', resId: 'INNER' }],
},
];
const before = structuredClone(outer);
const fetch = vi.fn(async (resId: string) => (resId === 'OUTER' ? outer : [leaf]));
const upload = vi.fn(
async (_nodes: ForwardNodePayload[], _groupId?: number, _userId?: number) =>
'NEW_RES',
);
const sendPrivate = vi.fn(async () => ({
sequence: 1,
clientSequence: 2,
random: 3,
timestamp: 1700000000,
}));
const ctx = makeCtx(
fakeBridge({
apis: { forward: { fetch, upload }, message: { sendPrivate } },
} as any),
);
ctx.messageStore.findEvent = () => ({
message: [{ type: 'forward', data: { id: 'OUTER' } }],
});
await forwardSingleMessage(ctx, 77, { userId: 10001 });
const expected = expect.objectContaining({
...fingerprint,
type,
noByteFallback: true,
});
const finalNodes = upload.mock.calls.at(-1)![0];
expect(finalNodes[0]!.elements).toEqual([expected]);
expect(finalNodes[1]!.elements[0]).toEqual(type === 'video' ? sibling : expected);
expect(finalNodes[2]!.innerForward![0]!.elements).toEqual([expected]);
expect(upload.mock.calls[0]![0][0]!.elements).toEqual([expected]);
for (const [, groupId, userId] of upload.mock.calls) {
expect(groupId).toBeUndefined();
expect(userId).toBe(10001);
}
expect(outer).toEqual(before);
expect(sendPrivate).toHaveBeenCalledOnce();
},
);
it.each([
{ type: 'image', imageUrl: 'https://example.com/legacy.png', md5Hex: 'ab'.repeat(16) },
{
type: 'image',
imageUrl: 'https://example.com/partial.png',
md5Hex: 'ab'.repeat(16),
sha1Hex: 'cd'.repeat(20),
width: 0,
height: 0,
},
] satisfies MessageElement[])(
'keeps the source upload path for incomplete image fingerprints ($imageUrl)',
async (media) => {
const upload = vi.fn(async (_nodes: ForwardNodePayload[]) => 'NEW_RES');
const fetch = vi.fn(async () => [
{ userUin: 111, nickname: 'alice', elements: [media] },
]);
const sendGroup = vi.fn(async () => ({
sequence: 1,
clientSequence: 0,
random: 2,
timestamp: 1700000000,
}));
const ctx = makeCtx(
fakeBridge({ apis: { forward: { fetch, upload }, message: { sendGroup } } } as any),
);
ctx.messageStore.findEvent = () => ({
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
});
await forwardSingleMessage(ctx, 77, { groupId: 12345 });
expect(upload.mock.calls[0]![0][0]!.elements).toEqual([media]);
expect(upload.mock.calls[0]![0][0]!.elements[0]!.noByteFallback).toBeUndefined();
},
);
it('fails a merged-forward single send when the inner tree cannot be fetched (#437)', async () => {
const fetch = vi.fn(async () => {
throw new Error('download forward message failed');
@@ -430,6 +552,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
...ctx.messageStore,
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
@@ -492,6 +615,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
...ctx.messageStore,
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OUTER' } }],
@@ -514,6 +638,7 @@ describe('forward — nested {type:"node"} content', () => {
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage } } } as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
...ctx.messageStore,
findMedia: () => null,
findEvent: () => ({
message: [
@@ -605,6 +730,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
...ctx.messageStore,
findMedia: () => null,
findEvent: () => ({
user_id: 0,
@@ -661,7 +787,7 @@ describe('forward — nested {type:"node"} content', () => {
},
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = { findEvent, findMedia: () => null };
(ctx as any).messageStore = { ...ctx.messageStore, findEvent, findMedia: () => null };
await sendGroupForwardMessage(ctx, 12345, [{ type: 'node', data: { id: -123 } }] as any);
@@ -719,7 +845,7 @@ describe('forward — nested {type:"node"} content', () => {
},
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = { findEvent, findMedia: () => null };
(ctx as any).messageStore = { ...ctx.messageStore, findEvent, findMedia: () => null };
await sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { id: 7, nickname: 'node-override' } },
+326
View File
@@ -0,0 +1,326 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { Elem } from '@snowluma/proto-defs/element';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { decodeRichBody } from '@snowluma/protocol/msg-push/rich-body-decoder';
import type { ForwardNodePayload } from '@snowluma/protocol/events';
import type { OneBotInstanceContext } from '../src/instance-context';
import type { JsonObject } from '../src/types';
import { elementsToOneBotSegments } from '../src/event-converter';
import { parseMessage } from '../src/message-parser';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import {
getForwardMessage,
sendGroupForwardMessage,
sendPrivateForwardMessage,
uploadForwardMessage,
} from '../src/modules/message-actions';
const time = 1700000000;
function fixture(nodes: ForwardNodePayload[] = []) {
const upload = vi.fn(async (_nodes: ForwardNodePayload[]) => 'forward-id');
const send = vi.fn(async () => ({
messageId: 9,
sequence: 100,
clientSequence: 0,
random: 1,
timestamp: time,
}));
const findEvent = vi.fn(() => null);
const ctx = {
uin: '10001',
selfId: 10001,
bridge: {
identity: { nickname: 'SnowLuma' },
apis: {
forward: { upload, fetch: vi.fn(async () => nodes) },
message: { sendGroup: send, sendPrivate: send },
},
},
messageStore: { findEvent, findMedia: () => null, storeEvent: vi.fn() },
converterCtx: {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
cacheMessageMeta: vi.fn(),
mediaStore: {},
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
return { ctx, upload, send, findEvent };
}
function node(data: JsonObject): JsonObject {
return {
type: 'node',
data: {
user_id: 20002,
nickname: 'sender',
time,
content: [
{ type: 'reply', data },
{ type: 'text', data: { text: 'answer' } },
],
},
};
}
describe('custom replies inside merged forwards (#241)', () => {
it.each(['group', 'private', 'upload'] as const)(
'%s preserves custom quote text on the wire without looking up an id',
async (scene) => {
const { ctx, upload, findEvent } = fixture();
const messages = [
node({
id: '-123',
message: [{ type: 'text', data: { text: '原文\nSnowLuma 😀' } }],
qq: '30003',
time: String(time - 10),
seq: '42',
}),
];
if (scene === 'group') {
await sendGroupForwardMessage(ctx, 40004, messages);
} else if (scene === 'private') {
await sendPrivateForwardMessage(ctx, 40004, messages);
} else {
await uploadForwardMessage(ctx, messages);
}
expect(findEvent).not.toHaveBeenCalledWith(-123);
const elements = upload.mock.calls[0]![0][0]!.elements;
const wire = await buildSendElems(elements);
const src = protobuf_decode<Elem>(protobuf_encode<Elem>(wire[0]!)).srcMsg;
expect(src).toMatchObject({ origSeqs: [42], senderUin: 30003n, time: time - 10 });
expect(src?.elemsRaw?.map((raw) => protobuf_decode<Elem>(raw).text?.str).join('')).toBe(
'原文\nSnowLuma 😀',
);
expect(wire[1]?.text?.str).toBe('answer');
const decoded = decodeRichBody(
{
richText: {
elems: wire.map((element) =>
protobuf_decode<Elem>(protobuf_encode<Elem>(element)),
),
},
},
scene === 'group',
);
expect(decoded[0]).toMatchObject({
type: 'reply',
replySeq: 42,
replySenderUin: 30003,
replyTime: time - 10,
replyElements: [{ type: 'text', text: '原文\nSnowLuma 😀' }],
});
},
);
it.each(
[
'SnowLuma',
{ type: 'text', data: { text: 'SnowLuma' } },
[{ type: 'text', data: { text: 'SnowLuma' } }],
].map((message) => ({ message })),
)('uses node metadata when only message is supplied ($message)', async ({ message }) => {
const { ctx, upload } = fixture();
await uploadForwardMessage(ctx, [node({ message })]);
expect(upload.mock.calls[0]![0][0]?.elements[0]).toMatchObject({
type: 'reply',
replySeq: 1,
replySenderUin: 20002,
replyTime: time,
replyElements: [{ type: 'text', text: 'SnowLuma' }],
});
});
it('round-trips fetched quote content and metadata without a local message record', async () => {
const { ctx, upload } = fixture([
{
userUin: 20002,
nickname: 'sender',
time,
groupId: 40004,
messageType: 'group',
elements: [
{
type: 'reply',
replySeq: 42,
replySenderUin: 30003,
replyTime: time - 10,
replyElements: [{ type: 'text', text: 'quoted' }],
},
{ type: 'text', text: 'answer' },
],
},
]);
const [fetched] = await getForwardMessage(ctx, 'original');
expect((fetched!.message as JsonObject[])[0]?.data).toMatchObject({
id: expect.any(String),
message: [{ type: 'text', data: { text: 'quoted' } }],
qq: '30003',
time: String(time - 10),
seq: '42',
});
await uploadForwardMessage(ctx, [
{
type: 'node',
data: {
user_id: fetched!.user_id,
nickname: 'sender',
content: fetched!.message,
},
},
]);
expect(upload.mock.calls[0]![0][0]?.elements[0]).toMatchObject({
type: 'reply',
replySeq: 42,
replySenderUin: 30003,
replyTime: time - 10,
replyElements: [{ type: 'text', text: 'quoted' }],
});
});
it('summarizes quoted media without uploading it, and works in nested forwards', async () => {
const { ctx, upload } = fixture();
await uploadForwardMessage(ctx, [
{
type: 'node',
data: {
user_id: 10001,
content: [
node({
message: [
{ type: 'text', data: { text: 'photo' } },
{ type: 'image', data: { file: 'unavailable.png' } },
{ type: 'at', data: { qq: 'all' } },
],
}),
],
},
},
]);
expect(upload.mock.calls[0]![0][0]?.innerForward?.[0]?.elements[0]?.replyElements).toEqual([
{ type: 'text', text: 'photo[图片]@全体成员' },
]);
});
it('keeps id-only replies when QQ supplies no inline content', async () => {
const { ctx } = fixture([
{
userUin: 20002,
nickname: 'sender',
time,
elements: [
{ type: 'reply', replySeq: 42 },
{ type: 'text', text: 'answer' },
],
},
]);
const [fetched] = await getForwardMessage(ctx, 'original');
expect((fetched!.message as JsonObject[])[0]).toEqual({
type: 'reply',
data: { id: '42' },
});
});
it('accepts the full uint32 sequence range and CQ text within a quote', async () => {
const { ctx, upload } = fixture();
await uploadForwardMessage(ctx, [
node({ message: 'hello[CQ:at,qq=all]', seq: 0xffffffff, time: 0 }),
]);
const wire = await buildSendElems(upload.mock.calls[0]![0][0]!.elements);
const src = protobuf_decode<Elem>(protobuf_encode<Elem>(wire[0]!)).srcMsg;
expect(src?.origSeqs).toEqual([0xffffffff]);
expect(src?.elemsRaw?.map((raw) => protobuf_decode<Elem>(raw).text?.str).join('')).toBe(
'hello@全体成员',
);
});
it.each([
{ message: [] },
{ message: '' },
{ message: null },
{ message: 123 },
{ message: [{ type: 'text', data: { text: {} } }] },
{ message: [{ type: 'unknown', data: {} }] },
{ message: [{ type: 'music', data: { type: 'qq', id: '1' } }] },
{ message: [{ type: 'node', data: { content: 'nested' } }] },
{ message: [{ type: 'reply', data: { message: 'nested' } }] },
{ message: 'quote', seq: 0 },
{ message: 'quote', seq: 0x100000000 },
{ message: 'quote', qq: -1 },
{ message: 'quote', qq: true },
{ message: 'quote', time: 1700000000000 },
{ message: 'quote', time: -1 },
{ message: 'quote', time: null },
{ message: 'quote', time: '' },
{ message: 'quote', time: ' ' },
{ message: 'quote', time: 1.5 },
{ message: 'quote', qq: null },
{ message: 'quote', seq: '' },
] satisfies JsonObject[])(
'rejects invalid custom reply input before uploading (%j)',
async (data) => {
const { ctx, upload, send } = fixture();
await expect(sendGroupForwardMessage(ctx, 40004, [node(data)])).rejects.toThrow();
expect(upload).not.toHaveBeenCalled();
expect(send).not.toHaveBeenCalled();
},
);
it('reports malformed custom quotes as BAD_REQUEST at the action boundary', async () => {
const { ctx, upload, send } = fixture();
const api = new ApiHandler({
sendGroupForwardMsg: (groupId, messages) =>
sendGroupForwardMessage(ctx, groupId, messages),
} as ApiActionContext);
const result = await api.handle('send_group_forward_msg', {
group_id: 40004,
messages: [node({ message: 'quote', seq: 0 })],
});
expect(result).toMatchObject({
status: 'failed',
retcode: 1400,
wording: expect.stringContaining('reply.seq'),
});
expect(upload).not.toHaveBeenCalled();
expect(send).not.toHaveBeenCalled();
});
it('keeps ordinary reply id parsing and ordinary received reply segments unchanged', async () => {
expect(await parseMessage([{ type: 'reply', data: { id: 42 } }], false)).toEqual([
{ type: 'reply', replySeq: 42 },
]);
const { ctx } = fixture();
expect(
await elementsToOneBotSegments(
ctx.converterCtx,
[
{
type: 'reply',
replySeq: 42,
replySenderUin: 30003,
replyTime: time,
replyElements: [{ type: 'text', text: 'quoted' }],
},
],
true,
40004,
),
).toEqual([{ type: 'reply', data: { id: expect.any(String) } }]);
await expect(
parseMessage(
[
{ type: 'reply', data: { message: 'quote' } },
{ type: 'text', data: { text: 'answer' } },
],
false,
),
).rejects.toThrow(/forward/);
});
});
@@ -300,8 +300,8 @@ describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
mediaSegmentSink: null,
} as never;
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', () => {
const out = convertGroupMsgEmojiLike(ctx, baseEvent);
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', async () => {
const out = await convertGroupMsgEmojiLike(ctx, baseEvent);
expect(out.post_type).toBe('notice');
expect(out.notice_type).toBe('group_msg_emoji_like');
expect(out.sub_type).toBe('add');
@@ -313,8 +313,8 @@ describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
expect(out.likes).toEqual([{ emoji_id: '76', count: 1 }]);
});
it('flips sub_type to remove when isAdd is false', () => {
const out = convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
it('flips sub_type to remove when isAdd is false', async () => {
const out = await convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
expect(out.sub_type).toBe('remove');
});
});
+102 -66
View File
@@ -57,7 +57,7 @@ function converter(media: MediaStore): ConverterContext {
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: (...args) => indexer.remember(...args),
mediaSegmentSink: async (...args) => await indexer.remember(...args),
};
}
@@ -89,7 +89,9 @@ describe('durable historical media', () => {
async (type) => {
const { dbPath } = location();
let messages = new MessageStore(dbPath);
await messages.initialization;
let media = new MediaStore(dbPath, 2);
await media.initialization;
const element = {
type,
fileId: 'same.png',
@@ -119,9 +121,9 @@ describe('durable historical media', () => {
elements: [element],
});
event!.message_id = 42;
messages.storeHistoryEvent(42, true, 123, 10, 'GroupMessage', event!);
await messages.storeHistoryEvent(42, true, 123, 10, 'GroupMessage', event!);
expect(JSON.stringify(event)).not.toContain('md5Hex');
expect(JSON.stringify(messages.findEvent(42))).not.toContain('sha1Hex');
expect(JSON.stringify(await messages.findEvent(42))).not.toContain('sha1Hex');
// Repeated names and many new resources must not change the old message.
for (let i = 0; i < 80; i++) {
@@ -131,14 +133,16 @@ describe('durable historical media', () => {
true,
123,
);
media.rememberImage({ ...image, file: `other-${i}`, fileName: `other-${i}` });
media.findImage(`other-${i}`);
await media.rememberImage({ ...image, file: `other-${i}`, fileName: `other-${i}` });
await media.findImage(`other-${i}`);
}
media.close();
messages.close();
await media.close();
await messages.close();
messages = new MessageStore(dbPath);
await messages.initialization;
media = new MediaStore(dbPath, 2);
await media.initialization;
try {
const { ref, sendGroup, upload } = context(messages, media);
@@ -163,10 +167,10 @@ describe('durable historical media', () => {
],
}),
]);
expect(messages.findEvent(42)?.message_id).toBe(42);
expect((await messages.findEvent(42))?.message_id).toBe(42);
} finally {
media.close();
messages.close();
await media.close();
await messages.close();
}
},
);
@@ -174,7 +178,9 @@ describe('durable historical media', () => {
it('stores the body and media snapshot atomically and strips inline bytes', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
await messages.initialization;
const media = new MediaStore(dbPath);
await media.initialization;
const db = new DatabaseSync(dbPath);
try {
@@ -196,25 +202,26 @@ describe('durable historical media', () => {
db.exec(
"CREATE TRIGGER fail_media BEFORE INSERT ON messages WHEN NEW.media_data IS NOT NULL BEGIN SELECT RAISE(ABORT, 'test media write failure'); END",
);
expect(() => messages.storeEvent(1, true, 123, 1, 'GroupMessage', event)).toThrow(
'test media write failure',
);
expect(messages.findEvent(1)).toBeNull();
await expect(
async () => await messages.storeEvent(1, true, 123, 1, 'GroupMessage', event),
).rejects.toThrow('test media write failure');
expect(await messages.findEvent(1)).toBeNull();
db.exec('DROP TRIGGER fail_media');
messages.storeEvent(1, true, 123, 1, 'GroupMessage', event);
expect(messages.findMedia(1)?.[0].md5Hex).toBe(image.md5Hex);
expect(JSON.stringify(messages.findMedia(1))).not.toContain('base64://');
await messages.storeEvent(1, true, 123, 1, 'GroupMessage', event);
expect((await messages.findMedia(1))?.[0].md5Hex).toBe(image.md5Hex);
expect(JSON.stringify(await messages.findMedia(1))).not.toContain('base64://');
} finally {
db.close();
media.close();
messages.close();
await media.close();
await messages.close();
}
});
it('propagates media persistence failures instead of silently skipping segments', async () => {
const { dbPath } = location();
const media = new MediaStore(dbPath);
media.close();
await media.initialization;
await media.close();
await expect(
elementsToOneBotSegments(
converter(media),
@@ -228,7 +235,9 @@ describe('durable historical media', () => {
it('does not substitute another same-named resource for an incomplete snapshot', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
await messages.initialization;
const media = new MediaStore(dbPath);
await media.initialization;
try {
const segments = await elementsToOneBotSegments(
@@ -237,28 +246,30 @@ describe('durable historical media', () => {
true,
123,
);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
media.rememberImage(image);
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
await media.rememberImage(image);
const { ref, sendGroup } = context(messages, media);
await expect(forwardSingleMessage(ref, 42, { groupId: 999 })).rejects.toThrow(
'metadata is incomplete',
);
expect(sendGroup).not.toHaveBeenCalled();
} finally {
media.close();
messages.close();
await media.close();
await messages.close();
}
});
it('preserves complete metadata across an incomplete repeat and rejects conflicting resources', async () => {
const { dbPath } = location();
let messages = new MessageStore(dbPath);
await messages.initialization;
let media = new MediaStore(dbPath);
await media.initialization;
const complete: MessageElement = { type: 'image', ...image, fileId: image.file };
const save = async (element: MessageElement) => {
const segments = await elementsToOneBotSegments(converter(media), [element], true, 123);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
};
await save(complete);
@@ -270,10 +281,12 @@ describe('durable historical media', () => {
height: 0,
});
await expect(save({ ...complete, md5Hex: 'cc'.repeat(16) })).rejects.toThrow('conflicting');
media.close();
messages.close();
await media.close();
await messages.close();
messages = new MessageStore(dbPath);
await messages.initialization;
media = new MediaStore(dbPath);
await media.initialization;
try {
const { ref, sendGroup } = context(messages, media);
@@ -287,15 +300,17 @@ describe('durable historical media', () => {
}),
]);
} finally {
media.close();
messages.close();
await media.close();
await messages.close();
}
});
it('does not combine disjoint image fingerprints merely because fileId is the same filename', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
await messages.initialization;
const media = new MediaStore(dbPath);
await media.initialization;
try {
const original = await elementsToOneBotSegments(
@@ -304,43 +319,53 @@ describe('durable historical media', () => {
true,
123,
);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: original });
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: original });
const different = await elementsToOneBotSegments(
converter(media),
[{ type: 'image', fileId: 'photo.jpg', sha1Hex: image.sha1Hex, width: 64 }],
true,
123,
);
expect(() =>
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: different }),
).toThrow('unverified media association');
expect(messages.findMedia(42)).toEqual([
await expect(
async () =>
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
message: different,
}),
).rejects.toThrow('unverified media association');
expect(await messages.findMedia(42)).toEqual([
{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 },
]);
} finally {
media.close();
messages.close();
await media.close();
await messages.close();
}
});
it('rejects corrupt and oversized metadata without deleting history', () => {
it('rejects corrupt and oversized metadata without deleting history', async () => {
const { dbPath } = location();
const media = new MediaStore(dbPath);
await media.initialization;
const db = new DatabaseSync(dbPath);
try {
expect(() =>
media.rememberImage({ ...image, summary: 'x'.repeat(MEDIA_DATA_MAX_CHARS) }),
).toThrow('storage limit');
media.rememberImage(image);
await expect(
async () =>
await media.rememberImage({
...image,
summary: 'x'.repeat(MEDIA_DATA_MAX_CHARS),
}),
).rejects.toThrow('storage limit');
await media.rememberImage(image);
db.exec("UPDATE media_entries SET data = '{broken'");
expect(() => media.findImage(image.file)).toThrow();
await expect(async () => await media.findImage(image.file)).rejects.toThrow();
db.exec("UPDATE media_entries SET data = 'null'");
expect(() => media.findImage(image.file)).toThrow('invalid persisted');
expect(media.size().images).toBe(1);
await expect(async () => await media.findImage(image.file)).rejects.toThrow(
'invalid persisted',
);
expect((await media.size()).images).toBe(1);
} finally {
db.close();
media.close();
await media.close();
}
});
@@ -349,6 +374,7 @@ describe('durable historical media', () => {
async (type) => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
await old.initialization;
const element = {
type,
fileId: 'same.png',
@@ -364,10 +390,11 @@ describe('durable historical media', () => {
videoFormat: 0,
} as MessageElement;
await elementsToOneBotSegments(converter(old), [element], true, 123);
old.close();
await old.close();
const source = fs.readFileSync(legacyPath);
const messages = new MessageStore(dbPath);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
await messages.initialization;
await messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
user_id: 456,
message_id: 42,
message_type: 'group',
@@ -378,6 +405,7 @@ describe('durable historical media', () => {
fs.rmSync(legacyPath);
await migrateLegacyMedia(dbPath);
const media = new MediaStore(dbPath);
await media.initialization;
try {
await elementsToOneBotSegments(
@@ -392,8 +420,8 @@ describe('durable historical media', () => {
expect.objectContaining({ md5Hex: image.md5Hex }),
]);
} finally {
media.close();
messages.close();
await media.close();
await messages.close();
}
},
);
@@ -401,15 +429,17 @@ describe('durable historical media', () => {
it('rolls back a failed legacy batch and resumes after the source is repaired', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
old.rememberImage(image);
old.close();
await old.initialization;
await old.rememberImage(image);
await old.close();
const source = new DatabaseSync(legacyPath);
source.prepare("INSERT INTO media_entries VALUES ('image', 'broken', ?, 1)").run('{broken');
source.close();
await expect(migrateLegacyMedia(dbPath)).rejects.toThrow();
const destination = new MediaStore(dbPath);
expect(destination.size().images).toBe(0);
destination.close();
await destination.initialization;
expect((await destination.size()).images).toBe(0);
await destination.close();
const repaired = new DatabaseSync(legacyPath);
repaired
.prepare("UPDATE media_entries SET data = ? WHERE primary_key = 'broken'")
@@ -417,14 +447,16 @@ describe('durable historical media', () => {
repaired.close();
await migrateLegacyMedia(dbPath);
const reopened = new MediaStore(dbPath);
expect(reopened.size().images).toBe(2);
reopened.close();
await reopened.initialization;
expect((await reopened.size()).images).toBe(2);
await reopened.close();
});
it('normalizes legacy inline payloads without discarding their metadata', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
old.close();
await old.initialization;
await old.close();
const inline = `base64://${'Z'.repeat(100000)}`;
const source = new DatabaseSync(legacyPath);
source
@@ -434,37 +466,41 @@ describe('durable historical media', () => {
source.close();
await migrateLegacyMedia(dbPath);
const media = new MediaStore(dbPath);
await media.initialization;
try {
expect(media.findImage(inline)).toMatchObject({
expect(await media.findImage(inline)).toMatchObject({
md5Hex: image.md5Hex,
url: '',
imageUrl: '',
});
expect(JSON.stringify(media.findImage(inline))).not.toContain('base64://');
expect(JSON.stringify(await media.findImage(inline))).not.toContain('base64://');
} finally {
media.close();
await media.close();
}
});
it('resumes a cancelled migration from its committed batch cursor', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
await old.initialization;
for (let i = 0; i < 205; i++) {
old.rememberImage({ ...image, file: `entry-${i}` });
await old.rememberImage({ ...image, file: `entry-${i}` });
}
old.close();
await old.close();
let checks = 0;
await migrateLegacyMedia(dbPath, () => ++checks > 1);
const partial = new MediaStore(dbPath);
expect(partial.size().images).toBe(200);
partial.close();
await partial.initialization;
expect((await partial.size()).images).toBe(200);
await partial.close();
await migrateLegacyMedia(dbPath);
const complete = new MediaStore(dbPath);
expect(complete.size().images).toBe(205);
expect(complete.findImage('entry-204')?.md5Hex).toBe(image.md5Hex);
complete.close();
await complete.initialization;
expect((await complete.size()).images).toBe(205);
expect((await complete.findImage('entry-204'))?.md5Hex).toBe(image.md5Hex);
await complete.close();
});
});
+57 -32
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,
@@ -60,12 +61,13 @@ function friendMessage(sequence: number, senderUin: number, clientSequence = seq
describe('history direction plumbing', () => {
let messageStore: MessageStore;
beforeEach(() => {
beforeEach(async () => {
messageStore = new MessageStore(':memory:');
await messageStore.initialization;
});
afterEach(() => {
messageStore.close();
afterEach(async () => {
await messageStore.close();
});
it('returns the group anchor followed by newer server messages', async () => {
@@ -74,7 +76,7 @@ describe('history direction plumbing', () => {
? [groupMessage(500), groupMessage(501)]
: [groupMessage(499), groupMessage(500)],
);
messageStore.storeMeta(-123456789, {
await messageStore.storeMeta(-123456789, {
isGroup: true,
targetId: GROUP_ID,
sequence: 500,
@@ -104,7 +106,7 @@ describe('history direction plumbing', () => {
? [friendMessage(700, SELF_ID), friendMessage(701, FRIEND_ID)]
: [friendMessage(699, FRIEND_ID), friendMessage(700, SELF_ID)],
);
messageStore.storeMeta(-987654321, {
await messageStore.storeMeta(-987654321, {
isGroup: false,
targetId: FRIEND_ID,
sequence: 700,
@@ -138,7 +140,7 @@ describe('history direction plumbing', () => {
friendMessage(63213, FRIEND_ID, 32742),
friendMessage(63214, SELF_ID, 32743),
]);
messageStore.storeMeta(-222222222, {
await messageStore.storeMeta(-222222222, {
isGroup: false,
targetId: FRIEND_ID,
sequence: 99999,
@@ -176,7 +178,7 @@ describe('history direction plumbing', () => {
{ sender: FRIEND_ID, sequence: 32742 },
{ sender: SELF_ID, sequence: 32743 },
]);
expect(messageStore.findMeta(Number(messages[0]!.message_id))).toMatchObject({
expect(await messageStore.findMeta(Number(messages[0]!.message_id))).toMatchObject({
sequence: 63213,
clientSequence: 32742,
sequenceAuthoritative: true,
@@ -220,33 +222,56 @@ describe('history direction plumbing', () => {
hashMessageIdInt32(63214, FRIEND_ID, PRIVATE_NT_MESSAGE_EVENT),
]);
expect(new Set(ids).size).toBe(2);
expect(ids.map((id) => messageStore.findEvent(id)?.message_id)).toEqual(ids);
expect(
await mapWithConcurrency(
ids,
8,
async (id) => (await messageStore.findEvent(id))?.message_id,
),
).toEqual(ids);
});
it('does not return or re-cache a private message covered by a recall tombstone', async () => {
messageStore.recordPrivateRecall(FRIEND_ID, 32742, false, 1700000010);
const fetchLatestHistory = vi.fn(async () => [
friendMessage(63213, FRIEND_ID, 32742),
friendMessage(63214, SELF_ID, 32743),
]);
const ref = {
selfId: SELF_ID,
bridge: {
resolveUserUid: vi.fn(async () => 'u_friend'),
apis: { message: { getC2cLatestHistory: fetchLatestHistory } },
},
messageStore,
converterCtx,
} as any;
it.each(['before reading', 'before persistence'] as const)(
'does not return or re-cache a private message recalled %s',
async (timing) => {
const recall = () =>
messageStore.recordPrivateRecall(FRIEND_ID, 32742, false, 1700000010);
const messages = await getFriendHistory(ref, FRIEND_ID, undefined, 20);
if (timing === 'before reading') {
await recall();
} else {
const persist = messageStore.storeHistoryEvent.bind(messageStore);
vi.spyOn(messageStore, 'storeHistoryEvent').mockImplementationOnce(
async (...args) => {
await recall();
return persist(...args);
},
);
}
expect(messages.map((message) => message.message_seq)).toEqual([32743]);
expect(messageStore.listSessionEvents(false, FRIEND_ID, 20)).toHaveLength(1);
});
const fetchLatestHistory = vi.fn(async () => [
friendMessage(63213, FRIEND_ID, 32742),
friendMessage(63214, SELF_ID, 32743),
]);
const ref = {
selfId: SELF_ID,
bridge: {
resolveUserUid: vi.fn(async () => 'u_friend'),
apis: { message: { getC2cLatestHistory: fetchLatestHistory } },
},
messageStore,
converterCtx,
} as any;
const messages = await getFriendHistory(ref, FRIEND_ID, undefined, 20);
expect(messages.map((message) => message.message_seq)).toEqual([32743]);
expect(await messageStore.listSessionEvents(false, FRIEND_ID, 20)).toHaveLength(1);
},
);
it('surfaces an unanchored server failure instead of returning incomplete local history', async () => {
messageStore.storeEvent(1, false, FRIEND_ID, 12, PRIVATE_MESSAGE_EVENT, {
await messageStore.storeEvent(1, false, FRIEND_ID, 12, PRIVATE_MESSAGE_EVENT, {
time: 12,
post_type: 'message',
message_type: 'private',
@@ -282,14 +307,14 @@ describe('history direction plumbing', () => {
? [groupMessage(899), groupMessage(900)]
: [groupMessage(900), groupMessage(901)],
);
messageStore.storeEvent(1, true, GROUP_ID, 900, GROUP_MESSAGE_EVENT, {
await messageStore.storeEvent(1, true, GROUP_ID, 900, GROUP_MESSAGE_EVENT, {
post_type: 'message',
message_type: 'group',
group_id: GROUP_ID,
message_id: 1,
message_seq: 900,
});
messageStore.storeEvent(
await messageStore.storeEvent(
2,
true,
GROUP_ID,
@@ -323,7 +348,7 @@ describe('history direction plumbing', () => {
it('does not use an explicitly requested local-only id as a server history anchor', async () => {
const fetchHistory = vi.fn(async () => [groupMessage(1799283572)]);
messageStore.storeEvent(
await messageStore.storeEvent(
2,
true,
GROUP_ID,
@@ -355,7 +380,7 @@ describe('history direction plumbing', () => {
it('rejects a private anchor from a different friend conversation', async () => {
const fetchHistory = vi.fn(async () => [friendMessage(800, FRIEND_ID)]);
messageStore.storeMeta(-111111111, {
await messageStore.storeMeta(-111111111, {
isGroup: false,
targetId: 987654321,
sequence: 800,
+97 -72
View File
@@ -62,13 +62,14 @@ function converterContext(): ConverterContext {
};
}
function makeStore(): { store: MessageStore; close(): void } {
async function makeStore(): Promise<{ store: MessageStore; close(): Promise<void> }> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-history-sync-'));
const store = new MessageStore(path.join(dir, 'messages.db'));
await store.initialization;
return {
store,
close: () => {
store.close();
close: async () => {
await store.close();
fs.rmSync(dir, { recursive: true, force: true });
},
};
@@ -122,10 +123,10 @@ function makeBridge(
} as unknown as BridgeInterface;
}
const resources: Array<ReturnType<typeof makeStore>> = [];
afterEach(() => {
const resources: Array<Awaited<ReturnType<typeof makeStore>>> = [];
afterEach(async () => {
for (const resource of resources.splice(0)) {
resource.close();
await resource.close();
}
vi.restoreAllMocks();
@@ -139,7 +140,7 @@ describe('login history sync', () => {
delays.push(ms);
},
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const bridge = makeBridge();
@@ -197,7 +198,7 @@ describe('login history sync', () => {
groupPage,
privateLatestPage,
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
@@ -242,7 +243,7 @@ describe('login history sync', () => {
friendCount: LOGIN_HISTORY_SYNC_LIMITS.scannedPrivateUsers + 1,
probe,
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
@@ -266,7 +267,7 @@ describe('login history sync', () => {
});
it('fills a known local gap from its oldest missing sequence', async () => {
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const local = groupMessage(30001, 50);
const localEvent = {
@@ -277,7 +278,7 @@ describe('login history sync', () => {
message_seq: 50,
group_id: 30001,
};
resource.store.storeEvent(123, true, 30001, 50, 'group_message', localEvent);
await resource.store.storeEvent(123, true, 30001, 50, 'group_message', localEvent);
const groupPage = vi.fn(async () => []);
const bridge = makeBridge({
@@ -304,9 +305,9 @@ describe('login history sync', () => {
});
it('backfills past a newer metadata-only authoritative row', async () => {
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
resource.store.storeEvent(123, true, 30001, 50, 'group_message', {
await resource.store.storeEvent(123, true, 30001, 50, 'group_message', {
time: 1_700_000_050,
post_type: 'message',
message_type: 'group',
@@ -314,7 +315,7 @@ describe('login history sync', () => {
message_seq: 50,
group_id: 30001,
});
resource.store.storeMeta(124, {
await resource.store.storeMeta(124, {
isGroup: true,
targetId: 30001,
sequence: 100,
@@ -324,8 +325,8 @@ describe('login history sync', () => {
random: 0,
timestamp: 1_700_000_100,
});
expect(resource.store.findLatestAuthoritativeSequence(true, 30001)).toBe(100);
expect(resource.store.findLatestPersistedAuthoritativeSequence(true, 30001)).toBe(50);
expect(await resource.store.findLatestAuthoritativeSequence(true, 30001)).toBe(100);
expect(await resource.store.findLatestPersistedAuthoritativeSequence(true, 30001)).toBe(50);
const groupPage = vi.fn(async () => []);
const bridge = makeBridge({
@@ -352,9 +353,9 @@ describe('login history sync', () => {
});
it('backfills a metadata-only session even when the server read cursor is current', async () => {
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
resource.store.storeMeta(124, {
await resource.store.storeMeta(124, {
isGroup: true,
targetId: 30001,
sequence: 100,
@@ -364,7 +365,9 @@ describe('login history sync', () => {
random: 0,
timestamp: 1_700_000_100,
});
expect(resource.store.findLatestPersistedAuthoritativeSequence(true, 30001)).toBeNull();
expect(
await resource.store.findLatestPersistedAuthoritativeSequence(true, 30001),
).toBeNull();
const groupPage = vi.fn(async () => []);
const bridge = makeBridge({
@@ -391,9 +394,9 @@ describe('login history sync', () => {
});
it('uses the authoritative private sequence for a known local gap', async () => {
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
resource.store.storeEvent(
await resource.store.storeEvent(
456,
false,
40001,
@@ -472,7 +475,7 @@ describe('login history sync', () => {
})),
groupPage,
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
@@ -507,7 +510,7 @@ describe('login history sync', () => {
})),
groupPage,
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
@@ -535,51 +538,73 @@ describe('login history sync', () => {
).resolves.toHaveLength(1);
});
it('does not restore a private message hidden by a recall tombstone', async () => {
const resource = makeStore();
resources.push(resource);
const recalled = friendMessage(40001, 1);
resource.store.recordPrivateRecall(40001, recalled.clientSeq!, false, recalled.time + 1);
const bridge = makeBridge({
groupCount: 0,
probe: vi.fn(async () => ({
groups: [],
privateUsers: [
{
userId: 40001,
uid: 'u_40001',
readSeq: 0,
latestSeq: 1,
lastMsgTime: recalled.time,
it.each(['before reading', 'before persistence'] as const)(
'does not restore or count a private message recalled %s',
async (timing) => {
const resource = await makeStore();
resources.push(resource);
const recalled = friendMessage(40001, 1);
const recall = () =>
resource.store.recordPrivateRecall(
40001,
recalled.clientSeq!,
false,
recalled.time + 1,
);
if (timing === 'before reading') {
await recall();
} else {
const persist = resource.store.storeHistoryEvent.bind(resource.store);
vi.spyOn(resource.store, 'storeHistoryEvent').mockImplementationOnce(
async (...args) => {
await recall();
return persist(...args);
},
],
})),
privateLatestPage: vi.fn(async () => [recalled]),
});
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
);
}
const result = await coordinator.schedule(
{
selfId: SELF_ID,
bridge,
messageStore: resource.store,
converterCtx: converterContext(),
},
new AbortController().signal,
);
const bridge = makeBridge({
groupCount: 0,
probe: vi.fn(async () => ({
groups: [],
privateUsers: [
{
userId: 40001,
uid: 'u_40001',
readSeq: 0,
latestSeq: 1,
lastMsgTime: recalled.time,
},
],
})),
privateLatestPage: vi.fn(async () => [recalled]),
});
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
expect(result).toMatchObject({
fetchedMessages: 1,
storedMessages: 0,
failedSessions: 0,
});
await expect(getFriendMsgHistory(resource.store, 40001, undefined, 20)).resolves.toEqual(
[],
);
});
const result = await coordinator.schedule(
{
selfId: SELF_ID,
bridge,
messageStore: resource.store,
converterCtx: converterContext(),
},
new AbortController().signal,
);
expect(result).toMatchObject({
fetchedMessages: 1,
storedMessages: 0,
failedSessions: 0,
});
await expect(
getFriendMsgHistory(resource.store, 40001, undefined, 20),
).resolves.toEqual([]);
},
);
it('rejects private history attributed to a different peer', async () => {
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const bridge = makeBridge({
groupCount: 0,
@@ -629,7 +654,7 @@ describe('login history sync', () => {
const mediaUrlResolver = vi.fn(async () => {
throw new Error('media resolver must not run');
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const bridge = makeBridge({
friendCount: 0,
@@ -682,8 +707,8 @@ describe('login history sync', () => {
}),
);
const secondProbe = vi.fn(async () => ({ groups: [], privateUsers: [] }));
const firstStore = makeStore();
const secondStore = makeStore();
const firstStore = await makeStore();
const secondStore = await makeStore();
resources.push(firstStore, secondStore);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
@@ -726,9 +751,9 @@ describe('login history sync', () => {
);
const cancelledProbe = vi.fn(async () => ({ groups: [], privateUsers: [] }));
const thirdProbe = vi.fn(async () => ({ groups: [], privateUsers: [] }));
const firstStore = makeStore();
const cancelledStore = makeStore();
const thirdStore = makeStore();
const firstStore = await makeStore();
const cancelledStore = await makeStore();
const thirdStore = await makeStore();
resources.push(firstStore, cancelledStore, thirdStore);
const coordinator = new LoginHistorySyncCoordinator({ sleep: async () => undefined });
const cancelledController = new AbortController();
@@ -782,7 +807,7 @@ describe('login history sync', () => {
releasePage = () => resolve([groupMessage(30001, 1)]);
}),
);
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const bridge = makeBridge({
friendCount: 0,
@@ -815,7 +840,7 @@ describe('login history sync', () => {
});
it('stops conversion side effects when disposal happens during conversion', async () => {
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const controller = new AbortController();
const mediaSegmentSink = vi.fn();
@@ -867,7 +892,7 @@ describe('login history sync', () => {
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
}),
});
const resource = makeStore();
const resource = await makeStore();
resources.push(resource);
const controller = new AbortController();
@@ -327,7 +327,7 @@ describe('buildApiContext getLoginInfo', () => {
});
describe('buildApiContext message-store passthroughs', () => {
it('reads events and metas through the message store', () => {
it('reads events and metas through the message store', async () => {
const storedEvent = {
post_type: 'message',
message_type: 'group',
@@ -339,14 +339,14 @@ describe('buildApiContext message-store passthroughs', () => {
events.set(-55, storedEvent);
metas.set(-55, storedMeta);
expect(api.getMessage(-55)).toEqual({
expect(await api.getMessage(-55)).toEqual({
post_type: 'message',
message_type: 'group',
message_id: -55,
raw_message: 'stored',
});
expect(api.getMessage(1)).toBeNull();
expect(api.getMessageMeta(-55)).toEqual({
expect(await api.getMessage(1)).toBeNull();
expect(await api.getMessageMeta(-55)).toEqual({
isGroup: true,
targetId: GROUP_ID,
sequence: 91,
@@ -358,18 +358,18 @@ describe('buildApiContext message-store passthroughs', () => {
});
});
it('stores meta batches on the message store', () => {
it('stores meta batches on the message store', async () => {
const storeMetas = vi.fn();
const { api } = makeRef({ messageStore: { storeMetas } });
const entries = [{ messageId: -12, meta: privateMeta({ sequence: 8 }) }];
api.cacheMessageMetas(entries);
await api.cacheMessageMetas(entries);
expect(storeMetas).toHaveBeenCalledOnce();
expect(storeMetas).toHaveBeenCalledWith(entries);
});
it('lists read sessions from the current identity group ids', () => {
it('lists read sessions from the current identity group ids', async () => {
const listReadSessions = vi.fn(() => ({
groupIds: [710101, 710102],
privateUserIds: [50001],
@@ -381,7 +381,7 @@ describe('buildApiContext message-store passthroughs', () => {
messageStore: { listReadSessions },
});
expect(api.listReadSessions()).toEqual({
expect(await api.listReadSessions()).toEqual({
groupIds: [710101, 710102],
privateUserIds: [50001],
});
@@ -1059,7 +1059,7 @@ describe('buildApiContext media', () => {
await expect(api.getImageInfo('missing.jpg')).resolves.toBeNull();
});
it('returns cached record info and refetches a missing group ptt url', async () => {
it('resolves indexed record info through the group ptt API', async () => {
const getPttUrl = vi.fn(async () => 'https://ptt.example/group');
const updateRecordUrl = vi.fn();
const mediaNode = { fileUuid: 'uuid-1' };
+39 -185
View File
@@ -776,218 +776,72 @@ describe('getImageInfo', () => {
});
describe('getRecordInfo', () => {
it('returns null when the record is not cached', async () => {
it('returns null when the record is not indexed', async () => {
await expect(
getRecordInfo(fakeBridge(), fakeRecordStore(null), 'missing.silk'),
).resolves.toBeNull();
});
it('returns the stored url without refetching', async () => {
const getPttUrl = vi.fn(async () => 'https://ptt.example/should-not-run');
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/should-not-run');
const updateRecordUrl = vi.fn();
await expect(
getRecordInfo(
fakeBridge({ getPttUrl, getPrivatePttUrl }),
fakeRecordStore(
cachedRecord({
url: 'https://ptt.example/cached.silk',
mediaNode: { fileUuid: 'uuid-1' },
it.each([true, false])(
'requests a fresh URL even when one is stored (group=%s)',
async (isGroup) => {
const mediaNode = { fileUuid: 'voice-uuid', storeId: 1 };
const getPttUrl = vi.fn(async () => 'https://ptt.example/group-fresh');
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private-fresh');
const updateRecordUrl = vi.fn();
const url = `https://ptt.example/${isGroup ? 'group' : 'private'}-fresh`;
await expect(
getRecordInfo(
fakeBridge({ getPttUrl, getPrivatePttUrl }),
fakeRecordStore(cachedRecord({ isGroup, sessionId: GROUP_ID, mediaNode }), {
updateRecordUrl,
}),
{ updateRecordUrl },
'voice.silk',
),
'voice.silk',
),
).resolves.toEqual({
file: 'https://ptt.example/cached.silk',
url: 'https://ptt.example/cached.silk',
file_size: '4096',
file_name: 'voice.silk',
});
expect(getPttUrl).not.toHaveBeenCalled();
expect(getPrivatePttUrl).not.toHaveBeenCalled();
expect(updateRecordUrl).not.toHaveBeenCalled();
});
).resolves.toEqual({ file: url, url, file_size: '4096', file_name: 'voice.silk' });
it('does not refetch when the url is empty and there is no mediaNode', async () => {
const getPttUrl = vi.fn(async () => 'https://ptt.example/group');
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private');
if (isGroup) {
expect(getPttUrl).toHaveBeenCalledWith(GROUP_ID, mediaNode);
expect(getPrivatePttUrl).not.toHaveBeenCalled();
} else {
expect(getPrivatePttUrl).toHaveBeenCalledWith(mediaNode);
expect(getPttUrl).not.toHaveBeenCalled();
}
expect(updateRecordUrl).toHaveBeenCalledWith('voice.silk', url);
},
);
it('rejects missing resource metadata even when an old URL exists', async () => {
await expect(
getRecordInfo(
fakeBridge({ getPttUrl, getPrivatePttUrl }),
fakeRecordStore(cachedRecord({ url: '', mediaNode: undefined })),
'voice.silk',
),
).resolves.toEqual({
file: 'voice.silk',
url: '',
file_size: '4096',
file_name: 'voice.silk',
});
expect(getPttUrl).not.toHaveBeenCalled();
expect(getPrivatePttUrl).not.toHaveBeenCalled();
getRecordInfo(fakeBridge(), fakeRecordStore(cachedRecord()), 'voice.silk'),
).rejects.toThrow('record media metadata is missing');
});
it('refetches a group ptt url and writes it back under the lookup key', async () => {
const mediaNode = { fileUuid: 'group-uuid', storeId: 1 };
const getPttUrl = vi.fn(async () => 'https://ptt.example/group-fresh');
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private');
const updateRecordUrl = vi.fn();
await expect(
getRecordInfo(
fakeBridge({ getPttUrl, getPrivatePttUrl }),
fakeRecordStore(
cachedRecord({
file: 'primary.silk',
url: '',
isGroup: true,
sessionId: GROUP_ID,
mediaNode,
}),
{ updateRecordUrl },
),
'alias.silk',
),
).resolves.toEqual({
file: 'https://ptt.example/group-fresh',
url: 'https://ptt.example/group-fresh',
file_size: '4096',
file_name: 'voice.silk',
});
expect(getPttUrl).toHaveBeenCalledWith(710010, mediaNode);
expect(getPrivatePttUrl).not.toHaveBeenCalled();
expect(updateRecordUrl).toHaveBeenCalledWith(
'alias.silk',
'https://ptt.example/group-fresh',
);
});
it('refetches a private ptt url from the media node only', async () => {
const mediaNode = { fileUuid: 'c2c-uuid' };
const getPttUrl = vi.fn(async () => 'https://ptt.example/group');
const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private-fresh');
const updateRecordUrl = vi.fn();
await expect(
getRecordInfo(
fakeBridge({ getPttUrl, getPrivatePttUrl }),
fakeRecordStore(
cachedRecord({
url: '',
isGroup: false,
mediaNode,
}),
{ updateRecordUrl },
),
'voice.silk',
),
).resolves.toEqual({
file: 'https://ptt.example/private-fresh',
url: 'https://ptt.example/private-fresh',
file_size: '4096',
file_name: 'voice.silk',
});
expect(getPrivatePttUrl).toHaveBeenCalledWith(mediaNode);
expect(getPttUrl).not.toHaveBeenCalled();
expect(updateRecordUrl).toHaveBeenCalledWith(
'voice.silk',
'https://ptt.example/private-fresh',
);
});
it('does not write back an empty refetch result', async () => {
const updateRecordUrl = vi.fn();
const getPrivatePttUrl = vi.fn(async () => '');
it('propagates remote errors instead of returning the cached URL', async () => {
const failure = new Error('QQ resource expired');
const getPrivatePttUrl = vi.fn().mockRejectedValue(failure);
await expect(
getRecordInfo(
fakeBridge({ getPrivatePttUrl }),
fakeRecordStore(
cachedRecord({
url: '',
mediaNode: { fileUuid: 'empty-uuid' },
}),
{ updateRecordUrl },
),
fakeRecordStore(cachedRecord({ mediaNode: { fileUuid: 'voice-uuid' } })),
'voice.silk',
),
).resolves.toEqual({
file: 'voice.silk',
url: '',
file_size: '4096',
file_name: 'voice.silk',
});
expect(updateRecordUrl).not.toHaveBeenCalled();
});
it('returns the cached file after a refetch Error', async () => {
const updateRecordUrl = vi.fn();
const getPttUrl = vi.fn(async () => {
throw new Error('cdn timeout');
});
await expect(
getRecordInfo(
fakeBridge({ getPttUrl }),
fakeRecordStore(
cachedRecord({
file: 'keep.silk',
url: '',
isGroup: true,
sessionId: GROUP_ID,
mediaNode: { fileUuid: 'fail-uuid' },
}),
{ updateRecordUrl },
),
'keep.silk',
),
).resolves.toEqual({
file: 'keep.silk',
url: '',
file_size: '4096',
file_name: 'voice.silk',
});
expect(updateRecordUrl).not.toHaveBeenCalled();
});
it('returns the cached file after a non-Error refetch rejection', async () => {
const getPrivatePttUrl = vi.fn(async () => {
throw 'offline';
});
await expect(
getRecordInfo(
fakeBridge({ getPrivatePttUrl }),
fakeRecordStore(
cachedRecord({
url: '',
isGroup: false,
mediaNode: { fileUuid: 'offline-uuid' },
}),
),
'voice.silk',
),
).resolves.toEqual({
file: 'voice.silk',
url: '',
file_size: '4096',
file_name: 'voice.silk',
});
).rejects.toBe(failure);
});
it('stringifies a missing fileSize as 0 and falls file_name back to file', async () => {
await expect(
getRecordInfo(
fakeBridge(),
fakeBridge({
getPrivatePttUrl: vi.fn(async () => 'https://ptt.example/named.silk'),
}),
fakeRecordStore(
cachedRecord({
file: 'fallback.silk',
fileName: '',
fileSize: undefined as unknown as number,
url: 'https://ptt.example/named.silk',
mediaNode: { fileUuid: 'voice-uuid' },
}),
),
'fallback.silk',
+18 -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,13 @@ describe('MediaIndexer', () => {
height: 1080,
videoFormat: 2,
};
indexer.remember('video', element, { url: 'http://v', file: 'override.mp4' }, true, 11111);
await indexer.remember(
'video',
element,
{ url: 'http://v', file: 'override.mp4' },
true,
11111,
);
const arg = store.rememberVideo.mock.calls[0]![0];
expect(arg.file).toBe('override.mp4'); // data.file used when non-empty
@@ -97,18 +103,18 @@ describe('MediaIndexer', () => {
expect(arg.videoFormat).toBe(2);
});
it('falls back to element.fileId when data.file AND element.fileName are missing (record)', () => {
it('falls back to element.fileId when data.file AND element.fileName are missing (record)', async () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = { type: 'record', fileId: 'only-fid' };
indexer.remember('record', element, { url: '', file: '' }, false, 1);
await indexer.remember('record', element, { url: '', file: '' }, false, 1);
expect(store.rememberRecord.mock.calls[0]![0].file).toBe('only-fid');
});
it('defaults missing numeric fields to 0 / missing strings to ""', () => {
it('defaults missing numeric fields to 0 / missing strings to ""', async () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
indexer.remember('image', { type: 'image' }, { url: '', file: '' }, false, 0);
await indexer.remember('image', { type: 'image' }, { url: '', file: '' }, false, 0);
const arg = store.rememberImage.mock.calls[0]![0];
expect(arg.fileSize).toBe(0);
expect(arg.subType).toBe(0);
@@ -116,10 +122,10 @@ describe('MediaIndexer', () => {
expect(arg.imageUrl).toBe('');
});
it('only the matching rememberX is called', () => {
it('only the matching rememberX is called', async () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
indexer.remember('image', { type: 'image' }, { url: '', file: 'a' }, true, 1);
await indexer.remember('image', { type: 'image' }, { url: '', file: 'a' }, true, 1);
expect(store.rememberImage).toHaveBeenCalledOnce();
expect(store.rememberRecord).not.toHaveBeenCalled();
expect(store.rememberVideo).not.toHaveBeenCalled();
+63 -59
View File
@@ -96,9 +96,9 @@ describe('MediaStore basic semantics', () => {
return max !== undefined ? new MediaStore(dbPath, max) : new MediaStore(dbPath);
}
it('indexes images by file, fileName, and url', () => {
it('indexes images by file, fileName, and url', async () => {
const store = open('img-keys');
store.rememberImage({
await store.rememberImage({
file: 'abc.png',
url: 'https://example.com/abc.png',
fileSize: 4242,
@@ -110,18 +110,18 @@ describe('MediaStore basic semantics', () => {
sessionId: GROUP_ID,
});
expect(store.findImage('abc.png')?.fileSize).toBe(4242);
expect(store.findImage('https://example.com/abc.png')?.url).toBe(
expect((await store.findImage('abc.png'))?.fileSize).toBe(4242);
expect((await store.findImage('https://example.com/abc.png'))?.url).toBe(
'https://example.com/abc.png',
);
expect(store.findImage('missing.png')).toBeNull();
expect(store.findImage('')).toBeNull();
store.close();
expect(await store.findImage('missing.png')).toBeNull();
expect(await store.findImage('')).toBeNull();
await store.close();
});
it('indexes records by file, fileName, fileId, and url', () => {
it('indexes records by file, fileName, fileId, and url', async () => {
const store = open('rec-keys');
store.rememberRecord({
await store.rememberRecord({
file: 'silk_test.amr',
fileId: 'uuid-base64-fake',
url: 'https://example.com/voice.amr',
@@ -134,18 +134,18 @@ describe('MediaStore basic semantics', () => {
sessionId: PEER_UIN,
});
expect(store.findRecord('silk_test.amr')?.duration).toBe(3);
expect(store.findRecord('uuid-base64-fake')?.fileId).toBe('uuid-base64-fake');
expect(store.findRecord('https://example.com/voice.amr')?.url).toBe(
expect((await store.findRecord('silk_test.amr'))?.duration).toBe(3);
expect((await store.findRecord('uuid-base64-fake'))?.fileId).toBe('uuid-base64-fake');
expect((await store.findRecord('https://example.com/voice.amr'))?.url).toBe(
'https://example.com/voice.amr',
);
expect(store.findRecord('nope')).toBeNull();
store.close();
expect(await store.findRecord('nope')).toBeNull();
await store.close();
});
it('updates URLs in place across all alias keys', () => {
it('updates URLs in place across all alias keys', async () => {
const store = open('url-update');
store.rememberRecord({
await store.rememberRecord({
file: 'silk_test.amr',
fileId: 'uuid-base64-fake',
url: '',
@@ -157,24 +157,25 @@ describe('MediaStore basic semantics', () => {
isGroup: false,
sessionId: PEER_UIN,
});
store.updateRecordUrl('silk_test.amr', 'https://refreshed.example.com/voice.amr');
await store.updateRecordUrl('silk_test.amr', 'https://refreshed.example.com/voice.amr');
expect(store.findRecord('silk_test.amr')?.url).toBe(
expect((await store.findRecord('silk_test.amr'))?.url).toBe(
'https://refreshed.example.com/voice.amr',
);
expect(store.findRecord('uuid-base64-fake')?.url).toBe(
expect((await store.findRecord('uuid-base64-fake'))?.url).toBe(
'https://refreshed.example.com/voice.amr',
);
store.close();
await store.close();
});
it('survives close+reopen against the same db path', () => {
it('survives close+reopen against the same db path', async () => {
const dbPath = tempDbPath('persist');
dbs.push(dbPath);
{
const store = new MediaStore(dbPath);
store.rememberImage({
await store.initialization;
await store.rememberImage({
file: 'abc.png',
url: 'https://example.com/abc.png',
fileSize: 99,
@@ -185,27 +186,28 @@ describe('MediaStore basic semantics', () => {
isGroup: true,
sessionId: GROUP_ID,
});
store.close();
await store.close();
}
{
const store = new MediaStore(dbPath);
const found = store.findImage('abc.png');
await store.initialization;
const found = await store.findImage('abc.png');
expect(found).not.toBeNull();
expect(found!.fileSize).toBe(99);
// Alias index must also persist.
expect(store.findImage('https://example.com/abc.png')?.fileSize).toBe(99);
store.close();
expect((await store.findImage('https://example.com/abc.png'))?.fileSize).toBe(99);
await store.close();
}
});
it('retains durable entries beyond the memory cache cap', () => {
it('retains durable entries beyond the memory cache cap', async () => {
// Lookups can be evicted from memory, but historical metadata survives.
const cap = 80;
const store = open('evict', cap);
for (let i = 0; i < 200; i++) {
store.rememberImage({
await store.rememberImage({
file: `file-${i}.png`,
url: `https://example.com/${i}.png`,
fileSize: i,
@@ -218,23 +220,23 @@ describe('MediaStore basic semantics', () => {
});
}
const { images } = store.size();
const { images } = await store.size();
expect(images).toBe(200);
for (let i = 0; i < 200; i++) {
expect(store.findImage(`file-${i}.png`)?.fileSize).toBe(i);
expect((await store.findImage(`file-${i}.png`))?.fileSize).toBe(i);
}
expect(store.findImage('file-0.png')?.fileSize).toBe(0);
expect((await store.findImage('file-0.png'))?.fileSize).toBe(0);
// Most recent entries should still be present.
expect(store.findImage('file-199.png')?.fileSize).toBe(199);
store.close();
expect((await store.findImage('file-199.png'))?.fileSize).toBe(199);
await store.close();
});
it('does not persist inline base64 as a key or JSON payload (#463)', () => {
it('does not persist inline base64 as a key or JSON payload (#463)', async () => {
const store = open('inline-b64');
const payload = `base64://${'A'.repeat(8192)}`;
store.rememberImage({
await store.rememberImage({
file: payload,
url: payload,
fileSize: 99,
@@ -249,7 +251,7 @@ describe('MediaStore basic semantics', () => {
height: 600,
});
const found = store.findImage(payload);
const found = await store.findImage(payload);
expect(found).not.toBeNull();
expect(found!.fileSize).toBe(99);
expect(found!.md5Hex).toBe('aa'.repeat(16));
@@ -258,7 +260,7 @@ describe('MediaStore basic semantics', () => {
expect(found!.file.startsWith('inline:')).toBe(true);
expect(found!.file.includes('base64://')).toBe(false);
store.close();
await store.close();
const rows = inspectMediaDb(dbs[dbs.length - 1]!);
expect(rows.longestKey).toBeLessThanOrEqual(MEDIA_KEY_MAX_CHARS);
expect(rows.longestData).toBeLessThanOrEqual(MEDIA_DATA_MAX_CHARS);
@@ -267,10 +269,10 @@ describe('MediaStore basic semantics', () => {
expect(rows.concatenated).not.toContain('A'.repeat(64));
});
it('folds oversized non-inline keys the same way', () => {
it('folds oversized non-inline keys the same way', async () => {
const store = open('long-url');
const url = `https://cdn.example/${'a'.repeat(3000)}.png`;
store.rememberImage({
await store.rememberImage({
file: 'short.png',
url,
fileSize: 12,
@@ -282,18 +284,18 @@ describe('MediaStore basic semantics', () => {
sessionId: GROUP_ID,
});
expect(store.findImage('short.png')?.fileSize).toBe(12);
expect(store.findImage(url)?.fileSize).toBe(12);
expect(store.findImage('short.png')?.url).toBe('');
store.close();
expect((await store.findImage('short.png'))?.fileSize).toBe(12);
expect((await store.findImage(url))?.fileSize).toBe(12);
expect((await store.findImage('short.png'))?.url).toBe('');
await store.close();
const rows = inspectMediaDb(dbs[dbs.length - 1]!);
expect(rows.longestKey).toBeLessThanOrEqual(MEDIA_KEY_MAX_CHARS);
expect(rows.concatenated).not.toContain('a'.repeat(64));
});
it('ignores an inline URL refresh so eviction cannot be re-poisoned', () => {
it('ignores an inline URL refresh so eviction cannot be re-poisoned', async () => {
const store = open('no-inline-refresh');
store.rememberImage({
await store.rememberImage({
file: 'abc.png',
url: 'https://example.com/abc.png',
fileSize: 7,
@@ -304,12 +306,12 @@ describe('MediaStore basic semantics', () => {
isGroup: true,
sessionId: GROUP_ID,
});
store.updateImageUrl('abc.png', `base64://${'B'.repeat(100)}`);
expect(store.findImage('abc.png')?.url).toBe('https://example.com/abc.png');
store.close();
await store.updateImageUrl('abc.png', `base64://${'B'.repeat(100)}`);
expect((await store.findImage('abc.png'))?.url).toBe('https://example.com/abc.png');
await store.close();
});
it('does not destructively purge existing metadata on open', () => {
it('does not destructively purge existing metadata on open', async () => {
const dbPath = tempDbPath('legacy-overflow');
dbs.push(dbPath);
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
@@ -340,9 +342,10 @@ describe('MediaStore basic semantics', () => {
raw.close();
const store = new MediaStore(dbPath);
expect(store.findImage(poisonKey)).toBeNull();
expect(store.size().images).toBe(1);
store.close();
await store.initialization;
expect(await store.findImage(poisonKey)).toBeNull();
expect((await store.size()).images).toBe(1);
await store.close();
const rows = inspectMediaDb(dbPath);
expect(rows.entryCount).toBe(1);
expect(rows.keyCount).toBe(1);
@@ -432,17 +435,18 @@ describe('convertEvent media segment sink → MediaStore wiring', () => {
dbs.push(dbPath);
const store = new MediaStore(dbPath);
await store.initialization;
const ctx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: (element) => element.imageUrl ?? '',
mediaUrlResolver: async (element) => element.url ?? '',
messageIdResolver: null,
mediaSegmentSink: (type, element, data, isGroup, sessionId) => {
mediaSegmentSink: async (type, element, data, isGroup, sessionId) => {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (type === 'image') {
store.rememberImage({
await store.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
@@ -454,7 +458,7 @@ describe('convertEvent media segment sink → MediaStore wiring', () => {
sessionId,
});
} else {
store.rememberRecord({
await store.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
@@ -473,22 +477,22 @@ describe('convertEvent media segment sink → MediaStore wiring', () => {
await convertEvent(ctx, makeGroupMessage([imageElement()]));
await convertEvent(ctx, makeFriendMessage([recordElement()]));
const img = store.findImage('abc.png');
const img = await store.findImage('abc.png');
expect(img).not.toBeNull();
expect(img!.url).toBe('https://example.com/abc.png');
expect(img!.fileSize).toBe(4242);
expect(img!.isGroup).toBe(true);
expect(img!.sessionId).toBe(GROUP_ID);
const rec = store.findRecord('silk_test.amr');
const rec = await store.findRecord('silk_test.amr');
expect(rec).not.toBeNull();
expect(rec!.fileId).toBe('uuid-base64-fake');
expect(rec!.duration).toBe(3);
expect(rec!.isGroup).toBe(false);
expect(rec!.sessionId).toBe(PEER_UIN);
// Alias lookup by fileUuid still works.
expect(store.findRecord('uuid-base64-fake')?.fileName).toBe('silk_test.amr');
store.close();
expect((await store.findRecord('uuid-base64-fake'))?.fileName).toBe('silk_test.amr');
await store.close();
});
it('does not invoke the sink when no media segments are present', async () => {
@@ -1,16 +1,9 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { MediaUrlResolver } from '../src/media-url-resolver';
import { RKeyCache } from '../src/instance-rkey';
import type { MessageElement } from '@snowluma/protocol/events';
// Minimal stand-ins for the two collaborators. Each test wires whatever
// subset of Bridge methods the element type exercises.
//
// MediaUrlResolver now reaches `bridge.apis.groupFile.{getUrl,
// getPrivateUrl, getPttUrl, getPrivatePttUrl, getVideoUrl,
// getPrivateVideoUrl}` per the #6 Api-on-ctx refactor. The helper here
// builds an `apis.groupFile` stub directly so tests can keep asserting
// "which file/url helper got called" without going through the
// `mockBridge` shared fixture.
function makeBridge(overrides: Record<string, ReturnType<typeof vi.fn>> = {}) {
return {
apis: {
@@ -132,19 +125,44 @@ describe('MediaUrlResolver — short-circuits and resilience', () => {
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
});
it('bridge throws: swallowed, rkey still applied', async () => {
const bridge = makeBridge({
getUrl: vi.fn(async () => {
throw new Error('network down');
}),
});
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') });
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid' };
const out = await resolver.resolve(element, true, 12345);
expect(out).toBe('rkey-fallback');
expect(element.url).toBeUndefined(); // bridge threw before assignment
});
it.each([
['file', true, 'getUrl'],
['file', false, 'getPrivateUrl'],
['record', true, 'getPttUrl'],
['record', false, 'getPrivatePttUrl'],
['video', true, 'getVideoUrl'],
['video', false, 'getPrivateVideoUrl'],
] as const)(
'%s group=%s: reports URL failure and preserves the media',
async (type, isGroup, method) => {
const bridge = makeBridge({
[method]: vi.fn().mockRejectedValue(new Error('network down')),
});
const resolver = new MediaUrlResolver(bridge as any, new RKeyCache());
const element: MessageElement = {
type,
fileId: 'fid',
fileHash: 'hash',
mediaNode: MEDIA_NODE,
};
const original = structuredClone(element);
const entries: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
await expect(resolver.resolve(element, isGroup, 12345)).resolves.toBe('');
expect(element).toEqual(original);
expect(entries).toContainEqual(
expect.objectContaining({
level: 'warn',
message: expect.stringMatching(/media URL resolution failed.*network down/),
}),
);
} finally {
unsubscribe();
}
},
);
it('always calls rkey.resolveMediaUrl at the end', async () => {
const bridge = makeBridge();
@@ -15,6 +15,7 @@ function instanceContext(
sendPrivate: ReturnType<typeof vi.fn> = vi.fn(),
): OneBotInstanceContext {
const bridge = {
identity: { nickname: 'SnowLuma' },
apis: { message: { sendGroup, sendPrivate } },
resolveUserUid: vi.fn(async () => 'u_peer'),
} as unknown as BridgeInterface;
@@ -27,9 +28,17 @@ function instanceContext(
resolveReplySequence: () => 0,
findEvent: () => null,
findMeta: () => null,
storeEvent: vi.fn(),
} as never,
cacheMessageMeta: vi.fn(),
mediaStore: {} as never,
converterCtx: {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
@@ -29,10 +29,12 @@ function createControlPort(): {
preparations: MessageStoreMigrationPreparation[];
send(message: unknown): void;
listenerCount(): number;
waitForMessages(count: number): Promise<void>;
} {
const messages: MessageStoreMigrationWorkerMessage[] = [];
const preparations: MessageStoreMigrationPreparation[] = [];
const events = new EventEmitter();
const waiters: Array<() => void> = [];
return {
port: {
on: events.on.bind(events),
@@ -43,6 +45,10 @@ function createControlPort(): {
} else {
messages.push(message);
}
for (const check of [...waiters]) {
check();
}
},
} as unknown as MessagePort,
messages,
@@ -50,14 +56,34 @@ function createControlPort(): {
send(message: unknown) {
events.emit('message', message);
},
waitForMessages(count) {
return new Promise<void>((resolve) => {
const check = () => {
if (messages.length < count) {
return;
}
const index = waiters.indexOf(check);
if (index >= 0) {
waiters.splice(index, 1);
}
resolve();
};
waiters.push(check);
check();
});
},
listenerCount() {
return events.listenerCount('message');
},
};
}
function seedUnclassified(dbPath: string, count: number): void {
prepareMessageStoreDatabase(dbPath);
async function seedUnclassified(dbPath: string, count: number): Promise<void> {
await prepareMessageStoreDatabase(dbPath);
const db = new DatabaseSync(dbPath);
const insert = db.prepare(`
INSERT INTO messages (
@@ -146,7 +172,7 @@ describe('runMessageStoreMigrationWorker', () => {
const close = vi.spyOn(MessageStoreMigrator.prototype, 'close');
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
expect(control.messages).toEqual([{ kind: 'ready' }]);
expect(control.listenerCount()).toBe(1);
@@ -158,12 +184,12 @@ describe('runMessageStoreMigrationWorker', () => {
{
kind: 'progress',
status: { phase: 'complete', processed: 0, total: 0 },
elapsedMs: 0,
elapsedMs: expect.any(Number),
},
]);
expect(control.listenerCount()).toBe(0);
expect(close).toHaveBeenCalledOnce();
expect(inspectMessageStoreMigration(dbPath)).toEqual({
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
phase: 'complete',
processed: 0,
total: 0,
@@ -174,7 +200,7 @@ describe('runMessageStoreMigrationWorker', () => {
const dbPath = path.join(tmpDir, 'messages.db');
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
control.send('go');
control.send({ kind: 'start' });
@@ -188,7 +214,7 @@ describe('runMessageStoreMigrationWorker', () => {
{
kind: 'progress',
status: { phase: 'complete', processed: 0, total: 0 },
elapsedMs: 0,
elapsedMs: expect.any(Number),
},
]);
});
@@ -202,7 +228,7 @@ describe('runMessageStoreMigrationWorker', () => {
const unsubscribe = subscribeLogs((entry) => logs.push(entry.scope));
vi.stubEnv('SNOWLUMA_LOG_FILE', '1');
const dbPath = path.join(tmpDir, 'messages.db');
seedUnclassified(dbPath, 1);
await seedUnclassified(dbPath, 1);
const control = createControlPort();
try {
@@ -231,11 +257,11 @@ describe('runMessageStoreMigrationWorker', () => {
it('returns after cancel without posting progress', async () => {
const dbPath = path.join(tmpDir, 'messages.db');
seedUnclassified(dbPath, 1);
await seedUnclassified(dbPath, 1);
const control = createControlPort();
const runBatch = vi.spyOn(MessageStoreMigrator.prototype, 'runBatch');
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
control.send('cancel');
await running;
@@ -243,7 +269,7 @@ describe('runMessageStoreMigrationWorker', () => {
expect(control.messages).toEqual([{ kind: 'ready' }]);
expect(runBatch).not.toHaveBeenCalled();
expect(control.listenerCount()).toBe(0);
expect(inspectMessageStoreMigration(dbPath)).toEqual({
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
phase: 'migrating',
processed: 0,
total: 1,
@@ -252,11 +278,11 @@ describe('runMessageStoreMigrationWorker', () => {
it('treats start then cancel in the same turn as a cancel', async () => {
const dbPath = path.join(tmpDir, 'messages.db');
seedUnclassified(dbPath, 1);
await seedUnclassified(dbPath, 1);
const control = createControlPort();
const runBatch = vi.spyOn(MessageStoreMigrator.prototype, 'runBatch');
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
control.send('start');
control.send('cancel');
@@ -268,10 +294,10 @@ describe('runMessageStoreMigrationWorker', () => {
it('migrates pending rows in one batch and posts complete progress', async () => {
const dbPath = path.join(tmpDir, 'messages.db');
seedUnclassified(dbPath, 1);
await seedUnclassified(dbPath, 1);
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
control.send('start');
await running;
@@ -281,10 +307,10 @@ describe('runMessageStoreMigrationWorker', () => {
{
kind: 'progress',
status: { phase: 'complete', processed: 1, total: 1 },
elapsedMs: 0,
elapsedMs: expect.any(Number),
},
]);
expect(inspectMessageStoreMigration(dbPath)).toEqual({
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
phase: 'complete',
processed: 1,
total: 1,
@@ -293,10 +319,10 @@ describe('runMessageStoreMigrationWorker', () => {
it('posts a second progress after the batch pause when more than 200 rows remain', async () => {
const dbPath = path.join(tmpDir, 'messages.db');
seedUnclassified(dbPath, 201);
await seedUnclassified(dbPath, 201);
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
control.send('start');
await running;
@@ -306,7 +332,7 @@ describe('runMessageStoreMigrationWorker', () => {
expect(control.messages[1]).toEqual({
kind: 'progress',
status: { phase: 'migrating', processed: 200, total: 201 },
elapsedMs: 0,
elapsedMs: expect.any(Number),
});
expect(control.messages[2]).toMatchObject({
kind: 'progress',
@@ -319,7 +345,7 @@ describe('runMessageStoreMigrationWorker', () => {
expect(last.elapsedMs).toBeGreaterThanOrEqual(0);
}
expect(inspectMessageStoreMigration(dbPath)).toEqual({
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
phase: 'complete',
processed: 201,
total: 201,
@@ -329,19 +355,19 @@ describe('runMessageStoreMigrationWorker', () => {
it('stops after cancel between batches', async () => {
vi.useFakeTimers();
const dbPath = path.join(tmpDir, 'messages.db');
seedUnclassified(dbPath, 201);
await seedUnclassified(dbPath, 201);
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
control.send('start');
await Promise.resolve();
await control.waitForMessages(2);
expect(control.messages).toEqual([
{ kind: 'ready' },
{
kind: 'progress',
status: { phase: 'migrating', processed: 200, total: 201 },
elapsedMs: 0,
elapsedMs: expect.any(Number),
},
]);
@@ -354,10 +380,10 @@ describe('runMessageStoreMigrationWorker', () => {
{
kind: 'progress',
status: { phase: 'migrating', processed: 200, total: 201 },
elapsedMs: 0,
elapsedMs: expect.any(Number),
},
]);
expect(inspectMessageStoreMigration(dbPath)).toEqual({
expect(await inspectMessageStoreMigration(dbPath)).toEqual({
phase: 'migrating',
processed: 200,
total: 201,
@@ -389,7 +415,7 @@ describe('runMessageStoreMigrationWorker', () => {
const dbPath = path.join(tmpDir, 'messages.db');
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
expect(control.messages).toEqual([{ kind: 'ready' }]);
const db = new DatabaseSync(dbPath);
@@ -401,13 +427,13 @@ describe('runMessageStoreMigrationWorker', () => {
expect(control.messages).toEqual([
{ kind: 'ready' },
{ kind: 'failed', message: 'no such table: main.messages' },
{ kind: 'failed', message: expect.stringContaining('no such table: main.messages') },
]);
});
it('posts failed when a batch update is aborted', async () => {
const dbPath = path.join(tmpDir, 'messages.db');
seedUnclassified(dbPath, 1);
await seedUnclassified(dbPath, 1);
const db = new DatabaseSync(dbPath);
db.exec(`
CREATE TRIGGER fail_classify BEFORE UPDATE ON messages
@@ -420,14 +446,14 @@ describe('runMessageStoreMigrationWorker', () => {
const control = createControlPort();
const close = vi.spyOn(MessageStoreMigrator.prototype, 'close');
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
control.send('start');
await running;
expect(control.messages).toEqual([
{ kind: 'ready' },
{ kind: 'failed', message: 'classified row rejected' },
{ kind: 'failed', message: expect.stringContaining('classified row rejected') },
]);
expect(close).toHaveBeenCalledOnce();
});
@@ -439,7 +465,7 @@ describe('runMessageStoreMigrationWorker', () => {
});
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
await control.waitForMessages(1);
control.send('start');
await running;
@@ -1,7 +1,7 @@
import { SqliteDatabase } from '@snowluma/sqlite';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MessageStoreMigrator, prepareMessageStoreDatabase } from '../src/message-store-migration';
@@ -10,14 +10,14 @@ const pendingIndex = 'idx_messages_pending_classification_v1';
describe('message history migration scans', () => {
let directory: string;
let dbPath: string;
let db: DatabaseSync;
let db: SqliteDatabase;
let migrator: MessageStoreMigrator | undefined;
beforeEach(() => {
beforeEach(async () => {
directory = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-migration-scans-'));
dbPath = path.join(directory, 'messages.db');
prepareMessageStoreDatabase(dbPath);
db = new DatabaseSync(dbPath);
await prepareMessageStoreDatabase(dbPath);
db = new SqliteDatabase(dbPath);
const insert = db.prepare(`INSERT INTO messages
(message_hash, is_group, session_id, sequence, client_sequence, event_name, data, media_data, classification_version)
VALUES (?, 0, 42, 1, 1, 'message.private', ?, ?, ?)`);
@@ -27,10 +27,10 @@ describe('message history migration scans', () => {
sub_type: 'friend',
message: [{ type: 'text', data: { text: 'x'.repeat(3000) } }],
});
db.exec('BEGIN');
await db.exec('BEGIN');
for (let hash = -500; hash <= 500; hash++) {
insert.run(
await insert.run(
hash,
data,
'{"retained":"snapshot"}',
@@ -38,14 +38,14 @@ describe('message history migration scans', () => {
);
}
db.exec('COMMIT');
await db.exec('COMMIT');
});
afterEach(() => {
afterEach(async () => {
vi.restoreAllMocks();
migrator?.close();
await migrator?.close();
migrator = undefined;
db.close();
await db.close();
fs.rmSync(directory, { recursive: true, force: true });
});
@@ -59,9 +59,9 @@ describe('message history migration scans', () => {
];
}
function expectPendingQueryPlans(queries: string[]): void {
async function expectPendingQueryPlans(queries: string[]): Promise<void> {
expect(queries).toHaveLength(3);
const planDb = new DatabaseSync(dbPath);
const planDb = new SqliteDatabase(dbPath, { readOnly: true });
try {
for (const sql of queries) {
@@ -70,9 +70,7 @@ describe('message history migration scans', () => {
? [1, -400, 1]
: [1, 1]
: [1];
const details = planDb
.prepare(`EXPLAIN QUERY PLAN ${sql}`)
.all(...args)
const details = (await planDb.prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...args))
.map((row) => String(row.detail))
.join('\n');
expect(details).toContain(pendingIndex);
@@ -83,34 +81,37 @@ describe('message history migration scans', () => {
}
}
} finally {
planDb.close();
await planDb.close();
}
}
it('uses pending rows for the actual count and ordered batch queries without changing history', () => {
const before = db
it('uses pending rows for the actual count and ordered batch queries without changing history', async () => {
const before = await db
.prepare('SELECT message_hash, data, media_data FROM messages ORDER BY message_hash')
.all();
const prepare = vi.spyOn(DatabaseSync.prototype, 'prepare');
const prepare = vi.spyOn(SqliteDatabase.prototype, 'prepare');
migrator = new MessageStoreMigrator(dbPath);
await migrator.initialization;
const queries = capturedPendingQueries(prepare.mock.calls.map(([sql]) => sql));
expectPendingQueryPlans(queries);
expect(migrator.getStatus()).toEqual({ phase: 'migrating', processed: 0, total: 3 });
expect(migrator.runBatch(2)).toEqual({ phase: 'migrating', processed: 2, total: 3 });
expect(migrator.runBatch(2)).toEqual({ phase: 'complete', processed: 3, total: 3 });
expectPendingQueryPlans(queries);
await expectPendingQueryPlans(queries);
expect(await migrator.getStatus()).toEqual({ phase: 'migrating', processed: 0, total: 3 });
expect(await migrator.runBatch(2)).toEqual({ phase: 'migrating', processed: 2, total: 3 });
expect(await migrator.runBatch(2)).toEqual({ phase: 'complete', processed: 3, total: 3 });
await expectPendingQueryPlans(queries);
expect(
db.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1').get(),
await db
.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1')
.get(),
).toEqual({ n: 0 });
expect(
db
await db
.prepare(
'SELECT message_hash, data, media_data FROM messages ORDER BY message_hash',
)
.all(),
).toEqual(before);
expect(
db
await db
.prepare(
'SELECT message_hash, private_direction FROM messages WHERE message_hash IN (-400, 0, 400) ORDER BY message_hash',
)
@@ -122,75 +123,84 @@ describe('message history migration scans', () => {
]);
});
it('adds the index when resuming a migration started by an older version', () => {
it('adds the index when resuming a migration started by an older version', async () => {
migrator = new MessageStoreMigrator(dbPath);
expect(migrator.runBatch(1)).toEqual({ phase: 'migrating', processed: 1, total: 3 });
migrator.close();
await migrator.initialization;
expect(await migrator.runBatch(1)).toEqual({ phase: 'migrating', processed: 1, total: 3 });
await migrator.close();
migrator = undefined;
db.exec(`DROP INDEX IF EXISTS ${pendingIndex}`);
await db.exec(`DROP INDEX IF EXISTS ${pendingIndex}`);
migrator = new MessageStoreMigrator(dbPath);
await migrator.initialization;
expect(
db
await db
.prepare('SELECT name FROM sqlite_schema WHERE type = ? AND name = ?')
.get('index', pendingIndex),
).toEqual({ name: pendingIndex });
expect(migrator.getStatus()).toEqual({ phase: 'migrating', processed: 1, total: 3 });
expect(migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
expect(await migrator.getStatus()).toEqual({ phase: 'migrating', processed: 1, total: 3 });
expect(await migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
});
it('does not rebuild an existing pending index when an interrupted migration resumes', () => {
it('does not rebuild an existing pending index when an interrupted migration resumes', async () => {
migrator = new MessageStoreMigrator(dbPath);
migrator.runBatch(1);
migrator.close();
await migrator.initialization;
await migrator.runBatch(1);
await migrator.close();
migrator = undefined;
const schemaVersion = db.prepare('PRAGMA schema_version').get();
const schemaVersion = await db.prepare('PRAGMA schema_version').get();
migrator = new MessageStoreMigrator(dbPath);
expect(db.prepare('PRAGMA schema_version').get()).toEqual(schemaVersion);
expect(migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
await migrator.initialization;
expect(await db.prepare('PRAGMA schema_version').get()).toEqual(schemaVersion);
expect(await migrator.runBatch(3)).toEqual({ phase: 'complete', processed: 3, total: 3 });
});
it('revisits rows left behind the cursor after a concurrent update prevented classification', () => {
db.exec(`CREATE TRIGGER defer_first BEFORE UPDATE ON messages
it('revisits rows left behind the cursor after a concurrent update prevented classification', async () => {
await db.exec(`CREATE TRIGGER defer_first BEFORE UPDATE ON messages
WHEN OLD.message_hash = -400 BEGIN SELECT RAISE(IGNORE); END`);
migrator = new MessageStoreMigrator(dbPath);
expect(migrator.runBatch(1)).toEqual({ phase: 'migrating', processed: 0, total: 3 });
db.exec('DROP TRIGGER defer_first');
expect(migrator.runBatch(2)).toEqual({ phase: 'migrating', processed: 2, total: 3 });
expect(migrator.runBatch(2)).toEqual({ phase: 'complete', processed: 3, total: 3 });
await migrator.initialization;
expect(await migrator.runBatch(1)).toEqual({ phase: 'migrating', processed: 0, total: 3 });
await db.exec('DROP TRIGGER defer_first');
expect(await migrator.runBatch(2)).toEqual({ phase: 'migrating', processed: 2, total: 3 });
expect(await migrator.runBatch(2)).toEqual({ phase: 'complete', processed: 3, total: 3 });
expect(
db.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1').get(),
await db
.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1')
.get(),
).toEqual({ n: 0 });
expect(db.prepare('SELECT COUNT(*) AS n FROM messages').get()).toEqual({ n: 1001 });
expect(await db.prepare('SELECT COUNT(*) AS n FROM messages').get()).toEqual({ n: 1001 });
});
it('skips index creation and pending counts when an older version already completed migration', () => {
it('skips index creation and pending counts when an older version already completed migration', async () => {
migrator = new MessageStoreMigrator(dbPath);
migrator.runBatch(10);
migrator.close();
await migrator.initialization;
await migrator.runBatch(10);
await migrator.close();
migrator = undefined;
db.exec(`DROP INDEX IF EXISTS ${pendingIndex}`);
const exec = vi.spyOn(DatabaseSync.prototype, 'exec');
const prepare = vi.spyOn(DatabaseSync.prototype, 'prepare');
await db.exec(`DROP INDEX IF EXISTS ${pendingIndex}`);
const exec = vi.spyOn(SqliteDatabase.prototype, 'exec');
const prepare = vi.spyOn(SqliteDatabase.prototype, 'prepare');
migrator = new MessageStoreMigrator(dbPath);
expect(migrator.runBatch(10)).toEqual({ phase: 'complete', processed: 3, total: 3 });
await migrator.initialization;
expect(await migrator.runBatch(10)).toEqual({ phase: 'complete', processed: 3, total: 3 });
expect(exec.mock.calls.some(([sql]) => /CREATE\s+INDEX/i.test(sql))).toBe(false);
expect(prepare.mock.calls.some(([sql]) => sql.includes('COUNT(*)'))).toBe(false);
expect(
db
await db
.prepare('SELECT name FROM sqlite_schema WHERE type = ? AND name = ?')
.get('index', pendingIndex),
).toBeUndefined();
});
it('propagates preparation failure and closes the failed migration connection', () => {
const originalExec = DatabaseSync.prototype.exec;
it('propagates preparation failure and closes the failed migration connection', async () => {
const originalExec = SqliteDatabase.prototype.exec;
const failure = new Error('pending index unavailable');
let failedDb: DatabaseSync | undefined;
vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (
this: DatabaseSync,
let failedDb: SqliteDatabase | undefined;
vi.spyOn(SqliteDatabase.prototype, 'exec').mockImplementation(async function (
this: SqliteDatabase,
sql,
) {
if (sql.includes(pendingIndex)) {
@@ -201,13 +211,18 @@ describe('message history migration scans', () => {
return originalExec.call(this, sql);
});
expect(() => {
await expect(async () => {
migrator = new MessageStoreMigrator(dbPath);
}).toThrow(failure);
await migrator.initialization;
}).rejects.toThrow(failure);
expect(failedDb).toBeDefined();
expect(() => failedDb!.prepare('SELECT 1')).toThrow(/not open/);
await migrator!.close();
migrator = undefined;
await expect(failedDb!.exec('SELECT 1')).rejects.toThrow(/closing/);
expect(
db.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1').get(),
await db
.prepare('SELECT COUNT(*) AS n FROM messages WHERE classification_version < 1')
.get(),
).toEqual({ n: 3 });
});
});
File diff suppressed because it is too large. Load diff
@@ -29,7 +29,10 @@ async function sendQuote(isGroup: boolean, original: JsonValue | null) {
const ref = {
uin: '10001',
selfId: 10001,
bridge: { apis: { message: { sendGroup: send, sendPrivate: send } } },
bridge: {
identity: { nickname: 'SnowLuma' },
apis: { message: { sendGroup: send, sendPrivate: send } },
},
messageStore: {
findEvent: () =>
original === null ? null : { user_id: sender, time, message: original },
@@ -41,6 +44,14 @@ async function sendQuote(isGroup: boolean, original: JsonValue | null) {
sequenceAuthoritative: true,
}),
resolveReplySequence: () => sequence,
storeEvent: vi.fn(),
},
converterCtx: {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
cacheMessageMeta: vi.fn(),
mediaStore: {},
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff. Show more