@metamask/snaps-controllers 0.38.2-flask.1 → 0.39.0-flask.1
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 +22 -1
- package/dist/cjs/cronjob/CronjobController.js +14 -10
- package/dist/cjs/cronjob/CronjobController.js.map +1 -1
- package/dist/cjs/services/AbstractExecutionService.js +7 -3
- package/dist/cjs/services/AbstractExecutionService.js.map +1 -1
- package/dist/cjs/snaps/SnapController.js +3 -2
- package/dist/cjs/snaps/SnapController.js.map +1 -1
- package/dist/cjs/snaps/endowments/enum.js +1 -0
- package/dist/cjs/snaps/endowments/enum.js.map +1 -1
- package/dist/cjs/snaps/endowments/index.js +10 -2
- package/dist/cjs/snaps/endowments/index.js.map +1 -1
- package/dist/cjs/snaps/endowments/name-lookup.js +106 -0
- package/dist/cjs/snaps/endowments/name-lookup.js.map +1 -0
- package/dist/cjs/snaps/location/npm.js +5 -3
- package/dist/cjs/snaps/location/npm.js.map +1 -1
- package/dist/esm/cronjob/CronjobController.js +14 -10
- package/dist/esm/cronjob/CronjobController.js.map +1 -1
- package/dist/esm/services/AbstractExecutionService.js +7 -3
- package/dist/esm/services/AbstractExecutionService.js.map +1 -1
- package/dist/esm/snaps/SnapController.js +3 -2
- package/dist/esm/snaps/SnapController.js.map +1 -1
- package/dist/esm/snaps/endowments/enum.js +1 -0
- package/dist/esm/snaps/endowments/enum.js.map +1 -1
- package/dist/esm/snaps/endowments/index.js +8 -2
- package/dist/esm/snaps/endowments/index.js.map +1 -1
- package/dist/esm/snaps/endowments/name-lookup.js +98 -0
- package/dist/esm/snaps/endowments/name-lookup.js.map +1 -0
- package/dist/esm/snaps/location/npm.js +5 -3
- package/dist/esm/snaps/location/npm.js.map +1 -1
- package/dist/types/cronjob/CronjobController.d.ts +6 -6
- package/dist/types/snaps/SnapController.d.ts +16 -1
- package/dist/types/snaps/endowments/enum.d.ts +1 -0
- package/dist/types/snaps/endowments/index.d.ts +12 -0
- package/dist/types/snaps/endowments/name-lookup.d.ts +38 -0
- package/package.json +17 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/AbstractExecutionService.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcNotification } from '@metamask/utils';\nimport { Duration, isJsonRpcNotification, isObject } from '@metamask/utils';\nimport type {\n // TODO: Replace with @metamask/utils version after bumping json-rpc-engine\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from 'json-rpc-engine';\nimport { JsonRpcEngine } from 'json-rpc-engine';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport pump from 'pump';\nimport type { Duplex } from 'stream';\n\nimport { log } from '../logging';\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 terminationTimeout?: number;\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 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 #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = Duration.Second,\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.#terminationTimeout = terminationTimeout;\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 (snapData: SnapExecutionData) => this.executeSnap(snapData),\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: Job<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 // 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\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.#removeSnapAndJobMapping(jobId);\n this.jobs.delete(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\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 * @returns Information regarding the created job.\n */\n protected async initJob(): Promise<Job<WorkerType>> {\n const jobId = nanoid();\n const { streams, worker } = await this.initStreams(jobId);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pump(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream);\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 * 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 * @param jobId - The id of the job.\n * @returns The streams to communicate with the worker and the worker itself.\n */\n protected async initStreams(\n jobId: string,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const { worker, stream: envStream } = await this.initEnvStream(jobId);\n // Typecast justification: stream type mismatch\n const mux = setupMultiplex(\n envStream as unknown as Duplex,\n `Job: \"${jobId}\"`,\n );\n\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<unknown>\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 as unknown as Duplex,\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 * 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 * @param snapData - Data needed for Snap execution.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error.\n */\n async executeSnap(snapData: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapData.snapId)) {\n throw new Error(`Snap \"${snapData.snapId}\" is already being executed.`);\n }\n\n const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc as unknown as Duplex;\n\n this.setupSnapProvider(snapData.snapId, rpcStream);\n\n const result = await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: snapData,\n id: nanoid(),\n });\n this.#createSnapHooks(snapData.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<unknown>,\n ): Promise<unknown> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\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 const response: PendingJsonRpcResponse<unknown> =\n await job.rpcEngine.handle(message);\n if (response.error) {\n throw new Error(response.error.message);\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,\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 = await 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 pump(\n connectionStream,\n // Typecast: stream type mismatch\n mux as unknown as Duplex,\n connectionStream,\n (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n },\n );\n return mux;\n}\n"],"names":["ObjectMultiplex","SNAP_STREAM_NAMES","logError","Duration","isJsonRpcNotification","isObject","JsonRpcEngine","createStreamMiddleware","nanoid","pump","log","hasTimedOut","withTimeout","controllerName","AbstractExecutionService","registerMessageHandlers","messenger","registerActionHandler","snapId","options","handleRpcRequest","snapData","executeSnap","terminateSnap","terminateAllSnaps","terminate","jobId","jobWrapper","jobs","get","Error","result","command","jsonrpc","method","params","id","terminationTimeout","Object","values","streams","forEach","stream","destroyed","destroy","removeAllListeners","error","terminateJob","removeSnapAndJobMapping","delete","initJob","worker","initStreams","rpcEngine","jsonRpcConnection","push","middleware","envMetadata","set","envStream","initEnvStream","mux","setupMultiplex","commandStream","createStream","COMMAND","notificationHandler","message","jobToSnapMap","publish","removeListener","on","rpcStream","JSON_RPC","rpc","_connection","snapToJobMap","Promise","all","keys","map","snapRpcHooks","clear","getRpcRequestHandler","has","job","mapSnapAndJob","setupSnapProvider","createSnapHooks","response","handle","rpcRequestHandler","constructor","Second","Map","workerId","rpcHook","origin","handler","request","target","removeSnapHooks","connectionStream","streamName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,qBAAqB,6BAA6B;AAGzD,SAASC,iBAAiB,EAAEC,QAAQ,QAAQ,wBAAwB;AAEpE,SAASC,QAAQ,EAAEC,qBAAqB,EAAEC,QAAQ,QAAQ,kBAAkB;AAM5E,SAASC,aAAa,QAAQ,kBAAkB;AAChD,SAASC,sBAAsB,QAAQ,6BAA6B;AACpE,SAASC,MAAM,QAAQ,SAAS;AAChC,OAAOC,UAAU,OAAO;AAGxB,SAASC,GAAG,QAAQ,aAAa;AACjC,SAASC,WAAW,EAAEC,WAAW,QAAQ,WAAW;AAQpD,MAAMC,iBAAiB;IA0BrB,6CAQA,6CAEA,6CAEA,0CAEA,mDAuTA,gDAIA,gDAkBA,8CAKA;AAnWF,OAAO,MAAeC;IAmCpB;;;GAGC,GACD,AAAQC,0BAAgC;QACtC,yBAAA,IAAI,EAAEC,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,iBAAiB,CAAC,EACpC,OAAOK,QAAgBC,UACrB,IAAI,CAACC,gBA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AQ;YACRC,QAAQ;gBACN8D;gBACAC;gBACAC;gBACAC,QAAQlF;YACV;QACF;IACF;IAEA,yBAAA,IAAI,EAAE+D,eAAavB,GAAG,CAACxC,QAAQ8E;AACjC;AAEA,SAAA,cAAe9E,MAAc,EAAEQ,KAAa;IAC1C,yBAAA,IAAI,EAAEkD,eAAalB,GAAG,CAACxC,QAAQQ;IAC/B,yBAAA,IAAI,EAAE0C,eAAaV,GAAG,CAAChC,OAAOR;AAChC;AAEA,SAAA,wBAAyBQ,KAAa;IACpC,MAAMR,SAAS,yBAAA,IAAI,EAAEkD,eAAavC,GAAG,CAACH;IACtC,IAAI,CAACR,QAAQ;QACX,MAAM,IAAIY,MAAM,CAAC,MAAM,EAAEJ,MAAM,qBAAqB,CAAC;IACvD;IAEA,yBAAA,IAAI,EAAE0C,eAAanB,MAAM,CAACvB;IAC1B,yBAAA,IAAI,EAAEkD,eAAa3B,MAAM,CAAC/B;IAC1B,0BAAA,IAAI,EAAEmF,kBAAAA,sBAAN,IAAI,EAAkBnF;AACxB;AAyBF;;;;;;CAMC,GACD,OAAO,SAAS4C,eACdwC,gBAAwB,EACxBC,UAAkB;IAElB,MAAM1C,MAAM,IAAI7D;IAChBS,KACE6F,kBACA,iCAAiC;IACjCzC,KACAyC,kBACA,CAACxD;QACC,IAAIA,OAAO;YACTyD,aACIrG,SAAS,CAAC,CAAC,EAAEqG,WAAW,iBAAiB,CAAC,EAAEzD,SAC5C5C,SAAS4C;QACf;IACF;IAEF,OAAOe;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/AbstractExecutionService.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcNotification } from '@metamask/utils';\nimport { Duration, isJsonRpcNotification, isObject } from '@metamask/utils';\nimport type {\n // TODO: Replace with @metamask/utils version after bumping json-rpc-engine\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from 'json-rpc-engine';\nimport { JsonRpcEngine } from 'json-rpc-engine';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'stream';\nimport type { Duplex } from 'stream';\n\nimport { log } from '../logging';\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 terminationTimeout?: number;\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 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 #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = Duration.Second,\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.#terminationTimeout = terminationTimeout;\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 (snapData: SnapExecutionData) => this.executeSnap(snapData),\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: Job<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 // 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\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.#removeSnapAndJobMapping(jobId);\n this.jobs.delete(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\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 * @returns Information regarding the created job.\n */\n protected async initJob(): Promise<Job<WorkerType>> {\n const jobId = nanoid();\n const { streams, worker } = await this.initStreams(jobId);\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 * 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 * @param jobId - The id of the job.\n * @returns The streams to communicate with the worker and the worker itself.\n */\n protected async initStreams(\n jobId: string,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const { worker, stream: envStream } = await this.initEnvStream(jobId);\n // Typecast justification: stream type mismatch\n const mux = setupMultiplex(\n envStream as unknown as Duplex,\n `Job: \"${jobId}\"`,\n );\n\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<unknown>\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 as unknown as Duplex,\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 * 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 * @param snapData - Data needed for Snap execution.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error.\n */\n async executeSnap(snapData: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapData.snapId)) {\n throw new Error(`Snap \"${snapData.snapId}\" is already being executed.`);\n }\n\n const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc as unknown as Duplex;\n\n this.setupSnapProvider(snapData.snapId, rpcStream);\n\n const result = await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: snapData,\n id: nanoid(),\n });\n this.#createSnapHooks(snapData.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<unknown>,\n ): Promise<unknown> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\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 const response: PendingJsonRpcResponse<unknown> =\n await job.rpcEngine.handle(message);\n if (response.error) {\n throw new Error(response.error.message);\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,\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 = await 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(\n connectionStream,\n // Typecast: stream type mismatch\n mux as unknown as Duplex,\n connectionStream,\n (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n },\n );\n return mux;\n}\n"],"names":["ObjectMultiplex","SNAP_STREAM_NAMES","logError","Duration","isJsonRpcNotification","isObject","JsonRpcEngine","createStreamMiddleware","nanoid","pipeline","log","hasTimedOut","withTimeout","controllerName","AbstractExecutionService","registerMessageHandlers","messenger","registerActionHandler","snapId","options","handleRpcRequest","snapData","executeSnap","terminateSnap","terminateAllSnaps","terminate","jobId","jobWrapper","jobs","get","Error","result","command","jsonrpc","method","params","id","terminationTimeout","Object","values","streams","forEach","stream","destroyed","destroy","removeAllListeners","error","terminateJob","removeSnapAndJobMapping","delete","initJob","worker","initStreams","rpcEngine","jsonRpcConnection","push","middleware","envMetadata","set","envStream","initEnvStream","mux","setupMultiplex","commandStream","createStream","COMMAND","notificationHandler","message","jobToSnapMap","publish","removeListener","on","rpcStream","JSON_RPC","rpc","_connection","snapToJobMap","Promise","all","keys","map","snapRpcHooks","clear","getRpcRequestHandler","has","job","mapSnapAndJob","setupSnapProvider","createSnapHooks","response","handle","rpcRequestHandler","constructor","Second","Map","workerId","rpcHook","origin","handler","request","target","removeSnapHooks","connectionStream","streamName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,qBAAqB,6BAA6B;AAGzD,SAASC,iBAAiB,EAAEC,QAAQ,QAAQ,wBAAwB;AAEpE,SAASC,QAAQ,EAAEC,qBAAqB,EAAEC,QAAQ,QAAQ,kBAAkB;AAM5E,SAASC,aAAa,QAAQ,kBAAkB;AAChD,SAASC,sBAAsB,QAAQ,6BAA6B;AACpE,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,QAAQ,SAAS;AAGlC,SAASC,GAAG,QAAQ,aAAa;AACjC,SAASC,WAAW,EAAEC,WAAW,QAAQ,WAAW;AAQpD,MAAMC,iBAAiB;IA0BrB,6CAQA,6CAEA,6CAEA,0CAEA,mDAgUA,gDAIA,gDAkBA,8CAKA;AA5WF,OAAO,MAAeC;IAmCpB;;;GAGC,GACD,AAAQC,0BAAgC;QACtC,yBAAA,IAAI,EAAEC,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,iBAAiB,CAAC,EACpC,OAAOK,QAAgBC,UACrB,IAAI,CAACC,gBAAgB,CAACF,QAAQC;QAGlC,yBAAA,IAAI,EAAEH,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,YAAY,CAAC,EAC/B,OAAOQ,WAAgC,IAAI,CAACC,WAAW,CAACD;QAG1D,yBAAA,IAAI,EAAEL,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,cAAc,CAAC,EACjC,OAAOK,SAAmB,IAAI,CAACK,aAAa,CAACL;QAG/C,yBAAA,IAAI,EAAEF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CAACxC,QAAQQ;IAC/B,yBAAA,IAAI,EAAE0C,eAAaV,GAAG,CAAChC,OAAOR;AAChC;AAEA,SAAA,wBAAyBQ,KAAa;IACpC,MAAMR,SAAS,yBAAA,IAAI,EAAEkD,eAAavC,GAAG,CAACH;IACtC,IAAI,CAACR,QAAQ;QACX,MAAM,IAAIY,MAAM,CAAC,MAAM,EAAEJ,MAAM,qBAAqB,CAAC;IACvD;IAEA,yBAAA,IAAI,EAAE0C,eAAanB,MAAM,CAACvB;IAC1B,yBAAA,IAAI,EAAEkD,eAAa3B,MAAM,CAAC/B;IAC1B,0BAAA,IAAI,EAAEmF,kBAAAA,sBAAN,IAAI,EAAkBnF;AACxB;AAyBF;;;;;;CAMC,GACD,OAAO,SAAS4C,eACdwC,gBAAwB,EACxBC,UAAkB;IAElB,MAAM1C,MAAM,IAAI7D;IAChBS,SACE6F,kBACA,iCAAiC;IACjCzC,KACAyC,kBACA,CAACxD;QACC,IAAIA,OAAO;YACTyD,aACIrG,SAAS,CAAC,CAAC,EAAEqG,WAAW,iBAAiB,CAAC,EAAEzD,SAC5C5C,SAAS4C;QACf;IACF;IAEF,OAAOe;AACT"}
|
|
@@ -267,6 +267,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
|
|
|
267
267
|
this.update((state)=>{
|
|
268
268
|
state.snaps[snapId].enabled = true;
|
|
269
269
|
});
|
|
270
|
+
this.messagingSystem.publish('SnapController:snapEnabled', this.getTruncatedExpect(snapId));
|
|
270
271
|
}
|
|
271
272
|
/**
|
|
272
273
|
* Disables the given snap. A snap can only be started if it is enabled.
|
|
@@ -281,9 +282,9 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
|
|
|
281
282
|
state.snaps[snapId].enabled = false;
|
|
282
283
|
});
|
|
283
284
|
if (this.isRunning(snapId)) {
|
|
284
|
-
|
|
285
|
+
await this.stopSnap(snapId, SnapStatusEvents.Stop);
|
|
285
286
|
}
|
|
286
|
-
|
|
287
|
+
this.messagingSystem.publish('SnapController:snapDisabled', this.getTruncatedExpect(snapId));
|
|
287
288
|
}
|
|
288
289
|
/**
|
|
289
290
|
* Stops the given snap, removes all hooks, closes all connections, and
|