1// Copyright (C) 2018 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import {assertExists} from '../base/logging'; 16import {EngineWorkerInitMessage} from '../common/worker_messages'; 17import {WasmBridge} from './wasm_bridge'; 18 19const selfWorker = self as {} as Worker; 20const wasmBridge = new WasmBridge(); 21 22// There are two message handlers here: 23// 1. The Worker (self.onmessage) handler. 24// 2. The MessagePort handler. 25// When the app bootstraps, frontend/index.ts creates a MessageChannel and sends 26// one end to the controller (the other worker) and the other end to us, so that 27// the controller can interact with the Wasm worker without roundtrips through 28// the frontend. 29// The sequence of actions is the following: 30// 1. The frontend does one postMessage({port: MessagePort}) on the Worker 31// scope. This message transfers the MessagePort (whose other end is 32// connected to the Conotroller). This is the only postMessage we'll ever 33// receive here. 34// 2. All the other messages (i.e. the TraceProcessor RPC binary pipe) will be 35// received on the MessagePort. 36 37// Receives the boostrap message from the frontend with the MessagePort. 38selfWorker.onmessage = (msg: MessageEvent) => { 39 const port = assertExists((msg.data as EngineWorkerInitMessage).enginePort); 40 wasmBridge.initialize(port); 41}; 42