| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301 |
- 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;
- /**
- * 安静期退避档数上限(2026-11-24 请求量优化)。
- * 节拍 = `POLL_MS * 2^level`:15s → 30s → 60s 封顶。
- */
- const POLL_MAX_LEVEL = 2;
- /**
- * 实况服务 —— **全项目唯一的轮询器**
- *
- * 依据 SPEC FR-14 AC-14.1/14.3 与《数据访问层设计.md》§五.1。
- *
- * 存量有 **4 个重叠轮询器**(15s + 10s + 桌面组件自建 10s + 移动组件自建 10s),
- * 且 `ConversationsService.stopPolling()` 是**空实现**(停不掉)。v2 收敛为这一个,
- * 且 `stop()` 必须**真实停止**(有单测覆盖)。
- *
- * 约束:
- * · 视图层**禁止**自建 `setInterval` 取数(AC-14.2)
- * · 其它服务**消费**本服务,不得各自轮询
- *
- * ## 请求量优化(2026-11-24 用户反馈「/api/functions 请求太多」)
- *
- * 轮询是唯一稳态来源(15s×24h ≈ 5760 次/天),两条减量策略:
- * ① **安静期退避**:数据连续未变时节拍 15s → 30s → 60s 封顶
- * (有变化/手动刷新/回前台立即复位 15s —— 容器跑活时数据每轮都变,
- * 天然保持快节拍,安静期才省请求)
- * ② **标签页隐藏暂停**:`document.hidden` 时空转节拍不发请求,
- * 回前台立即补一轮静默刷新
- * 失败轮次按「未变」处理(故障期同样退避,不给坏后端加压)。
- */
- @Injectable({ providedIn: 'root' })
- export class LiveService {
- private readonly api = inject(FmodeApi);
- private readonly _agents = signal<Agent[]>([]);
- private readonly _state = signal<LoadState>('idle');
- private readonly _error = signal<string | null>(null);
- private readonly _lastUpdated = signal<string | null>(null);
- /** 轮询轮次(数据未变也自增,供下游做快照对比) */
- private readonly _tick = signal(0);
- /**
- * 最近一次拉取成功的时刻(epoch ms,0 = 还没拉过)。
- *
- * 🔴 为什么需要(2026-11-11):云函数直出的 `heartbeatAgeSec` 是
- * **响应那一刻**的年龄。本服务每 15 秒轮询一次,两次拉取之间
- * `heartbeatAgeSec` 是冻结的 —— 直接拿它判「是否超过 80 分钟」,
- * 真实年龄会被低估最多 15 秒。
- *
- * 判定在线时应使用 `heartbeatAgeSec + (now - fetchedAt)`,
- * 见 `agent-liveness.ts` 中 `livenessOf` 的 `now` 参数说明。
- */
- private readonly _fetchedAt = signal(0);
- readonly fetchedAt = this._fetchedAt.asReadonly();
- readonly tick = this._tick.asReadonly();
- 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<typeof setTimeout> | null = null;
- /**
- * 安静期退避档(0=15s / 1=30s / 2=60s)。
- * 数据有变化、手动刷新、回前台时归零。
- */
- private backoffLevel = 0;
- /** 上一轮 load 是否检测到数据变化(驱动退避;失败按未变处理) */
- private lastChanged = true;
- /** visibilitychange 监听解注册(stop 时摘除) */
- private visListener: (() => void) | null = null;
- /** 递增序号:切上下文/并发请求时丢弃过期回包(存量 seq 模式) */
- private seq = 0;
- /** 进行中的首次加载(并发调用共享,避免"加载中"被误判为"不存在") */
- private _inflight: Promise<void> | null = null;
- /**
- * 就地更新单个容器(2026-11-04)。
- *
- * 用于「重命名」这类**小范围**变更:整表重拉会让列表闪烁、
- * 也会打断正在进行的操作。下一次轮询仍以服务端为准。
- */
- patchAgent(next: Agent): void {
- this._agents.update((list) => list.map((a) => (a.id === next.id ? { ...a, ...next } : a)));
- }
- /** 首次加载(若已有数据则不重复请求) */
- async ensureLoaded(): Promise<void> {
- /*
- * 🔴 `empty` 也算「已加载过」。
- * `load()` 在列表为空时设的是 `state='empty'`,只判 'ready' 会导致
- * 每次调用都重新请求(列表为空时尤为浪费)。
- */
- if (this._state() === 'ready' || this._state() === 'empty') return;
- /*
- * 🔴 `loading` 时必须**等待**进行中的那次加载,不能直接 return。
- *
- * 原实现 `if (ready || loading) return;` —— 并发调用方(如聊天页
- * `onRouteChange` 与 shell 的启动加载同时触发)里,后到者立刻拿到 undefined,
- * 上层据此判「数字生命不存在」→ 刷新页面时报错(实测)。
- *
- * 改为复用同一个 in-flight Promise:所有人等到同一份数据。
- */
- if (this._inflight) return this._inflight;
- this._inflight = this.load().then(() => undefined).finally(() => {
- this._inflight = null;
- });
- return this._inflight;
- }
- /**
- * 加载实况数据。
- *
- * @param silent `true` = **静默更新**(轮询触发的常规刷新):
- * ① **不置 `loading`** —— 否则列表每 15s 闪一次骨架屏(实测反馈)
- * ② 数据**未变化时不换数组引用** —— 否则 `@for` 重算、滚动位置与选中态抖动
- *
- * 口径:
- * · 首次加载 / 手动「刷新」→ 非静默(用户需要看到加载反馈)
- * · 定时轮询 → 静默
- */
- async load(silent = false): Promise<Agent[] | null> {
- 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 agents; // 不覆盖较新轮次;调用者仍能消费本次真实结果
- // 数据未变 → 不换引用(避免整列重渲染导致闪烁/滚动跳动)
- if (!sameAgents(this._agents(), agents)) {
- this._agents.set(agents);
- this.lastChanged = true;
- } else {
- /*
- * 🔴 数据没变也必须让下游「知道又到一轮了」。
- *
- * `TaskPulseService` 靠每次轮询建立快照对比来发现状态翻转;
- * 只在引用变化时才通知的话,「running → idle 但其它字段都没动」
- * 这种最常见的翻转会被吞掉。故用独立的轻量信号承载轮次。
- */
- this._tick.update((n) => n + 1);
- this.lastChanged = false;
- }
- // 区分「空」与「就绪」:空列表是合法但需显示空态的状态(AC-03.4 禁止用空态掩盖失败)
- this._state.set(agents.length === 0 ? 'empty' : 'ready');
- this._lastUpdated.set(new Date().toISOString());
- /* 记录拉取时刻:心跳年龄判定要以此为基准向后推算(见 _fetchedAt 注释) */
- this._fetchedAt.set(Date.now());
- return agents;
- } catch (e) {
- if (my !== this.seq) return null;
- this._state.set('error');
- this._error.set(e instanceof Error ? e.message : '实况数据加载失败');
- /* 失败轮次按「未变」处理:故障期退避,不给坏后端/故障端加压(2026-11-24) */
- this.lastChanged = false;
- return null;
- }
- }
- /** 手动刷新(工作台「刷新实况」按钮):同时复位退避节拍 */
- async refresh(): Promise<Agent[] | null> {
- this.backoffLevel = 0;
- return this.load();
- }
- /** 启动轮询;重复调用不会产生第二个定时器 */
- start(): void {
- if (this.timer) return;
- this.polling.set(true);
- this.backoffLevel = 0;
- void this.load(); // 首屏:非静默,让骨架屏生效
- this.schedule(POLL_MS);
- /*
- * 🔴 回到前台立刻补一轮(2026-11-24)。
- * 隐藏期节拍空转(见 onTick),数据可能已落后;可见即静默刷新并复位节拍。
- */
- const onVisible = () => {
- if (this.isPageHidden() || !this.timer) return;
- this.backoffLevel = 0;
- void this.load(true);
- this.schedule(POLL_MS);
- };
- document.addEventListener('visibilitychange', onVisible);
- this.visListener = () => document.removeEventListener('visibilitychange', onVisible);
- }
- /**
- * 停止轮询 —— **真实停止**(AC-14.3:不得空实现)
- * 单测断言:调用后定时器不再触发。
- */
- stop(): void {
- if (this.timer) {
- clearTimeout(this.timer);
- this.timer = null;
- }
- if (this.visListener) {
- this.visListener();
- this.visListener = null;
- }
- this.polling.set(false);
- }
- /** 安排下一拍(setTimeout 链:每拍时长随退避档变化,setInterval 做不到) */
- private schedule(ms: number): void {
- if (this.timer) clearTimeout(this.timer);
- this.timer = setTimeout(() => void this.onTick(), ms);
- }
- private onTick(): void {
- if (!this.timer) return; // stop 后迟到的回调
- /* 隐藏期空转节拍:不发请求,保持链条存活(回前台由 visibility 监听立即补数) */
- if (this.isPageHidden()) {
- this.schedule(POLL_MS);
- return;
- }
- void this.load(true).then(() => {
- if (!this.timer) return; // load 期间被 stop
- this.backoffLevel = this.lastChanged
- ? 0
- : Math.min(this.backoffLevel + 1, POLL_MAX_LEVEL);
- this.schedule(POLL_MS * 2 ** this.backoffLevel);
- });
- }
- /** 标签页是否隐藏(抽方法便于单测打桩) */
- private isPageHidden(): boolean {
- return typeof document !== 'undefined' && document.hidden;
- }
- /** 复位(退出登录时调用) */
- 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.provisioned === y.provisioned &&
- 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 &&
- x.channels?.matrixConfig?.channelState === y.channels?.matrixConfig?.channelState
- );
- }
|