powr-sdk-api 4.15.3 → 4.16.0
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/dist/middleware/projectId.js +1 -1
- package/dist/routes/index.js +2 -0
- package/dist/routes/scheduler.js +326 -0
- package/dist/utils/scheduler.js +339 -0
- package/dist/utils/scheduler.test.js +251 -0
- package/package.json +1 -1
|
@@ -17,7 +17,7 @@ const injectProjectId = (options = {}) => {
|
|
|
17
17
|
return (req, res, next) => {
|
|
18
18
|
try {
|
|
19
19
|
// Skip validation for excluded paths
|
|
20
|
-
if (excludePaths.some(path => req.path.startsWith(path))) {
|
|
20
|
+
if (req.path === "/scheduler/tick" || excludePaths.some(path => req.path.startsWith(path))) {
|
|
21
21
|
req.projectId = null;
|
|
22
22
|
return next();
|
|
23
23
|
}
|
package/dist/routes/index.js
CHANGED
|
@@ -34,6 +34,7 @@ const feedsRoutes = require('./feeds');
|
|
|
34
34
|
const toolsRoutes = require('./tools');
|
|
35
35
|
const tasksRoutes = require('./tasks');
|
|
36
36
|
const preferencesRoutes = require('./preferences');
|
|
37
|
+
const schedulerRoutes = require('./scheduler');
|
|
37
38
|
|
|
38
39
|
// Synchronous router creation
|
|
39
40
|
const createPowrRoutes = (options = {}) => {
|
|
@@ -64,6 +65,7 @@ const createPowrRoutes = (options = {}) => {
|
|
|
64
65
|
router.use('/feeds', verifyToken, feedsRoutes);
|
|
65
66
|
router.use('/tools', verifyToken, toolsRoutes);
|
|
66
67
|
router.use('/tasks', verifyToken, tasksRoutes);
|
|
68
|
+
router.use('/scheduler', verifyTokenOrServiceKey, schedulerRoutes);
|
|
67
69
|
return router;
|
|
68
70
|
};
|
|
69
71
|
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const express = require("express");
|
|
4
|
+
const {
|
|
5
|
+
ObjectId
|
|
6
|
+
} = require("mongodb");
|
|
7
|
+
const router = express.Router();
|
|
8
|
+
const {
|
|
9
|
+
getDb
|
|
10
|
+
} = require("../services/mongo");
|
|
11
|
+
const {
|
|
12
|
+
isPageviewAdmin
|
|
13
|
+
} = require("../utils/track");
|
|
14
|
+
const {
|
|
15
|
+
COLLECTION,
|
|
16
|
+
SMOKE_KIND,
|
|
17
|
+
nextRunFromCron,
|
|
18
|
+
parseScheduleCreate,
|
|
19
|
+
parseSchedulePatch,
|
|
20
|
+
scheduleSummary,
|
|
21
|
+
readSmokeEnv,
|
|
22
|
+
ensureSmokeSchedule,
|
|
23
|
+
fireTarget,
|
|
24
|
+
runDue
|
|
25
|
+
} = require("../utils/scheduler");
|
|
26
|
+
async function callerIsAdmin(db, req) {
|
|
27
|
+
var _req$user, _req$user2;
|
|
28
|
+
const rawId = String(((_req$user = req.user) === null || _req$user === void 0 ? void 0 : _req$user.powrId) || "");
|
|
29
|
+
let profileAccess;
|
|
30
|
+
let userAccess;
|
|
31
|
+
if (rawId.length === 24 && ObjectId.isValid(rawId)) {
|
|
32
|
+
const oid = new ObjectId(rawId);
|
|
33
|
+
const [profile, user] = await Promise.all([db.collection("profiles").findOne({
|
|
34
|
+
userId: {
|
|
35
|
+
$in: [oid, rawId]
|
|
36
|
+
},
|
|
37
|
+
projectId: String(req.projectId || "")
|
|
38
|
+
}, {
|
|
39
|
+
projection: {
|
|
40
|
+
access: 1
|
|
41
|
+
}
|
|
42
|
+
}), db.collection("users").findOne({
|
|
43
|
+
_id: oid
|
|
44
|
+
}, {
|
|
45
|
+
projection: {
|
|
46
|
+
access: 1
|
|
47
|
+
}
|
|
48
|
+
})]);
|
|
49
|
+
if (profile) profileAccess = profile.access;
|
|
50
|
+
if (user) userAccess = user.access;
|
|
51
|
+
}
|
|
52
|
+
return isPageviewAdmin({
|
|
53
|
+
jwtAccess: (_req$user2 = req.user) === null || _req$user2 === void 0 ? void 0 : _req$user2.access,
|
|
54
|
+
profileAccess,
|
|
55
|
+
userAccess
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
async function requireActor(db, req, res) {
|
|
59
|
+
if (req.serviceCall) return true;
|
|
60
|
+
if (!req.user) {
|
|
61
|
+
res.status(401).json({
|
|
62
|
+
success: false,
|
|
63
|
+
message: "Sign in required."
|
|
64
|
+
});
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
if (!(await callerIsAdmin(db, req))) {
|
|
68
|
+
res.status(403).json({
|
|
69
|
+
success: false,
|
|
70
|
+
message: "Access denied."
|
|
71
|
+
});
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
function asId(value) {
|
|
77
|
+
const id = String(value || "");
|
|
78
|
+
if (!ObjectId.isValid(id) || id.length !== 24) return null;
|
|
79
|
+
return new ObjectId(id);
|
|
80
|
+
}
|
|
81
|
+
async function seedSmokeIfConfigured(db, projectId) {
|
|
82
|
+
const smoke = readSmokeEnv();
|
|
83
|
+
if (!smoke.projectId || smoke.projectId !== String(projectId || "")) return;
|
|
84
|
+
await ensureSmokeSchedule(db, smoke);
|
|
85
|
+
}
|
|
86
|
+
router.post("/tick", async (req, res) => {
|
|
87
|
+
if (!req.serviceCall) {
|
|
88
|
+
return res.status(401).json({
|
|
89
|
+
success: false,
|
|
90
|
+
message: "Unauthorized: valid X-Service-Key required."
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
const db = await getDb();
|
|
95
|
+
const smoke = readSmokeEnv();
|
|
96
|
+
if (smoke.projectId) await ensureSmokeSchedule(db, smoke);
|
|
97
|
+
const now = new Date();
|
|
98
|
+
const results = await runDue(db, now);
|
|
99
|
+
const ok = results.filter(row => row.ok).length;
|
|
100
|
+
return res.json({
|
|
101
|
+
success: true,
|
|
102
|
+
ran: results.length,
|
|
103
|
+
ok,
|
|
104
|
+
failed: results.length - ok
|
|
105
|
+
});
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error("POST /scheduler/tick", error.message);
|
|
108
|
+
return res.status(500).json({
|
|
109
|
+
success: false,
|
|
110
|
+
message: "Tick failed."
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
router.get("/", async (req, res) => {
|
|
115
|
+
try {
|
|
116
|
+
const db = await getDb();
|
|
117
|
+
if (!(await requireActor(db, req, res))) return;
|
|
118
|
+
const projectId = String(req.projectId || "");
|
|
119
|
+
await seedSmokeIfConfigured(db, projectId);
|
|
120
|
+
const rows = await db.collection(COLLECTION).find({
|
|
121
|
+
projectId
|
|
122
|
+
}).sort({
|
|
123
|
+
name: 1
|
|
124
|
+
}).limit(100).toArray();
|
|
125
|
+
return res.json({
|
|
126
|
+
success: true,
|
|
127
|
+
count: rows.length,
|
|
128
|
+
data: rows.map(scheduleSummary)
|
|
129
|
+
});
|
|
130
|
+
} catch (error) {
|
|
131
|
+
console.error("GET /scheduler", error.message);
|
|
132
|
+
return res.status(500).json({
|
|
133
|
+
success: false,
|
|
134
|
+
message: "Failed to list schedules."
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
router.post("/", async (req, res) => {
|
|
139
|
+
try {
|
|
140
|
+
let fields;
|
|
141
|
+
try {
|
|
142
|
+
fields = parseScheduleCreate(req.body || {});
|
|
143
|
+
} catch (error) {
|
|
144
|
+
return res.status(error.statusCode || 400).json({
|
|
145
|
+
success: false,
|
|
146
|
+
message: error.message
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
const db = await getDb();
|
|
150
|
+
if (!(await requireActor(db, req, res))) return;
|
|
151
|
+
const now = new Date();
|
|
152
|
+
const doc = {
|
|
153
|
+
projectId: String(req.projectId),
|
|
154
|
+
kind: "http",
|
|
155
|
+
...fields,
|
|
156
|
+
nextRun: fields.enabled ? now : null,
|
|
157
|
+
lastRunAt: null,
|
|
158
|
+
lastOk: null,
|
|
159
|
+
lastStatus: null,
|
|
160
|
+
lastError: null,
|
|
161
|
+
claimedUntil: null,
|
|
162
|
+
createdAt: now,
|
|
163
|
+
updatedAt: now
|
|
164
|
+
};
|
|
165
|
+
const result = await db.collection(COLLECTION).insertOne(doc);
|
|
166
|
+
return res.status(201).json({
|
|
167
|
+
success: true,
|
|
168
|
+
data: scheduleSummary({
|
|
169
|
+
...doc,
|
|
170
|
+
_id: result.insertedId
|
|
171
|
+
})
|
|
172
|
+
});
|
|
173
|
+
} catch (error) {
|
|
174
|
+
console.error("POST /scheduler", error.message);
|
|
175
|
+
return res.status(500).json({
|
|
176
|
+
success: false,
|
|
177
|
+
message: "Failed to save schedule."
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
router.patch("/:id", async (req, res) => {
|
|
182
|
+
const oid = asId(req.params.id);
|
|
183
|
+
if (!oid) return res.status(400).json({
|
|
184
|
+
success: false,
|
|
185
|
+
message: "Invalid schedule id."
|
|
186
|
+
});
|
|
187
|
+
let patch;
|
|
188
|
+
try {
|
|
189
|
+
patch = parseSchedulePatch(req.body || {});
|
|
190
|
+
} catch (error) {
|
|
191
|
+
return res.status(error.statusCode || 400).json({
|
|
192
|
+
success: false,
|
|
193
|
+
message: error.message
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
const db = await getDb();
|
|
198
|
+
if (!(await requireActor(db, req, res))) return;
|
|
199
|
+
const now = new Date();
|
|
200
|
+
const update = {
|
|
201
|
+
...patch,
|
|
202
|
+
updatedAt: now
|
|
203
|
+
};
|
|
204
|
+
if (patch.enabled === true) update.nextRun = now;
|
|
205
|
+
const result = await db.collection(COLLECTION).findOneAndUpdate({
|
|
206
|
+
_id: oid,
|
|
207
|
+
projectId: String(req.projectId)
|
|
208
|
+
}, {
|
|
209
|
+
$set: update
|
|
210
|
+
}, {
|
|
211
|
+
returnDocument: "after"
|
|
212
|
+
});
|
|
213
|
+
const row = result && result.value ? result.value : result;
|
|
214
|
+
if (!row || !row._id) {
|
|
215
|
+
return res.status(404).json({
|
|
216
|
+
success: false,
|
|
217
|
+
message: "Schedule not found."
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
return res.json({
|
|
221
|
+
success: true,
|
|
222
|
+
data: scheduleSummary(row)
|
|
223
|
+
});
|
|
224
|
+
} catch (error) {
|
|
225
|
+
console.error("PATCH /scheduler/:id", error.message);
|
|
226
|
+
return res.status(500).json({
|
|
227
|
+
success: false,
|
|
228
|
+
message: "Failed to update schedule."
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
router.post("/:id/run", async (req, res) => {
|
|
233
|
+
const oid = asId(req.params.id);
|
|
234
|
+
if (!oid) return res.status(400).json({
|
|
235
|
+
success: false,
|
|
236
|
+
message: "Invalid schedule id."
|
|
237
|
+
});
|
|
238
|
+
try {
|
|
239
|
+
const db = await getDb();
|
|
240
|
+
if (!(await requireActor(db, req, res))) return;
|
|
241
|
+
const col = db.collection(COLLECTION);
|
|
242
|
+
const existing = await col.findOne({
|
|
243
|
+
_id: oid,
|
|
244
|
+
projectId: String(req.projectId)
|
|
245
|
+
});
|
|
246
|
+
if (!existing) return res.status(404).json({
|
|
247
|
+
success: false,
|
|
248
|
+
message: "Schedule not found."
|
|
249
|
+
});
|
|
250
|
+
const now = new Date();
|
|
251
|
+
const fired = await fireTarget(existing);
|
|
252
|
+
let nextRun = existing.nextRun || null;
|
|
253
|
+
if (existing.enabled) {
|
|
254
|
+
try {
|
|
255
|
+
nextRun = nextRunFromCron(existing.cron, now);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
nextRun = new Date(now.getTime() + 60 * 1000);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const result = await col.findOneAndUpdate({
|
|
261
|
+
_id: oid,
|
|
262
|
+
projectId: String(req.projectId)
|
|
263
|
+
}, {
|
|
264
|
+
$set: {
|
|
265
|
+
nextRun,
|
|
266
|
+
lastRunAt: now,
|
|
267
|
+
lastOk: fired.ok,
|
|
268
|
+
lastStatus: fired.status,
|
|
269
|
+
lastError: fired.error,
|
|
270
|
+
updatedAt: new Date()
|
|
271
|
+
}
|
|
272
|
+
}, {
|
|
273
|
+
returnDocument: "after"
|
|
274
|
+
});
|
|
275
|
+
const row = result && result.value ? result.value : result;
|
|
276
|
+
return res.json({
|
|
277
|
+
success: true,
|
|
278
|
+
data: scheduleSummary(row || existing)
|
|
279
|
+
});
|
|
280
|
+
} catch (error) {
|
|
281
|
+
console.error("POST /scheduler/:id/run", error.message);
|
|
282
|
+
return res.status(500).json({
|
|
283
|
+
success: false,
|
|
284
|
+
message: "Run failed."
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
router.delete("/:id", async (req, res) => {
|
|
289
|
+
const oid = asId(req.params.id);
|
|
290
|
+
if (!oid) return res.status(400).json({
|
|
291
|
+
success: false,
|
|
292
|
+
message: "Invalid schedule id."
|
|
293
|
+
});
|
|
294
|
+
try {
|
|
295
|
+
const db = await getDb();
|
|
296
|
+
if (!(await requireActor(db, req, res))) return;
|
|
297
|
+
const existing = await db.collection(COLLECTION).findOne({
|
|
298
|
+
_id: oid,
|
|
299
|
+
projectId: String(req.projectId)
|
|
300
|
+
});
|
|
301
|
+
if (!existing) return res.status(404).json({
|
|
302
|
+
success: false,
|
|
303
|
+
message: "Schedule not found."
|
|
304
|
+
});
|
|
305
|
+
if (existing.kind === SMOKE_KIND) {
|
|
306
|
+
return res.status(400).json({
|
|
307
|
+
success: false,
|
|
308
|
+
message: "The smoke schedule stays. Turn it off instead."
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
await db.collection(COLLECTION).deleteOne({
|
|
312
|
+
_id: oid,
|
|
313
|
+
projectId: String(req.projectId)
|
|
314
|
+
});
|
|
315
|
+
return res.json({
|
|
316
|
+
success: true
|
|
317
|
+
});
|
|
318
|
+
} catch (error) {
|
|
319
|
+
console.error("DELETE /scheduler/:id", error.message);
|
|
320
|
+
return res.status(500).json({
|
|
321
|
+
success: false,
|
|
322
|
+
message: "Failed to delete schedule."
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
module.exports = router;
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const COLLECTION = "powrSchedules";
|
|
4
|
+
const SMOKE_KIND = "smoke";
|
|
5
|
+
const SMOKE_NAME = "Host health";
|
|
6
|
+
const SMOKE_CRON = "* * * * *";
|
|
7
|
+
const SMOKE_URL = "https://powr-api.lawazia.tech/health";
|
|
8
|
+
const TICK_LIMIT = 20;
|
|
9
|
+
const CLAIM_MS = 45 * 1000;
|
|
10
|
+
const FIRE_MS = 8 * 1000;
|
|
11
|
+
const TZ = "Asia/Kolkata";
|
|
12
|
+
function reject(message, statusCode = 400) {
|
|
13
|
+
const error = new Error(message);
|
|
14
|
+
error.statusCode = statusCode;
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
function isFiveFieldCron(value) {
|
|
18
|
+
return String(value || "").trim().split(/\s+/).length === 5;
|
|
19
|
+
}
|
|
20
|
+
function nextRunFromCron(cron, from = new Date()) {
|
|
21
|
+
if (!isFiveFieldCron(cron)) {
|
|
22
|
+
reject("When must be a 5-field cron in India time.");
|
|
23
|
+
}
|
|
24
|
+
let parser;
|
|
25
|
+
try {
|
|
26
|
+
parser = require("cron-parser");
|
|
27
|
+
} catch (error) {
|
|
28
|
+
reject("Scheduler clock is not available.", 503);
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
const interval = parser.parseExpression(String(cron).trim(), {
|
|
32
|
+
currentDate: from,
|
|
33
|
+
tz: TZ
|
|
34
|
+
});
|
|
35
|
+
return interval.next().toDate();
|
|
36
|
+
} catch (error) {
|
|
37
|
+
reject("When must be a 5-field cron in India time.");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function whenLabel(cron) {
|
|
41
|
+
if (String(cron || "").trim() === SMOKE_CRON) return "Every minute";
|
|
42
|
+
return String(cron || "").trim();
|
|
43
|
+
}
|
|
44
|
+
function isClaimed(row, now) {
|
|
45
|
+
if (!row || !row.claimedUntil) return false;
|
|
46
|
+
return new Date(row.claimedUntil).getTime() > now.getTime();
|
|
47
|
+
}
|
|
48
|
+
function isDue(row, now) {
|
|
49
|
+
if (!row || row.enabled !== true || !row.nextRun) return false;
|
|
50
|
+
if (new Date(row.nextRun).getTime() > now.getTime()) return false;
|
|
51
|
+
if (isClaimed(row, now)) return false;
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
function dueFilter(now) {
|
|
55
|
+
return {
|
|
56
|
+
enabled: true,
|
|
57
|
+
nextRun: {
|
|
58
|
+
$lte: now
|
|
59
|
+
},
|
|
60
|
+
$or: [{
|
|
61
|
+
claimedUntil: null
|
|
62
|
+
}, {
|
|
63
|
+
claimedUntil: {
|
|
64
|
+
$lte: now
|
|
65
|
+
}
|
|
66
|
+
}]
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function isBlockedHost(hostname) {
|
|
70
|
+
const host = String(hostname || "").toLowerCase().replace(/^\[|\]$/g, "");
|
|
71
|
+
if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) return true;
|
|
72
|
+
if (host === "metadata.google.internal" || host === "0.0.0.0" || host === "::1") return true;
|
|
73
|
+
const match = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
74
|
+
if (!match) return false;
|
|
75
|
+
const parts = match.slice(1).map(Number);
|
|
76
|
+
if (parts.some(n => n > 255)) return true;
|
|
77
|
+
const a = parts[0];
|
|
78
|
+
const b = parts[1];
|
|
79
|
+
if (a === 10 || a === 127 || a === 0) return true;
|
|
80
|
+
if (a === 169 && b === 254) return true;
|
|
81
|
+
if (a === 192 && b === 168) return true;
|
|
82
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
function assertPublicHttpsUrl(value) {
|
|
86
|
+
let url;
|
|
87
|
+
try {
|
|
88
|
+
url = new URL(String(value || "").trim());
|
|
89
|
+
} catch (error) {
|
|
90
|
+
reject("Target must be an https URL.");
|
|
91
|
+
}
|
|
92
|
+
if (url.protocol !== "https:") reject("Target must be an https URL.");
|
|
93
|
+
if (url.username || url.password) reject("Target URL cannot include a login.");
|
|
94
|
+
if (isBlockedHost(url.hostname)) reject("Target host is not allowed.");
|
|
95
|
+
if (url.href.length > 500) reject("Target URL is too long.");
|
|
96
|
+
return url.href;
|
|
97
|
+
}
|
|
98
|
+
function parseName(value) {
|
|
99
|
+
const name = String(value || "").trim();
|
|
100
|
+
if (!name) reject("Name is required.");
|
|
101
|
+
if (name.length > 80) reject("Name must be under 80 characters.");
|
|
102
|
+
return name;
|
|
103
|
+
}
|
|
104
|
+
function parseMethod(value) {
|
|
105
|
+
const method = String(value || "GET").trim().toUpperCase();
|
|
106
|
+
if (method !== "GET" && method !== "POST") reject("Method must be GET or POST.");
|
|
107
|
+
return method;
|
|
108
|
+
}
|
|
109
|
+
function parseScheduleCreate(body) {
|
|
110
|
+
const source = body || {};
|
|
111
|
+
const name = parseName(source.name);
|
|
112
|
+
const cron = String(source.cron || "").trim();
|
|
113
|
+
nextRunFromCron(cron, new Date());
|
|
114
|
+
return {
|
|
115
|
+
name,
|
|
116
|
+
cron,
|
|
117
|
+
method: parseMethod(source.method),
|
|
118
|
+
url: assertPublicHttpsUrl(source.url),
|
|
119
|
+
enabled: source.enabled === true
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function parseSchedulePatch(body) {
|
|
123
|
+
const source = body || {};
|
|
124
|
+
const patch = {};
|
|
125
|
+
if (source.name !== undefined) patch.name = parseName(source.name);
|
|
126
|
+
if (source.cron !== undefined) {
|
|
127
|
+
const cron = String(source.cron || "").trim();
|
|
128
|
+
nextRunFromCron(cron, new Date());
|
|
129
|
+
patch.cron = cron;
|
|
130
|
+
}
|
|
131
|
+
if (source.method !== undefined) patch.method = parseMethod(source.method);
|
|
132
|
+
if (source.url !== undefined) patch.url = assertPublicHttpsUrl(source.url);
|
|
133
|
+
if (source.enabled !== undefined) {
|
|
134
|
+
if (typeof source.enabled !== "boolean") reject("Enabled must be true or false.");
|
|
135
|
+
patch.enabled = source.enabled;
|
|
136
|
+
}
|
|
137
|
+
if (!Object.keys(patch).length) reject("Nothing to update.");
|
|
138
|
+
return patch;
|
|
139
|
+
}
|
|
140
|
+
function scheduleSummary(row) {
|
|
141
|
+
return {
|
|
142
|
+
_id: String(row._id),
|
|
143
|
+
projectId: String(row.projectId || ""),
|
|
144
|
+
name: row.name || "",
|
|
145
|
+
kind: row.kind || "http",
|
|
146
|
+
cron: row.cron || "",
|
|
147
|
+
when: whenLabel(row.cron),
|
|
148
|
+
method: row.method || "GET",
|
|
149
|
+
url: row.url || "",
|
|
150
|
+
enabled: row.enabled === true,
|
|
151
|
+
nextRun: row.nextRun || null,
|
|
152
|
+
lastRunAt: row.lastRunAt || null,
|
|
153
|
+
lastOk: row.lastOk === true ? true : row.lastOk === false ? false : null,
|
|
154
|
+
lastStatus: row.lastStatus == null ? null : row.lastStatus,
|
|
155
|
+
lastError: row.lastError || null
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function smokeScheduleDoc({
|
|
159
|
+
projectId,
|
|
160
|
+
url,
|
|
161
|
+
now
|
|
162
|
+
}) {
|
|
163
|
+
return {
|
|
164
|
+
projectId: String(projectId),
|
|
165
|
+
name: SMOKE_NAME,
|
|
166
|
+
kind: SMOKE_KIND,
|
|
167
|
+
cron: SMOKE_CRON,
|
|
168
|
+
method: "GET",
|
|
169
|
+
url,
|
|
170
|
+
enabled: false,
|
|
171
|
+
nextRun: null,
|
|
172
|
+
lastRunAt: null,
|
|
173
|
+
lastOk: null,
|
|
174
|
+
lastStatus: null,
|
|
175
|
+
lastError: null,
|
|
176
|
+
claimedUntil: null,
|
|
177
|
+
createdAt: now,
|
|
178
|
+
updatedAt: now
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function readSmokeEnv(env = process.env) {
|
|
182
|
+
return {
|
|
183
|
+
projectId: String(env.SCHEDULER_SMOKE_PROJECT_ID || "").trim(),
|
|
184
|
+
url: String(env.SCHEDULER_SMOKE_URL || SMOKE_URL).trim()
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
async function ensureSmokeSchedule(db, {
|
|
188
|
+
projectId,
|
|
189
|
+
url,
|
|
190
|
+
now = new Date()
|
|
191
|
+
} = {}) {
|
|
192
|
+
const project = String(projectId || "").trim();
|
|
193
|
+
if (!project) return {
|
|
194
|
+
created: false
|
|
195
|
+
};
|
|
196
|
+
const target = assertPublicHttpsUrl(url || SMOKE_URL);
|
|
197
|
+
const existing = await db.collection(COLLECTION).findOne({
|
|
198
|
+
projectId: project,
|
|
199
|
+
kind: SMOKE_KIND
|
|
200
|
+
});
|
|
201
|
+
if (existing) return {
|
|
202
|
+
created: false,
|
|
203
|
+
id: existing._id
|
|
204
|
+
};
|
|
205
|
+
const doc = smokeScheduleDoc({
|
|
206
|
+
projectId: project,
|
|
207
|
+
url: target,
|
|
208
|
+
now
|
|
209
|
+
});
|
|
210
|
+
const result = await db.collection(COLLECTION).insertOne(doc);
|
|
211
|
+
return {
|
|
212
|
+
created: true,
|
|
213
|
+
id: result.insertedId
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function updatedDoc(raw) {
|
|
217
|
+
if (!raw) return null;
|
|
218
|
+
if (raw.value && raw.value._id) return raw.value;
|
|
219
|
+
if (raw._id) return raw;
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
async function fireTarget(row, fetchImpl = global.fetch) {
|
|
223
|
+
let url;
|
|
224
|
+
try {
|
|
225
|
+
url = assertPublicHttpsUrl(row && row.url);
|
|
226
|
+
} catch (error) {
|
|
227
|
+
return {
|
|
228
|
+
ok: false,
|
|
229
|
+
status: null,
|
|
230
|
+
error: error.message
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
let method;
|
|
234
|
+
try {
|
|
235
|
+
method = parseMethod(row && row.method);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
return {
|
|
238
|
+
ok: false,
|
|
239
|
+
status: null,
|
|
240
|
+
error: error.message
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
const controller = new AbortController();
|
|
244
|
+
const timer = setTimeout(() => controller.abort(), FIRE_MS);
|
|
245
|
+
try {
|
|
246
|
+
const response = await fetchImpl(url, {
|
|
247
|
+
method,
|
|
248
|
+
redirect: "manual",
|
|
249
|
+
cache: "no-store",
|
|
250
|
+
signal: controller.signal,
|
|
251
|
+
headers: method === "POST" ? {
|
|
252
|
+
"Content-Type": "application/json"
|
|
253
|
+
} : undefined,
|
|
254
|
+
body: method === "POST" ? "{}" : undefined
|
|
255
|
+
});
|
|
256
|
+
const status = Number(response && response.status);
|
|
257
|
+
const ok = status >= 200 && status < 300;
|
|
258
|
+
return {
|
|
259
|
+
ok,
|
|
260
|
+
status: Number.isFinite(status) ? status : null,
|
|
261
|
+
error: ok ? null : `HTTP ${status}`
|
|
262
|
+
};
|
|
263
|
+
} catch (error) {
|
|
264
|
+
const timedOut = error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
265
|
+
return {
|
|
266
|
+
ok: false,
|
|
267
|
+
status: null,
|
|
268
|
+
error: timedOut ? "Timed out" : "Request failed"
|
|
269
|
+
};
|
|
270
|
+
} finally {
|
|
271
|
+
clearTimeout(timer);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
async function runDue(db, now = new Date(), fetchImpl = global.fetch) {
|
|
275
|
+
const col = db.collection(COLLECTION);
|
|
276
|
+
const results = [];
|
|
277
|
+
for (let i = 0; i < TICK_LIMIT; i += 1) {
|
|
278
|
+
const claimedUntil = new Date(now.getTime() + CLAIM_MS);
|
|
279
|
+
const raw = await col.findOneAndUpdate(dueFilter(now), {
|
|
280
|
+
$set: {
|
|
281
|
+
claimedUntil,
|
|
282
|
+
updatedAt: now
|
|
283
|
+
}
|
|
284
|
+
}, {
|
|
285
|
+
returnDocument: "after"
|
|
286
|
+
});
|
|
287
|
+
const doc = updatedDoc(raw);
|
|
288
|
+
if (!doc) break;
|
|
289
|
+
const fired = await fireTarget(doc, fetchImpl);
|
|
290
|
+
let nextRun = null;
|
|
291
|
+
try {
|
|
292
|
+
nextRun = nextRunFromCron(doc.cron, now);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
nextRun = new Date(now.getTime() + 60 * 1000);
|
|
295
|
+
}
|
|
296
|
+
await col.updateOne({
|
|
297
|
+
_id: doc._id
|
|
298
|
+
}, {
|
|
299
|
+
$set: {
|
|
300
|
+
nextRun,
|
|
301
|
+
lastRunAt: now,
|
|
302
|
+
lastOk: fired.ok,
|
|
303
|
+
lastStatus: fired.status,
|
|
304
|
+
lastError: fired.error,
|
|
305
|
+
claimedUntil: null,
|
|
306
|
+
updatedAt: new Date()
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
results.push({
|
|
310
|
+
id: String(doc._id),
|
|
311
|
+
ok: fired.ok === true
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
return results;
|
|
315
|
+
}
|
|
316
|
+
module.exports = {
|
|
317
|
+
COLLECTION,
|
|
318
|
+
SMOKE_KIND,
|
|
319
|
+
SMOKE_NAME,
|
|
320
|
+
SMOKE_CRON,
|
|
321
|
+
SMOKE_URL,
|
|
322
|
+
TICK_LIMIT,
|
|
323
|
+
TZ,
|
|
324
|
+
nextRunFromCron,
|
|
325
|
+
whenLabel,
|
|
326
|
+
isDue,
|
|
327
|
+
isClaimed,
|
|
328
|
+
dueFilter,
|
|
329
|
+
isBlockedHost,
|
|
330
|
+
assertPublicHttpsUrl,
|
|
331
|
+
parseScheduleCreate,
|
|
332
|
+
parseSchedulePatch,
|
|
333
|
+
scheduleSummary,
|
|
334
|
+
smokeScheduleDoc,
|
|
335
|
+
readSmokeEnv,
|
|
336
|
+
ensureSmokeSchedule,
|
|
337
|
+
fireTarget,
|
|
338
|
+
runDue
|
|
339
|
+
};
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
SMOKE_URL,
|
|
5
|
+
nextRunFromCron,
|
|
6
|
+
whenLabel,
|
|
7
|
+
isDue,
|
|
8
|
+
dueFilter,
|
|
9
|
+
assertPublicHttpsUrl,
|
|
10
|
+
parseScheduleCreate,
|
|
11
|
+
parseSchedulePatch,
|
|
12
|
+
scheduleSummary,
|
|
13
|
+
ensureSmokeSchedule,
|
|
14
|
+
fireTarget,
|
|
15
|
+
runDue
|
|
16
|
+
} = require("./scheduler");
|
|
17
|
+
describe("nextRunFromCron", () => {
|
|
18
|
+
it("steps within a minute", () => {
|
|
19
|
+
const from = new Date("2026-10-09T10:00:30.000Z");
|
|
20
|
+
const next = nextRunFromCron("* * * * *", from);
|
|
21
|
+
expect(next.getTime()).toBeGreaterThan(from.getTime());
|
|
22
|
+
expect(next.getTime() - from.getTime()).toBeLessThanOrEqual(60 * 1000);
|
|
23
|
+
});
|
|
24
|
+
it("rejects a nickname", () => {
|
|
25
|
+
expect(() => nextRunFromCron("@hourly")).toThrow("5-field cron");
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
describe("isDue", () => {
|
|
29
|
+
const now = new Date("2026-10-09T10:01:00.000Z");
|
|
30
|
+
it("is due when enabled and nextRun is past", () => {
|
|
31
|
+
expect(isDue({
|
|
32
|
+
enabled: true,
|
|
33
|
+
nextRun: new Date("2026-10-09T10:00:00.000Z")
|
|
34
|
+
}, now)).toBe(true);
|
|
35
|
+
});
|
|
36
|
+
it("skips a disabled or claimed row", () => {
|
|
37
|
+
expect(isDue({
|
|
38
|
+
enabled: false,
|
|
39
|
+
nextRun: new Date("2026-10-09T10:00:00.000Z")
|
|
40
|
+
}, now)).toBe(false);
|
|
41
|
+
expect(isDue({
|
|
42
|
+
enabled: true,
|
|
43
|
+
nextRun: new Date("2026-10-09T10:00:00.000Z"),
|
|
44
|
+
claimedUntil: new Date("2026-10-09T10:02:00.000Z")
|
|
45
|
+
}, now)).toBe(false);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
describe("dueFilter", () => {
|
|
49
|
+
it("matches the due rule", () => {
|
|
50
|
+
const now = new Date("2026-10-09T10:01:00.000Z");
|
|
51
|
+
expect(dueFilter(now)).toEqual({
|
|
52
|
+
enabled: true,
|
|
53
|
+
nextRun: {
|
|
54
|
+
$lte: now
|
|
55
|
+
},
|
|
56
|
+
$or: [{
|
|
57
|
+
claimedUntil: null
|
|
58
|
+
}, {
|
|
59
|
+
claimedUntil: {
|
|
60
|
+
$lte: now
|
|
61
|
+
}
|
|
62
|
+
}]
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
describe("assertPublicHttpsUrl", () => {
|
|
67
|
+
it("keeps the host health URL", () => {
|
|
68
|
+
expect(assertPublicHttpsUrl(SMOKE_URL)).toBe(SMOKE_URL);
|
|
69
|
+
});
|
|
70
|
+
it("rejects private and non-https targets", () => {
|
|
71
|
+
expect(() => assertPublicHttpsUrl("http://powr-api.lawazia.tech/health")).toThrow("https");
|
|
72
|
+
expect(() => assertPublicHttpsUrl("https://127.0.0.1/health")).toThrow("not allowed");
|
|
73
|
+
expect(() => assertPublicHttpsUrl("https://169.254.169.254/")).toThrow("not allowed");
|
|
74
|
+
expect(() => assertPublicHttpsUrl("https://user:pass@powr-api.lawazia.tech/health")).toThrow("login");
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
describe("parseScheduleCreate", () => {
|
|
78
|
+
it("stores a public GET target", () => {
|
|
79
|
+
expect(parseScheduleCreate({
|
|
80
|
+
name: " Host health ",
|
|
81
|
+
cron: "* * * * *",
|
|
82
|
+
url: SMOKE_URL
|
|
83
|
+
})).toEqual({
|
|
84
|
+
name: "Host health",
|
|
85
|
+
cron: "* * * * *",
|
|
86
|
+
method: "GET",
|
|
87
|
+
url: SMOKE_URL,
|
|
88
|
+
enabled: false
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
describe("parseSchedulePatch", () => {
|
|
93
|
+
it("accepts on/off", () => {
|
|
94
|
+
expect(parseSchedulePatch({
|
|
95
|
+
enabled: true
|
|
96
|
+
})).toEqual({
|
|
97
|
+
enabled: true
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
it("rejects an empty patch", () => {
|
|
101
|
+
expect(() => parseSchedulePatch({})).toThrow("Nothing to update.");
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
describe("scheduleSummary", () => {
|
|
105
|
+
it("labels every minute", () => {
|
|
106
|
+
const row = scheduleSummary({
|
|
107
|
+
_id: "abc",
|
|
108
|
+
projectId: "p1",
|
|
109
|
+
name: "Host health",
|
|
110
|
+
kind: "smoke",
|
|
111
|
+
cron: "* * * * *",
|
|
112
|
+
method: "GET",
|
|
113
|
+
url: SMOKE_URL,
|
|
114
|
+
enabled: false,
|
|
115
|
+
lastOk: false,
|
|
116
|
+
lastError: "HTTP 500"
|
|
117
|
+
});
|
|
118
|
+
expect(whenLabel(row.cron)).toBe("Every minute");
|
|
119
|
+
expect(row.when).toBe("Every minute");
|
|
120
|
+
expect(row.lastOk).toBe(false);
|
|
121
|
+
expect(row.lastError).toBe("HTTP 500");
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
describe("ensureSmokeSchedule", () => {
|
|
125
|
+
function memoryDb() {
|
|
126
|
+
const rows = [];
|
|
127
|
+
return {
|
|
128
|
+
rows,
|
|
129
|
+
collection() {
|
|
130
|
+
return {
|
|
131
|
+
async findOne(query) {
|
|
132
|
+
return rows.find(row => row.projectId === query.projectId && row.kind === query.kind) || null;
|
|
133
|
+
},
|
|
134
|
+
async insertOne(doc) {
|
|
135
|
+
const stored = {
|
|
136
|
+
...doc,
|
|
137
|
+
_id: "smoke-1"
|
|
138
|
+
};
|
|
139
|
+
rows.push(stored);
|
|
140
|
+
return {
|
|
141
|
+
insertedId: stored._id
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
it("inserts one disabled smoke row and does not clobber it", async () => {
|
|
149
|
+
const db = memoryDb();
|
|
150
|
+
const first = await ensureSmokeSchedule(db, {
|
|
151
|
+
projectId: "excelrs",
|
|
152
|
+
url: SMOKE_URL
|
|
153
|
+
});
|
|
154
|
+
expect(first.created).toBe(true);
|
|
155
|
+
expect(db.rows[0].enabled).toBe(false);
|
|
156
|
+
db.rows[0].enabled = true;
|
|
157
|
+
const second = await ensureSmokeSchedule(db, {
|
|
158
|
+
projectId: "excelrs",
|
|
159
|
+
url: SMOKE_URL
|
|
160
|
+
});
|
|
161
|
+
expect(second.created).toBe(false);
|
|
162
|
+
expect(db.rows).toHaveLength(1);
|
|
163
|
+
expect(db.rows[0].enabled).toBe(true);
|
|
164
|
+
});
|
|
165
|
+
it("skips when no project is configured", async () => {
|
|
166
|
+
const db = memoryDb();
|
|
167
|
+
const result = await ensureSmokeSchedule(db, {
|
|
168
|
+
projectId: " "
|
|
169
|
+
});
|
|
170
|
+
expect(result.created).toBe(false);
|
|
171
|
+
expect(db.rows).toHaveLength(0);
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
describe("fireTarget", () => {
|
|
175
|
+
it("records HTTP 500 as a fail without calling a blocked host", async () => {
|
|
176
|
+
const fetchImpl = jest.fn(async () => ({
|
|
177
|
+
status: 500
|
|
178
|
+
}));
|
|
179
|
+
const failed = await fireTarget({
|
|
180
|
+
url: SMOKE_URL,
|
|
181
|
+
method: "GET"
|
|
182
|
+
}, fetchImpl);
|
|
183
|
+
expect(failed).toEqual({
|
|
184
|
+
ok: false,
|
|
185
|
+
status: 500,
|
|
186
|
+
error: "HTTP 500"
|
|
187
|
+
});
|
|
188
|
+
const blocked = await fireTarget({
|
|
189
|
+
url: "https://127.0.0.1/health",
|
|
190
|
+
method: "GET"
|
|
191
|
+
}, fetchImpl);
|
|
192
|
+
expect(blocked.ok).toBe(false);
|
|
193
|
+
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
194
|
+
});
|
|
195
|
+
it("records a 200 as ok", async () => {
|
|
196
|
+
const ok = await fireTarget({
|
|
197
|
+
url: SMOKE_URL,
|
|
198
|
+
method: "GET"
|
|
199
|
+
}, async () => ({
|
|
200
|
+
status: 200
|
|
201
|
+
}));
|
|
202
|
+
expect(ok.ok).toBe(true);
|
|
203
|
+
expect(ok.error).toBe(null);
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
describe("runDue", () => {
|
|
207
|
+
it("fires a due row once and stores the fail", async () => {
|
|
208
|
+
const now = new Date("2026-10-09T10:01:00.000Z");
|
|
209
|
+
const rows = [{
|
|
210
|
+
_id: "job-1",
|
|
211
|
+
enabled: true,
|
|
212
|
+
cron: "* * * * *",
|
|
213
|
+
method: "GET",
|
|
214
|
+
url: SMOKE_URL,
|
|
215
|
+
nextRun: new Date("2026-10-09T10:00:00.000Z"),
|
|
216
|
+
claimedUntil: null
|
|
217
|
+
}];
|
|
218
|
+
const col = {
|
|
219
|
+
async findOneAndUpdate(filter, update) {
|
|
220
|
+
const row = rows.find(item => item.enabled === filter.enabled && item.nextRun <= filter.nextRun.$lte && !item.claimedUntil);
|
|
221
|
+
if (!row) return null;
|
|
222
|
+
Object.assign(row, update.$set);
|
|
223
|
+
return {
|
|
224
|
+
...row
|
|
225
|
+
};
|
|
226
|
+
},
|
|
227
|
+
async updateOne(filter, update) {
|
|
228
|
+
const row = rows.find(item => item._id === filter._id);
|
|
229
|
+
Object.assign(row, update.$set);
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
const db = {
|
|
233
|
+
collection: () => col
|
|
234
|
+
};
|
|
235
|
+
const results = await runDue(db, now, async () => ({
|
|
236
|
+
status: 404
|
|
237
|
+
}));
|
|
238
|
+
expect(results).toEqual([{
|
|
239
|
+
id: "job-1",
|
|
240
|
+
ok: false
|
|
241
|
+
}]);
|
|
242
|
+
expect(rows[0].lastOk).toBe(false);
|
|
243
|
+
expect(rows[0].lastError).toBe("HTTP 404");
|
|
244
|
+
expect(rows[0].claimedUntil).toBe(null);
|
|
245
|
+
expect(rows[0].nextRun.getTime()).toBeGreaterThan(now.getTime());
|
|
246
|
+
const again = await runDue(db, now, async () => ({
|
|
247
|
+
status: 200
|
|
248
|
+
}));
|
|
249
|
+
expect(again).toEqual([]);
|
|
250
|
+
});
|
|
251
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "powr-sdk-api",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.16.0",
|
|
4
4
|
"description": "Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|