refactor: use native async discovery and simplify shared state

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:57:18 +08:00
1 parent 5032cbb8c0
commit 4e2b6b1200
87 files changed
+2063 -2002

No files matched your search

+28 -68
View File
@@ -1,12 +1,12 @@
import { errorMessage } from '@snowluma/common/errors';
import { resolveRuntimeNativePath } from '@snowluma/common/native-path';
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { createLogger } from '@snowluma/common/logger';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const log = createLogger('Highway.Audio');
export interface FFmpegVideoInfo {
@@ -42,46 +42,10 @@ interface FFmpegNativeAddon {
let cachedAddon: FFmpegNativeAddon | null = null;
let cachedLoadError: string | null = null;
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function addonFileName(): string {
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
}
function addonSearchDirs(): string[] {
// Mirrors the hook injector's resolution strategy so the addon is found
// regardless of whether we're running from:
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
// the dist root.
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
// __dirname is `packages/core/src/bridge/highway` — four levels deep
// under `packages/`. Note: the hook injector lives at
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
return [
path.resolve(__dirname, 'native', 'ffmpeg'),
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
];
}
function resolveAddonPath(): string | null {
const fileName = addonFileName();
for (const dir of addonSearchDirs()) {
const full = path.join(dir, fileName);
if (fs.existsSync(full)) {
return full;
}
}
return null;
}
/**
* Load the ffmpegAddon once and return a cached instance.
* Throws on first-use failure; subsequent calls replay the same error message
@@ -96,7 +60,7 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
throw new Error(cachedLoadError);
}
const addonPath = resolveAddonPath();
const addonPath = resolveRuntimeNativePath(path.join('ffmpeg', addonFileName()));
if (!addonPath) {
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
@@ -121,19 +85,14 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
* a ready-to-upload silk file.
*/
export function isSilkFile(filePath: string): boolean {
try {
const fd = fs.openSync(filePath, 'r');
const fd = fs.openSync(filePath, 'r');
try {
const buf = Buffer.alloc(10);
fs.readSync(fd, buf, 0, 10, 0);
const header = buf.toString();
return header.includes('#!SILK') || header.includes('\x02#!SILK');
} finally {
fs.closeSync(fd);
}
} catch {
return false;
try {
const buf = Buffer.alloc(10);
fs.readSync(fd, buf, 0, 10, 0);
return buf.toString().includes('#!SILK');
} finally {
fs.closeSync(fd);
}
}
@@ -153,33 +112,34 @@ export interface EncodeSilkResult {
*/
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
const addon = getFFmpegAddon();
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
// Already silk — trust the file, just measure duration via the addon.
if (isSilkFile(inputFile)) {
let duration = 1;
try {
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
} catch {
// getDuration on a silk file occasionally fails on certain encodings;
// the upload path only needs a rough, non-zero value, so fall back
// to the size-based heuristic used by NapCat's audio.ts.
const stat = fs.statSync(inputFile);
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
}
return { path: inputFile, duration, converted: false };
}
fs.mkdirSync(tempDir, { recursive: true });
const outPath = path.join(tempDir, crypto.randomUUID());
await addon.convertToNTSilkTct(inputFile, outPath);
if (!fs.existsSync(outPath)) {
throw new Error('convertToNTSilkTct produced no output file');
try {
await addon.convertToNTSilkTct(inputFile, outPath);
if (!fs.existsSync(outPath)) {
throw new Error('convertToNTSilkTct produced no output file');
}
} catch (error) {
try {
await fs.promises.rm(outPath, { force: true });
} catch (cleanupError) {
throw new AggregateError(
[error, cleanupError],
`SILK conversion failed: ${errorMessage(error)}; temporary file cleanup failed: ${errorMessage(cleanupError)}`,
);
}
throw error;
}
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
return { path: outPath, duration, converted: true };
}
+2 -5
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
import type {
EncodableMediaMsgInfo,
@@ -136,10 +137,6 @@ function uploadDescriptors(uploads: MediaSubFileUpload[]): string {
.join(';')}]`;
}
function mediaErrorText(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
// ─────────────── main entrypoint ───────────────
/**
@@ -191,7 +188,7 @@ export function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespB
label,
failureReason,
params.uploads.length,
mediaErrorText(error),
errorMessage(error),
Date.now() - startedAt,
]);
throw error;
+1 -1
View File
@@ -1766,7 +1766,7 @@ export class IdentityService {
this.recordPersistenceFailure('retry', error),
);
}, delay);
this.retryTimer_.unref?.();
this.retryTimer_.unref();
}
private flushPendingWrites(scheduleRetry = true): Promise<void> {
@@ -0,0 +1,86 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@snowluma/common/native-path', () => ({
resolveRuntimeNativePath: () => '/test/ffmpeg.node',
}));
const addon = {
getDuration: vi.fn<(file: string) => Promise<number>>(),
convertToNTSilkTct: vi.fn<(input: string, output: string) => Promise<void>>(),
};
let root: string;
beforeEach(() => {
vi.resetModules();
addon.getDuration.mockReset().mockResolvedValue(2.5);
addon.convertToNTSilkTct.mockReset().mockImplementation(async (_input, output) => {
await fs.promises.writeFile(output, '\x02#!SILK_V3payload');
});
vi.spyOn(process, 'dlopen').mockImplementation((module) => {
(module as { exports: object }).exports = addon;
});
root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-encode-silk-'));
});
afterEach(() => {
vi.restoreAllMocks();
fs.rmSync(root, { recursive: true, force: true });
});
describe('SILK encoding', () => {
it('rejects unreadable files instead of treating them as a different audio format', async () => {
const { isSilkFile } = await import('../../src/highway/ffmpeg-addon');
expect(() => isSilkFile(path.join(root, 'missing'))).toThrow(/ENOENT/);
});
it('keeps native duration failures visible instead of guessing from SILK file size', async () => {
const input = path.join(root, 'invalid.silk');
fs.writeFileSync(input, '#!SILK_V3truncated');
const failure = new Error('truncated SILK packet');
addon.getDuration.mockRejectedValue(failure);
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
await expect(encodeSilk(input, root)).rejects.toBe(failure);
expect(addon.convertToNTSilkTct).not.toHaveBeenCalled();
expect(fs.readdirSync(root)).toEqual(['invalid.silk']);
});
it('reuses a valid SILK input without creating a temporary file', async () => {
const input = path.join(root, 'voice.silk');
fs.writeFileSync(input, '\x02#!SILK_V3payload');
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
await expect(encodeSilk(input, root)).resolves.toEqual({
path: input,
duration: 3,
converted: false,
});
expect(addon.convertToNTSilkTct).not.toHaveBeenCalled();
});
it('returns the converted file for caller-owned cleanup', async () => {
const input = path.join(root, 'voice.wav');
fs.writeFileSync(input, 'RIFF');
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
const result = await encodeSilk(input, root);
expect(result.converted).toBe(true);
expect(result.duration).toBe(3);
expect(fs.readFileSync(result.path, 'utf8')).toBe('\x02#!SILK_V3payload');
expect(addon.convertToNTSilkTct).toHaveBeenCalledWith(input, result.path);
});
it('removes partial output when native conversion fails, preserving the source and error', async () => {
const input = path.join(root, 'voice.wav');
fs.writeFileSync(input, 'RIFF');
const failure = new Error('conversion interrupted');
addon.convertToNTSilkTct.mockImplementation(async (_input, output) => {
await fs.promises.writeFile(output, 'partial');
throw failure;
});
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
await expect(encodeSilk(input, root)).rejects.toBe(failure);
expect(fs.readdirSync(root)).toEqual(['voice.wav']);
expect(fs.readFileSync(input, 'utf8')).toBe('RIFF');
});
});
@@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
import { convertAudioBytes, encodeSilk } from '@snowluma/protocol/highway/ffmpeg-addon';
interface NativeAudioAddon {
convertToNTSilkTct(inputFile: string, outputFile: string): Promise<void>;
@@ -111,9 +111,20 @@ describeBundledAddon('bundled native ffmpeg addon', () => {
);
await expect(addon.getDuration(recordPath)).rejects.toThrow(/Invalid data/);
await expect(encodeSilk(recordPath, tmpDir)).rejects.toThrow(/Invalid data/);
});
});
it('encodes a WAV with the runtime addon when started from the protocol package', async () => {
const wavPath = path.join(tmpDir, 'runtime-input.wav');
writeFileSync(wavPath, makeMonoWav());
const result = await encodeSilk(wavPath, tmpDir);
expect(result.converted).toBe(true);
expect(result.duration).toBe(1);
expect(readFileSync(result.path).subarray(1, 10).toString('ascii')).toBe('#!SILK_V3');
expect(await loadBundledAddon().getDuration(result.path)).toBeCloseTo(1, 6);
});
it('converts a mono QQ-style SILK record to a decodable MP3 through the public transcode seam', async () => {
const addon = loadBundledAddon();
const wavPath = path.join(tmpDir, 'mono-input.wav');