fix(tts): bound synthesis requests and tolerate cache write failures

This commit is contained in:
Chris Scott committed 2026-10-09 23:57:09 -04:00
1 parent 1bfcdd0496
commit 1eba33c6f1
2 files changed
+78 -23

No files matched your search

+36 -23
View File
@@ -18,6 +18,7 @@ const TTS_CACHE_DIR = join(getWorkspacePath(), 'cache', 'tts')
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
const MAX_CACHE_SIZE_MB = 200
const MAX_CACHE_SIZE_BYTES = MAX_CACHE_SIZE_MB * 1024 * 1024
const TTS_SYNTHESIS_TIMEOUT_MS = 60_000
const TTSRequestSchema = z.object({
text: z.string().min(1).max(4096),
@@ -158,29 +159,37 @@ async function fetchSynthesizedAudio(params: SynthesisParams): Promise<Buffer> {
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))
try {
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',
}),
signal: AbortSignal.timeout(TTS_SYNTHESIS_TIMEOUT_MS),
})
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())
} catch (error) {
if (error instanceof Error && error.name === 'TimeoutError') {
throw new TTSUpstreamError(500, 'TTS upstream request timed out')
}
throw error
}
return Buffer.from(await response.arrayBuffer())
}
function getOrStartSynthesis(cacheKey: string, params: SynthesisParams): Promise<Buffer> {
@@ -189,7 +198,11 @@ function getOrStartSynthesis(cacheKey: string, params: SynthesisParams): Promise
const promise = (async () => {
const audioBuffer = await fetchSynthesizedAudio(params)
await cacheAudio(cacheKey, audioBuffer)
try {
await cacheAudio(cacheKey, audioBuffer)
} catch (error) {
logger.error('TTS cache write failed:', error)
}
return audioBuffer
})()
+42
View File
@@ -341,6 +341,7 @@ describe('TTS route handlers', () => {
expect.objectContaining({
method: 'POST',
headers: expect.objectContaining({ Authorization: 'Bearer test-api-key' }),
signal: expect.any(AbortSignal),
}),
)
expect(mockWriteFile).toHaveBeenCalledWith(
@@ -353,6 +354,28 @@ describe('TTS route handlers', () => {
)
})
it('returns synthesized audio when the cache write fails', async () => {
mockStat.mockRejectedValue(new Error('not found'))
mockReaddir.mockResolvedValue([] as any)
mockWriteFile.mockRejectedValue(new Error('disk full'))
mockUnlink.mockResolvedValue(undefined)
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
arrayBuffer: async () => Buffer.from('fresh-audio'),
})
vi.stubGlobal('fetch', fetchMock)
const res = await app.request('/synthesize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'Hello' }),
})
expect(res.status).toBe(200)
expect(res.headers.get('X-Cache')).toBe('MISS')
expect(Buffer.from(await res.arrayBuffer()).toString()).toBe('fresh-audio')
})
it('deduplicates concurrent synthesis requests for the same text', async () => {
mockStat.mockRejectedValue(new Error('not found'))
mockReaddir.mockResolvedValue([] as any)
@@ -416,6 +439,25 @@ describe('TTS route handlers', () => {
})
})
it('returns an upstream error when synthesis times out', async () => {
mockStat.mockRejectedValue(new Error('not found'))
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new DOMException('The operation timed out.', 'TimeoutError')))
const res = await app.request('/synthesize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'Hello' }),
})
expect(res.status).toBe(500)
expect(await res.json()).toEqual({
error: 'TTS API request failed',
details: 'TTS upstream request timed out',
voice: 'alloy',
availableVoices: [],
})
})
it('lists models and stores them when not cached', async () => {
mockDiscoverModelsCached.mockResolvedValue({ models: ['tts-1', 'tts-1-hd'], cached: false })