broadcastHub.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import type { UtilityProcess as ElectronUtilityProcess } from "electron";
  2. import {
  3. HostMessageTypes,
  4. HostResponseTypes,
  5. broadcastMessageSchema,
  6. formatZodError,
  7. hostResponseMessageSchema,
  8. } from "@zcode/shared";
  9. import type { BroadcastMessage } from "@zcode/services";
  10. import { logger } from "./logger.js";
  11. /**
  12. * BroadcastHub —— main 进程中的广播中转站
  13. *
  14. * 管理所有活跃的 host process,当某个 host 发来广播消息时,
  15. * 转发给所有其他 host process。
  16. *
  17. * 广播路径:
  18. * Renderer A → (RPC) → Host A → (parentPort) → Main(BroadcastHub)
  19. * → (postMessage) → Host B → (RPC event) → Renderer B
  20. * → (postMessage) → Host C → (RPC event) → Renderer C
  21. */
  22. const MAX_BROADCAST_CLAIMS = 1_024;
  23. const BROADCAST_CLAIM_RESERVATION_TTL_MS = 5_000;
  24. const BROADCAST_CLAIM_RETRY_MS = 250;
  25. let claimTokenSequence = 0;
  26. type BroadcastClaimRecord = {
  27. token: string;
  28. ownerWindowId: number;
  29. status: "reserved" | "committed";
  30. expiresAt: number | null;
  31. };
  32. function createClaimToken(windowId: number, requestId: string): string {
  33. claimTokenSequence += 1;
  34. return `${windowId}:${requestId}:${claimTokenSequence}`;
  35. }
  36. export class BroadcastHub {
  37. onMobilePushRun: ((payload: unknown) => void) | undefined;
  38. onMobilePushEvent: ((payload: unknown) => void) | undefined;
  39. private processes = new Map<number, ElectronUtilityProcess>();
  40. /** 通用 opaque reservation/claim;不保存 Coding Plan 等业务状态。 */
  41. private readonly claims = new Map<string, BroadcastClaimRecord>();
  42. /** 内存诊断计数器;只读 size。 */
  43. collectMemoryDiagnostics(): Record<string, number> {
  44. return { claims: this.claims.size, processes: this.processes.size };
  45. }
  46. /** 注册 host process 并监听其广播消息 */
  47. register(windowId: number, child: ElectronUtilityProcess): void {
  48. this.processes.set(windowId, child);
  49. child.on("message", (msg: unknown) => {
  50. const result = hostResponseMessageSchema.safeParse(msg);
  51. if (!result.success) {
  52. logger.warn("[BroadcastHub] invalid host response message:", formatZodError(result.error));
  53. return;
  54. }
  55. if (result.data.type === HostResponseTypes.Broadcast) {
  56. this.relay(windowId, result.data.message);
  57. return;
  58. }
  59. if (result.data.type === HostResponseTypes.BroadcastClaimRequest) {
  60. this.handleClaim(windowId, child, result.data.requestId, result.data.key);
  61. return;
  62. }
  63. if (result.data.type === HostResponseTypes.BroadcastClaimCommit) {
  64. this.handleClaimCommit(windowId, result.data.key, result.data.claimToken);
  65. return;
  66. }
  67. if (result.data.type === HostResponseTypes.BroadcastClaimRelease) {
  68. this.handleClaimRelease(windowId, result.data.key, result.data.claimToken);
  69. }
  70. });
  71. }
  72. /** 注销 host process(窗口关闭时调用) */
  73. unregister(windowId: number): void {
  74. this.processes.delete(windowId);
  75. // 窗口在 reservation 返回前关闭时无法主动 release;只回收该窗口未 commit
  76. // 的占用,已 commit claim 继续保留,避免后来打开的窗口重播同一次完成提示。
  77. for (const [key, claim] of this.claims) {
  78. if (claim.ownerWindowId === windowId && claim.status === "reserved") {
  79. this.claims.delete(key);
  80. }
  81. }
  82. }
  83. private pruneExpiredReservations(now = Date.now()): void {
  84. for (const [key, claim] of this.claims) {
  85. if (claim.status === "reserved" && claim.expiresAt !== null && claim.expiresAt <= now) {
  86. this.claims.delete(key);
  87. }
  88. }
  89. while (this.claims.size > MAX_BROADCAST_CLAIMS) {
  90. const oldest = this.claims.keys().next().value as string | undefined;
  91. if (!oldest) {
  92. break;
  93. }
  94. this.claims.delete(oldest);
  95. }
  96. }
  97. /**
  98. * 原子申请 opaque key 的临时 reservation。Main 单线程保证 first-wins;reservation
  99. * 必须由 winner 在展示边界 commit,否则可按 token release,并受 TTL/host 注销兜底回收。
  100. */
  101. private handleClaim(
  102. windowId: number,
  103. source: ElectronUtilityProcess,
  104. requestId: string,
  105. key: string,
  106. ): void {
  107. const now = Date.now();
  108. this.pruneExpiredReservations(now);
  109. const existing = this.claims.get(key);
  110. if (existing?.status === "committed") {
  111. source.postMessage({
  112. type: HostMessageTypes.BroadcastClaimResult,
  113. requestId,
  114. status: "committed",
  115. });
  116. return;
  117. }
  118. if (existing) {
  119. source.postMessage({
  120. type: HostMessageTypes.BroadcastClaimResult,
  121. requestId,
  122. status: "busy",
  123. retryAfterMs: Math.max(
  124. 0,
  125. Math.min(BROADCAST_CLAIM_RETRY_MS, (existing.expiresAt ?? now) - now),
  126. ),
  127. });
  128. return;
  129. }
  130. const claimToken = createClaimToken(windowId, requestId);
  131. this.claims.set(key, {
  132. token: claimToken,
  133. ownerWindowId: windowId,
  134. status: "reserved",
  135. expiresAt: now + BROADCAST_CLAIM_RESERVATION_TTL_MS,
  136. });
  137. this.pruneExpiredReservations(now);
  138. source.postMessage({
  139. type: HostMessageTypes.BroadcastClaimResult,
  140. requestId,
  141. status: "acquired",
  142. claimToken,
  143. });
  144. }
  145. private handleClaimCommit(windowId: number, key: string, claimToken: string): void {
  146. this.pruneExpiredReservations();
  147. const current = this.claims.get(key);
  148. if (
  149. current?.status === "reserved" &&
  150. current.ownerWindowId === windowId &&
  151. current.token === claimToken
  152. ) {
  153. this.claims.set(key, { ...current, status: "committed", expiresAt: null });
  154. }
  155. }
  156. private handleClaimRelease(windowId: number, key: string, claimToken: string): void {
  157. this.pruneExpiredReservations();
  158. const current = this.claims.get(key);
  159. if (
  160. current?.status === "reserved" &&
  161. current.ownerWindowId === windowId &&
  162. current.token === claimToken
  163. ) {
  164. this.claims.delete(key);
  165. }
  166. }
  167. /** 将广播消息转发给除发送源以外的所有 host process */
  168. private relay(sourceWindowId: number, message: BroadcastMessage): void {
  169. const result = broadcastMessageSchema.safeParse(message);
  170. if (!result.success) {
  171. logger.warn("[BroadcastHub] invalid broadcast message:", formatZodError(result.error));
  172. return;
  173. }
  174. // 通知事实只交给 Main 网络适配器,不向其他 Host 回播形成第二次事件。
  175. if (result.data.channel === "mobile-push:run") {
  176. this.onMobilePushRun?.(result.data.payload);
  177. return;
  178. }
  179. if (result.data.channel === "mobile-push:event") {
  180. this.onMobilePushEvent?.(result.data.payload);
  181. return;
  182. }
  183. // 填充来源信息,接收端可用于去重
  184. const enriched: BroadcastMessage = { ...result.data, sourceWindowId };
  185. for (const [id, proc] of this.processes) {
  186. if (id !== sourceWindowId) {
  187. proc.postMessage({ type: HostMessageTypes.Broadcast, message: enriched });
  188. }
  189. }
  190. }
  191. }