background-job 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,10 @@
1
- # background-job
1
+ # Background Job
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/background-job.svg)](https://www.npmjs.com/package/background-job)
4
4
 
5
- Managed background jobs for Node.js. Provides suspension, disabling, and controlled execution loops for long-running worker processes.
5
+ Managed background jobs for Node.js. Provides suspension, disabling, and controlled execution loops for long-running
6
+ worker processes.
7
+
6
8
  ## Installation
7
9
 
8
10
  ```bash
@@ -130,13 +132,13 @@ Orchestrator that owns enabled/running/suspended state per job id.
130
132
 
131
133
  The object returned (per job) by `getExecutableJobs()`:
132
134
 
133
- | Field | Type | Description |
134
- |---------------|------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
135
- | `id` | `string \| number` | Unique job identifier. |
136
- | `jobClass` | `typeof BackgroundJob` | The `BackgroundJob` subclass to instantiate. |
137
- | `initParams` | `*` | Optional — passed to the job's `init()`. |
138
- | `delayMs` | `number` | Optional (default `0`) — delay between executions in ms. |
139
- | `isFixedRate` | `boolean` | Optional (default `false`) — when `true`, execute time counts toward the delay (fixed-rate); otherwise the full delay is waited after each execute (fixed-delay). |
135
+ | Field | Type | Description |
136
+ |----------------|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
137
+ | `id` | `string \| number` | Unique job identifier. |
138
+ | `jobClass` | `typeof BackgroundJob` | The `BackgroundJob` subclass to instantiate. |
139
+ | `initParams` | `*` | Optional — passed to the job's `init()`. |
140
+ | `delayMs` | `number` | Optional (default `0`) — delay between executions in ms. |
141
+ | `isFixedDelay` | `boolean` | Optional (default `true`) — when `true`, the full delay is waited after each execute (fixed-delay); when `false`, execute time counts toward the delay (fixed-rate). |
140
142
 
141
143
  ## License
142
144
 
package/dist/index.cjs CHANGED
@@ -9,6 +9,12 @@ let melperjs = require("melperjs");
9
9
  function notImplemented(method) {
10
10
  throw new Error(`${method}() must be implemented by a subclass`);
11
11
  }
12
+ var BackgroundJobDefinitionError = class extends Error {
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = "BackgroundJobDefinitionError";
16
+ }
17
+ };
12
18
  //#endregion
13
19
  //#region src/background-job.js
14
20
  /**
@@ -71,7 +77,7 @@ var BackgroundJob = class {
71
77
  * @property {typeof import("./background-job.js").BackgroundJob} jobClass - BackgroundJob subclass constructor
72
78
  * @property {*} [initParams] - Parameters passed to init()
73
79
  * @property {number} [delayMs=0] - Delay between executions in ms
74
- * @property {boolean} [isFixedRate=false] - When true, execute time counts toward the delay (fixed-rate); otherwise the full delay is waited after each execute (fixed-delay)
80
+ * @property {boolean} [isFixedDelay=true] - When true (default), the full delay is waited after each execute (fixed-delay); when false, execute time counts toward the delay (fixed-rate)
75
81
  */
76
82
  /**
77
83
  * Orchestrates background jobs, owning enabled/running/suspended state per job id.
@@ -132,7 +138,8 @@ var BackgroundJobRunner = class {
132
138
  * @returns {Promise<void>}
133
139
  */
134
140
  async _startJob(definition) {
135
- definition.delayMs = definition.delayMs || 0;
141
+ definition.delayMs = Number.isFinite(definition.delayMs) ? Math.max(0, definition.delayMs) : 0;
142
+ definition.isFixedDelay = definition.isFixedDelay !== false;
136
143
  const id = definition.id;
137
144
  if (!this.runningJobs[id]) this.runningJobs[id] = new definition.jobClass(this, id);
138
145
  const ref = this.runningJobs[id];
@@ -144,15 +151,34 @@ var BackgroundJobRunner = class {
144
151
  } catch (e) {
145
152
  console.error(`[${ref.name}] error`, e);
146
153
  }
147
- if (definition.delayMs > 0) if (definition.isFixedRate) {
154
+ if (definition.delayMs > 0) if (definition.isFixedDelay) await (0, melperjs.sleepMs)(definition.delayMs);
155
+ else {
148
156
  const remaining = definition.delayMs - (Date.now() - startTime);
149
157
  if (remaining > 0) await (0, melperjs.sleepMs)(remaining);
150
- } else await (0, melperjs.sleepMs)(definition.delayMs);
158
+ }
151
159
  }
152
160
  ref.destroy();
153
161
  delete this.runningJobs[id];
154
162
  }
155
163
  /**
164
+ * Validates the job definitions from {@link BackgroundJobRunner#getExecutableJobs},
165
+ * rejecting a missing or duplicate id or a jobClass that is not a BackgroundJob subclass.
166
+ * @private
167
+ * @param {BackgroundJobDefinition[]} jobs - Definitions to validate
168
+ * @returns {void}
169
+ * @throws {BackgroundJobDefinitionError} When a definition is invalid
170
+ */
171
+ _validateJobs(jobs) {
172
+ const seenIds = /* @__PURE__ */ new Set();
173
+ for (const job of jobs) {
174
+ if (job.id === void 0 || job.id === null) throw new BackgroundJobDefinitionError(`[${this.name}] a job definition is missing an id`);
175
+ const key = String(job.id);
176
+ if (seenIds.has(key)) throw new BackgroundJobDefinitionError(`[${this.name}] duplicate job id "${job.id}"`);
177
+ seenIds.add(key);
178
+ if (typeof job.jobClass !== "function" || job.jobClass !== BackgroundJob && !(job.jobClass.prototype instanceof BackgroundJob)) throw new BackgroundJobDefinitionError(`[${this.name}] job "${job.id}" has an invalid jobClass; expected a BackgroundJob subclass`);
179
+ }
180
+ }
181
+ /**
156
182
  * Runs the main loop: periodically refreshes the executable job set, lifts
157
183
  * expired suspensions, and starts any enabled job that is not already running.
158
184
  * @param {number} [pollIntervalMs=1000] - Interval in ms between job status checks
@@ -161,6 +187,7 @@ var BackgroundJobRunner = class {
161
187
  async executeJobs(pollIntervalMs = 1e3) {
162
188
  await (0, melperjs.forever)(pollIntervalMs, async () => {
163
189
  const jobs = await this.getExecutableJobs();
190
+ this._validateJobs(jobs);
164
191
  this.enabledJobs = {};
165
192
  for (const job of jobs) {
166
193
  const id = job.id;
@@ -176,6 +203,7 @@ var BackgroundJobRunner = class {
176
203
  }
177
204
  }
178
205
  }, (e) => {
206
+ if (e instanceof BackgroundJobDefinitionError) throw e;
179
207
  console.error(`[${this.name}] error`, e);
180
208
  });
181
209
  }
@@ -190,19 +218,20 @@ var BackgroundJobRunner = class {
190
218
  * Builds a list of identical job definitions with sequential 1-based ids.
191
219
  * @param {number} count - Number of definitions to generate
192
220
  * @param {typeof import("./background-job.js").BackgroundJob} jobClass - BackgroundJob subclass to use for every definition
193
- * @param {{initParams?: *, delayMs?: number, isFixedRate?: boolean}} [options] - Shared options applied to every definition
221
+ * @param {{initParams?: *, delayMs?: number, isFixedDelay?: boolean}} [options] - Shared options applied to every definition
194
222
  * @returns {BackgroundJobDefinition[]}
195
223
  */
196
- static iteratingJobList(count, jobClass, { initParams = null, delayMs = 0, isFixedRate = false } = {}) {
224
+ static iteratingJobList(count, jobClass, { initParams = null, delayMs = 0, isFixedDelay = true } = {}) {
197
225
  return Array.from({ length: count }, (_, i) => ({
198
226
  id: i + 1,
199
227
  jobClass,
200
228
  initParams,
201
229
  delayMs,
202
- isFixedRate
230
+ isFixedDelay
203
231
  }));
204
232
  }
205
233
  };
206
234
  //#endregion
207
235
  exports.BackgroundJob = BackgroundJob;
236
+ exports.BackgroundJobDefinitionError = BackgroundJobDefinitionError;
208
237
  exports.BackgroundJobRunner = BackgroundJobRunner;
package/dist/index.mjs CHANGED
@@ -8,6 +8,12 @@ import { forever, randomInteger, sleepMs } from "melperjs";
8
8
  function notImplemented(method) {
9
9
  throw new Error(`${method}() must be implemented by a subclass`);
10
10
  }
11
+ var BackgroundJobDefinitionError = class extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "BackgroundJobDefinitionError";
15
+ }
16
+ };
11
17
  //#endregion
12
18
  //#region src/background-job.js
13
19
  /**
@@ -70,7 +76,7 @@ var BackgroundJob = class {
70
76
  * @property {typeof import("./background-job.js").BackgroundJob} jobClass - BackgroundJob subclass constructor
71
77
  * @property {*} [initParams] - Parameters passed to init()
72
78
  * @property {number} [delayMs=0] - Delay between executions in ms
73
- * @property {boolean} [isFixedRate=false] - When true, execute time counts toward the delay (fixed-rate); otherwise the full delay is waited after each execute (fixed-delay)
79
+ * @property {boolean} [isFixedDelay=true] - When true (default), the full delay is waited after each execute (fixed-delay); when false, execute time counts toward the delay (fixed-rate)
74
80
  */
75
81
  /**
76
82
  * Orchestrates background jobs, owning enabled/running/suspended state per job id.
@@ -131,7 +137,8 @@ var BackgroundJobRunner = class {
131
137
  * @returns {Promise<void>}
132
138
  */
133
139
  async _startJob(definition) {
134
- definition.delayMs = definition.delayMs || 0;
140
+ definition.delayMs = Number.isFinite(definition.delayMs) ? Math.max(0, definition.delayMs) : 0;
141
+ definition.isFixedDelay = definition.isFixedDelay !== false;
135
142
  const id = definition.id;
136
143
  if (!this.runningJobs[id]) this.runningJobs[id] = new definition.jobClass(this, id);
137
144
  const ref = this.runningJobs[id];
@@ -143,15 +150,34 @@ var BackgroundJobRunner = class {
143
150
  } catch (e) {
144
151
  console.error(`[${ref.name}] error`, e);
145
152
  }
146
- if (definition.delayMs > 0) if (definition.isFixedRate) {
153
+ if (definition.delayMs > 0) if (definition.isFixedDelay) await sleepMs(definition.delayMs);
154
+ else {
147
155
  const remaining = definition.delayMs - (Date.now() - startTime);
148
156
  if (remaining > 0) await sleepMs(remaining);
149
- } else await sleepMs(definition.delayMs);
157
+ }
150
158
  }
151
159
  ref.destroy();
152
160
  delete this.runningJobs[id];
153
161
  }
154
162
  /**
163
+ * Validates the job definitions from {@link BackgroundJobRunner#getExecutableJobs},
164
+ * rejecting a missing or duplicate id or a jobClass that is not a BackgroundJob subclass.
165
+ * @private
166
+ * @param {BackgroundJobDefinition[]} jobs - Definitions to validate
167
+ * @returns {void}
168
+ * @throws {BackgroundJobDefinitionError} When a definition is invalid
169
+ */
170
+ _validateJobs(jobs) {
171
+ const seenIds = /* @__PURE__ */ new Set();
172
+ for (const job of jobs) {
173
+ if (job.id === void 0 || job.id === null) throw new BackgroundJobDefinitionError(`[${this.name}] a job definition is missing an id`);
174
+ const key = String(job.id);
175
+ if (seenIds.has(key)) throw new BackgroundJobDefinitionError(`[${this.name}] duplicate job id "${job.id}"`);
176
+ seenIds.add(key);
177
+ if (typeof job.jobClass !== "function" || job.jobClass !== BackgroundJob && !(job.jobClass.prototype instanceof BackgroundJob)) throw new BackgroundJobDefinitionError(`[${this.name}] job "${job.id}" has an invalid jobClass; expected a BackgroundJob subclass`);
178
+ }
179
+ }
180
+ /**
155
181
  * Runs the main loop: periodically refreshes the executable job set, lifts
156
182
  * expired suspensions, and starts any enabled job that is not already running.
157
183
  * @param {number} [pollIntervalMs=1000] - Interval in ms between job status checks
@@ -160,6 +186,7 @@ var BackgroundJobRunner = class {
160
186
  async executeJobs(pollIntervalMs = 1e3) {
161
187
  await forever(pollIntervalMs, async () => {
162
188
  const jobs = await this.getExecutableJobs();
189
+ this._validateJobs(jobs);
163
190
  this.enabledJobs = {};
164
191
  for (const job of jobs) {
165
192
  const id = job.id;
@@ -175,6 +202,7 @@ var BackgroundJobRunner = class {
175
202
  }
176
203
  }
177
204
  }, (e) => {
205
+ if (e instanceof BackgroundJobDefinitionError) throw e;
178
206
  console.error(`[${this.name}] error`, e);
179
207
  });
180
208
  }
@@ -189,18 +217,18 @@ var BackgroundJobRunner = class {
189
217
  * Builds a list of identical job definitions with sequential 1-based ids.
190
218
  * @param {number} count - Number of definitions to generate
191
219
  * @param {typeof import("./background-job.js").BackgroundJob} jobClass - BackgroundJob subclass to use for every definition
192
- * @param {{initParams?: *, delayMs?: number, isFixedRate?: boolean}} [options] - Shared options applied to every definition
220
+ * @param {{initParams?: *, delayMs?: number, isFixedDelay?: boolean}} [options] - Shared options applied to every definition
193
221
  * @returns {BackgroundJobDefinition[]}
194
222
  */
195
- static iteratingJobList(count, jobClass, { initParams = null, delayMs = 0, isFixedRate = false } = {}) {
223
+ static iteratingJobList(count, jobClass, { initParams = null, delayMs = 0, isFixedDelay = true } = {}) {
196
224
  return Array.from({ length: count }, (_, i) => ({
197
225
  id: i + 1,
198
226
  jobClass,
199
227
  initParams,
200
228
  delayMs,
201
- isFixedRate
229
+ isFixedDelay
202
230
  }));
203
231
  }
204
232
  };
205
233
  //#endregion
206
- export { BackgroundJob, BackgroundJobRunner };
234
+ export { BackgroundJob, BackgroundJobDefinitionError, BackgroundJobRunner };
package/package.json CHANGED
@@ -1,19 +1,14 @@
1
1
  {
2
2
  "name": "background-job",
3
- "version": "1.0.1",
3
+ "version": "2.0.0",
4
4
  "private": false,
5
5
  "description": "Managed background jobs for Node.js — suspension, disabling, and controlled execution loops.",
6
6
  "keywords": [
7
- "background-job",
8
- "background",
9
- "job",
10
- "jobs",
11
7
  "worker",
12
8
  "runner",
13
9
  "scheduler",
14
10
  "task",
15
- "queue",
16
- "esm"
11
+ "queue"
17
12
  ],
18
13
  "homepage": "https://github.com/mahelbir/background-job#readme",
19
14
  "bugs": "https://github.com/mahelbir/background-job/issues",
@@ -41,10 +36,10 @@
41
36
  "relock": "rm -rf node_modules package-lock.json && NODE_ENV= npm install --include=dev --include=optional"
42
37
  },
43
38
  "dependencies": {
44
- "melperjs": "^17.1.1"
39
+ "melperjs": "^17.2.0"
45
40
  },
46
41
  "devDependencies": {
47
- "tsdown": "^0.22.2"
42
+ "tsdown": "^0.22.3"
48
43
  },
49
44
  "engines": {
50
45
  "node": ">=18.0.0"