Skip to content

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

fix(quality): 探测按 host 全局限并发,直播测活闸门抽取为共享模块

bestZwei5b88d98e37be
diff --git a/src/app/api/live/probe/route.ts b/src/app/api/live/probe/route.ts
index 683da7b..53d6a6c 100644
--- a/src/app/api/live/probe/route.ts
+++ b/src/app/api/live/probe/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { guardRequest, jsonError } from '@/lib/api-guard';
import { fetchUpstreamWithMeta } from '@/lib/fetch-utils';
+import { withHostLimit } from '@/lib/host-gate';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
@@ -390,59 +391,6 @@ async function probeOne(url: string): Promise<ProbeOutcome> {
}
}
-/**
- * 全局按 host 限并发:IPTV 列表里同一运营商的几十个频道常共用一个 host,
- * 批量测活若不限流,会以「客户端多批次 × 服务端 CONCURRENCY」的并发冲击同一源,
- * 弱源服务器会被打挂甚至封掉本服务 IP(表现为越测越红)。
- * 同一 host 最多 PER_HOST_CONCURRENCY 个在途探测,跨请求共享(模块级闸门),
- * 不同 host 互不影响;名额满时 FIFO 排队,空闲闸门及时清理避免 Map 无界增长。
- */
-const PER_HOST_CONCURRENCY = 3;
-
-const hostGates = new Map<string, { active: number; waiters: (() => void)[] }>();
-
-function hostOf(url: string): string {
- try {
- return new URL(url).host;
- } catch {
- return url;
- }
-}
-
-/** 取一个该 host 的在途名额,返回释放函数;名额满时排队等待 */
-function acquireHostSlot(host: string): Promise<() => void> {
- let gate = hostGates.get(host);
- if (!gate) {
- gate = { active: 0, waiters: [] };
- hostGates.set(host, gate);
- }
- const g = gate;
- return new Promise((resolve) => {
- const take = () => {
- g.active++;
- resolve(() => {
- g.active--;
- // 唤醒的等待者同步接管名额(active-- 后立即 ++),不留被新请求插队的竞态窗口
- const next = g.waiters.shift();
- if (next) next();
- else if (g.active === 0) hostGates.delete(host);
- });
- };
- if (g.active < PER_HOST_CONCURRENCY) take();
- else g.waiters.push(take);
- });
-}
-
-/** 在 host 闸门内探测单个频道(probeOne 内部已兜底,不会抛出) */
-async function probeWithHostLimit(url: string): Promise<ProbeOutcome> {
- const release = await acquireHostSlot(hostOf(url));
- try {
- return await probeOne(url);
- } finally {
- release();
- }
-}
-
const NDJSON_HEADERS = {
'Content-Type': 'application/x-ndjson; charset=utf-8',
'Cache-Control': 'no-store, no-transform',
@@ -490,7 +438,7 @@ function ndjsonResponse(urls: string[], reqSignal: AbortSignal): Response {
while (cursor < pending.length) {
if (closed || reqSignal.aborted) return;
const url = pending[cursor++];
- const outcome = await probeWithHostLimit(url);
+ const outcome = await withHostLimit(url, () => probeOne(url));
if (closed || reqSignal.aborted) return;
cacheSet(url, outcome);
send(outcome);
@@ -577,7 +525,7 @@ export async function POST(req: Request) {
const worker = async () => {
while (cursor < pending.length) {
const url = pending[cursor++];
- const outcome = await probeWithHostLimit(url);
+ const outcome = await withHostLimit(url, () => probeOne(url));
cacheSet(url, outcome);
outcomes.set(url, outcome);
}
diff --git a/src/app/api/quality/route.ts b/src/app/api/quality/route.ts
index 76f23e0..647a296 100644
--- a/src/app/api/quality/route.ts
+++ b/src/app/api/quality/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { guardRequest } from '@/lib/api-guard';
import { getCache, setCache } from '@/lib/fetch-utils';
+import { withHostLimit } from '@/lib/host-gate';
import { probeQuality } from '@/lib/quality-probe';
import type { QualityProbeItem, QualityProbeResult } from '@/lib/types';
@@ -99,7 +100,10 @@ export async function POST(req: Request) {
if (!pending) {
pending = (async () => {
try {
- const result = await probeQuality(item, req.signal);
+ // per-host 闸门放在最外层:同一采集站的多个影片共用一个 host,
+ // 只限单请求内的 CONCURRENCY 挡不住「多用户 × 单请求并发」的叠加冲击。
+ // 排队等待不占用 probeQuality 内部的 8s 死线(超时在拿到名额后才起算)
+ const result = await withHostLimit(item.source.url, () => probeQuality(item, req.signal));
const value: CachedProbe = { height: result.height, error: result.error };
// 「测不出」(height 缺失且无 error)同样是有效结论,也要缓存,
// 否则单码率源每次展开都会被重复探测一遍
diff --git a/src/lib/host-gate.test.ts b/src/lib/host-gate.test.ts
new file mode 100644
index 0000000..000f430
--- /dev/null
+++ b/src/lib/host-gate.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+import { acquireHostSlot, hostOf, withHostLimit } from './host-gate';
+
+const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+describe('hostOf', () => {
+ it('取 host(含端口),非法输入原样返回', () => {
+ expect(hostOf('https://a.example.com:8443/x?y=1')).toBe('a.example.com:8443');
+ expect(hostOf('not-a-url')).toBe('not-a-url');
+ });
+});
+
+describe('acquireHostSlot', () => {
+ it('同一 host 最多 3 个在途名额,超出排队', async () => {
+ const r1 = await acquireHostSlot('t-cap');
+ const r2 = await acquireHostSlot('t-cap');
+ const r3 = await acquireHostSlot('t-cap');
+ let fourthTaken = false;
+ const p4 = acquireHostSlot('t-cap').then((release) => {
+ fourthTaken = true;
+ return release;
+ });
+ await tick();
+ expect(fourthTaken).toBe(false);
+ r1();
+ const r4 = await p4;
+ expect(fourthTaken).toBe(true);
+ r2();
+ r3();
+ r4();
+ });
+
+ it('不同 host 互不影响', async () => {
+ const r1 = await acquireHostSlot('t-a');
+ const r2 = await acquireHostSlot('t-b');
+ const r3 = await acquireHostSlot('t-c');
+ r1();
+ r2();
+ r3();
+ });
+
+ it('名额全部释放后可立即重新获取', async () => {
+ const r1 = await acquireHostSlot('t-reuse');
+ r1();
+ const start = Date.now();
+ const r2 = await acquireHostSlot('t-reuse');
+ expect(Date.now() - start).toBeLessThan(50);
+ r2();
+ });
+});
+
+describe('withHostLimit', () => {
+ it('同一 host 的并发峰值不超过 3', async () => {
+ let active = 0;
+ let peak = 0;
+ const task = () =>
+ withHostLimit('t-peak', async () => {
+ active++;
+ peak = Math.max(peak, active);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ active--;
+ });
+ await Promise.all(Array.from({ length: 8 }, task));
+ expect(peak).toBe(3);
+ });
+
+ it('不同 host 之间不互相等待', async () => {
+ const start = Date.now();
+ await Promise.all([
+ withHostLimit('t-x', () => new Promise<void>((r) => setTimeout(r, 30))),
+ withHostLimit('t-y', () => new Promise<void>((r) => setTimeout(r, 30))),
+ withHostLimit('t-z', () => new Promise<void>((r) => setTimeout(r, 30))),
+ ]);
+ expect(Date.now() - start).toBeLessThan(90);
+ });
+});
diff --git a/src/lib/host-gate.ts b/src/lib/host-gate.ts
new file mode 100644
index 0000000..c3730b1
--- /dev/null
+++ b/src/lib/host-gate.ts
@@ -0,0 +1,56 @@
+/**
+ * 全局按 host 限并发(模块级闸门,跨请求共享)。
+ *
+ * 使用场景:服务端代替用户向采集站发探测类请求(直播测活 / 画质探测)。
+ * 同一运营商的几十个条目常共用一个 host,若只限单请求内的并发,
+ * 「多用户 × 单请求并发」会叠加冲击同一弱源,被源站打挂甚至封掉本服务 IP。
+ * 同一 host 最多 PER_HOST_CONCURRENCY 个在途请求,不同 host 互不影响;
+ * 名额满时 FIFO 排队,空闲闸门及时清理避免 Map 无界增长。
+ */
+
+/** 同一 host 允许的最大在途请求数 */
+const PER_HOST_CONCURRENCY = 3;
+
+const hostGates = new Map<string, { active: number; waiters: (() => void)[] }>();
+
+export function hostOf(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
+/** 取一个该 host 的在途名额,返回释放函数;名额满时排队等待 */
+export function acquireHostSlot(host: string): Promise<() => void> {
+ let gate = hostGates.get(host);
+ if (!gate) {
+ gate = { active: 0, waiters: [] };
+ hostGates.set(host, gate);
+ }
+ const g = gate;
+ return new Promise((resolve) => {
+ const take = () => {
+ g.active++;
+ resolve(() => {
+ g.active--;
+ // 唤醒的等待者同步接管名额(active-- 后立即 ++),不留被新请求插队的竞态窗口
+ const next = g.waiters.shift();
+ if (next) next();
+ else if (g.active === 0) hostGates.delete(host);
+ });
+ };
+ if (g.active < PER_HOST_CONCURRENCY) take();
+ else g.waiters.push(take);
+ });
+}
+
+/** 在 host 闸门内执行 fn:排队等待的时间不占用 fn 内部的超时预算(超时在 fn 内自行起算) */
+export async function withHostLimit<T>(url: string, fn: () => Promise<T>): Promise<T> {
+ const release = await acquireHostSlot(hostOf(url));
+ try {
+ return await fn();
+ } finally {
+ release();
+ }
+}