zcode-builtin-provider-config-source.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import { watch, type FSWatcher } from "node:fs";
  2. import { createHash } from "node:crypto";
  3. import { mkdir, readFile } from "node:fs/promises";
  4. import { basename, dirname, resolve } from "node:path";
  5. import type { ProviderConfigLayerSnapshot, ProviderSource } from "@zcode/provider";
  6. import { atomicWritePrivateTextFile, withFileLock } from "@zcode/shared/node";
  7. import {
  8. decodeZCodeBuiltinRelease,
  9. encodeZCodeBuiltinRelease,
  10. serializeZCodeBuiltinRelease,
  11. type ZCodeBuiltinRelease,
  12. } from "./zcode-builtin-release.js";
  13. export interface NodeZCodeBuiltinProviderConfigSourceOptions {
  14. readonly bundledFilePath: string;
  15. readonly activeFilePath?: string;
  16. readonly watch?: boolean;
  17. }
  18. export type ApplyZCodeBuiltinReleaseResult = "updated" | "unchanged" | "stale";
  19. /** Bundled、Active/LKG 与 Remote 共用同一 Release,并最终发布为现有 Config Snapshot。 */
  20. export class NodeZCodeBuiltinProviderConfigSource implements ProviderSource<ProviderConfigLayerSnapshot> {
  21. readonly #bundledFilePath: string;
  22. readonly #activeFilePath: string;
  23. readonly #sourceKey: string;
  24. readonly #watchEnabled: boolean;
  25. readonly #listeners = new Set<(reason: string) => void>();
  26. #watcher: FSWatcher | null = null;
  27. #observedSignature: string | null = null;
  28. #watchRefresh = Promise.resolve();
  29. #disposed = false;
  30. constructor(options: NodeZCodeBuiltinProviderConfigSourceOptions) {
  31. const bundledFilePath = options.bundledFilePath.trim();
  32. if (!bundledFilePath) throw new Error("ZCode Built-in bundledFilePath 不能为空");
  33. this.#bundledFilePath = bundledFilePath;
  34. this.#activeFilePath = options.activeFilePath?.trim() || bundledFilePath;
  35. // 旧标识只有发布序号,不同 Endpoint 同序号会让 Registry 误复用上一来源。
  36. // Active 路径已含规范化 Endpoint 隔离范围;Worker 收到同一路径,不另拼账号事实。
  37. this.#sourceKey = createHash("sha256").update(resolve(this.#activeFilePath)).digest("hex");
  38. this.#watchEnabled = options.watch !== false;
  39. }
  40. get activeFilePath(): string {
  41. return this.#activeFilePath;
  42. }
  43. async read(): Promise<ProviderConfigLayerSnapshot> {
  44. this.#assertNotDisposed();
  45. let release: ZCodeBuiltinRelease;
  46. try {
  47. await this.#ensureWatcher();
  48. release = await withFileLock(this.#activeFilePath, () => this.#readAndMaterializeLocked());
  49. } catch {
  50. // Active 只是可丢弃缓存,目录锁、监听或原子物化失败不能阻断
  51. // Bundled 基线。缓存边界不可用时绕过 Active;Bundled 自身无效仍会在这里抛错。
  52. release = selectReleaseCandidate(await readReleaseCandidate(this.#bundledFilePath), null);
  53. }
  54. this.#observedSignature ??= signatureOf(release);
  55. return snapshotFromRelease(release, this.#sourceKey);
  56. }
  57. async applyRemoteRelease(release: ZCodeBuiltinRelease): Promise<ApplyZCodeBuiltinReleaseResult> {
  58. this.#assertNotDisposed();
  59. await this.#ensureWatcher();
  60. const result = await withFileLock(this.#activeFilePath, async () => {
  61. this.#assertNotDisposed();
  62. const current = await this.#readAndMaterializeLocked();
  63. this.#assertNotDisposed();
  64. if (release.revision < current.revision) return "stale" as const;
  65. if (release.revision === current.revision) {
  66. if (serializeZCodeBuiltinRelease(release) === serializeZCodeBuiltinRelease(current)) {
  67. return "unchanged" as const;
  68. }
  69. throw new Error(`ZCode Built-in 相同 revision ${release.revision} 对应不同内容`);
  70. }
  71. await this.#writeActiveLocked(release);
  72. this.#observedSignature = signatureOf(release);
  73. return "updated" as const;
  74. });
  75. if (result === "updated" && !this.#disposed) this.#emit("remote-updated");
  76. return result;
  77. }
  78. onDidChange(listener: (reason: string) => void): () => void {
  79. this.#assertNotDisposed();
  80. this.#listeners.add(listener);
  81. return () => this.#listeners.delete(listener);
  82. }
  83. dispose(): void {
  84. if (this.#disposed) return;
  85. this.#disposed = true;
  86. this.#watcher?.close();
  87. this.#watcher = null;
  88. this.#listeners.clear();
  89. }
  90. async #readAndMaterializeLocked(): Promise<ZCodeBuiltinRelease> {
  91. const [bundled, active] = await Promise.all([
  92. readReleaseCandidate(this.#bundledFilePath),
  93. this.#activeFilePath === this.#bundledFilePath
  94. ? Promise.resolve(null)
  95. : readReleaseCandidate(this.#activeFilePath),
  96. ]);
  97. const selected = selectReleaseCandidate(bundled, active);
  98. if (this.#activeFilePath !== this.#bundledFilePath) {
  99. const activeSignature = active?.release ? signatureOf(active.release) : null;
  100. if (activeSignature !== signatureOf(selected)) await this.#writeActiveLocked(selected);
  101. }
  102. return selected;
  103. }
  104. async #writeActiveLocked(release: ZCodeBuiltinRelease): Promise<void> {
  105. this.#assertNotDisposed();
  106. await atomicWritePrivateTextFile(
  107. this.#activeFilePath,
  108. JSON.stringify(encodeZCodeBuiltinRelease(release), null, 2),
  109. );
  110. }
  111. async #ensureWatcher(): Promise<void> {
  112. await mkdir(dirname(this.#activeFilePath), { recursive: true });
  113. if (!this.#watchEnabled || this.#watcher || this.#disposed) return;
  114. const target = basename(this.#activeFilePath);
  115. this.#watcher = watch(dirname(this.#activeFilePath), (_eventType, fileName) => {
  116. if (fileName === null || fileName.toString() === target) this.#scheduleWatchRefresh();
  117. });
  118. this.#watcher.on("error", () => this.#emit("watch-error"));
  119. }
  120. #scheduleWatchRefresh(): void {
  121. this.#watchRefresh = this.#watchRefresh.then(async () => {
  122. if (this.#disposed) return;
  123. try {
  124. const release = await withFileLock(this.#activeFilePath, () =>
  125. this.#readAndMaterializeLocked(),
  126. );
  127. const signature = signatureOf(release);
  128. if (this.#disposed || signature === this.#observedSignature) return;
  129. this.#observedSignature = signature;
  130. this.#emit("file-changed");
  131. } catch {
  132. this.#emit("watch-error");
  133. }
  134. });
  135. }
  136. #emit(reason: string): void {
  137. if (this.#disposed) return;
  138. for (const listener of this.#listeners) listener(reason);
  139. }
  140. #assertNotDisposed(): void {
  141. if (this.#disposed) throw new Error("NodeZCodeBuiltinProviderConfigSource 已 dispose");
  142. }
  143. }
  144. export function createNodeZCodeBuiltinProviderConfigSource(
  145. options: NodeZCodeBuiltinProviderConfigSourceOptions,
  146. ): NodeZCodeBuiltinProviderConfigSource {
  147. return new NodeZCodeBuiltinProviderConfigSource(options);
  148. }
  149. interface ReleaseCandidate {
  150. readonly release?: ZCodeBuiltinRelease;
  151. readonly error?: unknown;
  152. }
  153. async function readReleaseCandidate(filePath: string): Promise<ReleaseCandidate | null> {
  154. try {
  155. return { release: decodeZCodeBuiltinRelease(JSON.parse(await readFile(filePath, "utf8"))) };
  156. } catch (error) {
  157. if (isFileNotFound(error)) return null;
  158. return { error };
  159. }
  160. }
  161. function selectReleaseCandidate(
  162. bundled: ReleaseCandidate | null,
  163. active: ReleaseCandidate | null,
  164. ): ZCodeBuiltinRelease {
  165. if (
  166. bundled?.release &&
  167. active?.release &&
  168. bundled.release.revision === active.release.revision &&
  169. serializeZCodeBuiltinRelease(bundled.release) !== serializeZCodeBuiltinRelease(active.release)
  170. ) {
  171. // 同 revision 冲突属于 Active 缓存失效,不能反向使可信 Bundled 无法启动。
  172. // 返回 Bundled 后调用方会在能够写入时原子替换 Active。
  173. return bundled.release;
  174. }
  175. const valid = [bundled?.release, active?.release].filter(
  176. (candidate): candidate is ZCodeBuiltinRelease => candidate !== undefined,
  177. );
  178. if (valid.length === 0) {
  179. throw new AggregateError(
  180. [bundled?.error, active?.error].filter((error) => error !== undefined),
  181. "Bundled 与 Active ZCode Built-in Release 均不可用",
  182. );
  183. }
  184. return valid.reduce((newest, candidate) =>
  185. candidate.revision > newest.revision ? candidate : newest,
  186. );
  187. }
  188. function snapshotFromRelease(
  189. release: ZCodeBuiltinRelease,
  190. sourceKey: string,
  191. ): ProviderConfigLayerSnapshot {
  192. return Object.freeze({
  193. revision: `zcode-builtin:${release.revision}:${sourceKey}`,
  194. providers: release.config.providers,
  195. providerTemplates: release.config.providerTemplates,
  196. models: release.config.modelConfigRules,
  197. });
  198. }
  199. function signatureOf(release: ZCodeBuiltinRelease): string {
  200. return `${release.revision}:${serializeZCodeBuiltinRelease(release)}`;
  201. }
  202. function isFileNotFound(error: unknown): boolean {
  203. return (
  204. typeof error === "object" &&
  205. error !== null &&
  206. "code" in error &&
  207. (error as { code?: unknown }).code === "ENOENT"
  208. );
  209. }