powr-sdk-api 4.15.3 → 4.16.1

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.
@@ -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
  }
@@ -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,347 @@
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 ? nextRunFromCron(fields.cron, 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 existing = await db.collection(COLLECTION).findOne({
200
+ _id: oid,
201
+ projectId: String(req.projectId)
202
+ });
203
+ if (!existing) {
204
+ return res.status(404).json({
205
+ success: false,
206
+ message: "Schedule not found."
207
+ });
208
+ }
209
+ const now = new Date();
210
+ const update = {
211
+ ...patch,
212
+ updatedAt: now
213
+ };
214
+ const turningOn = patch.enabled === true;
215
+ const cronChangedWhileOn = patch.cron && existing.enabled === true && patch.enabled !== false;
216
+ if (turningOn || cronChangedWhileOn) {
217
+ try {
218
+ update.nextRun = nextRunFromCron(patch.cron || existing.cron, now);
219
+ } catch (error) {
220
+ return res.status(error.statusCode || 400).json({
221
+ success: false,
222
+ message: error.message
223
+ });
224
+ }
225
+ }
226
+ const result = await db.collection(COLLECTION).findOneAndUpdate({
227
+ _id: oid,
228
+ projectId: String(req.projectId)
229
+ }, {
230
+ $set: update
231
+ }, {
232
+ returnDocument: "after"
233
+ });
234
+ const row = result && result.value ? result.value : result;
235
+ if (!row || !row._id) {
236
+ return res.status(404).json({
237
+ success: false,
238
+ message: "Schedule not found."
239
+ });
240
+ }
241
+ return res.json({
242
+ success: true,
243
+ data: scheduleSummary(row)
244
+ });
245
+ } catch (error) {
246
+ console.error("PATCH /scheduler/:id", error.message);
247
+ return res.status(500).json({
248
+ success: false,
249
+ message: "Failed to update schedule."
250
+ });
251
+ }
252
+ });
253
+ router.post("/:id/run", async (req, res) => {
254
+ const oid = asId(req.params.id);
255
+ if (!oid) return res.status(400).json({
256
+ success: false,
257
+ message: "Invalid schedule id."
258
+ });
259
+ try {
260
+ const db = await getDb();
261
+ if (!(await requireActor(db, req, res))) return;
262
+ const col = db.collection(COLLECTION);
263
+ const existing = await col.findOne({
264
+ _id: oid,
265
+ projectId: String(req.projectId)
266
+ });
267
+ if (!existing) return res.status(404).json({
268
+ success: false,
269
+ message: "Schedule not found."
270
+ });
271
+ const now = new Date();
272
+ const fired = await fireTarget(existing);
273
+ let nextRun = existing.nextRun || null;
274
+ if (existing.enabled) {
275
+ try {
276
+ nextRun = nextRunFromCron(existing.cron, now);
277
+ } catch (error) {
278
+ nextRun = new Date(now.getTime() + 60 * 1000);
279
+ }
280
+ }
281
+ const result = await col.findOneAndUpdate({
282
+ _id: oid,
283
+ projectId: String(req.projectId)
284
+ }, {
285
+ $set: {
286
+ nextRun,
287
+ lastRunAt: now,
288
+ lastOk: fired.ok,
289
+ lastStatus: fired.status,
290
+ lastError: fired.error,
291
+ updatedAt: new Date()
292
+ }
293
+ }, {
294
+ returnDocument: "after"
295
+ });
296
+ const row = result && result.value ? result.value : result;
297
+ return res.json({
298
+ success: true,
299
+ data: scheduleSummary(row || existing)
300
+ });
301
+ } catch (error) {
302
+ console.error("POST /scheduler/:id/run", error.message);
303
+ return res.status(500).json({
304
+ success: false,
305
+ message: "Run failed."
306
+ });
307
+ }
308
+ });
309
+ router.delete("/:id", async (req, res) => {
310
+ const oid = asId(req.params.id);
311
+ if (!oid) return res.status(400).json({
312
+ success: false,
313
+ message: "Invalid schedule id."
314
+ });
315
+ try {
316
+ const db = await getDb();
317
+ if (!(await requireActor(db, req, res))) return;
318
+ const existing = await db.collection(COLLECTION).findOne({
319
+ _id: oid,
320
+ projectId: String(req.projectId)
321
+ });
322
+ if (!existing) return res.status(404).json({
323
+ success: false,
324
+ message: "Schedule not found."
325
+ });
326
+ if (existing.kind === SMOKE_KIND) {
327
+ return res.status(400).json({
328
+ success: false,
329
+ message: "The smoke schedule stays. Turn it off instead."
330
+ });
331
+ }
332
+ await db.collection(COLLECTION).deleteOne({
333
+ _id: oid,
334
+ projectId: String(req.projectId)
335
+ });
336
+ return res.json({
337
+ success: true
338
+ });
339
+ } catch (error) {
340
+ console.error("DELETE /scheduler/:id", error.message);
341
+ return res.status(500).json({
342
+ success: false,
343
+ message: "Failed to delete schedule."
344
+ });
345
+ }
346
+ });
347
+ module.exports = router;
@@ -0,0 +1,378 @@
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 parseKeyEnv(value) {
110
+ if (value == null || value === "") return null;
111
+ const name = String(value).trim();
112
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(name)) {
113
+ reject("Service key env must be an uppercase env name.");
114
+ }
115
+ return name;
116
+ }
117
+ function configuredServiceKey(row, env) {
118
+ const name = row && row.keyEnv;
119
+ if (!name) return "";
120
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(String(name))) {
121
+ reject("Service key is not configured.");
122
+ }
123
+ const value = env && env[name];
124
+ if (!value) reject("Service key is not configured.");
125
+ return String(value);
126
+ }
127
+ function parseScheduleCreate(body) {
128
+ const source = body || {};
129
+ const name = parseName(source.name);
130
+ const cron = String(source.cron || "").trim();
131
+ nextRunFromCron(cron, new Date());
132
+ const parsed = {
133
+ name,
134
+ cron,
135
+ method: parseMethod(source.method),
136
+ url: assertPublicHttpsUrl(source.url),
137
+ enabled: source.enabled === true
138
+ };
139
+ const keyEnv = parseKeyEnv(source.keyEnv);
140
+ if (keyEnv) parsed.keyEnv = keyEnv;
141
+ return parsed;
142
+ }
143
+ function parseSchedulePatch(body) {
144
+ const source = body || {};
145
+ const patch = {};
146
+ if (source.name !== undefined) patch.name = parseName(source.name);
147
+ if (source.cron !== undefined) {
148
+ const cron = String(source.cron || "").trim();
149
+ nextRunFromCron(cron, new Date());
150
+ patch.cron = cron;
151
+ }
152
+ if (source.method !== undefined) patch.method = parseMethod(source.method);
153
+ if (source.url !== undefined) patch.url = assertPublicHttpsUrl(source.url);
154
+ if (source.enabled !== undefined) {
155
+ if (typeof source.enabled !== "boolean") reject("Enabled must be true or false.");
156
+ patch.enabled = source.enabled;
157
+ }
158
+ if (source.keyEnv !== undefined) {
159
+ const keyEnv = parseKeyEnv(source.keyEnv);
160
+ if (!keyEnv) reject("Service key env must be an uppercase env name.");
161
+ patch.keyEnv = keyEnv;
162
+ }
163
+ if (!Object.keys(patch).length) reject("Nothing to update.");
164
+ return patch;
165
+ }
166
+ function scheduleSummary(row) {
167
+ return {
168
+ _id: String(row._id),
169
+ projectId: String(row.projectId || ""),
170
+ name: row.name || "",
171
+ kind: row.kind || "http",
172
+ cron: row.cron || "",
173
+ when: whenLabel(row.cron),
174
+ method: row.method || "GET",
175
+ url: row.url || "",
176
+ enabled: row.enabled === true,
177
+ nextRun: row.nextRun || null,
178
+ lastRunAt: row.lastRunAt || null,
179
+ lastOk: row.lastOk === true ? true : row.lastOk === false ? false : null,
180
+ lastStatus: row.lastStatus == null ? null : row.lastStatus,
181
+ lastError: row.lastError || null
182
+ };
183
+ }
184
+ function smokeScheduleDoc({
185
+ projectId,
186
+ url,
187
+ now
188
+ }) {
189
+ return {
190
+ projectId: String(projectId),
191
+ name: SMOKE_NAME,
192
+ kind: SMOKE_KIND,
193
+ cron: SMOKE_CRON,
194
+ method: "GET",
195
+ url,
196
+ enabled: false,
197
+ nextRun: null,
198
+ lastRunAt: null,
199
+ lastOk: null,
200
+ lastStatus: null,
201
+ lastError: null,
202
+ claimedUntil: null,
203
+ createdAt: now,
204
+ updatedAt: now
205
+ };
206
+ }
207
+ function readSmokeEnv(env = process.env) {
208
+ return {
209
+ projectId: String(env.SCHEDULER_SMOKE_PROJECT_ID || "").trim(),
210
+ url: String(env.SCHEDULER_SMOKE_URL || SMOKE_URL).trim()
211
+ };
212
+ }
213
+ async function ensureSmokeSchedule(db, {
214
+ projectId,
215
+ url,
216
+ now = new Date()
217
+ } = {}) {
218
+ const project = String(projectId || "").trim();
219
+ if (!project) return {
220
+ created: false
221
+ };
222
+ const target = assertPublicHttpsUrl(url || SMOKE_URL);
223
+ const existing = await db.collection(COLLECTION).findOne({
224
+ projectId: project,
225
+ kind: SMOKE_KIND
226
+ });
227
+ if (existing) return {
228
+ created: false,
229
+ id: existing._id
230
+ };
231
+ const doc = smokeScheduleDoc({
232
+ projectId: project,
233
+ url: target,
234
+ now
235
+ });
236
+ const result = await db.collection(COLLECTION).insertOne(doc);
237
+ return {
238
+ created: true,
239
+ id: result.insertedId
240
+ };
241
+ }
242
+ function updatedDoc(raw) {
243
+ if (!raw) return null;
244
+ if (raw.value && raw.value._id) return raw.value;
245
+ if (raw._id) return raw;
246
+ return null;
247
+ }
248
+ async function fireTarget(row, fetchImpl = global.fetch, env = process.env) {
249
+ let url;
250
+ try {
251
+ url = assertPublicHttpsUrl(row && row.url);
252
+ } catch (error) {
253
+ return {
254
+ ok: false,
255
+ status: null,
256
+ error: error.message
257
+ };
258
+ }
259
+ let method;
260
+ try {
261
+ method = parseMethod(row && row.method);
262
+ } catch (error) {
263
+ return {
264
+ ok: false,
265
+ status: null,
266
+ error: error.message
267
+ };
268
+ }
269
+ let serviceKey = "";
270
+ if (row && row.keyEnv) {
271
+ try {
272
+ serviceKey = configuredServiceKey(row, env);
273
+ } catch (error) {
274
+ return {
275
+ ok: false,
276
+ status: null,
277
+ error: "Service key is not configured."
278
+ };
279
+ }
280
+ }
281
+ const headers = {};
282
+ if (method === "POST") headers["Content-Type"] = "application/json";
283
+ if (serviceKey) headers["X-Service-Key"] = serviceKey;
284
+ const controller = new AbortController();
285
+ const timer = setTimeout(() => controller.abort(), FIRE_MS);
286
+ try {
287
+ const response = await fetchImpl(url, {
288
+ method,
289
+ redirect: "manual",
290
+ cache: "no-store",
291
+ signal: controller.signal,
292
+ headers: Object.keys(headers).length ? headers : undefined,
293
+ body: method === "POST" ? "{}" : undefined
294
+ });
295
+ const status = Number(response && response.status);
296
+ const ok = status >= 200 && status < 300;
297
+ return {
298
+ ok,
299
+ status: Number.isFinite(status) ? status : null,
300
+ error: ok ? null : `HTTP ${status}`
301
+ };
302
+ } catch (error) {
303
+ const timedOut = error && (error.name === "AbortError" || error.name === "TimeoutError");
304
+ return {
305
+ ok: false,
306
+ status: null,
307
+ error: timedOut ? "Timed out" : "Request failed"
308
+ };
309
+ } finally {
310
+ clearTimeout(timer);
311
+ }
312
+ }
313
+ async function runDue(db, now = new Date(), fetchImpl = global.fetch) {
314
+ const col = db.collection(COLLECTION);
315
+ const results = [];
316
+ for (let i = 0; i < TICK_LIMIT; i += 1) {
317
+ const claimedUntil = new Date(now.getTime() + CLAIM_MS);
318
+ const raw = await col.findOneAndUpdate(dueFilter(now), {
319
+ $set: {
320
+ claimedUntil,
321
+ updatedAt: now
322
+ }
323
+ }, {
324
+ returnDocument: "after"
325
+ });
326
+ const doc = updatedDoc(raw);
327
+ if (!doc) break;
328
+ const fired = await fireTarget(doc, fetchImpl);
329
+ let nextRun = null;
330
+ try {
331
+ nextRun = nextRunFromCron(doc.cron, now);
332
+ } catch (error) {
333
+ nextRun = new Date(now.getTime() + 60 * 1000);
334
+ }
335
+ await col.updateOne({
336
+ _id: doc._id
337
+ }, {
338
+ $set: {
339
+ nextRun,
340
+ lastRunAt: now,
341
+ lastOk: fired.ok,
342
+ lastStatus: fired.status,
343
+ lastError: fired.error,
344
+ claimedUntil: null,
345
+ updatedAt: new Date()
346
+ }
347
+ });
348
+ results.push({
349
+ id: String(doc._id),
350
+ ok: fired.ok === true
351
+ });
352
+ }
353
+ return results;
354
+ }
355
+ module.exports = {
356
+ COLLECTION,
357
+ SMOKE_KIND,
358
+ SMOKE_NAME,
359
+ SMOKE_CRON,
360
+ SMOKE_URL,
361
+ TICK_LIMIT,
362
+ TZ,
363
+ nextRunFromCron,
364
+ whenLabel,
365
+ isDue,
366
+ isClaimed,
367
+ dueFilter,
368
+ isBlockedHost,
369
+ assertPublicHttpsUrl,
370
+ parseScheduleCreate,
371
+ parseSchedulePatch,
372
+ scheduleSummary,
373
+ smokeScheduleDoc,
374
+ readSmokeEnv,
375
+ ensureSmokeSchedule,
376
+ fireTarget,
377
+ runDue
378
+ };
@@ -0,0 +1,310 @@
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
+ it("lands on 23:30 India time, not the next minute", () => {
28
+ const morning = new Date("2026-10-09T04:00:00.000Z");
29
+ const next = nextRunFromCron("30 23 * * *", morning);
30
+ expect(next.toISOString()).toBe("2026-10-09T18:00:00.000Z");
31
+ const afterClose = new Date("2026-10-09T18:00:01.000Z");
32
+ const tomorrow = nextRunFromCron("30 23 * * *", afterClose);
33
+ expect(tomorrow.toISOString()).toBe("2026-10-10T18:00:00.000Z");
34
+ });
35
+ });
36
+ describe("isDue", () => {
37
+ const now = new Date("2026-10-09T10:01:00.000Z");
38
+ it("is due when enabled and nextRun is past", () => {
39
+ expect(isDue({
40
+ enabled: true,
41
+ nextRun: new Date("2026-10-09T10:00:00.000Z")
42
+ }, now)).toBe(true);
43
+ });
44
+ it("skips a disabled or claimed row", () => {
45
+ expect(isDue({
46
+ enabled: false,
47
+ nextRun: new Date("2026-10-09T10:00:00.000Z")
48
+ }, now)).toBe(false);
49
+ expect(isDue({
50
+ enabled: true,
51
+ nextRun: new Date("2026-10-09T10:00:00.000Z"),
52
+ claimedUntil: new Date("2026-10-09T10:02:00.000Z")
53
+ }, now)).toBe(false);
54
+ });
55
+ });
56
+ describe("dueFilter", () => {
57
+ it("matches the due rule", () => {
58
+ const now = new Date("2026-10-09T10:01:00.000Z");
59
+ expect(dueFilter(now)).toEqual({
60
+ enabled: true,
61
+ nextRun: {
62
+ $lte: now
63
+ },
64
+ $or: [{
65
+ claimedUntil: null
66
+ }, {
67
+ claimedUntil: {
68
+ $lte: now
69
+ }
70
+ }]
71
+ });
72
+ });
73
+ });
74
+ describe("assertPublicHttpsUrl", () => {
75
+ it("keeps the host health URL", () => {
76
+ expect(assertPublicHttpsUrl(SMOKE_URL)).toBe(SMOKE_URL);
77
+ });
78
+ it("rejects private and non-https targets", () => {
79
+ expect(() => assertPublicHttpsUrl("http://powr-api.lawazia.tech/health")).toThrow("https");
80
+ expect(() => assertPublicHttpsUrl("https://127.0.0.1/health")).toThrow("not allowed");
81
+ expect(() => assertPublicHttpsUrl("https://169.254.169.254/")).toThrow("not allowed");
82
+ expect(() => assertPublicHttpsUrl("https://user:pass@powr-api.lawazia.tech/health")).toThrow("login");
83
+ });
84
+ });
85
+ describe("parseScheduleCreate", () => {
86
+ it("stores a public GET target", () => {
87
+ expect(parseScheduleCreate({
88
+ name: " Host health ",
89
+ cron: "* * * * *",
90
+ url: SMOKE_URL
91
+ })).toEqual({
92
+ name: "Host health",
93
+ cron: "* * * * *",
94
+ method: "GET",
95
+ url: SMOKE_URL,
96
+ enabled: false
97
+ });
98
+ });
99
+ it("keeps an uppercase service-key env name", () => {
100
+ expect(parseScheduleCreate({
101
+ name: "Day close",
102
+ cron: "30 23 * * *",
103
+ method: "POST",
104
+ url: "https://example.com/ops/day-close",
105
+ keyEnv: "URBANSTALL_SERVICE_KEY"
106
+ }).keyEnv).toBe("URBANSTALL_SERVICE_KEY");
107
+ });
108
+ it("rejects a service-key value pasted as the env name", () => {
109
+ expect(() => parseScheduleCreate({
110
+ name: "Day close",
111
+ cron: "30 23 * * *",
112
+ method: "POST",
113
+ url: "https://example.com/ops/day-close",
114
+ keyEnv: "not-an-env-name"
115
+ })).toThrow("uppercase env name");
116
+ });
117
+ });
118
+ describe("parseSchedulePatch", () => {
119
+ it("accepts on/off", () => {
120
+ expect(parseSchedulePatch({
121
+ enabled: true
122
+ })).toEqual({
123
+ enabled: true
124
+ });
125
+ });
126
+ it("rejects an empty patch", () => {
127
+ expect(() => parseSchedulePatch({})).toThrow("Nothing to update.");
128
+ });
129
+ });
130
+ describe("scheduleSummary", () => {
131
+ it("labels every minute", () => {
132
+ const row = scheduleSummary({
133
+ _id: "abc",
134
+ projectId: "p1",
135
+ name: "Host health",
136
+ kind: "smoke",
137
+ cron: "* * * * *",
138
+ method: "GET",
139
+ url: SMOKE_URL,
140
+ enabled: false,
141
+ lastOk: false,
142
+ lastError: "HTTP 500"
143
+ });
144
+ expect(whenLabel(row.cron)).toBe("Every minute");
145
+ expect(row.when).toBe("Every minute");
146
+ expect(row.lastOk).toBe(false);
147
+ expect(row.lastError).toBe("HTTP 500");
148
+ });
149
+ });
150
+ describe("ensureSmokeSchedule", () => {
151
+ function memoryDb() {
152
+ const rows = [];
153
+ return {
154
+ rows,
155
+ collection() {
156
+ return {
157
+ async findOne(query) {
158
+ return rows.find(row => row.projectId === query.projectId && row.kind === query.kind) || null;
159
+ },
160
+ async insertOne(doc) {
161
+ const stored = {
162
+ ...doc,
163
+ _id: "smoke-1"
164
+ };
165
+ rows.push(stored);
166
+ return {
167
+ insertedId: stored._id
168
+ };
169
+ }
170
+ };
171
+ }
172
+ };
173
+ }
174
+ it("inserts one disabled smoke row and does not clobber it", async () => {
175
+ const db = memoryDb();
176
+ const first = await ensureSmokeSchedule(db, {
177
+ projectId: "excelrs",
178
+ url: SMOKE_URL
179
+ });
180
+ expect(first.created).toBe(true);
181
+ expect(db.rows[0].enabled).toBe(false);
182
+ db.rows[0].enabled = true;
183
+ const second = await ensureSmokeSchedule(db, {
184
+ projectId: "excelrs",
185
+ url: SMOKE_URL
186
+ });
187
+ expect(second.created).toBe(false);
188
+ expect(db.rows).toHaveLength(1);
189
+ expect(db.rows[0].enabled).toBe(true);
190
+ });
191
+ it("skips when no project is configured", async () => {
192
+ const db = memoryDb();
193
+ const result = await ensureSmokeSchedule(db, {
194
+ projectId: " "
195
+ });
196
+ expect(result.created).toBe(false);
197
+ expect(db.rows).toHaveLength(0);
198
+ });
199
+ });
200
+ describe("fireTarget", () => {
201
+ it("records HTTP 500 as a fail without calling a blocked host", async () => {
202
+ const fetchImpl = jest.fn(async () => ({
203
+ status: 500
204
+ }));
205
+ const failed = await fireTarget({
206
+ url: SMOKE_URL,
207
+ method: "GET"
208
+ }, fetchImpl);
209
+ expect(failed).toEqual({
210
+ ok: false,
211
+ status: 500,
212
+ error: "HTTP 500"
213
+ });
214
+ const blocked = await fireTarget({
215
+ url: "https://127.0.0.1/health",
216
+ method: "GET"
217
+ }, fetchImpl);
218
+ expect(blocked.ok).toBe(false);
219
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
220
+ });
221
+ it("records a 200 as ok", async () => {
222
+ const ok = await fireTarget({
223
+ url: SMOKE_URL,
224
+ method: "GET"
225
+ }, async () => ({
226
+ status: 200
227
+ }));
228
+ expect(ok.ok).toBe(true);
229
+ expect(ok.error).toBe(null);
230
+ });
231
+ it("sends the product service key on POST and does not call when it is missing", async () => {
232
+ const fetchImpl = jest.fn(async () => ({
233
+ status: 200
234
+ }));
235
+ const ok = await fireTarget({
236
+ url: "https://example.com/ops/day-close",
237
+ method: "POST",
238
+ keyEnv: "URBANSTALL_SERVICE_KEY"
239
+ }, fetchImpl, {
240
+ URBANSTALL_SERVICE_KEY: "test-key"
241
+ });
242
+ expect(ok.ok).toBe(true);
243
+ expect(fetchImpl).toHaveBeenCalledWith("https://example.com/ops/day-close", expect.objectContaining({
244
+ method: "POST",
245
+ body: "{}",
246
+ headers: {
247
+ "Content-Type": "application/json",
248
+ "X-Service-Key": "test-key"
249
+ }
250
+ }));
251
+ const skipped = jest.fn();
252
+ const missing = await fireTarget({
253
+ url: "https://example.com/ops/day-close",
254
+ method: "POST",
255
+ keyEnv: "URBANSTALL_SERVICE_KEY"
256
+ }, skipped, {});
257
+ expect(missing).toEqual({
258
+ ok: false,
259
+ status: null,
260
+ error: "Service key is not configured."
261
+ });
262
+ expect(skipped).not.toHaveBeenCalled();
263
+ });
264
+ });
265
+ describe("runDue", () => {
266
+ it("fires a due row once and stores the fail", async () => {
267
+ const now = new Date("2026-10-09T10:01:00.000Z");
268
+ const rows = [{
269
+ _id: "job-1",
270
+ enabled: true,
271
+ cron: "* * * * *",
272
+ method: "GET",
273
+ url: SMOKE_URL,
274
+ nextRun: new Date("2026-10-09T10:00:00.000Z"),
275
+ claimedUntil: null
276
+ }];
277
+ const col = {
278
+ async findOneAndUpdate(filter, update) {
279
+ const row = rows.find(item => item.enabled === filter.enabled && item.nextRun <= filter.nextRun.$lte && !item.claimedUntil);
280
+ if (!row) return null;
281
+ Object.assign(row, update.$set);
282
+ return {
283
+ ...row
284
+ };
285
+ },
286
+ async updateOne(filter, update) {
287
+ const row = rows.find(item => item._id === filter._id);
288
+ Object.assign(row, update.$set);
289
+ }
290
+ };
291
+ const db = {
292
+ collection: () => col
293
+ };
294
+ const results = await runDue(db, now, async () => ({
295
+ status: 404
296
+ }));
297
+ expect(results).toEqual([{
298
+ id: "job-1",
299
+ ok: false
300
+ }]);
301
+ expect(rows[0].lastOk).toBe(false);
302
+ expect(rows[0].lastError).toBe("HTTP 404");
303
+ expect(rows[0].claimedUntil).toBe(null);
304
+ expect(rows[0].nextRun.getTime()).toBeGreaterThan(now.getTime());
305
+ const again = await runDue(db, now, async () => ({
306
+ status: 200
307
+ }));
308
+ expect(again).toEqual([]);
309
+ });
310
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.15.3",
3
+ "version": "4.16.1",
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",