import { computed, inject, Injectable, signal } from '@angular/core'; import { FmodeApi } from './api/fmode-api'; import { Agent, LoadState } from './api/models'; /** 轮询节拍(《数据访问层设计.md》§五.1:收敛为 1 个轮询器) */ const POLL_MS = 15_000; /** * 实况服务 —— **全项目唯一的轮询器** * * 依据 SPEC FR-14 AC-14.1/14.3 与《数据访问层设计.md》§五.1。 * * 存量有 **4 个重叠轮询器**(15s + 10s + 桌面组件自建 10s + 移动组件自建 10s), * 且 `ConversationsService.stopPolling()` 是**空实现**(停不掉)。v2 收敛为这一个, * 且 `stop()` 必须**真实停止**(有单测覆盖)。 * * 约束: * · 视图层**禁止**自建 `setInterval` 取数(AC-14.2) * · 其它服务**消费**本服务,不得各自轮询 */ @Injectable({ providedIn: 'root' }) export class LiveService { private readonly api = inject(FmodeApi); private readonly _agents = signal([]); private readonly _state = signal('idle'); private readonly _error = signal(null); private readonly _lastUpdated = signal(null); readonly agents = this._agents.asReadonly(); readonly state = this._state.asReadonly(); readonly error = this._error.asReadonly(); readonly lastUpdated = this._lastUpdated.asReadonly(); readonly hasData = computed(() => this._agents().length > 0); readonly blockedAgents = computed(() => this._agents().filter((a) => a.status === 'error')); /** 当前是否在轮询(用于界面提示与单测断言) */ readonly polling = signal(false); private timer: ReturnType | null = null; /** 递增序号:切上下文/并发请求时丢弃过期回包(存量 seq 模式) */ private seq = 0; /** 首次加载(若已有数据则不重复请求) */ async ensureLoaded(): Promise { if (this._state() === 'ready' || this._state() === 'loading') return; await this.load(); } /** * 加载实况数据。 * * @param silent `true` = **静默更新**(轮询触发的常规刷新): * ① **不置 `loading`** —— 否则列表每 15s 闪一次骨架屏(实测反馈) * ② 数据**未变化时不换数组引用** —— 否则 `@for` 重算、滚动位置与选中态抖动 * * 口径: * · 首次加载 / 手动「刷新」→ 非静默(用户需要看到加载反馈) * · 定时轮询 → 静默 */ async load(silent = false): Promise { const my = ++this.seq; if (!silent) { this._state.set('loading'); } this._error.set(null); try { const agents = await this.api.fetchAgents(); if (my !== this.seq) return; // 过期回包丢弃 // 数据未变 → 不换引用(避免整列重渲染导致闪烁/滚动跳动) if (!sameAgents(this._agents(), agents)) { this._agents.set(agents); } // 区分「空」与「就绪」:空列表是合法但需显示空态的状态(AC-03.4 禁止用空态掩盖失败) this._state.set(agents.length === 0 ? 'empty' : 'ready'); this._lastUpdated.set(new Date().toISOString()); } catch (e) { if (my !== this.seq) return; this._state.set('error'); this._error.set(e instanceof Error ? e.message : '实况数据加载失败'); } } /** 手动刷新(工作台「刷新实况」按钮) */ async refresh(): Promise { await this.load(); } /** 启动轮询;重复调用不会产生第二个定时器 */ start(): void { if (this.timer) return; this.polling.set(true); void this.load(); // 首屏:非静默,让骨架屏生效 this.timer = setInterval(() => void this.load(true), POLL_MS); // 轮询:静默 } /** * 停止轮询 —— **真实停止**(AC-14.3:不得空实现) * 单测断言:调用后定时器不再触发。 */ stop(): void { if (this.timer) { clearInterval(this.timer); this.timer = null; } this.polling.set(false); } /** 复位(退出登录时调用) */ reset(): void { this.stop(); this.seq++; this._agents.set([]); this._state.set('idle'); this._error.set(null); this._lastUpdated.set(null); } /** 单条查询(详情页;不发新请求,从已加载列表取,避免重复取数) */ agentById(id: string): Agent | undefined { return this._agents().find((a) => a.id === id); } } /** * 两个 agent 列表是否**实质相同**(决定要不要换数组引用)。 * * 比较 id 与所有可能影响界面的字段;顺序敏感(列表顺序变化属可见变化)。 * 目的:轮询周期内数据没变时**不触发重渲染**,避免骨架屏/滚动位置抖动。 */ function sameAgents(a: Agent[], b: Agent[]): boolean { if (a === b) return true; if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (!sameAgent(a[i], b[i])) return false; } return true; } function sameAgent(x: Agent, y: Agent): boolean { return ( x.id === y.id && x.name === y.name && x.avatar === y.avatar && x.status === y.status && x.statusText === y.statusText && x.currentTask === y.currentTask && x.currentAction === y.currentAction && x.progress === y.progress && x.heartbeatAt === y.heartbeatAt && x.updatedAt === y.updatedAt && x.matrixReady === y.matrixReady && x.unread === y.unread && x.companyId === y.companyId && // 嵌套对象按关键字段比(避免深比较开销) x.host?.cpuPercent === y.host?.cpuPercent && x.host?.memPercent === y.host?.memPercent && x.host?.diskPercent === y.host?.diskPercent && x.balance?.remainCny === y.balance?.remainCny && x.channels?.matrix === y.channels?.matrix && x.channels?.matrixConfig?.userId === y.channels?.matrixConfig?.userId ); }