fix(tts): dedupe concurrent synthesis and write the audio cache atomically

- Write cached audio to a temp file and rename it into place so a concurrent read never sees a partial or interleaved file.
- Share one upstream synthesis call per text and cache key, so concurrent requests no longer produce different recordings that race on the same file.
- Return the same upstream error to every waiter.
This commit is contained in:
Chris Scott committed 2026-10-09 22:16:04 -04:00
1 parent 4abbfef77f
commit aed50e6d99
2 files changed
+199 -51

No files matched your search

+109 -48
View File
@@ -1,8 +1,8 @@
import { Hono } from 'hono'
import { z } from 'zod'
import { Database } from 'bun:sqlite'
import { createHash } from 'crypto'
import { readFile, writeFile, readdir, stat, unlink } from 'fs/promises'
import { createHash, randomUUID } from 'crypto'
import { readFile, writeFile, readdir, stat, unlink, rename } from 'fs/promises'
import { join } from 'path'
import { SettingsService } from '../services/settings'
import { logger } from '../utils/logger'
@@ -107,7 +107,96 @@ async function cacheAudio(cacheKey: string, audioData: Buffer): Promise<void> {
await cleanupOldestFiles(audioData.length)
}
await writeFile(filePath, audioData)
const tempPath = join(TTS_CACHE_DIR, `${cacheKey}.${process.pid}.${randomUUID()}.tmp`)
try {
await writeFile(tempPath, audioData)
await rename(tempPath, filePath)
} catch (error) {
await unlink(tempPath).catch(() => undefined)
throw error
}
}
interface SynthesisParams {
text: string
endpoint: string
apiKey: string
voice: string
model: string
speed: number
}
class TTSUpstreamError extends Error {
readonly status: 400 | 500
readonly details: string
constructor(status: 400 | 500, details: string) {
super('TTS API request failed')
this.name = 'TTSUpstreamError'
this.status = status
this.details = details
}
}
const inFlightSynthesis = new Map<string, Promise<Buffer>>()
function parseErrorDetails(errorText: string): string {
try {
const errorJson = JSON.parse(errorText)
if (errorJson.detail?.error?.message) return errorJson.detail.error.message
if (errorJson.detail?.message) return errorJson.detail.message
if (errorJson.message) return errorJson.message
} catch {
return errorText
}
return errorText
}
async function fetchSynthesizedAudio(params: SynthesisParams): Promise<Buffer> {
const { text, endpoint, apiKey, voice, model, speed } = params
const baseUrl = normalizeToBaseUrl(endpoint)
const speechEndpoint = `${baseUrl}/v1/audio/speech`
const response = await fetch(speechEndpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model,
voice,
input: text,
speed,
response_format: 'mp3',
}),
})
if (!response.ok) {
const errorText = await response.text()
logger.error(`TTS API error: ${response.status} - ${errorText}`)
const status = response.status >= 400 && response.status < 600 ? response.status as 400 | 500 : 500
throw new TTSUpstreamError(status, parseErrorDetails(errorText))
}
return Buffer.from(await response.arrayBuffer())
}
function getOrStartSynthesis(cacheKey: string, params: SynthesisParams): Promise<Buffer> {
const existing = inFlightSynthesis.get(cacheKey)
if (existing) return existing
const promise = (async () => {
const audioBuffer = await fetchSynthesizedAudio(params)
await cacheAudio(cacheKey, audioBuffer)
return audioBuffer
})()
inFlightSynthesis.set(cacheKey, promise)
const cleanup = () => inFlightSynthesis.delete(cacheKey)
promise.finally(cleanup).catch(() => undefined)
return promise
}
@@ -272,56 +361,28 @@ export function createTTSRoutes(db: Database) {
logger.info(`TTS cache miss, calling API: ${cacheKey.substring(0, 8)}...`)
const baseUrl = normalizeToBaseUrl(endpoint)
const speechEndpoint = `${baseUrl}/v1/audio/speech`
const response = await fetch(speechEndpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model,
let audioBuffer: Buffer
try {
audioBuffer = await getOrStartSynthesis(cacheKey, {
text,
endpoint,
apiKey,
voice,
input: text,
model,
speed,
response_format: 'mp3',
}),
signal: abortController.signal,
})
if (!response.ok) {
const errorText = await response.text()
logger.error(`TTS API error: ${response.status} - ${errorText}`)
const status = response.status >= 400 && response.status < 600 ? response.status as 400 | 500 : 500
// Try to parse error details for better frontend display
let errorDetails = errorText
try {
const errorJson = JSON.parse(errorText)
if (errorJson.detail?.error?.message) {
errorDetails = errorJson.detail.error.message
} else if (errorJson.detail?.message) {
errorDetails = errorJson.detail.message
} else if (errorJson.message) {
errorDetails = errorJson.message
}
} catch {
// Use raw error text if parsing fails
})
} catch (error) {
if (error instanceof TTSUpstreamError) {
return c.json({
error: 'TTS API request failed',
details: error.details,
voice: voice,
availableVoices: ttsConfig?.availableVoices || []
}, error.status)
}
return c.json({
error: 'TTS API request failed',
details: errorDetails,
voice: voice,
availableVoices: ttsConfig?.availableVoices || []
}, status)
throw error
}
const audioBuffer = Buffer.from(await response.arrayBuffer())
await cacheAudio(cacheKey, audioBuffer)
logger.info(`TTS audio cached: ${cacheKey.substring(0, 8)}...`)
return new Response(audioBuffer, {
+90 -3
View File
@@ -7,6 +7,7 @@ vi.mock('fs/promises', () => ({
readdir: vi.fn(),
stat: vi.fn(),
unlink: vi.fn(),
rename: vi.fn(),
}))
vi.mock('../../src/utils/fs-safe', () => ({
@@ -57,6 +58,7 @@ const mockUnlink = fs.unlink as any
import { createTTSRoutes, cleanupExpiredCache, getCacheStats, generateCacheKey, ensureCacheDir, getCachedAudio, getCacheSize, cleanupOldestFiles, cacheAudio } from '../../src/routes/tts'
const mockWriteFile = fs.writeFile as any
const mockRename = (fs as any).rename as any
function createTtsConfig(overrides: Record<string, unknown> = {}) {
return {
@@ -316,6 +318,9 @@ describe('TTS route handlers', () => {
it('synthesizes and caches audio on a cache miss', async () => {
mockStat.mockRejectedValue(new Error('not found'))
mockReaddir.mockResolvedValue([] as any)
mockWriteFile.mockResolvedValue(undefined)
mockRename.mockResolvedValue(undefined)
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: async () => Buffer.from('fresh-audio'),
@@ -339,9 +344,53 @@ describe('TTS route handlers', () => {
}),
)
expect(mockWriteFile).toHaveBeenCalledWith(
expect.stringContaining('.mp3'),
expect.stringMatching(/\.tmp$/),
expect.any(Buffer),
)
expect(mockRename).toHaveBeenCalledWith(
expect.stringMatching(/\.tmp$/),
expect.stringContaining('.mp3'),
)
})
it('deduplicates concurrent synthesis requests for the same text', async () => {
mockStat.mockRejectedValue(new Error('not found'))
mockReaddir.mockResolvedValue([] as any)
mockWriteFile.mockResolvedValue(undefined)
mockRename.mockResolvedValue(undefined)
let resolveFetch: ((value: { ok: boolean; arrayBuffer: () => Promise<Buffer> }) => void) | undefined
const fetchMock = vi.fn().mockImplementation(
() => new Promise((resolve) => {
resolveFetch = resolve
}),
)
vi.stubGlobal('fetch', fetchMock)
const request = () => app.request('/synthesize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'Hello' }),
})
const first = request()
const second = request()
await new Promise((resolve) => setTimeout(resolve, 0))
expect(fetchMock).toHaveBeenCalledTimes(1)
resolveFetch!({
ok: true,
arrayBuffer: async () => Buffer.from('shared-audio'),
})
const [firstRes, secondRes] = await Promise.all([first, second])
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(firstRes.status).toBe(200)
expect(secondRes.status).toBe(200)
expect(Buffer.from(await firstRes.arrayBuffer()).toString()).toBe('shared-audio')
expect(Buffer.from(await secondRes.arrayBuffer()).toString()).toBe('shared-audio')
})
it('returns the upstream error details when synthesis fails', async () => {
@@ -463,27 +512,65 @@ describe('cacheAudio', () => {
mockStat.mockResolvedValue({ size: 200 * 1024 * 1024, mtimeMs: 1000 } as any)
mockUnlink.mockResolvedValue(undefined)
mockWriteFile.mockResolvedValue(undefined)
mockRename.mockResolvedValue(undefined)
await cacheAudio('cache-key', Buffer.from('audio'))
expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('big.mp3'))
expect(mockWriteFile).toHaveBeenCalledWith(
expect.stringContaining('cache-key.mp3'),
expect.stringMatching(/\.tmp$/),
expect.any(Buffer),
)
expect(mockRename).toHaveBeenCalledWith(
expect.stringMatching(/\.tmp$/),
expect.stringContaining('cache-key.mp3'),
)
})
it('writes audio without cleanup when the cache has room', async () => {
mockReaddir.mockResolvedValue(['small.mp3'] as any)
mockStat.mockResolvedValue({ size: 1024, mtimeMs: 1000 } as any)
mockWriteFile.mockResolvedValue(undefined)
mockRename.mockResolvedValue(undefined)
await cacheAudio('cache-key', Buffer.from('audio'))
expect(mockUnlink).not.toHaveBeenCalled()
expect(mockWriteFile).toHaveBeenCalledWith(
expect.stringContaining('cache-key.mp3'),
expect.stringMatching(/\.tmp$/),
expect.any(Buffer),
)
expect(mockRename).toHaveBeenCalledWith(
expect.stringMatching(/\.tmp$/),
expect.stringContaining('cache-key.mp3'),
)
})
it('writes to a unique temp path and renames it to the final .mp3 path', async () => {
mockReaddir.mockResolvedValue([] as any)
mockWriteFile.mockResolvedValue(undefined)
mockRename.mockResolvedValue(undefined)
await cacheAudio('cache-key', Buffer.from('audio'))
const [writtenPath] = mockWriteFile.mock.calls[0]
const [renamedFrom, renamedTo] = mockRename.mock.calls[0]
expect(writtenPath).toContain('cache-key.')
expect(writtenPath).toMatch(/\.tmp$/)
expect(writtenPath).not.toContain('.mp3')
expect(renamedFrom).toBe(writtenPath)
expect(renamedTo).toContain('cache-key.mp3')
})
it('removes the temp file and rethrows when the rename fails', async () => {
mockReaddir.mockResolvedValue([] as any)
mockWriteFile.mockResolvedValue(undefined)
mockRename.mockRejectedValue(new Error('rename failed'))
mockUnlink.mockResolvedValue(undefined)
await expect(cacheAudio('cache-key', Buffer.from('audio'))).rejects.toThrow('rename failed')
expect(mockUnlink).toHaveBeenCalledWith(expect.stringMatching(/\.tmp$/))
})
})