143 lines
6.6 KiB
TypeScript
143 lines
6.6 KiB
TypeScript
import { test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { EventEmitter } from 'node:events';
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { Store } from '../src/core/db/db.ts';
|
|
import { Timeline } from '../src/core/timeline.ts';
|
|
import { Bus } from '../src/core/util/events.ts';
|
|
import { SttPipeline } from '../src/core/stt/pipeline.ts';
|
|
import { WorkerError } from '../src/core/stt/worker.ts';
|
|
import { TrayShell } from '../src/main/tray-shell.ts';
|
|
|
|
test('앱 종료: 변환 중이던 작업이 워커 종료로 실패해도 닫힌 DB 를 건드리지 않고, 남은 작업을 꺼내지 않는다', async () => {
|
|
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
|
|
const store = new Store(path.join(dir, 'db.sqlite'));
|
|
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
|
for (const id of ['s1', 's2']) {
|
|
const f = path.join(dir, `${id}.ogg`);
|
|
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
|
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
|
|
}
|
|
const transcribing: string[] = [];
|
|
let fail: ((e: Error) => void) | null = null;
|
|
const worker: any = Object.assign(new EventEmitter(), {
|
|
ready: true,
|
|
request: async (op: string, req: any) => {
|
|
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
|
|
if (op !== 'transcribe') return {};
|
|
transcribing.push(path.basename(req.path, '.ogg'));
|
|
return new Promise((_, rej) => (fail = rej));
|
|
},
|
|
});
|
|
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
|
|
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
|
|
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
|
|
await stt.load('realtime', 'm');
|
|
const done: string[] = [];
|
|
stt.onDone = (id) => {
|
|
done.push(id);
|
|
store.getUtterance(id); // 실제 앱의 녹음 파일 이름 맞추기도 DB 를 읽는다
|
|
};
|
|
stt.enqueue('s1', 'realtime');
|
|
stt.enqueue('s2', 'realtime');
|
|
assert.deepEqual(transcribing, ['s1']);
|
|
|
|
// core.stop 순서: stt.stop → 워커 종료 → DB 닫기 → (워커 프로세스 종료 이벤트로) 변환 요청 실패
|
|
stt.stop();
|
|
store.close();
|
|
fail!(new WorkerError('worker_exit', '워커 종료'));
|
|
await new Promise((r) => setTimeout(r, 50));
|
|
assert.deepEqual(done, [], '종료 중에는 변환 뒤 처리를 하지 않는다');
|
|
assert.deepEqual(transcribing, ['s1']);
|
|
assert.equal(stt.status.queue, 1, '종료 중에는 다음 작업을 꺼내지 않는다 (다음 시작 때 다시 처리)');
|
|
});
|
|
|
|
test('앱 종료: DB 를 닫은 뒤 변환 성공 응답이 와도 닫힌 DB 를 건드리지 않는다', async () => {
|
|
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
|
|
const store = new Store(path.join(dir, 'db.sqlite'));
|
|
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
|
const f = path.join(dir, 's1.ogg');
|
|
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
|
store.insertUtterance({ id: 's1', session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
|
|
let ok: ((r: unknown) => void) | null = null;
|
|
const worker: any = Object.assign(new EventEmitter(), {
|
|
ready: true,
|
|
request: async (op: string) => {
|
|
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
|
|
if (op !== 'transcribe') return {};
|
|
return new Promise((res) => (ok = res));
|
|
},
|
|
});
|
|
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
|
|
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
|
|
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
|
|
await stt.load('realtime', 'm');
|
|
const errors: unknown[] = [];
|
|
const done: string[] = [];
|
|
stt.onDone = (id) => done.push(id);
|
|
// run() 의 오류는 pump 의 catch 가 log.error 로만 남기므로, DB 접근을 감시한다
|
|
const prepare = (store as any).db.prepare.bind((store as any).db);
|
|
(store as any).db.prepare = (sql: string) => {
|
|
try {
|
|
return prepare(sql);
|
|
} catch (e) {
|
|
errors.push(e);
|
|
throw e;
|
|
}
|
|
};
|
|
stt.enqueue('s1', 'realtime');
|
|
stt.stop();
|
|
store.close();
|
|
ok!({ text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, speech_ratio: 1, duration_s: 1, model: 'm', elapsed_ms: 1 });
|
|
await new Promise((r) => setTimeout(r, 50));
|
|
assert.deepEqual(errors, [], '닫힌 DB 에 접근하지 않는다');
|
|
assert.deepEqual(done, []);
|
|
});
|
|
|
|
test('트레이: 종료하면 갱신 타이머가 멈추고 트레이를 한 번만 없앤다 · 이미 없어진 트레이는 건드리지 않는다', (t) => {
|
|
t.mock.timers.enable({ apis: ['setInterval'] });
|
|
const fake = () => {
|
|
const tr = { destroyed: false, destroys: 0, updates: 0, isDestroyed: () => tr.destroyed, destroy: () => ((tr.destroyed = true), tr.destroys++) };
|
|
return tr;
|
|
};
|
|
// 갱신 함수는 main.ts 의 updateTray 처럼 shell.get() 으로 트레이를 얻는다 (없어진 트레이에 쓰면 Electron 이 던지는 것을 흉내)
|
|
const shell = new TrayShell<ReturnType<typeof fake>>();
|
|
let ticks = 0;
|
|
const update = () => {
|
|
ticks++;
|
|
const tr = shell.get();
|
|
if (!tr) return;
|
|
if (tr.destroyed) throw new Error('Tray is destroyed');
|
|
tr.updates++;
|
|
};
|
|
const a = fake();
|
|
shell.set(a);
|
|
shell.every(1500, update);
|
|
t.mock.timers.tick(3000);
|
|
assert.equal(a.updates, 2);
|
|
shell.dispose();
|
|
assert.equal(a.destroys, 1);
|
|
assert.equal(shell.get(), null);
|
|
t.mock.timers.tick(3000);
|
|
assert.equal(a.updates, 2, '종료 뒤에는 갱신하지 않는다');
|
|
assert.equal(ticks, 2, '종료하면 갱신 타이머가 멈춘다');
|
|
shell.dispose();
|
|
assert.equal(a.destroys, 1, '두 번 없애지 않는다');
|
|
|
|
// Windows 로그오프 등으로 Electron 이 트레이를 먼저 없앤 경우
|
|
const b = fake();
|
|
const shell2 = new TrayShell<ReturnType<typeof fake>>();
|
|
shell2.set(b);
|
|
shell2.every(1500, () => {
|
|
const tr = shell2.get();
|
|
if (tr?.destroyed) throw new Error('Tray is destroyed');
|
|
});
|
|
b.destroyed = true;
|
|
assert.equal(shell2.get(), null);
|
|
assert.doesNotThrow(() => t.mock.timers.tick(1500));
|
|
shell2.dispose();
|
|
assert.equal(b.destroys, 0, '이미 없어진 트레이는 다시 없애지 않는다');
|
|
});
|