playov2-js-utilities 0.3.31 → 0.3.33

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/lib/index.js CHANGED
@@ -11,5 +11,6 @@ module.exports = {
11
11
  httpRequest: require('./request'),
12
12
  Cron: require('./cron'),
13
13
  MessagePublisher: require('./message_publisher'),
14
- middleware: require('./middleware')
14
+ middleware: require('./middleware'),
15
+ taskScheduler: require('./taskscheduler')
15
16
  };
@@ -17,6 +17,10 @@ const LOCATION = process.env.GCP_LOCATION;
17
17
  if (!PROJECT || !LOCATION) {
18
18
  console.warn('You need to pass - GCP_PROJECT, GCP_LOCATION in env for message queue to work!');
19
19
  }
20
+
21
+ const { google } = require('googleapis');
22
+ const cloudtasks = google.cloudtasks('v2');
23
+
20
24
  /**
21
25
  *
22
26
  * @param {String} queueId - Name of the queue being targeted
@@ -89,7 +93,38 @@ const getTaskId = (projectId, locationId, queueId, taskId = uuidv4()) => {
89
93
  return `projects/${projectId}/locations/${locationId}/queues/${queueId}/tasks/${taskId}`;
90
94
  };
91
95
 
96
+ /**
97
+ * https://cloud.google.com/tasks/docs/reference/rest/v2/projects.locations.queues.tasks/delete
98
+ *
99
+ */
100
+
101
+ const authClient = await authorize();
102
+
103
+ const deleteHttpTask = async (queueId, taskId) => {
104
+ if (!queueId || !taskId) {
105
+ throw new Error('Both queueId, and taskId are required to delete a task!;')
106
+ }
107
+ const requestData = {
108
+ name: getTaskId(PROJECT, LOCATION, queueId, taskId),
109
+ auth: authClient
110
+ };
111
+
112
+ try {
113
+ await cloudtasks.projects.locations.queues.tasks.delete(requestData);
114
+ } catch (err) {
115
+ throw err;
116
+ }
117
+ };
118
+
119
+ async function authorize() {
120
+ const auth = new google.auth.GoogleAuth({
121
+ scopes: ['https://www.googleapis.com/auth/cloud-platform']
122
+ });
123
+ return await auth.getClient();
124
+ };
125
+
92
126
  module.exports = {
93
127
  createHttpTask,
94
- getTaskId
128
+ getTaskId,
129
+ deleteHttpTask
95
130
  };
@@ -0,0 +1,30 @@
1
+ const mongoose = require('mongoose');
2
+ const Schema = mongoose.Schema;
3
+
4
+ // compound index on queuId and taskId and status, so that a task is saved only once per queue
5
+ const scheduledTaskSchema = new Schema({
6
+ taskId: { type: String, required: true },
7
+ queueId: { type: String, required: true },
8
+ payload: {
9
+
10
+ },
11
+ activationTime: {
12
+ type: Date, required: true
13
+ },
14
+ cloudProvider: {
15
+ type: String,
16
+ enum: ['GCP', 'AWS'],
17
+ required: true
18
+ },
19
+ status: {
20
+ type: String,
21
+ enum: ['saved', 'executed', 'failed', 'cancelled'],
22
+ default: 'saved',
23
+ required: true
24
+ },
25
+ lastExecutionDetails: {
26
+
27
+ }
28
+ });
29
+
30
+ module.exports = mongoose.model('scheduledtasks', scheduledTaskSchema);
@@ -0,0 +1,97 @@
1
+
2
+ // methods - save future task - producers
3
+ // push future task to queue -- from cron service
4
+ // cancel future task -- producers
5
+
6
+ const SCHEDULED_TASK = require("../models/scheduled.tasks");
7
+ const CloudTask = require("../message_publisher/index");
8
+ const Moment = require("moment");
9
+ const Logger = require('../logger');
10
+
11
+ const MAX_RETRY_COUNT = 5;
12
+
13
+ /**
14
+ *
15
+ * @param {String} message
16
+ * @param {String} name - Optional - If "RetryableException", then function will be retried till MAX_RETRY_COUNT
17
+ */
18
+ function CTException(message, name) {
19
+ this.message = message;
20
+ this.name = name;
21
+ };
22
+
23
+ /**
24
+ * Currently, for cloudtask -
25
+ * Maximum schedule time for a task - 30 days, that means any task that is to be executed after 30 days
26
+ * can't be scheduled by GCP cloudtask queues.
27
+ * This function will provide a way for every microservices to save a task to mongo scheduledtasks model,
28
+ * from which tasks will be pushed via cron service to cloud task push queue on an every day basis.
29
+ * RetryableException - Network exceptions
30
+ */
31
+ const saveFutureTask = async (queueId, taskId, payload, eta, count = MAX_RETRY_COUNT, requestId) => {
32
+ try {
33
+ if (!queueId || !taskId || !payload || !eta) {
34
+ throw CTException('Parameter validation failed!', 'ValidationException')
35
+ }
36
+
37
+ if (Moment(eta).isBefore(Moment().add(30, 'days'))) {
38
+ throw CTException('eta can not be before 30 days from now. Schedule directly!', 'ValidationException')
39
+ }
40
+
41
+ const taskData = {
42
+ taskId,
43
+ payload,
44
+ queueId,
45
+ activationTime: eta,
46
+ status: 'saved',
47
+ cloudProvider: 'GCP'
48
+ }
49
+
50
+ const task = new SCHEDULED_TASK(taskData);
51
+
52
+ await task.save();
53
+
54
+ } catch (err) {
55
+ if (err.message !== "RetryableException") {
56
+ throw err;
57
+ }
58
+
59
+ if (count === 0) {
60
+ Logger.prepareAlertLog(requestId, { func: 'saveFutureTask', queueId, taskId, payload, eta, err }, 'saving future task failed!');
61
+ throw err;
62
+ }
63
+
64
+ return saveFutureTask(queueId, taskId, payload, eta, count--, requestId);
65
+ }
66
+ };
67
+
68
+
69
+ const deleteScheduledTask = async (queueId, taskId, count = MAX_RETRY_COUNT, requestId) => {
70
+ try {
71
+ if (!queueId || !taskId) {
72
+ throw CTException('Parameter validation failed!', 'ValidationException')
73
+ }
74
+
75
+ await Promise.all([
76
+ SCHEDULED_TASK.findOneAndUpdate({ queueId, taskId }, { $set: { status: 'cancelled' } }),
77
+ CloudTask.deleteHttpTask(queueId, taskId)
78
+ ]);
79
+
80
+ } catch (err) {
81
+ if (err.message !== "RetryableException") {
82
+ throw err;
83
+ }
84
+ if (count === 0) {
85
+ Logger.prepareAlertLog(requestId, { func: 'deleteScheduledTask', queueId, taskId, payload, eta, err }, 'saving future task failed!');
86
+ throw err;
87
+ }
88
+
89
+ return deleteScheduledTask(queueId, taskId, count--, requestId);
90
+ }
91
+ }
92
+
93
+ module.exports = {
94
+ saveFutureTask,
95
+ // pushScheduledTaskToQueue,
96
+ deleteScheduledTask
97
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "playov2-js-utilities",
3
- "version": "0.3.31",
3
+ "version": "0.3.33",
4
4
  "description": "Private package for JS utility functions",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -26,7 +26,10 @@
26
26
  "@playo/logger": "^0.9.24",
27
27
  "axios": "^0.24.0",
28
28
  "cron": "^1.8.2",
29
+ "googleapis": "^109.0.1",
29
30
  "handlebars": "^4.7.7",
31
+ "moment": "^2.29.4",
32
+ "mongoose": "^6.7.4",
30
33
  "uuid": "^8.3.2"
31
34
  }
32
35
  }