live.service.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import { computed, inject, Injectable, signal } from '@angular/core';
  2. import { FmodeApi } from './api/fmode-api';
  3. import { Agent, LoadState } from './api/models';
  4. /** 轮询节拍(《数据访问层设计.md》§五.1:收敛为 1 个轮询器) */
  5. const POLL_MS = 15_000;
  6. /**
  7. * 安静期退避档数上限(2026-11-24 请求量优化)。
  8. * 节拍 = `POLL_MS * 2^level`:15s → 30s → 60s 封顶。
  9. */
  10. const POLL_MAX_LEVEL = 2;
  11. /**
  12. * 实况服务 —— **全项目唯一的轮询器**
  13. *
  14. * 依据 SPEC FR-14 AC-14.1/14.3 与《数据访问层设计.md》§五.1。
  15. *
  16. * 存量有 **4 个重叠轮询器**(15s + 10s + 桌面组件自建 10s + 移动组件自建 10s),
  17. * 且 `ConversationsService.stopPolling()` 是**空实现**(停不掉)。v2 收敛为这一个,
  18. * 且 `stop()` 必须**真实停止**(有单测覆盖)。
  19. *
  20. * 约束:
  21. * · 视图层**禁止**自建 `setInterval` 取数(AC-14.2)
  22. * · 其它服务**消费**本服务,不得各自轮询
  23. *
  24. * ## 请求量优化(2026-11-24 用户反馈「/api/functions 请求太多」)
  25. *
  26. * 轮询是唯一稳态来源(15s×24h ≈ 5760 次/天),两条减量策略:
  27. * ① **安静期退避**:数据连续未变时节拍 15s → 30s → 60s 封顶
  28. * (有变化/手动刷新/回前台立即复位 15s —— 容器跑活时数据每轮都变,
  29. * 天然保持快节拍,安静期才省请求)
  30. * ② **标签页隐藏暂停**:`document.hidden` 时空转节拍不发请求,
  31. * 回前台立即补一轮静默刷新
  32. * 失败轮次按「未变」处理(故障期同样退避,不给坏后端加压)。
  33. */
  34. @Injectable({ providedIn: 'root' })
  35. export class LiveService {
  36. private readonly api = inject(FmodeApi);
  37. private readonly _agents = signal<Agent[]>([]);
  38. private readonly _state = signal<LoadState>('idle');
  39. private readonly _error = signal<string | null>(null);
  40. private readonly _lastUpdated = signal<string | null>(null);
  41. /** 轮询轮次(数据未变也自增,供下游做快照对比) */
  42. private readonly _tick = signal(0);
  43. /**
  44. * 最近一次拉取成功的时刻(epoch ms,0 = 还没拉过)。
  45. *
  46. * 🔴 为什么需要(2026-11-11):云函数直出的 `heartbeatAgeSec` 是
  47. * **响应那一刻**的年龄。本服务每 15 秒轮询一次,两次拉取之间
  48. * `heartbeatAgeSec` 是冻结的 —— 直接拿它判「是否超过 80 分钟」,
  49. * 真实年龄会被低估最多 15 秒。
  50. *
  51. * 判定在线时应使用 `heartbeatAgeSec + (now - fetchedAt)`,
  52. * 见 `agent-liveness.ts` 中 `livenessOf` 的 `now` 参数说明。
  53. */
  54. private readonly _fetchedAt = signal(0);
  55. readonly fetchedAt = this._fetchedAt.asReadonly();
  56. readonly tick = this._tick.asReadonly();
  57. readonly agents = this._agents.asReadonly();
  58. readonly state = this._state.asReadonly();
  59. readonly error = this._error.asReadonly();
  60. readonly lastUpdated = this._lastUpdated.asReadonly();
  61. readonly hasData = computed(() => this._agents().length > 0);
  62. readonly blockedAgents = computed(() => this._agents().filter((a) => a.status === 'error'));
  63. /** 当前是否在轮询(用于界面提示与单测断言) */
  64. readonly polling = signal(false);
  65. private timer: ReturnType<typeof setTimeout> | null = null;
  66. /**
  67. * 安静期退避档(0=15s / 1=30s / 2=60s)。
  68. * 数据有变化、手动刷新、回前台时归零。
  69. */
  70. private backoffLevel = 0;
  71. /** 上一轮 load 是否检测到数据变化(驱动退避;失败按未变处理) */
  72. private lastChanged = true;
  73. /** visibilitychange 监听解注册(stop 时摘除) */
  74. private visListener: (() => void) | null = null;
  75. /** 递增序号:切上下文/并发请求时丢弃过期回包(存量 seq 模式) */
  76. private seq = 0;
  77. /** 进行中的首次加载(并发调用共享,避免"加载中"被误判为"不存在") */
  78. private _inflight: Promise<void> | null = null;
  79. /**
  80. * 就地更新单个容器(2026-11-04)。
  81. *
  82. * 用于「重命名」这类**小范围**变更:整表重拉会让列表闪烁、
  83. * 也会打断正在进行的操作。下一次轮询仍以服务端为准。
  84. */
  85. patchAgent(next: Agent): void {
  86. this._agents.update((list) => list.map((a) => (a.id === next.id ? { ...a, ...next } : a)));
  87. }
  88. /** 首次加载(若已有数据则不重复请求) */
  89. async ensureLoaded(): Promise<void> {
  90. /*
  91. * 🔴 `empty` 也算「已加载过」。
  92. * `load()` 在列表为空时设的是 `state='empty'`,只判 'ready' 会导致
  93. * 每次调用都重新请求(列表为空时尤为浪费)。
  94. */
  95. if (this._state() === 'ready' || this._state() === 'empty') return;
  96. /*
  97. * 🔴 `loading` 时必须**等待**进行中的那次加载,不能直接 return。
  98. *
  99. * 原实现 `if (ready || loading) return;` —— 并发调用方(如聊天页
  100. * `onRouteChange` 与 shell 的启动加载同时触发)里,后到者立刻拿到 undefined,
  101. * 上层据此判「数字生命不存在」→ 刷新页面时报错(实测)。
  102. *
  103. * 改为复用同一个 in-flight Promise:所有人等到同一份数据。
  104. */
  105. if (this._inflight) return this._inflight;
  106. this._inflight = this.load().then(() => undefined).finally(() => {
  107. this._inflight = null;
  108. });
  109. return this._inflight;
  110. }
  111. /**
  112. * 加载实况数据。
  113. *
  114. * @param silent `true` = **静默更新**(轮询触发的常规刷新):
  115. * ① **不置 `loading`** —— 否则列表每 15s 闪一次骨架屏(实测反馈)
  116. * ② 数据**未变化时不换数组引用** —— 否则 `@for` 重算、滚动位置与选中态抖动
  117. *
  118. * 口径:
  119. * · 首次加载 / 手动「刷新」→ 非静默(用户需要看到加载反馈)
  120. * · 定时轮询 → 静默
  121. */
  122. async load(silent = false): Promise<Agent[] | null> {
  123. const my = ++this.seq;
  124. if (!silent) {
  125. this._state.set('loading');
  126. }
  127. this._error.set(null);
  128. try {
  129. const agents = await this.api.fetchAgents();
  130. if (my !== this.seq) return agents; // 不覆盖较新轮次;调用者仍能消费本次真实结果
  131. // 数据未变 → 不换引用(避免整列重渲染导致闪烁/滚动跳动)
  132. if (!sameAgents(this._agents(), agents)) {
  133. this._agents.set(agents);
  134. this.lastChanged = true;
  135. } else {
  136. /*
  137. * 🔴 数据没变也必须让下游「知道又到一轮了」。
  138. *
  139. * `TaskPulseService` 靠每次轮询建立快照对比来发现状态翻转;
  140. * 只在引用变化时才通知的话,「running → idle 但其它字段都没动」
  141. * 这种最常见的翻转会被吞掉。故用独立的轻量信号承载轮次。
  142. */
  143. this._tick.update((n) => n + 1);
  144. this.lastChanged = false;
  145. }
  146. // 区分「空」与「就绪」:空列表是合法但需显示空态的状态(AC-03.4 禁止用空态掩盖失败)
  147. this._state.set(agents.length === 0 ? 'empty' : 'ready');
  148. this._lastUpdated.set(new Date().toISOString());
  149. /* 记录拉取时刻:心跳年龄判定要以此为基准向后推算(见 _fetchedAt 注释) */
  150. this._fetchedAt.set(Date.now());
  151. return agents;
  152. } catch (e) {
  153. if (my !== this.seq) return null;
  154. this._state.set('error');
  155. this._error.set(e instanceof Error ? e.message : '实况数据加载失败');
  156. /* 失败轮次按「未变」处理:故障期退避,不给坏后端/故障端加压(2026-11-24) */
  157. this.lastChanged = false;
  158. return null;
  159. }
  160. }
  161. /** 手动刷新(工作台「刷新实况」按钮):同时复位退避节拍 */
  162. async refresh(): Promise<Agent[] | null> {
  163. this.backoffLevel = 0;
  164. return this.load();
  165. }
  166. /** 启动轮询;重复调用不会产生第二个定时器 */
  167. start(): void {
  168. if (this.timer) return;
  169. this.polling.set(true);
  170. this.backoffLevel = 0;
  171. void this.load(); // 首屏:非静默,让骨架屏生效
  172. this.schedule(POLL_MS);
  173. /*
  174. * 🔴 回到前台立刻补一轮(2026-11-24)。
  175. * 隐藏期节拍空转(见 onTick),数据可能已落后;可见即静默刷新并复位节拍。
  176. */
  177. const onVisible = () => {
  178. if (this.isPageHidden() || !this.timer) return;
  179. this.backoffLevel = 0;
  180. void this.load(true);
  181. this.schedule(POLL_MS);
  182. };
  183. document.addEventListener('visibilitychange', onVisible);
  184. this.visListener = () => document.removeEventListener('visibilitychange', onVisible);
  185. }
  186. /**
  187. * 停止轮询 —— **真实停止**(AC-14.3:不得空实现)
  188. * 单测断言:调用后定时器不再触发。
  189. */
  190. stop(): void {
  191. if (this.timer) {
  192. clearTimeout(this.timer);
  193. this.timer = null;
  194. }
  195. if (this.visListener) {
  196. this.visListener();
  197. this.visListener = null;
  198. }
  199. this.polling.set(false);
  200. }
  201. /** 安排下一拍(setTimeout 链:每拍时长随退避档变化,setInterval 做不到) */
  202. private schedule(ms: number): void {
  203. if (this.timer) clearTimeout(this.timer);
  204. this.timer = setTimeout(() => void this.onTick(), ms);
  205. }
  206. private onTick(): void {
  207. if (!this.timer) return; // stop 后迟到的回调
  208. /* 隐藏期空转节拍:不发请求,保持链条存活(回前台由 visibility 监听立即补数) */
  209. if (this.isPageHidden()) {
  210. this.schedule(POLL_MS);
  211. return;
  212. }
  213. void this.load(true).then(() => {
  214. if (!this.timer) return; // load 期间被 stop
  215. this.backoffLevel = this.lastChanged
  216. ? 0
  217. : Math.min(this.backoffLevel + 1, POLL_MAX_LEVEL);
  218. this.schedule(POLL_MS * 2 ** this.backoffLevel);
  219. });
  220. }
  221. /** 标签页是否隐藏(抽方法便于单测打桩) */
  222. private isPageHidden(): boolean {
  223. return typeof document !== 'undefined' && document.hidden;
  224. }
  225. /** 复位(退出登录时调用) */
  226. reset(): void {
  227. this.stop();
  228. this.seq++;
  229. this._agents.set([]);
  230. this._state.set('idle');
  231. this._error.set(null);
  232. this._lastUpdated.set(null);
  233. }
  234. /** 单条查询(详情页;不发新请求,从已加载列表取,避免重复取数) */
  235. agentById(id: string): Agent | undefined {
  236. return this._agents().find((a) => a.id === id);
  237. }
  238. }
  239. /**
  240. * 两个 agent 列表是否**实质相同**(决定要不要换数组引用)。
  241. *
  242. * 比较 id 与所有可能影响界面的字段;顺序敏感(列表顺序变化属可见变化)。
  243. * 目的:轮询周期内数据没变时**不触发重渲染**,避免骨架屏/滚动位置抖动。
  244. */
  245. function sameAgents(a: Agent[], b: Agent[]): boolean {
  246. if (a === b) return true;
  247. if (a.length !== b.length) return false;
  248. for (let i = 0; i < a.length; i++) {
  249. if (!sameAgent(a[i], b[i])) return false;
  250. }
  251. return true;
  252. }
  253. function sameAgent(x: Agent, y: Agent): boolean {
  254. return (
  255. x.id === y.id &&
  256. x.name === y.name &&
  257. x.avatar === y.avatar &&
  258. x.status === y.status &&
  259. x.statusText === y.statusText &&
  260. x.currentTask === y.currentTask &&
  261. x.currentAction === y.currentAction &&
  262. x.progress === y.progress &&
  263. x.heartbeatAt === y.heartbeatAt &&
  264. x.updatedAt === y.updatedAt &&
  265. x.matrixReady === y.matrixReady &&
  266. x.provisioned === y.provisioned &&
  267. x.unread === y.unread &&
  268. x.companyId === y.companyId &&
  269. // 嵌套对象按关键字段比(避免深比较开销)
  270. x.host?.cpuPercent === y.host?.cpuPercent &&
  271. x.host?.memPercent === y.host?.memPercent &&
  272. x.host?.diskPercent === y.host?.diskPercent &&
  273. x.balance?.remainCny === y.balance?.remainCny &&
  274. x.channels?.matrix === y.channels?.matrix &&
  275. x.channels?.matrixConfig?.userId === y.channels?.matrixConfig?.userId &&
  276. x.channels?.matrixConfig?.channelState === y.channels?.matrixConfig?.channelState
  277. );
  278. }