@metamask/snaps-controllers 14.0.1 → 14.0.2
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 +11 -1
- package/dist/cronjob/CronjobController.cjs +2 -0
- package/dist/cronjob/CronjobController.cjs.map +1 -1
- package/dist/cronjob/CronjobController.d.cts.map +1 -1
- package/dist/cronjob/CronjobController.d.mts.map +1 -1
- package/dist/cronjob/CronjobController.mjs +2 -0
- package/dist/cronjob/CronjobController.mjs.map +1 -1
- package/dist/services/AbstractExecutionService.cjs +28 -3
- package/dist/services/AbstractExecutionService.cjs.map +1 -1
- package/dist/services/AbstractExecutionService.d.cts +16 -0
- package/dist/services/AbstractExecutionService.d.cts.map +1 -1
- package/dist/services/AbstractExecutionService.d.mts +16 -0
- package/dist/services/AbstractExecutionService.d.mts.map +1 -1
- package/dist/services/AbstractExecutionService.mjs +28 -3
- package/dist/services/AbstractExecutionService.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.d.cts.map +1 -1
- package/dist/services/iframe/IframeExecutionService.d.mts.map +1 -1
- package/dist/services/iframe/IframeExecutionService.mjs +1 -0
- package/dist/services/iframe/IframeExecutionService.mjs.map +1 -1
- package/dist/services/node-js/NodeProcessExecutionService.cjs +2 -1
- package/dist/services/node-js/NodeProcessExecutionService.cjs.map +1 -1
- package/dist/services/node-js/NodeProcessExecutionService.d.cts +1 -1
- package/dist/services/node-js/NodeProcessExecutionService.d.cts.map +1 -1
- package/dist/services/node-js/NodeProcessExecutionService.d.mts +1 -1
- package/dist/services/node-js/NodeProcessExecutionService.d.mts.map +1 -1
- package/dist/services/node-js/NodeProcessExecutionService.mjs +2 -1
- package/dist/services/node-js/NodeProcessExecutionService.mjs.map +1 -1
- package/dist/services/node-js/NodeThreadExecutionService.cjs +2 -1
- package/dist/services/node-js/NodeThreadExecutionService.cjs.map +1 -1
- package/dist/services/node-js/NodeThreadExecutionService.d.cts +1 -1
- package/dist/services/node-js/NodeThreadExecutionService.d.cts.map +1 -1
- package/dist/services/node-js/NodeThreadExecutionService.d.mts +1 -1
- package/dist/services/node-js/NodeThreadExecutionService.d.mts.map +1 -1
- package/dist/services/node-js/NodeThreadExecutionService.mjs +2 -1
- package/dist/services/node-js/NodeThreadExecutionService.mjs.map +1 -1
- package/dist/services/proxy/ProxyExecutionService.cjs +1 -0
- package/dist/services/proxy/ProxyExecutionService.cjs.map +1 -1
- package/dist/services/proxy/ProxyExecutionService.d.cts.map +1 -1
- package/dist/services/proxy/ProxyExecutionService.d.mts.map +1 -1
- package/dist/services/proxy/ProxyExecutionService.mjs +1 -0
- package/dist/services/proxy/ProxyExecutionService.mjs.map +1 -1
- package/dist/services/webview/WebViewExecutionService.cjs +1 -0
- package/dist/services/webview/WebViewExecutionService.cjs.map +1 -1
- package/dist/services/webview/WebViewExecutionService.d.cts.map +1 -1
- package/dist/services/webview/WebViewExecutionService.d.mts.map +1 -1
- package/dist/services/webview/WebViewExecutionService.mjs +1 -0
- package/dist/services/webview/WebViewExecutionService.mjs.map +1 -1
- package/dist/snaps/SnapController.cjs +4 -1
- package/dist/snaps/SnapController.cjs.map +1 -1
- package/dist/snaps/SnapController.d.cts.map +1 -1
- package/dist/snaps/SnapController.d.mts.map +1 -1
- package/dist/snaps/SnapController.mjs +4 -1
- package/dist/snaps/SnapController.mjs.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [14.0.2]
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Clear cronjobs properly for local Snaps ([#3514](https://github.com/MetaMask/snaps/pull/3514))
|
|
15
|
+
- Improve error message for cancelled requests when a Snap is stopped ([#3518](https://github.com/MetaMask/snaps/pull/3518))
|
|
16
|
+
- Improve execution service error messages ([#3521](https://github.com/MetaMask/snaps/pull/3521))
|
|
17
|
+
- Ensure Snap gets half of allocated initialization time ([#3522](https://github.com/MetaMask/snaps/pull/3522))
|
|
18
|
+
|
|
10
19
|
## [14.0.1]
|
|
11
20
|
|
|
12
21
|
### Fixed
|
|
@@ -842,7 +851,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
842
851
|
- The version of the package no longer needs to match the version of all other
|
|
843
852
|
MetaMask Snaps packages.
|
|
844
853
|
|
|
845
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@14.0.
|
|
854
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@14.0.2...HEAD
|
|
855
|
+
[14.0.2]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@14.0.1...@metamask/snaps-controllers@14.0.2
|
|
846
856
|
[14.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@14.0.0...@metamask/snaps-controllers@14.0.1
|
|
847
857
|
[14.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@13.1.1...@metamask/snaps-controllers@14.0.0
|
|
848
858
|
[13.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@13.1.0...@metamask/snaps-controllers@13.1.1
|
|
@@ -277,6 +277,8 @@ class CronjobController extends base_controller_1.BaseController {
|
|
|
277
277
|
* @param snap - Basic Snap information.
|
|
278
278
|
*/
|
|
279
279
|
#handleSnapInstalledEvent = (snap) => {
|
|
280
|
+
// In case of local Snaps, they may already have cronjobs that should be cleared.
|
|
281
|
+
this.unregister(snap.id);
|
|
280
282
|
this.register(snap.id);
|
|
281
283
|
};
|
|
282
284
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CronjobController.cjs","sourceRoot":"","sources":["../../src/cronjob/CronjobController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EAAE;gBAC7C,OAAO,EAAE,IAAI;aACd,CAAC;iBACC,KAAK,EAAE;iBACP,QAAQ,EAAE,CAAC;YAEd,IAAI,CAAC,KAAK,CAAC,SAAS,IAAI,SAAS,GAAG,GAAG,EAAE,CAAC;gBACxC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC;QACH,CAAC;IACH,CAAC;CACF;AApdD,8CAodC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { BackgroundEvent, SnapId } from '@metamask/snaps-sdk';\nimport type { TruncatedSnap } from '@metamask/snaps-utils';\nimport {\n toCensoredISO8601String,\n HandlerType,\n logError,\n} from '@metamask/snaps-utils';\nimport { assert, Duration, inMilliseconds } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { DateTime } from 'luxon';\nimport { nanoid } from 'nanoid';\n\nimport { getCronjobSpecificationSchedule, getExecutionDate } from './utils';\nimport type {\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { METAMASK_ORIGIN } from '../snaps/constants';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n CronjobControllerState\n>;\nexport type CronjobControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n CronjobControllerState\n>;\n\n/**\n * Initialise the CronjobController. This should be called after all controllers\n * are created.\n */\nexport type CronjobControllerInitAction = {\n type: `${typeof controllerName}:init`;\n handler: CronjobController['init'];\n};\n\nexport type Schedule = {\n type: `${typeof controllerName}:schedule`;\n handler: CronjobController['schedule'];\n};\n\nexport type Cancel = {\n type: `${typeof controllerName}:cancel`;\n handler: CronjobController['cancel'];\n};\n\nexport type Get = {\n type: `${typeof controllerName}:get`;\n handler: CronjobController['get'];\n};\n\nexport type CronjobControllerActions =\n | CronjobControllerGetStateAction\n | HandleSnapRequest\n | GetPermissions\n | Schedule\n | Cancel\n | Get\n | CronjobControllerInitAction;\n\nexport type CronjobControllerEvents =\n | CronjobControllerStateChangeEvent\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\n/**\n * Represents a background event that is scheduled to be executed by the\n * cronjob controller.\n */\nexport type InternalBackgroundEvent = BackgroundEvent & {\n /**\n * Whether the event is recurring.\n */\n recurring: boolean;\n\n /**\n * The cron expression or ISO 8601 duration string that defines the event's\n * schedule.\n */\n schedule: string;\n};\n\n/**\n * A schedulable background event, which is a subset of the\n * {@link InternalBackgroundEvent} type, containing only the fields required to\n * schedule an event. Other fields will be populated by the cronjob controller\n * automatically.\n */\nexport type SchedulableBackgroundEvent = Omit<\n InternalBackgroundEvent,\n 'scheduledAt' | 'date' | 'id'\n> & {\n /**\n * The optional ID of the event. If not provided, a new ID will be\n * generated.\n */\n id?: string;\n};\n\nexport type CronjobControllerState = {\n /**\n * Background events and cronjobs that are scheduled to be executed.\n */\n events: Record<string, InternalBackgroundEvent>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * The cronjob controller is responsible for managing cronjobs and background\n * events for Snaps. It allows Snaps to schedule events that will be executed\n * at a later time.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n readonly #timers: Map<string, Timer>;\n\n #dailyTimer: Timer = new Timer(DAILY_TIMEOUT);\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n events: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n events: {},\n ...state,\n },\n });\n\n this.#timers = new Map();\n\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this.#handleSnapInstalledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this.#handleSnapUninstalledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this.#handleSnapEnabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this.#handleSnapDisabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this.#handleSnapUpdatedEvent,\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:init`,\n (...args) => this.init(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:schedule`,\n (...args) => this.schedule(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:cancel`,\n (...args) => this.cancel(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:get`,\n (...args) => this.get(...args),\n );\n }\n\n /**\n * Initialize the CronjobController.\n *\n * This starts the daily timer, clears out expired events\n * and reschedules any remaining events.\n */\n init() {\n this.#start();\n this.#clear();\n this.#reschedule();\n }\n\n /**\n * Schedule a non-recurring background event.\n *\n * @param event - The event to schedule.\n * @returns The ID of the scheduled event.\n */\n schedule(event: Omit<SchedulableBackgroundEvent, 'recurring'>) {\n return this.#add({\n ...event,\n recurring: false,\n });\n }\n\n /**\n * Cancel an event.\n *\n * @param origin - The origin making the cancel call.\n * @param id - The id of the event to cancel.\n * @throws If the event does not exist.\n */\n cancel(origin: string, id: string) {\n assert(\n this.state.events[id],\n `A background event with the id of \"${id}\" does not exist.`,\n );\n\n assert(\n this.state.events[id].snapId === origin,\n 'Only the origin that scheduled this event can cancel it.',\n );\n\n this.#cancel(id);\n }\n\n /**\n * Get a list of a Snap's background events.\n *\n * @param snapId - The id of the Snap to fetch background events for.\n * @returns An array of background events.\n */\n get(snapId: SnapId): InternalBackgroundEvent[] {\n return Object.values(this.state.events)\n .filter(\n (snapEvent) => snapEvent.snapId === snapId && !snapEvent.recurring,\n )\n .map((event) => ({\n ...event,\n date: toCensoredISO8601String(event.date),\n scheduledAt: toCensoredISO8601String(event.scheduledAt),\n }));\n }\n\n /**\n * Register cronjobs for a given Snap by getting specification from the\n * permission caveats. Once registered, each job will be scheduled.\n *\n * @param snapId - The snap ID to register jobs for.\n */\n register(snapId: SnapId) {\n const jobs = this.#getSnapCronjobs(snapId);\n jobs?.forEach((job) => this.#add(job));\n }\n\n /**\n * Unregister all cronjobs and background events for a given Snap.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n for (const [id, event] of Object.entries(this.state.events)) {\n if (event.snapId === snapId) {\n this.#cancel(id);\n }\n }\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this.#handleSnapInstalledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this.#handleSnapUninstalledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this.#handleSnapEnabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this.#handleSnapDisabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this.#handleSnapUpdatedEvent,\n );\n\n // Cancel all timers and clear the map.\n this.#timers.forEach((timer) => timer.cancel());\n this.#timers.clear();\n\n if (this.#dailyTimer.status === 'running') {\n this.#dailyTimer.cancel();\n }\n }\n\n /**\n * Start the daily timer that will reschedule events every 24 hours.\n */\n #start() {\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.#reschedule();\n this.#start();\n });\n }\n\n /**\n * Add a cronjob or background event to the controller state and schedule it\n * for execution.\n *\n * @param event - The event to schedule.\n * @returns The ID of the scheduled event.\n */\n #add(event: SchedulableBackgroundEvent) {\n const id = event.id ?? nanoid();\n const internalEvent: InternalBackgroundEvent = {\n ...event,\n id,\n date: getExecutionDate(event.schedule),\n scheduledAt: new Date().toISOString(),\n };\n\n this.update((state) => {\n state.events[internalEvent.id] = castDraft(internalEvent);\n });\n\n this.#schedule(internalEvent);\n return id;\n }\n\n /**\n * Get the next execution date for a given event and start a timer for it.\n *\n * @param event - The event to schedule.\n */\n #schedule(event: InternalBackgroundEvent) {\n const date = getExecutionDate(event.schedule);\n this.update((state) => {\n state.events[event.id].date = date;\n });\n\n this.#startTimer({\n ...event,\n date,\n });\n }\n\n /**\n * Set up and start a timer for the given event.\n *\n * @param event - The event to schedule.\n * @throws If the event is scheduled in the past.\n */\n #startTimer(event: InternalBackgroundEvent) {\n const ms =\n DateTime.fromISO(event.date, { setZone: true }).toMillis() - Date.now();\n\n // We don't schedule this job yet as it is too far in the future.\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n // When an event is supposed to be scheduled close to the current time\n // we may end up needing to execute immediately instead.\n if (ms <= 0) {\n this.#execute(event);\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.#execute(event);\n });\n\n this.#timers.set(event.id, timer);\n }\n\n /**\n * Execute a background event. This method is called when the event's timer\n * expires.\n *\n * If the event is not recurring, it will be removed from the state after\n * execution. If it is recurring, it will be rescheduled.\n *\n * @param event - The event to execute.\n */\n #execute(event: InternalBackgroundEvent) {\n this.messagingSystem\n .call('SnapController:handleRequest', {\n snapId: event.snapId,\n origin: METAMASK_ORIGIN,\n handler: HandlerType.OnCronjob,\n request: event.request,\n })\n .catch((error) => {\n logError(\n `An error occurred while executing an event for Snap \"${event.snapId}\":`,\n error,\n );\n });\n\n this.#timers.delete(event.id);\n\n // Non-recurring events are removed from the state after execution, and\n // recurring events are rescheduled.\n if (!event.recurring) {\n this.update((state) => {\n delete state.events[event.id];\n });\n\n return;\n }\n\n this.#schedule(event);\n }\n\n /**\n * Cancel a background event by its ID. Unlike {@link cancel}, this method\n * does not check the origin of the event, so it can be used internally.\n *\n * @param id - The ID of the background event to cancel.\n */\n #cancel(id: string) {\n const timer = this.#timers.get(id);\n timer?.cancel();\n this.#timers.delete(id);\n\n this.update((state) => {\n delete state.events[id];\n });\n }\n\n /**\n * Retrieve all cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of cronjob specifications.\n */\n #getSnapCronjobs(snapId: SnapId): SchedulableBackgroundEvent[] {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n if (!definitions) {\n return [];\n }\n\n return definitions.map((definition, idx) => {\n return {\n snapId,\n id: `cronjob-${snapId}-${idx}`,\n request: definition.request,\n schedule: getCronjobSpecificationSchedule(definition),\n recurring: true,\n };\n });\n }\n\n /**\n * Handle events that should cause cron jobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapInstalledEvent = (snap: TruncatedSnap) => {\n this.register(snap.id);\n };\n\n /**\n * Handle the Snap enabled event. This checks if the Snap has any cronjobs or\n * background events that need to be rescheduled.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapEnabledEvent = (snap: TruncatedSnap) => {\n const events = this.get(snap.id);\n this.#reschedule(events);\n this.register(snap.id);\n };\n\n /**\n * Handle events that should cause cronjobs and background events to be\n * unregistered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapUninstalledEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n };\n\n /**\n * Handle events that should cause cronjobs and background events to be\n * unregistered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapDisabledEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n };\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapUpdatedEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n this.register(snap.id);\n };\n\n /**\n * Reschedule events that are yet to be executed. This should be called on\n * controller initialization and once every 24 hours to ensure that\n * background events are scheduled correctly.\n *\n * @param events - An array of events to reschedule. Defaults to all events in\n * the controller state.\n */\n #reschedule(events = Object.values(this.state.events)) {\n const now = Date.now();\n\n for (const event of events) {\n if (this.#timers.has(event.id)) {\n // If the timer for this event already exists, we don't need to\n // reschedule it.\n continue;\n }\n\n const eventDate = DateTime.fromISO(event.date, {\n setZone: true,\n })\n .toUTC()\n .toMillis();\n\n // If the event is recurring and the date is in the past, execute it\n // immediately.\n if (event.recurring && eventDate <= now) {\n this.#execute(event);\n }\n\n this.#schedule(event);\n }\n }\n\n /**\n * Clear non-recurring events that are past their scheduled time.\n */\n #clear() {\n const now = Date.now();\n\n for (const event of Object.values(this.state.events)) {\n const eventDate = DateTime.fromISO(event.date, {\n setZone: true,\n })\n .toUTC()\n .toMillis();\n\n if (!event.recurring && eventDate < now) {\n this.#cancel(event.id);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CronjobController.cjs","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":";;;AAKA,+DAA2D;AAE3D,mEAGqC;AAGrC,uDAI+B;AAC/B,2CAAmE;AACnE,iCAAkC;AAClC,iCAAiC;AACjC,mCAAgC;AAEhC,uCAA4E;AAS5E,sDAAqD;AACrD,8CAAuC;AA4D1B,QAAA,aAAa,GAAG,IAAA,sBAAc,EAAC,EAAE,EAAE,gBAAQ,CAAC,IAAI,CAAC,CAAC;AAoD/D,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAE3C;;;;GAIG;AACH,MAAa,iBAAkB,SAAQ,gCAItC;IACU,OAAO,CAAqB;IAErC,WAAW,GAAU,IAAI,a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llerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { BackgroundEvent, SnapId } from '@metamask/snaps-sdk';\nimport type { TruncatedSnap } from '@metamask/snaps-utils';\nimport {\n toCensoredISO8601String,\n HandlerType,\n logError,\n} from '@metamask/snaps-utils';\nimport { assert, Duration, inMilliseconds } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { DateTime } from 'luxon';\nimport { nanoid } from 'nanoid';\n\nimport { getCronjobSpecificationSchedule, getExecutionDate } from './utils';\nimport type {\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { METAMASK_ORIGIN } from '../snaps/constants';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n CronjobControllerState\n>;\nexport type CronjobControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n CronjobControllerState\n>;\n\n/**\n * Initialise the CronjobController. This should be called after all controllers\n * are created.\n */\nexport type CronjobControllerInitAction = {\n type: `${typeof controllerName}:init`;\n handler: CronjobController['init'];\n};\n\nexport type Schedule = {\n type: `${typeof controllerName}:schedule`;\n handler: CronjobController['schedule'];\n};\n\nexport type Cancel = {\n type: `${typeof controllerName}:cancel`;\n handler: CronjobController['cancel'];\n};\n\nexport type Get = {\n type: `${typeof controllerName}:get`;\n handler: CronjobController['get'];\n};\n\nexport type CronjobControllerActions =\n | CronjobControllerGetStateAction\n | HandleSnapRequest\n | GetPermissions\n | Schedule\n | Cancel\n | Get\n | CronjobControllerInitAction;\n\nexport type CronjobControllerEvents =\n | CronjobControllerStateChangeEvent\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\n/**\n * Represents a background event that is scheduled to be executed by the\n * cronjob controller.\n */\nexport type InternalBackgroundEvent = BackgroundEvent & {\n /**\n * Whether the event is recurring.\n */\n recurring: boolean;\n\n /**\n * The cron expression or ISO 8601 duration string that defines the event's\n * schedule.\n */\n schedule: string;\n};\n\n/**\n * A schedulable background event, which is a subset of the\n * {@link InternalBackgroundEvent} type, containing only the fields required to\n * schedule an event. Other fields will be populated by the cronjob controller\n * automatically.\n */\nexport type SchedulableBackgroundEvent = Omit<\n InternalBackgroundEvent,\n 'scheduledAt' | 'date' | 'id'\n> & {\n /**\n * The optional ID of the event. If not provided, a new ID will be\n * generated.\n */\n id?: string;\n};\n\nexport type CronjobControllerState = {\n /**\n * Background events and cronjobs that are scheduled to be executed.\n */\n events: Record<string, InternalBackgroundEvent>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * The cronjob controller is responsible for managing cronjobs and background\n * events for Snaps. It allows Snaps to schedule events that will be executed\n * at a later time.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n readonly #timers: Map<string, Timer>;\n\n #dailyTimer: Timer = new Timer(DAILY_TIMEOUT);\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n events: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n events: {},\n ...state,\n },\n });\n\n this.#timers = new Map();\n\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this.#handleSnapInstalledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this.#handleSnapUninstalledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this.#handleSnapEnabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this.#handleSnapDisabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this.#handleSnapUpdatedEvent,\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:init`,\n (...args) => this.init(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:schedule`,\n (...args) => this.schedule(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:cancel`,\n (...args) => this.cancel(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:get`,\n (...args) => this.get(...args),\n );\n }\n\n /**\n * Initialize the CronjobController.\n *\n * This starts the daily timer, clears out expired events\n * and reschedules any remaining events.\n */\n init() {\n this.#start();\n this.#clear();\n this.#reschedule();\n }\n\n /**\n * Schedule a non-recurring background event.\n *\n * @param event - The event to schedule.\n * @returns The ID of the scheduled event.\n */\n schedule(event: Omit<SchedulableBackgroundEvent, 'recurring'>) {\n return this.#add({\n ...event,\n recurring: false,\n });\n }\n\n /**\n * Cancel an event.\n *\n * @param origin - The origin making the cancel call.\n * @param id - The id of the event to cancel.\n * @throws If the event does not exist.\n */\n cancel(origin: string, id: string) {\n assert(\n this.state.events[id],\n `A background event with the id of \"${id}\" does not exist.`,\n );\n\n assert(\n this.state.events[id].snapId === origin,\n 'Only the origin that scheduled this event can cancel it.',\n );\n\n this.#cancel(id);\n }\n\n /**\n * Get a list of a Snap's background events.\n *\n * @param snapId - The id of the Snap to fetch background events for.\n * @returns An array of background events.\n */\n get(snapId: SnapId): InternalBackgroundEvent[] {\n return Object.values(this.state.events)\n .filter(\n (snapEvent) => snapEvent.snapId === snapId && !snapEvent.recurring,\n )\n .map((event) => ({\n ...event,\n date: toCensoredISO8601String(event.date),\n scheduledAt: toCensoredISO8601String(event.scheduledAt),\n }));\n }\n\n /**\n * Register cronjobs for a given Snap by getting specification from the\n * permission caveats. Once registered, each job will be scheduled.\n *\n * @param snapId - The snap ID to register jobs for.\n */\n register(snapId: SnapId) {\n const jobs = this.#getSnapCronjobs(snapId);\n jobs?.forEach((job) => this.#add(job));\n }\n\n /**\n * Unregister all cronjobs and background events for a given Snap.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n for (const [id, event] of Object.entries(this.state.events)) {\n if (event.snapId === snapId) {\n this.#cancel(id);\n }\n }\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this.#handleSnapInstalledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this.#handleSnapUninstalledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this.#handleSnapEnabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this.#handleSnapDisabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this.#handleSnapUpdatedEvent,\n );\n\n // Cancel all timers and clear the map.\n this.#timers.forEach((timer) => timer.cancel());\n this.#timers.clear();\n\n if (this.#dailyTimer.status === 'running') {\n this.#dailyTimer.cancel();\n }\n }\n\n /**\n * Start the daily timer that will reschedule events every 24 hours.\n */\n #start() {\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.#reschedule();\n this.#start();\n });\n }\n\n /**\n * Add a cronjob or background event to the controller state and schedule it\n * for execution.\n *\n * @param event - The event to schedule.\n * @returns The ID of the scheduled event.\n */\n #add(event: SchedulableBackgroundEvent) {\n const id = event.id ?? nanoid();\n const internalEvent: InternalBackgroundEvent = {\n ...event,\n id,\n date: getExecutionDate(event.schedule),\n scheduledAt: new Date().toISOString(),\n };\n\n this.update((state) => {\n state.events[internalEvent.id] = castDraft(internalEvent);\n });\n\n this.#schedule(internalEvent);\n return id;\n }\n\n /**\n * Get the next execution date for a given event and start a timer for it.\n *\n * @param event - The event to schedule.\n */\n #schedule(event: InternalBackgroundEvent) {\n const date = getExecutionDate(event.schedule);\n this.update((state) => {\n state.events[event.id].date = date;\n });\n\n this.#startTimer({\n ...event,\n date,\n });\n }\n\n /**\n * Set up and start a timer for the given event.\n *\n * @param event - The event to schedule.\n * @throws If the event is scheduled in the past.\n */\n #startTimer(event: InternalBackgroundEvent) {\n const ms =\n DateTime.fromISO(event.date, { setZone: true }).toMillis() - Date.now();\n\n // We don't schedule this job yet as it is too far in the future.\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n // When an event is supposed to be scheduled close to the current time\n // we may end up needing to execute immediately instead.\n if (ms <= 0) {\n this.#execute(event);\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.#execute(event);\n });\n\n this.#timers.set(event.id, timer);\n }\n\n /**\n * Execute a background event. This method is called when the event's timer\n * expires.\n *\n * If the event is not recurring, it will be removed from the state after\n * execution. If it is recurring, it will be rescheduled.\n *\n * @param event - The event to execute.\n */\n #execute(event: InternalBackgroundEvent) {\n this.messagingSystem\n .call('SnapController:handleRequest', {\n snapId: event.snapId,\n origin: METAMASK_ORIGIN,\n handler: HandlerType.OnCronjob,\n request: event.request,\n })\n .catch((error) => {\n logError(\n `An error occurred while executing an event for Snap \"${event.snapId}\":`,\n error,\n );\n });\n\n this.#timers.delete(event.id);\n\n // Non-recurring events are removed from the state after execution, and\n // recurring events are rescheduled.\n if (!event.recurring) {\n this.update((state) => {\n delete state.events[event.id];\n });\n\n return;\n }\n\n this.#schedule(event);\n }\n\n /**\n * Cancel a background event by its ID. Unlike {@link cancel}, this method\n * does not check the origin of the event, so it can be used internally.\n *\n * @param id - The ID of the background event to cancel.\n */\n #cancel(id: string) {\n const timer = this.#timers.get(id);\n timer?.cancel();\n this.#timers.delete(id);\n\n this.update((state) => {\n delete state.events[id];\n });\n }\n\n /**\n * Retrieve all cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of cronjob specifications.\n */\n #getSnapCronjobs(snapId: SnapId): SchedulableBackgroundEvent[] {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n if (!definitions) {\n return [];\n }\n\n return definitions.map((definition, idx) => {\n return {\n snapId,\n id: `cronjob-${snapId}-${idx}`,\n request: definition.request,\n schedule: getCronjobSpecificationSchedule(definition),\n recurring: true,\n };\n });\n }\n\n /**\n * Handle events that should cause cron jobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapInstalledEvent = (snap: TruncatedSnap) => {\n // In case of local Snaps, they may already have cronjobs that should be cleared.\n this.unregister(snap.id);\n this.register(snap.id);\n };\n\n /**\n * Handle the Snap enabled event. This checks if the Snap has any cronjobs or\n * background events that need to be rescheduled.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapEnabledEvent = (snap: TruncatedSnap) => {\n const events = this.get(snap.id);\n this.#reschedule(events);\n this.register(snap.id);\n };\n\n /**\n * Handle events that should cause cronjobs and background events to be\n * unregistered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapUninstalledEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n };\n\n /**\n * Handle events that should cause cronjobs and background events to be\n * unregistered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapDisabledEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n };\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapUpdatedEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n this.register(snap.id);\n };\n\n /**\n * Reschedule events that are yet to be executed. This should be called on\n * controller initialization and once every 24 hours to ensure that\n * background events are scheduled correctly.\n *\n * @param events - An array of events to reschedule. Defaults to all events in\n * the controller state.\n */\n #reschedule(events = Object.values(this.state.events)) {\n const now = Date.now();\n\n for (const event of events) {\n if (this.#timers.has(event.id)) {\n // If the timer for this event already exists, we don't need to\n // reschedule it.\n continue;\n }\n\n const eventDate = DateTime.fromISO(event.date, {\n setZone: true,\n })\n .toUTC()\n .toMillis();\n\n // If the event is recurring and the date is in the past, execute it\n // immediately.\n if (event.recurring && eventDate <= now) {\n this.#execute(event);\n }\n\n this.#schedule(event);\n }\n }\n\n /**\n * Clear non-recurring events that are past their scheduled time.\n */\n #clear() {\n const now = Date.now();\n\n for (const event of Object.values(this.state.events)) {\n const eventDate = DateTime.fromISO(event.date, {\n setZone: true,\n })\n .toUTC()\n .toMillis();\n\n if (!event.recurring && eventDate < now) {\n this.#cancel(event.id);\n }\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CronjobController.d.cts","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,wCAAwC;AAKtE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,4BAA4B;AAanE,OAAO,KAAK,EACV,iBAAiB,EACjB,YAAY,EACZ,WAAW,EACX,aAAa,EACb,eAAe,EACf,WAAW,EACZ,qBAAW;AAIZ,MAAM,MAAM,+BAA+B,GAAG,wBAAwB,CACpE,OAAO,cAAc,EACrB,sBAAsB,CACvB,CAAC;AACF,MAAM,MAAM,iCAAiC,GAAG,0BAA0B,CACxE,OAAO,cAAc,EACrB,sBAAsB,CACvB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,GAAG,OAAO,cAAc,OAAO,CAAC;IACtC,OAAO,EAAE,iBAAiB,CAAC,MAAM,CAA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;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,cAAc,CACnD,OAAO,cAAc,EACrB,sBAAsB,EACtB,0BAA0B,CAC3B;;gBAKa,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,qBAAqB;IA6DvD;;;;;OAKG;IACH,IAAI;IAMJ;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,0BAA0B,EAAE,WAAW,CAAC;IAO7D;;;;;;OAMG;IACH,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAcjC;;;;;OAKG;IACH,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,uBAAuB,EAAE;IAY9C;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM;IAKvB;;;;OAIG;IACH,UAAU,CAAC,MAAM,EAAE,MAAM;IAQzB;;OAEG;IACH,OAAO;CAqTR"}
|
|
@@ -274,6 +274,8 @@ export class CronjobController extends BaseController {
|
|
|
274
274
|
* @param snap - Basic Snap information.
|
|
275
275
|
*/
|
|
276
276
|
#handleSnapInstalledEvent = (snap) => {
|
|
277
|
+
// In case of local Snaps, they may already have cronjobs that should be cleared.
|
|
278
|
+
this.unregister(snap.id);
|
|
277
279
|
this.register(snap.id);
|
|
278
280
|
};
|
|
279
281
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CronjobController.mjs","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,EACL,oBAAoB,EACpB,cAAc,EACf,oCAAoC;AAGrC,OAAO,EACL,uBAAuB,EACvB,WAAW,EACX,QAAQ,EACT,8BAA8B;AAC/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AACnE,OAAO,EAAE,SAAS,EAAE,cAAc;AAClC,OAAO,EAAE,QAAQ,EAAE,cAAc;AACjC,OAAO,EAAE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Ed,IAAI,CAAC,KAAK,CAAC,SAAS,IAAI,SAAS,GAAG,GAAG,EAAE,CAAC;gBACxC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { BackgroundEvent, SnapId } from '@metamask/snaps-sdk';\nimport type { TruncatedSnap } from '@metamask/snaps-utils';\nimport {\n toCensoredISO8601String,\n HandlerType,\n logError,\n} from '@metamask/snaps-utils';\nimport { assert, Duration, inMilliseconds } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { DateTime } from 'luxon';\nimport { nanoid } from 'nanoid';\n\nimport { getCronjobSpecificationSchedule, getExecutionDate } from './utils';\nimport type {\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { METAMASK_ORIGIN } from '../snaps/constants';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n CronjobControllerState\n>;\nexport type CronjobControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n CronjobControllerState\n>;\n\n/**\n * Initialise the CronjobController. This should be called after all controllers\n * are created.\n */\nexport type CronjobControllerInitAction = {\n type: `${typeof controllerName}:init`;\n handler: CronjobController['init'];\n};\n\nexport type Schedule = {\n type: `${typeof controllerName}:schedule`;\n handler: CronjobController['schedule'];\n};\n\nexport type Cancel = {\n type: `${typeof controllerName}:cancel`;\n handler: CronjobController['cancel'];\n};\n\nexport type Get = {\n type: `${typeof controllerName}:get`;\n handler: CronjobController['get'];\n};\n\nexport type CronjobControllerActions =\n | CronjobControllerGetStateAction\n | HandleSnapRequest\n | GetPermissions\n | Schedule\n | Cancel\n | Get\n | CronjobControllerInitAction;\n\nexport type CronjobControllerEvents =\n | CronjobControllerStateChangeEvent\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\n/**\n * Represents a background event that is scheduled to be executed by the\n * cronjob controller.\n */\nexport type InternalBackgroundEvent = BackgroundEvent & {\n /**\n * Whether the event is recurring.\n */\n recurring: boolean;\n\n /**\n * The cron expression or ISO 8601 duration string that defines the event's\n * schedule.\n */\n schedule: string;\n};\n\n/**\n * A schedulable background event, which is a subset of the\n * {@link InternalBackgroundEvent} type, containing only the fields required to\n * schedule an event. Other fields will be populated by the cronjob controller\n * automatically.\n */\nexport type SchedulableBackgroundEvent = Omit<\n InternalBackgroundEvent,\n 'scheduledAt' | 'date' | 'id'\n> & {\n /**\n * The optional ID of the event. If not provided, a new ID will be\n * generated.\n */\n id?: string;\n};\n\nexport type CronjobControllerState = {\n /**\n * Background events and cronjobs that are scheduled to be executed.\n */\n events: Record<string, InternalBackgroundEvent>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * The cronjob controller is responsible for managing cronjobs and background\n * events for Snaps. It allows Snaps to schedule events that will be executed\n * at a later time.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n readonly #timers: Map<string, Timer>;\n\n #dailyTimer: Timer = new Timer(DAILY_TIMEOUT);\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n events: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n events: {},\n ...state,\n },\n });\n\n this.#timers = new Map();\n\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this.#handleSnapInstalledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this.#handleSnapUninstalledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this.#handleSnapEnabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this.#handleSnapDisabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this.#handleSnapUpdatedEvent,\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:init`,\n (...args) => this.init(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:schedule`,\n (...args) => this.schedule(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:cancel`,\n (...args) => this.cancel(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:get`,\n (...args) => this.get(...args),\n );\n }\n\n /**\n * Initialize the CronjobController.\n *\n * This starts the daily timer, clears out expired events\n * and reschedules any remaining events.\n */\n init() {\n this.#start();\n this.#clear();\n this.#reschedule();\n }\n\n /**\n * Schedule a non-recurring background event.\n *\n * @param event - The event to schedule.\n * @returns The ID of the scheduled event.\n */\n schedule(event: Omit<SchedulableBackgroundEvent, 'recurring'>) {\n return this.#add({\n ...event,\n recurring: false,\n });\n }\n\n /**\n * Cancel an event.\n *\n * @param origin - The origin making the cancel call.\n * @param id - The id of the event to cancel.\n * @throws If the event does not exist.\n */\n cancel(origin: string, id: string) {\n assert(\n this.state.events[id],\n `A background event with the id of \"${id}\" does not exist.`,\n );\n\n assert(\n this.state.events[id].snapId === origin,\n 'Only the origin that scheduled this event can cancel it.',\n );\n\n this.#cancel(id);\n }\n\n /**\n * Get a list of a Snap's background events.\n *\n * @param snapId - The id of the Snap to fetch background events for.\n * @returns An array of background events.\n */\n get(snapId: SnapId): InternalBackgroundEvent[] {\n return Object.values(this.state.events)\n .filter(\n (snapEvent) => snapEvent.snapId === snapId && !snapEvent.recurring,\n )\n .map((event) => ({\n ...event,\n date: toCensoredISO8601String(event.date),\n scheduledAt: toCensoredISO8601String(event.scheduledAt),\n }));\n }\n\n /**\n * Register cronjobs for a given Snap by getting specification from the\n * permission caveats. Once registered, each job will be scheduled.\n *\n * @param snapId - The snap ID to register jobs for.\n */\n register(snapId: SnapId) {\n const jobs = this.#getSnapCronjobs(snapId);\n jobs?.forEach((job) => this.#add(job));\n }\n\n /**\n * Unregister all cronjobs and background events for a given Snap.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n for (const [id, event] of Object.entries(this.state.events)) {\n if (event.snapId === snapId) {\n this.#cancel(id);\n }\n }\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this.#handleSnapInstalledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this.#handleSnapUninstalledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this.#handleSnapEnabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this.#handleSnapDisabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this.#handleSnapUpdatedEvent,\n );\n\n // Cancel all timers and clear the map.\n this.#timers.forEach((timer) => timer.cancel());\n this.#timers.clear();\n\n if (this.#dailyTimer.status === 'running') {\n this.#dailyTimer.cancel();\n }\n }\n\n /**\n * Start the daily timer that will reschedule events every 24 hours.\n */\n #start() {\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.#reschedule();\n this.#start();\n });\n }\n\n /**\n * Add a cronjob or background event to the controller state and schedule it\n * for execution.\n *\n * @param event - The event to schedule.\n * @returns The ID of the scheduled event.\n */\n #add(event: SchedulableBackgroundEvent) {\n const id = event.id ?? nanoid();\n const internalEvent: InternalBackgroundEvent = {\n ...event,\n id,\n date: getExecutionDate(event.schedule),\n scheduledAt: new Date().toISOString(),\n };\n\n this.update((state) => {\n state.events[internalEvent.id] = castDraft(internalEvent);\n });\n\n this.#schedule(internalEvent);\n return id;\n }\n\n /**\n * Get the next execution date for a given event and start a timer for it.\n *\n * @param event - The event to schedule.\n */\n #schedule(event: InternalBackgroundEvent) {\n const date = getExecutionDate(event.schedule);\n this.update((state) => {\n state.events[event.id].date = date;\n });\n\n this.#startTimer({\n ...event,\n date,\n });\n }\n\n /**\n * Set up and start a timer for the given event.\n *\n * @param event - The event to schedule.\n * @throws If the event is scheduled in the past.\n */\n #startTimer(event: InternalBackgroundEvent) {\n const ms =\n DateTime.fromISO(event.date, { setZone: true }).toMillis() - Date.now();\n\n // We don't schedule this job yet as it is too far in the future.\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n // When an event is supposed to be scheduled close to the current time\n // we may end up needing to execute immediately instead.\n if (ms <= 0) {\n this.#execute(event);\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.#execute(event);\n });\n\n this.#timers.set(event.id, timer);\n }\n\n /**\n * Execute a background event. This method is called when the event's timer\n * expires.\n *\n * If the event is not recurring, it will be removed from the state after\n * execution. If it is recurring, it will be rescheduled.\n *\n * @param event - The event to execute.\n */\n #execute(event: InternalBackgroundEvent) {\n this.messagingSystem\n .call('SnapController:handleRequest', {\n snapId: event.snapId,\n origin: METAMASK_ORIGIN,\n handler: HandlerType.OnCronjob,\n request: event.request,\n })\n .catch((error) => {\n logError(\n `An error occurred while executing an event for Snap \"${event.snapId}\":`,\n error,\n );\n });\n\n this.#timers.delete(event.id);\n\n // Non-recurring events are removed from the state after execution, and\n // recurring events are rescheduled.\n if (!event.recurring) {\n this.update((state) => {\n delete state.events[event.id];\n });\n\n return;\n }\n\n this.#schedule(event);\n }\n\n /**\n * Cancel a background event by its ID. Unlike {@link cancel}, this method\n * does not check the origin of the event, so it can be used internally.\n *\n * @param id - The ID of the background event to cancel.\n */\n #cancel(id: string) {\n const timer = this.#timers.get(id);\n timer?.cancel();\n this.#timers.delete(id);\n\n this.update((state) => {\n delete state.events[id];\n });\n }\n\n /**\n * Retrieve all cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of cronjob specifications.\n */\n #getSnapCronjobs(snapId: SnapId): SchedulableBackgroundEvent[] {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n if (!definitions) {\n return [];\n }\n\n return definitions.map((definition, idx) => {\n return {\n snapId,\n id: `cronjob-${snapId}-${idx}`,\n request: definition.request,\n schedule: getCronjobSpecificationSchedule(definition),\n recurring: true,\n };\n });\n }\n\n /**\n * Handle events that should cause cron jobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapInstalledEvent = (snap: TruncatedSnap) => {\n this.register(snap.id);\n };\n\n /**\n * Handle the Snap enabled event. This checks if the Snap has any cronjobs or\n * background events that need to be rescheduled.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapEnabledEvent = (snap: TruncatedSnap) => {\n const events = this.get(snap.id);\n this.#reschedule(events);\n this.register(snap.id);\n };\n\n /**\n * Handle events that should cause cronjobs and background events to be\n * unregistered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapUninstalledEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n };\n\n /**\n * Handle events that should cause cronjobs and background events to be\n * unregistered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapDisabledEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n };\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapUpdatedEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n this.register(snap.id);\n };\n\n /**\n * Reschedule events that are yet to be executed. This should be called on\n * controller initialization and once every 24 hours to ensure that\n * background events are scheduled correctly.\n *\n * @param events - An array of events to reschedule. Defaults to all events in\n * the controller state.\n */\n #reschedule(events = Object.values(this.state.events)) {\n const now = Date.now();\n\n for (const event of events) {\n if (this.#timers.has(event.id)) {\n // If the timer for this event already exists, we don't need to\n // reschedule it.\n continue;\n }\n\n const eventDate = DateTime.fromISO(event.date, {\n setZone: true,\n })\n .toUTC()\n .toMillis();\n\n // If the event is recurring and the date is in the past, execute it\n // immediately.\n if (event.recurring && eventDate <= now) {\n this.#execute(event);\n }\n\n this.#schedule(event);\n }\n }\n\n /**\n * Clear non-recurring events that are past their scheduled time.\n */\n #clear() {\n const now = Date.now();\n\n for (const event of Object.values(this.state.events)) {\n const eventDate = DateTime.fromISO(event.date, {\n setZone: true,\n })\n .toUTC()\n .toMillis();\n\n if (!event.recurring && eventDate < now) {\n this.#cancel(event.id);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CronjobController.mjs","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,EACL,oBAAoB,EACpB,cAAc,EACf,oCAAoC;AAGrC,OAAO,EACL,uBAAuB,EACvB,WAAW,EACX,QAAQ,EACT,8BAA8B;AAC/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AACnE,OAAO,EAAE,SAAS,EAAE,cAAc;AAClC,OAAO,EAAE,QAAQ,EAAE,cAAc;AACjC,OAAO,EAAE,MAAM,EAAE,eAAe;AAEhC,OAAO,EAAE,+BAA+B,EAAE,gBAAgB,EAAE,oBAAgB;AAS5E,OAAO,EAAE,eAAe,EAAE,+BAA2B;AACrD,OAAO,EAAE,KAAK,EAAE,2BAAuB;AA4DvC,MAAM,CA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AAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { BackgroundEvent, SnapId } from '@metamask/snaps-sdk';\nimport type { TruncatedSnap } from '@metamask/snaps-utils';\nimport {\n toCensoredISO8601String,\n HandlerType,\n logError,\n} from '@metamask/snaps-utils';\nimport { assert, Duration, inMilliseconds } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { DateTime } from 'luxon';\nimport { nanoid } from 'nanoid';\n\nimport { getCronjobSpecificationSchedule, getExecutionDate } from './utils';\nimport type {\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { METAMASK_ORIGIN } from '../snaps/constants';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n CronjobControllerState\n>;\nexport type CronjobControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n CronjobControllerState\n>;\n\n/**\n * Initialise the CronjobController. This should be called after all controllers\n * are created.\n */\nexport type CronjobControllerInitAction = {\n type: `${typeof controllerName}:init`;\n handler: CronjobController['init'];\n};\n\nexport type Schedule = {\n type: `${typeof controllerName}:schedule`;\n handler: CronjobController['schedule'];\n};\n\nexport type Cancel = {\n type: `${typeof controllerName}:cancel`;\n handler: CronjobController['cancel'];\n};\n\nexport type Get = {\n type: `${typeof controllerName}:get`;\n handler: CronjobController['get'];\n};\n\nexport type CronjobControllerActions =\n | CronjobControllerGetStateAction\n | HandleSnapRequest\n | GetPermissions\n | Schedule\n | Cancel\n | Get\n | CronjobControllerInitAction;\n\nexport type CronjobControllerEvents =\n | CronjobControllerStateChangeEvent\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\n/**\n * Represents a background event that is scheduled to be executed by the\n * cronjob controller.\n */\nexport type InternalBackgroundEvent = BackgroundEvent & {\n /**\n * Whether the event is recurring.\n */\n recurring: boolean;\n\n /**\n * The cron expression or ISO 8601 duration string that defines the event's\n * schedule.\n */\n schedule: string;\n};\n\n/**\n * A schedulable background event, which is a subset of the\n * {@link InternalBackgroundEvent} type, containing only the fields required to\n * schedule an event. Other fields will be populated by the cronjob controller\n * automatically.\n */\nexport type SchedulableBackgroundEvent = Omit<\n InternalBackgroundEvent,\n 'scheduledAt' | 'date' | 'id'\n> & {\n /**\n * The optional ID of the event. If not provided, a new ID will be\n * generated.\n */\n id?: string;\n};\n\nexport type CronjobControllerState = {\n /**\n * Background events and cronjobs that are scheduled to be executed.\n */\n events: Record<string, InternalBackgroundEvent>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * The cronjob controller is responsible for managing cronjobs and background\n * events for Snaps. It allows Snaps to schedule events that will be executed\n * at a later time.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n readonly #timers: Map<string, Timer>;\n\n #dailyTimer: Timer = new Timer(DAILY_TIMEOUT);\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n events: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n events: {},\n ...state,\n },\n });\n\n this.#timers = new Map();\n\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this.#handleSnapInstalledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this.#handleSnapUninstalledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this.#handleSnapEnabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this.#handleSnapDisabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this.#handleSnapUpdatedEvent,\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:init`,\n (...args) => this.init(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:schedule`,\n (...args) => this.schedule(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:cancel`,\n (...args) => this.cancel(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:get`,\n (...args) => this.get(...args),\n );\n }\n\n /**\n * Initialize the CronjobController.\n *\n * This starts the daily timer, clears out expired events\n * and reschedules any remaining events.\n */\n init() {\n this.#start();\n this.#clear();\n this.#reschedule();\n }\n\n /**\n * Schedule a non-recurring background event.\n *\n * @param event - The event to schedule.\n * @returns The ID of the scheduled event.\n */\n schedule(event: Omit<SchedulableBackgroundEvent, 'recurring'>) {\n return this.#add({\n ...event,\n recurring: false,\n });\n }\n\n /**\n * Cancel an event.\n *\n * @param origin - The origin making the cancel call.\n * @param id - The id of the event to cancel.\n * @throws If the event does not exist.\n */\n cancel(origin: string, id: string) {\n assert(\n this.state.events[id],\n `A background event with the id of \"${id}\" does not exist.`,\n );\n\n assert(\n this.state.events[id].snapId === origin,\n 'Only the origin that scheduled this event can cancel it.',\n );\n\n this.#cancel(id);\n }\n\n /**\n * Get a list of a Snap's background events.\n *\n * @param snapId - The id of the Snap to fetch background events for.\n * @returns An array of background events.\n */\n get(snapId: SnapId): InternalBackgroundEvent[] {\n return Object.values(this.state.events)\n .filter(\n (snapEvent) => snapEvent.snapId === snapId && !snapEvent.recurring,\n )\n .map((event) => ({\n ...event,\n date: toCensoredISO8601String(event.date),\n scheduledAt: toCensoredISO8601String(event.scheduledAt),\n }));\n }\n\n /**\n * Register cronjobs for a given Snap by getting specification from the\n * permission caveats. Once registered, each job will be scheduled.\n *\n * @param snapId - The snap ID to register jobs for.\n */\n register(snapId: SnapId) {\n const jobs = this.#getSnapCronjobs(snapId);\n jobs?.forEach((job) => this.#add(job));\n }\n\n /**\n * Unregister all cronjobs and background events for a given Snap.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n for (const [id, event] of Object.entries(this.state.events)) {\n if (event.snapId === snapId) {\n this.#cancel(id);\n }\n }\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this.#handleSnapInstalledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this.#handleSnapUninstalledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this.#handleSnapEnabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this.#handleSnapDisabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this.#handleSnapUpdatedEvent,\n );\n\n // Cancel all timers and clear the map.\n this.#timers.forEach((timer) => timer.cancel());\n this.#timers.clear();\n\n if (this.#dailyTimer.status === 'running') {\n this.#dailyTimer.cancel();\n }\n }\n\n /**\n * Start the daily timer that will reschedule events every 24 hours.\n */\n #start() {\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.#reschedule();\n this.#start();\n });\n }\n\n /**\n * Add a cronjob or background event to the controller state and schedule it\n * for execution.\n *\n * @param event - The event to schedule.\n * @returns The ID of the scheduled event.\n */\n #add(event: SchedulableBackgroundEvent) {\n const id = event.id ?? nanoid();\n const internalEvent: InternalBackgroundEvent = {\n ...event,\n id,\n date: getExecutionDate(event.schedule),\n scheduledAt: new Date().toISOString(),\n };\n\n this.update((state) => {\n state.events[internalEvent.id] = castDraft(internalEvent);\n });\n\n this.#schedule(internalEvent);\n return id;\n }\n\n /**\n * Get the next execution date for a given event and start a timer for it.\n *\n * @param event - The event to schedule.\n */\n #schedule(event: InternalBackgroundEvent) {\n const date = getExecutionDate(event.schedule);\n this.update((state) => {\n state.events[event.id].date = date;\n });\n\n this.#startTimer({\n ...event,\n date,\n });\n }\n\n /**\n * Set up and start a timer for the given event.\n *\n * @param event - The event to schedule.\n * @throws If the event is scheduled in the past.\n */\n #startTimer(event: InternalBackgroundEvent) {\n const ms =\n DateTime.fromISO(event.date, { setZone: true }).toMillis() - Date.now();\n\n // We don't schedule this job yet as it is too far in the future.\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n // When an event is supposed to be scheduled close to the current time\n // we may end up needing to execute immediately instead.\n if (ms <= 0) {\n this.#execute(event);\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.#execute(event);\n });\n\n this.#timers.set(event.id, timer);\n }\n\n /**\n * Execute a background event. This method is called when the event's timer\n * expires.\n *\n * If the event is not recurring, it will be removed from the state after\n * execution. If it is recurring, it will be rescheduled.\n *\n * @param event - The event to execute.\n */\n #execute(event: InternalBackgroundEvent) {\n this.messagingSystem\n .call('SnapController:handleRequest', {\n snapId: event.snapId,\n origin: METAMASK_ORIGIN,\n handler: HandlerType.OnCronjob,\n request: event.request,\n })\n .catch((error) => {\n logError(\n `An error occurred while executing an event for Snap \"${event.snapId}\":`,\n error,\n );\n });\n\n this.#timers.delete(event.id);\n\n // Non-recurring events are removed from the state after execution, and\n // recurring events are rescheduled.\n if (!event.recurring) {\n this.update((state) => {\n delete state.events[event.id];\n });\n\n return;\n }\n\n this.#schedule(event);\n }\n\n /**\n * Cancel a background event by its ID. Unlike {@link cancel}, this method\n * does not check the origin of the event, so it can be used internally.\n *\n * @param id - The ID of the background event to cancel.\n */\n #cancel(id: string) {\n const timer = this.#timers.get(id);\n timer?.cancel();\n this.#timers.delete(id);\n\n this.update((state) => {\n delete state.events[id];\n });\n }\n\n /**\n * Retrieve all cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of cronjob specifications.\n */\n #getSnapCronjobs(snapId: SnapId): SchedulableBackgroundEvent[] {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n if (!definitions) {\n return [];\n }\n\n return definitions.map((definition, idx) => {\n return {\n snapId,\n id: `cronjob-${snapId}-${idx}`,\n request: definition.request,\n schedule: getCronjobSpecificationSchedule(definition),\n recurring: true,\n };\n });\n }\n\n /**\n * Handle events that should cause cron jobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapInstalledEvent = (snap: TruncatedSnap) => {\n // In case of local Snaps, they may already have cronjobs that should be cleared.\n this.unregister(snap.id);\n this.register(snap.id);\n };\n\n /**\n * Handle the Snap enabled event. This checks if the Snap has any cronjobs or\n * background events that need to be rescheduled.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapEnabledEvent = (snap: TruncatedSnap) => {\n const events = this.get(snap.id);\n this.#reschedule(events);\n this.register(snap.id);\n };\n\n /**\n * Handle events that should cause cronjobs and background events to be\n * unregistered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapUninstalledEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n };\n\n /**\n * Handle events that should cause cronjobs and background events to be\n * unregistered.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapDisabledEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n };\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n readonly #handleSnapUpdatedEvent = (snap: TruncatedSnap) => {\n this.unregister(snap.id);\n this.register(snap.id);\n };\n\n /**\n * Reschedule events that are yet to be executed. This should be called on\n * controller initialization and once every 24 hours to ensure that\n * background events are scheduled correctly.\n *\n * @param events - An array of events to reschedule. Defaults to all events in\n * the controller state.\n */\n #reschedule(events = Object.values(this.state.events)) {\n const now = Date.now();\n\n for (const event of events) {\n if (this.#timers.has(event.id)) {\n // If the timer for this event already exists, we don't need to\n // reschedule it.\n continue;\n }\n\n const eventDate = DateTime.fromISO(event.date, {\n setZone: true,\n })\n .toUTC()\n .toMillis();\n\n // If the event is recurring and the date is in the past, execute it\n // immediately.\n if (event.recurring && eventDate <= now) {\n this.#execute(event);\n }\n\n this.#schedule(event);\n }\n }\n\n /**\n * Clear non-recurring events that are past their scheduled time.\n */\n #clear() {\n const now = Date.now();\n\n for (const event of Object.values(this.state.events)) {\n const eventDate = DateTime.fromISO(event.date, {\n setZone: true,\n })\n .toUTC()\n .toMillis();\n\n if (!event.recurring && eventDate < now) {\n this.#cancel(event.id);\n }\n }\n }\n}\n"]}
|
|
@@ -20,6 +20,7 @@ class AbstractExecutionService {
|
|
|
20
20
|
name = controllerName;
|
|
21
21
|
state = null;
|
|
22
22
|
#jobs;
|
|
23
|
+
#status;
|
|
23
24
|
#setupSnapProvider;
|
|
24
25
|
#messenger;
|
|
25
26
|
#initTimeout;
|
|
@@ -28,6 +29,7 @@ class AbstractExecutionService {
|
|
|
28
29
|
#usePing;
|
|
29
30
|
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, }) {
|
|
30
31
|
this.#jobs = new Map();
|
|
32
|
+
this.#status = new Map();
|
|
31
33
|
this.#setupSnapProvider = setupSnapProvider;
|
|
32
34
|
this.#messenger = messenger;
|
|
33
35
|
this.#initTimeout = initTimeout;
|
|
@@ -90,6 +92,7 @@ class AbstractExecutionService {
|
|
|
90
92
|
});
|
|
91
93
|
this.terminateJob(job);
|
|
92
94
|
this.#jobs.delete(snapId);
|
|
95
|
+
this.#status.delete(snapId);
|
|
93
96
|
(0, logging_1.log)(`Snap "${snapId}" terminated.`);
|
|
94
97
|
}
|
|
95
98
|
/**
|
|
@@ -132,7 +135,12 @@ class AbstractExecutionService {
|
|
|
132
135
|
if (result === utils_2.hasTimedOut) {
|
|
133
136
|
// For certain environments, such as the iframe we may have already created the worker and wish to terminate it.
|
|
134
137
|
this.terminateJob({ id: snapId });
|
|
135
|
-
|
|
138
|
+
const status = this.#status.get(snapId);
|
|
139
|
+
if (status === 'created') {
|
|
140
|
+
// Currently this error can only be thrown by OffscreenExecutionService.
|
|
141
|
+
throw new Error(`The executor for "${snapId}" couldn't start initialization. The offscreen document may not exist.`);
|
|
142
|
+
}
|
|
143
|
+
throw new Error(`The executor for "${snapId}" failed to initialize. The iframe/webview/worker failed to load.`);
|
|
136
144
|
}
|
|
137
145
|
const { worker, stream: envStream } = result;
|
|
138
146
|
const mux = setupMultiplex(envStream, `Snap: "${snapId}"`);
|
|
@@ -170,6 +178,15 @@ class AbstractExecutionService {
|
|
|
170
178
|
worker,
|
|
171
179
|
};
|
|
172
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Set the execution status of the Snap.
|
|
183
|
+
*
|
|
184
|
+
* @param snapId - The Snap ID.
|
|
185
|
+
* @param status - The current execution status.
|
|
186
|
+
*/
|
|
187
|
+
setSnapStatus(snapId, status) {
|
|
188
|
+
this.#status.set(snapId, status);
|
|
189
|
+
}
|
|
173
190
|
async terminateAllSnaps() {
|
|
174
191
|
await Promise.all([...this.#jobs.keys()].map(async (snapId) => this.terminateSnap(snapId)));
|
|
175
192
|
}
|
|
@@ -187,6 +204,7 @@ class AbstractExecutionService {
|
|
|
187
204
|
if (this.#jobs.has(snapId)) {
|
|
188
205
|
throw new Error(`"${snapId}" is already running.`);
|
|
189
206
|
}
|
|
207
|
+
this.setSnapStatus(snapId, 'created');
|
|
190
208
|
const timer = new Timer_1.Timer(this.#initTimeout);
|
|
191
209
|
// This may resolve even if the environment has failed to start up fully
|
|
192
210
|
const job = await this.#initJob(snapId, timer);
|
|
@@ -199,12 +217,15 @@ class AbstractExecutionService {
|
|
|
199
217
|
id: (0, nanoid_1.nanoid)(),
|
|
200
218
|
}), this.#pingTimeout);
|
|
201
219
|
if (pingResult === utils_2.hasTimedOut) {
|
|
202
|
-
throw new Error(
|
|
220
|
+
throw new Error(`The executor for "${snapId}" was unreachable. The executor did not respond in time.`);
|
|
203
221
|
}
|
|
204
222
|
}
|
|
205
223
|
const rpcStream = job.streams.rpc;
|
|
206
224
|
this.#setupSnapProvider(snapId, rpcStream);
|
|
207
|
-
|
|
225
|
+
// Use the remaining time as the timer, but ensure that the
|
|
226
|
+
// Snap gets at least half the init timeout.
|
|
227
|
+
const remainingTime = Math.max(timer.remaining, this.#initTimeout / 2);
|
|
228
|
+
this.setSnapStatus(snapId, 'initialized');
|
|
208
229
|
const request = {
|
|
209
230
|
jsonrpc: '2.0',
|
|
210
231
|
method: 'executeSnap',
|
|
@@ -212,10 +233,14 @@ class AbstractExecutionService {
|
|
|
212
233
|
id: (0, nanoid_1.nanoid)(),
|
|
213
234
|
};
|
|
214
235
|
(0, utils_1.assertIsJsonRpcRequest)(request);
|
|
236
|
+
this.setSnapStatus(snapId, 'executing');
|
|
215
237
|
const result = await (0, utils_2.withTimeout)(this.#command(job.id, request), remainingTime);
|
|
216
238
|
if (result === utils_2.hasTimedOut) {
|
|
217
239
|
throw new Error(`${snapId} failed to start.`);
|
|
218
240
|
}
|
|
241
|
+
if (result === 'OK') {
|
|
242
|
+
this.setSnapStatus(snapId, 'running');
|
|
243
|
+
}
|
|
219
244
|
return result;
|
|
220
245
|
}
|
|
221
246
|
async #command(snapId, message) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractExecutionService.cjs","sourceRoot":"","sources":["../../src/services/AbstractExecutionService.ts"],"names":[],"mappings":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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/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;AA4C1C,MAAsB,wBAAwB;IAG5C,IAAI,GAA0B,cAAc,CAAC;IAE7C,KAAK,GAAG,IAAI,CAAC;IAEJ,KAAK,CAA+B;IAEpC,OAAO,CAA+B;IAEtC,kBAAkB,CAAoB;IAEtC,UAAU,CAA4B;IAEtC,YAAY,CAAS;IA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AAc,EACd,OAAwB;QAExB,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QAE7C,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE;YACjC,EAAE,EAAE,IAAA,eAAM,GAAE;YACZ,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,SAAS;YACjB,MAAM,EAAE;gBACN,MAAM;gBACN,OAAO;gBACP,OAAO,EAAE,OAAyB;gBAClC,MAAM,EAAE,MAAM;aACf;SACF,CAAC,CAAC;IACL,CAAC;CACF;AAvZD,4DAuZC;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,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\n/** \n Statuses used for diagnostic purposes\n - created: The initial state, no initialization has started \n - initializing: Snap execution environment is initializing\n - initialized: Snap execution environment has initialized\n - executing: Snap source code is being executed\n - running: Snap executed and ready for RPC requests\n */\ntype ExecutionStatus =\n | 'created'\n | 'initializing'\n | 'initialized'\n | 'executing'\n | 'running';\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 #status: Map<string, ExecutionStatus>;\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.#status = 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 this.#status.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\n const status = this.#status.get(snapId);\n if (status === 'created') {\n // Currently this error can only be thrown by OffscreenExecutionService.\n throw new Error(\n `The executor for \"${snapId}\" couldn't start initialization. The offscreen document may not exist.`,\n );\n }\n throw new Error(\n `The executor for \"${snapId}\" failed to initialize. The iframe/webview/worker failed to load.`,\n );\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 /**\n * Set the execution status of the Snap.\n *\n * @param snapId - The Snap ID.\n * @param status - The current execution status.\n */\n protected setSnapStatus(snapId: string, status: ExecutionStatus) {\n this.#status.set(snapId, status);\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 this.setSnapStatus(snapId, 'created');\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(\n `The executor for \"${snapId}\" was unreachable. The executor did not respond in time.`,\n );\n }\n }\n\n const rpcStream = job.streams.rpc;\n\n this.#setupSnapProvider(snapId, rpcStream);\n\n // Use the remaining time as the timer, but ensure that the\n // Snap gets at least half the init timeout.\n const remainingTime = Math.max(timer.remaining, this.#initTimeout / 2);\n\n this.setSnapStatus(snapId, 'initialized');\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 this.setSnapStatus(snapId, 'executing');\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 if (result === 'OK') {\n this.setSnapStatus(snapId, 'running');\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"]}
|
|
@@ -26,6 +26,15 @@ export type Job<WorkerType> = {
|
|
|
26
26
|
worker: WorkerType;
|
|
27
27
|
};
|
|
28
28
|
export type TerminateJobArgs<WorkerType> = Partial<Job<WorkerType>> & Pick<Job<WorkerType>, 'id'>;
|
|
29
|
+
/**
|
|
30
|
+
Statuses used for diagnostic purposes
|
|
31
|
+
- created: The initial state, no initialization has started
|
|
32
|
+
- initializing: Snap execution environment is initializing
|
|
33
|
+
- initialized: Snap execution environment has initialized
|
|
34
|
+
- executing: Snap source code is being executed
|
|
35
|
+
- running: Snap executed and ready for RPC requests
|
|
36
|
+
*/
|
|
37
|
+
type ExecutionStatus = 'created' | 'initializing' | 'initialized' | 'executing' | 'running';
|
|
29
38
|
export declare abstract class AbstractExecutionService<WorkerType> implements ExecutionService {
|
|
30
39
|
#private;
|
|
31
40
|
name: typeof controllerName;
|
|
@@ -57,6 +66,13 @@ export declare abstract class AbstractExecutionService<WorkerType> implements Ex
|
|
|
57
66
|
worker: WorkerType;
|
|
58
67
|
stream: BasePostMessageStream;
|
|
59
68
|
}>;
|
|
69
|
+
/**
|
|
70
|
+
* Set the execution status of the Snap.
|
|
71
|
+
*
|
|
72
|
+
* @param snapId - The Snap ID.
|
|
73
|
+
* @param status - The current execution status.
|
|
74
|
+
*/
|
|
75
|
+
protected setSnapStatus(snapId: string, status: ExecutionStatus): void;
|
|
60
76
|
terminateAllSnaps(): Promise<void>;
|
|
61
77
|
/**
|
|
62
78
|
* Initializes and executes a Snap, setting up the communication channels to the Snap etc.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractExecutionService.d.cts","sourceRoot":"","sources":["../../src/services/AbstractExecutionService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,kCAAkC;AAE1D,OAAO,eAAe,mCAAmC;AACzD,OAAO,KAAK,EAAE,qBAAqB,EAAE,sCAAsC;AAE3E,OAAO,KAAK,EAAE,eAAe,EAAE,8BAA8B;AAgB7D,OAAO,KAAK,EAAE,MAAM,EAAE,wBAAwB;AAE9C,OAAO,KAAK,EACV,gBAAgB,EAChB,yBAAyB,EAEzB,iBAAiB,EAClB,+BAA2B;AAK5B,QAAA,MAAM,cAAc,qBAAqB,CAAC;AAE1C,MAAM,MAAM,iBAAiB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;AAEzE,MAAM,MAAM,oBAAoB,GAAG;IACjC,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,SAAS,EAAE,yBAAyB,CAAC;IACrC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B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OAAO,CAAC;QACxD,MAAM,EAAE,UAAU,CAAC;QACnB,MAAM,EAAE,qBAAqB,CAAC;KAC/B,CAAC;IAEF;;;;;OAKG;IACH,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe;IAIzD,iBAAiB;IAMvB;;;;;;;;;OASG;IACG,WAAW,CAAC,EAChB,MAAM,EACN,UAAU,EACV,UAAU,GACX,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC;IA2FtC;;;;;;OAMG;IACU,gBAAgB,CAC3B,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,OAAO,CAAC;CAepB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,gBAAgB,EAAE,MAAM,EACxB,UAAU,EAAE,MAAM,GACjB,eAAe,CAQjB"}
|
|
@@ -26,6 +26,15 @@ export type Job<WorkerType> = {
|
|
|
26
26
|
worker: WorkerType;
|
|
27
27
|
};
|
|
28
28
|
export type TerminateJobArgs<WorkerType> = Partial<Job<WorkerType>> & Pick<Job<WorkerType>, 'id'>;
|
|
29
|
+
/**
|
|
30
|
+
Statuses used for diagnostic purposes
|
|
31
|
+
- created: The initial state, no initialization has started
|
|
32
|
+
- initializing: Snap execution environment is initializing
|
|
33
|
+
- initialized: Snap execution environment has initialized
|
|
34
|
+
- executing: Snap source code is being executed
|
|
35
|
+
- running: Snap executed and ready for RPC requests
|
|
36
|
+
*/
|
|
37
|
+
type ExecutionStatus = 'created' | 'initializing' | 'initialized' | 'executing' | 'running';
|
|
29
38
|
export declare abstract class AbstractExecutionService<WorkerType> implements ExecutionService {
|
|
30
39
|
#private;
|
|
31
40
|
name: typeof controllerName;
|
|
@@ -57,6 +66,13 @@ export declare abstract class AbstractExecutionService<WorkerType> implements Ex
|
|
|
57
66
|
worker: WorkerType;
|
|
58
67
|
stream: BasePostMessageStream;
|
|
59
68
|
}>;
|
|
69
|
+
/**
|
|
70
|
+
* Set the execution status of the Snap.
|
|
71
|
+
*
|
|
72
|
+
* @param snapId - The Snap ID.
|
|
73
|
+
* @param status - The current execution status.
|
|
74
|
+
*/
|
|
75
|
+
protected setSnapStatus(snapId: string, status: ExecutionStatus): void;
|
|
60
76
|
terminateAllSnaps(): Promise<void>;
|
|
61
77
|
/**
|
|
62
78
|
* Initializes and executes a Snap, setting up the communication channels to the Snap etc.
|