remote-navigation.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import type {
  2. IProjectService,
  3. IRemoteProjectService,
  4. ProjectSidebarProps,
  5. } from "@/project-sidebar/contract.js";
  6. /**
  7. * 同一设备在途的未指定目录连接。Host 把这类 connect 按设备复用为同一 logical session,
  8. * Renderer 也必须按 hostId 合并,才能让所有等待者共享同一个结果与释放责任。
  9. */
  10. interface HostConnectionFlight {
  11. readonly sessionId: Promise<string>;
  12. waiters: number;
  13. claimed: boolean;
  14. }
  15. const hostConnectionFlights = new Map<string, HostConnectionFlight>();
  16. function joinHostConnectionFlight(
  17. hostId: string,
  18. connect: () => Promise<string>,
  19. ): HostConnectionFlight {
  20. const current = hostConnectionFlights.get(hostId);
  21. if (current) {
  22. current.waiters += 1;
  23. return current;
  24. }
  25. const flight: HostConnectionFlight = { sessionId: connect(), waiters: 1, claimed: false };
  26. hostConnectionFlights.set(hostId, flight);
  27. return flight;
  28. }
  29. /** 不接管就退出;返回 true 表示自己是最后一个等待者且无人接管,需要释放这次连接。 */
  30. function leaveHostConnectionFlight(hostId: string, flight: HostConnectionFlight): boolean {
  31. flight.waiters -= 1;
  32. if (flight.waiters > 0 || flight.claimed) return false;
  33. if (hostConnectionFlights.get(hostId) === flight) hostConnectionFlights.delete(hostId);
  34. return true;
  35. }
  36. /** 开始绑定目录即接管连接;之后恢复的等待者不能把同一 session 改绑到其他目录。 */
  37. function claimHostConnectionFlight(hostId: string, flight: HostConnectionFlight): void {
  38. if (flight.claimed) throw new Error("project.navigation-cancelled");
  39. flight.claimed = true;
  40. flight.waiters -= 1;
  41. if (hostConnectionFlights.get(hostId) === flight) hostConnectionFlights.delete(hostId);
  42. }
  43. /** 连接实例归 Host;这里只申请/绑定 logical attachment,不按 path 复用另一台设备的 scope。 */
  44. export async function attachRemoteProjectWorkspace(input: {
  45. hostId: string;
  46. workspacePath: string;
  47. workspaceIdentity: string;
  48. expectedMembershipId?: string;
  49. projectId?: string | null;
  50. projectService?: Pick<IProjectService, "readProjects">;
  51. remoteService: IRemoteProjectService;
  52. isCurrent?(): boolean;
  53. findSession(identity: string): { sessionId: string } | undefined;
  54. /** 等该目录在途的项目重连或 Source 可恢复断连结束;不在途时立即返回。 */
  55. waitForPendingConnection?(workspaceKey: string): Promise<void>;
  56. connect: ProjectSidebarProps["onConnectRemote"];
  57. bind(
  58. sessionId: string,
  59. path: string,
  60. isCurrent?: () => boolean | Promise<boolean>,
  61. ): Promise<void>;
  62. cancel: ProjectSidebarProps["onCancelRemoteProject"];
  63. }): Promise<string> {
  64. const assertCurrent = () => {
  65. if (input.isCurrent?.() === false) throw new Error("project.navigation-cancelled");
  66. };
  67. // Bug 原因:项目重连或 Source 恢复在途时 tab 还没有可用 owner,导航曾立即连接设备并另建连接,
  68. // 与重连争写 tab(ZCT-2117174788253970432),恢复期间还会抢先扩大恢复 flight。现在先等在途连接
  69. // 结束,再按当时的 owner 复用或自建;connectHost 可能让设备上线并触发项目重连,自建前再等一次。
  70. const settle = async () => {
  71. await input.waitForPendingConnection?.(input.workspaceIdentity);
  72. assertCurrent();
  73. };
  74. await settle();
  75. const host = await input.remoteService.connectHost(input.hostId);
  76. assertCurrent();
  77. const target = host.target;
  78. if (host.id !== input.hostId || !target) throw new Error("project.host-identity-changed");
  79. if (input.expectedMembershipId && host.membershipId !== input.expectedMembershipId)
  80. throw new Error("remote-project.host-removed");
  81. const validateMembership = async () => {
  82. if (input.expectedMembershipId) {
  83. const directory = await input.remoteService.readDirectory();
  84. if (
  85. !directory.hosts.some(
  86. (item) => item.id === input.hostId && item.membershipId === input.expectedMembershipId,
  87. )
  88. )
  89. throw new Error("remote-project.host-removed");
  90. }
  91. if (input.projectService && input.projectId) {
  92. const projects = await input.projectService.readProjects({ hostId: input.hostId });
  93. if (
  94. !projects.some(
  95. (project) =>
  96. project.id === input.projectId &&
  97. project.hostId === input.hostId &&
  98. !project.deleted &&
  99. project.roots.length === 1 &&
  100. project.roots[0]?.rootPath === input.workspacePath,
  101. )
  102. )
  103. throw new Error("project.not-found");
  104. }
  105. assertCurrent();
  106. return true;
  107. };
  108. // 连接和绑定都会等待远端;claim 在目录绑定前执行,标记本导航接管连接。
  109. const bindWorkspace = async (sessionId: string, claim?: () => void) => {
  110. assertCurrent();
  111. // Host 在连接等待中被移除再添加时,原请求不能借新成员的身份提交导航。
  112. const guard =
  113. input.expectedMembershipId || input.projectService ? validateMembership : input.isCurrent;
  114. if (guard === validateMembership) await validateMembership();
  115. claim?.();
  116. if (guard) await input.bind(sessionId, input.workspacePath, guard);
  117. else await input.bind(sessionId, input.workspacePath);
  118. // Bug 原因:bind 发现目录已有 tab owner(如 tab 重连与导航并发)时会复用它并回收本次连接,
  119. // 旧检查要求 owner 必须是本次 session,把成功复用误报为 workspace-identity-mismatch 并丢弃导航。
  120. // 现在只要求目录 identity 已落到某个 session(Host 绑定到其他 identity 时仍报错),并返回该 session。
  121. const bound = input.findSession(input.workspaceIdentity);
  122. if (!bound) throw new Error("project.workspace-identity-mismatch");
  123. return bound.sessionId;
  124. };
  125. // 目录已有 session 时只复用;失败也不能取消其他项目复用的连接。
  126. await settle();
  127. const existing = input.findSession(input.workspaceIdentity);
  128. if (existing) return await bindWorkspace(existing.sessionId);
  129. // Bug 原因:首连 Provisioning 可达十几秒,期间再次点击会再发一次 connect,Host 把它 join 到同一
  130. // session。旧逻辑把每次 connect 结果都当作“本次创建”,被替代的旧点击在连接迟到成功后立即释放,
  131. // 最新点击随之失败。现在按设备合并在途连接:被替代的等待者只退出,由接管者或最后一个等待者释放。
  132. const flight = joinHostConnectionFlight(input.hostId, () => input.connect(target));
  133. let sessionId: string;
  134. try {
  135. sessionId = await flight.sessionId;
  136. } catch (error) {
  137. leaveHostConnectionFlight(input.hostId, flight);
  138. throw error;
  139. }
  140. let claimed = false;
  141. try {
  142. return await bindWorkspace(sessionId, () => {
  143. claimHostConnectionFlight(input.hostId, flight);
  144. claimed = true;
  145. });
  146. } catch (error) {
  147. if (claimed || leaveHostConnectionFlight(input.hostId, flight)) await input.cancel(sessionId);
  148. throw error;
  149. }
  150. }