feat: add async SQLite on Node 24 and improve messaging diagnostics (#520)

Move database work off the main thread on Node.js 24 and improve message handling and runtime diagnostics.

Preserve migration, restart, and concurrency coverage with the async SQLite driver.
This commit is contained in:
MliKiowa authored and GitHub committed 2026-10-13 10:12:47 +08:00
1 parent 20f48d11ec
commit c7428363cb
170 files changed
+7748 -3913

No files matched your search

@@ -38,6 +38,7 @@ describe('forward metadata through upload and cached reads', () => {
const ctx = {
selfId: 10001,
bridge: {
identity: { nickname: 'SnowLuma' },
apis: {
forward,
message: {
@@ -51,7 +52,7 @@ describe('forward metadata through upload and cached reads', () => {
},
},
},
messageStore: { findEvent: () => null, findMedia: () => null },
messageStore: { findEvent: () => null, findMedia: () => null, storeEvent: vi.fn() },
cacheMessageMeta: vi.fn(),
converterCtx: {
selfId: 10001,
@@ -104,9 +105,7 @@ describe('forward metadata through upload and cached reads', () => {
if (nested) {
expect(
(await api.getForwardMsg(`metadata-true-${enrich}-1`))[0]!.sender,
).toMatchObject({
title: 'inner title',
});
).toMatchObject({ title: 'inner title' });
}
const fetched = await forward.fetch(forwardId!);
@@ -0,0 +1,225 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { gunzipSync, gzipSync, inflateSync } from 'node:zlib';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import type {
LongMsgResult,
RecvLongMsgResp,
SendLongMsgReq,
SendLongMsgResp,
} from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MessageElement } from '@snowluma/protocol/events';
import { runNtv2Upload } from '@snowluma/protocol/highway/pipeline';
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { ForwardApi } from '../../src/bridge/apis/forward';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { mockBridge } from './_helpers';
// Keep the image uploader, element builder and Proton codecs real. Only the
// network boundaries are faked, including a source URL that needs an rkey.
vi.mock('@snowluma/protocol/highway/pipeline', async (importOriginal) => ({
...(await importOriginal<typeof import('@snowluma/protocol/highway/pipeline')>()),
runNtv2Upload: vi.fn(),
}));
vi.mock('@snowluma/protocol/highway/utils', async (importOriginal) => ({
...(await importOriginal<typeof import('@snowluma/protocol/highway/utils')>()),
loadBinarySource: vi.fn(async () => {
throw new Error('source image URL requires an rkey');
}),
}));
const md5Hex = 'ab'.repeat(16);
const sha1Hex = 'cd'.repeat(20);
const sourceInfo: MsgInfo = {
msgInfoBody: [
{
index: {
fileUuid: 'source-group-image',
info: {
fileHash: md5Hex,
fileSha1: sha1Hex,
fileSize: 1234,
fileName: 'image.png',
width: 32,
height: 24,
type: { type: 1, picFormat: 1001 },
},
},
picture: {
domain: 'multimedia.nt.qq.com.cn',
urlPath: '/download?appid=1407&fileid=source-group-image',
},
},
],
};
function packetResult(responseData: Uint8Array) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(responseData),
};
}
function setup(id: string) {
const sourceBody: PushMsgBody = {
responseHead: {
fromUin: 20002,
fromUid: 'sender-uid',
grp: { groupUin: 12345, memberCard: 'alice' },
},
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
body: {
richText: {
elems: [
{ text: { str: 'picture' } },
{
commonElem: {
serviceType: 48,
businessType: 20,
pbElem: protobuf_encode<MsgInfo>(sourceInfo),
},
},
],
},
},
};
const sentLongMessages: SendLongMsgReq[] = [];
const bridge = mockBridge({
resolveUserUid: vi.fn(async () => 'self-uid'),
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
if (command.endsWith('SsoRecvLongMsg')) {
return packetResult(
protobuf_encode<RecvLongMsgResp>({
result: {
payload: gzipSync(
protobuf_encode<LongMsgResult>({
action: [
{
actionCommand: 'MultiMsg',
actionData: { msgBody: [sourceBody] },
},
],
}),
),
},
}),
);
}
expect(command).toMatch(/SsoSendLongMsg$/);
sentLongMessages.push(protobuf_decode<SendLongMsgReq>(bytes));
return packetResult(
protobuf_encode<SendLongMsgResp>({ result: { resId: `new-${id}` } }),
);
}),
});
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const sendPrivate = vi.fn(async (_userId: number, elements: MessageElement[]) => {
const [card] = await buildSendElems(elements);
expect(card?.richMsg?.serviceId).toBe(35);
const xml = inflateSync(card!.richMsg!.template1!.subarray(1)).toString();
expect(xml).toContain(`m_resid="new-${id}"`);
expect(xml).toContain('alice: picture [图片]');
return { messageId: 1, sequence: 2, clientSequence: 3, random: 4, timestamp: 1700000001 };
});
const ctx = {
selfId: 10001,
bridge: { identity: { nickname: 'SnowLuma' }, apis: { forward, message: { sendPrivate } } },
messageStore: {
findEvent: () => ({ message: [{ type: 'forward', data: { id } }] }),
storeEvent: vi.fn(),
},
converterCtx: {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
cacheMessageMeta: vi.fn(),
dispatchEvent: vi.fn(),
} as unknown as OneBotInstanceContext;
return { api: buildApiContext(ctx), forward, sendPrivate, sentLongMessages, bridge };
}
describe('single merged-forward media (#437)', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(runNtv2Upload).mockImplementation(async (params) => ({
msgInfo: {
msgInfoBody: [
{
index: {
fileUuid: 'target-private-image',
info: params.uploadInfo[0]!.fileInfo,
},
},
],
},
}));
});
it('reuploads a decoded group image for self-chat without downloading its unsigned source URL', async () => {
const { api, forward, sentLongMessages, bridge } = setup('image-to-self');
await expect(api.forwardSingleMsg(77, { userId: 10001 })).resolves.toHaveProperty(
'messageId',
);
expect(loadBinarySource).not.toHaveBeenCalled();
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
expect(runNtv2Upload).toHaveBeenCalledOnce();
expect(vi.mocked(runNtv2Upload).mock.calls[0]![0]).toMatchObject({
isGroup: false,
targetIdOrUid: 'self-uid',
oidbCmd: 0x11c5,
uploadInfo: [
{
fileInfo: {
fileHash: md5Hex,
fileSha1: sha1Hex,
width: 32,
height: 24,
fileSize: 1234,
},
},
],
uploads: [{ bytes: new Uint8Array(0) }],
});
expect(sentLongMessages).toHaveLength(1);
expect(sentLongMessages[0]!.info?.type).toBe(1);
const body = protobuf_decode<LongMsgResult>(
gunzipSync(sentLongMessages[0]!.info!.payload!),
);
const elems = body.action![0]!.actionData!.msgBody![0]!.body!.richText!.elems!;
expect(elems.find((e) => e.commonElem)?.commonElem?.businessType).toBe(10);
const media = protobuf_decode<MsgInfo>(
elems.find((e) => e.commonElem)!.commonElem!.pbElem!,
);
expect(media.msgInfoBody?.[0]?.index?.fileUuid).toBe('target-private-image');
expect(elems.find((e) => e.notOnlineImage)?.notOnlineImage?.picMd5).toEqual(
Buffer.from(md5Hex, 'hex'),
);
expect(
(await forward.fetch('image-to-self'))[0]!.elements[1]!.noByteFallback,
).toBeUndefined();
});
it('does not send a card or upload a long message when target image upload fails', async () => {
vi.mocked(runNtv2Upload).mockRejectedValueOnce(
new Error('image fast-upload not available (server requires bytes)'),
);
const { api, sendPrivate, sentLongMessages } = setup('image-upload-failure');
await expect(api.forwardSingleMsg(77, { userId: 10001 })).rejects.toThrow(
'image fast-upload not available',
);
expect(sendPrivate).not.toHaveBeenCalled();
expect(sentLongMessages).toHaveLength(0);
expect(loadBinarySource).not.toHaveBeenCalled();
});
});
+2 -1
View File
@@ -233,6 +233,7 @@ describe('apis/friend', () => {
it('approves a filtered stranger through Identity without requiring a shared roster', async () => {
const identity = new IdentityService('10001', null);
await identity.initialization;
const bridge = mockBridge();
const fetchProfile = vi.fn(async (uin: number) => ({
uin,
@@ -250,7 +251,7 @@ describe('apis/friend', () => {
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ selfUid: 'u_self', targetUid: 'u_stranger' });
} finally {
identity.close();
await identity.close();
}
});
@@ -121,7 +121,7 @@ describe('Bridge group member identity refresh', () => {
seen.push(event);
});
bridge.onPacket(makePacket());
await bridge.onPacket(makePacket());
const event = await waitForEvent(seen);
expect(profileFetches).toEqual([member.uid]);
@@ -129,7 +129,7 @@ describe('Bridge group member identity refresh', () => {
expect(event.userUin).toBe(member.uin);
});
it('remembers UID mappings from realtime request events', () => {
it('remembers UID mappings from realtime request events', async () => {
const bridge = new Bridge(IdentityService.memory(SELF_UIN));
const events: QQEventVariant[] = [
{
@@ -155,7 +155,7 @@ describe('Bridge group member identity refresh', () => {
];
bridge.registerCmd('test.request_identity', () => events);
bridge.onPacket(makeRequestPacket());
await bridge.onPacket(makeRequestPacket());
expect(bridge.identity.findUidByUin(55555)).toBe('u_friend_request');
expect(bridge.identity.findUidByUin(66666)).toBe('u_group_request');
@@ -29,7 +29,7 @@ function device(overrides: Partial<OnlineDeviceInfo> = {}): OnlineDeviceInfo {
}
describe('Bridge online-device snapshot', () => {
it('distinguishes not-yet-observed from an observed empty snapshot', () => {
it('distinguishes not-yet-observed from an observed empty snapshot', async () => {
const bridge = new Bridge(IdentityService.memory('10001'));
let current: OnlineDeviceInfo[] = [device()];
bridge.registerCmd('test.online_devices', () => [
@@ -43,15 +43,15 @@ describe('Bridge online-device snapshot', () => {
expect(bridge.getOnlineClients()).toBeNull();
bridge.onPacket(packet(1));
await bridge.onPacket(packet(1));
expect(bridge.getOnlineClients()).toEqual([device()]);
current = [];
bridge.onPacket(packet(2));
await bridge.onPacket(packet(2));
expect(bridge.getOnlineClients()).toEqual([]);
});
it('owns an immutable copy and clears it when the Bridge is disposed', () => {
it('owns an immutable copy and clears it when the Bridge is disposed', async () => {
const bridge = new Bridge(IdentityService.memory('10001'));
const source = device();
bridge.registerCmd('test.online_devices', () => [
@@ -63,7 +63,7 @@ describe('Bridge online-device snapshot', () => {
},
]);
bridge.onPacket(packet(1));
await bridge.onPacket(packet(1));
const snapshot = bridge.getOnlineClients();
expect(snapshot).not.toBeNull();
expect(snapshot?.[0]).not.toBe(source);
@@ -73,7 +73,7 @@ describe('Bridge online-device snapshot', () => {
source.deviceName = 'MUTATED';
expect(bridge.getOnlineClients()?.[0]?.deviceName).toBe('DESKTOP-TEST');
bridge.dispose();
await bridge.dispose();
expect(bridge.getOnlineClients()).toBeNull();
});
});
@@ -103,7 +103,7 @@ describe('Bridge roster warmup', () => {
expect(identity.findFriend(22222)?.uid).toBe('u_friend');
expect(identity.findGroup(123)?.groupName).toBe('group');
expect(identity.findGroupMember(123, 33333)?.uid).toBe('u_member');
bridge.dispose();
await bridge.dispose();
});
it('does not retry a failed friend list fetch', async () => {
@@ -125,7 +125,7 @@ describe('Bridge roster warmup', () => {
bridge.bindPid(8, sender);
await bridge.whenRosterWarmupSettled();
expect(fetchFriendList).toHaveBeenCalledOnce();
bridge.dispose();
await bridge.dispose();
});
it('discards in-flight warmup writes after dispose', async () => {
@@ -140,7 +140,7 @@ describe('Bridge roster warmup', () => {
bridge.bindPid(7, sender);
const settled = bridge.whenRosterWarmupSettled();
bridge.dispose();
await bridge.dispose();
releaseFriends([makeFriend(22222, 'u_friend', 'friend')]);
await expect(settled).resolves.toEqual({ friendsLoaded: false, groupsLoaded: false });
+10 -10
View File
@@ -203,7 +203,7 @@ describe('formatMessageSegments', () => {
});
describe('formatReply', () => {
it('renders the resolved sender + body preview when the original is in the store', () => {
it('renders the resolved sender + body preview when the original is in the store', async () => {
const store = fakeMessageStore({
42: {
message_type: 'group',
@@ -214,16 +214,16 @@ describe('formatReply', () => {
},
});
const id = fakeIdentity({ members: { '1/100': { uin: 100, card: 'OrigSender' } } });
expect(formatReply(store, id, 42)).toBe('[回复 [OrigSender(100)]: 早安]');
expect(await formatReply(store, id, 42)).toBe('[回复 [OrigSender(100)]: 早安]');
});
it('falls back to [回复:<id>] when the original is missing', () => {
it('falls back to [回复:<id>] when the original is missing', async () => {
const store = fakeMessageStore({});
const id = fakeIdentity();
expect(formatReply(store, id, 9999)).toBe('[回复:9999]');
expect(await formatReply(store, id, 9999)).toBe('[回复:9999]');
});
it('uses the sender baked into the stored event when cache misses', () => {
it('uses the sender baked into the stored event when cache misses', async () => {
const store = fakeMessageStore({
42: {
message_type: 'private',
@@ -233,10 +233,10 @@ describe('formatReply', () => {
},
});
const id = fakeIdentity(); // no cache
expect(formatReply(store, id, 42)).toBe('[回复 [StoredNick(100)]: hi]');
expect(await formatReply(store, id, 42)).toBe('[回复 [StoredNick(100)]: hi]');
});
it('truncates the body preview to 30 chars', () => {
it('truncates the body preview to 30 chars', async () => {
const store = fakeMessageStore({
42: {
message_type: 'private',
@@ -246,20 +246,20 @@ describe('formatReply', () => {
},
});
const id = fakeIdentity();
const out = formatReply(store, id, 42);
const out = await formatReply(store, id, 42);
// Inner text gets truncated to 50 by formatMessageSegments, then to 30 here
expect(out).toContain('...');
expect(out.length).toBeLessThan(80);
});
it('returns the fallback when findEvent throws', () => {
it('returns the fallback when findEvent throws', async () => {
const store = {
findEvent: () => {
throw new Error('store dead');
},
} as any;
const id = fakeIdentity();
expect(formatReply(store, id, 42)).toBe('[回复:42]');
expect(await formatReply(store, id, 42)).toBe('[回复:42]');
});
});
+209 -120
View File
@@ -3,6 +3,7 @@ import fs from 'fs';
import { DatabaseSync } from 'node:sqlite';
import path from 'path';
import { subscribeLogs } from '@snowluma/common/logger';
import { SqliteDatabase } from '@snowluma/sqlite';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
@@ -31,20 +32,19 @@ function cleanupDb(dbPath: string): void {
}
}
function holdWriteLock(dbPath: string): () => void {
const locker = new DatabaseSync(dbPath);
locker.exec('PRAGMA busy_timeout = 0');
locker.exec('BEGIN IMMEDIATE');
async function holdWriteLock(dbPath: string): Promise<() => Promise<void>> {
const locker = new SqliteDatabase(dbPath, { busyTimeout: 0 });
await locker.exec('BEGIN IMMEDIATE');
let released = false;
return () => {
return async () => {
if (released) {
return;
}
released = true;
locker.exec('ROLLBACK');
locker.close();
await locker.exec('ROLLBACK');
await locker.close();
};
}
@@ -84,21 +84,52 @@ afterEach(() => {
});
describe('IdentityService', () => {
it('persists friends, groups, and active group members', () => {
it('replays observations accepted during loading and drains them when closed before ready', async () => {
const dbPath = tempDbPath('async-startup');
const previous = new IdentityService(SELF_UIN, dbPath);
previous.rememberFriends([{ uin: 22222, uid: 'u_old', nickname: 'old', remark: '' }]);
await previous.close();
let release!: () => void;
const loading = new Promise<void>((resolve) => {
release = resolve;
});
const identity = new IdentityService(SELF_UIN, dbPath, loading);
const friends = [{ uin: 33333, uid: 'u_new', nickname: 'accepted', remark: '' }];
identity.rememberFriends(friends);
friends[0]!.nickname = 'mutated by caller';
expect(identity.findFriend(33333)?.nickname).toBe('accepted');
const closing = identity.close();
expect(() => identity.rememberFriends([])).toThrow(/closed/);
release();
await closing;
const reopened = new IdentityService(SELF_UIN, dbPath);
try {
await reopened.initialization;
expect(reopened.findFriend(22222)).toBeNull();
expect(reopened.findFriend(33333)?.nickname).toBe('accepted');
} finally {
await reopened.close();
}
});
it('persists friends, groups, and active group members', async () => {
const dbPath = tempDbPath('persist');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberFriends([
{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: 'remark' },
]);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_member', 'card')]);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findFriend(22222)?.uid).toBe('u_friend');
expect(identity.findGroup(GROUP_ID)?.groupName).toBe('group');
@@ -106,28 +137,30 @@ describe('IdentityService', () => {
expect(identity.findUidByUin(33333, GROUP_ID)).toBe('u_member');
expect(identity.findUinByUid('u_member', GROUP_ID)).toBe(33333);
identity.close();
await identity.close();
}
});
it('persists group member robot classification across restarts', () => {
it('persists group member robot classification across restarts', async () => {
const dbPath = tempDbPath('persist-robot');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [makeMember(33333, 'u_robot', '', true)]);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBe(true);
identity.close();
await identity.close();
}
});
it('migrates legacy member caches without inventing a robot classification', () => {
it('migrates legacy member caches without inventing a robot classification', async () => {
const dbPath = tempDbPath('migrate-robot');
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const legacy = new DatabaseSync(dbPath);
@@ -177,8 +210,9 @@ describe('IdentityService', () => {
legacy.close();
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, 33333)?.isRobot).toBeUndefined();
identity.close();
await identity.close();
const migrated = new DatabaseSync(dbPath);
const columns = migrated.prepare('PRAGMA table_info(group_members)').all() as Array<{
@@ -188,52 +222,57 @@ describe('IdentityService', () => {
migrated.close();
});
it('keeps updateGroupMember changes after reopening the persistent cache', () => {
it('keeps updateGroupMember changes after reopening the persistent cache', async () => {
const dbPath = tempDbPath('update-member');
const member = makeMember(33333, 'u_member', 'old-card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.updateGroupMember(GROUP_ID, { ...member, card: 'new-card' });
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('new-card');
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('new-card');
identity.close();
await identity.close();
}
});
it('persists an explicitly cleared member card instead of restoring the old value', () => {
it('persists an explicitly cleared member card instead of restoring the old value', async () => {
const dbPath = tempDbPath('clear-member-card');
const member = makeMember(33333, 'u_member', 'old-card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.updateGroupMember(GROUP_ID, { ...member, card: '' });
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('');
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('');
identity.close();
await identity.close();
}
});
it('keeps friend remark updates after reopening the persistent cache', () => {
it('keeps friend remark updates after reopening the persistent cache', async () => {
const dbPath = tempDbPath('update-friend-remark');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberFriends([
{
uin: 22222,
@@ -245,37 +284,40 @@ describe('IdentityService', () => {
expect(identity.updateFriendRemark('u_friend', 22222, 'new-remark')).toBe(true);
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
identity.close();
await identity.close();
}
});
it('keeps exact group remark updates after reopening the persistent cache', () => {
it('keeps exact group remark updates after reopening the persistent cache', async () => {
const dbPath = tempDbPath('update-group-remark');
const remark = ' project group ';
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([{ ...makeGroup(), remark: 'old-remark' }]);
expect(identity.updateGroupRemark(GROUP_ID, remark)).toBe(true);
expect(identity.findGroup(GROUP_ID)?.remark).toBe(remark);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroup(GROUP_ID)?.remark).toBe(remark);
identity.close();
await identity.close();
}
});
it('does not invent a group while applying a remark update', () => {
it('does not invent a group while applying a remark update', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
@@ -283,18 +325,19 @@ describe('IdentityService', () => {
expect(identity.groups).toHaveLength(1);
expect(identity.findGroup(GROUP_ID)?.remark).toBe('');
expect(identity.findGroup(987654321)).toBeNull();
identity.close();
await identity.close();
});
it.each([
['empty', ''],
['whitespace-only', ' '],
['surrounding-whitespace', ' padded remark '],
])('preserves %s friend remarks exactly after reopening', (_label, remark) => {
])('preserves %s friend remarks exactly after reopening', async (_label, remark) => {
const dbPath = tempDbPath('exact-friend-remark');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberFriends([
{
uin: 22222,
@@ -306,13 +349,14 @@ describe('IdentityService', () => {
expect(identity.updateFriendRemark('u_friend', 22222, remark)).toBe(true);
expect(identity.findFriend(22222)?.remark).toBe(remark);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findFriend(22222)?.remark).toBe(remark);
identity.close();
await identity.close();
}
});
@@ -334,7 +378,8 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-recovery');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
let closed = false;
try {
@@ -348,6 +393,7 @@ describe('IdentityService', () => {
]);
expect(identity.findFriend(22222)?.uid).toBe('u_retry');
await expect(identity.flush()).rejects.toThrow(/locked/i);
expect(identity.persistenceStatus).toMatchObject({
state: 'degraded',
pendingWrites: 1,
@@ -358,6 +404,7 @@ describe('IdentityService', () => {
expect(identity.persistenceStatus.nextRetryAt! - Date.now()).toBe(100);
await vi.advanceTimersByTimeAsync(100);
await expect(identity.flush()).rejects.toThrow(/locked/i);
expect(identity.persistenceStatus).toMatchObject({
state: 'degraded',
pendingWrites: 1,
@@ -365,8 +412,9 @@ describe('IdentityService', () => {
});
expect(identity.persistenceStatus.nextRetryAt! - Date.now()).toBe(500);
releaseLock();
await releaseLock();
await vi.advanceTimersByTimeAsync(500);
await identity.flush();
expect(identity.persistenceStatus).toMatchObject({
state: 'healthy',
@@ -374,17 +422,18 @@ describe('IdentityService', () => {
retryAttempt: 0,
nextRetryAt: null,
});
identity.close();
await identity.close();
closed = true;
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findFriend(22222)?.uid).toBe('u_retry');
reopened.close();
await reopened.close();
} finally {
releaseLock();
await releaseLock();
if (!closed) {
identity.close();
await identity.close();
}
}
});
@@ -393,7 +442,8 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-order');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
let closed = false;
try {
@@ -418,20 +468,21 @@ describe('IdentityService', () => {
expect(identity.findFriend(11111)).toBeNull();
expect(identity.findFriend(22222)?.uid).toBe('u_second');
releaseLock();
await releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
closed = true;
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findFriend(11111)).toBeNull();
expect(reopened.findFriend(22222)?.uid).toBe('u_second');
reopened.close();
await reopened.close();
} finally {
releaseLock();
await releaseLock();
if (!closed) {
identity.close();
await identity.close();
}
}
});
@@ -440,10 +491,12 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-snapshot');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const member = makeMember(33333, 'u_member', 'before');
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
const releaseLock = holdWriteLock(dbPath);
await identity.flush();
const releaseLock = await holdWriteLock(dbPath);
const observed = { ...member, card: 'accepted' };
try {
@@ -451,16 +504,17 @@ describe('IdentityService', () => {
observed.card = 'caller-mutated';
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('accepted');
releaseLock();
await releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findGroupMember(GROUP_ID, member.uin)?.card).toBe('accepted');
reopened.close();
await reopened.close();
} finally {
releaseLock();
identity.close();
await releaseLock();
await identity.close();
}
});
@@ -468,10 +522,12 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('pending-member-group-refresh');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const member = makeMember(33333, 'u_member', 'persisted-card');
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
const releaseLock = holdWriteLock(dbPath);
await identity.flush();
const releaseLock = await holdWriteLock(dbPath);
try {
identity.updateGroupMember(GROUP_ID, { ...member, card: 'pending-card' });
@@ -480,17 +536,18 @@ describe('IdentityService', () => {
expect(identity.findGroup(GROUP_ID)?.groupName).toBe('refreshed-group');
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('pending-card');
releaseLock();
await releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findGroup(GROUP_ID)?.groupName).toBe('refreshed-group');
expect(reopened.findGroupMember(GROUP_ID, member.uin)?.card).toBe('pending-card');
reopened.close();
await reopened.close();
} finally {
releaseLock();
identity.close();
await releaseLock();
await identity.close();
}
});
@@ -498,9 +555,11 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('pending-rebind');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberRequestIdentity({ uid: 'u_old_for_uin', uin: 22001 });
identity.rememberRequestIdentity({ uid: 'u_stable', uin: 22002 });
const releaseLock = holdWriteLock(dbPath);
await identity.flush();
const releaseLock = await holdWriteLock(dbPath);
try {
identity.rememberRequestIdentity({ uid: 'u_new_for_uin', uin: 22001 });
@@ -511,17 +570,18 @@ describe('IdentityService', () => {
expect(identity.findUinByUid('u_old_for_uin')).toBeNull();
expect(identity.findUidByUin(22002)).toBeNull();
releaseLock();
await releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findUidByUin(22001)).toBe('u_new_for_uin');
expect(reopened.findUinByUid('u_stable')).toBe(22999);
reopened.close();
await reopened.close();
} finally {
releaseLock();
identity.close();
await releaseLock();
await identity.close();
}
});
@@ -529,7 +589,8 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-capacity');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
try {
const capacity = identity.persistenceStatus.queueCapacity;
@@ -561,9 +622,9 @@ describe('IdentityService', () => {
});
expect(identity.persistenceStatus.lastError).toMatch(/queue full/i);
} finally {
releaseLock();
await releaseLock();
await vi.runOnlyPendingTimersAsync();
identity.close();
await identity.close();
}
});
@@ -571,7 +632,8 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-exhausted');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
const seen: Array<{ level: string; message: string }> = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'Identity' && entry.uin === Number(SELF_UIN)) {
@@ -590,8 +652,11 @@ describe('IdentityService', () => {
]);
identity.rememberRequestIdentity({ uid: 'u_abandoned_request', uin: 33333 });
await expect(identity.flush()).rejects.toThrow(/locked/i);
for (const delay of [100, 500, 2_000, 10_000, 30_000]) {
await vi.advanceTimersByTimeAsync(delay);
await identity.flush().catch(() => undefined);
}
expect(identity.persistenceStatus).toMatchObject({
@@ -655,10 +720,11 @@ describe('IdentityService', () => {
expect(skipLogs).toHaveLength(2);
expect(skipLogs[1]?.message).toMatch(/suppressed=50/);
releaseLock();
identity.close();
await releaseLock();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.persistenceStatus).toMatchObject({
state: 'healthy',
suspended: false,
@@ -668,23 +734,25 @@ describe('IdentityService', () => {
expect(reopened.findUinByUid('u_abandoned_request')).toBeNull();
expect(reopened.findUinByUid('u_skipped_after_suspend')).toBeNull();
reopened.rememberRequestIdentity({ uid: 'u_after_restart', uin: 55555 });
reopened.close();
await reopened.close();
const persisted = new IdentityService(SELF_UIN, dbPath);
await persisted.initialization;
expect(persisted.findUinByUid('u_after_restart')).toBe(55555);
persisted.close();
await persisted.close();
} finally {
unsubscribe();
releaseLock();
identity.close();
await releaseLock();
await identity.close();
}
});
it('flushes pending writes synchronously during close when SQLite has recovered', () => {
it('flushes pending writes during asynchronous close when SQLite has recovered', async () => {
vi.useFakeTimers();
const dbPath = tempDbPath('close-flush');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
identity.rememberFriends([
{
@@ -696,8 +764,8 @@ describe('IdentityService', () => {
]);
expect(identity.persistenceStatus.pendingWrites).toBe(1);
releaseLock();
identity.close();
await releaseLock();
await identity.close();
expect(identity.persistenceStatus).toMatchObject({
state: 'closed',
@@ -707,15 +775,17 @@ describe('IdentityService', () => {
});
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findFriend(22222)?.uid).toBe('u_close_flush');
reopened.close();
await reopened.close();
});
it('warns and releases pending retry work when close cannot flush SQLite', () => {
it('warns and releases pending retry work when close cannot flush SQLite', async () => {
vi.useFakeTimers();
const dbPath = tempDbPath('close-pending');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
const seen: Array<{ level: string; message: string }> = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'Identity' && entry.uin === Number(SELF_UIN)) {
@@ -734,7 +804,7 @@ describe('IdentityService', () => {
]);
expect(identity.persistenceStatus.pendingWrites).toBe(1);
identity.close();
await identity.close();
expect(identity.persistenceStatus).toMatchObject({
state: 'closed',
@@ -754,8 +824,8 @@ describe('IdentityService', () => {
);
} finally {
unsubscribe();
releaseLock();
identity.close();
await releaseLock();
await identity.close();
}
});
@@ -763,8 +833,9 @@ describe('IdentityService', () => {
vi.useFakeTimers();
const dbPath = tempDbPath('close-failure');
const identity = new IdentityService(SELF_UIN, dbPath);
const releaseLock = holdWriteLock(dbPath);
const database = (identity as unknown as { db: DatabaseSync }).db;
await identity.initialization;
const releaseLock = await holdWriteLock(dbPath);
const database = (identity as unknown as { db: SqliteDatabase }).db;
const closeSpy = vi.spyOn(database, 'close').mockImplementationOnce(() => {
throw new Error('injected close failure');
});
@@ -780,7 +851,8 @@ describe('IdentityService', () => {
]);
expect(identity.persistenceStatus.pendingWrites).toBe(1);
expect(() => identity.close()).toThrow(/injected close failure/);
await expect(identity.flush()).rejects.toThrow(/locked/i);
await expect(identity.close()).rejects.toThrow(/injected close failure/);
expect(identity.persistenceStatus).toMatchObject({
state: 'degraded',
pendingWrites: 1,
@@ -799,31 +871,33 @@ describe('IdentityService', () => {
expect(identity.persistenceStatus.pendingWrites).toBe(2);
closeSpy.mockRestore();
releaseLock();
await releaseLock();
await vi.runOnlyPendingTimersAsync();
await identity.flush();
expect(identity.persistenceStatus).toMatchObject({
state: 'healthy',
pendingWrites: 0,
});
identity.close();
await identity.close();
const reopened = new IdentityService(SELF_UIN, dbPath);
await reopened.initialization;
expect(reopened.findFriend(22222)?.uid).toBe('u_close_retry_friend');
expect(reopened.findUinByUid('u_after_close_failure')).toBe(33333);
reopened.close();
await reopened.close();
} finally {
closeSpy.mockRestore();
releaseLock();
identity.close();
await releaseLock();
await identity.close();
}
});
it('fails fast on every observation entry point after close', () => {
it('fails fast on every observation entry point after close', async () => {
const identity = IdentityService.memory(SELF_UIN);
const member = makeMember(33333, 'u_member', 'before-close');
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.close();
await identity.close();
const profile: UserProfileInfo = {
uin: 44444,
@@ -916,39 +990,41 @@ describe('IdentityService', () => {
expect(identity.findUinByUid('u_request')).toBeNull();
});
it('does not treat identity-only sightings as live group members', () => {
it('does not treat identity-only sightings as live group members', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_seen', uin: 88888 });
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
expect(identity.findUinByUid('u_seen')).toBe(88888);
identity.close();
await identity.close();
});
it('does not hydrate identity-only sightings as live members after reopen', () => {
it('does not hydrate identity-only sightings as live members after reopen', async () => {
const dbPath = tempDbPath('identity-only-not-roster');
const member = makeMember(33333, 'u_member', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_operator', uin: 88888 });
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('card');
expect(identity.findGroupMember(GROUP_ID, 88888)).toBeNull();
expect(identity.findUinByUid('u_operator')).toBe(88888);
identity.close();
await identity.close();
}
});
it('records a thin live member on join without inventing roster details', () => {
it('records a thin live member on join without inventing roster details', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const existing = makeMember(33333, 'u_existing', 'card');
@@ -968,23 +1044,25 @@ describe('IdentityService', () => {
});
expect(joined?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
identity.close();
await identity.close();
});
it('persists a thin live member on join across reopen', () => {
it('persists a thin live member on join across reopen', async () => {
const dbPath = tempDbPath('join-live-roster');
const existing = makeMember(33333, 'u_existing', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [existing]);
identity.rememberGroupMemberJoined(GROUP_ID, { uid: 'u_join', uin: 44444 });
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
const joined = identity.findGroupMember(GROUP_ID, 44444);
expect(joined).toMatchObject({
uin: 44444,
@@ -995,11 +1073,11 @@ describe('IdentityService', () => {
});
expect(joined?.isRobot).toBeUndefined();
expect(identity.findGroupMember(GROUP_ID, 33333)?.card).toBe('card');
identity.close();
await identity.close();
}
});
it('drops a leaver from the live roster and keeps their identity mapping', () => {
it('drops a leaver from the live roster and keeps their identity mapping', async () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
const member = makeMember(33333, 'u_member', 'card');
@@ -1009,61 +1087,66 @@ describe('IdentityService', () => {
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
await identity.close();
});
it('keeps a leaver out of the live roster after reopen', () => {
it('keeps a leaver out of the live roster after reopen', async () => {
const dbPath = tempDbPath('leave-live-roster');
const member = makeMember(33333, 'u_member', 'card');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
await identity.close();
}
});
it('marks missing members inactive only after a successful full refresh', () => {
it('marks missing members inactive only after a successful full refresh', async () => {
const dbPath = tempDbPath('inactive-refresh');
const first = makeMember(33333, 'u_first');
const second = makeMember(44444, 'u_second');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [first, second]);
identity.rememberGroupMembers(GROUP_ID, [second]);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, first.uin)).toBeNull();
expect(identity.findGroupMember(GROUP_ID, second.uin)?.uid).toBe(second.uid);
// Historical identity remains available for UID/UIN resolution.
expect(identity.findUidByUin(first.uin, GROUP_ID)).toBe(first.uid);
identity.close();
await identity.close();
}
});
it('marks missing friends and groups inactive after successful full refreshes', () => {
it('marks missing friends and groups inactive after successful full refreshes', async () => {
const dbPath = tempDbPath('inactive-lists');
const member = makeMember(33333, 'u_member');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberFriends([
{ uin: 22222, uid: 'u_friend', nickname: 'friend', remark: '' },
]);
@@ -1071,11 +1154,12 @@ describe('IdentityService', () => {
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.rememberFriends([]);
identity.rememberGroups([]);
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findFriend(22222)).toBeNull();
expect(identity.findGroup(GROUP_ID)).toBeNull();
@@ -1083,37 +1167,40 @@ describe('IdentityService', () => {
expect(identity.findUidByUin(22222)).toBe('u_friend');
expect(identity.findUidByUin(member.uin, GROUP_ID)).toBe(member.uid);
identity.close();
await identity.close();
}
});
it('can mark one member inactive without losing the identity mapping', () => {
it('can mark one member inactive without losing the identity mapping', async () => {
const dbPath = tempDbPath('inactive-event');
const member = makeMember(33333, 'u_member');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberGroups([makeGroup()]);
identity.rememberGroupMembers(GROUP_ID, [member]);
identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin });
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findGroupMember(GROUP_ID, member.uin)).toBeNull();
expect(identity.findUinByUid(member.uid, GROUP_ID)).toBe(member.uin);
identity.close();
await identity.close();
}
});
it('persists identities learned from request events', () => {
it('persists identities learned from request events', async () => {
const dbPath = tempDbPath('request-events');
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.rememberRequestIdentity({
uid: 'u_friend_request',
uin: 55555,
@@ -1125,18 +1212,19 @@ describe('IdentityService', () => {
uin: 66666,
source: 'group_request',
});
identity.close();
await identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
expect(identity.findUidByUin(55555)).toBe('u_friend_request');
expect(identity.findUinByUid('u_friend_request')).toBe(55555);
expect(identity.findGroup(GROUP_ID)).toBeNull();
expect(identity.findUidByUin(66666)).toBe('u_group_request');
identity.close();
await identity.close();
}
});
});
@@ -1369,6 +1457,7 @@ describe('IdentityService inbound UID→UIN', () => {
it('does not enter Identity degraded when the inbound fetcher throws', async () => {
const dbPath = tempDbPath('inbound-fetch-throw');
const identity = new IdentityService(SELF_UIN, dbPath);
await identity.initialization;
identity.setFetcher({
fetchProfile: async () => makeProfile(0, ''),
fetchProfileByUid: async () => {
@@ -1379,6 +1468,6 @@ describe('IdentityService inbound UID→UIN', () => {
await expect(identity.resolveUin('u_none')).resolves.toBeNull();
expect(identity.persistenceStatus.state).toBe('healthy');
expect(identity.persistenceStatus.pendingWrites).toBe(0);
identity.close();
await identity.close();
});
});
@@ -0,0 +1,63 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { RuntimeIntegrity } from '@snowluma/bridge';
import { redactLogMessage } from '@snowluma/common/log-summary';
const log = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn() }));
vi.mock('@snowluma/common/logger', () => ({ createLogger: () => log }));
import { logRuntimeIntegrity } from '../src/runtime-integrity-log';
const sample: Extract<RuntimeIntegrity, { status: 'available' }> = {
status: 'available',
pid: 123,
executablePath: 'C:\\private\\node.exe',
process: { status: 'ok', rid: 8192 },
file: { status: 'ok', label: null },
};
beforeEach(() => vi.clearAllMocks());
describe('startup integrity log', () => {
it('writes one readable line with the token level and unlabeled file', () => {
logRuntimeIntegrity(sample);
expect(log.info).toHaveBeenCalledExactlyOnceWith(
'Node integrity: pid=123, process=Medium (RID=8192); EXE=unlabeled',
);
expect(redactLogMessage(log.info.mock.calls[0]![0])).toContain('process=Medium (RID=8192)');
expect(log.warn).not.toHaveBeenCalled();
expect(log.info.mock.calls.flat().join(' ')).not.toContain('private');
});
it('writes one warning with Low token and inherited EXE details', () => {
logRuntimeIntegrity({
...sample,
process: { status: 'ok', rid: 4096 },
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
});
expect(log.warn).toHaveBeenCalledExactlyOnceWith(
'Node integrity: pid=123, process=Low (RID=4096); EXE=Low (RID=4096), inherited=true, policy=1',
);
expect(redactLogMessage(log.warn.mock.calls[0]![0])).toContain('process=Low (RID=4096)');
expect(log.info).not.toHaveBeenCalled();
});
it('preserves read failures while still reporting the successful part', () => {
logRuntimeIntegrity({
...sample,
file: { status: 'error', operation: 'GetNamedSecurityInfoW', code: 5 },
});
expect(log.warn).toHaveBeenCalledExactlyOnceWith(
'Node integrity: pid=123, process=Medium (RID=8192); EXE=unknown (GetNamedSecurityInfoW, Win32=5)',
);
});
it('logs unavailable diagnostics once and skips unsupported platforms', () => {
logRuntimeIntegrity({ status: 'unsupported' });
expect(log.info).not.toHaveBeenCalled();
expect(log.warn).not.toHaveBeenCalled();
logRuntimeIntegrity({ status: 'unavailable', error: 'addon unavailable' });
expect(log.warn).toHaveBeenCalledExactlyOnceWith(
'Node integrity: unknown (%s)',
'addon unavailable',
);
});
});
@@ -10,16 +10,15 @@ const { SUPPORTED_NODE_RANGE, isSupportedNodeVersion } =
describe('runtime Node.js preflight', () => {
it('accepts the documented minimum and newer versions', () => {
expect(SUPPORTED_NODE_RANGE).toBe('^22.13.0 || >=23.4.0');
expect(isSupportedNodeVersion('22.13.0')).toBe(true);
expect(isSupportedNodeVersion('22.13.1')).toBe(true);
expect(isSupportedNodeVersion('23.4.0')).toBe(true);
expect(SUPPORTED_NODE_RANGE).toBe('>=24');
expect(isSupportedNodeVersion('24.0.0')).toBe(true);
expect(isSupportedNodeVersion('24.21.0')).toBe(true);
expect(isSupportedNodeVersion('26.0.0')).toBe(true);
});
it('rejects older and malformed versions', () => {
expect(isSupportedNodeVersion('22.12.99')).toBe(false);
expect(isSupportedNodeVersion('23.3.99')).toBe(false);
expect(isSupportedNodeVersion('22.99.99')).toBe(false);
expect(isSupportedNodeVersion('23.99.99')).toBe(false);
expect(isSupportedNodeVersion('21.99.99')).toBe(false);
expect(isSupportedNodeVersion('not-a-version')).toBe(false);
});