LibreChat/api/server/routes/files/speech/tts.js
Marco Beretta 784582850a
🧯 fix: Guard SSE Writes and Interval Cleanups Against Crashes (#17462)
* fix: Harden Timer Sweeps, SSE Writes, and Violation Counters

Guard SSE writes against ended or destroyed responses through one helper, catch and single-flight the job store and TTL cache cleanup timers, serialize in-process counter updates, cap the violation log, prune stale OAuth failure records, batch the active-job lookup, and count Redis keys with DBSIZE.

* refactor: Drop the redundant violation log entry copy

* refactor: Log single-flight sweep failures from the API package

* test: Cover active generation listing and client disconnect mid-stream

* refactor: Configure violation log retention and move title timeout into the API package

* feat: Configure OAuth failure retention through mcpSettings

* fix: Prune OAuth failures promptly under short retention
2026-10-27 23:06:58 +01:00

70 lines
2 KiB
JavaScript

const multer = require('multer');
const express = require('express');
const {
inspectContent,
extractStoredMessageContent,
contentFilterBlockResponse,
restoreTenantContextFromReq,
} = require('@librechat/api');
const { logger } = require('@librechat/data-schemas');
const { CacheKeys, hasActivePiiFields } = require('librechat-data-provider');
const { getVoices, streamAudio, textToSpeech } = require('~/server/services/Files/Audio');
const { getLogStores } = require('~/cache');
const router = express.Router();
const upload = multer();
router.post(
'/manual',
upload.none(),
restoreTenantContextFromReq,
(req, res, next) => {
const filters = req.config?.filters;
if (!hasActivePiiFields(filters?.messages?.pii, ['text'])) {
next();
return;
}
const finding = inspectContent(extractStoredMessageContent({ text: req.body?.input }), {
filters,
});
if (finding == null) {
next();
return;
}
res.status(400).json(contentFilterBlockResponse(finding));
},
async (req, res) => {
await textToSpeech(req, res);
},
);
const logDebugMessage = (req, message) =>
logger.debug(`[streamAudio] user: ${req?.user?.id ?? 'UNDEFINED_USER'} | ${message}`);
// TODO: test caching
router.post('/', async (req, res) => {
try {
const audioRunsCache = getLogStores(CacheKeys.AUDIO_RUNS);
const audioRun = await audioRunsCache.get(req.body.runId);
logDebugMessage(req, 'start stream audio');
if (audioRun) {
logDebugMessage(req, 'stream audio already running');
return res.status(401).json({ error: 'Audio stream already running' });
}
await audioRunsCache.set(req.body.runId, true);
await streamAudio(req, res);
logDebugMessage(req, 'end stream audio');
res.status(200).end();
} catch (error) {
logger.error(`[streamAudio] user: ${req.user.id} | Failed to stream audio: ${error}`);
res.status(500).json({ error: 'Failed to stream audio' });
}
});
router.get('/voices', async (req, res) => {
await getVoices(req, res);
});
module.exports = router;