pluginManagementStoreLoading.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import type { IPluginManagementService } from "@zcode/services";
  2. import {
  3. remoteHostIdFromWorkspaceIdentity,
  4. parseRemoteWorkspaceIdentity,
  5. type ZCodePluginScope,
  6. } from "@zcode/shared";
  7. import { logger } from "@/logger.js";
  8. import type { PluginManagementState } from "@/store/pluginManagementStore.js";
  9. function toMessage(error: unknown): string {
  10. return error instanceof Error ? error.message : String(error);
  11. }
  12. export function buildWorkspaceKey(
  13. workspacePath: string,
  14. workspaceIdentity: string | null,
  15. authorityKey: string | null,
  16. ): string {
  17. return `${authorityKey?.trim() || "workspace"}\0${workspaceIdentity?.trim() || workspacePath}`;
  18. }
  19. // 只共享同服务、同身份、同配置投影的在途查询;每个视图仍独立写回和保存错误态。
  20. const loadsByService = new WeakMap<
  21. IPluginManagementService,
  22. Map<string, { task: Promise<Partial<PluginManagementState>>; revision: number }>
  23. >();
  24. export interface PluginManagementChange {
  25. owner?: () => PluginManagementState;
  26. workspacePath: string;
  27. workspaceIdentity: string | null;
  28. authorityKey: string | null;
  29. scope: ZCodePluginScope;
  30. }
  31. const changeListeners = new Set<(change: PluginManagementChange) => void | Promise<void>>();
  32. let revision = 0;
  33. export const getPluginManagementRevision = () => revision;
  34. export function subscribePluginManagementChanges(
  35. listener: (change: PluginManagementChange) => void | Promise<void>,
  36. ) {
  37. changeListeners.add(listener);
  38. return () => {
  39. changeListeners.delete(listener);
  40. };
  41. }
  42. export function notifyPluginManagementChange(change: PluginManagementChange): void {
  43. revision += 1;
  44. // 派生视图不能拖住已成功的写入;发布失效信号后,后台查询各自收口。
  45. for (const listener of changeListeners) {
  46. void Promise.resolve()
  47. .then(() => listener(change))
  48. .catch((error: unknown) => {
  49. logger.warn("[plugins] background projection refresh failed", {
  50. message: toMessage(error),
  51. });
  52. });
  53. }
  54. }
  55. export function isPluginManagementChangeRelevant(
  56. state: Pick<
  57. PluginManagementState,
  58. "workspacePath" | "workspaceIdentity" | "authorityKey" | "configScope"
  59. >,
  60. change: PluginManagementChange,
  61. ): boolean {
  62. if (!state.workspacePath) return false;
  63. if (change.scope === "workspace") {
  64. return (
  65. state.configScope !== "user" &&
  66. buildWorkspaceKey(state.workspacePath, state.workspaceIdentity, state.authorityKey) ===
  67. buildWorkspaceKey(change.workspacePath, change.workspaceIdentity, change.authorityKey)
  68. );
  69. }
  70. const hostKey = (target: { workspaceIdentity: string | null; authorityKey: string | null }) => {
  71. const identity = target.workspaceIdentity ?? "";
  72. const sourceServerId = parseRemoteWorkspaceIdentity(identity)?.sourceServerId;
  73. // Source 用户设置没有项目 identity,但和该 Source 下项目共享用户配置。
  74. return (
  75. target.authorityKey ??
  76. (sourceServerId
  77. ? `source-settings:${sourceServerId}`
  78. : (remoteHostIdFromWorkspaceIdentity(identity) ?? "local"))
  79. );
  80. };
  81. return hostKey(state) === hostKey(change);
  82. }
  83. // 单个 operationId 会被后一次安装覆盖;每次调用持有独立条目,完成时只移除自己。
  84. // 通过条目身份清理,同名并发操作以及切换配置层后的新操作都不会被误清除。
  85. export function beginPluginOperation(
  86. set: (partial: Partial<PluginManagementState>) => void,
  87. get: () => PluginManagementState,
  88. id: string,
  89. ): () => void {
  90. const entry = { id };
  91. set({
  92. activeOperations: [...get().activeOperations, entry],
  93. operationVersion: get().operationVersion + 1,
  94. error: null,
  95. lastFailedPluginId: null,
  96. });
  97. return () => {
  98. set({ activeOperations: get().activeOperations.filter((operation) => operation !== entry) });
  99. };
  100. }
  101. export async function runWorkspaceOperation(
  102. set: (partial: Partial<PluginManagementState>) => void,
  103. get: () => PluginManagementState,
  104. pluginService: IPluginManagementService,
  105. operationId: string,
  106. operation: (workspace: { workspacePath: string; workspaceIdentity?: string }) => Promise<void>,
  107. scope: ZCodePluginScope = "user",
  108. ): Promise<boolean> {
  109. const { workspacePath, workspaceIdentity, authorityKey, configScope } = get();
  110. if (!workspacePath) return false;
  111. const finish = beginPluginOperation(set, get, operationId);
  112. const operationVersion = get().operationVersion;
  113. const isCurrentContext = (): boolean => {
  114. const current = get();
  115. return (
  116. current.workspacePath === workspacePath &&
  117. current.workspaceIdentity === workspaceIdentity &&
  118. current.authorityKey === authorityKey &&
  119. current.configScope === configScope
  120. );
  121. };
  122. const ownsVisibleOperation = (): boolean =>
  123. isCurrentContext() && get().operationVersion === operationVersion;
  124. try {
  125. await operation({
  126. workspacePath,
  127. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  128. });
  129. // 并发刷新不能把已成功落盘的安装报告成失败;结果只受当前目标上下文约束。
  130. if (!isCurrentContext()) {
  131. await notifyPluginManagementChange({
  132. owner: get,
  133. workspacePath,
  134. workspaceIdentity,
  135. authorityKey,
  136. scope,
  137. });
  138. return false;
  139. }
  140. await loadInto(set, get, {
  141. workspacePath,
  142. workspaceIdentity,
  143. authorityKey,
  144. configScope,
  145. pluginService,
  146. fresh: true,
  147. });
  148. await notifyPluginManagementChange({
  149. owner: get,
  150. workspacePath,
  151. workspaceIdentity,
  152. authorityKey,
  153. scope,
  154. });
  155. return isCurrentContext();
  156. } catch (error) {
  157. // marketplace add/update 等通用操作失败:无插件目标,归属清空。
  158. logger.error("[plugins] operation failed", { operationId, error: toMessage(error) });
  159. // 旧操作不能覆盖同一配置层中新操作的错误态;只有最近发起的操作才回写。
  160. if (ownsVisibleOperation()) {
  161. set({ error: toMessage(error), lastFailedPluginId: null });
  162. }
  163. return false;
  164. } finally {
  165. finish();
  166. }
  167. }
  168. interface PluginLoadParams {
  169. workspacePath: string;
  170. workspaceIdentity: string | null;
  171. authorityKey: string | null;
  172. configScope: ZCodePluginScope | null;
  173. pluginService: IPluginManagementService;
  174. fresh?: boolean;
  175. background?: boolean;
  176. }
  177. export async function loadInto(
  178. set: (partial: Partial<PluginManagementState>) => void,
  179. get: () => PluginManagementState,
  180. params: PluginLoadParams,
  181. ): Promise<void> {
  182. let inFlightLoads = loadsByService.get(params.pluginService);
  183. if (!inFlightLoads) {
  184. inFlightLoads = new Map();
  185. loadsByService.set(params.pluginService, inFlightLoads);
  186. }
  187. const workspaceKey = buildWorkspaceKey(
  188. params.workspacePath,
  189. params.workspaceIdentity,
  190. params.authorityKey,
  191. );
  192. const loadKey = `${workspaceKey}\0${params.configScope ?? "effective"}`;
  193. const existing = inFlightLoads.get(loadKey);
  194. // 变更前启动的查询不能充当变更后的刷新;同一轮通知的新查询仍可共用。
  195. if (existing && (params.fresh || (params.background && existing.revision < revision))) {
  196. await existing.task;
  197. return loadInto(set, get, { ...params, fresh: false });
  198. }
  199. const request = existing ?? { task: runLoadInto({ ...params, workspaceKey }), revision };
  200. inFlightLoads.set(loadKey, request);
  201. try {
  202. const result = await request.task;
  203. const current = get();
  204. if (
  205. current.workspacePath !== params.workspacePath ||
  206. current.workspaceIdentity !== params.workspaceIdentity ||
  207. current.authorityKey !== params.authorityKey ||
  208. current.configScope !== params.configScope
  209. )
  210. return;
  211. // 其它视图的成功操作只刷新数据,不能抹掉本视图尚未处理的操作错误。
  212. set(
  213. params.background && current.error
  214. ? { ...result, error: current.error, lastFailedPluginId: current.lastFailedPluginId }
  215. : result,
  216. );
  217. } finally {
  218. if (inFlightLoads.get(loadKey) === request) inFlightLoads.delete(loadKey);
  219. }
  220. }
  221. async function runLoadInto(
  222. params: PluginLoadParams & { workspaceKey: string },
  223. ): Promise<Partial<PluginManagementState>> {
  224. // 列表的单插件协议错误曾丢弃成功目录;分别收口,失败接口不在这里重复请求。
  225. const [listResult, overviewResult] = await Promise.allSettled([
  226. params.pluginService.listPlugins({
  227. workspacePath: params.workspacePath,
  228. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  229. ...(params.configScope ? { configScope: params.configScope } : {}),
  230. }),
  231. params.pluginService.getPluginsOverview({
  232. workspacePath: params.workspacePath,
  233. ...(params.workspaceIdentity ? { workspaceIdentity: params.workspaceIdentity } : {}),
  234. ...(params.configScope ? { configScope: params.configScope } : {}),
  235. }),
  236. ]);
  237. const errors: string[] = [];
  238. for (const [method, result] of [
  239. ["list", listResult],
  240. ["overview", overviewResult],
  241. ] as const) {
  242. if (result.status === "rejected") {
  243. const message = toMessage(result.reason);
  244. errors.push(message);
  245. logger.error(`[plugins] ${method} failed`, {
  246. workspacePath: params.workspacePath,
  247. workspaceKey: params.workspaceKey,
  248. error: message,
  249. });
  250. }
  251. }
  252. const list = listResult.status === "fulfilled" ? listResult.value : undefined;
  253. const overview = overviewResult.status === "fulfilled" ? overviewResult.value : undefined;
  254. return {
  255. plugins: list?.plugins ?? [],
  256. marketplaces: overview?.marketplaces ?? [],
  257. // 目录失败表示来源未知,不能把仍在工作的已安装插件误判为孤立安装。
  258. marketplaceAvailabilityKnown: overview !== undefined,
  259. availablePlugins: overview?.availablePlugins ?? [],
  260. installedPlugins: overview?.installedPlugins ?? [],
  261. restorableBuiltins: overview?.restorableBuiltins ?? [],
  262. diagnostics: [...(list?.diagnostics ?? []), ...(overview?.diagnostics ?? [])],
  263. loading: false,
  264. lastFailedPluginId: null,
  265. error: errors.length > 0 ? errors.join("\n") : null,
  266. };
  267. }