@metamask/snaps-controllers 9.7.0 → 9.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +142 -1
- package/dist/cronjob/CronjobController.cjs +21 -34
- package/dist/cronjob/CronjobController.cjs.map +1 -1
- package/dist/cronjob/CronjobController.mjs +21 -34
- package/dist/cronjob/CronjobController.mjs.map +1 -1
- package/dist/insights/SnapInsightsController.cjs +194 -144
- package/dist/insights/SnapInsightsController.cjs.map +1 -1
- package/dist/insights/SnapInsightsController.mjs +193 -143
- package/dist/insights/SnapInsightsController.mjs.map +1 -1
- package/dist/interface/SnapInterfaceController.cjs +90 -65
- package/dist/interface/SnapInterfaceController.cjs.map +1 -1
- package/dist/interface/SnapInterfaceController.d.cts +2 -1
- package/dist/interface/SnapInterfaceController.d.cts.map +1 -1
- package/dist/interface/SnapInterfaceController.d.mts +2 -1
- package/dist/interface/SnapInterfaceController.d.mts.map +1 -1
- package/dist/interface/SnapInterfaceController.mjs +90 -65
- package/dist/interface/SnapInterfaceController.mjs.map +1 -1
- package/dist/services/AbstractExecutionService.cjs +71 -77
- package/dist/services/AbstractExecutionService.cjs.map +1 -1
- package/dist/services/AbstractExecutionService.mjs +71 -77
- package/dist/services/AbstractExecutionService.mjs.map +1 -1
- package/dist/services/ProxyPostMessageStream.cjs +19 -26
- package/dist/services/ProxyPostMessageStream.cjs.map +1 -1
- package/dist/services/ProxyPostMessageStream.mjs +19 -26
- package/dist/services/ProxyPostMessageStream.mjs.map +1 -1
- package/dist/services/iframe/IframeExecutionService.cjs +1 -0
- package/dist/services/iframe/IframeExecutionService.cjs.map +1 -1
- package/dist/services/iframe/IframeExecutionService.mjs +1 -0
- package/dist/services/iframe/IframeExecutionService.mjs.map +1 -1
- package/dist/services/offscreen/OffscreenExecutionService.cjs +3 -16
- package/dist/services/offscreen/OffscreenExecutionService.cjs.map +1 -1
- package/dist/services/offscreen/OffscreenExecutionService.mjs +3 -16
- package/dist/services/offscreen/OffscreenExecutionService.mjs.map +1 -1
- package/dist/services/proxy/ProxyExecutionService.cjs +4 -17
- package/dist/services/proxy/ProxyExecutionService.cjs.map +1 -1
- package/dist/services/proxy/ProxyExecutionService.mjs +4 -17
- package/dist/services/proxy/ProxyExecutionService.mjs.map +1 -1
- package/dist/services/webview/WebViewExecutionService.cjs +9 -23
- package/dist/services/webview/WebViewExecutionService.cjs.map +1 -1
- package/dist/services/webview/WebViewExecutionService.mjs +9 -23
- package/dist/services/webview/WebViewExecutionService.mjs.map +1 -1
- package/dist/services/webview/WebViewMessageStream.cjs +12 -25
- package/dist/services/webview/WebViewMessageStream.cjs.map +1 -1
- package/dist/services/webview/WebViewMessageStream.d.cts +1 -2
- package/dist/services/webview/WebViewMessageStream.d.cts.map +1 -1
- package/dist/services/webview/WebViewMessageStream.d.mts +1 -2
- package/dist/services/webview/WebViewMessageStream.d.mts.map +1 -1
- package/dist/services/webview/WebViewMessageStream.mjs +12 -25
- package/dist/services/webview/WebViewMessageStream.mjs.map +1 -1
- package/dist/services/webview/index.cjs +1 -0
- package/dist/services/webview/index.cjs.map +1 -1
- package/dist/services/webview/index.d.cts +1 -0
- package/dist/services/webview/index.d.cts.map +1 -1
- package/dist/services/webview/index.d.mts +1 -0
- package/dist/services/webview/index.d.mts.map +1 -1
- package/dist/services/webview/index.mjs +1 -0
- package/dist/services/webview/index.mjs.map +1 -1
- package/dist/services/webworker/WebWorkerExecutionService.cjs +10 -23
- package/dist/services/webworker/WebWorkerExecutionService.cjs.map +1 -1
- package/dist/services/webworker/WebWorkerExecutionService.mjs +10 -23
- package/dist/services/webworker/WebWorkerExecutionService.mjs.map +1 -1
- package/dist/snaps/RequestQueue.cjs +2 -0
- package/dist/snaps/RequestQueue.cjs.map +1 -1
- package/dist/snaps/RequestQueue.mjs +2 -0
- package/dist/snaps/RequestQueue.mjs.map +1 -1
- package/dist/snaps/SnapController.cjs +1141 -1001
- package/dist/snaps/SnapController.cjs.map +1 -1
- package/dist/snaps/SnapController.mjs +1140 -1000
- package/dist/snaps/SnapController.mjs.map +1 -1
- package/dist/snaps/Timer.cjs +1 -0
- package/dist/snaps/Timer.cjs.map +1 -1
- package/dist/snaps/Timer.mjs +1 -0
- package/dist/snaps/Timer.mjs.map +1 -1
- package/dist/snaps/location/http.cjs +11 -7
- package/dist/snaps/location/http.cjs.map +1 -1
- package/dist/snaps/location/http.mjs +11 -7
- package/dist/snaps/location/http.mjs.map +1 -1
- package/dist/snaps/location/local.cjs +4 -17
- package/dist/snaps/location/local.cjs.map +1 -1
- package/dist/snaps/location/local.mjs +4 -17
- package/dist/snaps/location/local.mjs.map +1 -1
- package/dist/snaps/location/npm.cjs +25 -37
- package/dist/snaps/location/npm.cjs.map +1 -1
- package/dist/snaps/location/npm.mjs +25 -37
- package/dist/snaps/location/npm.mjs.map +1 -1
- package/dist/snaps/registry/json.cjs +172 -173
- package/dist/snaps/registry/json.cjs.map +1 -1
- package/dist/snaps/registry/json.mjs +171 -172
- package/dist/snaps/registry/json.mjs.map +1 -1
- package/package.json +38 -23
|
@@ -1,19 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
-
};
|
|
8
|
-
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
-
};
|
|
13
2
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
4
|
};
|
|
16
|
-
var _AbstractExecutionService_instances, _AbstractExecutionService_snapRpcHooks, _AbstractExecutionService_snapToJobMap, _AbstractExecutionService_jobToSnapMap, _AbstractExecutionService_messenger, _AbstractExecutionService_initTimeout, _AbstractExecutionService_pingTimeout, _AbstractExecutionService_terminationTimeout, _AbstractExecutionService_usePing, _AbstractExecutionService_removeSnapHooks, _AbstractExecutionService_createSnapHooks, _AbstractExecutionService_mapSnapAndJob, _AbstractExecutionService_removeSnapAndJobMapping;
|
|
17
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
6
|
exports.setupMultiplex = exports.AbstractExecutionService = void 0;
|
|
19
7
|
const json_rpc_engine_1 = require("@metamask/json-rpc-engine");
|
|
@@ -29,26 +17,29 @@ const Timer_1 = require("../snaps/Timer.cjs");
|
|
|
29
17
|
const utils_2 = require("../utils.cjs");
|
|
30
18
|
const controllerName = 'ExecutionService';
|
|
31
19
|
class AbstractExecutionService {
|
|
20
|
+
#snapRpcHooks;
|
|
21
|
+
// Cannot be hash private yet because of tests.
|
|
22
|
+
jobs;
|
|
23
|
+
// Cannot be hash private yet because of tests.
|
|
24
|
+
setupSnapProvider;
|
|
25
|
+
#snapToJobMap;
|
|
26
|
+
#jobToSnapMap;
|
|
27
|
+
#messenger;
|
|
28
|
+
#initTimeout;
|
|
29
|
+
#pingTimeout;
|
|
30
|
+
#terminationTimeout;
|
|
31
|
+
#usePing;
|
|
32
32
|
constructor({ setupSnapProvider, messenger, initTimeout = (0, utils_1.inMilliseconds)(60, utils_1.Duration.Second), pingTimeout = (0, utils_1.inMilliseconds)(2, utils_1.Duration.Second), terminationTimeout = (0, utils_1.inMilliseconds)(1, utils_1.Duration.Second), usePing = true, }) {
|
|
33
|
-
|
|
34
|
-
_AbstractExecutionService_snapRpcHooks.set(this, void 0);
|
|
35
|
-
_AbstractExecutionService_snapToJobMap.set(this, void 0);
|
|
36
|
-
_AbstractExecutionService_jobToSnapMap.set(this, void 0);
|
|
37
|
-
_AbstractExecutionService_messenger.set(this, void 0);
|
|
38
|
-
_AbstractExecutionService_initTimeout.set(this, void 0);
|
|
39
|
-
_AbstractExecutionService_pingTimeout.set(this, void 0);
|
|
40
|
-
_AbstractExecutionService_terminationTimeout.set(this, void 0);
|
|
41
|
-
_AbstractExecutionService_usePing.set(this, void 0);
|
|
42
|
-
__classPrivateFieldSet(this, _AbstractExecutionService_snapRpcHooks, new Map(), "f");
|
|
33
|
+
this.#snapRpcHooks = new Map();
|
|
43
34
|
this.jobs = new Map();
|
|
44
35
|
this.setupSnapProvider = setupSnapProvider;
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
36
|
+
this.#snapToJobMap = new Map();
|
|
37
|
+
this.#jobToSnapMap = new Map();
|
|
38
|
+
this.#messenger = messenger;
|
|
39
|
+
this.#initTimeout = initTimeout;
|
|
40
|
+
this.#pingTimeout = pingTimeout;
|
|
41
|
+
this.#terminationTimeout = terminationTimeout;
|
|
42
|
+
this.#usePing = usePing;
|
|
52
43
|
this.registerMessageHandlers();
|
|
53
44
|
}
|
|
54
45
|
/**
|
|
@@ -56,10 +47,10 @@ class AbstractExecutionService {
|
|
|
56
47
|
* actions.
|
|
57
48
|
*/
|
|
58
49
|
registerMessageHandlers() {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
50
|
+
this.#messenger.registerActionHandler(`${controllerName}:handleRpcRequest`, async (snapId, options) => this.handleRpcRequest(snapId, options));
|
|
51
|
+
this.#messenger.registerActionHandler(`${controllerName}:executeSnap`, async (data) => this.executeSnap(data));
|
|
52
|
+
this.#messenger.registerActionHandler(`${controllerName}:terminateSnap`, async (snapId) => this.terminateSnap(snapId));
|
|
53
|
+
this.#messenger.registerActionHandler(`${controllerName}:terminateAllSnaps`, async () => this.terminateAllSnaps());
|
|
63
54
|
}
|
|
64
55
|
/**
|
|
65
56
|
* Terminates the job with the specified ID and deletes all its associated
|
|
@@ -81,7 +72,7 @@ class AbstractExecutionService {
|
|
|
81
72
|
method: 'terminate',
|
|
82
73
|
params: [],
|
|
83
74
|
id: (0, nanoid_1.nanoid)(),
|
|
84
|
-
}),
|
|
75
|
+
}), this.#terminationTimeout);
|
|
85
76
|
if (result === utils_2.hasTimedOut || result !== 'OK') {
|
|
86
77
|
// We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and
|
|
87
78
|
// hogging down the whole JS process.
|
|
@@ -105,7 +96,7 @@ class AbstractExecutionService {
|
|
|
105
96
|
});
|
|
106
97
|
this.terminateJob(jobWrapper);
|
|
107
98
|
this.jobs.delete(jobId);
|
|
108
|
-
|
|
99
|
+
this.#removeSnapAndJobMapping(jobId);
|
|
109
100
|
(0, logging_1.log)(`Job "${jobId}" terminated.`);
|
|
110
101
|
}
|
|
111
102
|
/**
|
|
@@ -160,16 +151,16 @@ class AbstractExecutionService {
|
|
|
160
151
|
return;
|
|
161
152
|
}
|
|
162
153
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
163
|
-
const snapId =
|
|
154
|
+
const snapId = this.#jobToSnapMap.get(jobId);
|
|
164
155
|
if (message.method === 'OutboundRequest') {
|
|
165
|
-
|
|
156
|
+
this.#messenger.publish('ExecutionService:outboundRequest', snapId);
|
|
166
157
|
}
|
|
167
158
|
else if (message.method === 'OutboundResponse') {
|
|
168
|
-
|
|
159
|
+
this.#messenger.publish('ExecutionService:outboundResponse', snapId);
|
|
169
160
|
}
|
|
170
161
|
else if (message.method === 'UnhandledError') {
|
|
171
162
|
if ((0, utils_1.isObject)(message.params) && message.params.error) {
|
|
172
|
-
|
|
163
|
+
this.#messenger.publish('ExecutionService:unhandledError', snapId, message.params.error);
|
|
173
164
|
commandStream.removeListener('data', notificationHandler);
|
|
174
165
|
}
|
|
175
166
|
else {
|
|
@@ -201,14 +192,14 @@ class AbstractExecutionService {
|
|
|
201
192
|
* @param snapId - The ID of the snap to terminate.
|
|
202
193
|
*/
|
|
203
194
|
async terminateSnap(snapId) {
|
|
204
|
-
const jobId =
|
|
195
|
+
const jobId = this.#snapToJobMap.get(snapId);
|
|
205
196
|
if (jobId) {
|
|
206
197
|
await this.terminate(jobId);
|
|
207
198
|
}
|
|
208
199
|
}
|
|
209
200
|
async terminateAllSnaps() {
|
|
210
201
|
await Promise.all([...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)));
|
|
211
|
-
|
|
202
|
+
this.#snapRpcHooks.clear();
|
|
212
203
|
}
|
|
213
204
|
/**
|
|
214
205
|
* Gets the RPC request handler for the given snap.
|
|
@@ -217,7 +208,7 @@ class AbstractExecutionService {
|
|
|
217
208
|
* @returns The RPC request handler for the snap.
|
|
218
209
|
*/
|
|
219
210
|
getRpcRequestHandler(snapId) {
|
|
220
|
-
return
|
|
211
|
+
return this.#snapRpcHooks.get(snapId);
|
|
221
212
|
}
|
|
222
213
|
/**
|
|
223
214
|
* Initializes and executes a snap, setting up the communication channels to the snap etc.
|
|
@@ -230,22 +221,22 @@ class AbstractExecutionService {
|
|
|
230
221
|
* @throws If the execution service returns an error or execution times out.
|
|
231
222
|
*/
|
|
232
223
|
async executeSnap({ snapId, sourceCode, endowments, }) {
|
|
233
|
-
if (
|
|
224
|
+
if (this.#snapToJobMap.has(snapId)) {
|
|
234
225
|
throw new Error(`Snap "${snapId}" is already being executed.`);
|
|
235
226
|
}
|
|
236
227
|
const jobId = (0, nanoid_1.nanoid)();
|
|
237
|
-
const timer = new Timer_1.Timer(
|
|
228
|
+
const timer = new Timer_1.Timer(this.#initTimeout);
|
|
238
229
|
// This may resolve even if the environment has failed to start up fully
|
|
239
230
|
const job = await this.initJob(jobId, timer);
|
|
240
|
-
|
|
231
|
+
this.#mapSnapAndJob(snapId, job.id);
|
|
241
232
|
// Certain environments use ping as part of their initialization and thus can skip it here
|
|
242
|
-
if (
|
|
233
|
+
if (this.#usePing) {
|
|
243
234
|
// Ping the worker to ensure that it started up
|
|
244
235
|
const pingResult = await (0, utils_2.withTimeout)(this.command(job.id, {
|
|
245
236
|
jsonrpc: '2.0',
|
|
246
237
|
method: 'ping',
|
|
247
238
|
id: (0, nanoid_1.nanoid)(),
|
|
248
|
-
}),
|
|
239
|
+
}), this.#pingTimeout);
|
|
249
240
|
if (pingResult === utils_2.hasTimedOut) {
|
|
250
241
|
throw new Error('The Snaps execution environment failed to start.');
|
|
251
242
|
}
|
|
@@ -262,7 +253,7 @@ class AbstractExecutionService {
|
|
|
262
253
|
if (result === utils_2.hasTimedOut) {
|
|
263
254
|
throw new Error(`${snapId} failed to start.`);
|
|
264
255
|
}
|
|
265
|
-
|
|
256
|
+
this.#createSnapHooks(snapId, job.id);
|
|
266
257
|
return result;
|
|
267
258
|
}
|
|
268
259
|
// Cannot be hash private yet because of tests.
|
|
@@ -281,6 +272,38 @@ class AbstractExecutionService {
|
|
|
281
272
|
}
|
|
282
273
|
return response.result;
|
|
283
274
|
}
|
|
275
|
+
#removeSnapHooks(snapId) {
|
|
276
|
+
this.#snapRpcHooks.delete(snapId);
|
|
277
|
+
}
|
|
278
|
+
#createSnapHooks(snapId, workerId) {
|
|
279
|
+
const rpcHook = async ({ origin, handler, request }) => {
|
|
280
|
+
return await this.command(workerId, {
|
|
281
|
+
id: (0, nanoid_1.nanoid)(),
|
|
282
|
+
jsonrpc: '2.0',
|
|
283
|
+
method: 'snapRpc',
|
|
284
|
+
params: {
|
|
285
|
+
origin,
|
|
286
|
+
handler,
|
|
287
|
+
request: request,
|
|
288
|
+
target: snapId,
|
|
289
|
+
},
|
|
290
|
+
});
|
|
291
|
+
};
|
|
292
|
+
this.#snapRpcHooks.set(snapId, rpcHook);
|
|
293
|
+
}
|
|
294
|
+
#mapSnapAndJob(snapId, jobId) {
|
|
295
|
+
this.#snapToJobMap.set(snapId, jobId);
|
|
296
|
+
this.#jobToSnapMap.set(jobId, snapId);
|
|
297
|
+
}
|
|
298
|
+
#removeSnapAndJobMapping(jobId) {
|
|
299
|
+
const snapId = this.#jobToSnapMap.get(jobId);
|
|
300
|
+
if (!snapId) {
|
|
301
|
+
throw new Error(`job: "${jobId}" has no mapped snap.`);
|
|
302
|
+
}
|
|
303
|
+
this.#jobToSnapMap.delete(jobId);
|
|
304
|
+
this.#snapToJobMap.delete(snapId);
|
|
305
|
+
this.#removeSnapHooks(snapId);
|
|
306
|
+
}
|
|
284
307
|
/**
|
|
285
308
|
* Handle RPC request.
|
|
286
309
|
*
|
|
@@ -297,35 +320,6 @@ class AbstractExecutionService {
|
|
|
297
320
|
}
|
|
298
321
|
}
|
|
299
322
|
exports.AbstractExecutionService = AbstractExecutionService;
|
|
300
|
-
_AbstractExecutionService_snapRpcHooks = new WeakMap(), _AbstractExecutionService_snapToJobMap = new WeakMap(), _AbstractExecutionService_jobToSnapMap = new WeakMap(), _AbstractExecutionService_messenger = new WeakMap(), _AbstractExecutionService_initTimeout = new WeakMap(), _AbstractExecutionService_pingTimeout = new WeakMap(), _AbstractExecutionService_terminationTimeout = new WeakMap(), _AbstractExecutionService_usePing = new WeakMap(), _AbstractExecutionService_instances = new WeakSet(), _AbstractExecutionService_removeSnapHooks = function _AbstractExecutionService_removeSnapHooks(snapId) {
|
|
301
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").delete(snapId);
|
|
302
|
-
}, _AbstractExecutionService_createSnapHooks = function _AbstractExecutionService_createSnapHooks(snapId, workerId) {
|
|
303
|
-
const rpcHook = async ({ origin, handler, request }) => {
|
|
304
|
-
return await this.command(workerId, {
|
|
305
|
-
id: (0, nanoid_1.nanoid)(),
|
|
306
|
-
jsonrpc: '2.0',
|
|
307
|
-
method: 'snapRpc',
|
|
308
|
-
params: {
|
|
309
|
-
origin,
|
|
310
|
-
handler,
|
|
311
|
-
request: request,
|
|
312
|
-
target: snapId,
|
|
313
|
-
},
|
|
314
|
-
});
|
|
315
|
-
};
|
|
316
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").set(snapId, rpcHook);
|
|
317
|
-
}, _AbstractExecutionService_mapSnapAndJob = function _AbstractExecutionService_mapSnapAndJob(snapId, jobId) {
|
|
318
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").set(snapId, jobId);
|
|
319
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").set(jobId, snapId);
|
|
320
|
-
}, _AbstractExecutionService_removeSnapAndJobMapping = function _AbstractExecutionService_removeSnapAndJobMapping(jobId) {
|
|
321
|
-
const snapId = __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").get(jobId);
|
|
322
|
-
if (!snapId) {
|
|
323
|
-
throw new Error(`job: "${jobId}" has no mapped snap.`);
|
|
324
|
-
}
|
|
325
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").delete(jobId);
|
|
326
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").delete(snapId);
|
|
327
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_removeSnapHooks).call(this, snapId);
|
|
328
|
-
};
|
|
329
323
|
/**
|
|
330
324
|
* Sets up stream multiplexing for the given stream.
|
|
331
325
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractExecutionService.cjs","sourceRoot":"","sources":["../../src/services/AbstractExecutionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,+DAA0D;AAC1D,qFAA8E;AAC9E,kFAAyD;AAEzD,qDAAoD;AAEpD,uDAAoE;AAMpE,2CAOyB;AACzB,mCAAgC;AAChC,qDAA2C;AAG3C,4CAAiC;AACjC,8CAAuC;AACvC,wCAAoD;AAQpD,MAAM,cAAc,GAAG,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AEF,uBAAA,IAAI,8CAAc,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAC1C,CAAC,6FAEc,MAAc,EAAE,KAAa;IAC1C,uBAAA,IAAI,8CAAc,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACtC,uBAAA,IAAI,8CAAc,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;AACxC,CAAC,iHAEwB,KAAa;IACpC,MAAM,MAAM,GAAG,uBAAA,IAAI,8CAAc,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC7C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,uBAAuB,CAAC,CAAC;IACzD,CAAC;IAED,uBAAA,IAAI,8CAAc,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACjC,uBAAA,IAAI,8CAAc,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAClC,uBAAA,IAAI,sFAAiB,MAArB,IAAI,EAAkB,MAAM,CAAC,CAAC;AAChC,CAAC;AAyBH;;;;;;GAMG;AACH,SAAgB,cAAc,CAC5B,gBAAwB,EACxB,UAAkB;IAElB,MAAM,GAAG,GAAG,IAAI,0BAAe,EAAE,CAAC;IAClC,IAAA,0BAAQ,EAAC,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,EAAE,CAAC,KAAK,EAAE,EAAE;QAC1D,IAAI,KAAK,EAAE,CAAC;YACV,UAAU;gBACR,CAAC,CAAC,IAAA,sBAAQ,EAAC,IAAI,UAAU,mBAAmB,EAAE,KAAK,CAAC;gBACpD,CAAC,CAAC,IAAA,sBAAQ,EAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACb,CAAC;AAbD,wCAaC","sourcesContent":["import { JsonRpcEngine } from '@metamask/json-rpc-engine';\nimport { createStreamMiddleware } from '@metamask/json-rpc-middleware-stream';\nimport ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { JsonRpcError } from '@metamask/rpc-errors';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type {\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport {\n Duration,\n assertIsJsonRpcRequest,\n inMilliseconds,\n isJsonRpcFailure,\n isJsonRpcNotification,\n isObject,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'readable-stream';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport { Timer } from '../snaps/Timer';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n initTimeout?: number;\n pingTimeout?: number;\n terminationTimeout?: number;\n usePing?: boolean;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport type TerminateJobArgs<WorkerType> = Partial<Job<WorkerType>> &\n Pick<Job<WorkerType>, 'id'>;\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #initTimeout: number;\n\n #pingTimeout: number;\n\n #terminationTimeout: number;\n\n #usePing: boolean;\n\n constructor({\n setupSnapProvider,\n messenger,\n initTimeout = inMilliseconds(60, Duration.Second),\n pingTimeout = inMilliseconds(2, Duration.Second),\n terminationTimeout = inMilliseconds(1, Duration.Second),\n usePing = true,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#initTimeout = initTimeout;\n this.#pingTimeout = pingTimeout;\n this.#terminationTimeout = terminationTimeout;\n this.#usePing = usePing;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (data: SnapExecutionData) => this.executeSnap(data),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: TerminateJobArgs<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n try {\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n } catch {\n // Ignore\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.jobs.delete(jobId);\n this.#removeSnapAndJobMapping(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * @param jobId - The ID of the job to initiate.\n * @param timer - The timer to use for timeouts.\n * @returns Information regarding the created job.\n * @throws If the execution service returns an error or execution times out.\n */\n protected async initJob(\n jobId: string,\n timer: Timer,\n ): Promise<Job<WorkerType>> {\n const { streams, worker } = await this.initStreams(jobId, timer);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pipeline(\n jsonRpcConnection.stream,\n streams.command,\n jsonRpcConnection.stream,\n (error) => {\n if (error) {\n logError(`Command stream failure.`, error);\n }\n },\n );\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * @param jobId - The id of the job.\n * @param timer - The timer to use for timeouts.\n * @returns The streams to communicate with the worker and the worker itself.\n * @throws If the execution service returns an error or execution times out.\n */\n protected async initStreams(\n jobId: string,\n timer: Timer,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const result = await withTimeout(this.initEnvStream(jobId), timer);\n\n if (result === hasTimedOut) {\n // For certain environments, such as the iframe we may have already created the worker and wish to terminate it.\n this.terminateJob({ id: jobId });\n throw new Error('The Snaps execution environment failed to start.');\n }\n\n const { worker, stream: envStream } = result;\n const mux = setupMultiplex(envStream, `Job: \"${jobId}\"`);\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * @param snapData - Data needed for Snap execution.\n * @param snapData.snapId - The ID of the Snap to execute.\n * @param snapData.sourceCode - The source code of the Snap to execute.\n * @param snapData.endowments - The endowments available to the executing Snap.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error or execution times out.\n */\n async executeSnap({\n snapId,\n sourceCode,\n endowments,\n }: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapId)) {\n throw new Error(`Snap \"${snapId}\" is already being executed.`);\n }\n\n const jobId = nanoid();\n const timer = new Timer(this.#initTimeout);\n\n // This may resolve even if the environment has failed to start up fully\n const job = await this.initJob(jobId, timer);\n\n this.#mapSnapAndJob(snapId, job.id);\n\n // Certain environments use ping as part of their initialization and thus can skip it here\n if (this.#usePing) {\n // Ping the worker to ensure that it started up\n const pingResult = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n }),\n this.#pingTimeout,\n );\n\n if (pingResult === hasTimedOut) {\n throw new Error('The Snaps execution environment failed to start.');\n }\n }\n\n const rpcStream = job.streams.rpc;\n\n this.setupSnapProvider(snapId, rpcStream);\n\n const remainingTime = timer.remaining;\n\n const result = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: { snapId, sourceCode, endowments },\n id: nanoid(),\n }),\n remainingTime,\n );\n\n if (result === hasTimedOut) {\n throw new Error(`${snapId} failed to start.`);\n }\n\n this.#createSnapHooks(snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest,\n ): Promise<Json | undefined> {\n assertIsJsonRpcRequest(message);\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n // eslint is blocking `await` usage even though `handle` overload returns a promise.\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const response = await job.rpcEngine.handle(message);\n\n if (isJsonRpcFailure(response)) {\n throw new JsonRpcError(\n response.error.code,\n response.error.message,\n response.error.data,\n );\n }\n\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request: request as JsonRpcRequest,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pipeline(connectionStream, mux, connectionStream, (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n });\n return mux;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AbstractExecutionService.cjs","sourceRoot":"","sources":["../../src/services/AbstractExecutionService.ts"],"names":[],"mappings":";;;;;;AAAA,+DAA0D;AAC1D,qFAA8E;AAC9E,kFAAyD;AAEzD,qDAAoD;AAEpD,uDAAoE;AAMpE,2CAOyB;AACzB,mCAAgC;AAChC,qDAA2C;AAG3C,4CAAiC;AACjC,8CAAuC;AACvC,wCAAoD;AAQpD,MAAM,cAAc,GAAG,kBAAkB,CAAC;AA6B1C,MAAsB,wBAAwB;IAG5C,aAAa,CAA2B;IAExC,+CAA+C;IACrC,IAAI,CAA+B;IAE7C,+CAA+C;IAC9B,iBAAiB,CAAoB;IAEtD,aAAa,CAAsB;IAEnC,aAAa,CAAsB;IAEnC,UAAU,CAA4B;IAEtC,YAAY,CAAS;IAErB,YAAY,CAAS;IAErB,mBAAmB,CAAS;IAE5B,QAAQ,CAAU;IAElB,YAAY,EACV,iBAAiB,EACjB,SAAS,EACT,WAAW,GAAG,IAAA,sBAAc,EAAC,EAAE,E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C;IAChC,CAAC;IAED;;;;;;OAMG;IACI,KAAK,CAAC,gBAAgB,CAC3B,MAAc,EACd,OAAwB;QAExB,MAAM,iBAAiB,GAAG,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;QAE5D,IAAI,CAAC,iBAAiB,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CACb,oEAAoE,MAAM,IAAI,CAC/E,CAAC;QACJ,CAAC;QAED,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;IACpC,CAAC;CACF;AAtcD,4DAscC;AAED;;;;;;GAMG;AACH,SAAgB,cAAc,CAC5B,gBAAwB,EACxB,UAAkB;IAElB,MAAM,GAAG,GAAG,IAAI,0BAAe,EAAE,CAAC;IAClC,IAAA,0BAAQ,EAAC,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,EAAE,CAAC,KAAK,EAAE,EAAE;QAC1D,IAAI,KAAK,EAAE,CAAC;YACV,UAAU;gBACR,CAAC,CAAC,IAAA,sBAAQ,EAAC,IAAI,UAAU,mBAAmB,EAAE,KAAK,CAAC;gBACpD,CAAC,CAAC,IAAA,sBAAQ,EAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACb,CAAC;AAbD,wCAaC","sourcesContent":["import { JsonRpcEngine } from '@metamask/json-rpc-engine';\nimport { createStreamMiddleware } from '@metamask/json-rpc-middleware-stream';\nimport ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { JsonRpcError } from '@metamask/rpc-errors';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type {\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport {\n Duration,\n assertIsJsonRpcRequest,\n inMilliseconds,\n isJsonRpcFailure,\n isJsonRpcNotification,\n isObject,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'readable-stream';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport { Timer } from '../snaps/Timer';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n initTimeout?: number;\n pingTimeout?: number;\n terminationTimeout?: number;\n usePing?: boolean;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport type TerminateJobArgs<WorkerType> = Partial<Job<WorkerType>> &\n Pick<Job<WorkerType>, 'id'>;\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #initTimeout: number;\n\n #pingTimeout: number;\n\n #terminationTimeout: number;\n\n #usePing: boolean;\n\n constructor({\n setupSnapProvider,\n messenger,\n initTimeout = inMilliseconds(60, Duration.Second),\n pingTimeout = inMilliseconds(2, Duration.Second),\n terminationTimeout = inMilliseconds(1, Duration.Second),\n usePing = true,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#initTimeout = initTimeout;\n this.#pingTimeout = pingTimeout;\n this.#terminationTimeout = terminationTimeout;\n this.#usePing = usePing;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (data: SnapExecutionData) => this.executeSnap(data),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: TerminateJobArgs<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n try {\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n } catch {\n // Ignore\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.jobs.delete(jobId);\n this.#removeSnapAndJobMapping(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * @param jobId - The ID of the job to initiate.\n * @param timer - The timer to use for timeouts.\n * @returns Information regarding the created job.\n * @throws If the execution service returns an error or execution times out.\n */\n protected async initJob(\n jobId: string,\n timer: Timer,\n ): Promise<Job<WorkerType>> {\n const { streams, worker } = await this.initStreams(jobId, timer);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pipeline(\n jsonRpcConnection.stream,\n streams.command,\n jsonRpcConnection.stream,\n (error) => {\n if (error) {\n logError(`Command stream failure.`, error);\n }\n },\n );\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * @param jobId - The id of the job.\n * @param timer - The timer to use for timeouts.\n * @returns The streams to communicate with the worker and the worker itself.\n * @throws If the execution service returns an error or execution times out.\n */\n protected async initStreams(\n jobId: string,\n timer: Timer,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const result = await withTimeout(this.initEnvStream(jobId), timer);\n\n if (result === hasTimedOut) {\n // For certain environments, such as the iframe we may have already created the worker and wish to terminate it.\n this.terminateJob({ id: jobId });\n throw new Error('The Snaps execution environment failed to start.');\n }\n\n const { worker, stream: envStream } = result;\n const mux = setupMultiplex(envStream, `Job: \"${jobId}\"`);\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * @param snapData - Data needed for Snap execution.\n * @param snapData.snapId - The ID of the Snap to execute.\n * @param snapData.sourceCode - The source code of the Snap to execute.\n * @param snapData.endowments - The endowments available to the executing Snap.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error or execution times out.\n */\n async executeSnap({\n snapId,\n sourceCode,\n endowments,\n }: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapId)) {\n throw new Error(`Snap \"${snapId}\" is already being executed.`);\n }\n\n const jobId = nanoid();\n const timer = new Timer(this.#initTimeout);\n\n // This may resolve even if the environment has failed to start up fully\n const job = await this.initJob(jobId, timer);\n\n this.#mapSnapAndJob(snapId, job.id);\n\n // Certain environments use ping as part of their initialization and thus can skip it here\n if (this.#usePing) {\n // Ping the worker to ensure that it started up\n const pingResult = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n }),\n this.#pingTimeout,\n );\n\n if (pingResult === hasTimedOut) {\n throw new Error('The Snaps execution environment failed to start.');\n }\n }\n\n const rpcStream = job.streams.rpc;\n\n this.setupSnapProvider(snapId, rpcStream);\n\n const remainingTime = timer.remaining;\n\n const result = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: { snapId, sourceCode, endowments },\n id: nanoid(),\n }),\n remainingTime,\n );\n\n if (result === hasTimedOut) {\n throw new Error(`${snapId} failed to start.`);\n }\n\n this.#createSnapHooks(snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest,\n ): Promise<Json | undefined> {\n assertIsJsonRpcRequest(message);\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n // eslint is blocking `await` usage even though `handle` overload returns a promise.\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const response = await job.rpcEngine.handle(message);\n\n if (isJsonRpcFailure(response)) {\n throw new JsonRpcError(\n response.error.code,\n response.error.message,\n response.error.data,\n );\n }\n\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request: request as JsonRpcRequest,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pipeline(connectionStream, mux, connectionStream, (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n });\n return mux;\n}\n"]}
|
|
@@ -1,15 +1,3 @@
|
|
|
1
|
-
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
5
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
-
};
|
|
7
|
-
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
9
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
-
};
|
|
12
|
-
var _AbstractExecutionService_instances, _AbstractExecutionService_snapRpcHooks, _AbstractExecutionService_snapToJobMap, _AbstractExecutionService_jobToSnapMap, _AbstractExecutionService_messenger, _AbstractExecutionService_initTimeout, _AbstractExecutionService_pingTimeout, _AbstractExecutionService_terminationTimeout, _AbstractExecutionService_usePing, _AbstractExecutionService_removeSnapHooks, _AbstractExecutionService_createSnapHooks, _AbstractExecutionService_mapSnapAndJob, _AbstractExecutionService_removeSnapAndJobMapping;
|
|
13
1
|
function $importDefault(module) {
|
|
14
2
|
if (module?.__esModule) {
|
|
15
3
|
return module.default;
|
|
@@ -30,26 +18,29 @@ import { Timer } from "../snaps/Timer.mjs";
|
|
|
30
18
|
import { hasTimedOut, withTimeout } from "../utils.mjs";
|
|
31
19
|
const controllerName = 'ExecutionService';
|
|
32
20
|
export class AbstractExecutionService {
|
|
21
|
+
#snapRpcHooks;
|
|
22
|
+
// Cannot be hash private yet because of tests.
|
|
23
|
+
jobs;
|
|
24
|
+
// Cannot be hash private yet because of tests.
|
|
25
|
+
setupSnapProvider;
|
|
26
|
+
#snapToJobMap;
|
|
27
|
+
#jobToSnapMap;
|
|
28
|
+
#messenger;
|
|
29
|
+
#initTimeout;
|
|
30
|
+
#pingTimeout;
|
|
31
|
+
#terminationTimeout;
|
|
32
|
+
#usePing;
|
|
33
33
|
constructor({ setupSnapProvider, messenger, initTimeout = inMilliseconds(60, Duration.Second), pingTimeout = inMilliseconds(2, Duration.Second), terminationTimeout = inMilliseconds(1, Duration.Second), usePing = true, }) {
|
|
34
|
-
|
|
35
|
-
_AbstractExecutionService_snapRpcHooks.set(this, void 0);
|
|
36
|
-
_AbstractExecutionService_snapToJobMap.set(this, void 0);
|
|
37
|
-
_AbstractExecutionService_jobToSnapMap.set(this, void 0);
|
|
38
|
-
_AbstractExecutionService_messenger.set(this, void 0);
|
|
39
|
-
_AbstractExecutionService_initTimeout.set(this, void 0);
|
|
40
|
-
_AbstractExecutionService_pingTimeout.set(this, void 0);
|
|
41
|
-
_AbstractExecutionService_terminationTimeout.set(this, void 0);
|
|
42
|
-
_AbstractExecutionService_usePing.set(this, void 0);
|
|
43
|
-
__classPrivateFieldSet(this, _AbstractExecutionService_snapRpcHooks, new Map(), "f");
|
|
34
|
+
this.#snapRpcHooks = new Map();
|
|
44
35
|
this.jobs = new Map();
|
|
45
36
|
this.setupSnapProvider = setupSnapProvider;
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
37
|
+
this.#snapToJobMap = new Map();
|
|
38
|
+
this.#jobToSnapMap = new Map();
|
|
39
|
+
this.#messenger = messenger;
|
|
40
|
+
this.#initTimeout = initTimeout;
|
|
41
|
+
this.#pingTimeout = pingTimeout;
|
|
42
|
+
this.#terminationTimeout = terminationTimeout;
|
|
43
|
+
this.#usePing = usePing;
|
|
53
44
|
this.registerMessageHandlers();
|
|
54
45
|
}
|
|
55
46
|
/**
|
|
@@ -57,10 +48,10 @@ export class AbstractExecutionService {
|
|
|
57
48
|
* actions.
|
|
58
49
|
*/
|
|
59
50
|
registerMessageHandlers() {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
51
|
+
this.#messenger.registerActionHandler(`${controllerName}:handleRpcRequest`, async (snapId, options) => this.handleRpcRequest(snapId, options));
|
|
52
|
+
this.#messenger.registerActionHandler(`${controllerName}:executeSnap`, async (data) => this.executeSnap(data));
|
|
53
|
+
this.#messenger.registerActionHandler(`${controllerName}:terminateSnap`, async (snapId) => this.terminateSnap(snapId));
|
|
54
|
+
this.#messenger.registerActionHandler(`${controllerName}:terminateAllSnaps`, async () => this.terminateAllSnaps());
|
|
64
55
|
}
|
|
65
56
|
/**
|
|
66
57
|
* Terminates the job with the specified ID and deletes all its associated
|
|
@@ -82,7 +73,7 @@ export class AbstractExecutionService {
|
|
|
82
73
|
method: 'terminate',
|
|
83
74
|
params: [],
|
|
84
75
|
id: nanoid(),
|
|
85
|
-
}),
|
|
76
|
+
}), this.#terminationTimeout);
|
|
86
77
|
if (result === hasTimedOut || result !== 'OK') {
|
|
87
78
|
// We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and
|
|
88
79
|
// hogging down the whole JS process.
|
|
@@ -106,7 +97,7 @@ export class AbstractExecutionService {
|
|
|
106
97
|
});
|
|
107
98
|
this.terminateJob(jobWrapper);
|
|
108
99
|
this.jobs.delete(jobId);
|
|
109
|
-
|
|
100
|
+
this.#removeSnapAndJobMapping(jobId);
|
|
110
101
|
log(`Job "${jobId}" terminated.`);
|
|
111
102
|
}
|
|
112
103
|
/**
|
|
@@ -161,16 +152,16 @@ export class AbstractExecutionService {
|
|
|
161
152
|
return;
|
|
162
153
|
}
|
|
163
154
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
164
|
-
const snapId =
|
|
155
|
+
const snapId = this.#jobToSnapMap.get(jobId);
|
|
165
156
|
if (message.method === 'OutboundRequest') {
|
|
166
|
-
|
|
157
|
+
this.#messenger.publish('ExecutionService:outboundRequest', snapId);
|
|
167
158
|
}
|
|
168
159
|
else if (message.method === 'OutboundResponse') {
|
|
169
|
-
|
|
160
|
+
this.#messenger.publish('ExecutionService:outboundResponse', snapId);
|
|
170
161
|
}
|
|
171
162
|
else if (message.method === 'UnhandledError') {
|
|
172
163
|
if (isObject(message.params) && message.params.error) {
|
|
173
|
-
|
|
164
|
+
this.#messenger.publish('ExecutionService:unhandledError', snapId, message.params.error);
|
|
174
165
|
commandStream.removeListener('data', notificationHandler);
|
|
175
166
|
}
|
|
176
167
|
else {
|
|
@@ -202,14 +193,14 @@ export class AbstractExecutionService {
|
|
|
202
193
|
* @param snapId - The ID of the snap to terminate.
|
|
203
194
|
*/
|
|
204
195
|
async terminateSnap(snapId) {
|
|
205
|
-
const jobId =
|
|
196
|
+
const jobId = this.#snapToJobMap.get(snapId);
|
|
206
197
|
if (jobId) {
|
|
207
198
|
await this.terminate(jobId);
|
|
208
199
|
}
|
|
209
200
|
}
|
|
210
201
|
async terminateAllSnaps() {
|
|
211
202
|
await Promise.all([...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)));
|
|
212
|
-
|
|
203
|
+
this.#snapRpcHooks.clear();
|
|
213
204
|
}
|
|
214
205
|
/**
|
|
215
206
|
* Gets the RPC request handler for the given snap.
|
|
@@ -218,7 +209,7 @@ export class AbstractExecutionService {
|
|
|
218
209
|
* @returns The RPC request handler for the snap.
|
|
219
210
|
*/
|
|
220
211
|
getRpcRequestHandler(snapId) {
|
|
221
|
-
return
|
|
212
|
+
return this.#snapRpcHooks.get(snapId);
|
|
222
213
|
}
|
|
223
214
|
/**
|
|
224
215
|
* Initializes and executes a snap, setting up the communication channels to the snap etc.
|
|
@@ -231,22 +222,22 @@ export class AbstractExecutionService {
|
|
|
231
222
|
* @throws If the execution service returns an error or execution times out.
|
|
232
223
|
*/
|
|
233
224
|
async executeSnap({ snapId, sourceCode, endowments, }) {
|
|
234
|
-
if (
|
|
225
|
+
if (this.#snapToJobMap.has(snapId)) {
|
|
235
226
|
throw new Error(`Snap "${snapId}" is already being executed.`);
|
|
236
227
|
}
|
|
237
228
|
const jobId = nanoid();
|
|
238
|
-
const timer = new Timer(
|
|
229
|
+
const timer = new Timer(this.#initTimeout);
|
|
239
230
|
// This may resolve even if the environment has failed to start up fully
|
|
240
231
|
const job = await this.initJob(jobId, timer);
|
|
241
|
-
|
|
232
|
+
this.#mapSnapAndJob(snapId, job.id);
|
|
242
233
|
// Certain environments use ping as part of their initialization and thus can skip it here
|
|
243
|
-
if (
|
|
234
|
+
if (this.#usePing) {
|
|
244
235
|
// Ping the worker to ensure that it started up
|
|
245
236
|
const pingResult = await withTimeout(this.command(job.id, {
|
|
246
237
|
jsonrpc: '2.0',
|
|
247
238
|
method: 'ping',
|
|
248
239
|
id: nanoid(),
|
|
249
|
-
}),
|
|
240
|
+
}), this.#pingTimeout);
|
|
250
241
|
if (pingResult === hasTimedOut) {
|
|
251
242
|
throw new Error('The Snaps execution environment failed to start.');
|
|
252
243
|
}
|
|
@@ -263,7 +254,7 @@ export class AbstractExecutionService {
|
|
|
263
254
|
if (result === hasTimedOut) {
|
|
264
255
|
throw new Error(`${snapId} failed to start.`);
|
|
265
256
|
}
|
|
266
|
-
|
|
257
|
+
this.#createSnapHooks(snapId, job.id);
|
|
267
258
|
return result;
|
|
268
259
|
}
|
|
269
260
|
// Cannot be hash private yet because of tests.
|
|
@@ -282,6 +273,38 @@ export class AbstractExecutionService {
|
|
|
282
273
|
}
|
|
283
274
|
return response.result;
|
|
284
275
|
}
|
|
276
|
+
#removeSnapHooks(snapId) {
|
|
277
|
+
this.#snapRpcHooks.delete(snapId);
|
|
278
|
+
}
|
|
279
|
+
#createSnapHooks(snapId, workerId) {
|
|
280
|
+
const rpcHook = async ({ origin, handler, request }) => {
|
|
281
|
+
return await this.command(workerId, {
|
|
282
|
+
id: nanoid(),
|
|
283
|
+
jsonrpc: '2.0',
|
|
284
|
+
method: 'snapRpc',
|
|
285
|
+
params: {
|
|
286
|
+
origin,
|
|
287
|
+
handler,
|
|
288
|
+
request: request,
|
|
289
|
+
target: snapId,
|
|
290
|
+
},
|
|
291
|
+
});
|
|
292
|
+
};
|
|
293
|
+
this.#snapRpcHooks.set(snapId, rpcHook);
|
|
294
|
+
}
|
|
295
|
+
#mapSnapAndJob(snapId, jobId) {
|
|
296
|
+
this.#snapToJobMap.set(snapId, jobId);
|
|
297
|
+
this.#jobToSnapMap.set(jobId, snapId);
|
|
298
|
+
}
|
|
299
|
+
#removeSnapAndJobMapping(jobId) {
|
|
300
|
+
const snapId = this.#jobToSnapMap.get(jobId);
|
|
301
|
+
if (!snapId) {
|
|
302
|
+
throw new Error(`job: "${jobId}" has no mapped snap.`);
|
|
303
|
+
}
|
|
304
|
+
this.#jobToSnapMap.delete(jobId);
|
|
305
|
+
this.#snapToJobMap.delete(snapId);
|
|
306
|
+
this.#removeSnapHooks(snapId);
|
|
307
|
+
}
|
|
285
308
|
/**
|
|
286
309
|
* Handle RPC request.
|
|
287
310
|
*
|
|
@@ -297,35 +320,6 @@ export class AbstractExecutionService {
|
|
|
297
320
|
return rpcRequestHandler(options);
|
|
298
321
|
}
|
|
299
322
|
}
|
|
300
|
-
_AbstractExecutionService_snapRpcHooks = new WeakMap(), _AbstractExecutionService_snapToJobMap = new WeakMap(), _AbstractExecutionService_jobToSnapMap = new WeakMap(), _AbstractExecutionService_messenger = new WeakMap(), _AbstractExecutionService_initTimeout = new WeakMap(), _AbstractExecutionService_pingTimeout = new WeakMap(), _AbstractExecutionService_terminationTimeout = new WeakMap(), _AbstractExecutionService_usePing = new WeakMap(), _AbstractExecutionService_instances = new WeakSet(), _AbstractExecutionService_removeSnapHooks = function _AbstractExecutionService_removeSnapHooks(snapId) {
|
|
301
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").delete(snapId);
|
|
302
|
-
}, _AbstractExecutionService_createSnapHooks = function _AbstractExecutionService_createSnapHooks(snapId, workerId) {
|
|
303
|
-
const rpcHook = async ({ origin, handler, request }) => {
|
|
304
|
-
return await this.command(workerId, {
|
|
305
|
-
id: nanoid(),
|
|
306
|
-
jsonrpc: '2.0',
|
|
307
|
-
method: 'snapRpc',
|
|
308
|
-
params: {
|
|
309
|
-
origin,
|
|
310
|
-
handler,
|
|
311
|
-
request: request,
|
|
312
|
-
target: snapId,
|
|
313
|
-
},
|
|
314
|
-
});
|
|
315
|
-
};
|
|
316
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").set(snapId, rpcHook);
|
|
317
|
-
}, _AbstractExecutionService_mapSnapAndJob = function _AbstractExecutionService_mapSnapAndJob(snapId, jobId) {
|
|
318
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").set(snapId, jobId);
|
|
319
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").set(jobId, snapId);
|
|
320
|
-
}, _AbstractExecutionService_removeSnapAndJobMapping = function _AbstractExecutionService_removeSnapAndJobMapping(jobId) {
|
|
321
|
-
const snapId = __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").get(jobId);
|
|
322
|
-
if (!snapId) {
|
|
323
|
-
throw new Error(`job: "${jobId}" has no mapped snap.`);
|
|
324
|
-
}
|
|
325
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").delete(jobId);
|
|
326
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").delete(snapId);
|
|
327
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_removeSnapHooks).call(this, snapId);
|
|
328
|
-
};
|
|
329
323
|
/**
|
|
330
324
|
* Sets up stream multiplexing for the given stream.
|
|
331
325
|
*
|