live.service.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. async ensureLoaded(): Promise<void> {
  39. if (this._state() === 'ready' || this._state() === 'loading') return;
  40. await this.load();
  41. }
  42. /**
  43. * 加载实况数据。
  44. *
  45. * @param silent `true` = **静默更新**(轮询触发的常规刷新):
  46. * ① **不置 `loading`** —— 否则列表每 15s 闪一次骨架屏(实测反馈)
  47. * ② 数据**未变化时不换数组引用** —— 否则 `@for` 重算、滚动位置与选中态抖动
  48. *
  49. * 口径:
  50. * · 首次加载 / 手动「刷新」→ 非静默(用户需要看到加载反馈)
  51. * · 定时轮询 → 静默
  52. */
  53. async load(silent = false): Promise<void> {
  54. const my = ++this.seq;
  55. if (!silent) {
  56. this._state.set('loading');
  57. }
  58. this._error.set(null);
  59. try {
  60. const agents = await this.api.fetchAgents();
  61. if (my !== this.seq) return; // 过期回包丢弃
  62. // 数据未变 → 不换引用(避免整列重渲染导致闪烁/滚动跳动)
  63. if (!sameAgents(this._agents(), agents)) {
  64. this._agents.set(agents);
  65. }
  66. // 区分「空」与「就绪」:空列表是合法但需显示空态的状态(AC-03.4 禁止用空态掩盖失败)
  67. this._state.set(agents.length === 0 ? 'empty' : 'ready');
  68. this._lastUpdated.set(new Date().toISOString());
  69. } catch (e) {
  70. if (my !== this.seq) return;
  71. this._state.set('error');
  72. this._error.set(e instanceof Error ? e.message : '实况数据加载失败');
  73. }
  74. }
  75. /** 手动刷新(工作台「刷新实况」按钮) */
  76. async refresh(): Promise<void> {
  77. await this.load();
  78. }
  79. /** 启动轮询;重复调用不会产生第二个定时器 */
  80. start(): void {
  81. if (this.timer) return;
  82. this.polling.set(true);
  83. void this.load(); // 首屏:非静默,让骨架屏生效
  84. this.timer = setInterval(() => void this.load(true), POLL_MS); // 轮询:静默
  85. }
  86. /**
  87. * 停止轮询 —— **真实停止**(AC-14.3:不得空实现)
  88. * 单测断言:调用后定时器不再触发。
  89. */
  90. stop(): void {
  91. if (this.timer) {
  92. clearInterval(this.timer);
  93. this.timer = null;
  94. }
  95. this.polling.set(false);
  96. }
  97. /** 复位(退出登录时调用) */
  98. reset(): void {
  99. this.stop();
  100. this.seq++;
  101. this._agents.set([]);
  102. this._state.set('idle');
  103. this._error.set(null);
  104. this._lastUpdated.set(null);
  105. }
  106. /** 单条查询(详情页;不发新请求,从已加载列表取,避免重复取数) */
  107. agentById(id: string): Agent | undefined {
  108. return this._agents().find((a) => a.id === id);
  109. }
  110. }
  111. /**
  112. * 两个 agent 列表是否**实质相同**(决定要不要换数组引用)。
  113. *
  114. * 比较 id 与所有可能影响界面的字段;顺序敏感(列表顺序变化属可见变化)。
  115. * 目的:轮询周期内数据没变时**不触发重渲染**,避免骨架屏/滚动位置抖动。
  116. */
  117. function sameAgents(a: Agent[], b: Agent[]): boolean {
  118. if (a === b) return true;
  119. if (a.length !== b.length) return false;
  120. for (let i = 0; i < a.length; i++) {
  121. if (!sameAgent(a[i], b[i])) return false;
  122. }
  123. return true;
  124. }
  125. function sameAgent(x: Agent, y: Agent): boolean {
  126. return (
  127. x.id === y.id &&
  128. x.name === y.name &&
  129. x.avatar === y.avatar &&
  130. x.status === y.status &&
  131. x.statusText === y.statusText &&
  132. x.currentTask === y.currentTask &&
  133. x.currentAction === y.currentAction &&
  134. x.progress === y.progress &&
  135. x.heartbeatAt === y.heartbeatAt &&
  136. x.updatedAt === y.updatedAt &&
  137. x.matrixReady === y.matrixReady &&
  138. x.unread === y.unread &&
  139. x.companyId === y.companyId &&
  140. // 嵌套对象按关键字段比(避免深比较开销)
  141. x.host?.cpuPercent === y.host?.cpuPercent &&
  142. x.host?.memPercent === y.host?.memPercent &&
  143. x.host?.diskPercent === y.host?.diskPercent &&
  144. x.balance?.remainCny === y.balance?.remainCny &&
  145. x.channels?.matrix === y.channels?.matrix &&
  146. x.channels?.matrixConfig?.userId === y.channels?.matrixConfig?.userId
  147. );
  148. }