@webiny/api-scheduler-standalone 0.0.0-unstable.eb81deee7e → 6.6.0-alpha.11

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.
@@ -0,0 +1,60 @@
1
+ import { type ISchedulerServiceCreateParams, type ISchedulerServiceUpdateParams, SchedulerService } from "@webiny/api-scheduler/shared/abstractions.js";
2
+ import type { Logger } from "@webiny/api-core/features/logger/abstractions.js";
3
+ export interface IPendingAction {
4
+ id: string;
5
+ namespace: string;
6
+ tenant: string;
7
+ scheduledFor: Date;
8
+ }
9
+ export interface ITimerSchedulerServiceParams {
10
+ logger: Logger.Interface;
11
+ runAction: (id: string, namespace: string, tenant: string) => Promise<void>;
12
+ maxConcurrentActions?: number;
13
+ }
14
+ /**
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).
19
+ *
20
+ * With several processes, each holds its own timers for the same actions: `recover` runs again on a
21
+ * timer to arm what this process has not seen, and whoever supplies `runAction` makes sure an action
22
+ * runs once.
23
+ */
24
+ export declare class TimerSchedulerService implements SchedulerService.Interface {
25
+ private readonly jobs;
26
+ private readonly logger;
27
+ private readonly runAction;
28
+ private readonly maxConcurrentActions;
29
+ private readonly running;
30
+ private readonly slots;
31
+ private stopped;
32
+ constructor(params: ITimerSchedulerServiceParams);
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
+ */
38
+ stop(): Promise<void>;
39
+ /**
40
+ * Resolves once every trigger already started has finished, or after `timeoutMs`. Call it after
41
+ * `stop`, which keeps new ones from starting.
42
+ */
43
+ waitForRunning(timeoutMs: number): Promise<void>;
44
+ create(params: ISchedulerServiceCreateParams): Promise<void>;
45
+ update(params: ISchedulerServiceUpdateParams): Promise<void>;
46
+ delete(params: SchedulerService.DeleteParams): Promise<void>;
47
+ exists(params: SchedulerService.ExistsParams): Promise<boolean>;
48
+ /**
49
+ * (Re)arm timers for a batch of persisted pending actions. Runs at boot (per tenant) to restore
50
+ * schedules after a restart, and then on a timer, so this process also arms actions another
51
+ * process scheduled or moved. Overdue actions run one by one, before the next action is looked at.
52
+ *
53
+ * An action already armed for the same time is left as it is; one armed for a different time was
54
+ * moved by another process and is re-armed.
55
+ */
56
+ recover(pendingActions: IPendingAction[]): Promise<void>;
57
+ private arm;
58
+ private disarm;
59
+ private trigger;
60
+ }
@@ -0,0 +1,134 @@
1
+ import { WebinyError } from "@webiny/error";
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
+ constructor(params){
7
+ this.jobs = new Map();
8
+ this.running = new Set();
9
+ this.stopped = false;
10
+ this.logger = params.logger;
11
+ this.runAction = params.runAction;
12
+ this.maxConcurrentActions = params.maxConcurrentActions ?? DEFAULT_MAX_CONCURRENT_ACTIONS;
13
+ this.slots = new ConcurrencySlots(this.maxConcurrentActions);
14
+ }
15
+ async start() {
16
+ this.stopped = false;
17
+ this.slots.open();
18
+ }
19
+ async stop() {
20
+ this.stopped = true;
21
+ for (const job of this.jobs.values())clearTimeout(job.timer);
22
+ this.jobs.clear();
23
+ this.slots.close();
24
+ }
25
+ async waitForRunning(timeoutMs) {
26
+ let timer;
27
+ const timeout = new Promise((resolve)=>{
28
+ timer = setTimeout(resolve, timeoutMs);
29
+ });
30
+ const running = Promise.allSettled([
31
+ ...this.running
32
+ ]);
33
+ await Promise.race([
34
+ running,
35
+ timeout
36
+ ]);
37
+ clearTimeout(timer);
38
+ }
39
+ async create(params) {
40
+ const { id, namespace, scheduleFor, tenant } = params;
41
+ if (scheduleFor <= new Date()) throw new WebinyError(`Cannot create a schedule for "${id}" with date in the past`, "INVALID_SCHEDULE_DATE", {
42
+ scheduleFor,
43
+ id
44
+ });
45
+ const exists = await this.exists({
46
+ id,
47
+ namespace,
48
+ tenant
49
+ });
50
+ if (exists) return this.update(params);
51
+ this.arm(id, namespace, tenant, scheduleFor);
52
+ }
53
+ async update(params) {
54
+ const { id, scheduleFor } = params;
55
+ if (scheduleFor <= new Date()) throw new WebinyError(`Cannot update an existing schedule for "${id}" with date in the past`, "INVALID_SCHEDULE_DATE", {
56
+ scheduleFor,
57
+ id
58
+ });
59
+ this.disarm(id);
60
+ await this.create(params);
61
+ }
62
+ async delete(params) {
63
+ const { id } = params;
64
+ const exists = await this.exists(params);
65
+ if (!exists) throw new WebinyError(`Cannot delete schedule "${id}" because it does not exist.`);
66
+ this.disarm(id);
67
+ }
68
+ async exists(params) {
69
+ const { id } = params;
70
+ return this.jobs.has(id);
71
+ }
72
+ async recover(pendingActions) {
73
+ const now = new Date();
74
+ for (const action of pendingActions){
75
+ if (this.stopped) return;
76
+ if (action.scheduledFor <= now) {
77
+ await this.trigger(action.id, action.namespace, action.tenant);
78
+ continue;
79
+ }
80
+ const armed = this.jobs.get(action.id);
81
+ if (!armed || armed.scheduledFor.getTime() !== action.scheduledFor.getTime()) {
82
+ this.disarm(action.id);
83
+ this.arm(action.id, action.namespace, action.tenant, action.scheduledFor);
84
+ }
85
+ }
86
+ }
87
+ arm(id, namespace, tenant, scheduledFor) {
88
+ if (this.stopped) return;
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
104
+ });
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
+ }
112
+ async trigger(id, namespace, tenant) {
113
+ const granted = await this.slots.acquire();
114
+ if (!granted) return;
115
+ if (this.stopped) return void this.slots.release();
116
+ const triggered = this.runAction(id, namespace, tenant);
117
+ this.running.add(triggered);
118
+ try {
119
+ await triggered;
120
+ } catch (error) {
121
+ this.logger.error({
122
+ error,
123
+ id,
124
+ tenant
125
+ }, "[scheduler] scheduled action failed");
126
+ } finally{
127
+ this.running.delete(triggered);
128
+ this.slots.release();
129
+ }
130
+ }
131
+ }
132
+ export { TimerSchedulerService };
133
+
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;a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AE,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 { BreeSchedulerService } from "./BreeSchedulerService.js";
2
- export type { IPendingAction, IBreeSchedulerServiceParams } from "./BreeSchedulerService.js";
1
+ export { TimerSchedulerService } from "./TimerSchedulerService.js";
2
+ export type { IPendingAction, ITimerSchedulerServiceParams } from "./TimerSchedulerService.js";
package/index.js CHANGED
@@ -1 +1 @@
1
- export { BreeSchedulerService } from "./BreeSchedulerService.js";
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": "0.0.0-unstable.eb81deee7e",
3
+ "version": "6.6.0-alpha.11",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./index.js",
@@ -15,18 +15,18 @@
15
15
  "scheduler:server"
16
16
  ],
17
17
  "author": "Webiny Ltd",
18
- "description": "Standalone cron-based implementation for the Webiny action scheduler.",
18
+ "description": "Standalone in-process timer implementation for the Webiny action scheduler.",
19
19
  "license": "MIT",
20
20
  "dependencies": {
21
- "@webiny/api-core": "0.0.0-unstable.eb81deee7e",
22
- "@webiny/api-scheduler": "0.0.0-unstable.eb81deee7e",
23
- "@webiny/error": "0.0.0-unstable.eb81deee7e",
24
- "bree": "9.2.9"
21
+ "@webiny/api-core": "6.6.0-alpha.11",
22
+ "@webiny/api-scheduler": "6.6.0-alpha.11",
23
+ "@webiny/error": "6.6.0-alpha.11",
24
+ "@webiny/utils": "6.6.0-alpha.11"
25
25
  },
26
26
  "devDependencies": {
27
- "@webiny/build-tools": "0.0.0-unstable.eb81deee7e",
27
+ "@webiny/build-tools": "6.6.0-alpha.11",
28
28
  "typescript": "7.0.2",
29
- "vitest": "4.1.11"
29
+ "vitest": "5.0.5"
30
30
  },
31
31
  "publishConfig": {
32
32
  "access": "public"
@@ -1,37 +0,0 @@
1
- import { type ISchedulerServiceCreateParams, type ISchedulerServiceUpdateParams, SchedulerService } from "@webiny/api-scheduler/shared/abstractions.js";
2
- import type { Logger } from "@webiny/api-core/features/logger/abstractions.js";
3
- export interface IPendingAction {
4
- id: string;
5
- namespace: string;
6
- tenant: string;
7
- scheduledFor: Date;
8
- }
9
- export interface IBreeSchedulerServiceParams {
10
- logger: Logger.Interface;
11
- onTrigger: (id: string, namespace: string, tenant: string) => Promise<void>;
12
- }
13
- /**
14
- * One-shot bree job per scheduled action — mirrors EventBridge behaviour. This is a single-process,
15
- * long-lived root SINGLETON (started once at boot): it holds the live timers for ALL tenants, so each
16
- * job records its own tenant and `onTrigger` is fired with it (the trigger runs outside any request,
17
- * so the tenant can't be read from a request context).
18
- */
19
- export declare class BreeSchedulerService implements SchedulerService.Interface {
20
- private readonly bree;
21
- private readonly jobs;
22
- private readonly logger;
23
- private readonly onTrigger;
24
- constructor(params: IBreeSchedulerServiceParams);
25
- start(): Promise<void>;
26
- stop(): Promise<void>;
27
- create(params: ISchedulerServiceCreateParams): Promise<void>;
28
- update(params: ISchedulerServiceUpdateParams): Promise<void>;
29
- delete(params: SchedulerService.DeleteParams): Promise<void>;
30
- exists(params: SchedulerService.ExistsParams): Promise<boolean>;
31
- /**
32
- * (Re)arm timers for a batch of persisted pending actions — called at boot (per tenant) to restore
33
- * schedules after a restart. Overdue actions fire immediately.
34
- */
35
- recover(pendingActions: IPendingAction[]): Promise<void>;
36
- private safeRemove;
37
- }
@@ -1,105 +0,0 @@
1
- import bree from "bree";
2
- import { fileURLToPath } from "node:url";
3
- import { WebinyError } from "@webiny/error";
4
- const workerPath = fileURLToPath(new URL("./jobs/pollWorker.js", import.meta.url));
5
- class BreeSchedulerService {
6
- constructor(params){
7
- this.jobs = new Map();
8
- this.logger = params.logger;
9
- this.onTrigger = params.onTrigger;
10
- this.bree = new bree({
11
- root: false,
12
- jobs: [],
13
- logger: false,
14
- workerMessageHandler: async ({ name })=>{
15
- const job = this.jobs.get(name);
16
- if (!job) return;
17
- this.jobs.delete(name);
18
- await this.onTrigger(name, job.namespace, job.tenant);
19
- }
20
- });
21
- }
22
- async start() {
23
- await this.bree.start();
24
- }
25
- async stop() {
26
- await this.bree.stop();
27
- }
28
- async create(params) {
29
- const { id, namespace, scheduleFor, tenant } = params;
30
- if (scheduleFor <= new Date()) throw new WebinyError(`Cannot create a schedule for "${id}" with date in the past`, "INVALID_SCHEDULE_DATE", {
31
- scheduleFor,
32
- id
33
- });
34
- const exists = await this.exists({
35
- id,
36
- namespace,
37
- tenant
38
- });
39
- if (exists) return this.update(params);
40
- this.jobs.set(id, {
41
- namespace,
42
- tenant
43
- });
44
- await this.bree.add({
45
- name: id,
46
- date: scheduleFor,
47
- path: workerPath
48
- });
49
- await this.bree.start(id);
50
- }
51
- async update(params) {
52
- const { id, scheduleFor } = params;
53
- if (scheduleFor <= new Date()) throw new WebinyError(`Cannot update an existing schedule for "${id}" with date in the past`, "INVALID_SCHEDULE_DATE", {
54
- scheduleFor,
55
- id
56
- });
57
- await this.safeRemove(id);
58
- await this.create(params);
59
- }
60
- async delete(params) {
61
- const { id } = params;
62
- const exists = await this.exists(params);
63
- if (!exists) throw new WebinyError(`Cannot delete schedule "${id}" because it does not exist.`);
64
- await this.safeRemove(id);
65
- }
66
- async exists(params) {
67
- const { id } = params;
68
- return this.jobs.has(id);
69
- }
70
- async recover(pendingActions) {
71
- const now = new Date();
72
- for (const action of pendingActions){
73
- if (action.scheduledFor <= now) {
74
- await this.onTrigger(action.id, action.namespace, action.tenant);
75
- continue;
76
- }
77
- this.jobs.set(action.id, {
78
- namespace: action.namespace,
79
- tenant: action.tenant
80
- });
81
- await this.bree.add({
82
- name: action.id,
83
- date: action.scheduledFor,
84
- path: workerPath
85
- });
86
- await this.bree.start(action.id);
87
- }
88
- }
89
- async safeRemove(id) {
90
- this.jobs.delete(id);
91
- try {
92
- await this.bree.stop(id);
93
- } catch {
94
- this.logger.debug(`Could not stop bree job "${id}" — it may have already fired.`);
95
- }
96
- try {
97
- await this.bree.remove(id);
98
- } catch {
99
- this.logger.debug(`Could not remove bree job "${id}" — it may have already been removed.`);
100
- }
101
- }
102
- }
103
- export { BreeSchedulerService };
104
-
105
- //# sourceMappingURL=BreeSchedulerService.js.map
@@ -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}\n\nexport interface IBreeSchedulerServiceParams {\n logger: Logger.Interface;\n onTrigger: (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 single-process,\n * long-lived root SINGLETON (started once at boot): it holds the live timers for ALL tenants, so each\n * job records its own tenant and `onTrigger` is fired with it (the trigger runs outside any request,\n * so the tenant can't be read from a request context).\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 onTrigger;\n\n public constructor(params: IBreeSchedulerServiceParams) {\n this.logger = params.logger;\n this.onTrigger = params.onTrigger;\n\n this.bree = new Bree({\n root: false,\n jobs: [],\n logger: false,\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.onTrigger(name, job.namespace, job.tenant);\n }\n });\n }\n\n public async start(): Promise<void> {\n await this.bree.start();\n }\n\n public async stop(): Promise<void> {\n await this.bree.stop();\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.jobs.set(id, { namespace, tenant });\n\n await this.bree.add({\n name: id,\n date: scheduleFor,\n path: workerPath\n });\n\n await this.bree.start(id);\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 — called at boot (per tenant) to restore\n * schedules after a restart. Overdue actions fire immediately.\n */\n public async recover(pendingActions: IPendingAction[]): Promise<void> {\n const now = new Date();\n\n for (const action of pendingActions) {\n if (action.scheduledFor <= now) {\n /* Overdue — execute immediately. */\n await this.onTrigger(action.id, action.namespace, action.tenant);\n continue;\n }\n\n this.jobs.set(action.id, { namespace: action.namespace, tenant: action.tenant });\n\n await this.bree.add({\n name: action.id,\n date: action.scheduledFor,\n path: workerPath\n });\n\n await this.bree.start(action.id);\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","Bree","name","job","id","namespace","scheduleFor","tenant","Date","WebinyError","exists","pendingActions","now","action"],"mappings":";;;AAcA,MAAMA,aAAaC,cAAc,IAAIC,IAAI,wBAAwB,YAAY,GAAG;AAyBzE,MAAMC;IAMT,YAAmBC,MAAmC,CAAE;aAJvC,IAAI,GAAG,IAAIC;QAKxB,IAAI,CAAC,MAAM,GAAGD,OAAO,MAAM;QAC3B,IAAI,CAAC,SAAS,GAAGA,OAAO,SAAS;QAEjC,IAAI,CAAC,IAAI,GAAG,IAAIE,KAAK;YACjB,MAAM;YACN,MAAM,EAAE;YACR,QAAQ;YACR,sBAAsB,OAAO,EAAEC,IAAI,EAAE;gBACjC,MAAMC,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAACD;gBAC1B,IAAI,CAACC,KACD;gBAGJ,IAAI,CAAC,IAAI,CAAC,MAAM,CAACD;gBACjB,MAAM,IAAI,CAAC,SAAS,CAACA,MAAMC,IAAI,SAAS,EAAEA,IAAI,MAAM;YACxD;QACJ;IACJ;IAEA,MAAa,QAAuB;QAChC,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK;IACzB;IAEA,MAAa,OAAsB;QAC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AGL;QACf,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAACK;IACzB;IAMA,MAAa,QAAQO,cAAgC,EAAiB;QAClE,MAAMC,MAAM,IAAIJ;QAEhB,KAAK,MAAMK,UAAUF,eAAgB;YACjC,IAAIE,OAAO,YAAY,IAAID,KAAK;gBAE5B,MAAM,IAAI,CAAC,SAAS,CAACC,OAAO,EAAE,EAAEA,OAAO,SAAS,EAAEA,OAAO,MAAM;gBAC/D;YACJ;YAEA,IAAI,CAAC,IAAI,CAAC,GAAG,CAACA,OAAO,EAAE,EAAE;gBAAE,WAAWA,OAAO,SAAS;gBAAE,QAAQA,OAAO,MAAM;YAAC;YAE9E,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;gBAChB,MAAMA,OAAO,EAAE;gBACf,MAAMA,OAAO,YAAY;gBACzB,MAAMlB;YACV;YAEA,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAACkB,OAAO,EAAE;QACnC;IACJ;IAEA,MAAc,WAAWT,EAAU,EAAiB;QAChD,IAAI,CAAC,IAAI,CAAC,MAAM,CAACA;QAEjB,IAAI;YACA,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,CAACA;QACzB,EAAE,OAAM;YACJ,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,yBAAyB,EAAEA,GAAG,8BAA8B,CAAC;QACpF;QAEA,IAAI;YACA,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAACA;QAC3B,EAAE,OAAM;YACJ,IAAI,CAAC,MAAM,CAAC,KAAK,CACb,CAAC,2BAA2B,EAAEA,GAAG,qCAAqC,CAAC;QAE/E;IACJ;AACJ"}
@@ -1 +0,0 @@
1
- export {};
@@ -1,4 +0,0 @@
1
- import { parentPort } from "node:worker_threads";
2
- if (parentPort) parentPort.postMessage("poll");
3
-
4
- //# sourceMappingURL=pollWorker.js.map
@@ -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"}