fix: 避免 Reader 有界空窗读取阻塞主线程

This commit is contained in:
hateyouing-ai committed 2026-11-10 15:27:06 +08:00
1 parent 804466aad8
commit 00b55c9cca
5 files changed
+442 -41

No files matched your search

+11 -3
View File
@@ -6,7 +6,7 @@ import {
isReady,
listContacts,
listContactsAsync,
listMessages,
listMessagesAsync,
getGroupSnapshot,
listRecentChat,
resolveMd5,
@@ -433,7 +433,7 @@ const routes: Record<string, RouteHandler> = {
sendJson(res, 200, { count: items.length, items })
}),
'/api/v1/chatlog': withMethods(['GET'], ({ res, url }) => {
'/api/v1/chatlog': withMethods(['GET'], async ({ res, url }) => {
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
const talker = url.searchParams.get('talker')
if (!talker) return sendError(res, 400, '缺少必要参数 talker')
@@ -462,7 +462,15 @@ const routes: Record<string, RouteHandler> = {
}
}
const messages = listMessages(resolved.md5, startTime, endTime)
// A quiet time window can fall back to a long native history scan. Use the
// asynchronous, time-filtered shard reader so it cannot block /health or the UI.
const messages = await listMessagesAsync(
resolved.md5,
startTime,
endTime,
undefined,
String(res.getHeader('X-Request-Id') || '')
)
sendJson(res, 200, {
contact: resolved,
query: { talker, time: timeParam, startTime, endTime },
+102 -34
View File
@@ -1457,7 +1457,14 @@ export class Wcdb4Client {
`[${requestId}] WCDB message source decision cursorSatisfiesLimit=${cursorSatisfiesLimit} tableScanExecuted=${tableScanExecuted} cursorRows=${cursorMessages.length} tableRows=${tableMessages.length}`
)
const mergeStartedAt = Date.now()
const messages = this.mergeMessageRows(cursorMessages, tableMessages, maxRows)
const recoveredMessages = this.recallJournalEnabled
? await this.readRecallJournalAsync(username, startTime, endTime)
: []
const messages = this.mergeMessageRows(
this.mergeMessageRows(cursorMessages, tableMessages),
recoveredMessages,
maxRows
)
wcdbDebugLog(
`[${requestId}] WCDB mergeMessageRows cost=${Date.now() - mergeStartedAt}ms finalRows=${messages.length}`
)
@@ -1906,14 +1913,14 @@ export class Wcdb4Client {
limit?: number,
requestId = 'NO-REQUEST'
): Promise<Wcdb4Message[]> {
if (!this.wcdbExecQuery) return []
if (!this.wcdbExecQuery) throw new Error('当前 WCDB 数据服务不支持消息分片查询')
const startedAt = Date.now()
wcdbDebugLog(`[${requestId}] WCDB table scan start username=${username}`)
let tables: Wcdb4MessageStore[] = []
try {
const statsStartedAt = Date.now()
tables = await this.listMessageStoresAsync(username)
tables = await this.listMessageStoresAsync(username, true)
wcdbDebugLog(
`[${requestId}] WCDB get_message_table_stats end stores=${tables.length} cost=${Date.now() - statsStartedAt}ms`
)
@@ -1935,34 +1942,39 @@ export class Wcdb4Client {
const order = limit ? 'DESC' : 'ASC'
const allRows: Record<string, unknown>[] = []
let successfulTables = 0
for (const table of tables) {
let offset = 0
try {
const sql = `${this.messageTableSelect(table)}${whereSql} ORDER BY "create_time" ${order} LIMIT ${rowLimit}`
const queryStartedAt = Date.now()
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
'message',
table.dbPath,
sql
)
wcdbDebugLog(
`[${requestId}] WCDB exec_query table=${table.tableName} db=${table.dbPath} rows=${Array.isArray(rows) ? rows.length : 0} cost=${Date.now() - queryStartedAt}ms`
)
successfulTables += 1
if (Array.isArray(rows)) allRows.push(...rows)
while (true) {
// An omitted limit means the complete range, not the first 5,000 rows.
// Stable ordering also keeps equal-timestamp messages across pages.
const sql = `${this.messageTableSelect(table)}${whereSql} ORDER BY "create_time" ${order}, "local_id" ${order} LIMIT ${rowLimit} OFFSET ${offset}`
const queryStartedAt = Date.now()
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
'message',
table.dbPath,
sql
)
if (!Array.isArray(rows)) throw new Error('消息分片返回格式无效')
wcdbDebugLog(
`[${requestId}] WCDB exec_query table=${table.tableName} db=${table.dbPath} rows=${rows.length} offset=${offset} cost=${Date.now() - queryStartedAt}ms`
)
allRows.push(...rows)
if (limit || rows.length < rowLimit) break
offset += rowLimit
}
} catch (error) {
console.warn(
`[WCDB4] async message table scan failed username=${username} db=${table.dbPath} table=${table.tableName}:`,
error
)
// A partial history must not look like a successful complete range: callers
// may persist a cursor after this request and permanently skip unread rows.
throw new Error('历史消息分片读取失败,请检查数据目录或微信数据版本')
}
}
if (tables.length > 0 && successfulTables === 0) {
throw new Error('历史消息分片均读取失败,请检查数据目录或微信数据版本')
}
const result = this.finalizeMessages(username, allRows, startTime, endTime, limit)
wcdbDebugLog(
`[${requestId}] WCDB table scan end rows=${result.length} cost=${Date.now() - startedAt}ms`
@@ -2144,7 +2156,10 @@ export class Wcdb4Client {
return stores.length > 0 ? stores : this.listFallbackMessageStores(username)
}
private async listMessageStoresAsync(username: string): Promise<Wcdb4MessageStore[]> {
private async listMessageStoresAsync(
username: string,
strict = false
): Promise<Wcdb4MessageStore[]> {
let stores: Wcdb4MessageStore[] = []
if (this.wcdbGetMessageTableStats) {
try {
@@ -2152,12 +2167,13 @@ export class Wcdb4Client {
this.wcdbGetMessageTableStats as unknown as KoffiAsyncFunction,
username
)
if (strict && !Array.isArray(rows)) throw new Error('消息分片目录返回格式无效')
stores = this.parseMessageStores(rows)
} catch (error) {
if (!username.startsWith('gh_')) throw error
}
}
return stores.length > 0 ? stores : this.listFallbackMessageStoresAsync(username)
return stores.length > 0 ? stores : this.listFallbackMessageStoresAsync(username, strict)
}
private parseMessageStores(rows: Record<string, unknown>[]): Wcdb4MessageStore[] {
@@ -2169,7 +2185,7 @@ export class Wcdb4Client {
.filter((row) => row.tableName && row.dbPath)
}
private getMessageDatabasePaths(username: string): string[] {
private getMessageDatabasePaths(username: string, strict = false): string[] {
// Native shard discovery can return no stores on Windows even when SQL reads work.
// Enumerate only canonical databases; sync-conflict copies are not message shards.
const messageRoot = path.join(this.dbStoragePath, 'message')
@@ -2182,7 +2198,8 @@ export class Wcdb4Client {
.filter((name) => pattern.test(name))
.sort()
.map((name) => path.join(messageRoot, name))
} catch {
} catch (error) {
if (strict) throw error
return []
}
}
@@ -2218,12 +2235,18 @@ export class Wcdb4Client {
return stores
}
private async listFallbackMessageStoresAsync(username: string): Promise<Wcdb4MessageStore[]> {
if (!this.wcdbExecQuery) return []
private async listFallbackMessageStoresAsync(
username: string,
strict = false
): Promise<Wcdb4MessageStore[]> {
if (!this.wcdbExecQuery) {
if (strict) throw new Error('当前 WCDB 数据服务不支持消息分片查询')
return []
}
const tableName = `Msg_${this.md5(username)}`
const escapedTableName = tableName.replace(/'/g, "''")
const stores: Wcdb4MessageStore[] = []
for (const dbPath of this.getMessageDatabasePaths(username)) {
for (const dbPath of this.getMessageDatabasePaths(username, strict)) {
try {
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
@@ -2231,6 +2254,7 @@ export class Wcdb4Client {
dbPath,
`SELECT name FROM sqlite_master WHERE type='table' AND (name='${escapedTableName}' OR name LIKE 'Name2Id%') ORDER BY name DESC`
)
if (strict && !Array.isArray(rows)) throw new Error('消息分片目录返回格式无效')
if (Array.isArray(rows) && rows.some((row) => row.name === tableName)) {
const senderTableName = rows.find((row) => /^Name2Id/i.test(String(row.name)))?.name
stores.push({
@@ -2239,7 +2263,8 @@ export class Wcdb4Client {
...(senderTableName ? { senderTableName: String(senderTableName) } : {})
})
}
} catch {
} catch (error) {
if (strict) throw error
// A shard may use a different key; continue checking the other databases.
}
}
@@ -2341,6 +2366,35 @@ export class Wcdb4Client {
return this.finalizeMessages(username, recoveredRows, startTime, endTime)
}
private async readRecallJournalAsync(
username: string,
startTime?: number,
endTime?: number
): Promise<Wcdb4Message[]> {
const recoveredRows: Record<string, unknown>[] = []
for (const store of await this.listMessageStoresAsync(username)) {
try {
const begin = this.normalizeTimestamp(startTime || 0)
const end = this.normalizeTimestamp(endTime || 0)
const where = [
`"_wxe_source_table" = '${store.tableName.replace(/'/g, "''")}'`,
begin > 0 ? `"create_time" >= ${begin}` : '',
end > 0 ? `"create_time" <= ${end}` : ''
].filter(Boolean)
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
'message',
store.dbPath,
`SELECT *, 1 AS "_wxe_recovered" FROM ${this.quoteSqlIdentifier(this.recallJournalTableName(store.tableName))} WHERE ${where.join(' AND ')} ORDER BY "create_time" ASC LIMIT 500`
)
if (Array.isArray(rows)) recoveredRows.push(...rows)
} catch {
// Like the sync path, the optional journal may not exist on every store.
}
}
return this.finalizeMessages(username, recoveredRows, startTime, endTime)
}
private mergeMessageRows(
current: Wcdb4Message[],
recovered: Wcdb4Message[],
@@ -2691,7 +2745,13 @@ export class Wcdb4Client {
limit?: number,
requestId = 'NO-REQUEST'
): Promise<Wcdb4Message[]> {
if (!this.wcdbOpenMessageCursor || !this.wcdbFetchMessageBatch) return []
if (
!this.wcdbOpenMessageCursor ||
!this.wcdbFetchMessageBatch ||
!this.wcdbCloseMessageCursor
) {
throw new Error('当前 WCDB 数据服务不支持消息游标')
}
const handle = this.ensureHandle()
const batchSize = limit ? Math.min(500, limit) : 1000
@@ -2716,7 +2776,9 @@ export class Wcdb4Client {
wcdbDebugLog(
`[${requestId}] WCDB open_message_cursor end code=${openResult} cursor=${cursorOut[0]} cost=${Date.now() - openStartedAt}ms`
)
if (openResult !== 0 || cursorOut[0] <= 0) return []
if (openResult !== 0 || cursorOut[0] <= 0) {
throw new Error(`无法打开消息游标:${openResult}`)
}
const cursor = cursorOut[0]
const allRows: Record<string, unknown>[] = []
@@ -2739,13 +2801,15 @@ export class Wcdb4Client {
wcdbDebugLog(
`[${requestId}] WCDB fetch_message_batch #${fetchIndex} code=${fetchResult} nativeCost=${fetchNativeCost}ms output=${Boolean(outJson[0])}`
)
break
if (outJson[0]) this.wcdbFreeString?.(outJson[0])
throw new Error(`消息游标读取失败:${fetchResult}`)
}
try {
const decodeStartedAt = Date.now()
const json = this.koffi!.decode(outJson[0], 'char', -1)
const batch = JSON.parse(json) as Record<string, unknown>[]
if (Array.isArray(batch)) allRows.push(...batch)
if (!Array.isArray(batch)) throw new Error('消息游标返回格式无效')
allRows.push(...batch)
wcdbDebugLog(
`[${requestId}] WCDB fetch_message_batch #${fetchIndex} code=${fetchResult} nativeCost=${fetchNativeCost}ms jsonCost=${Date.now() - decodeStartedAt}ms batchRows=${Array.isArray(batch) ? batch.length : 0} hasMore=${outHasMore[0]}`
)
@@ -2757,7 +2821,11 @@ export class Wcdb4Client {
} finally {
const closeStartedAt = Date.now()
try {
this.wcdbCloseMessageCursor?.(handle, cursor)
await this.callAsyncCode(
this.wcdbCloseMessageCursor as unknown as KoffiAsyncFunction,
handle,
cursor
)
} catch {
// Best-effort cursor cleanup.
}
+71 -3
View File
@@ -27,6 +27,8 @@ const fixture = vi.hoisted(() => ({
}
}
],
readMessages: vi.fn(),
syncReadMessages: vi.fn(),
testSend: vi.fn(async () => ({ success: true, status: 'sent' }))
}))
@@ -52,7 +54,8 @@ vi.mock('../../src/main/services/chat-service', () => ({
isReady: () => true,
listContacts: () => fixture.contacts,
listContactsAsync: async () => fixture.contacts,
listMessages: () => fixture.chatlogMessages,
listMessages: fixture.syncReadMessages,
listMessagesAsync: fixture.readMessages,
getGroupSnapshot: () => ({ members: [] }),
listRecentChat: () => [],
resolveMd5: () => fixture.contacts[0]
@@ -120,6 +123,8 @@ describe('Local API authentication', () => {
beforeEach(() => {
fixture.storageAvailable = true
fixture.readMessages.mockReset().mockImplementation(async () => fixture.chatlogMessages)
fixture.syncReadMessages.mockReset().mockImplementation(() => fixture.chatlogMessages)
})
afterEach(async () => {
@@ -135,7 +140,11 @@ describe('Local API authentication', () => {
const health = await fetch(`${baseUrl(handle)}/api/v1/health`)
expect(health.status).toBe(200)
const healthBody = await health.json()
expect(healthBody).toMatchObject({ ok: true, service: 'TraceMemo Reader', version: 'test-version' })
expect(healthBody).toMatchObject({
ok: true,
service: 'TraceMemo Reader',
version: 'test-version'
})
expect(JSON.stringify(healthBody)).not.toMatch(
/token|authorization|wxid|databasePath|provider/i
)
@@ -256,7 +265,10 @@ describe('Local API authentication', () => {
expect((await fetch(path)).status).toBe(401)
const response = await fetch(path, { headers: { Authorization: `Bearer ${VALID_TOKEN}` } })
expect(response.status).toBe(200)
await expect(response.json()).resolves.toMatchObject({ version: 1, tools: { query_messages: { limitMax: 200 } } })
await expect(response.json()).resolves.toMatchObject({
version: 1,
tools: { query_messages: { limitMax: 200 } }
})
})
it.each([
@@ -322,6 +334,62 @@ describe('Local API authentication', () => {
expect(provider).toHaveBeenCalledOnce()
})
it('keeps health responsive while an authenticated chatlog read is pending', async () => {
const handle = await startFixtureServer()
let finishRead!: (messages: typeof fixture.chatlogMessages) => void
let markStarted!: () => void
const started = new Promise<void>((resolve) => {
markStarted = resolve
})
fixture.readMessages.mockImplementationOnce(
() =>
new Promise((resolve) => {
finishRead = resolve
markStarted()
})
)
const pending = fetch(
`${baseUrl(handle)}/api/v1/chatlog?talker=fixture&time=2026-11-10/07:51~2026-11-10/07:56`,
{
headers: {
Authorization: `Bearer ${VALID_TOKEN}`,
'X-Request-Id': 'fixture-reader-pending'
}
}
)
await started
try {
const health = await fetch(`${baseUrl(handle)}/api/v1/health`, {
signal: AbortSignal.timeout(2000)
})
expect(health.status).toBe(200)
expect(fixture.syncReadMessages).not.toHaveBeenCalled()
expect(fixture.readMessages).toHaveBeenCalledWith(
'fixture-md5',
expect.any(Number),
expect.any(Number),
undefined,
'fixture-reader-pending'
)
} finally {
finishRead([])
const response = await pending
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ count: 0, messages: [] })
}
})
it('returns a failed chatlog read as an error instead of an empty success', async () => {
const handle = await startFixtureServer()
fixture.readMessages.mockRejectedValueOnce(new Error('fixture-shard-read-failed'))
const response = await fetch(`${baseUrl(handle)}/api/v1/chatlog?talker=fixture`, {
headers: { Authorization: `Bearer ${VALID_TOKEN}` }
})
expect(response.status).toBe(500)
expect(await response.json()).not.toHaveProperty('messages')
expect(fixture.syncReadMessages).not.toHaveBeenCalled()
})
it('adds media metadata to chatlog while redacting image keys', async () => {
const handle = await startFixtureServer()
const response = await fetch(`${baseUrl(handle)}/api/v1/chatlog?talker=测试联系人`, {
+5 -1
View File
@@ -124,7 +124,11 @@ describe('WCDB message shard pagination', () => {
expect(sql).toContain('n.user_name AS sender_username')
expect(sql).toContain('n.rowid = m.real_sender_id')
expect(sql).toContain('"create_time" <= 1800000000')
expect(sql).toContain('ORDER BY "create_time" DESC LIMIT 20')
// Sync queries keep their established ordering; async pagination adds a
// stable local-id tie break and an explicit first-page offset.
expect(sql).toMatch(
/ORDER BY "create_time" DESC(?:, "local_id" DESC)? LIMIT 20(?: OFFSET 0)?/
)
const isLatestShard = dbPath.endsWith('message_7.db')
return [
{
+253
View File
@@ -0,0 +1,253 @@
import { describe, expect, it, vi, type Mock } from 'vitest'
import { Wcdb4Client, type Wcdb4Message } from '../../src/main/wcdb4-client'
const message = (id: number): Wcdb4Message => ({
mesLocalID: String(id),
serverId: `server-${id}`,
mesDes: 0,
messageType: '1',
msgCreateTime: '150',
msgContent: `fixture-${id}`,
raw: {}
})
function makeClient(overrides: Record<string, unknown> = {}): Wcdb4Client {
return Object.assign(Object.create(Wcdb4Client.prototype), {
wcdbGetMessageTableStats: vi.fn(),
wcdbExecQuery: vi.fn(),
wcdbGetMessages: vi.fn(() => {
throw new Error('unbounded native fallback must not run')
}),
getMessagesByCursorAsync: vi.fn(async () => []),
listMessageStoresAsync: vi.fn(async () => [
{ tableName: 'Msg_fixture', dbPath: 'message_0.db' }
]),
// Native SQL returns normalized synthetic rows here. No real WeChat database is used.
finalizeMessages: vi.fn((_user: string, rows: Wcdb4Message[]) => rows),
...overrides
}) as Wcdb4Client
}
function makeCursorClient(fetch: { code: number; json?: string; hasMore?: number }[]): {
client: Wcdb4Client
read: () => Promise<Wcdb4Message[]>
call: Mock<(fn: unknown, ...args: unknown[]) => Promise<number>>
close: Mock
free: Mock
} {
const open = vi.fn()
const batch = vi.fn()
const close = vi.fn()
const free = vi.fn()
const call = vi.fn(async (fn: unknown, ...args: unknown[]) => {
if (fn === open) {
;(args[6] as [number])[0] = 123
return 0
}
if (fn === batch) {
const next = fetch.shift()!
;(args[2] as [unknown])[0] = next.json === undefined ? null : { json: next.json }
;(args[3] as [number])[0] = next.hasMore || 0
return next.code
}
return 0
})
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
wcdbOpenMessageCursor: open,
wcdbFetchMessageBatch: batch,
wcdbCloseMessageCursor: close,
wcdbFreeString: free,
ensureHandle: () => 1,
callAsyncCode: call,
koffi: { decode: (pointer: { json: string }) => pointer.json },
finalizeMessages: vi.fn((_user: string, rows: Wcdb4Message[]) => rows)
}) as Wcdb4Client
const read = (): Promise<Wcdb4Message[]> =>
Reflect.get(client, 'getMessagesByCursorAsync').call(client, 'fixture', 100, 200)
return { client, read, call, close, free }
}
describe('bounded Reader message reads', () => {
it('accepts an authoritative empty shard query without a full-conversation fallback', async () => {
const query = vi.fn<
(fn: unknown, kind: string, db: string, sql: string) => Promise<Wcdb4Message[]>
>(async () => [])
const client = makeClient({ callJsonAsync: query })
await expect(client.getMessagesAsync('fixture', 100, 200)).resolves.toEqual([])
expect(query).toHaveBeenCalledOnce()
expect(query.mock.calls[0][3]).toContain('"create_time" >= 100 AND "create_time" <= 200')
expect(Reflect.get(client, 'wcdbGetMessages')).not.toHaveBeenCalled()
})
it('reads more than 5,000 rows per shard when no limit was requested', async () => {
const first = Array.from({ length: 5000 }, (_, id) => message(id + 1))
const query = vi
.fn()
.mockResolvedValueOnce(first)
.mockResolvedValueOnce([message(5001)])
const client = makeClient({ callJsonAsync: query })
const result = await client.getMessagesAsync('fixture', 100, 200)
expect(result).toHaveLength(5001)
expect(result.at(-1)?.mesLocalID).toBe('5001')
expect(query.mock.calls[0][3]).toContain(
'ORDER BY "create_time" ASC, "local_id" ASC LIMIT 5000 OFFSET 0'
)
expect(query.mock.calls[1][3]).toContain('LIMIT 5000 OFFSET 5000')
expect(Reflect.get(client, 'wcdbGetMessages')).not.toHaveBeenCalled()
})
it('merges every matching historical store when the native cursor is empty', async () => {
const query = vi
.fn()
.mockResolvedValueOnce([message(1)])
.mockResolvedValueOnce([message(2)])
const client = makeClient({
callJsonAsync: query,
listMessageStoresAsync: vi.fn(async () => [
{ tableName: 'Msg_fixture', dbPath: 'message_0.db' },
{ tableName: 'Msg_fixture', dbPath: 'message_1.db' }
])
})
await expect(client.getMessagesAsync('fixture', 100, 200)).resolves.toHaveLength(2)
})
it('does not publish a partial range when a later shard fails', async () => {
const client = makeClient({
listMessageStoresAsync: vi.fn(async () => [
{ tableName: 'Msg_fixture', dbPath: 'message_0.db' },
{ tableName: 'Msg_fixture', dbPath: 'message_1.db' }
]),
callJsonAsync: vi
.fn()
.mockResolvedValueOnce([message(1)])
.mockRejectedValueOnce(new Error('locked'))
})
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow(
'历史消息分片读取失败'
)
})
it('rejects the complete range if a later SQL page fails', async () => {
const client = makeClient({
callJsonAsync: vi
.fn()
.mockResolvedValueOnce(Array.from({ length: 5000 }, (_, id) => message(id + 1)))
.mockRejectedValueOnce(new Error('second page unavailable'))
})
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow(
'历史消息分片读取失败'
)
})
it('fails closed when canonical shard discovery fails, but permits a missing conversation table', async () => {
const client = makeClient({
getMessageDatabasePaths: vi.fn(() => ['message_0.db']),
callJsonAsync: vi.fn(async () => {
throw new Error('cannot read sqlite_master')
})
})
const discover = Reflect.get(client, 'listFallbackMessageStoresAsync')
await expect(discover.call(client, 'fixture', true)).rejects.toThrow(
'cannot read sqlite_master'
)
// Non-Reader consumers retain their existing tolerant discovery contract.
await expect(discover.call(client, 'fixture')).resolves.toEqual([])
Reflect.set(
client,
'callJsonAsync',
vi.fn(async () => [])
)
await expect(discover.call(client, 'fixture', true)).resolves.toEqual([])
})
it('enables strict shard discovery for a complete Reader range', async () => {
const discover = vi.fn(async () => {
throw new Error('discovery failed')
})
const client = makeClient({ listMessageStoresAsync: discover })
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow(
'无法读取历史消息分片信息'
)
expect(discover).toHaveBeenCalledWith('fixture', true)
})
it('does not treat an unsupported or failed SQL read as a successful empty range', async () => {
const client = makeClient({
callJsonAsync: vi.fn(async () => {
throw new Error('native failure')
})
})
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow()
Reflect.set(client, 'wcdbExecQuery', undefined)
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow(
'无法检查历史消息分片'
)
})
it('keeps an explicit newest-message limit instead of paging an unlimited range', async () => {
const query = vi.fn<
(fn: unknown, kind: string, db: string, sql: string) => Promise<Wcdb4Message[]>
>(async () => [message(2)])
const client = makeClient({ callJsonAsync: query })
await expect(client.getMessagesAsync('fixture', 100, 200, { limit: 1 })).resolves.toHaveLength(
1
)
expect(query).toHaveBeenCalledOnce()
expect(query.mock.calls[0][3]).toContain('DESC LIMIT 1 OFFSET 0')
})
it.each([false, true])(
'keeps recall journal opt-in=%s on the async Reader path',
async (enabled) => {
const recovered = { ...message(2), raw: { _wxe_recovered: 1 } }
const journal = vi.fn(async () => [recovered])
const client = makeClient({
recallJournalEnabled: enabled,
callJsonAsync: vi.fn(async () => [message(1)]),
readRecallJournalAsync: journal
})
const result = await client.getMessagesAsync('fixture', 100, 200)
expect(result).toHaveLength(enabled ? 2 : 1)
expect(journal).toHaveBeenCalledTimes(enabled ? 1 : 0)
}
)
it('uses async SQL to read the optional journal with the original time bounds', async () => {
const query = vi.fn(async () => [{ ...message(2), raw: { _wxe_recovered: 1 } }])
const client = makeClient({ callJsonAsync: query })
const rows = await Reflect.get(client, 'readRecallJournalAsync').call(
client,
'fixture',
100,
200
)
expect(rows).toHaveLength(1)
const sql = (query.mock.calls as unknown[][])[0][3]
expect(sql).toContain(`"_wxe_source_table" = 'Msg_fixture'`)
expect(sql).toContain('"create_time" >= 100 AND "create_time" <= 200')
expect(sql).toContain('LIMIT 500')
})
it('distinguishes a completed empty cursor batch from a failed native fetch', async () => {
const valid = makeCursorClient([{ code: 0, json: '[]' }])
await expect(valid.read()).resolves.toEqual([])
expect(valid.free).toHaveBeenCalledOnce()
expect(valid.call).toHaveBeenLastCalledWith(valid.close, 1, 123)
const invalid = makeCursorClient([{ code: 5, json: '[]' }])
await expect(invalid.read()).rejects.toThrow('消息游标读取失败')
expect(invalid.free).toHaveBeenCalledOnce()
expect(invalid.call).toHaveBeenLastCalledWith(invalid.close, 1, 123)
})
it('closes the cursor and releases native output when JSON decoding fails', async () => {
const broken = makeCursorClient([{ code: 0, json: '{' }])
await expect(broken.read()).rejects.toThrow()
expect(broken.free).toHaveBeenCalledOnce()
expect(broken.call).toHaveBeenLastCalledWith(broken.close, 1, 123)
})
})