worker-transport.js (2659B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 // Each worker debugger supports only a single connection to the main thread. 8 // However, its theoretically possible for multiple servers to connect to the 9 // same worker. Consequently, each transport has a connection id, to allow 10 // messages from multiple connections to be multiplexed on a single channel. 11 12 /** 13 * A transport that uses a WorkerDebugger to send packets from the main 14 * thread to a worker thread. 15 */ 16 class MainThreadWorkerDebuggerTransport { 17 constructor(dbg, id) { 18 this._dbg = dbg; 19 this._id = id; 20 21 this._dbgListener = { 22 onMessage: this._onMessage.bind(this), 23 }; 24 } 25 26 ready() { 27 this._dbg.addListener(this._dbgListener); 28 } 29 30 close() { 31 if (this._dbgListener) { 32 this._dbg.removeListener(this._dbgListener); 33 } 34 this._dbgListener = null; 35 this.hooks?.onTransportClosed(); 36 } 37 38 send(packet) { 39 this._dbg.postMessage( 40 JSON.stringify({ 41 type: "message", 42 id: this._id, 43 message: packet, 44 }) 45 ); 46 } 47 48 startBulkSend() { 49 throw new Error("Can't send bulk data from worker threads!"); 50 } 51 52 _onMessage(message) { 53 const packet = JSON.parse(message); 54 if (packet.type !== "message" || packet.id !== this._id || !this.hooks) { 55 return; 56 } 57 58 this.hooks.onPacket(packet.message); 59 } 60 } 61 62 exports.MainThreadWorkerDebuggerTransport = MainThreadWorkerDebuggerTransport; 63 64 /** 65 * A transport that uses a WorkerDebuggerGlobalScope to send packets from a 66 * worker thread to the main thread. 67 */ 68 class WorkerThreadWorkerDebuggerTransport { 69 constructor(scope, id) { 70 this._scope = scope; 71 this._id = id; 72 this._onMessage = this._onMessage.bind(this); 73 } 74 ready() { 75 this._scope.addEventListener("message", this._onMessage); 76 } 77 78 close() { 79 this._scope.removeEventListener("message", this._onMessage); 80 this.hooks?.onTransportClosed(); 81 } 82 83 send(packet) { 84 this._scope.postMessage( 85 JSON.stringify({ 86 type: "message", 87 id: this._id, 88 message: packet, 89 }) 90 ); 91 } 92 93 startBulkSend() { 94 throw new Error("Can't send bulk data from worker threads!"); 95 } 96 97 _onMessage(event) { 98 const packet = JSON.parse(event.data); 99 if (packet.type !== "message" || packet.id !== this._id) { 100 return; 101 } 102 103 if (this.hooks) { 104 this.hooks.onPacket(packet.message); 105 } 106 } 107 } 108 109 exports.WorkerThreadWorkerDebuggerTransport = 110 WorkerThreadWorkerDebuggerTransport;