refactor: replace polling with event-driven updates

Trigger account detection and group requests from observed changes. Remove native stage log forwarding and its lifecycle state, and simplify the README.
This commit is contained in:
手瓜一十雪 committed 2026-10-19 09:56:20 +08:00
1 parent 1b74747251
commit e5cfec01bd
33 files changed
+1314 -1958

No files matched your search

+41 -4
View File
@@ -581,11 +581,48 @@ export class ContactsApi {
return requests;
}
/** Live observation write. IncomingPacketPipeline and tests only. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
if (groupUin > 0 && sequence > 0) {
this.groupInviteCardSeqs_.set(groupUin, sequence);
async resolveGroupJoinRequest(
groupId: number,
uid: string,
subType: 'add' | 'invite',
invitedUid?: string,
): Promise<GroupRequestInfo | null> {
const [main, filtered] = await Promise.allSettled([
this.fetchGroupRequestsByUid(false),
this.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
throw main.reason;
}
if (filtered.status === 'rejected') {
throw filtered.reason;
}
return (
[...main.value, ...filtered.value].find((request) => {
if (request.groupId !== groupId || request.state !== 1) {
return false;
}
return subType === 'add'
? request.eventType === 1 && request.targetUid === uid
: (request.eventType === 2 || request.eventType === 22) &&
request.invitorUid === uid &&
request.targetUid === invitedUid;
}) ?? null
);
}
/** Returns whether this live card introduces a new approval sequence. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): boolean {
if (this.groupInviteCardSeqs_.get(groupUin) === sequence) {
return false;
}
this.groupInviteCardSeqs_.set(groupUin, sequence);
return true;
}
/** The approval msgseq captured from a private "qun.invite" card for this
+4 -66
View File
@@ -61,72 +61,10 @@ export class Bridge implements BridgeInterface {
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequestsByUid(false),
this.apis.contacts.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
log.warn(
'group-request enrichment main inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
main.reason instanceof Error ? main.reason.message : String(main.reason),
);
}
if (filtered.status === 'rejected') {
log.warn(
'group-request enrichment filtered inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
filtered.reason instanceof Error
? filtered.reason.message
: String(filtered.reason),
);
}
if (main.status === 'rejected' && filtered.status === 'rejected') {
throw new Error('failed to fetch group requests from both inboxes');
}
const requests = [
...(main.status === 'fulfilled' ? main.value : []),
...(filtered.status === 'fulfilled' ? filtered.value : []),
];
const matches = requests.filter((r) => {
if (r.groupId !== groupId) {
return false;
}
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (subType === 'invite') {
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
}
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
},
resolveGroupInviteCardSequence: async (groupId) => {
const deadline = Date.now() + 1_000;
do {
const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId);
if (sequence) {
return sequence;
}
await new Promise((resolve) => setTimeout(resolve, 25));
} while (Date.now() < deadline);
return null;
},
rememberGroupInviteCardSequence: (groupUin, sequence) => {
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
},
resolveGroupJoinRequest: (groupId, uid, subType, invitedUid) =>
this.apis.contacts.resolveGroupJoinRequest(groupId, uid, subType, invitedUid),
rememberGroupInviteCardSequence: (groupUin, sequence) =>
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence),
});
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) =>
parseMsgPushOrThrow(pkt, identity, this.sysMsgDedup_),
-17
View File
@@ -1,5 +1,4 @@
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
import { APP_VERSION } from '@snowluma/common/version';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import {
@@ -23,7 +22,6 @@ import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
import { initWebUI } from './webui/server';
import { bindSystemFaceCatalog } from './sys-face-catalog';
import { startNativeStageSync, tempStagePath } from './native-stage-sync';
import { logRuntimeIntegrity } from './runtime-integrity-log';
import { RESTART_EXIT_CODE, runApplication } from './update/startup';
@@ -60,11 +58,6 @@ async function main() {
});
log.info('SnowLuma starting');
logRuntimeIntegrity(await getRuntimeIntegrity());
const stopNativeStageSync = startNativeStageSync({
version: APP_VERSION,
dataDir: 'data',
tempPath: tempStagePath(),
});
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
// any session (and thus any per-UIN config rewrite) can drop it.
@@ -193,16 +186,6 @@ async function main() {
);
}
try {
stopNativeStageSync.stop();
} catch (error) {
exitCode = 1;
log.error(
'stage sync shutdown failed: %s',
error instanceof Error ? error.message : String(error),
);
}
try {
hookManager.dispose();
} catch (error) {
-347
View File
@@ -1,347 +0,0 @@
import {
readFileSync,
writeFileSync,
mkdirSync,
statSync,
openSync,
readSync,
closeSync,
fstatSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createLogger, type Logger } from '@snowluma/common/logger';
export const STAGE_FILE_NAME = 's7.log';
export const MIRROR_LIMIT_BYTES = 1024 * 1024;
const VERSION_HEADER = /^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
export function isVersionHeader(line: string): boolean {
return VERSION_HEADER.test(line);
}
export function lineSeverity(line: string): 'info' | 'error' {
const parts = line.trim().split(/\s+/);
return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info';
}
export function publicLine(version: string, raw: string): string {
return `${version} ${raw.trim()}`;
}
function byteSize(lines: readonly string[]): number {
if (lines.length === 0) {
return 0;
}
return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8');
}
export function trimMirror(text: string, limit = MIRROR_LIMIT_BYTES): string {
const lines = text.split('\n').filter((line) => line.length > 0);
const size = () => byteSize(lines);
while (lines.length > 0 && size() > limit) {
const body = lines.findIndex((line) => !isVersionHeader(line));
if (body >= 0) {
lines.splice(body, 1);
continue;
}
if (lines.length <= 1) {
break;
}
lines.shift();
}
if (lines.length === 0) {
return '';
}
return `${lines.join('\n')}\n`;
}
export function appendEvents(
mirror: string,
version: string,
events: readonly string[],
limit = MIRROR_LIMIT_BYTES,
): string {
const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0);
if (fresh.length === 0) {
return mirror;
}
const header = `v${version}`;
const lines = mirror.split('\n').filter((line) => line.length > 0);
let lastHeader = '';
for (const line of lines) {
if (isVersionHeader(line)) {
lastHeader = line;
}
}
const next = [...lines];
if (lastHeader !== header) {
next.push(header);
}
next.push(...fresh);
return trimMirror(`${next.join('\n')}\n`, limit);
}
export function tempStagePath(
platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): string {
if (platform === 'win32') {
const base = env.TMP || env.TEMP || os.tmpdir();
return path.join(base, STAGE_FILE_NAME);
}
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
}
export function errorCode(error: unknown): string {
if (error && typeof error === 'object' && 'code' in error) {
const code = (error as { code?: unknown }).code;
if (typeof code === 'string' && code) {
return code;
}
}
return 'ERR';
}
export interface StageSyncOptions {
version: string;
dataDir: string;
tempPath: string;
log?: Logger;
intervalMs?: number;
}
interface IngestResult {
mirror: string;
offset: number;
lines: string[];
missing: boolean;
errorCode?: string;
}
export function ingestTemp(args: {
tempText: string;
offset: number;
mirror: string;
version: string;
missing?: boolean;
errorCode?: string;
}): IngestResult {
if (args.missing) {
return { mirror: args.mirror, offset: args.offset, lines: [], missing: true };
}
if (args.errorCode) {
return {
mirror: args.mirror,
offset: args.offset,
lines: [],
missing: false,
errorCode: args.errorCode,
};
}
const start = args.offset > args.tempText.length ? 0 : args.offset;
const chunk = args.tempText.slice(start);
const newline = chunk.lastIndexOf('\n');
if (newline < 0) {
return { mirror: args.mirror, offset: start, lines: [], missing: false };
}
const complete = chunk.slice(0, newline + 1);
const lines = complete
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
return {
mirror: appendEvents(args.mirror, args.version, lines),
offset: start + newline + 1,
lines,
missing: false,
};
}
function readOffset(file: string): number {
try {
const raw = readFileSync(file, 'utf8').trim();
const value = Number(raw);
return Number.isSafeInteger(value) && value >= 0 ? value : 0;
} catch {
return 0;
}
}
function readTemp(file: string): { text: string; missing: boolean; errorCode?: string } {
let fd: number | undefined;
try {
fd = openSync(file, 'r');
const info = fstatSync(fd);
const size = info.size;
if (size > 8 * 1024 * 1024) {
return { text: '', missing: false, errorCode: 'E2BIG' };
}
const buf = Buffer.alloc(size);
let got = 0;
while (got < size) {
const n = readSync(fd, buf, got, size - got, got);
if (n <= 0) {
break;
}
got += n;
}
return { text: buf.subarray(0, got).toString('utf8'), missing: false };
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
return { text: '', missing: true };
}
return { text: '', missing: false, errorCode: code };
} finally {
if (fd !== undefined) {
closeSync(fd);
}
}
}
export function startNativeStageSync(options: StageSyncOptions): { stop: () => void } {
const log = options.log ?? createLogger('native');
const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME);
const offsetPath = path.join(options.dataDir, 's7.off');
let offset = readOffset(offsetPath);
let failed = false;
let stopped = false;
const tick = () => {
if (stopped) {
return;
}
let tempSize = 0;
try {
tempSize = statSync(options.tempPath).size;
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
return;
}
if (!failed) {
failed = true;
log.error('sync failed %s', code);
}
return;
}
if (tempSize < offset) {
offset = 0;
}
const temp = readTemp(options.tempPath);
if (temp.missing) {
return;
}
if (temp.errorCode) {
if (!failed) {
failed = true;
log.error('sync failed %s', temp.errorCode);
}
return;
}
let mirror = '';
try {
mirror = readFileSync(mirrorPath, 'utf8');
} catch (error) {
if (errorCode(error) !== 'ENOENT') {
if (!failed) {
failed = true;
log.error('sync failed %s', errorCode(error));
}
return;
}
}
const ingested = ingestTemp({
tempText: temp.text,
offset,
mirror,
version: options.version,
});
if (ingested.lines.length === 0 && ingested.offset === offset) {
failed = false;
return;
}
try {
mkdirSync(options.dataDir, { recursive: true });
writeFileSync(mirrorPath, ingested.mirror);
writeFileSync(offsetPath, `${ingested.offset}\n`);
offset = ingested.offset;
failed = false;
} catch (error) {
if (!failed) {
failed = true;
log.error('sync failed %s', errorCode(error));
}
return;
}
for (const line of ingested.lines) {
const text = publicLine(options.version, line);
if (lineSeverity(line) === 'error') {
log.error('%s', text);
} else {
log.info('%s', text);
}
}
};
tick();
const timer = setInterval(tick, options.intervalMs ?? 500);
timer.unref();
return {
stop() {
stopped = true;
clearInterval(timer);
},
};
}