02-proxy-channel.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /**
  2. * 示例 2: ProxyChannel —— 零样板代码的服务代理
  3. *
  4. * 对比示例 1 中手写的 CalculatorChannel,这里用 ProxyChannel
  5. * 一行代码就能把 service 暴露为 channel,再一行恢复为 service。
  6. *
  7. * 这就是 VS Code 里几百个 service 能轻松跨进程通信的秘密。
  8. */
  9. import {
  10. Emitter,
  11. Event,
  12. DisposableStore,
  13. ChannelServer,
  14. ChannelClient,
  15. ProxyChannel,
  16. createQueuePair,
  17. } from "../src/index.js";
  18. // ============================================================================
  19. // 定义 service 接口和实现
  20. // ============================================================================
  21. /** 文件系统服务接口 */
  22. interface IFileService {
  23. onDidChangeFile: Event<{ path: string; type: string }>;
  24. readFile(path: string): Promise<string>;
  25. writeFile(path: string, content: string): Promise<void>;
  26. listFiles(dir: string): Promise<string[]>;
  27. }
  28. /** 模拟的文件系统实现 */
  29. class InMemoryFileService implements IFileService {
  30. private files = new Map<string, string>();
  31. private readonly _onDidChangeFile = new Emitter<{ path: string; type: string }>();
  32. readonly onDidChangeFile = this._onDidChangeFile.event;
  33. async readFile(path: string): Promise<string> {
  34. const content = this.files.get(path);
  35. if (content === undefined) {
  36. throw new Error(`File not found: ${path}`);
  37. }
  38. return content;
  39. }
  40. async writeFile(path: string, content: string): Promise<void> {
  41. const isNew = !this.files.has(path);
  42. this.files.set(path, content);
  43. this._onDidChangeFile.fire({
  44. path,
  45. type: isNew ? "created" : "changed",
  46. });
  47. }
  48. async listFiles(dir: string): Promise<string[]> {
  49. return [...this.files.keys()].filter((p) => p.startsWith(dir));
  50. }
  51. }
  52. // ============================================================================
  53. // 演示 ProxyChannel
  54. // ============================================================================
  55. async function main() {
  56. const [protocolA, protocolB] = createQueuePair();
  57. const disposables = new DisposableStore();
  58. // ========== 服务端 ==========
  59. const fileService = new InMemoryFileService();
  60. // 一行代码:把 service 变成 channel!
  61. // ProxyChannel.fromService 会自动:
  62. // - 把 readFile, writeFile, listFiles 映射为 call
  63. // - 把 onDidChangeFile 映射为 listen
  64. const channel = ProxyChannel.fromService<string>(fileService, disposables);
  65. const server = new ChannelServer(protocolB, "server");
  66. server.registerChannel("fileService", channel);
  67. // ========== 客户端 ==========
  68. const client = new ChannelClient(protocolA);
  69. await Event.toPromise(client.onDidInitialize);
  70. // 一行代码:把 channel 恢复为类型安全的 service!
  71. // 利用 ES6 Proxy,调用 remoteFS.readFile(...) 会自动变成 channel.call('readFile', [...])
  72. const remoteFS = ProxyChannel.toService<IFileService>(client.getChannel("fileService"));
  73. // ========== 使用远程服务(就像调本地方法一样!)==========
  74. console.log("--- ProxyChannel Demo ---");
  75. console.log("(注意:所有调用都经过了序列化 → 传输 → 反序列化)\n");
  76. // 监听文件变更事件
  77. const eventDisposable = remoteFS.onDidChangeFile((e) => {
  78. console.log(` [file event] ${e.type}: ${e.path}`);
  79. });
  80. // 写入文件
  81. await remoteFS.writeFile("/src/main.ts", 'console.log("hello")');
  82. await remoteFS.writeFile("/src/util.ts", "export function add(a, b) { return a + b; }");
  83. await remoteFS.writeFile("/src/main.ts", 'console.log("hello world")'); // 修改
  84. // 读取文件
  85. const content = await remoteFS.readFile("/src/main.ts");
  86. console.log(`\nreadFile('/src/main.ts') = "${content}"`);
  87. // 列出文件
  88. const files = await remoteFS.listFiles("/src");
  89. console.log(`listFiles('/src') = ${JSON.stringify(files)}`);
  90. // 测试错误传播
  91. try {
  92. await remoteFS.readFile("/nonexistent");
  93. } catch (err: any) {
  94. console.log(`readFile('/nonexistent') → Error: ${err.message}`);
  95. }
  96. // 清理
  97. eventDisposable.dispose();
  98. client.dispose();
  99. server.dispose();
  100. disposables.dispose();
  101. console.log("\nDone!");
  102. }
  103. main().catch(console.error);