Added retry mechanism to proxy for transient upstream 5xx erors
This commit is contained in:
+25
-3
@@ -257,6 +257,10 @@ router.post('/epg/:sourceId/channels', async (req, res) => {
|
|||||||
* This handles CORS for streams that don't allow cross-origin
|
* This handles CORS for streams that don't allow cross-origin
|
||||||
*/
|
*/
|
||||||
router.get('/stream', async (req, res) => {
|
router.get('/stream', async (req, res) => {
|
||||||
|
const maxRetries = 2;
|
||||||
|
let lastError = null;
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||||
try {
|
try {
|
||||||
let { url } = req.query;
|
let { url } = req.query;
|
||||||
if (!url) {
|
if (!url) {
|
||||||
@@ -276,6 +280,14 @@ router.get('/stream', async (req, res) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const response = await fetch(url, { headers });
|
const response = await fetch(url, { headers });
|
||||||
|
|
||||||
|
// Retry on 5xx errors (transient upstream issues)
|
||||||
|
if (response.status >= 500 && attempt < maxRetries) {
|
||||||
|
console.log(`[Proxy] Upstream 5xx error (attempt ${attempt}/${maxRetries}), retrying in 500ms...`);
|
||||||
|
await new Promise(r => setTimeout(r, 500));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
console.error(`Upstream error for ${url.substring(0, 80)}...: ${response.status} ${response.statusText}`);
|
console.error(`Upstream error for ${url.substring(0, 80)}...: ${response.status} ${response.statusText}`);
|
||||||
if (response.status === 403) {
|
if (response.status === 403) {
|
||||||
@@ -366,13 +378,23 @@ router.get('/stream', async (req, res) => {
|
|||||||
|
|
||||||
// Pipe to response
|
// Pipe to response
|
||||||
restOfStream.pipe(res);
|
restOfStream.pipe(res);
|
||||||
|
return; // Success - exit the retry loop
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Stream proxy error:', err);
|
lastError = err;
|
||||||
if (!res.headersSent) {
|
console.error(`Stream proxy error (attempt ${attempt}/${maxRetries}):`, err.message);
|
||||||
res.status(500).json({ error: err.message });
|
if (attempt < maxRetries) {
|
||||||
|
console.log('[Proxy] Retrying after error...');
|
||||||
|
await new Promise(r => setTimeout(r, 500));
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// All retries failed
|
||||||
|
if (!res.headersSent) {
|
||||||
|
res.status(500).json({ error: lastError?.message || 'Stream proxy failed after retries' });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user