fix(onebot): preserve historical media independently of cache limits

Preserve message history and the media information needed for reliable
forwarding. Retain available older data during upgrades and report storage
failures explicitly.

Fixes #462
This commit is contained in:
DrSmoothl committed 2026-10-04 14:00:30 +08:00
1 parent d86e0fc7b5
commit 99bcfca15c
17 files changed
+659 -230

No files matched your search

@@ -4,6 +4,7 @@ import type { ToSegmentContext } from './element-codecs';
import { getElementCodec } from './element-codecs';
import { createLogger } from '@snowluma/common/logger';
import type { ConverterContext } from './index';
import { attachMessageMedia } from '../message-media';
const log = createLogger('OneBot');
@@ -32,16 +33,24 @@ export async function elementsToOneBotSegments(
const segmentCtx = toSegmentContext(ctx, isGroup, sessionId);
const result: JsonArray = [];
for (const element of elements) {
let segment: JsonObject;
// One malformed element shouldn't drop the whole message — skip it (with a
// breadcrumb) and keep converting the rest.
try {
result.push(await elementToSegment(element, segmentCtx));
if (element.type === 'markdown' && element.text) {
result.push({ type: 'text', data: { text: element.text } });
}
segment = await elementToSegment(element, { ...segmentCtx, mediaSegmentSink: null });
} catch (err) {
log.warn('segment convert skipped type=%s (%s)', element.type,
err instanceof Error ? err.message : String(err));
continue;
}
// Persistence failures must propagate, not masquerade as bad wire elements.
attachMessageMedia(segment, element);
if (element.type === 'image' || element.type === 'record' || element.type === 'video') {
ctx.mediaSegmentSink?.(element.type, element, segment.data as JsonObject, isGroup, sessionId);
}
result.push(segment);
if (element.type === 'markdown' && element.text) {
result.push({ type: 'text', data: { text: element.text } });
}
}
return result;
+1 -1
View File
@@ -132,7 +132,7 @@ export class OneBotInstance {
: moduleLog;
this.rkeyCache = new RKeyCache(globalSettings.rkey);
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
this.mediaStore = new MediaStore(path.join('data', this.uin, 'messages.db'));
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db'));
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
@@ -0,0 +1,82 @@
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { createLogger } from '@snowluma/common/logger';
import { openSqliteDb } from './sqlite-open';
import { foldMediaKey, MediaStore, rollbackMediaTransaction, serializeMediaInfo } from './media-store';
const log = createLogger('OneBot.MediaMigration');
const BATCH_SIZE = 200;
/** Runs in the existing database worker, before the account is marked ready.
* Copy only: leave the old database (including its WAL) intact for recovery.
* Each committed batch advances its cursor in the destination transaction.
*/
export async function migrateLegacyMedia(
messageDbPath: string,
cancelled: () => boolean = () => false,
): Promise<void> {
const store = new MediaStore(messageDbPath);
store.close();
const destination = openSqliteDb(messageDbPath);
let source: DatabaseSync | undefined;
try {
destination.exec(`CREATE TABLE IF NOT EXISTS media_migration_state (
id INTEGER PRIMARY KEY CHECK (id = 1), phase TEXT NOT NULL, cursor INTEGER NOT NULL
); INSERT OR IGNORE INTO media_migration_state VALUES (1, 'entries', 0)`);
const state = destination.prepare('SELECT phase, cursor FROM media_migration_state WHERE id = 1')
.get() as { phase: string; cursor: number };
if (state.phase === 'complete') return;
const sourcePath = path.join(path.dirname(messageDbPath), 'media.db');
if (!fs.existsSync(sourcePath)) {
destination.exec("UPDATE media_migration_state SET phase = 'complete' WHERE id = 1");
return;
}
source = new DatabaseSync(sourcePath, { readOnly: true });
log.info('preserving legacy media metadata: migration started');
const insertEntry = destination.prepare(`INSERT INTO legacy_media_entries (type, primary_key, data, last_seen)
VALUES (?, ?, ?, ?) ON CONFLICT(type, primary_key) DO NOTHING`);
const insertKey = destination.prepare(`INSERT INTO legacy_media_keys (type, key, primary_key)
VALUES (?, ?, ?) ON CONFLICT(type, key) DO NOTHING`);
const saveState = destination.prepare('UPDATE media_migration_state SET phase = ?, cursor = ? WHERE id = 1');
while (!cancelled() && state.phase !== 'complete') {
const table = state.phase === 'entries' ? 'media_entries' : 'media_keys';
const rows = source.prepare(`SELECT rowid AS migration_rowid, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT ?`)
.all(state.cursor, BATCH_SIZE) as Array<{
migration_rowid: number; type: string; primary_key: string; data: string; last_seen: number; key: string;
}>;
const nextPhase = rows.length === 0 ? (state.phase === 'entries' ? 'keys' : 'complete') : state.phase;
const nextCursor = rows.at(-1)?.migration_rowid ?? 0;
destination.exec('BEGIN IMMEDIATE');
try {
for (const row of rows) {
if (!['image', 'record', 'video'].includes(row.type)) {
throw new Error(`unsupported legacy media type at row ${row.migration_rowid}`);
}
if (state.phase === 'entries') {
const info: unknown = JSON.parse(row.data);
if (!info || typeof info !== 'object' || Array.isArray(info)) {
throw new Error(`invalid legacy media metadata at row ${row.migration_rowid}`);
}
insertEntry.run(row.type, foldMediaKey(row.primary_key), serializeMediaInfo(info), row.last_seen);
} else {
insertKey.run(row.type, foldMediaKey(row.key), foldMediaKey(row.primary_key));
}
}
saveState.run(nextPhase, nextCursor);
destination.exec('COMMIT');
} catch (error) {
rollbackMediaTransaction(destination, error);
}
state.phase = nextPhase;
state.cursor = nextCursor;
log.debug('preserving legacy media metadata: phase=%s cursor=%d', state.phase, state.cursor);
// Yield between committed batches so cancellation is handled by the worker.
await new Promise<void>(resolve => setTimeout(resolve, 0));
}
if (!cancelled()) log.info('preserving legacy media metadata: migration complete; source retained');
} finally {
source?.close();
destination.close();
}
}
+118 -194
View File
@@ -60,239 +60,171 @@ const TYPE_IMAGE = 'image';
const TYPE_RECORD = 'record';
const TYPE_VIDEO = 'video';
const DEFAULT_KEEP_ENTRIES = 4096;
export type MediaLookupSource = 'current' | 'legacy';
/** SQLite keys / aliases longer than this are folded to a short digest. */
export const MEDIA_KEY_MAX_CHARS = 2048;
/** Persisted JSON must stay well under a page-overflow storm. */
export const MEDIA_DATA_MAX_CHARS = 64 * 1024;
const INLINE_MEDIA_SOURCE = /^(base64:\/\/|data:)/i;
/** Durable media metadata. Production shares messages.db with MessageStore.
* Only the in-memory lookup cache is bounded; history dependencies never expire.
*/
export class MediaStore {
private readonly db: DatabaseSync;
private readonly maxEntriesPerType: number;
// Prepared statements (pay the parsing cost once at startup).
private readonly cache = new Map<string, string>();
private readonly upsertEntry: StatementSync;
private readonly upsertKey: StatementSync;
private readonly findEntryByKey: StatementSync;
private readonly findEntryByPrimary: StatementSync;
private readonly evictByType: StatementSync;
private readonly purgeOrphanKeys: StatementSync;
private readonly countByType: StatementSync;
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
private readonly findEntry: StatementSync;
private readonly findLegacyEntry: StatementSync;
constructor(dbPath: string, private readonly maxCachedEntries = DEFAULT_KEEP_ENTRIES) {
this.db = openSqliteDb(dbPath);
this.initSchema();
this.purgeOversizedRows();
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.findEntryByKey = this.db.prepare(
`SELECT e.data FROM media_entries e
JOIN media_keys k ON k.type = e.type AND k.primary_key = e.primary_key
WHERE k.type = ? AND k.key = ?
LIMIT 1`,
);
this.findEntryByPrimary = this.db.prepare(
`SELECT data FROM media_entries WHERE type = ? AND primary_key = ?`,
);
this.evictByType = this.db.prepare(
// `rowid DESC` makes the tiebreaker match insertion order (newest first)
// so reproducible inserts within the same `last_seen` second still get
// the most recent rows retained, regardless of how the lexicographic
// sort would have ordered the synthetic primary_key.
`DELETE FROM media_entries WHERE type = ? AND rowid IN (
SELECT rowid FROM media_entries
WHERE type = ?
ORDER BY last_seen DESC, rowid DESC
LIMIT -1 OFFSET ?
)`,
);
this.purgeOrphanKeys = this.db.prepare(
`DELETE FROM media_keys WHERE type = ? AND primary_key NOT IN (
SELECT primary_key FROM media_entries WHERE type = ?
)`,
);
this.countByType = this.db.prepare(
`SELECT COUNT(*) AS n FROM media_entries WHERE type = ?`,
);
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.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 = ?), ?
)
`);
}
close(): void {
this.db.close();
}
close(): void { this.cache.clear(); this.db.close(); }
rememberImage(info: CachedImage): void {
const primaryKey = pickPrimary([info.file, info.fileName]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_IMAGE, primaryKey, info, [info.file, info.fileName, info.url]);
this.remember(TYPE_IMAGE, info, [info.file, info.fileName, info.url]);
}
rememberRecord(info: CachedRecord): void {
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_RECORD, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
this.remember(TYPE_RECORD, info, [info.file, info.fileName, info.fileId, info.url]);
}
rememberVideo(info: CachedVideo): void {
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_VIDEO, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
this.remember(TYPE_VIDEO, info, [info.file, info.fileName, info.fileId, info.url]);
}
findImage(key: string): CachedImage | null {
return this.findByAnyKey<CachedImage>(TYPE_IMAGE, key);
findImage(key: string, source: MediaLookupSource = 'current'): CachedImage | null {
return this.find(TYPE_IMAGE, key, source);
}
findRecord(key: string, source: MediaLookupSource = 'current'): CachedRecord | null {
return this.find(TYPE_RECORD, key, source);
}
findVideo(key: string, source: MediaLookupSource = 'current'): CachedVideo | null {
return this.find(TYPE_VIDEO, key, source);
}
findRecord(key: string): CachedRecord | null {
return this.findByAnyKey<CachedRecord>(TYPE_RECORD, key);
}
updateImageUrl(key: string, url: string): void { this.updateUrl(TYPE_IMAGE, key, url); }
updateRecordUrl(key: string, url: string): void { this.updateUrl(TYPE_RECORD, key, url); }
updateVideoUrl(key: string, url: string): void { this.updateUrl(TYPE_VIDEO, key, url); }
findVideo(key: string): CachedVideo | null {
return this.findByAnyKey<CachedVideo>(TYPE_VIDEO, key);
}
updateImageUrl(key: string, url: string): void {
if (!url || mustFoldMediaKey(url)) return;
const cached = this.findImage(key);
if (!cached || cached.url === url) return;
this.rememberImage({ ...cached, url });
}
updateRecordUrl(key: string, url: string): void {
if (!url || mustFoldMediaKey(url)) return;
const cached = this.findRecord(key);
if (!cached || cached.url === url) return;
this.rememberRecord({ ...cached, url });
}
updateVideoUrl(key: string, url: string): void {
if (!url || mustFoldMediaKey(url)) return;
const cached = this.findVideo(key);
if (!cached || cached.url === url) return;
this.rememberVideo({ ...cached, url });
}
/** Snapshot count of distinct entries per type; mostly used by tests. */
/** Counts durable records, not the bounded lookup cache. */
size(): { images: number; records: number; videos: number } {
const img = this.countByType.get(TYPE_IMAGE) as { n: number } | undefined;
const rec = this.countByType.get(TYPE_RECORD) as { n: number } | undefined;
const vid = this.countByType.get(TYPE_VIDEO) as { n: number } | undefined;
return { images: img?.n ?? 0, records: rec?.n ?? 0, videos: vid?.n ?? 0 };
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) };
}
// --- internals ---
private initSchema(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS 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 INDEX IF NOT EXISTS idx_media_entries_lastseen
ON media_entries(type, last_seen DESC);
CREATE TABLE IF NOT EXISTS media_keys (
type TEXT NOT NULL,
key TEXT NOT NULL,
primary_key TEXT NOT NULL,
PRIMARY KEY (type, key)
);
CREATE INDEX IF NOT EXISTS idx_media_keys_primary
ON media_keys(type, primary_key);
`);
}
private purgeOversizedRows(): void {
// Older builds could persist a whole inline payload as the key / JSON.
// Drop those rows on open so later eviction does not walk overflow pages.
this.db.exec(`
DELETE FROM media_keys
WHERE length(key) > ${MEDIA_KEY_MAX_CHARS}
OR length(primary_key) > ${MEDIA_KEY_MAX_CHARS};
DELETE FROM media_entries
WHERE length(primary_key) > ${MEDIA_KEY_MAX_CHARS}
OR length(data) > ${MEDIA_DATA_MAX_CHARS};
DELETE FROM media_keys
WHERE primary_key NOT IN (SELECT primary_key FROM media_entries);
`);
}
private upsertWithAliases<T extends object>(
type: string,
primaryKey: string,
info: T,
aliases: (string | undefined)[],
): void {
const data = JSON.stringify(persistableMediaInfo(info));
if (data.length > MEDIA_DATA_MAX_CHARS) return;
const lastSeen = Math.floor(Date.now() / 1000);
// Run the writes in a transaction so concurrent readers always see a
// consistent (entry, keys) pair.
this.db.exec('BEGIN');
private remember(type: string, info: object, aliases: string[]): void {
const primary = pickPrimary(aliases);
if (!primary) throw new Error(`cannot store ${type} metadata without an identifier`);
const data = serializeMediaInfo(info);
this.db.exec('BEGIN IMMEDIATE');
try {
this.upsertEntry.run(type, primaryKey, data, lastSeen);
const seen = new Set<string>();
for (const raw of aliases) {
if (!raw) continue;
const key = foldMediaKey(raw);
if (!key || seen.has(key)) continue;
seen.add(key);
this.upsertKey.run(type, key, primaryKey);
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);
}
this.db.exec('COMMIT');
} catch (err) {
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
throw err;
} catch (error) {
rollbackMediaTransaction(this.db, error);
}
// Eager eviction. Skip the DELETE entirely while we are under the cap.
this.evictOldEntries(type);
// Alias remapping can invalidate any cached lookup. JSON strings ensure
// callers cannot mutate the durable record through a returned object.
this.cache.clear();
}
private findByAnyKey<T>(type: string, key: string): T | null {
private find<T>(type: string, key: string, source: MediaLookupSource = 'current'): T | null {
const lookup = foldMediaKey(key);
if (!lookup) return null;
const row = this.findEntryByKey.get(type, lookup) as { data: string } | undefined;
if (row?.data) return safeParse<T>(row.data);
// Fall back to looking up by primary_key directly so callers that pass
// the canonical identifier still hit (e.g. when the alias index is yet
// to be built for that key in this session).
const fallback = this.findEntryByPrimary.get(type, lookup) as { data: string } | undefined;
return fallback?.data ? safeParse<T>(fallback.data) : null;
const cacheKey = `${source}:${type}:${lookup}`;
let data = this.cache.get(cacheKey);
if (data === undefined) {
// Legacy history has no per-message snapshots. Its frozen migration
// index must never resolve through a later, mutable filename alias.
const current = source === 'current' ? this.findEntry.get(type, type, lookup, lookup) : undefined;
const row = (current ?? this.findLegacyEntry.get(type, type, lookup, lookup)) as { data: string } | undefined;
if (!row) return null;
data = row.data;
}
// Parse before caching: malformed persisted metadata is an observable error.
const result: unknown = JSON.parse(data);
if (!result || typeof result !== 'object' || Array.isArray(result)) {
throw new Error(`invalid persisted ${type} metadata`);
}
this.cache.delete(cacheKey);
this.cache.set(cacheKey, data);
while (this.cache.size > Math.max(0, this.maxCachedEntries)) {
this.cache.delete(this.cache.keys().next().value!);
}
return result as T;
}
private evictOldEntries(type: string): void {
try {
const row = this.countByType.get(type) as { n: number } | undefined;
if ((row?.n ?? 0) <= this.maxEntriesPerType) return;
this.evictByType.run(type, type, this.maxEntriesPerType);
this.purgeOrphanKeys.run(type, type);
} catch {
// Best-effort eviction; don't propagate.
}
private updateUrl(type: string, key: string, url: string): void {
if (!url || mustFoldMediaKey(url)) return;
const info = this.find<Record<string, unknown>>(type, key);
if (!info || info.url === url) return;
this.remember(type, { ...info, url }, [info.file, info.fileName, info.fileId, url]
.filter((value): value is string => typeof value === 'string'));
}
}
export function serializeMediaInfo(info: object): string {
const data = JSON.stringify(persistableMediaInfo(info));
if (data.length > MEDIA_DATA_MAX_CHARS) {
throw new Error(`media metadata exceeds storage limit (${data.length} characters)`);
}
return data;
}
export function rollbackMediaTransaction(db: DatabaseSync, error: unknown): never {
try { db.exec('ROLLBACK'); }
catch (rollbackError) {
throw new AggregateError([error, rollbackError], 'media write and rollback failed', { cause: error });
}
throw error;
}
function mustFoldMediaKey(value: string): boolean {
return value.length > MEDIA_KEY_MAX_CHARS || INLINE_MEDIA_SOURCE.test(value);
}
function foldMediaKey(value: string): string {
export function foldMediaKey(value: string): string {
if (!value) return '';
if (!mustFoldMediaKey(value)) return value;
return `inline:${createHash('sha256').update(value).digest('hex')}`;
@@ -317,11 +249,3 @@ function pickPrimary(candidates: (string | undefined)[]): string {
}
return '';
}
function safeParse<T>(json: string): T | null {
try {
return JSON.parse(json) as T;
} catch {
return null;
}
}
+95
View File
@@ -0,0 +1,95 @@
import type { MessageElement } from '@snowluma/protocol/events';
import { serializeMediaInfo } from './media-store';
import type { JsonObject } from './types';
export type MessageMedia = Extract<MessageElement, { type: 'image' | 'record' | 'video' }>;
const mediaSnapshot = Symbol('message media snapshot');
type MediaSegment = JsonObject & { [mediaSnapshot]?: MessageMedia };
export function isMessageMedia(element: MessageElement): element is MessageMedia {
return element.type === 'image' || element.type === 'record' || element.type === 'video';
}
/** Keep persistence-only metadata beside the converted segment, never on the
* public JSON wire. Capture after successful conversion so skipped elements
* cannot shift the association between a message and its media snapshots.
*/
export function attachMessageMedia(segment: JsonObject, element: MessageElement): void {
if (!isMessageMedia(element)) return;
const { type, fileId, fileName, fileSize, url, imageUrl, md5Hex, sha1Hex,
subType, summary, width, height, picFormat, duration, voiceFormat,
videoFormat, fileHash, mediaNode, flash } = element;
const snapshot = JSON.parse(serializeMediaInfo({
type, fileId, fileName, fileSize, url, imageUrl, md5Hex, sha1Hex,
subType, summary, width, height, picFormat, duration, voiceFormat,
videoFormat, fileHash, mediaNode, flash,
})) as MessageMedia;
Object.defineProperty(segment, mediaSnapshot, { value: snapshot });
}
export function serializeMessageMedia(event: JsonObject): string | null {
if (!Array.isArray(event.message)) return null;
const snapshots = event.message.flatMap(segment => {
if (!segment || typeof segment !== 'object' || Array.isArray(segment)) return [];
const snapshot = (segment as MediaSegment)[mediaSnapshot];
return snapshot ? [snapshot] : [];
});
return snapshots.length > 0 ? JSON.stringify(snapshots) : null;
}
export function parseMessageMedia(data: string): MessageMedia[] {
const parsed: unknown = JSON.parse(data);
if (!Array.isArray(parsed) || parsed.some(value => !value || typeof value !== 'object'
|| !['image', 'record', 'video'].includes(value.type))) {
throw new Error('invalid persisted message media metadata');
}
return parsed as MessageMedia[];
}
/** A repeated server representation may omit fields already learned from an
* upload or earlier receive. Preserve those fields only for the same resource;
* conflicting fingerprints or uncertain associations must not rewrite history.
*/
export function mergeMessageMedia(previous: string | null, next: string | null): string | null {
if (!previous) return next;
if (previous === next) return previous;
if (!next) throw new Error('message update is missing previously stored media metadata');
const oldMedia = parseMessageMedia(previous);
const newMedia = parseMessageMedia(next);
if (oldMedia.length !== newMedia.length) throw new Error('message media association changed');
const merged = newMedia.map((media, index) => {
const old = oldMedia[index]!;
if (old.type !== media.type) throw new Error('message media association changed');
let matched = false;
for (const field of ['md5Hex', 'sha1Hex'] as const) {
if (!old[field] || !media[field]) continue;
if (old[field].toLowerCase() !== media[field].toLowerCase()) {
throw new Error('message update has conflicting media fingerprints');
}
matched = true;
}
// Images can expose a filename as fileId, so only their fingerprints can
// prove an association. Voice/video fileId is a source resource UUID.
matched ||= media.type !== 'image' && !!old.fileId && old.fileId === media.fileId;
if (!matched && JSON.stringify(old) !== JSON.stringify(media)) {
throw new Error('message update has an unverified media association');
}
return mergeKnownMediaFields(old, media);
});
return JSON.stringify(merged);
}
function mergeKnownMediaFields(old: object, next: object): Record<string, unknown> {
const merged: Record<string, unknown> = { ...old };
for (const [key, value] of Object.entries(next)) {
// Zero dimensions, sizes and durations are incomplete observations, not
// evidence that known properties of the same resource have changed.
if (value === undefined || value === null || value === '' || value === 0) continue;
const previous = merged[key];
merged[key] = typeof value === 'object' && !Array.isArray(value)
&& previous !== null && typeof previous === 'object' && !Array.isArray(previous)
? mergeKnownMediaFields(previous, value)
: value;
}
return merged;
}
@@ -1,4 +1,5 @@
import { parentPort, workerData } from 'node:worker_threads';
import { migrateLegacyMedia } from './media-store-migration';
import {
MessageStoreMigrator,
prepareMessageStoreDatabase,
@@ -49,6 +50,8 @@ export async function runMessageStoreMigrationWorker(
try {
prepareMessageStoreDatabase(data.dbPath);
await migrateLegacyMedia(data.dbPath, () => cancelled);
if (cancelled) return;
port.postMessage({ kind: 'ready' } satisfies MessageStoreMigrationWorkerMessage);
await startRequested;
if (cancelled) return;
@@ -279,6 +279,9 @@ export function inspectMessageStoreMigration(dbPath: string): MessageStoreMigrat
export function prepareMessageStoreSchema(db: DatabaseSync): void {
const before = 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');
}
const existingRowsAreCurrent = existingColumns.has('sequence_authoritative')
&& existingColumns.has('private_direction')
&& hasLegacyPrivateSequenceMigration(db);
+16 -2
View File
@@ -4,6 +4,7 @@ import type { JsonObject, MessageMeta } from './types';
import type { MessageElement } from '@snowluma/protocol/events';
import { cqUnescape } from './helper/cq';
import { openSqliteDb } from './sqlite-open';
import { mergeMessageMedia, parseMessageMedia, serializeMessageMedia, type MessageMedia } from './message-media';
import {
createMessageStoreIndexes,
prepareMessageStoreSchema,
@@ -34,6 +35,7 @@ export class MessageStore {
private readonly stmtStoreEvent: StatementSync;
private readonly stmtStoreMeta: StatementSync;
private readonly stmtFindEvent: StatementSync;
private readonly stmtFindMedia: StatementSync;
private readonly stmtFindMeta: StatementSync;
private readonly stmtResolveReplyGroup: StatementSync;
private readonly stmtResolveReplyPrivate: StatementSync;
@@ -61,8 +63,8 @@ export class MessageStore {
// Database instance — `close()` finalizes them automatically.
this.stmtStoreEvent = this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp, data, classification_version)
VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?, 1)
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp, data, media_data, classification_version)
VALUES (?, ?, ?, ?, ?, ?, 0, ?, 0, ?, ?, ?, 1)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
@@ -78,6 +80,7 @@ export class MessageStore {
END,
timestamp = excluded.timestamp,
data = excluded.data,
media_data = excluded.media_data,
classification_version = CASE
WHEN excluded.is_group = 1 THEN excluded.classification_version
ELSE messages.classification_version
@@ -105,6 +108,8 @@ export class MessageStore {
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
);
this.stmtFindMedia = this.db.prepare('SELECT media_data FROM messages WHERE message_hash = ?');
this.stmtFindMeta = this.db.prepare(
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, private_direction, random, timestamp FROM messages WHERE message_hash = ?',
);
@@ -275,6 +280,8 @@ export class MessageStore {
}
}
const previous = this.stmtFindMedia.get(messageId) as { media_data: string | null } | undefined;
const media = mergeMessageMedia(previous?.media_data ?? null, serializeMessageMedia(event));
this.stmtStoreEvent.run(
messageId,
isGroup ? 1 : 0,
@@ -285,9 +292,16 @@ export class MessageStore {
privateDirection,
timestamp,
json,
media,
);
}
findMedia(messageId: number): MessageMedia[] | null {
if (!isValidMessageId(messageId)) return null;
const row = this.stmtFindMedia.get(messageId) as { media_data: string | null } | undefined;
return row?.media_data != null ? parseMessageMedia(row.media_data) : null;
}
storeMeta(messageId: number, meta: MessageMeta): void {
if (!isValidMessageId(messageId)) return;
const privateDirection = encodePrivateDirection(meta.privateDirection);
+2 -1
View File
@@ -42,7 +42,8 @@ export async function fetchPttText(
}
if (!file) throw new Error('消息中不包含语音');
const cached = mediaStore.findRecord(file);
const snapshot = messageStore.findMedia(messageId)?.find(element => element.type === 'record');
const cached = snapshot ? { ...snapshot, isGroup: event.message_type === 'group', sessionId: Number(event.group_id) || selfId } : mediaStore.findRecord(file, 'legacy');
if (!cached) throw new Error('语音不在缓存中,无法转写');
const isGroup = event.message_type === 'group' || cached.isGroup;
+34 -11
View File
@@ -1,3 +1,4 @@
import { isMessageMedia, type MessageMedia } from '../message-media';
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
@@ -1287,7 +1288,7 @@ export async function forwardSingleMessage(
const parsed = await parseMessage(content, false);
if (parsed.length === 0) throw new Error('message has no content');
const elements = await prepareSingleForwardElements(ref, parsed, target);
const elements = await prepareSingleForwardElements(ref, restoreHistoricalMedia(ref, parsed, messageId), target);
let receipt;
let messageIdOut: number;
@@ -1319,7 +1320,7 @@ async function prepareSingleForwardElements(
const out: MessageElement[] = [];
for (const element of elements) {
if (element.type !== 'forward') {
out.push(enrichForForward(ref, element));
out.push(isMessageMedia(element) ? element : enrichForForward(ref, element));
continue;
}
const resId = element.resId.trim();
@@ -1395,7 +1396,29 @@ async function expandForwardNodeForTarget(
return { ...node, elements };
}
function enrichForForward(ref: OneBotInstanceContext, element: MessageElement): MessageElement {
function restoreHistoricalMedia(
ref: OneBotInstanceContext,
elements: MessageElement[],
messageId: number,
): MessageElement[] {
if (!elements.some(isMessageMedia)) return elements;
const snapshots = ref.messageStore.findMedia(messageId);
let index = 0;
const restored = elements.map(element => {
if (!isMessageMedia(element)) return element;
const snapshot = snapshots?.[index++];
if (snapshots && (!snapshot || snapshot.type !== element.type)) {
throw new Error(`historical media metadata does not match message ${messageId}`);
}
return enrichForForward(ref, element, snapshot);
});
if (snapshots && index !== snapshots.length) {
throw new Error(`historical media metadata does not match message ${messageId}`);
}
return restored;
}
function enrichForForward(ref: OneBotInstanceContext, element: MessageElement, snapshot?: MessageMedia): MessageElement {
if (element.type === 'forward') {
throw new Error('merged forward must be regenerated for the target chat');
}
@@ -1416,14 +1439,14 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
// the keys MediaStore aliases under. After parseMessage, the segment's
// `data.file` lands on `element.url` for all three types.
const lookupKey = element.url || element.fileName || element.fileId || '';
if (!lookupKey) {
if (!lookupKey && !snapshot) {
throw new Error(`forward ${element.type} missing cache key`);
}
if (element.type === 'image') {
const cached = ref.mediaStore.findImage(lookupKey);
const cached = snapshot?.type === 'image' ? snapshot : ref.mediaStore.findImage(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex || !cached.width || !cached.height || !cached.picFormat) {
throw new Error('forward image fingerprint not cached (legacy image or expired)');
throw new Error('historical image metadata is incomplete; fetch the original message again');
}
return {
...element,
@@ -1442,9 +1465,9 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
}
if (element.type === 'record') {
const cached = ref.mediaStore.findRecord(lookupKey);
const cached = snapshot?.type === 'record' ? snapshot : ref.mediaStore.findRecord(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error('forward record fingerprint not cached');
throw new Error('historical voice metadata is incomplete; fetch the original message again');
}
return {
...element,
@@ -1461,9 +1484,9 @@ function enrichForForward(ref: OneBotInstanceContext, element: MessageElement):
}
if (element.type === 'video') {
const cached = ref.mediaStore.findVideo(lookupKey);
const cached = snapshot?.type === 'video' ? snapshot : ref.mediaStore.findVideo(lookupKey, 'legacy');
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
throw new Error('forward video fingerprint not cached');
throw new Error('historical video metadata is incomplete; fetch the original message again');
}
log.warn('video forward uses a fallback thumbnail (original thumb not cached)');
return {
@@ -1825,7 +1848,7 @@ async function parseForwardNodes(
);
}
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
const elements = restoreHistoricalMedia(ref, await parseMessage(content, false), messageId);
if (elements.length > 0) {
const messageType = event.message_type === 'group' ? 'group' : 'private';
const groupIdValue = toPositiveInt(event.group_id);
+8 -3
View File
@@ -36,7 +36,7 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
uin: '10001',
selfId: 10001,
bridge,
messageStore: { findEvent: () => null } as any,
messageStore: { findMedia: () => null, findEvent: () => null } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
@@ -263,6 +263,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
}),
@@ -290,6 +291,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OLD_RES' } }],
}),
@@ -340,6 +342,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
message: [{ type: 'forward', data: { id: 'OUTER' } }],
}),
@@ -361,6 +364,7 @@ describe('forward — nested {type:"node"} content', () => {
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage } } } as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
message: [
{ type: 'video', data: { file: 'cached-video-id' } },
@@ -439,6 +443,7 @@ describe('forward — nested {type:"node"} content', () => {
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findMedia: () => null,
findEvent: () => ({
user_id: 0,
message_type: 'group',
@@ -478,7 +483,7 @@ describe('forward — nested {type:"node"} content', () => {
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = { findEvent };
(ctx as any).messageStore = { findEvent, findMedia: () => null };
await sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { id: -123 } },
@@ -525,7 +530,7 @@ describe('forward — nested {type:"node"} content', () => {
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = { findEvent };
(ctx as any).messageStore = { findEvent, findMedia: () => null };
await sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { id: 7, nickname: 'node-override' } },
@@ -0,0 +1,256 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import type { MessageElement } from '@snowluma/protocol/events';
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../src/event-converter';
import { MediaIndexer } from '../src/media-indexer';
import { MediaStore, MEDIA_DATA_MAX_CHARS } from '../src/media-store';
import { migrateLegacyMedia } from '../src/media-store-migration';
import { MessageStore } from '../src/message-store';
import type { OneBotInstanceContext } from '../src/instance-context';
import { forwardSingleMessage, sendGroupForwardMessage } from '../src/modules/message-actions';
const directories: string[] = [];
afterEach(() => { for (const dir of directories.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
function location() {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'historical-media-'));
directories.push(directory);
return { directory, dbPath: path.join(directory, 'messages.db'), legacyPath: path.join(directory, 'media.db') };
}
const image = {
file: 'same.png', fileName: 'same.png', url: '', imageUrl: '', fileSize: 120,
md5Hex: 'aa'.repeat(16), sha1Hex: 'bb'.repeat(20), width: 32, height: 24, picFormat: 1001,
subType: 0, summary: '', isGroup: true, sessionId: 123,
};
function converter(media: MediaStore): ConverterContext {
const indexer = new MediaIndexer(media);
return { selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null, messageIdResolver: null,
mediaSegmentSink: (...args) => indexer.remember(...args) };
}
function context(messages: MessageStore, media: MediaStore) {
const sendGroup = vi.fn(async () => ({ sequence: 234, clientSequence: 0, random: 1, timestamp: 1700000001 }));
const upload = vi.fn(async (_nodes: unknown) => 'forward-id');
const ref = {
selfId: 10001, messageStore: messages, mediaStore: media,
converterCtx: converter(media), cacheMessageMeta: vi.fn(),
bridge: { identity: { nickname: 'self' }, apis: { message: { sendGroup }, forward: { upload } } },
} as unknown as OneBotInstanceContext;
return { ref, sendGroup, upload };
}
describe('durable historical media', () => {
it.each(['image', 'record', 'video'] as const)('forwards %s after cache churn, alias replacement and reopen', async type => {
const { dbPath } = location();
let messages = new MessageStore(dbPath);
let media = new MediaStore(dbPath, 2);
const element = { type, fileId: 'same.png', fileName: 'same.png', fileSize: 120,
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: 32, height: 24,
picFormat: 1001, duration: 3, voiceFormat: 1, videoFormat: 0 } as MessageElement;
const event = await convertEvent(converter(media), {
kind: 'group_message', groupName: '', time: 1700000000, selfUin: 10001,
groupId: 123, senderUin: 456, senderNick: 'peer', senderCard: '', senderRole: 'member',
msgSeq: 10, msgId: 10, elements: [element],
});
event!.message_id = 42;
messages.storeHistoryEvent(42, true, 123, 10, 'GroupMessage', event!);
expect(JSON.stringify(event)).not.toContain('md5Hex');
expect(JSON.stringify(messages.findEvent(42))).not.toContain('sha1Hex');
// Repeated names and many new resources must not change the old message.
for (let i = 0; i < 80; i++) {
await elementsToOneBotSegments(converter(media), [{ ...element, md5Hex: 'cc'.repeat(16) }], true, 123);
media.rememberImage({ ...image, file: `other-${i}`, fileName: `other-${i}` });
media.findImage(`other-${i}`);
}
media.close(); messages.close();
messages = new MessageStore(dbPath); media = new MediaStore(dbPath, 2);
try {
const { ref, sendGroup, upload } = context(messages, media);
await forwardSingleMessage(ref, 42, { groupId: 999 });
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({
type, md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, noByteFallback: true,
})]);
await sendGroupForwardMessage(ref, 999, [{ type: 'node', data: { id: 42 } }]);
expect(upload.mock.calls[0]?.[0]).toEqual([expect.objectContaining({
elements: [expect.objectContaining({ type, md5Hex: image.md5Hex, noByteFallback: true })],
})]);
expect(messages.findEvent(42)?.message_id).toBe(42);
} finally { media.close(); messages.close(); }
});
it('stores the body and media snapshot atomically and strips inline bytes', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
const media = new MediaStore(dbPath);
const db = new DatabaseSync(dbPath);
try {
const segments = await elementsToOneBotSegments(converter(media), [{ type: 'image',
...image, url: `base64://${'A'.repeat(100000)}`, imageUrl: '', fileId: 'same.png' }], true, 123);
const event = { time: 1, message: segments };
db.exec("CREATE TRIGGER fail_media BEFORE INSERT ON messages WHEN NEW.media_data IS NOT NULL BEGIN SELECT RAISE(ABORT, 'test media write failure'); END");
expect(() => messages.storeEvent(1, true, 123, 1, 'GroupMessage', event)).toThrow('test media write failure');
expect(messages.findEvent(1)).toBeNull();
db.exec('DROP TRIGGER fail_media');
messages.storeEvent(1, true, 123, 1, 'GroupMessage', event);
expect(messages.findMedia(1)?.[0].md5Hex).toBe(image.md5Hex);
expect(JSON.stringify(messages.findMedia(1))).not.toContain('base64://');
} finally { db.close(); media.close(); messages.close(); }
});
it('propagates media persistence failures instead of silently skipping segments', async () => {
const { dbPath } = location();
const media = new MediaStore(dbPath);
media.close();
await expect(elementsToOneBotSegments(converter(media), [{ type: 'image', fileId: 'test' }], true, 123))
.rejects.toThrow();
});
it('does not substitute another same-named resource for an incomplete snapshot', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
const media = new MediaStore(dbPath);
try {
const segments = await elementsToOneBotSegments(converter(media), [{ type: 'image', fileId: image.file }], true, 123);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: segments });
media.rememberImage(image);
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(); }
});
it('preserves complete metadata across an incomplete repeat and rejects conflicting resources', async () => {
const { dbPath } = location();
let messages = new MessageStore(dbPath);
let media = new MediaStore(dbPath);
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 save(complete);
await save({ type: 'image', fileId: image.file, md5Hex: image.md5Hex, width: 0, height: 0 });
await expect(save({ ...complete, md5Hex: 'cc'.repeat(16) })).rejects.toThrow('conflicting');
media.close(); messages.close();
messages = new MessageStore(dbPath); media = new MediaStore(dbPath);
try {
const { ref, sendGroup } = context(messages, media);
await forwardSingleMessage(ref, 42, { groupId: 999 });
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: image.width, height: image.height,
})]);
} finally { media.close(); messages.close(); }
});
it('does not combine disjoint image fingerprints merely because fileId is the same filename', async () => {
const { dbPath } = location();
const messages = new MessageStore(dbPath);
const media = new MediaStore(dbPath);
try {
const original = await elementsToOneBotSegments(converter(media), [
{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 },
], true, 123);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: original });
const different = await elementsToOneBotSegments(converter(media), [
{ type: 'image', fileId: 'photo.jpg', sha1Hex: image.sha1Hex, width: 64 },
], true, 123);
expect(() => messages.storeEvent(42, true, 123, 1, 'GroupMessage', { message: different }))
.toThrow('unverified media association');
expect(messages.findMedia(42)).toEqual([{ type: 'image', fileId: 'photo.jpg', md5Hex: image.md5Hex, width: 32 }]);
} finally { media.close(); messages.close(); }
});
it('rejects corrupt and oversized metadata without deleting history', () => {
const { dbPath } = location();
const media = new MediaStore(dbPath);
const db = new DatabaseSync(dbPath);
try {
expect(() => media.rememberImage({ ...image, summary: 'x'.repeat(MEDIA_DATA_MAX_CHARS) })).toThrow('storage limit');
media.rememberImage(image);
db.exec("UPDATE media_entries SET data = '{broken'");
expect(() => media.findImage(image.file)).toThrow();
db.exec("UPDATE media_entries SET data = 'null'");
expect(() => media.findImage(image.file)).toThrow('invalid persisted');
expect(media.size().images).toBe(1);
} finally { db.close(); media.close(); }
});
it.each(['image', 'record', 'video'] as const)('keeps migrated %s history independent of new same-named resources', async type => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
const element = { type, fileId: 'same.png', fileName: 'same.png', fileSize: 120,
md5Hex: image.md5Hex, sha1Hex: image.sha1Hex, width: 32, height: 24,
picFormat: 1001, duration: 3, voiceFormat: 1, videoFormat: 0 } as MessageElement;
await elementsToOneBotSegments(converter(old), [element], true, 123);
old.close();
const source = fs.readFileSync(legacyPath);
const messages = new MessageStore(dbPath);
messages.storeEvent(42, true, 123, 1, 'GroupMessage', {
user_id: 456, message_id: 42, message_type: 'group',
message: [{ type, data: { file: image.file } }],
});
await migrateLegacyMedia(dbPath);
expect(fs.readFileSync(legacyPath)).toEqual(source);
fs.rmSync(legacyPath);
await migrateLegacyMedia(dbPath);
const media = new MediaStore(dbPath);
try {
await elementsToOneBotSegments(converter(media), [{ ...element, md5Hex: 'cc'.repeat(16) }], true, 123);
const { ref, sendGroup } = context(messages, media);
await forwardSingleMessage(ref, 42, { groupId: 999 });
expect(sendGroup).toHaveBeenCalledWith(999, [expect.objectContaining({ md5Hex: image.md5Hex })]);
} finally { media.close(); messages.close(); }
});
it('rolls back a failed legacy batch and resumes after the source is repaired', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath); old.rememberImage(image); old.close();
const 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();
const repaired = new DatabaseSync(legacyPath);
repaired.prepare("UPDATE media_entries SET data = ? WHERE primary_key = 'broken'").run(JSON.stringify({ ...image, file: 'broken' }));
repaired.close();
await migrateLegacyMedia(dbPath);
const reopened = new MediaStore(dbPath);
expect(reopened.size().images).toBe(2); reopened.close();
});
it('normalizes legacy inline payloads without discarding their metadata', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath); old.close();
const inline = `base64://${'Z'.repeat(100000)}`;
const source = new DatabaseSync(legacyPath);
source.prepare("INSERT INTO media_entries VALUES ('image', ?, ?, 1)")
.run(inline, JSON.stringify({ ...image, file: inline, url: inline, imageUrl: inline }));
source.prepare("INSERT INTO media_keys VALUES ('image', ?, ?)").run(inline, inline);
source.close();
await migrateLegacyMedia(dbPath);
const media = new MediaStore(dbPath);
try {
expect(media.findImage(inline)).toMatchObject({ md5Hex: image.md5Hex, url: '', imageUrl: '' });
expect(JSON.stringify(media.findImage(inline))).not.toContain('base64://');
} finally { media.close(); }
});
it('resumes a cancelled migration from its committed batch cursor', async () => {
const { dbPath, legacyPath } = location();
const old = new MediaStore(legacyPath);
for (let i = 0; i < 205; i++) old.rememberImage({ ...image, file: `entry-${i}` });
old.close();
let checks = 0;
await migrateLegacyMedia(dbPath, () => ++checks > 1);
const partial = new MediaStore(dbPath);
expect(partial.size().images).toBe(200); 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();
});
});
@@ -129,6 +129,7 @@ function makeRef(overrides: {
});
const messageStore = {
findMedia: () => null,
findEvent: (messageId: number) => events.get(messageId) ?? null,
findMeta: (messageId: number) => metas.get(messageId) ?? null,
storeMetas: (entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>) => {
@@ -36,7 +36,7 @@ function trackPttKey(selfId: number, messageId: number): string {
}
function fakeMessageStore(event: JsonObject | null): MessageStore {
return { findEvent: () => event } as unknown as MessageStore;
return { findMedia: () => null, findEvent: () => event } as unknown as MessageStore;
}
function fakeImageStore(image: CachedImage | null): MediaStore {
@@ -177,7 +177,7 @@ describe('fetchPttText', () => {
SELF_ID,
40004,
)).resolves.toEqual({ text: '跳过垃圾段落后转写' });
expect(store.findRecord).toHaveBeenCalledWith('keep.silk');
expect(store.findRecord).toHaveBeenCalledWith('keep.silk', 'legacy');
});
it('throws when the record segment has no file and no url', async () => {
@@ -248,7 +248,7 @@ describe('fetchPttText', () => {
SELF_ID,
40009,
)).resolves.toEqual({ text: 'url 字段转写' });
expect(store.findRecord).toHaveBeenCalledWith('https://ptt.example/by-url.silk');
expect(store.findRecord).toHaveBeenCalledWith('https://ptt.example/by-url.silk', 'legacy');
});
it('uses the first record segment even when a later one exists', async () => {
@@ -272,8 +272,8 @@ describe('fetchPttText', () => {
SELF_ID,
40010,
)).resolves.toEqual({ text: '第一段' });
expect(store.findRecord).toHaveBeenCalledWith('first.silk');
expect(store.findRecord).not.toHaveBeenCalledWith('second.silk');
expect(store.findRecord).toHaveBeenCalledWith('first.silk', 'legacy');
expect(store.findRecord).not.toHaveBeenCalledWith('second.silk', 'legacy');
});
it('stringifies a numeric file id before cache lookup', async () => {
@@ -292,7 +292,7 @@ describe('fetchPttText', () => {
SELF_ID,
40011,
)).resolves.toEqual({ text: '数字 file' });
expect(store.findRecord).toHaveBeenCalledWith('9001');
expect(store.findRecord).toHaveBeenCalledWith('9001', 'legacy');
});
it('throws when the record is not in the media cache', async () => {
+9 -8
View File
@@ -182,9 +182,8 @@ describe('MediaStore basic semantics', () => {
}
});
it('evicts old entries beyond the configured cap', () => {
// EVICT_EVERY_N_REMEMBERS = 64 inside the store; we exercise the eviction
// path by writing well past the cap so it triggers at least once.
it('retains durable entries beyond the memory cache cap', () => {
// 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++) {
@@ -201,7 +200,9 @@ describe('MediaStore basic semantics', () => {
});
}
const { images } = store.size();
expect(images).toBeLessThanOrEqual(cap);
expect(images).toBe(200);
for (let i = 0; i < 200; i++) expect(store.findImage(`file-${i}.png`)?.fileSize).toBe(i);
expect(store.findImage('file-0.png')?.fileSize).toBe(0);
// Most recent entries should still be present.
expect(store.findImage('file-199.png')?.fileSize).toBe(199);
store.close();
@@ -285,7 +286,7 @@ describe('MediaStore basic semantics', () => {
store.close();
});
it('drops oversized rows left by older builds on open', () => {
it('does not destructively purge existing metadata on open', () => {
const dbPath = tempDbPath('legacy-overflow');
dbs.push(dbPath);
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
@@ -316,11 +317,11 @@ describe('MediaStore basic semantics', () => {
const store = new MediaStore(dbPath);
expect(store.findImage(poisonKey)).toBeNull();
expect(store.size().images).toBe(0);
expect(store.size().images).toBe(1);
store.close();
const rows = inspectMediaDb(dbPath);
expect(rows.entryCount).toBe(0);
expect(rows.keyCount).toBe(0);
expect(rows.entryCount).toBe(1);
expect(rows.keyCount).toBe(1);
});
});
@@ -127,6 +127,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.
expect(control.messages).toEqual([{ kind: 'ready' }]);
expect(control.listenerCount()).toBe(1);
@@ -154,6 +155,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.
control.send('go');
control.send({ kind: 'start' });
@@ -178,6 +180,7 @@ describe('runMessageStoreMigrationWorker', () => {
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.
control.send('cancel');
await running;
@@ -198,6 +201,7 @@ describe('runMessageStoreMigrationWorker', () => {
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.
control.send('start');
control.send('cancel');
@@ -212,6 +216,7 @@ describe('runMessageStoreMigrationWorker', () => {
seedUnclassified(dbPath, 1);
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
control.send('start');
await running;
@@ -236,6 +241,7 @@ describe('runMessageStoreMigrationWorker', () => {
seedUnclassified(dbPath, 201);
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
control.send('start');
await running;
@@ -269,6 +275,7 @@ describe('runMessageStoreMigrationWorker', () => {
seedUnclassified(dbPath, 201);
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
control.send('start');
await Promise.resolve();
@@ -323,6 +330,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.
expect(control.messages).toEqual([{ kind: 'ready' }]);
const db = new DatabaseSync(dbPath);
@@ -353,6 +361,7 @@ 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.
control.send('start');
await running;
@@ -371,6 +380,7 @@ describe('runMessageStoreMigrationWorker', () => {
});
const control = createControlPort();
const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port);
await Promise.resolve(); // Account readiness follows asynchronous media preparation.
control.send('start');
await running;
@@ -79,6 +79,7 @@ function makeContext(receiptOrReceipts: Receipt | Receipt[] = RECEIPT): {
selfId: SELF_ID,
bridge,
messageStore: {
findMedia: () => null,
findEvent: (messageId: number) => events.get(messageId) ?? null,
findMeta: () => null,
resolveReplySequence: () => null,
@@ -123,6 +124,7 @@ function makeInstanceHarness(options: {
},
log: options.logger ?? { success: vi.fn(), trace: vi.fn(), warn: vi.fn() },
messageStore: {
findMedia: () => null,
findEvent: (messageId: number) => stored.get(messageId) ?? null,
storeEvent: (messageId: number, _isGroup: boolean, _sessionId: number, _sequence: number, _eventName: string, event: JsonObject) => {
stored.set(messageId, event);