live.service.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. * 实况服务 —— **全项目唯一的轮询器**
  8. *
  9. * 依据 SPEC FR-14 AC-14.1/14.3 与《数据访问层设计.md》§五.1。
  10. *
  11. * 存量有 **4 个重叠轮询器**(15s + 10s + 桌面组件自建 10s + 移动组件自建 10s),
  12. * 且 `ConversationsService.stopPolling()` 是**空实现**(停不掉)。v2 收敛为这一个,
  13. * 且 `stop()` 必须**真实停止**(有单测覆盖)。
  14. *
  15. * 约束:
  16. * · 视图层**禁止**自建 `setInterval` 取数(AC-14.2)
  17. * · 其它服务**消费**本服务,不得各自轮询
  18. */
  19. @Injectable({ providedIn: 'root' })
  20. export class LiveService {
  21. private readonly api = inject(FmodeApi);
  22. private readonly _agents = signal<Agent[]>([]);
  23. private readonly _state = signal<LoadState>('idle');
  24. private readonly _error = signal<string | null>(null);
  25. private readonly _lastUpdated = signal<string | null>(null);
  26. readonly agents = this._agents.asReadonly();
  27. readonly state = this._state.asReadonly();
  28. readonly error = this._error.asReadonly();
  29. readonly lastUpdated = this._lastUpdated.asReadonly();
  30. readonly hasData = computed(() => this._agents().length > 0);
  31. readonly blockedAgents = computed(() => this._agents().filter((a) => a.status === 'error'));
  32. /** 当前是否在轮询(用于界面提示与单测断言) */
  33. readonly polling = signal(false);
  34. private timer: ReturnType<typeof setInterval> | null = null;
  35. /** 递增序号:切上下文/并发请求时丢弃过期回包(存量 seq 模式) */
  36. private seq = 0;
  37. /** 进行中的首次加载(并发调用共享,避免"加载中"被误判为"不存在") */
  38. private _inflight: Promise<void> | null = null;
  39. /** 首次加载(若已有数据则不重复请求) */
  40. async ensureLoaded(): Promise<void> {
  41. if (this._state() === 'ready') return;
  42. /*
  43. * 🔴 `loading` 时必须**等待**进行中的那次加载,不能直接 return。
  44. *
  45. * 原实现 `if (ready || loading) return;` —— 并发调用方(如聊天页
  46. * `onRouteChange` 与 shell 的启动加载同时触发)里,后到者立刻拿到 undefined,
  47. * 上层据此判「数字生命不存在」→ 刷新页面时报错(实测)。
  48. *
  49. * 改为复用同一个 in-flight Promise:所有人等到同一份数据。
  50. */
  51. if (this._inflight) return this._inflight;
  52. this._inflight = this.load().finally(() => {
  53. this._inflight = null;
  54. });
  55. return this._inflight;
  56. }
  57. /**
  58. * 加载实况数据。
  59. *
  60. * @param silent `true` = **静默更新**(轮询触发的常规刷新):
  61. * ① **不置 `loading`** —— 否则列表每 15s 闪一次骨架屏(实测反馈)
  62. * ② 数据**未变化时不换数组引用** —— 否则 `@for` 重算、滚动位置与选中态抖动
  63. *
  64. * 口径:
  65. * · 首次加载 / 手动「刷新」→ 非静默(用户需要看到加载反馈)
  66. * · 定时轮询 → 静默
  67. */
  68. async load(silent = false): Promise<void> {
  69. const my = ++this.seq;
  70. if (!silent) {
  71. this._state.set('loading');
  72. }
  73. this._error.set(null);
  74. try {
  75. const agents = await this.api.fetchAgents();
  76. if (my !== this.seq) return; // 过期回包丢弃
  77. // 数据未变 → 不换引用(避免整列重渲染导致闪烁/滚动跳动)
  78. if (!sameAgents(this._agents(), agents)) {
  79. this._agents.set(agents);
  80. }
  81. // 区分「空」与「就绪」:空列表是合法但需显示空态的状态(AC-03.4 禁止用空态掩盖失败)
  82. this._state.set(agents.length === 0 ? 'empty' : 'ready');
  83. this._lastUpdated.set(new Date().toISOString());
  84. } catch (e) {
  85. if (my !== this.seq) return;
  86. this._state.set('error');
  87. this._error.set(e instanceof Error ? e.message : '实况数据加载失败');
  88. }
  89. }
  90. /** 手动刷新(工作台「刷新实况」按钮) */
  91. async refresh(): Promise<void> {
  92. await this.load();
  93. }
  94. /** 启动轮询;重复调用不会产生第二个定时器 */
  95. start(): void {
  96. if (this.timer) return;
  97. this.polling.set(true);
  98. void this.load(); // 首屏:非静默,让骨架屏生效
  99. this.timer = setInterval(() => void this.load(true), POLL_MS); // 轮询:静默
  100. }
  101. /**
  102. * 停止轮询 —— **真实停止**(AC-14.3:不得空实现)
  103. * 单测断言:调用后定时器不再触发。
  104. */
  105. stop(): void {
  106. if (this.timer) {
  107. clearInterval(this.timer);
  108. this.timer = null;
  109. }
  110. this.polling.set(false);
  111. }
  112. /** 复位(退出登录时调用) */
  113. reset(): void {
  114. this.stop();
  115. this.seq++;
  116. this._agents.set([]);
  117. this._state.set('idle');
  118. this._error.set(null);
  119. this._lastUpdated.set(null);
  120. }
  121. /** 单条查询(详情页;不发新请求,从已加载列表取,避免重复取数) */
  122. agentById(id: string): Agent | undefined {
  123. return this._agents().find((a) => a.id === id);
  124. }
  125. }
  126. /**
  127. * 两个 agent 列表是否**实质相同**(决定要不要换数组引用)。
  128. *
  129. * 比较 id 与所有可能影响界面的字段;顺序敏感(列表顺序变化属可见变化)。
  130. * 目的:轮询周期内数据没变时**不触发重渲染**,避免骨架屏/滚动位置抖动。
  131. */
  132. function sameAgents(a: Agent[], b: Agent[]): boolean {
  133. if (a === b) return true;
  134. if (a.length !== b.length) return false;
  135. for (let i = 0; i < a.length; i++) {
  136. if (!sameAgent(a[i], b[i])) return false;
  137. }
  138. return true;
  139. }
  140. function sameAgent(x: Agent, y: Agent): boolean {
  141. return (
  142. x.id === y.id &&
  143. x.name === y.name &&
  144. x.avatar === y.avatar &&
  145. x.status === y.status &&
  146. x.statusText === y.statusText &&
  147. x.currentTask === y.currentTask &&
  148. x.currentAction === y.currentAction &&
  149. x.progress === y.progress &&
  150. x.heartbeatAt === y.heartbeatAt &&
  151. x.updatedAt === y.updatedAt &&
  152. x.matrixReady === y.matrixReady &&
  153. x.unread === y.unread &&
  154. x.companyId === y.companyId &&
  155. // 嵌套对象按关键字段比(避免深比较开销)
  156. x.host?.cpuPercent === y.host?.cpuPercent &&
  157. x.host?.memPercent === y.host?.memPercent &&
  158. x.host?.diskPercent === y.host?.diskPercent &&
  159. x.balance?.remainCny === y.balance?.remainCny &&
  160. x.channels?.matrix === y.channels?.matrix &&
  161. x.channels?.matrixConfig?.userId === y.channels?.matrixConfig?.userId
  162. );
  163. }