background-job 1.0.2 → 2.0.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.
package/README.md CHANGED
@@ -1,15 +1,18 @@
1
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
+ [![license](https://img.shields.io/github/license/mahelbir/background-job.svg)](https://github.com/mahelbir/background-job/blob/HEAD/LICENSE)
5
+
6
+ Managed background jobs with controlled execution loops and per-job enabling, disabling, suspension, and cooldown for
7
+ long-running workers.
4
8
 
5
- Managed background jobs for Node.js. Provides suspension, disabling, and controlled execution loops for long-running worker processes.
6
9
  ## Installation
7
10
 
8
11
  ```bash
9
12
  npm i background-job
10
13
  ```
11
14
 
12
- Ships a dual ESM/CJS build, so both forms are supported:
15
+ The package ships both ESM and CommonJS builds:
13
16
 
14
17
  ```javascript
15
18
  // ES Module
@@ -25,7 +28,8 @@ Subclass `BackgroundJob` for the work and `BackgroundJobRunner` to enumerate whi
25
28
 
26
29
  ### Fixed worker pool
27
30
 
28
- A set of identical workers that each loop with a delay — sized from config, backing off when there is nothing to do:
31
+ Identical workers that each loop with a delay. Config sets the pool size, and a worker backs off when there is nothing
32
+ to do:
29
33
 
30
34
  ```javascript
31
35
  import {BackgroundJob, BackgroundJobRunner} from "background-job";
@@ -52,7 +56,7 @@ await new QueueRunner("queue").executeJobs(); // runs forever, polling for execu
52
56
 
53
57
  ### One job per entity
54
58
 
55
- When the work is dynamic — one job per row from a data source — return the `BackgroundJobDefinition` objects directly.
59
+ When the work is dynamic, such as one job per row from a data source, return `BackgroundJobDefinition` objects directly.
56
60
  `initParams` carries per-job context into `init()`, and the lifecycle hooks set up and tear down resources:
57
61
 
58
62
  ```javascript
@@ -88,8 +92,8 @@ class AccountRunner extends BackgroundJobRunner {
88
92
  await new AccountRunner("account").executeJobs();
89
93
  ```
90
94
 
91
- Returning a job's id keeps it running; omitting it on a later poll disables it (and triggers its `destroy()`).
92
- `getExecutableJobs()` is the single source of truth for what should be active.
95
+ `getExecutableJobs()` decides which jobs are active on every poll. A returned id keeps its job running. If a later poll
96
+ leaves the id out, the runner disables the job and calls its `destroy()` once the loop ends.
93
97
 
94
98
  ## How it works
95
99
 
@@ -101,14 +105,14 @@ thundering herd, then loops its own `execute()` with the configured delay until
101
105
 
102
106
  ### `BackgroundJob`
103
107
 
104
- Base class for an individual job. The runner instantiates it for you — subclass and override the hooks.
108
+ Base class for an individual job. You subclass it and override the hooks; the runner creates the instances.
105
109
 
106
110
  | Member | Description |
107
111
  |-------------------------------------|-------------------------------------------------------------------------------------------------|
108
112
  | `async execute()` | **Abstract.** The job's work; must be overridden or it throws. Called repeatedly while enabled. |
109
113
  | `init(params)` | Optional setup hook, called once before the loop starts. |
110
114
  | `destroy()` | Optional teardown hook, called once after the loop ends. |
111
- | `isEnabled()` | `boolean` — whether this job is still enabled in the runner. |
115
+ | `isEnabled()` | Returns whether this job is still enabled in the runner. |
112
116
  | `disable(suspendDurationMs = 5000)` | Disables the job and suspends it for a cooldown; pass `0` to disable without suspending. |
113
117
  | `runner` / `id` / `name` | The owning runner, this job's id, and its derived name (`"<base> #<id>"`). |
114
118
 
@@ -128,16 +132,17 @@ Orchestrator that owns enabled/running/suspended state per job id.
128
132
 
129
133
  ### `BackgroundJobDefinition`
130
134
 
131
- The object returned (per job) by `getExecutableJobs()`:
135
+ `getExecutableJobs()` returns one of these per job:
132
136
 
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). |
137
+ | Field | Type | Description |
138
+ |----------------|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
139
+ | `id` | `string \| number` | Unique job identifier. |
140
+ | `jobClass` | `typeof BackgroundJob` | The `BackgroundJob` subclass to instantiate. |
141
+ | `initParams` | `*` | Optional. Passed to the job's `init()`. |
142
+ | `delayMs` | `number` | Optional, default `0`. Delay between executions in ms. |
143
+ | `isFixedDelay` | `boolean` | Optional, default `true`. When `true`, the job waits the full delay after each run (fixed-delay); when `false`, execute time counts toward the delay (fixed-rate). |
140
144
 
141
- ## License
145
+ ## Support
142
146
 
143
- The MIT License (MIT). Please see [License File](LICENSE) for more information.
147
+ If this project helps you, please consider giving it a [Star ⭐️](https://github.com/mahelbir/background-job) on GitHub.
148
+ This will encourage us to continue developing and maintaining this project.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let melperjs = require("melperjs");
3
- //#region src/utils.js
3
+ // src/utils.js
4
4
  /**
5
5
  * Throws to signal an abstract method that a subclass must override.
6
6
  * @param {string} method - Name of the method that must be implemented
@@ -9,8 +9,13 @@ let melperjs = require("melperjs");
9
9
  function notImplemented(method) {
10
10
  throw new Error(`${method}() must be implemented by a subclass`);
11
11
  }
12
- //#endregion
13
- //#region src/background-job.js
12
+ var BackgroundJobDefinitionError = class extends Error {
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = "BackgroundJobDefinitionError";
16
+ }
17
+ };
18
+ // src/background-job.js
14
19
  /**
15
20
  * Base class for an individual background job.
16
21
  * Subclass and override {@link BackgroundJob#execute} for the work, with
@@ -63,15 +68,14 @@ var BackgroundJob = class {
63
68
  suspendDurationMs && this.runner.suspendJob(this.id, suspendDurationMs);
64
69
  }
65
70
  };
66
- //#endregion
67
- //#region src/background-job-runner.js
71
+ // src/background-job-runner.js
68
72
  /**
69
73
  * @typedef {Object} BackgroundJobDefinition
70
74
  * @property {string|number} id - Unique job identifier
71
75
  * @property {typeof import("./background-job.js").BackgroundJob} jobClass - BackgroundJob subclass constructor
72
76
  * @property {*} [initParams] - Parameters passed to init()
73
77
  * @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)
78
+ * @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
79
  */
76
80
  /**
77
81
  * Orchestrates background jobs, owning enabled/running/suspended state per job id.
@@ -132,7 +136,8 @@ var BackgroundJobRunner = class {
132
136
  * @returns {Promise<void>}
133
137
  */
134
138
  async _startJob(definition) {
135
- definition.delayMs = definition.delayMs || 0;
139
+ definition.delayMs = Number.isFinite(definition.delayMs) ? Math.max(0, definition.delayMs) : 0;
140
+ definition.isFixedDelay = definition.isFixedDelay !== false;
136
141
  const id = definition.id;
137
142
  if (!this.runningJobs[id]) this.runningJobs[id] = new definition.jobClass(this, id);
138
143
  const ref = this.runningJobs[id];
@@ -144,23 +149,45 @@ var BackgroundJobRunner = class {
144
149
  } catch (e) {
145
150
  console.error(`[${ref.name}] error`, e);
146
151
  }
147
- if (definition.delayMs > 0) if (definition.isFixedRate) {
148
- const remaining = definition.delayMs - (Date.now() - startTime);
149
- if (remaining > 0) await (0, melperjs.sleepMs)(remaining);
150
- } else await (0, melperjs.sleepMs)(definition.delayMs);
152
+ if (definition.delayMs > 0) {
153
+ if (definition.isFixedDelay) await (0, melperjs.sleep)(definition.delayMs);
154
+ else {
155
+ const remaining = definition.delayMs - (Date.now() - startTime);
156
+ if (remaining > 0) await (0, melperjs.sleep)(remaining);
157
+ }
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
159
185
  * @returns {Promise<void>}
160
186
  */
161
187
  async executeJobs(pollIntervalMs = 1e3) {
162
- await (0, melperjs.forever)(pollIntervalMs, async () => {
188
+ await (0, melperjs.forever)(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;
@@ -171,13 +198,14 @@ var BackgroundJobRunner = class {
171
198
  }
172
199
  } else this.enabledJobs[id] = true;
173
200
  if (this.isJobEnabled(id) && !this.isJobRunning(id)) {
174
- await (0, melperjs.sleepMs)((0, melperjs.randomInteger)(300, 1e3));
201
+ await (0, melperjs.sleep)((0, melperjs.randomInteger)(300, 1e3));
175
202
  this._startJob(job).catch(console.error);
176
203
  }
177
204
  }
178
- }, (e) => {
205
+ }, pollIntervalMs, { onError: (e) => {
206
+ if (e instanceof BackgroundJobDefinitionError) throw e;
179
207
  console.error(`[${this.name}] error`, e);
180
- });
208
+ } });
181
209
  }
182
210
  /**
183
211
  * @abstract Override in a subclass to enumerate executable jobs.
@@ -190,19 +218,19 @@ 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
- //#endregion
207
234
  exports.BackgroundJob = BackgroundJob;
235
+ exports.BackgroundJobDefinitionError = BackgroundJobDefinitionError;
208
236
  exports.BackgroundJobRunner = BackgroundJobRunner;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { forever, randomInteger, sleepMs } from "melperjs";
2
- //#region src/utils.js
1
+ import { forever, randomInteger, sleep } from "melperjs";
2
+ // src/utils.js
3
3
  /**
4
4
  * Throws to signal an abstract method that a subclass must override.
5
5
  * @param {string} method - Name of the method that must be implemented
@@ -8,8 +8,13 @@ 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
- //#endregion
12
- //#region src/background-job.js
11
+ var BackgroundJobDefinitionError = class extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "BackgroundJobDefinitionError";
15
+ }
16
+ };
17
+ // src/background-job.js
13
18
  /**
14
19
  * Base class for an individual background job.
15
20
  * Subclass and override {@link BackgroundJob#execute} for the work, with
@@ -62,15 +67,14 @@ var BackgroundJob = class {
62
67
  suspendDurationMs && this.runner.suspendJob(this.id, suspendDurationMs);
63
68
  }
64
69
  };
65
- //#endregion
66
- //#region src/background-job-runner.js
70
+ // src/background-job-runner.js
67
71
  /**
68
72
  * @typedef {Object} BackgroundJobDefinition
69
73
  * @property {string|number} id - Unique job identifier
70
74
  * @property {typeof import("./background-job.js").BackgroundJob} jobClass - BackgroundJob subclass constructor
71
75
  * @property {*} [initParams] - Parameters passed to init()
72
76
  * @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)
77
+ * @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
78
  */
75
79
  /**
76
80
  * Orchestrates background jobs, owning enabled/running/suspended state per job id.
@@ -131,7 +135,8 @@ var BackgroundJobRunner = class {
131
135
  * @returns {Promise<void>}
132
136
  */
133
137
  async _startJob(definition) {
134
- definition.delayMs = definition.delayMs || 0;
138
+ definition.delayMs = Number.isFinite(definition.delayMs) ? Math.max(0, definition.delayMs) : 0;
139
+ definition.isFixedDelay = definition.isFixedDelay !== false;
135
140
  const id = definition.id;
136
141
  if (!this.runningJobs[id]) this.runningJobs[id] = new definition.jobClass(this, id);
137
142
  const ref = this.runningJobs[id];
@@ -143,23 +148,45 @@ var BackgroundJobRunner = class {
143
148
  } catch (e) {
144
149
  console.error(`[${ref.name}] error`, e);
145
150
  }
146
- if (definition.delayMs > 0) if (definition.isFixedRate) {
147
- const remaining = definition.delayMs - (Date.now() - startTime);
148
- if (remaining > 0) await sleepMs(remaining);
149
- } else await sleepMs(definition.delayMs);
151
+ if (definition.delayMs > 0) {
152
+ if (definition.isFixedDelay) await sleep(definition.delayMs);
153
+ else {
154
+ const remaining = definition.delayMs - (Date.now() - startTime);
155
+ if (remaining > 0) await sleep(remaining);
156
+ }
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
158
184
  * @returns {Promise<void>}
159
185
  */
160
186
  async executeJobs(pollIntervalMs = 1e3) {
161
- await forever(pollIntervalMs, async () => {
187
+ await forever(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;
@@ -170,13 +197,14 @@ var BackgroundJobRunner = class {
170
197
  }
171
198
  } else this.enabledJobs[id] = true;
172
199
  if (this.isJobEnabled(id) && !this.isJobRunning(id)) {
173
- await sleepMs(randomInteger(300, 1e3));
200
+ await sleep(randomInteger(300, 1e3));
174
201
  this._startJob(job).catch(console.error);
175
202
  }
176
203
  }
177
- }, (e) => {
204
+ }, pollIntervalMs, { onError: (e) => {
205
+ if (e instanceof BackgroundJobDefinitionError) throw e;
178
206
  console.error(`[${this.name}] error`, e);
179
- });
207
+ } });
180
208
  }
181
209
  /**
182
210
  * @abstract Override in a subclass to enumerate executable jobs.
@@ -189,18 +217,17 @@ 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
- //#endregion
206
- export { BackgroundJob, BackgroundJobRunner };
233
+ export { BackgroundJob, BackgroundJobDefinitionError, BackgroundJobRunner };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "background-job",
3
- "version": "1.0.2",
3
+ "version": "2.0.1",
4
4
  "private": false,
5
- "description": "Managed background jobs for Node.js — suspension, disabling, and controlled execution loops.",
5
+ "description": "Managed background jobs with controlled execution loops and per-job enabling, disabling, suspension, and cooldown for long-running workers.",
6
6
  "keywords": [
7
7
  "worker",
8
8
  "runner",
@@ -19,6 +19,7 @@
19
19
  "license": "MIT",
20
20
  "author": "Mahmuthan Elbir <me@mahmuthanelbir.com.tr>",
21
21
  "type": "module",
22
+ "sideEffects": false,
22
23
  "exports": {
23
24
  ".": {
24
25
  "import": "./dist/index.mjs",
@@ -36,10 +37,10 @@
36
37
  "relock": "rm -rf node_modules package-lock.json && NODE_ENV= npm install --include=dev --include=optional"
37
38
  },
38
39
  "dependencies": {
39
- "melperjs": "^17.2.0"
40
+ "melperjs": "^18.1.0"
40
41
  },
41
42
  "devDependencies": {
42
- "tsdown": "^0.22.3"
43
+ "tsdown": "^0.23.8"
43
44
  },
44
45
  "engines": {
45
46
  "node": ">=18.0.0"