messageport.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { MessagePortProtocol, ChannelClient } from "@zcode/rpc";
  2. import type { IServiceAccessor } from "@zcode/services";
  3. import { RemoteServiceAccess } from "./remoteServiceAccess.js";
  4. import { isRendererProductionBuild } from "./rendererLoggingEnv.js";
  5. function logMessagePortDebug(message: string): void {
  6. // 生产构建下 renderer 连接日志不输出,避免窗口启动和重连路径产生同步 console 成本。
  7. if (isRendererProductionBuild()) {
  8. return;
  9. }
  10. console.log(message);
  11. }
  12. export interface MessagePortServiceConnection {
  13. services: IServiceAccessor;
  14. dispose: (reason?: Error) => void;
  15. }
  16. /**
  17. * 创建一个带明确生命周期的 MessagePort service connection。
  18. *
  19. * scoped remote session 换代时必须同时释放 ChannelClient 和底层 port,
  20. * 否则旧 attachment 上的挂起 RPC 无法 settle,并会继续占用上层去重状态。
  21. */
  22. export function createMessagePortServiceConnection(
  23. port: MessagePort,
  24. ): MessagePortServiceConnection {
  25. logMessagePortDebug("[messageport] creating protocol and client...");
  26. const protocol = new MessagePortProtocol(port);
  27. const client = new ChannelClient(protocol);
  28. client.onDidInitialize(() => {
  29. logMessagePortDebug("[messageport] ChannelClient received Initialize from server");
  30. });
  31. logMessagePortDebug("[messageport] client created, waiting for Initialize...");
  32. const services = new RemoteServiceAccess(client);
  33. let disposed = false;
  34. return {
  35. services,
  36. dispose: (reason?: Error) => {
  37. if (disposed) {
  38. return;
  39. }
  40. disposed = true;
  41. client.dispose(reason);
  42. protocol.disconnect();
  43. },
  44. };
  45. }
  46. /**
  47. * 通过 MessagePort 连接服务。
  48. *
  49. * Desktop 模式下,utilityProcess(或 main 进程的远程代理)通过 MessagePort
  50. * 暴露 ChannelServer,renderer 用此函数建立 ChannelClient 连接。
  51. */
  52. export function connectViaMessagePort(port: MessagePort): IServiceAccessor {
  53. return createMessagePortServiceConnection(port).services;
  54. }