d3ro-voice/apps/desktop/tests/main/services/disk-wav-audio-sink.test.ts

200 lines
7.1 KiB
TypeScript

// tests/main/services/disk-wav-audio-sink.test.ts
// GAP-PERF-01 잔여: 장시간 회의 녹음 PCM 디스크 스트리밍 계약 테스트
import fs from 'fs'
import os from 'os'
import path from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { CaptionSegment } from '@d3ro/core/types'
import { MeetingRecordingSession } from '../../../src/main/services/meeting/MeetingRecordingSession'
import {
DiskWavAudioSink,
MAX_WAV_DATA_BYTES,
writeWavHeader16kMonoPcm16,
} from '../../../src/main/services/meeting/disk-wav-audio-sink'
describe('DiskWavAudioSink & MeetingRecordingSession 스트리밍', () => {
let tempDir = ''
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'd3ro-wav-sink-'))
})
afterEach(() => {
vi.restoreAllMocks()
if (tempDir) {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
it('녹음종료_다중PCM청크스트리밍_메모리누적없이유효한WAV헤더와페이로드를기록한다', async () => {
const wavPath = path.join(tempDir, 'meeting-audio', 'session-1.wav')
const sink = new DiskWavAudioSink(wavPath)
let chunkListener: ((buffer: Buffer) => void) | null = null
const session = new MeetingRecordingSession('session-1', 1_000, {
caption: {
onSegment: () => () => undefined,
stop: async () => ({
segments: [{ id: 'seg-1', text: '회의 발언', timestamp: 2_000, isFinal: true } satisfies CaptionSegment],
}),
},
audio: {
onChunk: (listener) => {
chunkListener = listener
return () => {
chunkListener = null
}
},
},
audioSink: sink,
now: () => 5_000,
})
session.attachCaption()
session.attachAudio()
const chunk1 = Buffer.from([0x01, 0x02, 0x03, 0x04])
const chunk2 = Buffer.from([0x05, 0x06, 0x07, 0x08, 0x09, 0x0a])
chunkListener?.(chunk1)
chunkListener?.(chunk2)
// 중간 체크포인트는 임시 .part 를 유지하고 최종 WAV 를 아직 닫지 않는다
const mid = session.checkpoint({ includeAudio: false })
expect(mid.pcm.length).toBe(0)
expect(mid.audioSavedToDisk).toBe(false)
expect(fs.existsSync(`${wavPath}.part`)).toBe(true)
expect(fs.existsSync(wavPath)).toBe(false)
const snapshot = await session.stop()
expect(snapshot.pcm.length).toBe(0)
expect(snapshot.audioSavedToDisk).toBe(true)
expect(snapshot.pcmByteLength).toBe(10)
expect(fs.existsSync(`${wavPath}.part`)).toBe(false)
expect(fs.existsSync(wavPath)).toBe(true)
const written = fs.readFileSync(wavPath)
expect(written.length).toBe(44 + 10)
expect(written.subarray(0, 4).toString('ascii')).toBe('RIFF')
expect(written.readUInt32LE(4)).toBe(36 + 10)
expect(written.subarray(8, 12).toString('ascii')).toBe('WAVE')
expect(written.subarray(12, 16).toString('ascii')).toBe('fmt ')
expect(written.readUInt16LE(20)).toBe(1)
expect(written.readUInt16LE(22)).toBe(1)
expect(written.readUInt32LE(24)).toBe(16000)
expect(written.readUInt16LE(34)).toBe(16)
expect(written.subarray(36, 40).toString('ascii')).toBe('data')
expect(written.readUInt32LE(40)).toBe(10)
expect([...written.subarray(44)]).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
})
it('세션분리_시작실패나중단시detach호출_임시part파일을제거한다', () => {
const wavPath = path.join(tempDir, 'session-abort.wav')
const sink = new DiskWavAudioSink(wavPath)
let chunkListener: ((buffer: Buffer) => void) | null = null
const session = new MeetingRecordingSession('session-abort', 1_000, {
caption: {
onSegment: () => () => undefined,
stop: async () => null,
},
audio: {
onChunk: (listener) => {
chunkListener = listener
return () => {
chunkListener = null
}
},
},
audioSink: sink,
now: () => 2_000,
})
session.attachAudio()
chunkListener?.(Buffer.from([0x11, 0x22]))
expect(fs.existsSync(`${wavPath}.part`)).toBe(true)
session.detach()
expect(fs.existsSync(`${wavPath}.part`)).toBe(false)
expect(fs.existsSync(wavPath)).toBe(false)
})
it('무음종료_청크가하나도없을때_빈WAV파일을남기지않는다', async () => {
const wavPath = path.join(tempDir, 'session-empty.wav')
const sink = new DiskWavAudioSink(wavPath)
const session = new MeetingRecordingSession('session-empty', 1_000, {
caption: {
onSegment: () => () => undefined,
stop: async () => null,
},
audio: {
onChunk: () => () => undefined,
},
audioSink: sink,
now: () => 2_000,
})
session.attachAudio()
const snapshot = await session.stop()
expect(snapshot.audioSavedToDisk).toBe(false)
expect(snapshot.pcmByteLength).toBe(0)
expect(fs.existsSync(wavPath)).toBe(false)
expect(fs.existsSync(`${wavPath}.part`)).toBe(false)
})
it('append_initialPlaceholderWriteSyncThrows_closesOpenedFdRemovesPartAndRethrows', () => {
const wavPath = path.join(tempDir, 'placeholder-fail.wav')
const sink = new DiskWavAudioSink(wavPath)
const openedFds: number[] = []
const realOpenSync = fs.openSync
vi.spyOn(fs, 'openSync').mockImplementation((...args) => {
const fd = realOpenSync(...args)
openedFds.push(fd)
return fd
})
const closeSpy = vi.spyOn(fs, 'closeSync')
vi.spyOn(fs, 'writeSync').mockImplementationOnce(() => {
throw new Error('ENOSPC: no space left on device')
})
expect(() => sink.append(Buffer.from([0x01, 0x02]))).toThrow('ENOSPC: no space left on device')
expect(openedFds).toHaveLength(1)
expect(closeSpy).toHaveBeenCalledWith(openedFds[0])
expect(fs.existsSync(`${wavPath}.part`)).toBe(false)
expect(sink.pcmByteLength).toBe(0)
expect(sink.finalize()).toEqual({ saved: false, pcmByteLength: 0 })
})
it('writeWavHeader16kMonoPcm16_withinAndBeyondUint32Limit_validatesRange', () => {
const maxHeader = writeWavHeader16kMonoPcm16(Buffer.alloc(44), MAX_WAV_DATA_BYTES)
expect(maxHeader.readUInt32LE(4)).toBe(0xffffffff)
expect(maxHeader.readUInt32LE(40)).toBe(MAX_WAV_DATA_BYTES)
expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), MAX_WAV_DATA_BYTES + 1)).toThrow(
RangeError,
)
expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), -1)).toThrow(RangeError)
expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), 1.5)).toThrow(RangeError)
})
it('append_chunkExceedingUint32Limit_throwsRangeErrorWithoutCorruptingExistingAudio', () => {
const wavPath = path.join(tempDir, 'limit-check.wav')
const sink = new DiskWavAudioSink(wavPath)
const initialChunk = Buffer.from([0xaa, 0xbb])
sink.append(initialChunk)
expect(sink.pcmByteLength).toBe(2)
const oversizedSlice = { length: MAX_WAV_DATA_BYTES } as unknown as Buffer
expect(() => sink.append(oversizedSlice)).toThrow(RangeError)
expect(sink.pcmByteLength).toBe(2)
const finalized = sink.finalize()
expect(finalized).toEqual({ saved: true, pcmByteLength: 2 })
expect(fs.readFileSync(wavPath).subarray(44)).toEqual(initialChunk)
})
})