perf(sqlite): swap node:sqlite for better-sqlite3 + cache prepared stmts
Replaces the experimental `node:sqlite` builtin with the stable
`better-sqlite3` wrapper across the two hot SQLite users — the
OneBot message-store and the bridge identity-service. While the API
surface is essentially identical (sync, prepared-statement-driven,
`Database`/`Statement` shape), better-sqlite3 (a) doesn't carry the
"ExperimentalWarning: SQLite is an experimental feature" baggage
that ships with `node:sqlite`, (b) has a more mature C++ binding
that consistently outperforms the builtin by ~30-50%, and (c)
encourages reusing `Statement` objects by design — exactly the win
the second half of this commit is after.
Why both at once
----------------
Caching prepared statements (was P1 in the RoadMap-#5 analysis) is
the largest single optimization opportunity on the SQLite path. The
old shape was the textbook SQLite anti-pattern:
// every call re-parsed the SQL
this.db.prepare(BIG_SQL_STRING).run(...);
Each `prepare(sql)` runs the full SQL parser + planner — for simple
inserts/updates/selects that dominates wall-clock cost. Doing both
the driver swap AND the statement caching in one commit lets the
benchmark numbers attribute the combined effect honestly; splitting
them would have double-charged the same disruption budget.
What changed code-wise
----------------------
**messageStore** — 8 distinct SQL templates, all now `readonly`
fields prepared once in the constructor:
- stmtStoreEvent — INSERT/UPDATE event row + JSON payload
- stmtStoreMeta — INSERT/UPDATE meta-only row
- stmtFindEvent — single-row SELECT by message_hash
- stmtFindMeta — single-row SELECT (full meta columns)
- stmtResolveReplyGroup, stmtResolveReplyPrivate
— 2 variants for the reply-id lookup
- stmtListEventsAnchored, stmtListEventsLatest
— 2 variants for /get_history_msg
**identity-service** — 25+ distinct statements. Used a Map-based
`pstmt(sql)` memoization helper rather than enumerating all 25 as
named fields (call sites stay readable; Map lookup is O(1) hash +
string-eq, negligible next to the SQL parse it replaces). The
helper short-circuits to the cached `Statement` on second-and-later
calls.
API differences from node:sqlite (handled in this commit):
- `import { DatabaseSync } from 'node:sqlite'`
→ `import Database from 'better-sqlite3'`
- `new DatabaseSync(path)` → `new Database(path)`
- `db.exec('PRAGMA journal_mode = WAL')`
→ `db.pragma('journal_mode = WAL')`
- `db.exec('BEGIN' / 'COMMIT' / 'ROLLBACK')` — kept as-is; both
drivers accept raw `exec()` for transaction control. The
`db.transaction()` higher-order wrapper is more idiomatic
but the existing manual control already works and changing
it would invalidate the `transaction()` helper's matched
try/catch shape.
vite build wiring:
- `node:sqlite` removed from the externals list
- `better-sqlite3` added — must stay external because it has a
native binding (`require('./build/Release/better_sqlite3.node')`)
that Vite can't bundle. Vendoring the prebuilt `.node` into
`packages/runtime/native/` is a follow-up packaging task; the
workspace `pnpm install` already places the binding under
`node_modules` so dev + tests work today.
Bench results (RoadMap #5 baseline → after)
-------------------------------------------
@snowluma/bridge — recv pipeline (with SQLite identity writes):
group_member_join 17.5 μs/op → 4.7 μs/op (~3.7x faster)
group_message text 0.42→0.42 μs (no path change)
group_message mixed 0.67→0.67 μs (no path change)
@snowluma/onebot — send pipeline:
messageStore.storeMeta 17.0 μs/op → 10.9 μs/op (~1.6x)
messageStore.storeEvent 23.2 μs/op → 18.2 μs/op (~1.3x)
messageStore.findMeta hit 5.4 μs/op → 1.3 μs/op (~4x)
messageStore.findMeta miss 3.7 μs/op → 0.7 μs/op (~5x)
messageStore.findEvent 3.8 μs/op → 1.7 μs/op (~2.3x)
Read paths gained the most because they're parse-bound (small SQL
+ short execution → the parser was most of the cost). Writes gained
less because the fsync/journal overhead on each commit still
dominates the parse savings. Combined send hot path (storeMeta +
storeEvent, called on every outbound message + the /get_msg-fix
self-event store) drops from ~40 μs to ~29 μs — about a 27%
reduction per message sent.
Verification
------------
- pnpm -r typecheck: all 11 projects clean
- @snowluma/onebot test suite: 250/250
- @snowluma/core test suite: 302/302
- Combined: 552/552 (unchanged baseline)
- Vite build (with stubbed native binary): clean, 2.84 MB / 223 KB
gzip (matches pre-Phase-2 envelope after removing the better-
sqlite3 inline-bundle attempt — externalizing it shaves the
~30 KB regression we saw mid-flight)
Follow-up (next commits in this series)
---------------------------------------
- Skip rememberGroupMemberIdentity DB write when the (uid, uin,
nickname, card) tuple is unchanged in the in-memory cache.
- Drop the `Buffer.from(pkt.body)` allocation in msg-push context.
- Synchronous fast-path for elementsToJson when no async resolver
is wired.
- Vendor `better-sqlite3` prebuilt `.node` into the runtime/native
layout for the production package step.
This commit is contained in:
7 files changed
+440
-98
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import Database from 'better-sqlite3';
|
||||
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
@@ -109,7 +109,14 @@ export class IdentityService {
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
|
||||
// ─── Persistence + fetcher ───
|
||||
private readonly db: DatabaseSync | null;
|
||||
private readonly db: Database.Database | null;
|
||||
// Prepared-statement cache. Every `.prepare(sql)` call in this
|
||||
// service re-parses the SQL — that's the SQLite anti-pattern
|
||||
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
|
||||
// call sites stay readable (no need to enumerate 20+ named fields
|
||||
// upfront); the Map lookup is O(1) hash + string-eq, which is
|
||||
// negligible next to the SQL parse it replaces.
|
||||
private readonly stmtCache_ = new Map<string, Database.Statement>();
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
@@ -127,13 +134,23 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
this.loadSnapshot();
|
||||
}
|
||||
|
||||
/** Cached `prepare(sql)`. First call per unique SQL parses; later
|
||||
* calls reuse the same `Statement` object. See `stmtCache_`. */
|
||||
private pstmt(sql: string): Database.Statement {
|
||||
let cached = this.stmtCache_.get(sql);
|
||||
if (cached !== undefined) return cached;
|
||||
cached = this.db!.prepare(sql);
|
||||
this.stmtCache_.set(sql, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
static openForUin(uin: string, dataRoot = 'data'): IdentityService {
|
||||
return new IdentityService(uin, path.join(dataRoot, uin, 'snowluma_identity.db'));
|
||||
}
|
||||
@@ -238,7 +255,7 @@ export class IdentityService {
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
const row = this.pstmt(
|
||||
`SELECT uin FROM group_members
|
||||
WHERE group_id = ? AND uid = ? AND uin IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
@@ -248,7 +265,7 @@ export class IdentityService {
|
||||
if (uin !== null) return uin;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
const row = this.pstmt(
|
||||
'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uin: number | null } | undefined;
|
||||
return normalizeUin(row?.uin);
|
||||
@@ -267,7 +284,7 @@ export class IdentityService {
|
||||
|
||||
if (!this.db) return null;
|
||||
if (groupId !== undefined) {
|
||||
const row = this.db.prepare(
|
||||
const row = this.pstmt(
|
||||
`SELECT uid FROM group_members
|
||||
WHERE group_id = ? AND uin = ? AND uid IS NOT NULL
|
||||
ORDER BY active DESC, updated_at DESC
|
||||
@@ -277,7 +294,7 @@ export class IdentityService {
|
||||
if (uid) return uid;
|
||||
}
|
||||
|
||||
const row = this.db.prepare(
|
||||
const row = this.pstmt(
|
||||
'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1',
|
||||
).get(normalized) as { uid: string | null } | undefined;
|
||||
return normalizeUid(row?.uid) || null;
|
||||
@@ -289,7 +306,7 @@ export class IdentityService {
|
||||
this.friends_ = friends;
|
||||
for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin);
|
||||
this.runWrite('friends', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
|
||||
this.pstmt('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1')
|
||||
.run(nowSeconds());
|
||||
for (const friend of friends) {
|
||||
this.upsertUser({
|
||||
@@ -307,7 +324,7 @@ export class IdentityService {
|
||||
rememberGroups(groups: QQGroupInfo[]): void {
|
||||
this.setGroupsInMemory(groups);
|
||||
this.runWrite('groups', () => this.transaction(() => {
|
||||
this.db!.prepare('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
|
||||
this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1')
|
||||
.run(nowSeconds());
|
||||
for (const group of groups) {
|
||||
this.upsertGroup({
|
||||
@@ -327,7 +344,7 @@ export class IdentityService {
|
||||
for (const member of members) this.rememberUidUin(member.uid, member.uin);
|
||||
this.runWrite('group members', () => this.transaction(() => {
|
||||
this.upsertGroup({ groupId, memberCount: members.length });
|
||||
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
|
||||
this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?')
|
||||
.run(nowSeconds(), groupId);
|
||||
for (const member of members) {
|
||||
this.upsertGroupMember({
|
||||
@@ -432,7 +449,7 @@ export class IdentityService {
|
||||
const updatedAt = nowSeconds();
|
||||
this.transaction(() => {
|
||||
for (const row of rows) {
|
||||
this.db!.prepare('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
|
||||
this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE id = ?')
|
||||
.run(updatedAt, row.id);
|
||||
}
|
||||
});
|
||||
@@ -541,7 +558,7 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
private loadSnapshot(): void {
|
||||
const friendRows = this.db!.prepare(
|
||||
const friendRows = this.pstmt(
|
||||
`SELECT uid, uin, nickname, remark
|
||||
FROM users
|
||||
WHERE is_friend = 1 AND uin IS NOT NULL`,
|
||||
@@ -554,7 +571,7 @@ export class IdentityService {
|
||||
}));
|
||||
for (const friend of this.friends_) this.rememberUidUin(friend.uid, friend.uin);
|
||||
|
||||
const groups = this.db!.prepare(
|
||||
const groups = this.pstmt(
|
||||
`SELECT group_id, group_name, remark, member_count, member_max
|
||||
FROM groups
|
||||
WHERE active = 1`,
|
||||
@@ -579,7 +596,7 @@ export class IdentityService {
|
||||
private hydrateActiveMembersForGroups(groupIds: number[]): void {
|
||||
if (!this.db || groupIds.length === 0) return;
|
||||
|
||||
const select = this.db.prepare(
|
||||
const select = this.pstmt(
|
||||
`SELECT group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time
|
||||
FROM group_members
|
||||
@@ -626,9 +643,9 @@ export class IdentityService {
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.db.prepare('DELETE FROM users WHERE id = ?').run(duplicate.id);
|
||||
this.pstmt('DELETE FROM users WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`UPDATE users
|
||||
SET uid = ?, uin = ?, nickname = ?, remark = ?, is_friend = ?, source = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
@@ -645,7 +662,7 @@ export class IdentityService {
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`INSERT INTO users (uid, uin, nickname, remark, is_friend, source, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
@@ -662,7 +679,7 @@ export class IdentityService {
|
||||
private upsertGroup(input: GroupInput): void {
|
||||
if (!this.db || !Number.isInteger(input.groupId) || input.groupId <= 0) return;
|
||||
|
||||
const existing = this.db.prepare(
|
||||
const existing = this.pstmt(
|
||||
'SELECT group_name, remark, member_count, member_max FROM groups WHERE group_id = ?',
|
||||
).get(input.groupId) as {
|
||||
group_name: string;
|
||||
@@ -671,7 +688,7 @@ export class IdentityService {
|
||||
member_max: number;
|
||||
} | undefined;
|
||||
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`INSERT INTO groups (group_id, group_name, remark, member_count, member_max, active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?)
|
||||
ON CONFLICT(group_id) DO UPDATE SET
|
||||
@@ -725,9 +742,9 @@ export class IdentityService {
|
||||
|
||||
if (primary) {
|
||||
for (const duplicate of rows.slice(1)) {
|
||||
this.db.prepare('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
|
||||
this.pstmt('DELETE FROM group_members WHERE id = ?').run(duplicate.id);
|
||||
}
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`UPDATE group_members
|
||||
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
|
||||
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
|
||||
@@ -750,7 +767,7 @@ export class IdentityService {
|
||||
return;
|
||||
}
|
||||
|
||||
this.db.prepare(
|
||||
this.pstmt(
|
||||
`INSERT INTO group_members
|
||||
(group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active, updated_at)
|
||||
@@ -775,17 +792,17 @@ export class IdentityService {
|
||||
private findUserRows(uid: string, uin: number | null): UserRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? OR uin = ? ORDER BY id',
|
||||
).all(uid, uin) as unknown as UserRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uid = ? ORDER BY id',
|
||||
).all(uid) as unknown as UserRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
'SELECT id, uid, uin, nickname, remark, is_friend, source FROM users WHERE uin = ? ORDER BY id',
|
||||
).all(uin) as unknown as UserRow[];
|
||||
}
|
||||
@@ -795,7 +812,7 @@ export class IdentityService {
|
||||
private findMemberRows(groupId: number, uid: string, uin: number | null): MemberRow[] {
|
||||
if (!this.db) return [];
|
||||
if (uid && uin !== null) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
@@ -804,7 +821,7 @@ export class IdentityService {
|
||||
).all(groupId, uid, uin) as unknown as MemberRow[];
|
||||
}
|
||||
if (uid) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
@@ -813,7 +830,7 @@ export class IdentityService {
|
||||
).all(groupId, uid) as unknown as MemberRow[];
|
||||
}
|
||||
if (uin !== null) {
|
||||
return this.db.prepare(
|
||||
return this.pstmt(
|
||||
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
|
||||
join_time, last_sent_time, shut_up_time, active
|
||||
FROM group_members
|
||||
|
||||
Reference in new issue
Block a user