All files / kernel-browser-runtime/src PlatformServicesServer.ts

93.02% Statements 80/86
88.88% Branches 24/27
73.91% Functions 17/23
93.02% Lines 80/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430                                                                                                                                          33x       33x   33x   33x       33x       33x                                                 33x 33x 33x   33x     2x           33x                         33x                                       1x               1x 1x                 44x 2x 2x 42x 42x 42x 42x   42x       32x   10x 10x                                       44x                           8x 1x   7x 7x 7x   7x                   6x 6x 1x   5x 3x 3x                 2x   3x     1x                                       16x 1x               15x               15x 15x 15x 15x 15x 15x                 3x 1x   2x 2x 2x 2x 2x 2x 2x                   2x 1x   1x 1x                     2x 1x   1x 1x                     3x 1x   2x 2x                     2x 1x   1x 1x                           1x                         1x                                           3x  
import {
  VatAlreadyExistsError,
  VatNotFoundError,
} from '@metamask/kernel-errors';
import { RpcClient, RpcService } from '@metamask/kernel-rpc-methods';
import { isJsonRpcMessage } from '@metamask/kernel-utils';
import type { JsonRpcMessage } from '@metamask/kernel-utils';
import { Logger } from '@metamask/logger';
import type {
  VatId,
  VatConfig,
  SendRemoteMessage,
  StopRemoteComms,
  RemoteCommsOptions,
} from '@metamask/ocap-kernel';
import { initTransport } from '@metamask/ocap-kernel';
import {
  kernelRemoteMethodSpecs,
  platformServicesHandlers,
} from '@metamask/ocap-kernel/rpc';
import { serializeError } from '@metamask/rpc-errors';
import { PostMessageDuplexStream } from '@metamask/streams/browser';
import type {
  PostMessageEnvelope,
  PostMessageTarget,
} from '@metamask/streams/browser';
import { isJsonRpcRequest, isJsonRpcResponse } from '@metamask/utils';
 
// Appears in the docs.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import type { PlatformServicesClient } from './PlatformServicesClient.ts';
 
export type VatWorker = {
  launch: (vatConfig: VatConfig) => Promise<[MessagePort, unknown]>;
  terminate: () => Promise<null>;
};
 
export type PlatformServicesStream = PostMessageDuplexStream<
  MessageEvent<JsonRpcMessage>, // was JsonRpcRequest
  PostMessageEnvelope<JsonRpcMessage> // was JsonRpcResponse
>;
 
/**
 * The server end of the platform services, intended to be constructed in
 * the offscreen document. Listens for launch and terminate worker requests
 * from the client and uses the {@link VatWorker} methods to effect those
 * requests, and provides network connectivity.
 *
 * Note that {@link PlatformServicesServer.start} must be called to start
 * the server.
 *
 * @see {@link PlatformServicesClient} for the other end of the service.
 *
 * @param stream - The stream to use for communication with the client.
 * @param makeWorker - A method for making a {@link VatWorker}.
 * @param logger - An optional {@link Logger}. Defaults to a new logger labeled '[platform services server]'.
 * @returns A new {@link PlatformServicesServer}.
 */
export class PlatformServicesServer {
  readonly #logger;
 
  readonly #stream: PlatformServicesStream;
 
  /** RPC client for delivering remote message events to the kernel */
  readonly #rpcClient: RpcClient<typeof kernelRemoteMethodSpecs>;
 
  /** RPC service for handling platform services requests */
  readonly #rpcServer: RpcService<typeof platformServicesHandlers>;
 
  readonly #vatWorkers: Map<VatId, VatWorker> = new Map();
 
  readonly #makeWorker: (vatId: VatId) => VatWorker;
 
  #sendRemoteMessageFunc: SendRemoteMessage | null = null;
 
  #stopRemoteCommsFunc: StopRemoteComms | null = null;
 
  #closeConnectionFunc: ((peerId: string) => Promise<void>) | null = null;
 
  #registerLocationHintsFunc:
    | ((peerId: string, hints: string[]) => void)
    | null = null;
 
  #reconnectPeerFunc:
    | ((peerId: string, hints?: string[]) => Promise<void>)
    | null = null;
 
  /**
   * **ATTN:** Prefer {@link PlatformServicesServer.make} over constructing
   * this class directly.
   *
   * The server end of the platform services, intended to be constructed in
   * the offscreen document. Listens for launch and terminate worker requests
   * from the client and uses the {@link VatWorker} methods to effect those
   * requests, and provides network connectivity.
   *
   * Note that {@link PlatformServicesServer.start} must be called to start
   * the server.
   *
   * @see {@link PlatformServicesClient} for the other end of the service.
   *
   * @param stream - The stream to use for communication with the client.
   * @param makeWorker - A method for making a {@link VatWorker}.
   * @param logger - An optional {@link Logger}. Defaults to a new logger labeled '[platform services server]'.
   */
  constructor(
    stream: PlatformServicesStream,
    makeWorker: (vatId: VatId) => VatWorker,
    logger?: Logger,
  ) {
    this.#stream = stream;
    this.#makeWorker = makeWorker;
    this.#logger = logger ?? new Logger('platform-services-server');
 
    this.#rpcClient = new RpcClient(
      kernelRemoteMethodSpecs,
      async (request) => {
        await this.#sendMessage(request);
      },
      `vws:`,
      this.#logger.subLogger({ tags: ['rpc-client'] }),
    );
 
    this.#rpcServer = new RpcService(platformServicesHandlers, {
      launch: this.#launch.bind(this),
      terminate: this.#terminate.bind(this),
      terminateAll: this.#terminateAll.bind(this),
      sendRemoteMessage: this.#sendRemoteMessage.bind(this),
      initializeRemoteComms: this.#initializeRemoteComms.bind(this),
      stopRemoteComms: this.#stopRemoteComms.bind(this),
      closeConnection: this.#closeConnection.bind(this),
      registerLocationHints: this.#registerLocationHints.bind(this),
      reconnectPeer: this.#reconnectPeer.bind(this),
    });
 
    // Start draining messages immediately after construction
    this.#stream
      .drain(this.#handleMessage.bind(this))
      .catch((error: unknown) => {
        this.#logger.error('Error draining stream:', error);
      });
  }
 
  /**
   * Create a new {@link PlatformServicesServer}. Does not start the server.
   *
   * @param messageTarget - The target to use for posting and receiving messages.
   * @param makeWorker - A method for making a {@link VatWorker}.
   * @param logger - An optional {@link Logger}.
   * @returns A new {@link PlatformServicesServer}.
   */
  static async make(
    messageTarget: PostMessageTarget,
    makeWorker: (vatId: VatId) => VatWorker,
    logger?: Logger,
  ): Promise<PlatformServicesServer> {
    const stream: PlatformServicesStream = new PostMessageDuplexStream({
      messageTarget,
      messageEventMode: 'event',
      validateInput: (
        message: unknown,
      ): message is MessageEvent<JsonRpcMessage> =>
        message instanceof MessageEvent && isJsonRpcMessage(message.data),
    });
    await stream.synchronize();
    return new PlatformServicesServer(stream, makeWorker, logger);
  }
 
  /**
   * Handles incoming JSON-RPC messages from the shared worker.
   *
   * @param event - The message event containing the JSON-RPC message data.
   */
  async #handleMessage(event: MessageEvent<JsonRpcMessage>): Promise<void> {
    if (isJsonRpcResponse(event.data)) {
      const message = event.data;
      this.#rpcClient.handleResponse(message.id as string, message);
    E} else if (isJsonRpcRequest(event.data)) {
      const { id, method, params } = event.data;
      try {
        this.#rpcServer.assertHasMethod(method);
        // Ridiculous cast to bypass TypeScript vs. JsonRpc tug-o-war
        const port: MessagePort | undefined = (await this.#rpcServer.execute(
          method,
          params,
        )) as unknown as MessagePort | undefined;
        await this.#sendMessage({ id, result: null, jsonrpc: '2.0' }, port);
      } catch (error) {
        this.#logger.error(`Error handling "${method}" request:`, error);
        this.#sendMessage({
          id,
          error: serializeError(error),
          jsonrpc: '2.0',
        }).catch(() => undefined);
      }
    }
  }
 
  /**
   * Send a message to the client.
   *
   * @param message - The message to send.
   * @param port - An optional port to transfer.
   * @returns A promise that resolves when the message has been sent.
   */
  async #sendMessage(
    message: JsonRpcMessage,
    port?: MessagePort,
  ): Promise<void> {
    await this.#stream.write({
      payload: message,
      transfer: port ? [port] : [],
    });
  }
 
  /**
   * Launch a new worker with a specific vat id.
   *
   * @param vatId - The vat id of the worker to launch.
   * @param vatConfig - The configuration for the worker.
   * @returns A promise that resolves when the worker has been launched.
   */
  async #launch(vatId: VatId, vatConfig: VatConfig): Promise<null> {
    if (this.#vatWorkers.has(vatId)) {
      throw new VatAlreadyExistsError(vatId);
    }
    const vatWorker = this.#makeWorker(vatId);
    const [port] = await vatWorker.launch(vatConfig);
    this.#vatWorkers.set(vatId, vatWorker);
    // This cast is a deliberate lie, to bypass TypeScript vs. JsonRpc tug-o-war
    return port as unknown as null;
  }
 
  /**
   * Terminate a worker identified by its vat id.
   *
   * @param vatId - The vat id of the worker to terminate.
   * @returns A promise that resolves when the worker has been terminated.
   */
  async #terminate(vatId: VatId): Promise<null> {
    const vatWorker = this.#vatWorkers.get(vatId);
    if (!vatWorker) {
      throw new VatNotFoundError(vatId);
    }
    await vatWorker.terminate();
    this.#vatWorkers.delete(vatId);
    return null;
  }
 
  /**
   * Terminate all workers managed by the service.
   *
   * @returns A promise that resolves when all workers have been terminated.
   */
  async #terminateAll(): Promise<null> {
    await Promise.all(
      Array.from(this.#vatWorkers.keys()).map(async (vatId) =>
        this.#terminate(vatId),
      ),
    );
    return null;
  }
 
  /**
   * Initialize network communications.
   *
   * @param keySeed - The seed for generating this kernel's secret key.
   * @param options - Options for remote communications initialization.
   * @param options.relays - Array of the peerIDs of relay nodes that can be used to listen for incoming
   *   connections from other kernels.
   * @param options.maxRetryAttempts - Maximum number of reconnection attempts. 0 = infinite (default).
   * @param options.maxQueue - Maximum number of messages to queue per peer while reconnecting (default: 200).
   * @param incarnationId - This kernel's incarnation ID for handshake protocol.
   * @returns A promise that resolves when network access has been initialized.
   */
  async #initializeRemoteComms(
    keySeed: string,
    options: RemoteCommsOptions,
    incarnationId?: string,
  ): Promise<null> {
    if (this.#sendRemoteMessageFunc) {
      throw Error('remote comms already initialized');
    }
    const {
      sendRemoteMessage,
      stop,
      closeConnection,
      registerLocationHints,
      reconnectPeer,
    } = await initTransport(
      keySeed,
      options,
      this.#handleRemoteMessage.bind(this),
      this.#handleRemoteGiveUp.bind(this),
      incarnationId,
      this.#handleRemoteIncarnationChange.bind(this),
    );
    this.#sendRemoteMessageFunc = sendRemoteMessage;
    this.#stopRemoteCommsFunc = stop;
    this.#closeConnectionFunc = closeConnection;
    this.#registerLocationHintsFunc = registerLocationHints;
    this.#reconnectPeerFunc = reconnectPeer;
    return null;
  }
 
  /**
   * Stop network communications.
   *
   * @returns A promise that resolves when network access has been stopped.
   */
  async #stopRemoteComms(): Promise<null> {
    if (!this.#stopRemoteCommsFunc) {
      return null;
    }
    await this.#stopRemoteCommsFunc();
    this.#sendRemoteMessageFunc = null;
    this.#stopRemoteCommsFunc = null;
    this.#closeConnectionFunc = null;
    this.#registerLocationHintsFunc = null;
    this.#reconnectPeerFunc = null;
    return null;
  }
 
  /**
   * Explicitly close a connection to a peer.
   *
   * @param peerId - The peer ID to close the connection for.
   * @returns A promise that resolves when the connection has been closed.
   */
  async #closeConnection(peerId: string): Promise<null> {
    if (!this.#closeConnectionFunc) {
      throw Error('remote comms not initialized');
    }
    await this.#closeConnectionFunc(peerId);
    return null;
  }
 
  /**
   * Take note of where a peer might be.
   *
   * @param peerId - The peer ID to whom this information applies.
   * @param hints - An array of location hints
   * @returns A promise that resolves when the connection has been closed.
   */
  async #registerLocationHints(peerId: string, hints: string[]): Promise<null> {
    if (!this.#registerLocationHintsFunc) {
      throw Error('remote comms not initialized');
    }
    this.#registerLocationHintsFunc(peerId, hints);
    return null;
  }
 
  /**
   * Manually reconnect to a peer after intentional close.
   *
   * @param peerId - The peer ID to reconnect to.
   * @param hints - Optional hints for reconnection.
   * @returns A promise that resolves when reconnection has been initiated.
   */
  async #reconnectPeer(peerId: string, hints: string[] = []): Promise<null> {
    if (!this.#reconnectPeerFunc) {
      throw Error('remote comms not initialized');
    }
    await this.#reconnectPeerFunc(peerId, hints);
    return null;
  }
 
  /**
   * Send a remote message to a peer.
   *
   * @param to - The peer ID to send the message to.
   * @param message - The serialized message string to send.
   * @returns A promise that resolves when the message has been sent.
   */
  async #sendRemoteMessage(to: string, message: string): Promise<null> {
    if (!this.#sendRemoteMessageFunc) {
      throw Error('remote comms not initialized');
    }
    await this.#sendRemoteMessageFunc(to, message);
    return null;
  }
 
  /**
   * Handle a remote message from a peer.
   *
   * @param from - The peer ID that sent the message.
   * @param message - The message received.
   * @returns A promise that resolves with the reply message, or null if no reply is needed.
   */
  async #handleRemoteMessage(
    from: string,
    message: string,
  ): Promise<string | null> {
    return this.#rpcClient.call('remoteDeliver', {
      from,
      message,
    });
  }
 
  /**
   * Handle when we give up on a remote connection.
   * Notifies the kernel worker via RPC.
   *
   * @param peerId - The peer ID of the remote we're giving up on.
   */
  #handleRemoteGiveUp(peerId: string): void {
    this.#rpcClient.call('remoteGiveUp', { peerId }).catch((error) => {
      this.#logger.error('Error notifying kernel of remote give up:', error);
    });
  }
 
  /**
   * Handle when a remote peer's incarnation changes (peer restarted).
   * Notifies the kernel worker via RPC to reset the RemoteHandle state.
   *
   * @param peerId - The peer ID of the remote that restarted.
   */
  #handleRemoteIncarnationChange(peerId: string): void {
    this.#rpcClient
      .call('remoteIncarnationChange', { peerId })
      .catch((error) => {
        this.#logger.error(
          'Error notifying kernel of remote incarnation change:',
          error,
        );
      });
  }
}
harden(PlatformServicesServer);