registry-service.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import type { ModelId, ProviderId } from "./config/index.js";
  2. import {
  3. ProviderRegistry,
  4. type ModelSelection,
  5. type ModelSelectionValidation,
  6. type ProviderRegistryView,
  7. } from "./registry.js";
  8. import {
  9. ProviderConfigResolver,
  10. type ProviderConfigResolution,
  11. type Provider,
  12. type ProviderModel,
  13. } from "./resolver.js";
  14. import type {
  15. AccountProviderConfigSnapshot,
  16. ProviderConfigSnapshot,
  17. ProviderSource,
  18. } from "./sources.js";
  19. export interface ProviderRegistryServiceSnapshot {
  20. readonly sourceRevisions: {
  21. readonly config: string;
  22. readonly account: string;
  23. };
  24. readonly config: ProviderConfigSnapshot;
  25. readonly account: AccountProviderConfigSnapshot;
  26. readonly resolution: ProviderConfigResolution;
  27. readonly registry: ProviderRegistryView;
  28. }
  29. export interface ProviderRegistryServiceChangedEvent {
  30. readonly snapshot: ProviderRegistryServiceSnapshot;
  31. readonly reasons: readonly string[];
  32. }
  33. export interface ProviderRegistryServiceRefreshErrorEvent {
  34. readonly error: unknown;
  35. readonly reasons: readonly string[];
  36. }
  37. export interface ProviderRegistryServiceDependencies {
  38. readonly configSource: ProviderSource<ProviderConfigSnapshot>;
  39. readonly accountSource: ProviderSource<AccountProviderConfigSnapshot>;
  40. readonly resolver?: ProviderConfigResolver;
  41. }
  42. interface RefreshWaiter {
  43. readonly generation: number;
  44. readonly resolve: (snapshot: ProviderRegistryServiceSnapshot) => void;
  45. readonly reject: (error: unknown) => void;
  46. }
  47. export class ProviderRegistryService {
  48. readonly #configSource: ProviderSource<ProviderConfigSnapshot>;
  49. readonly #accountSource: ProviderSource<AccountProviderConfigSnapshot>;
  50. readonly #resolver: ProviderConfigResolver;
  51. readonly #registry = new ProviderRegistry();
  52. readonly #changeListeners = new Set<(event: ProviderRegistryServiceChangedEvent) => void>();
  53. readonly #errorListeners = new Set<(event: ProviderRegistryServiceRefreshErrorEvent) => void>();
  54. readonly #sourceDisposers: Array<() => void> = [];
  55. readonly #pendingReasons = new Set<string>();
  56. readonly #refreshWaiters: RefreshWaiter[] = [];
  57. #snapshot: ProviderRegistryServiceSnapshot | null = null;
  58. #requestedGeneration = 0;
  59. #completedGeneration = 0;
  60. #refreshInFlight: Promise<void> | null = null;
  61. #started = false;
  62. #disposed = false;
  63. constructor(dependencies: ProviderRegistryServiceDependencies) {
  64. this.#configSource = dependencies.configSource;
  65. this.#accountSource = dependencies.accountSource;
  66. this.#resolver = dependencies.resolver ?? new ProviderConfigResolver();
  67. }
  68. async start(): Promise<void> {
  69. this.#assertNotDisposed();
  70. if (!this.#started) {
  71. this.#started = true;
  72. this.#sourceDisposers.push(
  73. this.#configSource.onDidChange((reason) => this.#refreshFromSource("config", reason)),
  74. this.#accountSource.onDidChange((reason) => this.#refreshFromSource("account", reason)),
  75. );
  76. await this.#requestRefresh("start");
  77. return;
  78. }
  79. // 启动只负责就绪;业务读取必须使用 getSnapshot,不能长期保留首次启动快照。
  80. if (!this.#snapshot) await this.#requestRefresh("start");
  81. }
  82. refresh(reason = "explicit"): Promise<ProviderRegistryServiceSnapshot> {
  83. this.#assertNotDisposed();
  84. if (!this.#started) throw new Error("ProviderRegistryService 必须先 start() 再 refresh()");
  85. return this.#requestRefresh(reason);
  86. }
  87. getSnapshot(): ProviderRegistryServiceSnapshot | null {
  88. return this.#snapshot;
  89. }
  90. getView(): ProviderRegistryView {
  91. return this.#registry.getView();
  92. }
  93. listProviders(): readonly Provider[] {
  94. return this.#registry.listProviders();
  95. }
  96. getProvider(providerId: ProviderId): Provider | undefined {
  97. return this.#registry.getProvider(providerId);
  98. }
  99. getModel(providerId: ProviderId, modelId: ModelId): ProviderModel | undefined {
  100. return this.#registry.getModel(providerId, modelId);
  101. }
  102. validateSelection(selection: ModelSelection): ModelSelectionValidation {
  103. return this.#registry.validateSelection(selection);
  104. }
  105. onDidChange(listener: (event: ProviderRegistryServiceChangedEvent) => void): () => void {
  106. this.#changeListeners.add(listener);
  107. return () => this.#changeListeners.delete(listener);
  108. }
  109. onDidRefreshError(
  110. listener: (event: ProviderRegistryServiceRefreshErrorEvent) => void,
  111. ): () => void {
  112. this.#errorListeners.add(listener);
  113. return () => this.#errorListeners.delete(listener);
  114. }
  115. dispose(): void {
  116. if (this.#disposed) return;
  117. this.#disposed = true;
  118. for (const dispose of this.#sourceDisposers.splice(0)) dispose();
  119. const error = new Error("ProviderRegistryService 已 dispose");
  120. for (const waiter of this.#refreshWaiters.splice(0)) waiter.reject(error);
  121. this.#changeListeners.clear();
  122. this.#errorListeners.clear();
  123. }
  124. #refreshFromSource(source: "config" | "account", reason: string): void {
  125. if (this.#disposed) return;
  126. void this.#requestRefresh(`${source}:${reason || "changed"}`).catch(() => {
  127. // Source 驱动的后台刷新通过 onDidRefreshError 报告;调用栈没有 Promise 消费者。
  128. });
  129. }
  130. #requestRefresh(reason: string): Promise<ProviderRegistryServiceSnapshot> {
  131. const generation = this.#requestedGeneration + 1;
  132. this.#requestedGeneration = generation;
  133. this.#pendingReasons.add(reason);
  134. const result = new Promise<ProviderRegistryServiceSnapshot>((resolve, reject) => {
  135. this.#refreshWaiters.push({ generation, resolve, reject });
  136. });
  137. this.#ensureRefreshLoop();
  138. return result;
  139. }
  140. #ensureRefreshLoop(): void {
  141. if (this.#refreshInFlight || this.#disposed) return;
  142. const refresh = this.#runRefreshLoop();
  143. this.#refreshInFlight = refresh;
  144. void refresh.then(
  145. () => this.#finishRefresh(refresh),
  146. (error: unknown) => {
  147. this.#rejectRefreshWaiters(this.#requestedGeneration, error);
  148. this.#finishRefresh(refresh);
  149. },
  150. );
  151. }
  152. #finishRefresh(refresh: Promise<void>): void {
  153. if (this.#refreshInFlight !== refresh) return;
  154. this.#refreshInFlight = null;
  155. if (this.#completedGeneration < this.#requestedGeneration) this.#ensureRefreshLoop();
  156. }
  157. async #runRefreshLoop(): Promise<void> {
  158. const reasons = new Set<string>();
  159. while (this.#completedGeneration < this.#requestedGeneration) {
  160. const generation = this.#requestedGeneration;
  161. for (const reason of this.#pendingReasons) reasons.add(reason);
  162. this.#pendingReasons.clear();
  163. let config: ProviderConfigSnapshot;
  164. let account: AccountProviderConfigSnapshot;
  165. try {
  166. [config, account] = await Promise.all([
  167. this.#configSource.read(),
  168. this.#accountSource.read(),
  169. ]);
  170. } catch (error) {
  171. if (generation < this.#requestedGeneration) continue;
  172. this.#completedGeneration = generation;
  173. this.#emitRefreshError(error, reasons);
  174. this.#rejectRefreshWaiters(generation, error);
  175. return;
  176. }
  177. if (generation < this.#requestedGeneration) continue;
  178. this.#assertNotDisposed();
  179. if (account.basedOnZCodeBuiltinRevision !== config.zcodeBuiltinRevision) {
  180. // Built-in 已变化但 Account 仍基于旧事实时,继续服务上一份完整 Registry。
  181. // 当前 generation 结束;等待 Account Source 的后续 change 再一次性发布最终组合。
  182. this.#completedGeneration = generation;
  183. if (this.#snapshot) this.#resolveRefreshWaiters(generation, this.#snapshot);
  184. reasons.clear();
  185. continue;
  186. }
  187. if (this.#hasSameSourceRevisions(config, account)) {
  188. this.#completedGeneration = generation;
  189. this.#resolveRefreshWaiters(generation, this.#snapshot!);
  190. reasons.clear();
  191. continue;
  192. }
  193. try {
  194. const resolution = this.#resolver.resolve({
  195. zcodeBuiltinProviders: config.zcodeBuiltinProviders,
  196. zcodeBuiltinProviderTemplates: config.zcodeBuiltinProviderTemplates,
  197. personalProviders: config.personalProviders,
  198. zcodeBuiltinModelRules: config.zcodeBuiltinModelRules,
  199. personalModels: config.personalModels,
  200. accountProviders: account.providers,
  201. accountStates: account.states,
  202. personalProviderOrder: config.personalProviderOrder,
  203. });
  204. this.#registry.replace(resolution.registryProviders, [...reasons].join(","));
  205. const snapshot = Object.freeze({
  206. sourceRevisions: Object.freeze({
  207. config: config.revision,
  208. account: account.revision,
  209. }),
  210. config: Object.freeze({ ...config }),
  211. account: freezeAccountSnapshot(account),
  212. resolution,
  213. registry: this.#registry.getView(),
  214. });
  215. this.#snapshot = snapshot;
  216. this.#completedGeneration = generation;
  217. this.#resolveRefreshWaiters(generation, snapshot);
  218. this.#emitChanged(snapshot, reasons);
  219. reasons.clear();
  220. } catch (error) {
  221. this.#completedGeneration = generation;
  222. this.#emitRefreshError(error, reasons);
  223. this.#rejectRefreshWaiters(generation, error);
  224. return;
  225. }
  226. }
  227. }
  228. #resolveRefreshWaiters(generation: number, snapshot: ProviderRegistryServiceSnapshot): void {
  229. const remaining: RefreshWaiter[] = [];
  230. for (const waiter of this.#refreshWaiters) {
  231. if (waiter.generation <= generation) waiter.resolve(snapshot);
  232. else remaining.push(waiter);
  233. }
  234. this.#refreshWaiters.splice(0, this.#refreshWaiters.length, ...remaining);
  235. }
  236. #rejectRefreshWaiters(generation: number, error: unknown): void {
  237. const remaining: RefreshWaiter[] = [];
  238. for (const waiter of this.#refreshWaiters) {
  239. if (waiter.generation <= generation) waiter.reject(error);
  240. else remaining.push(waiter);
  241. }
  242. this.#refreshWaiters.splice(0, this.#refreshWaiters.length, ...remaining);
  243. }
  244. #hasSameSourceRevisions(
  245. config: ProviderConfigSnapshot,
  246. account: AccountProviderConfigSnapshot,
  247. ): boolean {
  248. return (
  249. this.#snapshot?.sourceRevisions.config === config.revision &&
  250. this.#snapshot.sourceRevisions.account === account.revision
  251. );
  252. }
  253. #emitChanged(snapshot: ProviderRegistryServiceSnapshot, reasons: ReadonlySet<string>): void {
  254. const event = Object.freeze({
  255. snapshot,
  256. reasons: Object.freeze([...reasons]),
  257. });
  258. for (const listener of this.#changeListeners) listener(event);
  259. }
  260. #emitRefreshError(error: unknown, reasons: ReadonlySet<string>): void {
  261. const event = Object.freeze({
  262. error,
  263. reasons: Object.freeze([...reasons]),
  264. });
  265. for (const listener of this.#errorListeners) listener(event);
  266. }
  267. #assertNotDisposed(): void {
  268. if (this.#disposed) throw new Error("ProviderRegistryService 已 dispose");
  269. }
  270. }
  271. function freezeAccountSnapshot(
  272. snapshot: AccountProviderConfigSnapshot,
  273. ): AccountProviderConfigSnapshot {
  274. return Object.freeze({
  275. revision: snapshot.revision,
  276. basedOnZCodeBuiltinRevision: snapshot.basedOnZCodeBuiltinRevision,
  277. providers: snapshot.providers,
  278. ...(snapshot.states ? { states: snapshot.states } : {}),
  279. });
  280. }