source-server-update-disconnect.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import { BufferReader, BufferWriter, deserialize, serialize, VSBuffer } from "@zcode/rpc";
  2. import { ISourceServerManagementService, type UpdateConnectionProfileInput } from "@zcode/services";
  3. const DISCONNECT_REQUEST = -8301;
  4. const UPDATE_REQUEST = -8302;
  5. const SAVE_PROFILE_REQUEST = -8303;
  6. interface UpdateDisconnectProbe {
  7. sent: boolean;
  8. requests: number[][];
  9. responses: number[][];
  10. restore(): void;
  11. }
  12. function decodeFrame(bytes: number[]) {
  13. const reader = new BufferReader(VSBuffer.wrap(Uint8Array.from(bytes)));
  14. return { header: deserialize(reader) as [number, number], body: deserialize(reader) };
  15. }
  16. interface UpdateDisconnectEvidence {
  17. sent: boolean;
  18. savedProfile?: ReturnType<typeof decodeFrame>;
  19. update?: ReturnType<typeof decodeFrame>;
  20. cancellation?: ReturnType<typeof decodeFrame>;
  21. states: Array<Record<string, unknown>>;
  22. }
  23. let evidence: UpdateDisconnectEvidence = { sent: false, states: [] };
  24. declare global {
  25. interface Window {
  26. __updateDisconnectProbe?: UpdateDisconnectProbe;
  27. }
  28. }
  29. /** 更新 UI 会禁用同卡按钮;在真实 updating 事件到达时提交并发 RPC,覆盖 Host 必须兑现的断开终态。 */
  30. export async function disconnectDuringNextSourceUpdate(sourceServerId: string): Promise<void> {
  31. await observeUpdateCancellation(sourceServerId, "disconnectSource", sourceServerId);
  32. }
  33. /** 两条真实 SSH 线路已建立;经同一 Host RPC 更新 B,并在 A 的物理连接失效时删除 B。 */
  34. export async function updateAndRemoveNonCurrentProfile(
  35. sourceServerId: string,
  36. ownerProfileId: string,
  37. profile: UpdateConnectionProfileInput,
  38. ): Promise<void> {
  39. await observeUpdateCancellation(
  40. sourceServerId,
  41. "removeProfile",
  42. profile.profileId,
  43. ownerProfileId,
  44. profile,
  45. );
  46. }
  47. async function observeUpdateCancellation(
  48. sourceServerId: string,
  49. command: "disconnectSource" | "removeProfile",
  50. removedId: string,
  51. ownerProfileId?: string,
  52. profile?: UpdateConnectionProfileInput,
  53. ): Promise<void> {
  54. evidence = { sent: false, states: [] };
  55. const writer = new BufferWriter();
  56. serialize(writer, [100, DISCONNECT_REQUEST, ISourceServerManagementService.channelName, command]);
  57. serialize(writer, [removedId]);
  58. const updateWriter = new BufferWriter();
  59. serialize(updateWriter, [
  60. 100,
  61. UPDATE_REQUEST,
  62. ISourceServerManagementService.channelName,
  63. "updateSource",
  64. ]);
  65. serialize(updateWriter, [{ profileId: removedId }]);
  66. // 复用已在线 Source 的线路可能没有独立保存密码;经正式设置命令准备可静默更新的 B 线路。
  67. const profileWriter = new BufferWriter();
  68. serialize(profileWriter, [
  69. 100,
  70. SAVE_PROFILE_REQUEST,
  71. ISourceServerManagementService.channelName,
  72. "updateProfile",
  73. ]);
  74. serialize(profileWriter, [profile]);
  75. const savedHeader = new BufferWriter();
  76. serialize(savedHeader, [201, SAVE_PROFILE_REQUEST]);
  77. await browser.execute(
  78. (
  79. channel,
  80. sourceId,
  81. disconnectRequest,
  82. ownerId,
  83. updateRequest,
  84. saveProfileRequest,
  85. savedPrefix,
  86. ) => {
  87. const original = MessagePort.prototype.postMessage;
  88. let removeListener: (() => void) | undefined;
  89. const probe: UpdateDisconnectProbe = {
  90. sent: false,
  91. requests: [],
  92. responses: [],
  93. restore() {
  94. MessagePort.prototype.postMessage = original;
  95. removeListener?.();
  96. delete window.__updateDisconnectProbe;
  97. },
  98. };
  99. function receive(this: MessagePort, event: MessageEvent) {
  100. if (!(event.data instanceof Uint8Array)) return;
  101. probe.responses.push(Array.from(event.data));
  102. if (
  103. saveProfileRequest.length &&
  104. savedPrefix.every((byte, index) => event.data[index] === byte)
  105. )
  106. original.call(this, Uint8Array.from(updateRequest));
  107. const text = new TextDecoder().decode(event.data);
  108. if (
  109. !probe.sent &&
  110. text.includes('"state":"updating"') &&
  111. text.includes(sourceId) &&
  112. (!ownerId || (text.includes('"state":{') && text.includes(`"profileId":"${ownerId}"`)))
  113. ) {
  114. probe.sent = true;
  115. original.call(this, Uint8Array.from(disconnectRequest));
  116. }
  117. }
  118. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  119. let startUpdate = false;
  120. if (message instanceof Uint8Array) {
  121. const text = new TextDecoder().decode(message);
  122. if (!ownerId && removeListener && text.includes(channel) && text.includes("updateSource"))
  123. throw new Error("Unexpected second update request");
  124. if (
  125. text.includes(channel) &&
  126. text.includes(ownerId ? "getSnapshot" : "updateSource") &&
  127. !removeListener
  128. ) {
  129. removeListener = () => this.removeEventListener("message", receive);
  130. probe.requests.push(ownerId ? updateRequest : Array.from(message));
  131. this.addEventListener("message", receive);
  132. startUpdate = Boolean(ownerId);
  133. }
  134. }
  135. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  136. if (startUpdate)
  137. original.call(
  138. this,
  139. Uint8Array.from(saveProfileRequest.length ? saveProfileRequest : updateRequest),
  140. );
  141. };
  142. window.__updateDisconnectProbe = probe;
  143. },
  144. ISourceServerManagementService.channelName,
  145. sourceServerId,
  146. Array.from(writer.buffer.buffer),
  147. ownerProfileId,
  148. Array.from(updateWriter.buffer.buffer),
  149. profile ? Array.from(profileWriter.buffer.buffer) : [],
  150. Array.from(savedHeader.buffer.buffer),
  151. );
  152. }
  153. export async function readUpdateDisconnectEvidence() {
  154. const probe = await browser.execute(() => {
  155. const probe = window.__updateDisconnectProbe;
  156. return probe
  157. ? { sent: probe.sent, requests: probe.requests, responses: probe.responses.splice(0) }
  158. : null;
  159. });
  160. if (!probe) throw new Error("Missing update disconnect probe");
  161. const updateId = probe.requests[0] ? decodeFrame(probe.requests[0]).header[1] : undefined;
  162. // 重传全部历史帧会使长时间恢复等待的 WDIO worker 堆耗尽;原始帧只读一次,累计保留断言证据。
  163. evidence.sent ||= probe.sent;
  164. for (const bytes of probe.responses) {
  165. const frame = decodeFrame(bytes);
  166. if (frame.header[1] === SAVE_PROFILE_REQUEST) evidence.savedProfile ??= frame;
  167. if (frame.header[1] === updateId && [201, 202, 203].includes(frame.header[0]))
  168. evidence.update ??= frame;
  169. if (frame.header[1] === DISCONNECT_REQUEST) evidence.cancellation ??= frame;
  170. if (frame.header[0] === 204 && frame.body?.state) evidence.states.push(frame.body.state);
  171. }
  172. return { ...evidence, states: [...evidence.states] };
  173. }
  174. export async function restoreUpdateDisconnectProbe(): Promise<void> {
  175. try {
  176. await browser.execute(() => window.__updateDisconnectProbe?.restore());
  177. } finally {
  178. evidence = { sent: false, states: [] };
  179. }
  180. }