覆盖 Phase 2e-2 代码审查报告(docs/reviews/2026-04-23-phase2e-2-code-review.md) P2/Nit 收尾批次,均在本仓库完成闭环;剩余 5 项登记推迟至 Phase 2f/3。 ===== P2 七项 ===== - P2-1 cleanupUserResources 补 transport 清理 · media-server 新增 DELETE /internal/v1/transports/:id + transport.service.closeTransport · Go MediaOrchestrator 接口新增 CloseTransport;HTTP 实现按 doCloseRequest 走 4xx 幂等 + 指数退避 · meeting_signal_service.cleanupUserResources 新增 "transport:<id>" 分支 - P2-2 preview.vue 快速切设备竞态 · previewSeq 序号 + nextTick 后 stale 判断,丢弃过期结果 · onVideoChange/onAudioChange 走 scheduleRestartPreview 200ms 防抖 · onBeforeUnmount 清理 changeDebounceTimer - P2-3 room.vue onLoad redirectTo 后补 return · 引入 redirectingToJoin 守卫,跳转页不再执行 onMounted 初始化 - P2-6 generateUniqueRoomCode 重试上限监控 · 重试后成功:Warn 日志(码空间健康度告警) · 重试耗尽:Error 日志 + ErrRoomCodeConflict · 修正 logs.Error 调用签名(去掉多余的 nil) - P2-7 SendChatMessage 服务端长度 + 频率限制 · 新增 ErrChatContentEmpty / ErrChatContentTooLong / ErrChatRateLimited · utf8.RuneCountInString 校验 500 字符上限 · Redis INCR + EXPIRE 滑动窗口(30 条/60s,首次写入 EXPIRE 兜底) · controller.handleError 映射为 HTTP 400 - P2-8 MEETING_ENDED_REASON_LABEL 覆盖复核 · 新增前端专属常量 MEETING_ENDED_REASON_KICKED + 文案 · store/meeting.js _onMemberKicked 使用常量 · 同步修复后端 OnWSDisconnect 硬编码 "ws_disconnect" → constants.MeetingLeftReasonDisconnect - P2 已修 P2-1/2/3/6/7/8;P2-4(WS token 迁出 URL query)与 P2-5(Chat 服务拆分)登记推迟 ===== Nit 七项 ===== - Nit: kind:id 解析改用 strings.SplitN · cleanupUserResources / pushExistingRoomState 两处同步 - Nit: resourceTTL 中央化 · 新增 constants.MeetingResourceTrackTTLSeconds(3600) · meeting_signal_service.go resourceTTL 由 const 改 var 并引用常量 - Nit: ws/handler.go CheckOrigin 白名单 · NewHandler 新增 serverCfg 依赖;checkOrigin 支持同源放行 / dev 模式放行 / release 模式白名单严格匹配 · config.ServerConfig 新增 WSAllowedOrigins(逗号分隔)+ AllowedOrigins() / IsRelease() 辅助方法 · provider.go 新增 provideServerConfig,wire_gen.go 同步 - Nit: http_media_orchestrator.go 超时 + CreateRouter 重试 · 默认 TimeoutMS 5000→10000ms 兼容 Worker 冷启动 · 新增 CreateRouterRetry(默认 1 次,300ms 退避),仅对非 404 错误重试 · config.dev.yaml / config.docker.yaml 同步写入显式配置 - Nit: deploy-public.sh REDIS_PASSWORD × redis.conf 联动校验 · 检测 REDIS_PASSWORD 与 redis.conf 的 requirepass 配对一致性 · redis.conf 增加公网部署 requirepass 使用说明 - Nit: media-server internal-auth isPrivatePath 按 path 匹配 · 剔除 query/hash 后再与白名单 startsWith,避免 "?" 语义混淆 - Nit: mediasoup-client.js in-flight 锁走读确认 · finally 分支已覆盖 resolve/reject 两路,追加注释强化语义 - Nit 走读复核:_onMemberLeft 整槽关闭 vs _onProducerNew(closed=true) 精确匹配 producerId · 粒度正确,无需改动(登记结论) ===== 构建验证 ===== - go vet ./... / go build ./... 通过 - frontend npm run build:h5 通过(仅 uni-app legacy warning,无 error) - media-server npx tsc --noEmit 通过 ===== 审查追踪小节 ===== docs/reviews/2026-04-23-phase2e-2-code-review.md 追加 "Task 16 修复追踪(2026-04-24 更新)": - 已修复一览(本批次 14 处 + 历次 commitcdaa39d/ea2bf96/f5ae095/ 5ed14c2) - 推迟登记表(P2-4 / P2-5 / 端口收敛 / appData 校验 / RFC3339 时间格式,共 5 项) Made-with: Cursor
181 lines
5.1 KiB
TypeScript
181 lines
5.1 KiB
TypeScript
import type {
|
||
DtlsParameters,
|
||
IceCandidate,
|
||
IceParameters,
|
||
WebRtcTransport,
|
||
} from 'mediasoup/types';
|
||
|
||
import { config } from '../config.js';
|
||
import { AppError, conflict, notFound } from '../utils/errors.js';
|
||
import { childLogger } from '../utils/logger.js';
|
||
import { assertTestOnly } from '../utils/test-guard.js';
|
||
|
||
import { getRouter } from './router.service.js';
|
||
import type { TransportDirection } from '../schemas/transport.schema.js';
|
||
|
||
const log = childLogger({ module: 'services.transport' });
|
||
|
||
interface TransportEntry {
|
||
transport: WebRtcTransport;
|
||
routerId: string;
|
||
userId: string;
|
||
direction: TransportDirection;
|
||
connected: boolean;
|
||
createdAt: number;
|
||
}
|
||
|
||
const transportMap = new Map<string, TransportEntry>();
|
||
|
||
export interface CreatedTransportInfo {
|
||
id: string;
|
||
iceParameters: IceParameters;
|
||
iceCandidates: IceCandidate[];
|
||
dtlsParameters: DtlsParameters;
|
||
}
|
||
|
||
function buildListenIps(): Array<{ ip: string; announcedIp?: string }> {
|
||
const entry: { ip: string; announcedIp?: string } = {
|
||
ip: config.mediasoup.listenIp,
|
||
};
|
||
if (config.mediasoup.announcedIp) {
|
||
entry.announcedIp = config.mediasoup.announcedIp;
|
||
}
|
||
return [entry];
|
||
}
|
||
|
||
export async function createWebRtcTransport(params: {
|
||
routerId: string;
|
||
userId: string;
|
||
direction: TransportDirection;
|
||
}): Promise<CreatedTransportInfo> {
|
||
const router = getRouter(params.routerId);
|
||
|
||
const transport = await router.createWebRtcTransport({
|
||
listenIps: buildListenIps(),
|
||
enableUdp: true,
|
||
enableTcp: true,
|
||
preferUdp: true,
|
||
initialAvailableOutgoingBitrate: 1_000_000,
|
||
appData: {
|
||
userId: params.userId,
|
||
direction: params.direction,
|
||
routerId: params.routerId,
|
||
},
|
||
});
|
||
|
||
transport.observer.once('close', () => {
|
||
transportMap.delete(transport.id);
|
||
log.info(
|
||
{ transportId: transport.id, routerId: params.routerId, userId: params.userId },
|
||
'transport closed and removed from map',
|
||
);
|
||
});
|
||
|
||
transportMap.set(transport.id, {
|
||
transport,
|
||
routerId: params.routerId,
|
||
userId: params.userId,
|
||
direction: params.direction,
|
||
connected: false,
|
||
createdAt: Date.now(),
|
||
});
|
||
|
||
log.info(
|
||
{
|
||
transportId: transport.id,
|
||
routerId: params.routerId,
|
||
userId: params.userId,
|
||
direction: params.direction,
|
||
},
|
||
'webrtc transport created',
|
||
);
|
||
|
||
return {
|
||
id: transport.id,
|
||
iceParameters: transport.iceParameters,
|
||
iceCandidates: transport.iceCandidates,
|
||
dtlsParameters: transport.dtlsParameters,
|
||
};
|
||
}
|
||
|
||
export function getTransport(transportId: string): WebRtcTransport {
|
||
const entry = transportMap.get(transportId);
|
||
if (!entry) {
|
||
throw notFound('transport', transportId);
|
||
}
|
||
return entry.transport;
|
||
}
|
||
|
||
export function getTransportEntry(transportId: string): TransportEntry {
|
||
const entry = transportMap.get(transportId);
|
||
if (!entry) {
|
||
throw notFound('transport', transportId);
|
||
}
|
||
return entry;
|
||
}
|
||
|
||
export async function connectTransport(params: {
|
||
transportId: string;
|
||
dtlsParameters: DtlsParameters;
|
||
}): Promise<void> {
|
||
const entry = transportMap.get(params.transportId);
|
||
if (!entry) {
|
||
throw notFound('transport', params.transportId);
|
||
}
|
||
// 乐观锁:先置位再 await,防止并发重复 connect 被 mediasoup 层包成 500
|
||
if (entry.connected) {
|
||
throw conflict(`transport already connected: ${params.transportId}`);
|
||
}
|
||
entry.connected = true;
|
||
try {
|
||
await entry.transport.connect({ dtlsParameters: params.dtlsParameters });
|
||
log.info({ transportId: params.transportId }, 'transport connected');
|
||
} catch (err) {
|
||
entry.connected = false;
|
||
const message = err instanceof Error ? err.message : String(err);
|
||
throw new AppError('MEDIASOUP_ERROR', `failed to connect transport: ${message}`, {
|
||
transportId: params.transportId,
|
||
});
|
||
}
|
||
}
|
||
|
||
export function getTransportStats(): { total: number } {
|
||
return { total: transportMap.size };
|
||
}
|
||
|
||
/**
|
||
* 主动关闭指定 Transport(Task 16 P2-1:cleanupUserResources 补全)
|
||
* - 已不存在 → 抛 notFound(HTTP 层映射 404,Go orchestrator 视为已清理的幂等成功)
|
||
* - 已存在 → 调 transport.close(),observer 'close' 会自动从 transportMap 移除
|
||
* - 幂等:外层可放心重试;内部依赖 mediasoup 的 close() 本身幂等
|
||
*/
|
||
export function closeTransport(transportId: string): void {
|
||
const entry = transportMap.get(transportId);
|
||
if (!entry) {
|
||
throw notFound('transport', transportId);
|
||
}
|
||
try {
|
||
entry.transport.close();
|
||
} catch (err) {
|
||
// mediasoup 对重复 close 一般不抛,但仍吞错避免"部分成功"语义
|
||
log.warn(
|
||
{ transportId, err: err instanceof Error ? err.message : String(err) },
|
||
'transport.close threw (ignored, already closed?)',
|
||
);
|
||
}
|
||
log.info({ transportId, userId: entry.userId, routerId: entry.routerId }, 'transport closed via API');
|
||
}
|
||
|
||
/** 测试专用:复位 transportMap,生产环境调用会抛错 */
|
||
export function _clearTransportMap(): void {
|
||
assertTestOnly('_clearTransportMap');
|
||
for (const entry of transportMap.values()) {
|
||
try {
|
||
entry.transport.close();
|
||
} catch {
|
||
// already closed
|
||
}
|
||
}
|
||
transportMap.clear();
|
||
}
|