@webiny/api-scheduler-standalone 6.6.0-alpha.10 → 6.6.0-alpha.12
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/{BreeSchedulerService.d.ts → TimerSchedulerService.d.ts} +16 -10
- package/{BreeSchedulerService.js → TimerSchedulerService.js} +49 -53
- package/TimerSchedulerService.js.map +1 -0
- package/index.d.ts +2 -2
- package/index.js +1 -1
- package/package.json +7 -7
- package/BreeSchedulerService.js.map +0 -1
- package/jobs/pollWorker.d.ts +0 -1
- package/jobs/pollWorker.js +0 -4
- package/jobs/pollWorker.js.map +0 -1
- package/static/assets/pollWorker.js +0 -2
|
@@ -6,29 +6,35 @@ export interface IPendingAction {
|
|
|
6
6
|
tenant: string;
|
|
7
7
|
scheduledFor: Date;
|
|
8
8
|
}
|
|
9
|
-
export interface
|
|
9
|
+
export interface ITimerSchedulerServiceParams {
|
|
10
10
|
logger: Logger.Interface;
|
|
11
11
|
runAction: (id: string, namespace: string, tenant: string) => Promise<void>;
|
|
12
|
+
maxConcurrentActions?: number;
|
|
12
13
|
}
|
|
13
14
|
/**
|
|
14
|
-
* One-
|
|
15
|
-
* SINGLETON (started once at boot): it holds this process's live timers for
|
|
16
|
-
* records its own tenant and `runAction` is called with it (the action runs
|
|
17
|
-
* the tenant can't be read from a request context).
|
|
15
|
+
* One in-process timer per scheduled action, the standalone counterpart of an EventBridge schedule.
|
|
16
|
+
* This is a long-lived root SINGLETON (started once at boot): it holds this process's live timers for
|
|
17
|
+
* ALL tenants, so each job records its own tenant and `runAction` is called with it (the action runs
|
|
18
|
+
* outside any request, so the tenant can't be read from a request context).
|
|
18
19
|
*
|
|
19
20
|
* With several processes, each holds its own timers for the same actions: `recover` runs again on a
|
|
20
21
|
* timer to arm what this process has not seen, and whoever supplies `runAction` makes sure an action
|
|
21
22
|
* runs once.
|
|
22
23
|
*/
|
|
23
|
-
export declare class
|
|
24
|
-
private readonly bree;
|
|
24
|
+
export declare class TimerSchedulerService implements SchedulerService.Interface {
|
|
25
25
|
private readonly jobs;
|
|
26
26
|
private readonly logger;
|
|
27
27
|
private readonly runAction;
|
|
28
|
+
private readonly maxConcurrentActions;
|
|
28
29
|
private readonly running;
|
|
30
|
+
private readonly slots;
|
|
29
31
|
private stopped;
|
|
30
|
-
constructor(params:
|
|
32
|
+
constructor(params: ITimerSchedulerServiceParams);
|
|
31
33
|
start(): Promise<void>;
|
|
34
|
+
/**
|
|
35
|
+
* Clears every timer and keeps waiting triggers from starting. Triggers already running are not
|
|
36
|
+
* interrupted; `waitForRunning` waits for them.
|
|
37
|
+
*/
|
|
32
38
|
stop(): Promise<void>;
|
|
33
39
|
/**
|
|
34
40
|
* Resolves once every trigger already started has finished, or after `timeoutMs`. Call it after
|
|
@@ -42,13 +48,13 @@ export declare class BreeSchedulerService implements SchedulerService.Interface
|
|
|
42
48
|
/**
|
|
43
49
|
* (Re)arm timers for a batch of persisted pending actions. Runs at boot (per tenant) to restore
|
|
44
50
|
* schedules after a restart, and then on a timer, so this process also arms actions another
|
|
45
|
-
* process scheduled or moved. Overdue actions
|
|
51
|
+
* process scheduled or moved. Overdue actions run one by one, before the next action is looked at.
|
|
46
52
|
*
|
|
47
53
|
* An action already armed for the same time is left as it is; one armed for a different time was
|
|
48
54
|
* moved by another process and is re-armed.
|
|
49
55
|
*/
|
|
50
56
|
recover(pendingActions: IPendingAction[]): Promise<void>;
|
|
51
57
|
private arm;
|
|
58
|
+
private disarm;
|
|
52
59
|
private trigger;
|
|
53
|
-
private safeRemove;
|
|
54
60
|
}
|
|
@@ -1,33 +1,26 @@
|
|
|
1
|
-
import bree from "bree";
|
|
2
|
-
import { fileURLToPath } from "node:url";
|
|
3
1
|
import { WebinyError } from "@webiny/error";
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
import { ConcurrencySlots } from "@webiny/utils/ConcurrencySlots.js";
|
|
3
|
+
const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
|
|
4
|
+
const DEFAULT_MAX_CONCURRENT_ACTIONS = 10;
|
|
5
|
+
class TimerSchedulerService {
|
|
6
6
|
constructor(params){
|
|
7
7
|
this.jobs = new Map();
|
|
8
8
|
this.running = new Set();
|
|
9
9
|
this.stopped = false;
|
|
10
10
|
this.logger = params.logger;
|
|
11
11
|
this.runAction = params.runAction;
|
|
12
|
-
this.
|
|
13
|
-
|
|
14
|
-
jobs: [],
|
|
15
|
-
logger: false,
|
|
16
|
-
workerMessageHandler: async ({ name })=>{
|
|
17
|
-
const job = this.jobs.get(name);
|
|
18
|
-
if (!job) return;
|
|
19
|
-
this.jobs.delete(name);
|
|
20
|
-
await this.trigger(name, job.namespace, job.tenant);
|
|
21
|
-
}
|
|
22
|
-
});
|
|
12
|
+
this.maxConcurrentActions = params.maxConcurrentActions ?? DEFAULT_MAX_CONCURRENT_ACTIONS;
|
|
13
|
+
this.slots = new ConcurrencySlots(this.maxConcurrentActions);
|
|
23
14
|
}
|
|
24
15
|
async start() {
|
|
25
16
|
this.stopped = false;
|
|
26
|
-
|
|
17
|
+
this.slots.open();
|
|
27
18
|
}
|
|
28
19
|
async stop() {
|
|
29
20
|
this.stopped = true;
|
|
30
|
-
|
|
21
|
+
for (const job of this.jobs.values())clearTimeout(job.timer);
|
|
22
|
+
this.jobs.clear();
|
|
23
|
+
this.slots.close();
|
|
31
24
|
}
|
|
32
25
|
async waitForRunning(timeoutMs) {
|
|
33
26
|
let timer;
|
|
@@ -55,11 +48,7 @@ class BreeSchedulerService {
|
|
|
55
48
|
tenant
|
|
56
49
|
});
|
|
57
50
|
if (exists) return this.update(params);
|
|
58
|
-
|
|
59
|
-
namespace,
|
|
60
|
-
tenant,
|
|
61
|
-
scheduledFor: scheduleFor
|
|
62
|
-
});
|
|
51
|
+
this.arm(id, namespace, tenant, scheduleFor);
|
|
63
52
|
}
|
|
64
53
|
async update(params) {
|
|
65
54
|
const { id, scheduleFor } = params;
|
|
@@ -67,14 +56,14 @@ class BreeSchedulerService {
|
|
|
67
56
|
scheduleFor,
|
|
68
57
|
id
|
|
69
58
|
});
|
|
70
|
-
|
|
59
|
+
this.disarm(id);
|
|
71
60
|
await this.create(params);
|
|
72
61
|
}
|
|
73
62
|
async delete(params) {
|
|
74
63
|
const { id } = params;
|
|
75
64
|
const exists = await this.exists(params);
|
|
76
65
|
if (!exists) throw new WebinyError(`Cannot delete schedule "${id}" because it does not exist.`);
|
|
77
|
-
|
|
66
|
+
this.disarm(id);
|
|
78
67
|
}
|
|
79
68
|
async exists(params) {
|
|
80
69
|
const { id } = params;
|
|
@@ -90,49 +79,56 @@ class BreeSchedulerService {
|
|
|
90
79
|
}
|
|
91
80
|
const armed = this.jobs.get(action.id);
|
|
92
81
|
if (!armed || armed.scheduledFor.getTime() !== action.scheduledFor.getTime()) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
namespace: action.namespace,
|
|
96
|
-
tenant: action.tenant,
|
|
97
|
-
scheduledFor: action.scheduledFor
|
|
98
|
-
});
|
|
82
|
+
this.disarm(action.id);
|
|
83
|
+
this.arm(action.id, action.namespace, action.tenant, action.scheduledFor);
|
|
99
84
|
}
|
|
100
85
|
}
|
|
101
86
|
}
|
|
102
|
-
|
|
87
|
+
arm(id, namespace, tenant, scheduledFor) {
|
|
103
88
|
if (this.stopped) return;
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
89
|
+
const untilDue = scheduledFor.getTime() - Date.now();
|
|
90
|
+
const capped = Math.min(untilDue, MAX_TIMER_DELAY_MS);
|
|
91
|
+
const delay = Math.max(capped, 0);
|
|
92
|
+
const timer = setTimeout(()=>{
|
|
93
|
+
if (this.jobs.get(id)?.timer !== timer) return;
|
|
94
|
+
this.jobs.delete(id);
|
|
95
|
+
if (scheduledFor.getTime() > Date.now()) return void this.arm(id, namespace, tenant, scheduledFor);
|
|
96
|
+
this.trigger(id, namespace, tenant);
|
|
97
|
+
}, delay);
|
|
98
|
+
timer.unref();
|
|
99
|
+
this.jobs.set(id, {
|
|
100
|
+
namespace,
|
|
101
|
+
tenant,
|
|
102
|
+
scheduledFor,
|
|
103
|
+
timer
|
|
109
104
|
});
|
|
110
|
-
|
|
105
|
+
}
|
|
106
|
+
disarm(id) {
|
|
107
|
+
const job = this.jobs.get(id);
|
|
108
|
+
if (!job) return;
|
|
109
|
+
clearTimeout(job.timer);
|
|
110
|
+
this.jobs.delete(id);
|
|
111
111
|
}
|
|
112
112
|
async trigger(id, namespace, tenant) {
|
|
113
|
-
|
|
113
|
+
const granted = await this.slots.acquire();
|
|
114
|
+
if (!granted) return;
|
|
115
|
+
if (this.stopped) return void this.slots.release();
|
|
114
116
|
const triggered = this.runAction(id, namespace, tenant);
|
|
115
117
|
this.running.add(triggered);
|
|
116
118
|
try {
|
|
117
119
|
await triggered;
|
|
120
|
+
} catch (error) {
|
|
121
|
+
this.logger.error({
|
|
122
|
+
error,
|
|
123
|
+
id,
|
|
124
|
+
tenant
|
|
125
|
+
}, "[scheduler] scheduled action failed");
|
|
118
126
|
} finally{
|
|
119
127
|
this.running.delete(triggered);
|
|
120
|
-
|
|
121
|
-
}
|
|
122
|
-
async safeRemove(id) {
|
|
123
|
-
this.jobs.delete(id);
|
|
124
|
-
try {
|
|
125
|
-
await this.bree.stop(id);
|
|
126
|
-
} catch {
|
|
127
|
-
this.logger.debug(`Could not stop bree job "${id}" — it may have already fired.`);
|
|
128
|
-
}
|
|
129
|
-
try {
|
|
130
|
-
await this.bree.remove(id);
|
|
131
|
-
} catch {
|
|
132
|
-
this.logger.debug(`Could not remove bree job "${id}" — it may have already been removed.`);
|
|
128
|
+
this.slots.release();
|
|
133
129
|
}
|
|
134
130
|
}
|
|
135
131
|
}
|
|
136
|
-
export {
|
|
132
|
+
export { TimerSchedulerService };
|
|
137
133
|
|
|
138
|
-
//# sourceMappingURL=
|
|
134
|
+
//# sourceMappingURL=TimerSchedulerService.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TimerSchedulerService.js","sources":["../src/TimerSchedulerService.ts"],"sourcesContent":["import { WebinyError } from \"@webiny/error\";\nimport {\n type ISchedulerServiceCreateParams,\n type ISchedulerServiceUpdateParams,\n SchedulerService\n} from \"@webiny/api-scheduler/shared/abstractions.js\";\nimport type { Logger } from \"@webiny/api-core/features/logger/abstractions.js\";\nimport { ConcurrencySlots } from \"@webiny/utils/ConcurrencySlots.js\";\n\n/*\n * The longest delay `setTimeout` takes (2^31 - 1 ms, about 24.8 days). A longer one fires at once, so\n * an action due later than this gets a timer for this long and is re-armed when it fires.\n */\nconst MAX_TIMER_DELAY_MS = 2 ** 31 - 1;\n\n/*\n * How many actions this process runs at the same time. Each one runs in a request container of its\n * own and talks to the database, so hundreds due at the same moment are run this many at a time\n * rather than all at once.\n */\nconst DEFAULT_MAX_CONCURRENT_ACTIONS = 10;\n\nexport interface IPendingAction {\n id: string;\n namespace: string;\n tenant: string;\n scheduledFor: Date;\n}\n\ninterface IScheduledJob {\n namespace: string;\n tenant: string;\n scheduledFor: Date;\n timer: ReturnType<typeof setTimeout>;\n}\n\nexport interface ITimerSchedulerServiceParams {\n logger: Logger.Interface;\n runAction: (id: string, namespace: string, tenant: string) => Promise<void>;\n maxConcurrentActions?: number;\n}\n\n/**\n * One in-process timer per scheduled action, the standalone counterpart of an EventBridge schedule.\n * This is a long-lived root SINGLETON (started once at boot): it holds this process's live timers for\n * ALL tenants, so each job records its own tenant and `runAction` is called with it (the action runs\n * outside any request, so the tenant can't be read from a request context).\n *\n * With several processes, each holds its own timers for the same actions: `recover` runs again on a\n * timer to arm what this process has not seen, and whoever supplies `runAction` makes sure an action\n * runs once.\n */\nexport class TimerSchedulerService implements SchedulerService.Interface {\n private readonly jobs = new Map<string, IScheduledJob>();\n private readonly logger;\n private readonly runAction;\n private readonly maxConcurrentActions;\n // Triggers started and not finished yet, so a shutdown can wait for them.\n private readonly running = new Set<Promise<void>>();\n // Triggers take one of these before they run; the rest wait in line. Closed by `stop`.\n private readonly slots: ConcurrencySlots;\n /*\n * Set by `stop`. A recovery that started before the stop runs overdue actions one by one and can\n * still be going after it; this keeps it from starting more actions or arming timers. Actions it\n * skips stay stored and are picked up by another process's recovery.\n */\n private stopped = false;\n\n public constructor(params: ITimerSchedulerServiceParams) {\n this.logger = params.logger;\n this.runAction = params.runAction;\n this.maxConcurrentActions = params.maxConcurrentActions ?? DEFAULT_MAX_CONCURRENT_ACTIONS;\n this.slots = new ConcurrencySlots(this.maxConcurrentActions);\n }\n\n public async start(): Promise<void> {\n this.stopped = false;\n // Actions still running from before a `stop` keep their slots, so they count against the limit.\n this.slots.open();\n }\n\n /**\n * Clears every timer and keeps waiting triggers from starting. Triggers already running are not\n * interrupted; `waitForRunning` waits for them.\n */\n public async stop(): Promise<void> {\n this.stopped = true;\n for (const job of this.jobs.values()) {\n clearTimeout(job.timer);\n }\n this.jobs.clear();\n this.slots.close();\n }\n\n /**\n * Resolves once every trigger already started has finished, or after `timeoutMs`. Call it after\n * `stop`, which keeps new ones from starting.\n */\n public async waitForRunning(timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>(resolve => {\n timer = setTimeout(resolve, timeoutMs);\n });\n const running = Promise.allSettled([...this.running]);\n await Promise.race([running, timeout]);\n clearTimeout(timer);\n }\n\n public async create(params: ISchedulerServiceCreateParams): Promise<void> {\n const { id, namespace, scheduleFor, tenant } = params;\n\n if (scheduleFor <= new Date()) {\n throw new WebinyError(\n `Cannot create a schedule for \"${id}\" with date in the past`,\n \"INVALID_SCHEDULE_DATE\",\n { scheduleFor, id }\n );\n }\n\n const exists = await this.exists({\n id,\n namespace,\n tenant\n });\n if (exists) {\n return this.update(params);\n }\n\n this.arm(id, namespace, tenant, scheduleFor);\n }\n\n public async update(params: ISchedulerServiceUpdateParams): Promise<void> {\n const { id, scheduleFor } = params;\n\n if (scheduleFor <= new Date()) {\n throw new WebinyError(\n `Cannot update an existing schedule for \"${id}\" with date in the past`,\n \"INVALID_SCHEDULE_DATE\",\n { scheduleFor, id }\n );\n }\n\n this.disarm(id);\n await this.create(params);\n }\n\n public async delete(params: SchedulerService.DeleteParams): Promise<void> {\n const { id } = params;\n const exists = await this.exists(params);\n if (!exists) {\n throw new WebinyError(`Cannot delete schedule \"${id}\" because it does not exist.`);\n }\n\n this.disarm(id);\n }\n\n public async exists(params: SchedulerService.ExistsParams): Promise<boolean> {\n const { id } = params;\n return this.jobs.has(id);\n }\n\n /**\n * (Re)arm timers for a batch of persisted pending actions. Runs at boot (per tenant) to restore\n * schedules after a restart, and then on a timer, so this process also arms actions another\n * process scheduled or moved. Overdue actions run one by one, before the next action is looked at.\n *\n * An action already armed for the same time is left as it is; one armed for a different time was\n * moved by another process and is re-armed.\n */\n public async recover(pendingActions: IPendingAction[]): Promise<void> {\n const now = new Date();\n\n for (const action of pendingActions) {\n if (this.stopped) {\n return;\n }\n if (action.scheduledFor <= now) {\n await this.trigger(action.id, action.namespace, action.tenant);\n continue;\n }\n\n const armed = this.jobs.get(action.id);\n if (armed && armed.scheduledFor.getTime() === action.scheduledFor.getTime()) {\n continue;\n }\n\n this.disarm(action.id);\n this.arm(action.id, action.namespace, action.tenant, action.scheduledFor);\n }\n }\n\n private arm(id: string, namespace: string, tenant: string, scheduledFor: Date): void {\n if (this.stopped) {\n return;\n }\n\n const untilDue = scheduledFor.getTime() - Date.now();\n const capped = Math.min(untilDue, MAX_TIMER_DELAY_MS);\n const delay = Math.max(capped, 0);\n const timer = setTimeout(() => {\n if (this.jobs.get(id)?.timer !== timer) {\n return;\n }\n this.jobs.delete(id);\n if (scheduledFor.getTime() > Date.now()) {\n this.arm(id, namespace, tenant, scheduledFor);\n return;\n }\n void this.trigger(id, namespace, tenant);\n }, delay);\n // An armed action alone should not keep the process running.\n timer.unref();\n\n this.jobs.set(id, { namespace, tenant, scheduledFor, timer });\n }\n\n private disarm(id: string): void {\n const job = this.jobs.get(id);\n if (!job) {\n return;\n }\n clearTimeout(job.timer);\n this.jobs.delete(id);\n }\n\n private async trigger(id: string, namespace: string, tenant: string): Promise<void> {\n const granted = await this.slots.acquire();\n if (!granted) {\n return;\n }\n // Granted just before a `stop`, which only turns away those still waiting.\n if (this.stopped) {\n this.slots.release();\n return;\n }\n const triggered = this.runAction(id, namespace, tenant);\n this.running.add(triggered);\n try {\n await triggered;\n } catch (error) {\n this.logger.error({ error, id, tenant }, \"[scheduler] scheduled action failed\");\n } finally {\n this.running.delete(triggered);\n this.slots.release();\n }\n }\n}\n"],"names":["MAX_TIMER_DELAY_MS","DEFAULT_MAX_CONCURRENT_ACTIONS","TimerSchedulerService","params","Map","Set","ConcurrencySlots","job","clearTimeout","timeoutMs","timer","timeout","Promise","resolve","setTimeout","running","id","namespace","scheduleFor","tenant","Date","WebinyError","exists","pendingActions","now","action","armed","scheduledFor","untilDue","capped","Math","delay","granted","triggered","error"],"mappings":";;AAaA,MAAMA,qBAAqB,KAAK,KAAK;AAOrC,MAAMC,iCAAiC;AAgChC,MAAMC;IAgBT,YAAmBC,MAAoC,CAAE;aAfxC,IAAI,GAAG,IAAIC;aAKX,OAAO,GAAG,IAAIC;QAO9B,KACO,OAAO,GAAG;QAGd,IAAI,CAAC,MAAM,GAAGF,OAAO,MAAM;QAC3B,IAAI,CAAC,SAAS,GAAGA,OAAO,SAAS;QACjC,IAAI,CAAC,oBAAoB,GAAGA,OAAO,oBAAoB,IAAIF;QAC3D,IAAI,CAAC,KAAK,GAAG,IAAIK,iBAAiB,IAAI,CAAC,oBAAoB;IAC/D;IAEA,MAAa,QAAuB;QAChC,IAAI,CAAC,OAAO,GAAG;QAEf,IAAI,CAAC,KAAK,CAAC,IAAI;IACnB;IAMA,MAAa,OAAsB;QAC/B,IAAI,CAAC,OAAO,GAAG;QACf,KAAK,MAAMC,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,GAC9BC,aAAaD,IAAI,KAAK;QAE1B,IAAI,CAAC,IAAI,CAAC,KAAK;QACf,IAAI,CAAC,KAAK,CAAC,KAAK;IACpB;IAMA,M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WE;QACrC,GAAGY;QAEHrB,MAAM,KAAK;QAEX,IAAI,CAAC,IAAI,CAAC,GAAG,CAACM,IAAI;YAAEC;YAAWE;YAAQQ;YAAcjB;QAAM;IAC/D;IAEQ,OAAOM,EAAU,EAAQ;QAC7B,MAAMT,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAACS;QAC1B,IAAI,CAACT,KACD;QAEJC,aAAaD,IAAI,KAAK;QACtB,IAAI,CAAC,IAAI,CAAC,MAAM,CAACS;IACrB;IAEA,MAAc,QAAQA,EAAU,EAAEC,SAAiB,EAAEE,MAAc,EAAiB;QAChF,MAAMa,UAAU,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO;QACxC,IAAI,CAACA,SACD;QAGJ,IAAI,IAAI,CAAC,OAAO,EAAE,YACd,IAAI,CAAC,KAAK,CAAC,OAAO;QAGtB,MAAMC,YAAY,IAAI,CAAC,SAAS,CAACjB,IAAIC,WAAWE;QAChD,IAAI,CAAC,OAAO,CAAC,GAAG,CAACc;QACjB,IAAI;YACA,MAAMA;QACV,EAAE,OAAOC,OAAO;YACZ,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;gBAAEA;gBAAOlB;gBAAIG;YAAO,GAAG;QAC7C,SAAU;YACN,IAAI,CAAC,OAAO,CAAC,MAAM,CAACc;YACpB,IAAI,CAAC,KAAK,CAAC,OAAO;QACtB;IACJ;AACJ"}
|
package/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export type { IPendingAction,
|
|
1
|
+
export { TimerSchedulerService } from "./TimerSchedulerService.js";
|
|
2
|
+
export type { IPendingAction, ITimerSchedulerServiceParams } from "./TimerSchedulerService.js";
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { TimerSchedulerService } from "./TimerSchedulerService.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webiny/api-scheduler-standalone",
|
|
3
|
-
"version": "6.6.0-alpha.
|
|
3
|
+
"version": "6.6.0-alpha.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./index.js",
|
|
@@ -15,16 +15,16 @@
|
|
|
15
15
|
"scheduler:server"
|
|
16
16
|
],
|
|
17
17
|
"author": "Webiny Ltd",
|
|
18
|
-
"description": "Standalone
|
|
18
|
+
"description": "Standalone in-process timer implementation for the Webiny action scheduler.",
|
|
19
19
|
"license": "MIT",
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@webiny/api-core": "6.6.0-alpha.
|
|
22
|
-
"@webiny/api-scheduler": "6.6.0-alpha.
|
|
23
|
-
"@webiny/error": "6.6.0-alpha.
|
|
24
|
-
"
|
|
21
|
+
"@webiny/api-core": "6.6.0-alpha.12",
|
|
22
|
+
"@webiny/api-scheduler": "6.6.0-alpha.12",
|
|
23
|
+
"@webiny/error": "6.6.0-alpha.12",
|
|
24
|
+
"@webiny/utils": "6.6.0-alpha.12"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"@webiny/build-tools": "6.6.0-alpha.
|
|
27
|
+
"@webiny/build-tools": "6.6.0-alpha.12",
|
|
28
28
|
"typescript": "7.0.2",
|
|
29
29
|
"vitest": "5.0.5"
|
|
30
30
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"BreeSchedulerService.js","sources":["../src/BreeSchedulerService.ts"],"sourcesContent":["import Bree from \"bree\";\nimport { fileURLToPath } from \"node:url\";\nimport { WebinyError } from \"@webiny/error\";\nimport {\n type ISchedulerServiceCreateParams,\n type ISchedulerServiceUpdateParams,\n SchedulerService\n} from \"@webiny/api-scheduler/shared/abstractions.js\";\nimport type { Logger } from \"@webiny/api-core/features/logger/abstractions.js\";\n\n// bree loads this file at runtime via `new Worker(path)`. Referencing it through `new URL` (rather\n// than path.join) makes the app bundler emit pollWorker into build/ as an asset, resolved relative\n// to this module (the server build sets assetPrefix \"auto\"); fileURLToPath then hands bree a plain\n// path string. Un-bundled (dev), import.meta.url is real and it resolves to the dist/jobs file.\nconst workerPath = fileURLToPath(new URL(\"./jobs/pollWorker.js\", import.meta.url));\n\nexport interface IPendingAction {\n id: string;\n namespace: string;\n tenant: string;\n scheduledFor: Date;\n}\n\ninterface IScheduledJob {\n namespace: string;\n tenant: string;\n scheduledFor: Date;\n}\n\nexport interface IBreeSchedulerServiceParams {\n logger: Logger.Interface;\n runAction: (id: string, namespace: string, tenant: string) => Promise<void>;\n}\n\n/**\n * One-shot bree job per scheduled action — mirrors EventBridge behaviour. This is a long-lived root\n * SINGLETON (started once at boot): it holds this process's live timers for ALL tenants, so each job\n * records its own tenant and `runAction` is called with it (the action runs outside any request, so\n * the tenant can't be read from a request context).\n *\n * With several processes, each holds its own timers for the same actions: `recover` runs again on a\n * timer to arm what this process has not seen, and whoever supplies `runAction` makes sure an action\n * runs once.\n */\nexport class BreeSchedulerService implements SchedulerService.Interface {\n private readonly bree;\n private readonly jobs = new Map<string, IScheduledJob>();\n private readonly logger;\n private readonly runAction;\n // Triggers started and not finished yet, so a shutdown can wait for them.\n private readonly running = new Set<Promise<void>>();\n /*\n * Set by `stop`. A recovery that started before the stop runs overdue actions one by one and can\n * still be going after it; this keeps it from starting more actions or arming timers on a Bree\n * that is stopped. Actions it skips stay stored and are picked up by another process's recovery.\n */\n private stopped = false;\n\n public constructor(params: IBreeSchedulerServiceParams) {\n this.logger = params.logger;\n this.runAction = params.runAction;\n\n this.bree = new Bree({\n root: false,\n jobs: [],\n logger: false,\n /*\n * Bree runs each job as a script in a worker thread; it cannot call a function. Running an\n * action needs the DI container, database and tenancy, which only the main thread has, so\n * the job script (`jobs/pollWorker.js`) only posts \"poll\" and exits. Bree passes that\n * message here, in the main thread of the Webiny API process that started Bree, and the\n * action runs in this process. `name` is the job's name, which is the action id.\n */\n workerMessageHandler: async ({ name }) => {\n const job = this.jobs.get(name);\n if (!job) {\n return;\n }\n\n this.jobs.delete(name);\n await this.trigger(name, job.namespace, job.tenant);\n }\n });\n }\n\n public async start(): Promise<void> {\n this.stopped = false;\n await this.bree.start();\n }\n\n public async stop(): Promise<void> {\n this.stopped = true;\n await this.bree.stop();\n }\n\n /**\n * Resolves once every trigger already started has finished, or after `timeoutMs`. Call it after\n * `stop`, which keeps new ones from starting.\n */\n public async waitForRunning(timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>(resolve => {\n timer = setTimeout(resolve, timeoutMs);\n });\n const running = Promise.allSettled([...this.running]);\n await Promise.race([running, timeout]);\n clearTimeout(timer);\n }\n\n public async create(params: ISchedulerServiceCreateParams): Promise<void> {\n const { id, namespace, scheduleFor, tenant } = params;\n\n if (scheduleFor <= new Date()) {\n throw new WebinyError(\n `Cannot create a schedule for \"${id}\" with date in the past`,\n \"INVALID_SCHEDULE_DATE\",\n { scheduleFor, id }\n );\n }\n\n const exists = await this.exists({\n id,\n namespace,\n tenant\n });\n if (exists) {\n return this.update(params);\n }\n\n await this.arm(id, { namespace, tenant, scheduledFor: scheduleFor });\n }\n\n public async update(params: ISchedulerServiceUpdateParams): Promise<void> {\n const { id, scheduleFor } = params;\n\n if (scheduleFor <= new Date()) {\n throw new WebinyError(\n `Cannot update an existing schedule for \"${id}\" with date in the past`,\n \"INVALID_SCHEDULE_DATE\",\n { scheduleFor, id }\n );\n }\n\n await this.safeRemove(id);\n await this.create(params);\n }\n\n public async delete(params: SchedulerService.DeleteParams): Promise<void> {\n const { id } = params;\n const exists = await this.exists(params);\n if (!exists) {\n throw new WebinyError(`Cannot delete schedule \"${id}\" because it does not exist.`);\n }\n\n await this.safeRemove(id);\n }\n\n public async exists(params: SchedulerService.ExistsParams): Promise<boolean> {\n const { id } = params;\n return this.jobs.has(id);\n }\n\n /**\n * (Re)arm timers for a batch of persisted pending actions. Runs at boot (per tenant) to restore\n * schedules after a restart, and then on a timer, so this process also arms actions another\n * process scheduled or moved. Overdue actions fire immediately.\n *\n * An action already armed for the same time is left as it is; one armed for a different time was\n * moved by another process and is re-armed.\n */\n public async recover(pendingActions: IPendingAction[]): Promise<void> {\n const now = new Date();\n\n for (const action of pendingActions) {\n if (this.stopped) {\n return;\n }\n if (action.scheduledFor <= now) {\n /* Overdue — execute immediately. */\n await this.trigger(action.id, action.namespace, action.tenant);\n continue;\n }\n\n const armed = this.jobs.get(action.id);\n if (armed && armed.scheduledFor.getTime() === action.scheduledFor.getTime()) {\n continue;\n }\n if (armed) {\n await this.safeRemove(action.id);\n }\n\n await this.arm(action.id, {\n namespace: action.namespace,\n tenant: action.tenant,\n scheduledFor: action.scheduledFor\n });\n }\n }\n\n private async arm(id: string, job: IScheduledJob): Promise<void> {\n if (this.stopped) {\n return;\n }\n this.jobs.set(id, job);\n\n await this.bree.add({\n name: id,\n date: job.scheduledFor,\n path: workerPath\n });\n\n await this.bree.start(id);\n }\n\n private async trigger(id: string, namespace: string, tenant: string): Promise<void> {\n if (this.stopped) {\n return;\n }\n const triggered = this.runAction(id, namespace, tenant);\n this.running.add(triggered);\n try {\n await triggered;\n } finally {\n this.running.delete(triggered);\n }\n }\n\n private async safeRemove(id: string): Promise<void> {\n this.jobs.delete(id);\n\n try {\n await this.bree.stop(id);\n } catch {\n this.logger.debug(`Could not stop bree job \"${id}\" — it may have already fired.`);\n }\n\n try {\n await this.bree.remove(id);\n } catch {\n this.logger.debug(\n `Could not remove bree job \"${id}\" — it may have already been removed.`\n );\n }\n }\n}\n"],"names":["workerPath","fileURLToPath","URL","BreeSchedulerService","params","Map","Set","Bree","name","job","timeoutMs","timer","timeout","Promise","resolve","setTimeout","running","clearTimeout","id","namespace","scheduleFor","tenant","Date","WebinyError","exists","pendingActions","now","action","armed","triggered"],"mappings":";;;AAcA,MAAMA,aAAaC,cAAc,IAAIC,IAAI,iCAAR;AA8B1B,MAAMC;IAcT,YAAmBC,MAAmC,CAAE;aAZvC,IAAI,GAAG,IAAIC;aAIX,OAAO,GAAG,IAA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|
package/jobs/pollWorker.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/jobs/pollWorker.js
DELETED
package/jobs/pollWorker.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"jobs/pollWorker.js","sources":["../../src/jobs/pollWorker.js"],"sourcesContent":["import { parentPort } from \"node:worker_threads\";\n\nif (parentPort) {\n parentPort.postMessage(\"poll\");\n}\n"],"names":["parentPort"],"mappings":";AAEA,IAAIA,YACAA,WAAW,WAAW,CAAC"}
|