@webda/async 4.0.0-beta.1 → 4.0.0-beta.10

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.
Files changed (41) hide show
  1. package/README.md +92 -8
  2. package/lib/{models.d.ts → asyncaction.model.d.ts} +76 -42
  3. package/lib/asyncaction.model.d.ts.map +1 -0
  4. package/lib/asyncaction.model.js +269 -0
  5. package/lib/asyncaction.model.js.map +1 -0
  6. package/lib/index.d.ts +7 -4
  7. package/lib/index.d.ts.map +1 -0
  8. package/lib/index.js +6 -4
  9. package/lib/index.js.map +1 -1
  10. package/lib/services/asyncevents.service.d.ts +154 -0
  11. package/lib/services/asyncevents.service.d.ts.map +1 -0
  12. package/lib/services/asyncevents.service.js +219 -0
  13. package/lib/services/asyncevents.service.js.map +1 -0
  14. package/lib/services/{asyncjobservice.d.ts → asyncjobservice.service.d.ts} +79 -74
  15. package/lib/services/asyncjobservice.service.d.ts.map +1 -0
  16. package/lib/services/asyncjobservice.service.js +596 -0
  17. package/lib/services/asyncjobservice.service.js.map +1 -0
  18. package/lib/services/{localrunner.d.ts → localrunner.service.d.ts} +24 -9
  19. package/lib/services/localrunner.service.d.ts.map +1 -0
  20. package/lib/services/localrunner.service.js +87 -0
  21. package/lib/services/localrunner.service.js.map +1 -0
  22. package/lib/services/{runner.d.ts → runner.service.d.ts} +17 -11
  23. package/lib/services/runner.service.d.ts.map +1 -0
  24. package/lib/services/{runner.js → runner.service.js} +16 -13
  25. package/lib/services/runner.service.js.map +1 -0
  26. package/lib/services/servicerunner.service.d.ts +105 -0
  27. package/lib/services/servicerunner.service.d.ts.map +1 -0
  28. package/lib/services/servicerunner.service.js +131 -0
  29. package/lib/services/servicerunner.service.js.map +1 -0
  30. package/package.json +35 -38
  31. package/webda.module.json +1898 -858
  32. package/lib/models.js +0 -177
  33. package/lib/models.js.map +0 -1
  34. package/lib/services/asyncjobservice.js +0 -505
  35. package/lib/services/asyncjobservice.js.map +0 -1
  36. package/lib/services/localrunner.js +0 -70
  37. package/lib/services/localrunner.js.map +0 -1
  38. package/lib/services/runner.js.map +0 -1
  39. package/lib/services/servicerunner.d.ts +0 -67
  40. package/lib/services/servicerunner.js +0 -97
  41. package/lib/services/servicerunner.js.map +0 -1
@@ -0,0 +1,596 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
35
+ import { canCallOperation, Command, CronService, listFullOperations, registerOperation, registerSchema, Service, ServiceParameters, SimpleOperationContext, useApplication, useCore, useDynamicService, useModel, useParameters, validateSchema, ValidationError, WebdaError } from "@webda/core";
36
+ import { CancelableLoopPromise, CancelablePromise, FileUtils, getUuid, JSONUtils, sleep } from "@webda/utils";
37
+ import axios from "axios";
38
+ import * as crypto from "node:crypto";
39
+ import { schedule as crontabSchedule } from "node-cron";
40
+ import { Runner } from "./runner.service.js";
41
+ import { ServiceRunner, ServiceRunnerParameters } from "./servicerunner.service.js";
42
+ /**
43
+ * @inheritdoc
44
+ */
45
+ export class AsyncJobServiceParameters extends ServiceParameters {
46
+ /**
47
+ * @override
48
+ * @param params - the input parameters
49
+ * @returns this
50
+ */
51
+ load(params = {}) {
52
+ super.load(params);
53
+ this.url ?? (this.url = "/async");
54
+ this.queue ?? (this.queue = "AsyncActionsQueue");
55
+ this.runners ?? (this.runners = []);
56
+ this.schedulerResolution ?? (this.schedulerResolution = 60000);
57
+ this.onlyHttpHook ?? (this.onlyHttpHook = false);
58
+ this.includeCron ?? (this.includeCron = true);
59
+ this.logsLimit ?? (this.logsLimit = 500);
60
+ this.asyncActionModel ?? (this.asyncActionModel = "Webda/AsyncWebdaAction");
61
+ this.asyncOperationModel ?? (this.asyncOperationModel = "Webda/AsyncOperationAction");
62
+ return this;
63
+ }
64
+ }
65
+ let AsyncJobService = (() => {
66
+ var _a;
67
+ let _classSuper = Service;
68
+ let _instanceExtraInitializers = [];
69
+ let _worker_decorators;
70
+ let _runAction_decorators;
71
+ let _scheduler_decorators;
72
+ return _a = class AsyncJobService extends _classSuper {
73
+ constructor() {
74
+ super(...arguments);
75
+ /**
76
+ * Queue for execution
77
+ */
78
+ this.queue = __runInitializers(this, _instanceExtraInitializers);
79
+ /**
80
+ * Validator of sessions
81
+ */
82
+ this.operationsQueries = {};
83
+ }
84
+ /**
85
+ * @inheritdoc
86
+ * @returns this
87
+ */
88
+ resolve() {
89
+ super.resolve();
90
+ this.model = useModel(this.parameters.asyncActionModel);
91
+ this.queue = this.parameters.queue ? useDynamicService(this.parameters.queue) : undefined;
92
+ if (!this.queue && !this.parameters.localLaunch) {
93
+ throw new Error(`AsyncService requires a valid queue. '${this.parameters.queue}' is invalid`);
94
+ }
95
+ // Get all runners
96
+ this.runners = this.parameters.runners
97
+ .map(n => {
98
+ const res = useDynamicService(n);
99
+ if (res === undefined) {
100
+ this.log("WARN", `Runner ${n} does not exist`);
101
+ }
102
+ return res;
103
+ })
104
+ .filter(r => r !== undefined);
105
+ // Add route for operations launch
106
+ if (this.parameters.asyncOperationDefinition) {
107
+ this.log("INFO", "Loading operations", this.parameters.asyncOperationDefinition);
108
+ this.addRoute(`${this.parameters.url}{?full}`, ["GET"], this.listOperations);
109
+ this.addRoute(`${this.parameters.url}/{operationId}{?schedule}`, ["PUT"], this.launchOperation);
110
+ this.operationModel = useModel(this.parameters.asyncOperationModel);
111
+ this.registerOperations(FileUtils.load(this.parameters.asyncOperationDefinition));
112
+ }
113
+ // This is internal job reporting so no need to document the api
114
+ this.addRoute(`${this.parameters.url}/status`, ["POST"], this.statusHook, {
115
+ hidden: true
116
+ });
117
+ return this;
118
+ }
119
+ /**
120
+ * Register new operations
121
+ * @param operations - the operations definition
122
+ */
123
+ registerOperations(operations) {
124
+ this.operations ?? (this.operations = {
125
+ application: operations.application || { name: "Unknown", version: "0.0.0" },
126
+ operations: {},
127
+ schemas: {}
128
+ });
129
+ // Register all schemas
130
+ const app = useApplication();
131
+ Object.keys(operations?.schemas || {})
132
+ .filter(key => !app.getSchema(key))
133
+ .forEach(key => {
134
+ app.getSchemas()[key] = operations.schemas[key];
135
+ registerSchema(key, operations.schemas[key]);
136
+ this.operations.schemas[key] = operations.schemas[key];
137
+ });
138
+ // Register all operations now
139
+ Object.keys(operations?.operations || {}).forEach(key => {
140
+ registerOperation(key, {
141
+ ...operations.operations[key],
142
+ method: "callOperation",
143
+ service: this.getName()
144
+ });
145
+ this.operations.operations[key] = operations.operations[key];
146
+ });
147
+ }
148
+ /**
149
+ * Allow job status report url
150
+ * @param context - the web context
151
+ * @returns true if the request is a job status report
152
+ */
153
+ async checkRequest(context) {
154
+ const url = context.getHttpContext().getRelativeUri();
155
+ // Only for status endpoint - operations endpoint should still be authorized by something else
156
+ if (url === `${this.parameters.url}/status`) {
157
+ // Allow status url to be called without other mechanism
158
+ const httpContext = context.getHttpContext();
159
+ return ["X-Job-Id", "X-Job-Time", "X-Job-Hash"].every(v => httpContext.getUniqueHeader(v) !== undefined);
160
+ }
161
+ return false;
162
+ }
163
+ /**
164
+ * Status hook for job report
165
+ *
166
+ * Only updates specific fields: status, errorMessage, statusDetails, results, logs (appending)
167
+ * @param context - the web context
168
+ */
169
+ async statusHook(context) {
170
+ if (!context.getHttpContext().getUniqueHeader("X-Job-Id")) {
171
+ throw new WebdaError.NotFound("X-Job-Id header required");
172
+ }
173
+ const jobId = context.getHttpContext().getUniqueHeader("X-Job-Id");
174
+ if (!(await this.model.ref(jobId).exists())) {
175
+ throw new WebdaError.NotFound(`Unknown Job Id '${jobId}'`);
176
+ }
177
+ const action = await this.model.ref(jobId).get();
178
+ await action.statusAction(context);
179
+ }
180
+ /**
181
+ * Worker
182
+ *
183
+ * This will launch actions based on defined runners
184
+ * @returns a cancelable promise
185
+ */
186
+ worker() {
187
+ if (this.runners.length === 0) {
188
+ throw new Error(`AsyncJobService.worker requires runners`);
189
+ }
190
+ const p = [this.queue.consume(this.handleEvent.bind(this))];
191
+ if (this.parameters.includeSchedulerInWorker) {
192
+ p.push(this.scheduler());
193
+ }
194
+ // Return a cancelable promise for both worker and scheduler
195
+ return new CancelablePromise((resolve, reject) => {
196
+ Promise.all(p).then(() => resolve(), reject);
197
+ }, async () => {
198
+ this.log("INFO", "Worker stopped");
199
+ await Promise.all(p.map(pi => (pi.cancel ? pi.cancel() : "")));
200
+ });
201
+ }
202
+ /**
203
+ * Handle one event from the queue and launch the job
204
+ * @param event - the queue item
205
+ * @returns the job promise if any
206
+ */
207
+ async handleEvent(event) {
208
+ // Acknowledge events of deleted actions, throwing would leave the message in the queue forever
209
+ if (!(await this.model.ref(event.uuid).exists())) {
210
+ this.log("ERROR", `Action ${event.uuid} not found, skipping event`);
211
+ return;
212
+ }
213
+ let selectedRunner;
214
+ // Take first to acknowledge the job
215
+ for (const runner of this.runners) {
216
+ if (runner.handleType(event.type)) {
217
+ selectedRunner = runner;
218
+ break;
219
+ }
220
+ }
221
+ // Fallback if needed
222
+ if (selectedRunner === undefined && this.parameters.fallbackOnFirst) {
223
+ selectedRunner = this.runners[0];
224
+ }
225
+ if (selectedRunner === undefined) {
226
+ this.log("ERROR", `Cannot find a runner for action ${event.uuid}`);
227
+ await this.model.ref(event.uuid).patch({
228
+ status: "ERROR",
229
+ errorMessage: `No runner found for the job`
230
+ });
231
+ return;
232
+ }
233
+ this.log("INFO", `Starting action ${event.uuid}`);
234
+ await this.model.ref(event.uuid).patch({
235
+ status: "STARTING"
236
+ });
237
+ const action = await this.model.ref(event.uuid).get();
238
+ const job = await selectedRunner.launchAction(action, this.getJobInfo(action));
239
+ await action.patch({ job });
240
+ return job.promise || Promise.resolve();
241
+ }
242
+ /**
243
+ * Absolute url of the status hook remote runners POST their reports to
244
+ *
245
+ * It is this service status route: its request filter lets the job headers through
246
+ * and the HMAC is then verified by the action
247
+ * @returns the hook url
248
+ */
249
+ getHookUrl() {
250
+ return `${useParameters().apiUrl ?? ""}${this.parameters.url}/status`;
251
+ }
252
+ /**
253
+ * Get the job info
254
+ * @param action - the action
255
+ * @returns the job information
256
+ */
257
+ getJobInfo(action) {
258
+ return {
259
+ JOB_SECRET_KEY: action.__secretKey,
260
+ JOB_ID: action.uuid,
261
+ JOB_HOOK: this.parameters.onlyHttpHook || !action.isInternal() ? this.getHookUrl() : "store",
262
+ JOB_ORCHESTRATOR: this.getName()
263
+ };
264
+ }
265
+ /**
266
+ * List available operations through this service
267
+ * @param context - the web context
268
+ */
269
+ async listOperations(context) {
270
+ const filtered = JSONUtils.duplicate(this.operations);
271
+ // Filter operations the caller may not call (session permission and authorizers, in probe mode)
272
+ const keys = Object.keys(filtered.operations);
273
+ const allowed = await Promise.all(keys.map(key => canCallOperation(context, key)));
274
+ keys.filter((_key, i) => !allowed[i]).forEach(key => delete filtered.operations[key]);
275
+ // Remove permission definition
276
+ Object.values(filtered.operations)
277
+ .filter(def => def.permission)
278
+ .forEach(def => delete def.permission);
279
+ if (!context.getParameters().full) {
280
+ context.write(Object.keys(filtered.operations));
281
+ return;
282
+ }
283
+ const schemas = [];
284
+ Object.values(filtered.operations).forEach((operation) => {
285
+ if (operation.input && operation.input !== "void") {
286
+ schemas.push(operation.input);
287
+ }
288
+ if (operation.output && operation.output !== "void") {
289
+ schemas.push(operation.output);
290
+ }
291
+ });
292
+ // Filter schemas
293
+ Object.keys(filtered.schemas)
294
+ .filter(key => !schemas.includes(key))
295
+ .forEach(key => {
296
+ delete filtered.schemas[key];
297
+ });
298
+ context.write(filtered);
299
+ }
300
+ /**
301
+ * Call an operation for an external system
302
+ * @param context - the operation context
303
+ * @returns the launched action
304
+ */
305
+ async callOperation(context) {
306
+ return await this.launchAction(new this.operationModel(context.getExtension("operation"), context));
307
+ }
308
+ /**
309
+ * Check the operation exists, is allowed and its input is valid
310
+ * @param context - the operation context
311
+ * @param operationId - the operation id
312
+ */
313
+ async checkOperation(context, operationId) {
314
+ const operation = listFullOperations()[operationId];
315
+ if (!operation) {
316
+ throw new WebdaError.NotFound(`${operationId} Unknown`);
317
+ }
318
+ // Probe first so a forbidden operation answers Forbidden before any input validation
319
+ if (!(await canCallOperation(context, operationId))) {
320
+ throw new WebdaError.Forbidden(`${operationId} PermissionDenied`);
321
+ }
322
+ let input;
323
+ if (operation.input && operation.input !== "void") {
324
+ input = await context.getInput();
325
+ try {
326
+ validateSchema(operation.input, input);
327
+ }
328
+ catch (err) {
329
+ if (err instanceof ValidationError) {
330
+ throw new WebdaError.BadRequest(`${operationId} InvalidInput ${err.message}`);
331
+ }
332
+ throw err;
333
+ }
334
+ }
335
+ // Exact check on the validated input
336
+ if (!(await canCallOperation(context, operationId, { input }))) {
337
+ throw new WebdaError.Forbidden(`${operationId} PermissionDenied`);
338
+ }
339
+ }
340
+ /**
341
+ * Launch an operation through this service
342
+ * @param context - the web context
343
+ */
344
+ async launchOperation(context) {
345
+ const { operationId, schedule } = context.getParameters();
346
+ await this.checkOperation(context, operationId);
347
+ let action;
348
+ if (schedule) {
349
+ action = await this.scheduleAction(new this.operationModel(operationId, await SimpleOperationContext.fromContext(context)), schedule);
350
+ }
351
+ else {
352
+ action = await this.callOperation((await SimpleOperationContext.fromContext(context)).setExtension("operation", operationId));
353
+ }
354
+ context.write(action);
355
+ }
356
+ /**
357
+ * Launch the action asynchronously
358
+ * @param action - the action
359
+ * @returns the action
360
+ */
361
+ async launchAction(action) {
362
+ action.status = "QUEUED";
363
+ action.type = action.constructor.name;
364
+ action.__secretKey = getUuid();
365
+ await action.save();
366
+ const item = { uuid: action.uuid, __secretKey: action.__secretKey, type: action.type };
367
+ if (this.parameters.localLaunch) {
368
+ // Directly call the handler but not wait for its result
369
+ this.handleEvent(item);
370
+ }
371
+ else {
372
+ await this.queue.sendMessage(item);
373
+ }
374
+ return action;
375
+ }
376
+ /**
377
+ * Schedule action for later execution
378
+ *
379
+ * @param action - the action
380
+ * @param timestamp - when to launch it
381
+ * @returns the action
382
+ */
383
+ async scheduleAction(action, timestamp) {
384
+ action.status = "SCHEDULED";
385
+ action.type = action.constructor.name;
386
+ // Schedule based on the scheduler resolution
387
+ action.scheduled = timestamp - (timestamp % this.parameters.schedulerResolution);
388
+ await action.save();
389
+ return action;
390
+ }
391
+ /**
392
+ * Return headers to request status hook
393
+ *
394
+ * @param jobInfo - the job information
395
+ * @returns the headers
396
+ */
397
+ getHeaders(jobInfo) {
398
+ const res = {
399
+ "X-Job-Id": jobInfo.JOB_ID,
400
+ "X-Job-Time": Date.now().toString()
401
+ };
402
+ res["X-Job-Hash"] = crypto
403
+ .createHmac(_a.HMAC_ALGO, jobInfo.JOB_SECRET_KEY)
404
+ .update(res["X-Job-Time"])
405
+ .digest("hex");
406
+ return res;
407
+ }
408
+ /**
409
+ * Post hook to a remote url or use local store to update status
410
+ * @param jobInfo - the job information
411
+ * @param message - the status report
412
+ * @returns the updated action
413
+ */
414
+ async postHook(jobInfo, message) {
415
+ // Http allow to break paradigm between the executor and the orchestrator
416
+ if (jobInfo.JOB_HOOK.startsWith("http")) {
417
+ return (await axios.post(jobInfo.JOB_HOOK, message, {
418
+ headers: this.getHeaders(jobInfo)
419
+ })).data;
420
+ }
421
+ else if (jobInfo.JOB_HOOK === "store") {
422
+ // If executor and orchestrator runs within same privilege it simplify the infrastructure
423
+ return (await this.model.ref(jobInfo.JOB_ID).get()).update(message);
424
+ }
425
+ }
426
+ /**
427
+ * Launch a service.method as an AsyncAction
428
+ * @param serviceName - the service
429
+ * @param method - the method
430
+ * @param args - the arguments
431
+ * @returns the action
432
+ */
433
+ async launchAsAsyncAction(serviceName, method, ...args) {
434
+ return this.launchAction(new this.model(serviceName, method, ...args));
435
+ }
436
+ /**
437
+ * Execute a service.method as an AsyncAction
438
+ *
439
+ * Useful for crontab execution
440
+ * @param serviceName - the service
441
+ * @param method - the method
442
+ * @param args - the arguments
443
+ * @returns the execution promise
444
+ */
445
+ async executeAsAsyncAction(serviceName, method, ...args) {
446
+ let runner = Object.values(useCore().getServices()).find(s => s instanceof ServiceRunner);
447
+ // Create a temporary one if needed
448
+ runner ?? (runner = await new ServiceRunner(this.getName() + "_temprunner", new ServiceRunnerParameters().load({ type: "Webda/ServiceRunner" }))
449
+ .resolve()
450
+ .init());
451
+ // Save action
452
+ const action = await new this.model(serviceName, method, ...args).save();
453
+ // Run it
454
+ return (await runner.launchAction(action, this.getJobInfo(action))).promise;
455
+ }
456
+ /**
457
+ * Run the AsyncAction described by the JOB_* environment variables
458
+ * @returns the execution promise
459
+ */
460
+ async runAction() {
461
+ return this.runAsyncOperationAction();
462
+ }
463
+ /**
464
+ * Wrap async job and call the job status hook
465
+ * @param jobInfo - the job information, from environment if not provided
466
+ * @returns a promise resolved once the job is reported
467
+ */
468
+ async runAsyncOperationAction(jobInfo) {
469
+ // Get it from environment
470
+ if (jobInfo === undefined) {
471
+ jobInfo = {};
472
+ Object.keys(process.env)
473
+ .filter(k => k.startsWith("JOB_"))
474
+ // @ts-ignore
475
+ .forEach((k) => (jobInfo[k] = process.env[k]));
476
+ }
477
+ // Ensure correct context
478
+ if (!jobInfo.JOB_ORCHESTRATOR || !jobInfo.JOB_ID || !jobInfo.JOB_SECRET_KEY || !jobInfo.JOB_HOOK) {
479
+ this.log("ERROR", "Cannot run AsyncAction without context");
480
+ throw new Error("Cannot run AsyncAction without context");
481
+ }
482
+ // If we are not the target redirect to the right one
483
+ if (jobInfo.JOB_ORCHESTRATOR !== this.getName()) {
484
+ this.log("DEBUG", `Passing jobInfo ${jobInfo} to targeted service`);
485
+ return useDynamicService(jobInfo.JOB_ORCHESTRATOR).runAsyncOperationAction(jobInfo);
486
+ }
487
+ this.log("DEBUG", "Getting action to execute from hook", jobInfo);
488
+ // Get action info by calling the hook
489
+ const action = await this.postHook(jobInfo, {
490
+ agent: {
491
+ ...Runner.getAgentInfo(),
492
+ nodeVersion: process.version
493
+ },
494
+ status: "RUNNING"
495
+ });
496
+ this.log("DEBUG", "Action received", action.serviceName, action.method, action.arguments);
497
+ let results;
498
+ try {
499
+ // Check it contains the right info
500
+ if (!action.method || !action.serviceName) {
501
+ throw new Error("WebdaAsyncAction must have method and serviceName defined at least");
502
+ }
503
+ // Call the service[method](...args)
504
+ const service = useDynamicService(action.serviceName);
505
+ if (!service) {
506
+ throw new Error(`WebdaAsyncAction Service '${action.serviceName}' not found: mismatch app version`);
507
+ }
508
+ // @ts-ignore
509
+ if (!service[action.method]) {
510
+ throw new Error(`WebdaAsyncAction Method '${action.method}' not found in service ${action.serviceName}: mismatch app version`);
511
+ }
512
+ // @ts-ignore
513
+ results = await service[action.method](...(action.arguments || []));
514
+ }
515
+ catch (err) {
516
+ // Job is in error
517
+ await this.postHook(jobInfo, {
518
+ errorMessage: err?.message,
519
+ status: "ERROR"
520
+ });
521
+ return;
522
+ }
523
+ // Update status
524
+ await this.postHook(jobInfo, {
525
+ results,
526
+ status: "SUCCESS"
527
+ });
528
+ }
529
+ /**
530
+ * Get the cron callback function
531
+ * @param cron - the cron definition
532
+ * @returns the cron callback
533
+ */
534
+ getCronExecutor(cron) {
535
+ return async () => {
536
+ try {
537
+ this.log("INFO", `Execute cron ${cron.cron}: ${cron.serviceName}.${cron.method}(...) # ${cron.description} as an AsyncOperationAction`);
538
+ await this.launchAction(new this.model(cron.serviceName, cron.method, cron.args));
539
+ }
540
+ catch (err) {
541
+ this.log("ERROR", `Execution error cron ${cron.cron}: ${cron.serviceName}.${cron.method}(...) # ${cron.description} - ${err}`);
542
+ }
543
+ };
544
+ }
545
+ /**
546
+ * Manage scheduled actions and crontab actions
547
+ * @returns a cancelable loop promise
548
+ */
549
+ scheduler() {
550
+ // Map cron to an AsyncOperationAction
551
+ // It allows you to keep a trace of the cron execution in the AsyncAction
552
+ if (this.parameters.includeCron) {
553
+ CronService.loadAnnotations(useCore().getServices()).forEach(cron => {
554
+ this.log("INFO", `Schedule cron ${cron.cron}: ${cron.serviceName}.${cron.method}(...) # ${cron.description}`);
555
+ crontabSchedule(cron.cron, this.getCronExecutor(cron));
556
+ });
557
+ }
558
+ // Every schedulerResolution will check for scheduled task
559
+ return new CancelableLoopPromise(async () => {
560
+ let time = Date.now();
561
+ time -= time % this.parameters.schedulerResolution;
562
+ // Queue all actions
563
+ await Promise.all((await this.model.query(`status = 'SCHEDULED' AND scheduled < ${time + 1}`)).results.map(a => this.launchAction(a)));
564
+ time += this.parameters.schedulerResolution;
565
+ // Wait for next scheduler resolution
566
+ if (time > Date.now()) {
567
+ await sleep(time - Date.now());
568
+ /* c8 ignore next */
569
+ }
570
+ });
571
+ }
572
+ },
573
+ (() => {
574
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
575
+ _worker_decorators = [Command("async worker", { description: "Launch the async actions worker" })];
576
+ _runAction_decorators = [Command("async run", { description: "Run the async action described by the JOB_* environment variables" })];
577
+ _scheduler_decorators = [Command("async scheduler", { description: "Launch the async actions scheduler" })];
578
+ __esDecorate(_a, null, _worker_decorators, { kind: "method", name: "worker", static: false, private: false, access: { has: obj => "worker" in obj, get: obj => obj.worker }, metadata: _metadata }, null, _instanceExtraInitializers);
579
+ __esDecorate(_a, null, _runAction_decorators, { kind: "method", name: "runAction", static: false, private: false, access: { has: obj => "runAction" in obj, get: obj => obj.runAction }, metadata: _metadata }, null, _instanceExtraInitializers);
580
+ __esDecorate(_a, null, _scheduler_decorators, { kind: "method", name: "scheduler", static: false, private: false, access: { has: obj => "scheduler" in obj, get: obj => obj.scheduler }, metadata: _metadata }, null, _instanceExtraInitializers);
581
+ if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
582
+ })(),
583
+ /**
584
+ * HMAC Algorithm used for simple auth
585
+ */
586
+ _a.HMAC_ALGO = "sha256",
587
+ _a;
588
+ })();
589
+ /**
590
+ * AsyncService allows you to launch jobs and report status
591
+ *
592
+ * @WebdaModda
593
+ */
594
+ export default AsyncJobService;
595
+ export { AsyncJobService };
596
+ //# sourceMappingURL=asyncjobservice.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asyncjobservice.service.js","sourceRoot":"","sources":["../../src/services/asyncjobservice.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,gBAAgB,EAChB,OAAO,EAEP,WAAW,EACX,kBAAkB,EAGlB,iBAAiB,EACjB,cAAc,EAEd,OAAO,EACP,iBAAiB,EACjB,sBAAsB,EACtB,cAAc,EACd,OAAO,EACP,iBAAiB,EACjB,QAAQ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