Skip to content

一分钟搭建影视站,支持Docker等部署方式

fix(quality): 传输层失败不再静默,加首字节心跳并放宽探测预算

bestZwei73827211fe9d
diff --git a/src/app/api/quality/route.test.ts b/src/app/api/quality/route.test.ts
index 10f4cf7..706f1ee 100644
--- a/src/app/api/quality/route.test.ts
+++ b/src/app/api/quality/route.test.ts
@@ -98,4 +98,21 @@ describe('POST /api/quality', () => {
await POST(post([item('a', 'https://s.test/api')]));
expect(state.calls).toBe(2);
});
+
+ it('流式响应先写一行心跳,客户端据此区分「网关拦了」与「探测失败」', async () => {
+ const res = await POST(
+ new Request('https://local.test/api/quality?stream=1', {
+ method: 'POST',
+ body: JSON.stringify({ items: [item('a', 'https://s.test/api')] }),
+ })
+ );
+ expect(res.headers.get('content-type')).toContain('application/x-ndjson');
+
+ const lines = (await res.text())
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line) as Record<string, unknown>);
+ expect(lines[0]).toEqual({ ping: true });
+ expect(lines[1]).toMatchObject({ sourceKey: 'a', height: 1080 });
+ });
});
diff --git a/src/app/api/quality/route.ts b/src/app/api/quality/route.ts
index 647a296..c726e93 100644
--- a/src/app/api/quality/route.ts
+++ b/src/app/api/quality/route.ts
@@ -14,8 +14,12 @@ interface QualityBody {
/** 单次请求最多探测的条目数:一张卡片展开最多十几个源,留足余量且防止被刷 */
const MAX_ITEMS = 50;
-/** 并发上限:一次打满十几个源容易触发源站限流,也会把服务端出站连接占满 */
-const CONCURRENCY = 6;
+/**
+ * 并发上限:一次打满十几个源容易触发源站限流,也会把服务端出站连接占满。
+ * 小内存 VPS 上并发过高时,探测峰值(64KB 文本 + 分片 + AES key)容易把容器顶到 OOM,
+ * 表现为浏览器整条 fetch 失败;降到 3 换取稳定,单批最坏时长仍在客户端看门狗(60s)内。
+ */
+const CONCURRENCY = 3;
/** 探测成功缓存 30 分钟:源站短期内不会给同一部剧换片源 */
const OK_CACHE_TTL = 30 * 60 * 1000;
@@ -132,14 +136,17 @@ export async function POST(req: Request) {
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let closed = false;
- const send = (result: QualityProbeResult) => {
+ const send = (payload: QualityProbeResult | { ping: true }) => {
if (closed) return;
try {
- controller.enqueue(encoder.encode(JSON.stringify(result) + '\n'));
+ controller.enqueue(encoder.encode(JSON.stringify(payload) + '\n'));
} catch {
closed = true; // 客户端已断开
}
};
+ // 首字节心跳:客户端据此区分「请求被网关/反代拦下」与「探测过程本身失败」。
+ // 一行 10 字节,换来线上排障时最关键的一条信息。
+ send({ ping: true });
await runWithConcurrency(items, CONCURRENCY, async (item) => {
if (closed) return;
send(await resolveItem(item));
diff --git a/src/components/use-quality-probe.ts b/src/components/use-quality-probe.ts
index f94f28d..61d2500 100644
--- a/src/components/use-quality-probe.ts
+++ b/src/components/use-quality-probe.ts
@@ -1,7 +1,7 @@
'use client';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { api } from '@/lib/client-api';
+import { ApiError, api } from '@/lib/client-api';
import { QUALITY_FAIL_TTL_MS, isRetryableTimeout, qualityKey, summarizeQuality } from '@/lib/quality';
import { createProbeQueue, type ProbeQueue } from '@/lib/quality-probe-queue';
import { readQualities, useAppStore } from '@/lib/store';
@@ -241,8 +241,21 @@ export function useQualityProbe(sources?: SourceConfig[]) {
},
controller.signal
)
- .catch(() => {
- // 整批失败(离线/未登录)或被新批掐掉:保持「未知」,不打断选源
+ .catch((err: unknown) => {
+ // 主动中止(新批接管 / 组件卸载)不是探测结论,保持「未知」
+ if (err instanceof DOMException && err.name === 'AbortError') return;
+ // 未登录:登录框已弹出,把每个源都标成失败只会误导
+ if (err instanceof ApiError && (err.status === 401 || err.status === 503)) return;
+ // 传输层失败(网关拦截 / 容器重启 / 断网):逐条落成失败结论,徽章上能看出原因。
+ // 原先这里静默吞掉,界面只剩一片「未测到」,线上无从判断是哪一环挂了。
+ const message = err instanceof Error && err.message ? err.message : '探测请求失败';
+ const at = Date.now();
+ for (const key of keys) {
+ if (collected[key]) continue;
+ collected[key] = { from: 'probe', error: message, timestamp: at };
+ settledRef.current.set(key, at);
+ }
+ setQualities((prev) => ({ ...prev, ...collected }));
})
.finally(() => {
if (Object.keys(collected).length > 0) useAppStore.getState().setQuality(collected);
diff --git a/src/lib/client-api.ts b/src/lib/client-api.ts
index 9e41b6a..8237197 100644
--- a/src/lib/client-api.ts
+++ b/src/lib/client-api.ts
@@ -149,22 +149,51 @@ export const api = {
/**
* 批量画质探测(NDJSON 流式):展开来源面板时逐条回调,先到的源先显示画质。
* 结果里的 height 缺失代表「测不出」(单码率 m3u8 / 直链 / 防盗链),不是失败。
+ *
+ * 传输层失败(请求没发出去 / 流中途断开)不再原样冒泡:调用方原先只能静默成
+ * 「未测到」,线上出问题时无法区分「网关拦了」「容器崩了」「探测本身失败」。
+ * 服务端开流即写一行心跳,收到过首字节说明请求确实进了应用,据此给出不同文案。
*/
qualityProbeStream: async (
items: QualityProbeItem[],
onResult: (result: QualityProbeResult) => void,
signal?: AbortSignal
): Promise<void> => {
- const res = await fetch('/api/quality?stream=1', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ items }),
- signal,
- });
+ let res: Response;
+ try {
+ res = await fetch('/api/quality?stream=1', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ items }),
+ signal,
+ });
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') throw err;
+ throw new ApiError('探测请求没能送达服务器(网络或反向代理中断)', 0);
+ }
throwForAuthStatus(res);
if (!res.ok || !res.body) throw new ApiError(`请求失败 (${res.status})`, res.status);
- await consumeNdjson<QualityProbeResult>(res, onResult);
+ let firstByte = false;
+ try {
+ await consumeNdjson<QualityProbeResult | { ping: true }>(res, (event) => {
+ // 心跳行不是结果:收到它就证明请求确实进了 Next,后面的失败才归因于探测本身
+ if ('ping' in event) {
+ firstByte = true;
+ return;
+ }
+ firstByte = true;
+ onResult(event);
+ });
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') throw err;
+ throw new ApiError(
+ firstByte
+ ? '探测连接中途被断开(已收到部分结果,多为网关超时)'
+ : '探测请求被网关拦截(未收到任何响应)',
+ 0
+ );
+ }
},
douban: (type: 'movie' | 'tv', tag: string, pageStart: number, pageSize: number, signal?: AbortSignal) => {
diff --git a/src/lib/quality-probe.ts b/src/lib/quality-probe.ts
index 8f03e84..519e477 100644
--- a/src/lib/quality-probe.ts
+++ b/src/lib/quality-probe.ts
@@ -35,8 +35,13 @@ const SEGMENT_PREFIX_BYTES = 96 * 1024;
/** fMP4 的 init segment 很小,moov 就在里面 */
const INIT_PREFIX_BYTES = 64 * 1024;
-/** 单条探测总死线:与搜索的单源死线同量级,避免一个慢源拖住整批 */
-export const QUALITY_PROBE_TIMEOUT_MS = 8000;
+/**
+ * 单条探测总死线。
+ * 一次探测要串行走 3~5 跳(列表接口 → m3u8 → init/分片 → 可能还有 AES key),
+ * 机房到国内源站的 RTT 远高于本地开发:8s 在线上经常只够握两次手,
+ * 于是可用源被误判成「未测到」。放宽到 12s,单跳仍各自受 6s 限制。
+ */
+export const QUALITY_PROBE_TIMEOUT_MS = 12000;
/**
* 分片解析的独立预算。
diff --git a/src/lib/quality.test.ts b/src/lib/quality.test.ts
index 0bd6523..9414e63 100644
--- a/src/lib/quality.test.ts
+++ b/src/lib/quality.test.ts
@@ -3,8 +3,10 @@ import {
QUALITY_FAIL_TTL_MS,
QUALITY_TTL_MS,
describeQualityBadge,
+ failureReasonLabel,
inferHeightFromBitrate,
isQualityEntryFresh,
+ isRetryableTimeout,
mergeQualityEntries,
qualityLabel,
summarizeQuality,
@@ -333,3 +335,31 @@ describe('summarizeQuality', () => {
expect(summarizeQuality([probe(720), play]).best).toBe('4K');
});
});
+
+describe('失败原因标签', () => {
+ it('源站拒绝与超时各有短标签', () => {
+ expect(failureReasonLabel('HTTP 403')).toBe('防盗链');
+ expect(failureReasonLabel('画质探测超时')).toBe('超时');
+ expect(failureReasonLabel('未找到播放资源')).toBe('无资源');
+ });
+
+ it('传输层失败也要有标签:否则线上只剩裸「未测到」,无从判断哪一环挂了', () => {
+ expect(failureReasonLabel('探测请求被网关拦截(未收到任何响应)')).toBe('连接中断');
+ expect(failureReasonLabel('探测连接中途被断开(已收到部分结果,多为网关超时)')).toBe('连接中断');
+ expect(failureReasonLabel('探测请求没能送达服务器(网络或反向代理中断)')).toBe('连接中断');
+ expect(failureReasonLabel('请求失败 (502)')).toBe('网关异常');
+ });
+
+ it('无法归类的错误不硬造标签', () => {
+ expect(failureReasonLabel('fetch failed')).toBeUndefined();
+ expect(failureReasonLabel(undefined)).toBeUndefined();
+ });
+});
+
+describe('isRetryableTimeout', () => {
+ it('只把超时视作值得自动补探的失败', () => {
+ expect(isRetryableTimeout('画质探测超时')).toBe(true);
+ expect(isRetryableTimeout('HTTP 403')).toBe(false);
+ expect(isRetryableTimeout(undefined)).toBe(false);
+ });
+});
diff --git a/src/lib/quality.ts b/src/lib/quality.ts
index 03a5ad0..e983111 100644
--- a/src/lib/quality.ts
+++ b/src/lib/quality.ts
@@ -24,8 +24,13 @@ export const QUALITY_FAIL_TTL_MS = 2 * 60 * 1000;
*/
export function failureReasonLabel(error?: string): string | undefined {
if (!error) return undefined;
+ // 传输层失败(请求没送达 / 流中途断)要排在「超时」之前:
+ // 这类文案本身就带「多为网关超时」的解释,先匹配超时会把归因指错
+ if (/中断|断开|送达|网关拦截/.test(error)) return '连接中断';
if (error.includes('超时')) return '超时';
if (/HTTP (401|403)/.test(error)) return '防盗链';
+ // 5xx 多为反代/网关回的错误页,和「源站不给画质」完全不是一回事
+ if (/HTTP 5\d\d|\(5\d\d\)/.test(error)) return '网关异常';
if (error.includes('未找到播放资源')) return '无资源';
if (error.includes('无效')) return '源无效';
return undefined;