zcode-builtin-remote-synchronizer.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import { randomUUID } from "node:crypto";
  2. import { readFile } from "node:fs/promises";
  3. import { atomicWritePrivateTextFile, withFileLock } from "@zcode/shared/node";
  4. import type { NodeZCodeBuiltinProviderConfigSource } from "./zcode-builtin-provider-config-source.js";
  5. import type { ZCodeBuiltinRelease } from "./zcode-builtin-release.js";
  6. const HOUR_MS = 60 * 60 * 1_000;
  7. export type ZCodeBuiltinRefreshResult =
  8. | "updated"
  9. | "unchanged"
  10. | "stale"
  11. | "missing"
  12. | "skipped"
  13. | "disposed";
  14. export interface ZCodeBuiltinRemoteSynchronizerOptions {
  15. readonly source: NodeZCodeBuiltinProviderConfigSource;
  16. readonly controlFilePath: string;
  17. readonly resolveEndpointKey: () => string | Promise<string>;
  18. readonly fetchRelease: (
  19. endpointKey: string,
  20. signal: AbortSignal,
  21. ) => Promise<ZCodeBuiltinRelease | null>;
  22. readonly onRefreshResult?: (event: ZCodeBuiltinRefreshEvent) => void;
  23. readonly now?: () => number;
  24. readonly successIntervalMs?: number;
  25. readonly leaseDurationMs?: number;
  26. readonly failureBaseDelayMs?: number;
  27. readonly failureMaxDelayMs?: number;
  28. }
  29. export interface ZCodeBuiltinRefreshEvent {
  30. readonly result: ZCodeBuiltinRefreshResult;
  31. readonly reason?: "lease-held" | "not-due" | "endpoint-changed";
  32. readonly revision?: number;
  33. }
  34. interface RefreshControl {
  35. readonly schemaVersion: 1;
  36. readonly endpointKey: string;
  37. readonly leaseId?: string;
  38. readonly leaseUntil: number;
  39. readonly nextEligibleAt: number;
  40. readonly failureCount: number;
  41. }
  42. /** Environment 共享控制文件合并多进程刷新;网络期间不持有文件锁。 */
  43. export class ZCodeBuiltinRemoteSynchronizer {
  44. readonly #options: ZCodeBuiltinRemoteSynchronizerOptions;
  45. readonly #now: () => number;
  46. #inFlight: Promise<ZCodeBuiltinRefreshResult> | null = null;
  47. #disposed = false;
  48. #abortController: AbortController | null = null;
  49. constructor(options: ZCodeBuiltinRemoteSynchronizerOptions) {
  50. this.#options = options;
  51. this.#now = options.now ?? Date.now;
  52. }
  53. refresh(options: { readonly force?: boolean } = {}): Promise<ZCodeBuiltinRefreshResult> {
  54. if (this.#disposed) return Promise.resolve("disposed");
  55. if (this.#inFlight) return this.#inFlight;
  56. const controller = new AbortController();
  57. this.#abortController = controller;
  58. const refresh = this.#refresh(options.force === true, controller.signal).finally(() => {
  59. if (this.#inFlight === refresh) {
  60. this.#inFlight = null;
  61. this.#abortController = null;
  62. }
  63. });
  64. this.#inFlight = refresh;
  65. return refresh;
  66. }
  67. dispose(): void {
  68. this.#disposed = true;
  69. this.#abortController?.abort();
  70. }
  71. async #refresh(force: boolean, signal: AbortSignal): Promise<ZCodeBuiltinRefreshResult> {
  72. const endpointKey = (await this.#options.resolveEndpointKey()).trim();
  73. if (this.#disposed) return "disposed";
  74. if (!endpointKey) throw new Error("ZCode Built-in 远端 Endpoint 不能为空");
  75. const leaseId = randomUUID();
  76. const acquired = await withFileLock(this.#options.controlFilePath, async () => {
  77. const now = this.#now();
  78. const current = await readControl(this.#options.controlFilePath);
  79. const sameEndpoint = current.endpointKey === endpointKey;
  80. if (sameEndpoint && current.leaseUntil > now) return "lease-held" as const;
  81. if (!force && sameEndpoint && current.nextEligibleAt > now) return "not-due" as const;
  82. await writeControl(this.#options.controlFilePath, {
  83. schemaVersion: 1,
  84. endpointKey,
  85. leaseId,
  86. leaseUntil: now + (this.#options.leaseDurationMs ?? 30_000),
  87. nextEligibleAt: sameEndpoint ? current.nextEligibleAt : 0,
  88. failureCount: sameEndpoint ? current.failureCount : 0,
  89. });
  90. return true;
  91. });
  92. if (acquired !== true) {
  93. this.#report({ result: "skipped", reason: acquired });
  94. return "skipped";
  95. }
  96. try {
  97. signal.throwIfAborted();
  98. const release = await this.#options.fetchRelease(endpointKey, signal);
  99. if (this.#disposed) {
  100. await this.#finishLease(endpointKey, leaseId, "cancelled");
  101. return "disposed";
  102. }
  103. const currentEndpointKey = (await this.#options.resolveEndpointKey()).trim();
  104. signal.throwIfAborted();
  105. if (currentEndpointKey !== endpointKey) {
  106. await this.#finishLease(endpointKey, leaseId, true);
  107. this.#report({ result: "skipped", reason: "endpoint-changed" });
  108. return "skipped";
  109. }
  110. const result = release ? await this.#options.source.applyRemoteRelease(release) : "missing";
  111. await this.#finishLease(endpointKey, leaseId, true);
  112. this.#report({ result, ...(release ? { revision: release.revision } : {}) });
  113. return result;
  114. } catch (error) {
  115. await this.#finishLease(endpointKey, leaseId, this.#disposed ? "cancelled" : false);
  116. if (this.#disposed) return "disposed";
  117. throw error;
  118. }
  119. }
  120. #report(event: ZCodeBuiltinRefreshEvent): void {
  121. if (this.#disposed) return;
  122. try {
  123. this.#options.onRefreshResult?.(event);
  124. } catch {
  125. /* 日志不能把成功应用改成下载失败。 */
  126. }
  127. }
  128. async #finishLease(
  129. endpointKey: string,
  130. leaseId: string,
  131. success: boolean | "cancelled",
  132. ): Promise<void> {
  133. await withFileLock(this.#options.controlFilePath, async () => {
  134. const current = await readControl(this.#options.controlFilePath);
  135. if (current.endpointKey !== endpointKey || current.leaseId !== leaseId) return;
  136. const failureCount =
  137. success === "cancelled" ? current.failureCount : success ? 0 : current.failureCount + 1;
  138. const delay =
  139. success === "cancelled"
  140. ? 0
  141. : success
  142. ? (this.#options.successIntervalMs ?? HOUR_MS)
  143. : Math.min(
  144. (this.#options.failureBaseDelayMs ?? 60_000) * 2 ** Math.max(0, failureCount - 1),
  145. this.#options.failureMaxDelayMs ?? HOUR_MS,
  146. );
  147. await writeControl(this.#options.controlFilePath, {
  148. schemaVersion: 1,
  149. endpointKey,
  150. leaseUntil: 0,
  151. nextEligibleAt: this.#now() + delay,
  152. failureCount,
  153. });
  154. });
  155. }
  156. }
  157. async function readControl(filePath: string): Promise<RefreshControl> {
  158. let raw: string;
  159. try {
  160. raw = await readFile(filePath, "utf8");
  161. } catch (error) {
  162. if (isFileNotFound(error)) return emptyControl();
  163. throw error;
  164. }
  165. try {
  166. const input = JSON.parse(raw) as unknown;
  167. return isRefreshControl(input) ? input : emptyControl();
  168. } catch {
  169. // 控制文件不是业务事实;进程崩溃留下的损坏内容在锁内重建,不能永久阻断刷新。
  170. return emptyControl();
  171. }
  172. }
  173. function emptyControl(): RefreshControl {
  174. return { schemaVersion: 1, endpointKey: "", leaseUntil: 0, nextEligibleAt: 0, failureCount: 0 };
  175. }
  176. function writeControl(filePath: string, control: RefreshControl): Promise<void> {
  177. return atomicWritePrivateTextFile(filePath, JSON.stringify(control, null, 2));
  178. }
  179. function isRefreshControl(input: unknown): input is RefreshControl {
  180. if (typeof input !== "object" || input === null || Array.isArray(input)) return false;
  181. const value = input as Record<string, unknown>;
  182. return (
  183. value.schemaVersion === 1 &&
  184. typeof value.endpointKey === "string" &&
  185. (value.leaseId === undefined || typeof value.leaseId === "string") &&
  186. typeof value.leaseUntil === "number" &&
  187. typeof value.nextEligibleAt === "number" &&
  188. Number.isInteger(value.failureCount) &&
  189. (value.failureCount as number) >= 0
  190. );
  191. }
  192. function isFileNotFound(error: unknown): boolean {
  193. return (
  194. typeof error === "object" &&
  195. error !== null &&
  196. "code" in error &&
  197. (error as { code?: unknown }).code === "ENOENT"
  198. );
  199. }