@metamask/snaps-controllers 12.3.0 → 13.0.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 +32 -1
- package/dist/cronjob/CronjobController.cjs +250 -276
- package/dist/cronjob/CronjobController.cjs.map +1 -1
- package/dist/cronjob/CronjobController.d.cts +61 -78
- package/dist/cronjob/CronjobController.d.cts.map +1 -1
- package/dist/cronjob/CronjobController.d.mts +61 -78
- package/dist/cronjob/CronjobController.d.mts.map +1 -1
- package/dist/cronjob/CronjobController.mjs +251 -277
- package/dist/cronjob/CronjobController.mjs.map +1 -1
- package/dist/cronjob/utils.cjs +79 -0
- package/dist/cronjob/utils.cjs.map +1 -0
- package/dist/cronjob/utils.d.cts +25 -0
- package/dist/cronjob/utils.d.cts.map +1 -0
- package/dist/cronjob/utils.d.mts +25 -0
- package/dist/cronjob/utils.d.mts.map +1 -0
- package/dist/cronjob/utils.mjs +75 -0
- package/dist/cronjob/utils.mjs.map +1 -0
- package/dist/insights/SnapInsightsController.cjs +199 -149
- package/dist/insights/SnapInsightsController.cjs.map +1 -1
- package/dist/insights/SnapInsightsController.mjs +198 -148
- package/dist/insights/SnapInsightsController.mjs.map +1 -1
- package/dist/interface/SnapInterfaceController.cjs +160 -101
- package/dist/interface/SnapInterfaceController.cjs.map +1 -1
- package/dist/interface/SnapInterfaceController.mjs +160 -101
- package/dist/interface/SnapInterfaceController.mjs.map +1 -1
- package/dist/multichain/MultichainRouter.cjs +117 -114
- package/dist/multichain/MultichainRouter.cjs.map +1 -1
- package/dist/multichain/MultichainRouter.mjs +117 -114
- package/dist/multichain/MultichainRouter.mjs.map +1 -1
- package/dist/services/AbstractExecutionService.cjs +131 -139
- package/dist/services/AbstractExecutionService.cjs.map +1 -1
- package/dist/services/AbstractExecutionService.mjs +131 -139
- 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 +6 -19
- package/dist/services/webview/WebViewExecutionService.cjs.map +1 -1
- package/dist/services/webview/WebViewExecutionService.mjs +6 -19
- package/dist/services/webview/WebViewExecutionService.mjs.map +1 -1
- package/dist/services/webview/WebViewMessageStream.cjs +13 -26
- package/dist/services/webview/WebViewMessageStream.cjs.map +1 -1
- package/dist/services/webview/WebViewMessageStream.mjs +13 -26
- package/dist/services/webview/WebViewMessageStream.mjs.map +1 -1
- package/dist/snaps/SnapController.cjs +1370 -1161
- package/dist/snaps/SnapController.cjs.map +1 -1
- package/dist/snaps/SnapController.d.cts +4 -4
- package/dist/snaps/SnapController.d.cts.map +1 -1
- package/dist/snaps/SnapController.d.mts +4 -4
- package/dist/snaps/SnapController.d.mts.map +1 -1
- package/dist/snaps/SnapController.mjs +1370 -1161
- package/dist/snaps/SnapController.mjs.map +1 -1
- package/dist/snaps/Timer.cjs +4 -0
- package/dist/snaps/Timer.cjs.map +1 -1
- package/dist/snaps/Timer.mjs +4 -0
- package/dist/snaps/Timer.mjs.map +1 -1
- package/dist/snaps/location/http.cjs +20 -4
- package/dist/snaps/location/http.cjs.map +1 -1
- package/dist/snaps/location/http.mjs +20 -4
- 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 +28 -48
- package/dist/snaps/location/npm.cjs.map +1 -1
- package/dist/snaps/location/npm.d.cts.map +1 -1
- package/dist/snaps/location/npm.d.mts.map +1 -1
- package/dist/snaps/location/npm.mjs +28 -48
- package/dist/snaps/location/npm.mjs.map +1 -1
- package/dist/snaps/registry/json.cjs +173 -166
- package/dist/snaps/registry/json.cjs.map +1 -1
- package/dist/snaps/registry/json.mjs +172 -165
- package/dist/snaps/registry/json.mjs.map +1 -1
- package/package.json +9 -9
|
@@ -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_jobs, _AbstractExecutionService_setupSnapProvider, _AbstractExecutionService_messenger, _AbstractExecutionService_initTimeout, _AbstractExecutionService_pingTimeout, _AbstractExecutionService_terminationTimeout, _AbstractExecutionService_usePing, _AbstractExecutionService_registerMessageHandlers, _AbstractExecutionService_initJob, _AbstractExecutionService_initStreams, _AbstractExecutionService_command;
|
|
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,25 +17,34 @@ 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
|
+
name = controllerName;
|
|
21
|
+
state = null;
|
|
22
|
+
#jobs;
|
|
23
|
+
#setupSnapProvider;
|
|
24
|
+
#messenger;
|
|
25
|
+
#initTimeout;
|
|
26
|
+
#pingTimeout;
|
|
27
|
+
#terminationTimeout;
|
|
28
|
+
#usePing;
|
|
32
29
|
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
|
-
this
|
|
35
|
-
this
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
30
|
+
this.#jobs = new Map();
|
|
31
|
+
this.#setupSnapProvider = setupSnapProvider;
|
|
32
|
+
this.#messenger = messenger;
|
|
33
|
+
this.#initTimeout = initTimeout;
|
|
34
|
+
this.#pingTimeout = pingTimeout;
|
|
35
|
+
this.#terminationTimeout = terminationTimeout;
|
|
36
|
+
this.#usePing = usePing;
|
|
37
|
+
this.#registerMessageHandlers();
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Constructor helper for registering the controller's messaging system
|
|
41
|
+
* actions.
|
|
42
|
+
*/
|
|
43
|
+
#registerMessageHandlers() {
|
|
44
|
+
this.#messenger.registerActionHandler(`${controllerName}:handleRpcRequest`, async (snapId, options) => this.handleRpcRequest(snapId, options));
|
|
45
|
+
this.#messenger.registerActionHandler(`${controllerName}:executeSnap`, async (data) => this.executeSnap(data));
|
|
46
|
+
this.#messenger.registerActionHandler(`${controllerName}:terminateSnap`, async (snapId) => this.terminateSnap(snapId));
|
|
47
|
+
this.#messenger.registerActionHandler(`${controllerName}:terminateAllSnaps`, async () => this.terminateAllSnaps());
|
|
51
48
|
}
|
|
52
49
|
/**
|
|
53
50
|
* Terminates the Snap with the specified ID and deletes all its associated
|
|
@@ -58,18 +55,18 @@ class AbstractExecutionService {
|
|
|
58
55
|
* @param snapId - The id of the Snap to be terminated.
|
|
59
56
|
*/
|
|
60
57
|
async terminateSnap(snapId) {
|
|
61
|
-
const job =
|
|
58
|
+
const job = this.#jobs.get(snapId);
|
|
62
59
|
if (!job) {
|
|
63
60
|
throw new Error(`"${snapId}" is not currently running.`);
|
|
64
61
|
}
|
|
65
62
|
try {
|
|
66
63
|
// Ping worker and tell it to run teardown, continue with termination if it takes too long
|
|
67
|
-
const result = await (0, utils_2.withTimeout)(
|
|
64
|
+
const result = await (0, utils_2.withTimeout)(this.#command(snapId, {
|
|
68
65
|
jsonrpc: '2.0',
|
|
69
66
|
method: 'terminate',
|
|
70
67
|
params: [],
|
|
71
68
|
id: (0, nanoid_1.nanoid)(),
|
|
72
|
-
}),
|
|
69
|
+
}), this.#terminationTimeout);
|
|
73
70
|
if (result === utils_2.hasTimedOut || result !== 'OK') {
|
|
74
71
|
// We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and
|
|
75
72
|
// hogging down the whole JS process.
|
|
@@ -92,11 +89,89 @@ class AbstractExecutionService {
|
|
|
92
89
|
}
|
|
93
90
|
});
|
|
94
91
|
this.terminateJob(job);
|
|
95
|
-
|
|
92
|
+
this.#jobs.delete(snapId);
|
|
96
93
|
(0, logging_1.log)(`Snap "${snapId}" terminated.`);
|
|
97
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Initiates a job for a Snap.
|
|
97
|
+
*
|
|
98
|
+
* @param snapId - The ID of the Snap to initiate a job for.
|
|
99
|
+
* @param timer - The timer to use for timeouts.
|
|
100
|
+
* @returns Information regarding the created job.
|
|
101
|
+
* @throws If the execution service returns an error or execution times out.
|
|
102
|
+
*/
|
|
103
|
+
async #initJob(snapId, timer) {
|
|
104
|
+
const { streams, worker } = await this.#initStreams(snapId, timer);
|
|
105
|
+
const rpcEngine = new json_rpc_engine_1.JsonRpcEngine();
|
|
106
|
+
const jsonRpcConnection = (0, json_rpc_middleware_stream_1.createStreamMiddleware)();
|
|
107
|
+
(0, readable_stream_1.pipeline)(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream, (error) => {
|
|
108
|
+
if (error) {
|
|
109
|
+
(0, snaps_utils_1.logError)(`Command stream failure.`, error);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
rpcEngine.push(jsonRpcConnection.middleware);
|
|
113
|
+
const envMetadata = {
|
|
114
|
+
id: snapId,
|
|
115
|
+
streams,
|
|
116
|
+
rpcEngine,
|
|
117
|
+
worker,
|
|
118
|
+
};
|
|
119
|
+
this.#jobs.set(snapId, envMetadata);
|
|
120
|
+
return envMetadata;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Sets up the streams for an initiated job.
|
|
124
|
+
*
|
|
125
|
+
* @param snapId - The Snap ID.
|
|
126
|
+
* @param timer - The timer to use for timeouts.
|
|
127
|
+
* @returns The streams to communicate with the worker and the worker itself.
|
|
128
|
+
* @throws If the execution service returns an error or execution times out.
|
|
129
|
+
*/
|
|
130
|
+
async #initStreams(snapId, timer) {
|
|
131
|
+
const result = await (0, utils_2.withTimeout)(this.initEnvStream(snapId), timer);
|
|
132
|
+
if (result === utils_2.hasTimedOut) {
|
|
133
|
+
// For certain environments, such as the iframe we may have already created the worker and wish to terminate it.
|
|
134
|
+
this.terminateJob({ id: snapId });
|
|
135
|
+
throw new Error('The Snaps execution environment failed to start.');
|
|
136
|
+
}
|
|
137
|
+
const { worker, stream: envStream } = result;
|
|
138
|
+
const mux = setupMultiplex(envStream, `Snap: "${snapId}"`);
|
|
139
|
+
const commandStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.COMMAND);
|
|
140
|
+
// Handle out-of-band errors, i.e. errors thrown from the Snap outside of the req/res cycle.
|
|
141
|
+
// Also keep track of outbound request/responses
|
|
142
|
+
const notificationHandler = (message) => {
|
|
143
|
+
if ((0, utils_1.hasProperty)(message, 'id')) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (message.method === 'OutboundRequest') {
|
|
147
|
+
this.#messenger.publish('ExecutionService:outboundRequest', snapId);
|
|
148
|
+
}
|
|
149
|
+
else if (message.method === 'OutboundResponse') {
|
|
150
|
+
this.#messenger.publish('ExecutionService:outboundResponse', snapId);
|
|
151
|
+
}
|
|
152
|
+
else if (message.method === 'UnhandledError') {
|
|
153
|
+
this.#messenger.publish('ExecutionService:unhandledError', snapId, message.params.error);
|
|
154
|
+
commandStream.removeListener('data', notificationHandler);
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
(0, snaps_utils_1.logError)(new Error(`Received unexpected command stream notification "${message.method}".`));
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
commandStream.on('data', notificationHandler);
|
|
161
|
+
const rpcStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.JSON_RPC);
|
|
162
|
+
// Typecast: stream type mismatch
|
|
163
|
+
return {
|
|
164
|
+
streams: {
|
|
165
|
+
command: commandStream,
|
|
166
|
+
rpc: rpcStream,
|
|
167
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
168
|
+
_connection: envStream,
|
|
169
|
+
},
|
|
170
|
+
worker,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
98
173
|
async terminateAllSnaps() {
|
|
99
|
-
await Promise.all([...
|
|
174
|
+
await Promise.all([...this.#jobs.keys()].map(async (snapId) => this.terminateSnap(snapId)));
|
|
100
175
|
}
|
|
101
176
|
/**
|
|
102
177
|
* Initializes and executes a Snap, setting up the communication channels to the Snap etc.
|
|
@@ -109,26 +184,26 @@ class AbstractExecutionService {
|
|
|
109
184
|
* @throws If the execution service returns an error or execution times out.
|
|
110
185
|
*/
|
|
111
186
|
async executeSnap({ snapId, sourceCode, endowments, }) {
|
|
112
|
-
if (
|
|
187
|
+
if (this.#jobs.has(snapId)) {
|
|
113
188
|
throw new Error(`"${snapId}" is already running.`);
|
|
114
189
|
}
|
|
115
|
-
const timer = new Timer_1.Timer(
|
|
190
|
+
const timer = new Timer_1.Timer(this.#initTimeout);
|
|
116
191
|
// This may resolve even if the environment has failed to start up fully
|
|
117
|
-
const job = await
|
|
192
|
+
const job = await this.#initJob(snapId, timer);
|
|
118
193
|
// Certain environments use ping as part of their initialization and thus can skip it here
|
|
119
|
-
if (
|
|
194
|
+
if (this.#usePing) {
|
|
120
195
|
// Ping the worker to ensure that it started up
|
|
121
|
-
const pingResult = await (0, utils_2.withTimeout)(
|
|
196
|
+
const pingResult = await (0, utils_2.withTimeout)(this.#command(job.id, {
|
|
122
197
|
jsonrpc: '2.0',
|
|
123
198
|
method: 'ping',
|
|
124
199
|
id: (0, nanoid_1.nanoid)(),
|
|
125
|
-
}),
|
|
200
|
+
}), this.#pingTimeout);
|
|
126
201
|
if (pingResult === utils_2.hasTimedOut) {
|
|
127
202
|
throw new Error('The Snaps execution environment failed to start.');
|
|
128
203
|
}
|
|
129
204
|
}
|
|
130
205
|
const rpcStream = job.streams.rpc;
|
|
131
|
-
|
|
206
|
+
this.#setupSnapProvider(snapId, rpcStream);
|
|
132
207
|
const remainingTime = timer.remaining;
|
|
133
208
|
const request = {
|
|
134
209
|
jsonrpc: '2.0',
|
|
@@ -137,12 +212,24 @@ class AbstractExecutionService {
|
|
|
137
212
|
id: (0, nanoid_1.nanoid)(),
|
|
138
213
|
};
|
|
139
214
|
(0, utils_1.assertIsJsonRpcRequest)(request);
|
|
140
|
-
const result = await (0, utils_2.withTimeout)(
|
|
215
|
+
const result = await (0, utils_2.withTimeout)(this.#command(job.id, request), remainingTime);
|
|
141
216
|
if (result === utils_2.hasTimedOut) {
|
|
142
217
|
throw new Error(`${snapId} failed to start.`);
|
|
143
218
|
}
|
|
144
219
|
return result;
|
|
145
220
|
}
|
|
221
|
+
async #command(snapId, message) {
|
|
222
|
+
const job = this.#jobs.get(snapId);
|
|
223
|
+
if (!job) {
|
|
224
|
+
throw new Error(`"${snapId}" is not currently running.`);
|
|
225
|
+
}
|
|
226
|
+
(0, logging_1.log)('Parent: Sending Command', message);
|
|
227
|
+
const response = await job.rpcEngine.handle(message);
|
|
228
|
+
if ((0, utils_1.isJsonRpcFailure)(response)) {
|
|
229
|
+
throw new rpc_errors_1.JsonRpcError(response.error.code, response.error.message, response.error.data);
|
|
230
|
+
}
|
|
231
|
+
return response.result;
|
|
232
|
+
}
|
|
146
233
|
/**
|
|
147
234
|
* Handle RPC request.
|
|
148
235
|
*
|
|
@@ -152,7 +239,7 @@ class AbstractExecutionService {
|
|
|
152
239
|
*/
|
|
153
240
|
async handleRpcRequest(snapId, options) {
|
|
154
241
|
const { handler, request, origin } = options;
|
|
155
|
-
return await
|
|
242
|
+
return await this.#command(snapId, {
|
|
156
243
|
id: (0, nanoid_1.nanoid)(),
|
|
157
244
|
jsonrpc: '2.0',
|
|
158
245
|
method: 'snapRpc',
|
|
@@ -166,101 +253,6 @@ class AbstractExecutionService {
|
|
|
166
253
|
}
|
|
167
254
|
}
|
|
168
255
|
exports.AbstractExecutionService = AbstractExecutionService;
|
|
169
|
-
_AbstractExecutionService_jobs = new WeakMap(), _AbstractExecutionService_setupSnapProvider = 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_registerMessageHandlers = function _AbstractExecutionService_registerMessageHandlers() {
|
|
170
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:handleRpcRequest`, async (snapId, options) => this.handleRpcRequest(snapId, options));
|
|
171
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:executeSnap`, async (data) => this.executeSnap(data));
|
|
172
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:terminateSnap`, async (snapId) => this.terminateSnap(snapId));
|
|
173
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:terminateAllSnaps`, async () => this.terminateAllSnaps());
|
|
174
|
-
}, _AbstractExecutionService_initJob =
|
|
175
|
-
/**
|
|
176
|
-
* Initiates a job for a Snap.
|
|
177
|
-
*
|
|
178
|
-
* @param snapId - The ID of the Snap to initiate a job for.
|
|
179
|
-
* @param timer - The timer to use for timeouts.
|
|
180
|
-
* @returns Information regarding the created job.
|
|
181
|
-
* @throws If the execution service returns an error or execution times out.
|
|
182
|
-
*/
|
|
183
|
-
async function _AbstractExecutionService_initJob(snapId, timer) {
|
|
184
|
-
const { streams, worker } = await __classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_initStreams).call(this, snapId, timer);
|
|
185
|
-
const rpcEngine = new json_rpc_engine_1.JsonRpcEngine();
|
|
186
|
-
const jsonRpcConnection = (0, json_rpc_middleware_stream_1.createStreamMiddleware)();
|
|
187
|
-
(0, readable_stream_1.pipeline)(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream, (error) => {
|
|
188
|
-
if (error) {
|
|
189
|
-
(0, snaps_utils_1.logError)(`Command stream failure.`, error);
|
|
190
|
-
}
|
|
191
|
-
});
|
|
192
|
-
rpcEngine.push(jsonRpcConnection.middleware);
|
|
193
|
-
const envMetadata = {
|
|
194
|
-
id: snapId,
|
|
195
|
-
streams,
|
|
196
|
-
rpcEngine,
|
|
197
|
-
worker,
|
|
198
|
-
};
|
|
199
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_jobs, "f").set(snapId, envMetadata);
|
|
200
|
-
return envMetadata;
|
|
201
|
-
}, _AbstractExecutionService_initStreams =
|
|
202
|
-
/**
|
|
203
|
-
* Sets up the streams for an initiated job.
|
|
204
|
-
*
|
|
205
|
-
* @param snapId - The Snap ID.
|
|
206
|
-
* @param timer - The timer to use for timeouts.
|
|
207
|
-
* @returns The streams to communicate with the worker and the worker itself.
|
|
208
|
-
* @throws If the execution service returns an error or execution times out.
|
|
209
|
-
*/
|
|
210
|
-
async function _AbstractExecutionService_initStreams(snapId, timer) {
|
|
211
|
-
const result = await (0, utils_2.withTimeout)(this.initEnvStream(snapId), timer);
|
|
212
|
-
if (result === utils_2.hasTimedOut) {
|
|
213
|
-
// For certain environments, such as the iframe we may have already created the worker and wish to terminate it.
|
|
214
|
-
this.terminateJob({ id: snapId });
|
|
215
|
-
throw new Error('The Snaps execution environment failed to start.');
|
|
216
|
-
}
|
|
217
|
-
const { worker, stream: envStream } = result;
|
|
218
|
-
const mux = setupMultiplex(envStream, `Snap: "${snapId}"`);
|
|
219
|
-
const commandStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.COMMAND);
|
|
220
|
-
// Handle out-of-band errors, i.e. errors thrown from the Snap outside of the req/res cycle.
|
|
221
|
-
// Also keep track of outbound request/responses
|
|
222
|
-
const notificationHandler = (message) => {
|
|
223
|
-
if ((0, utils_1.hasProperty)(message, 'id')) {
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
if (message.method === 'OutboundRequest') {
|
|
227
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:outboundRequest', snapId);
|
|
228
|
-
}
|
|
229
|
-
else if (message.method === 'OutboundResponse') {
|
|
230
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:outboundResponse', snapId);
|
|
231
|
-
}
|
|
232
|
-
else if (message.method === 'UnhandledError') {
|
|
233
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:unhandledError', snapId, message.params.error);
|
|
234
|
-
commandStream.removeListener('data', notificationHandler);
|
|
235
|
-
}
|
|
236
|
-
else {
|
|
237
|
-
(0, snaps_utils_1.logError)(new Error(`Received unexpected command stream notification "${message.method}".`));
|
|
238
|
-
}
|
|
239
|
-
};
|
|
240
|
-
commandStream.on('data', notificationHandler);
|
|
241
|
-
const rpcStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.JSON_RPC);
|
|
242
|
-
// Typecast: stream type mismatch
|
|
243
|
-
return {
|
|
244
|
-
streams: {
|
|
245
|
-
command: commandStream,
|
|
246
|
-
rpc: rpcStream,
|
|
247
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
248
|
-
_connection: envStream,
|
|
249
|
-
},
|
|
250
|
-
worker,
|
|
251
|
-
};
|
|
252
|
-
}, _AbstractExecutionService_command = async function _AbstractExecutionService_command(snapId, message) {
|
|
253
|
-
const job = __classPrivateFieldGet(this, _AbstractExecutionService_jobs, "f").get(snapId);
|
|
254
|
-
if (!job) {
|
|
255
|
-
throw new Error(`"${snapId}" is not currently running.`);
|
|
256
|
-
}
|
|
257
|
-
(0, logging_1.log)('Parent: Sending Command', message);
|
|
258
|
-
const response = await job.rpcEngine.handle(message);
|
|
259
|
-
if ((0, utils_1.isJsonRpcFailure)(response)) {
|
|
260
|
-
throw new rpc_errors_1.JsonRpcError(response.error.code, response.error.message, response.error.data);
|
|
261
|
-
}
|
|
262
|
-
return response.result;
|
|
263
|
-
};
|
|
264
256
|
/**
|
|
265
257
|
* Sets up stream multiplexing for the given stream.
|
|
266
258
|
*
|
|
@@ -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,2CAMyB;AACzB,mCAAgC;AAChC,qDAA2C;AAS3C,4CAAiC;AACjC,8CAAuC;AACvC,wCAAoD;AAEpD,MAAM,cAAc,GAAG,kBAAkB,CAAC;AA6B1C,MAAsB,wBAAwB;IAqB5C,YAAY,EACV,iBAAiB,EACjB,SAAS,EACT,WAAW,GAAG,IAAA,sBAAc,EAAC,EAAE,EAAE,gBAAQ,CAAC,MAAM,CAAC,EACjD,WAAW,GAAG,IAAA,sBAAc,EAAC,CAAC,EAAE,gBAAQ,CAAC,MAAM,CAAC,EAChD,kBAAkB,GAAG,IAAA,sBAAc,EAAC,CAAC,EAAE,gBAAQ,CAAC,MAAM,CAAC,EACvD,OAAO,GAAG,IAAI,GACO;;QAzBvB,SAAI,GAA0B,cAAc,CAAC;QAE7C,UAAK,GAAG,IAAI,CAAC;QAEJ,iDAAoC;QAEpC,8DAAsC;QAEtC,sDAAsC;QAEtC,wDAAqB;QAErB,wDAAqB;QAErB,+DAA4B;QAE5B,oDAAkB;QAUzB,uBAAA,IAAI,kCAAS,IAAI,GAAG,EAAE,MAAA,CAAC;QACvB,uBAAA,IAAI,+CAAsB,iBAAiB,MAAA,CAAC;QAC5C,uBAAA,IAAI,uCAAc,SAAS,MAAA,CAAC;QAC5B,uBA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CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAErD,IAAI,IAAA,wBAAgB,EAAC,QAAQ,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,yBAAY,CACpB,QAAQ,CAAC,KAAK,CAAC,IAAI,EACnB,QAAQ,CAAC,KAAK,CAAC,OAAO,EACtB,QAAQ,CAAC,KAAK,CAAC,IAAI,CACpB,CAAC;IACJ,CAAC;IAED,OAAO,QAAQ,CAAC,MAAM,CAAC;AACzB,CAAC;AA6BH;;;;;;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,IAAA,sBAAQ,EAAC,IAAI,UAAU,mBAAmB,EAAE,KAAK,CAAC,CAAC;QACrD,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACb,CAAC;AAXD,wCAWC","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 { 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 hasProperty,\n inMilliseconds,\n isJsonRpcFailure,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'readable-stream';\nimport type { Duplex } from 'readable-stream';\n\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\nimport { log } from '../logging';\nimport { Timer } from '../snaps/Timer';\nimport { hasTimedOut, withTimeout } from '../utils';\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 name: typeof controllerName = controllerName;\n\n state = null;\n\n readonly #jobs: Map<string, Job<WorkerType>>;\n\n readonly #setupSnapProvider: SetupSnapProvider;\n\n readonly #messenger: ExecutionServiceMessenger;\n\n readonly #initTimeout: number;\n\n readonly #pingTimeout: number;\n\n readonly #terminationTimeout: number;\n\n readonly #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.#jobs = new Map();\n this.#setupSnapProvider = setupSnapProvider;\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 #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 Snap with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the Snap will fail with an error.\n * Throws an error if the specified Snap does not exist, or if termination\n * fails unexpectedly.\n *\n * @param snapId - The id of the Snap to be terminated.\n */\n public async terminateSnap(snapId: string): Promise<void> {\n const job = this.#jobs.get(snapId);\n if (!job) {\n throw new Error(`\"${snapId}\" is not currently running.`);\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(snapId, {\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(`Snap \"${snapId}\" failed to terminate gracefully.`, result);\n }\n } catch {\n // Ignore\n }\n\n Object.values(job.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(job);\n\n this.#jobs.delete(snapId);\n log(`Snap \"${snapId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a Snap.\n *\n * @param snapId - The ID of the Snap to initiate a job for.\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 async #initJob(snapId: string, timer: Timer): Promise<Job<WorkerType>> {\n const { streams, worker } = await this.#initStreams(snapId, 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: snapId,\n streams,\n rpcEngine,\n worker,\n };\n this.#jobs.set(snapId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * @param snapId - The Snap ID.\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 async #initStreams(\n snapId: string,\n timer: Timer,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const result = await withTimeout(this.initEnvStream(snapId), 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: snapId });\n throw new Error('The Snaps execution environment failed to start.');\n }\n\n const { worker, stream: envStream } = result;\n const mux = setupMultiplex(envStream, `Snap: \"${snapId}\"`);\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 (hasProperty(message, 'id')) {\n return;\n }\n\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 this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n (message.params as { error: SnapErrorJson }).error,\n );\n commandStream.removeListener('data', notificationHandler);\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(snapId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.#jobs.keys()].map(async (snapId) => this.terminateSnap(snapId)),\n );\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.#jobs.has(snapId)) {\n throw new Error(`\"${snapId}\" is already running.`);\n }\n\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(snapId, timer);\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 request = {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: { snapId, sourceCode, endowments },\n id: nanoid(),\n };\n\n assertIsJsonRpcRequest(request);\n\n const result = await withTimeout(\n this.#command(job.id, request),\n remainingTime,\n );\n\n if (result === hasTimedOut) {\n throw new Error(`${snapId} failed to start.`);\n }\n\n return result as string;\n }\n\n async #command(\n snapId: string,\n message: JsonRpcRequest,\n ): Promise<Json | undefined> {\n const job = this.#jobs.get(snapId);\n if (!job) {\n throw new Error(`\"${snapId}\" is not currently running.`);\n }\n\n log('Parent: Sending Command', message);\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 /**\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 { handler, request, origin } = options;\n\n return await this.#command(snapId, {\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\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 logError(`\"${streamName}\" stream failure.`, error);\n }\n });\n return mux;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AbstractExecutionService.cjs","sourceRoot":"","sources":["../../src/services/Abst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,EAAE,CAAC;IAClC,IAAA,0BAAQ,EAAC,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,EAAE,CAAC,KAAK,EAAE,EAAE;QAC1D,IAAI,KAAK,EAAE,CAAC;YACV,IAAA,sBAAQ,EAAC,IAAI,UAAU,mBAAmB,EAAE,KAAK,CAAC,CAAC;QACrD,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACb,CAAC;AAXD,wCAWC","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 { 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 hasProperty,\n inMilliseconds,\n isJsonRpcFailure,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'readable-stream';\nimport type { Duplex } from 'readable-stream';\n\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\nimport { log } from '../logging';\nimport { Timer } from '../snaps/Timer';\nimport { hasTimedOut, withTimeout } from '../utils';\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 name: typeof controllerName = controllerName;\n\n state = null;\n\n readonly #jobs: Map<string, Job<WorkerType>>;\n\n readonly #setupSnapProvider: SetupSnapProvider;\n\n readonly #messenger: ExecutionServiceMessenger;\n\n readonly #initTimeout: number;\n\n readonly #pingTimeout: number;\n\n readonly #terminationTimeout: number;\n\n readonly #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.#jobs = new Map();\n this.#setupSnapProvider = setupSnapProvider;\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 #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 Snap with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the Snap will fail with an error.\n * Throws an error if the specified Snap does not exist, or if termination\n * fails unexpectedly.\n *\n * @param snapId - The id of the Snap to be terminated.\n */\n public async terminateSnap(snapId: string): Promise<void> {\n const job = this.#jobs.get(snapId);\n if (!job) {\n throw new Error(`\"${snapId}\" is not currently running.`);\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(snapId, {\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(`Snap \"${snapId}\" failed to terminate gracefully.`, result);\n }\n } catch {\n // Ignore\n }\n\n Object.values(job.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(job);\n\n this.#jobs.delete(snapId);\n log(`Snap \"${snapId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a Snap.\n *\n * @param snapId - The ID of the Snap to initiate a job for.\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 async #initJob(snapId: string, timer: Timer): Promise<Job<WorkerType>> {\n const { streams, worker } = await this.#initStreams(snapId, 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: snapId,\n streams,\n rpcEngine,\n worker,\n };\n this.#jobs.set(snapId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * @param snapId - The Snap ID.\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 async #initStreams(\n snapId: string,\n timer: Timer,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const result = await withTimeout(this.initEnvStream(snapId), 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: snapId });\n throw new Error('The Snaps execution environment failed to start.');\n }\n\n const { worker, stream: envStream } = result;\n const mux = setupMultiplex(envStream, `Snap: \"${snapId}\"`);\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 (hasProperty(message, 'id')) {\n return;\n }\n\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 this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n (message.params as { error: SnapErrorJson }).error,\n );\n commandStream.removeListener('data', notificationHandler);\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(snapId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.#jobs.keys()].map(async (snapId) => this.terminateSnap(snapId)),\n );\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.#jobs.has(snapId)) {\n throw new Error(`\"${snapId}\" is already running.`);\n }\n\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(snapId, timer);\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 request = {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: { snapId, sourceCode, endowments },\n id: nanoid(),\n };\n\n assertIsJsonRpcRequest(request);\n\n const result = await withTimeout(\n this.#command(job.id, request),\n remainingTime,\n );\n\n if (result === hasTimedOut) {\n throw new Error(`${snapId} failed to start.`);\n }\n\n return result as string;\n }\n\n async #command(\n snapId: string,\n message: JsonRpcRequest,\n ): Promise<Json | undefined> {\n const job = this.#jobs.get(snapId);\n if (!job) {\n throw new Error(`\"${snapId}\" is not currently running.`);\n }\n\n log('Parent: Sending Command', message);\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 /**\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 { handler, request, origin } = options;\n\n return await this.#command(snapId, {\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\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 logError(`\"${streamName}\" stream failure.`, error);\n }\n });\n return mux;\n}\n"]}
|