Merge "perfetto-ui: Remove engine worker proxy hacks"
diff --git a/ui/src/controller/engine.ts b/ui/src/controller/engine.ts
index 81c3872..9c018ec 100644
--- a/ui/src/controller/engine.ts
+++ b/ui/src/controller/engine.ts
@@ -87,8 +87,3 @@
     return new TimeSpan(start / 1e9, end / 1e9);
   }
 }
-
-export interface EnginePortAndId {
-  id: string;
-  port: MessagePort;
-}
diff --git a/ui/src/controller/globals.ts b/ui/src/controller/globals.ts
index 950b678..8a336fa 100644
--- a/ui/src/controller/globals.ts
+++ b/ui/src/controller/globals.ts
@@ -17,9 +17,13 @@
 import {Action} from '../common/actions';
 import {createEmptyState, State} from '../common/state';
 import {ControllerAny} from './controller';
-import {Engine, EnginePortAndId} from './engine';
+import {Engine} from './engine';
 import {rootReducer} from './reducer';
 import {WasmEngineProxy} from './wasm_engine_proxy';
+import {
+  createWasmEngine,
+  destroyWasmEngine,
+} from './wasm_engine_proxy';
 
 /**
  * Global accessors for state/dispatch in the controller.
@@ -79,14 +83,14 @@
     console.timeEnd(summary);
   }
 
-  async createEngine(): Promise<Engine> {
-    const portAndId = await assertExists(this._frontend)
-                          .send<EnginePortAndId>('createEngine', []);
-    return WasmEngineProxy.create(portAndId);
+  createEngine(): Engine {
+    const id = new Date().toUTCString();
+    const portAndId = {id, worker: createWasmEngine(id)};
+    return new WasmEngineProxy(portAndId);
   }
 
-  async destroyEngine(id: string): Promise<void> {
-    await assertExists(this._frontend).send<void>('destroyEngine', [id]);
+  destroyEngine(id: string): void {
+    destroyWasmEngine(id);
   }
 
   // TODO: this needs to be cleaned up.
diff --git a/ui/src/controller/index.ts b/ui/src/controller/index.ts
index 43d9535..28e095c 100644
--- a/ui/src/controller/index.ts
+++ b/ui/src/controller/index.ts
@@ -18,18 +18,21 @@
 
 import {AppController} from './app_controller';
 import {globals} from './globals';
+import {warmupWasmEngine} from './wasm_engine_proxy';
 
 function main(port: MessagePort) {
+  warmupWasmEngine();
   let receivedFrontendPort = false;
   port.onmessage = ({data}) => {
-    if (!receivedFrontendPort) {
-      const frontendPort = data as MessagePort;
-      const frontend = new Remote(frontendPort);
-      globals.initialize(new AppController(), frontend);
-      receivedFrontendPort = true;
-    } else {
+    if (receivedFrontendPort) {
       globals.dispatch(data);
+      return;
     }
+
+    const frontendPort = data as MessagePort;
+    const frontend = new Remote(frontendPort);
+    globals.initialize(new AppController(), frontend);
+    receivedFrontendPort = true;
   };
 }
 
diff --git a/ui/src/controller/trace_controller.ts b/ui/src/controller/trace_controller.ts
index 3580398..50cbcf2 100644
--- a/ui/src/controller/trace_controller.ts
+++ b/ui/src/controller/trace_controller.ts
@@ -112,7 +112,7 @@
   private async loadTrace() {
     globals.dispatch(updateStatus('Creating trace processor'));
     const engineCfg = assertExists(globals.state.engines[this.engineId]);
-    this.engine = await globals.createEngine();
+    this.engine = globals.createEngine();
 
     const statusHeader = 'Opening trace';
     if (engineCfg.source instanceof File) {
diff --git a/ui/src/controller/wasm_engine_proxy.ts b/ui/src/controller/wasm_engine_proxy.ts
index aff7503..80375b9 100644
--- a/ui/src/controller/wasm_engine_proxy.ts
+++ b/ui/src/controller/wasm_engine_proxy.ts
@@ -18,27 +18,18 @@
 import {TraceProcessor} from '../common/protos';
 import {WasmBridgeRequest, WasmBridgeResponse} from '../engine/wasm_bridge';
 
-import {Engine, EnginePortAndId} from './engine';
+import {Engine} from './engine';
 
-interface WorkerAndPort {
-  worker: Worker;
-  port: MessagePort;
-}
+const activeWorkers = new Map<string, Worker>();
+let warmWorker: null|Worker = null;
 
-const activeWorkers = new Map<string, WorkerAndPort>();
-let warmWorker: null|WorkerAndPort = null;
-
-function createWorker(): WorkerAndPort {
-  const channel = new MessageChannel();
-  const worker = new Worker('engine_bundle.js');
-  // tslint:disable-next-line deprecation
-  worker.postMessage(channel.port1, [channel.port1]);
-  return {worker, port: channel.port2};
+function createWorker(): Worker {
+  return new Worker('engine_bundle.js');
 }
 
 // Take the warm engine and start creating a new WASM engine in the background
 // for the next call.
-export function createWasmEngine(id: string): MessagePort {
+export function createWasmEngine(id: string): Worker {
   if (warmWorker === null) {
     throw new Error('warmupWasmEngine() not called');
   }
@@ -48,14 +39,14 @@
   const activeWorker = warmWorker;
   warmWorker = createWorker();
   activeWorkers.set(id, activeWorker);
-  return activeWorker.port;
+  return activeWorker;
 }
 
 export function destroyWasmEngine(id: string) {
   if (!activeWorkers.has(id)) {
     throw new Error(`Cannot find worker ID ${id}`);
   }
-  activeWorkers.get(id)!.worker.terminate();
+  activeWorkers.get(id)!.terminate();
   activeWorkers.delete(id);
 }
 
@@ -79,23 +70,19 @@
  * worker thread.
  */
 export class WasmEngineProxy extends Engine {
-  private readonly port: MessagePort;
+  private readonly worker: Worker;
   private readonly traceProcessor_: TraceProcessor;
   private pendingCallbacks: Map<number, protobufjs.RPCImplCallback>;
   private nextRequestId: number;
   readonly id: string;
 
-  static create(args: EnginePortAndId): Engine {
-    return new WasmEngineProxy(args);
-  }
-
-  constructor(args: EnginePortAndId) {
+  constructor(args: {id: string, worker: Worker}) {
     super();
     this.nextRequestId = 0;
     this.pendingCallbacks = new Map();
-    this.port = args.port;
     this.id = args.id;
-    this.port.onmessage = this.onMessage.bind(this);
+    this.worker = args.worker;
+    this.worker.onmessage = this.onMessage.bind(this);
     this.traceProcessor_ =
         TraceProcessor.create(this.rpcImpl.bind(this, 'trace_processor'));
   }
@@ -110,7 +97,7 @@
         {id, serviceName: 'trace_processor', methodName: 'parse', data};
     const promise = defer<void>();
     this.pendingCallbacks.set(id, () => promise.resolve());
-    this.port.postMessage(request);
+    this.worker.postMessage(request);
     return promise;
   }
 
@@ -121,7 +108,7 @@
         {id, serviceName: 'trace_processor', methodName: 'notifyEof', data};
     const promise = defer<void>();
     this.pendingCallbacks.set(id, () => promise.resolve());
-    this.port.postMessage(request);
+    this.worker.postMessage(request);
     return promise;
   }
 
@@ -147,6 +134,6 @@
       methodName,
       data: requestData,
     };
-    this.port.postMessage(request);
+    this.worker.postMessage(request);
   }
 }
diff --git a/ui/src/engine/index.ts b/ui/src/engine/index.ts
index fbf2a3d..7891a38 100644
--- a/ui/src/engine/index.ts
+++ b/ui/src/engine/index.ts
@@ -17,23 +17,13 @@
 import {WasmBridge, WasmBridgeRequest} from './wasm_bridge';
 
 // tslint:disable no-any
-
-// We expect to get exactly one message from the creator of the worker:
-// a MessagePort we should listen to for future messages.
-// This indirection is due to workers not being able create workers in Chrome
-// which is tracked at: crbug.com/31666
-// TODO(hjd): Remove this once the fix has landed.
-// Once we have the MessagePort we proxy all messages to WasmBridge#callWasm.
+// Proxy all messages to WasmBridge#callWasm.
 const anySelf = (self as any);
+const boundPostMessage = anySelf.postMessage.bind(anySelf);
+const bridge = new WasmBridge(init_trace_processor, boundPostMessage);
+bridge.initialize();
+
 anySelf.onmessage = (msg: MessageEvent) => {
-  const port: MessagePort = msg.data;
-
-  const bridge =
-      new WasmBridge(init_trace_processor, port.postMessage.bind(port));
-  bridge.initialize();
-
-  port.onmessage = (msg: MessageEvent) => {
-    const request: WasmBridgeRequest = msg.data;
-    bridge.callWasm(request);
-  };
+  const request: WasmBridgeRequest = msg.data;
+  bridge.callWasm(request);
 };
diff --git a/ui/src/frontend/index.ts b/ui/src/frontend/index.ts
index acd2c9f..0b92765 100644
--- a/ui/src/frontend/index.ts
+++ b/ui/src/frontend/index.ts
@@ -20,13 +20,6 @@
 import {loadPermalink} from '../common/actions';
 import {State} from '../common/state';
 import {TimeSpan} from '../common/time';
-import {EnginePortAndId} from '../controller/engine';
-import {
-  createWasmEngine,
-  destroyWasmEngine,
-  warmupWasmEngine,
-} from '../controller/wasm_engine_proxy';
-
 import {globals, QuantizedLoad, ThreadDesc} from './globals';
 import {HomePage} from './home_page';
 import {RecordPage} from './record_page';
@@ -87,22 +80,6 @@
     this.redraw();
   }
 
-  /**
-   * Creates a new trace processor wasm engine (backed by a worker running
-   * engine_bundle.js) and returns a MessagePort for talking to it.
-   * This indirection is due to workers not being able create workers in
-   * Chrome which is tracked at: crbug.com/31666
-   * TODO(hjd): Remove this once the fix has landed.
-   */
-  createEngine(): EnginePortAndId {
-    const id = new Date().toUTCString();
-    return {id, port: createWasmEngine(id)};
-  }
-
-  destroyEngine(id: string) {
-    destroyWasmEngine(id);
-  }
-
   private redraw(): void {
     if (globals.state.route &&
         globals.state.route !== this.router.getRouteFromHash()) {
@@ -135,7 +112,6 @@
   globals.rafScheduler.domRedraw = () =>
       m.render(document.body, m(router.resolve(globals.state.route)));
 
-  warmupWasmEngine();
 
   // Put these variables in the global scope for better debugging.
   (window as {} as {m: {}}).m = m;