-
Notifications
You must be signed in to change notification settings - Fork 542
/
CronjobController.ts
316 lines (278 loc) · 7.52 KB
/
CronjobController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import {
BaseControllerV2 as BaseController,
RestrictedControllerMessenger,
HasPermission,
GetPermissions,
} from '@metamask/controllers';
import { HandlerType, SnapId, TruncatedSnap } from '@metamask/snap-utils';
import { parseExpression } from 'cron-parser';
import { nanoid } from 'nanoid';
import {
GetSnap,
HandleSnapRequest,
SnapAdded,
SnapBlocked,
SnapEndowments,
SnapInstalled,
SnapRemoved,
SnapTerminated,
SnapUnblocked,
SnapUpdated,
} from '..';
import { Timer } from '../snaps/Timer';
export type CronjobControllerActions =
| GetSnap
| HandleSnapRequest
| HasPermission
| GetPermissions;
export type CronjobControllerEvents =
| SnapAdded
| SnapBlocked
| SnapInstalled
| SnapRemoved
| SnapUnblocked
| SnapUpdated
| SnapTerminated;
export type CronjobControllerMessenger = RestrictedControllerMessenger<
'CronjobController',
CronjobControllerActions,
CronjobControllerEvents,
CronjobControllerActions['type'],
CronjobControllerEvents['type']
>;
export type CronjobControllerArgs = {
messenger: CronjobControllerMessenger;
};
export type CronjobDefinition = {
expression: string;
request: {
method: string;
params: string[] | number[] | boolean[];
};
};
export type Cronjob = {
timer?: Timer;
id: string;
} & CronjobDefinition;
export type StoredJobInformation = {
lastRun: number;
};
export type CronjobControllerState = {
snaps: Record<SnapId, string[]>;
jobs: Record<string, StoredJobInformation>;
};
const controllerName = 'CronjobController';
/**
* Use this controller to register and schedule periodically executed jobs
* using RPC method hooks.
*/
export class CronjobController extends BaseController<
typeof controllerName,
CronjobControllerState,
CronjobControllerMessenger
> {
private _messenger: CronjobControllerMessenger;
private _jobs: Map<string, Cronjob>;
constructor({ messenger }: CronjobControllerArgs) {
super({
messenger,
metadata: {
snaps: { persist: true, anonymous: false },
jobs: { persist: true, anonymous: false },
},
name: controllerName,
state: {
snaps: {},
jobs: {},
},
});
this._jobs = new Map();
this._messenger = messenger;
this.initializeJobSchedule();
this._handleEventSnapInstalled = this._handleEventSnapInstalled.bind(this);
this._handleEventSnapRemoved = this._handleEventSnapRemoved.bind(this);
this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);
// Subscribe to Snap events
this.messagingSystem.subscribe(
'SnapController:snapInstalled',
this._handleEventSnapInstalled,
);
this.messagingSystem.subscribe(
'SnapController:snapRemoved',
this._handleEventSnapRemoved,
);
this.messagingSystem.subscribe(
'SnapController:snapInstalled',
this._handleEventSnapUpdated,
);
}
/**
* Register cron jobs for a given snap by getting specification from a permission caveats.
* Once registered, each job will be scheduled.
*
* @param snapId - ID of a snap.
*/
async register(snapId: SnapId) {
const hasCronjob = await this._messenger.call(
'PermissionController:hasPermission',
snapId,
SnapEndowments.cronjob,
);
if (!hasCronjob) {
return;
}
const permissions = await this._messenger.call(
'PermissionController:getPermissions',
snapId,
);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const cronjobPermission = permissions![SnapEndowments.cronjob]!;
const { caveats } = cronjobPermission;
if (!caveats) {
return;
}
const definitions: CronjobDefinition[] = caveats[0].value;
const jobs = definitions?.map((definition) => {
const id = nanoid();
return { ...definition, id };
});
this.update((state) => {
state.snaps[snapId] = jobs?.map((job) => job.id);
});
jobs.forEach((job) => this.schedule(snapId, job));
}
/**
* Schedule job.
*
* @param snapId - ID of a snap.
* @param job - Cronjob specification.
*/
schedule(snapId: SnapId, job: Cronjob) {
const parsed = parseExpression(job.expression);
if (!parsed.hasNext()) {
return;
}
const next = parsed.next();
const now = new Date();
const ms = next.getTime() - now.getTime();
const timer = new Timer(ms);
timer.start(() => {
this.updateJobLastRunState(job.id, next.getTime());
this._messenger.call('SnapController:handleRequest', {
snapId,
// @todo Decide on origin for requests like this
origin: 'METAMASK',
handler: HandlerType.OnCronjob,
request: job.request,
});
this.schedule(snapId, job);
});
this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually
this._jobs.set(job.id, { ...job, timer });
}
/**
* Unregister all jobs related to the given snapId.
*
* @param snapId - ID of a snap.
*/
unregister(snapId: SnapId) {
const jobs = this.state.snaps[snapId];
jobs?.forEach((id) => {
const job = this._jobs.get(id);
job?.timer?.cancel();
this._jobs.delete(job?.id as string);
});
this.update((state) => {
delete state.snaps[snapId];
});
}
/**
* Update time of a last run for the Cronjob specified by ID.
*
* @param jobId - ID of a cron job.
* @param lastRun - Unix timestamp when the job was last ran.
*/
updateJobLastRunState(jobId: string, lastRun: number) {
this.update((state) => {
state.jobs[jobId] = {
lastRun,
};
});
}
/**
* Retrieve job specification by given job ID.
*
* @param jobId - ID of a job.
* @returns Job specification.
*/
getJob(jobId: string): Cronjob | undefined {
return this._jobs.get(jobId);
}
/**
* Retrieve job specification from state by given job ID.
*
* @param jobId - ID of a job.
* @returns Plain job specification.
*/
getJobInfoFromState(jobId: string): StoredJobInformation {
return this.state.jobs[jobId];
}
/**
* Retrieve an array of job ID registered for a given snap identified by ID.
*
* @param snapId - ID of a snap.
* @returns All registered job ID for single snap.
*/
getRegisteredJobs(snapId: string): string[] {
return this.state.snaps[snapId] ? this.state.snaps[snapId] : [];
}
/**
* Initialize (schedule) jobs when controller starts.
*/
initializeJobSchedule() {
// TODO: Do some init actions after restart?
}
/**
* Run controller teardown process and unsubscribe from everything.
*/
protected destroy() {
super.destroy();
this.messagingSystem.unsubscribe(
'SnapController:snapInstalled',
this._handleEventSnapInstalled,
);
this.messagingSystem.unsubscribe(
'SnapController:snapRemoved',
this._handleEventSnapRemoved,
);
this.messagingSystem.unsubscribe(
'SnapController:snapUpdated',
this._handleEventSnapUpdated,
);
}
/**
* Handle cron jobs on 'snapInstalled' event.
*
* @param snap - Basic Snap information.
*/
async _handleEventSnapInstalled(snap: TruncatedSnap) {
await this.register(snap.id);
}
/**
* Handle cron jobs on 'snapRemoved' event.
*
* @param snap - Basic Snap information.
*/
_handleEventSnapRemoved(snap: TruncatedSnap) {
this.unregister(snap.id);
}
/**
* Handle cron jobs on 'snapUpdated' event.
*
* @param snap - Basic Snap information.
*/
async _handleEventSnapUpdated(snap: TruncatedSnap) {
this.unregister(snap.id);
await this.register(snap.id);
}
}