@webiny/api-scheduler-server 0.0.0-unstable.0d717d18dd

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,37 @@
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
+ }
@@ -0,0 +1,105 @@
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
@@ -0,0 +1 @@
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,C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1
+ MIT License
2
+
3
+ Copyright (c) Webiny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @webiny/api-scheduler-server
2
+
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
6
+
7
+ 📘 **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
8
+
9
+ ---
10
+
11
+ _This README file is automatically generated during the publish process._
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { BreeSchedulerService } from "./BreeSchedulerService.js";
2
+ export type { IPendingAction, IBreeSchedulerServiceParams } from "./BreeSchedulerService.js";
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export { BreeSchedulerService } from "./BreeSchedulerService.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ if (parentPort) parentPort.postMessage("poll");
3
+
4
+ //# sourceMappingURL=pollWorker.js.map
@@ -0,0 +1 @@
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"}
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@webiny/api-scheduler-server",
3
+ "version": "0.0.0-unstable.0d717d18dd",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./index.js",
7
+ "./*": "./*"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/webiny/webiny-js.git",
12
+ "directory": "packages/api-scheduler-server"
13
+ },
14
+ "keywords": [
15
+ "scheduler:server"
16
+ ],
17
+ "author": "Webiny Ltd",
18
+ "description": "Server-side cron-based implementation for the Webiny action scheduler.",
19
+ "license": "MIT",
20
+ "dependencies": {
21
+ "@webiny/api-core": "0.0.0-unstable.0d717d18dd",
22
+ "@webiny/api-scheduler": "0.0.0-unstable.0d717d18dd",
23
+ "@webiny/error": "0.0.0-unstable.0d717d18dd",
24
+ "bree": "9.2.9"
25
+ },
26
+ "devDependencies": {
27
+ "@webiny/build-tools": "0.0.0-unstable.0d717d18dd",
28
+ "@webiny/project-utils": "0.0.0-unstable.0d717d18dd",
29
+ "typescript": "7.0.2",
30
+ "vitest": "4.1.10"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "webiny": {
36
+ "publishFrom": "dist"
37
+ }
38
+ }