@constructive-io/job-scheduler 0.3.7

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/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ ## 0.3.7 (2025-12-18)
7
+
8
+ **Note:** Version bump only for package @constructive-io/job-scheduler
9
+
10
+ ## [0.3.6](https://github.com/constructive-io/jobs/compare/@launchql/job-scheduler@0.3.5...@launchql/job-scheduler@0.3.6) (2025-12-17)
11
+
12
+ **Note:** Version bump only for package @launchql/job-scheduler
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # job-scheduler
package/dist/env.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ declare const _default: Readonly<{
2
+ PGUSER: string;
3
+ PGHOST: string;
4
+ PGPASSWORD: string;
5
+ PGPORT: number;
6
+ PGDATABASE: string;
7
+ JOBS_SCHEMA: string;
8
+ JOBS_SUPPORT_ANY: boolean;
9
+ JOBS_SUPPORTED: string[];
10
+ HOSTNAME: string;
11
+ }> & import("envalid").CleanEnv & {
12
+ readonly [varName: string]: string;
13
+ };
14
+ export default _default;
package/dist/env.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const envalid_1 = require("envalid");
4
+ const array = (0, envalid_1.makeValidator)((x) => x.split(',').filter((i) => i), '');
5
+ exports.default = (0, envalid_1.cleanEnv)(process.env, {
6
+ PGUSER: (0, envalid_1.str)({ default: 'postgres' }),
7
+ PGHOST: (0, envalid_1.str)({ default: 'localhost' }),
8
+ PGPASSWORD: (0, envalid_1.str)({ default: 'password' }),
9
+ PGPORT: (0, envalid_1.port)({ default: 5432 }),
10
+ PGDATABASE: (0, envalid_1.str)({ default: 'jobs' }),
11
+ JOBS_SCHEMA: (0, envalid_1.str)({ default: 'app_jobs' }),
12
+ JOBS_SUPPORT_ANY: (0, envalid_1.bool)({ default: true }),
13
+ JOBS_SUPPORTED: array({ default: '' }),
14
+ HOSTNAME: (0, envalid_1.str)({
15
+ default: 'scheduler-0'
16
+ })
17
+ }, { dotEnvPath: null });
@@ -0,0 +1,44 @@
1
+ import type { PgClientLike } from '@constructive-io/job-utils';
2
+ import type { Pool } from 'pg';
3
+ export interface ScheduledJobRow {
4
+ id: number | string;
5
+ task_identifier: string;
6
+ schedule_info: unknown;
7
+ }
8
+ interface SchedulerJobHandle {
9
+ cancel(): void;
10
+ }
11
+ export default class Scheduler {
12
+ idleDelay: number;
13
+ supportedTaskNames: string[];
14
+ workerId: string;
15
+ doNextTimer?: NodeJS.Timeout;
16
+ pgPool: Pool;
17
+ jobs: Record<ScheduledJobRow['id'], SchedulerJobHandle>;
18
+ _initialized?: boolean;
19
+ constructor({ tasks, idleDelay, pgPool, workerId }: {
20
+ tasks: string[];
21
+ idleDelay?: number;
22
+ pgPool?: Pool;
23
+ workerId?: string;
24
+ });
25
+ initialize(client: PgClientLike): Promise<void>;
26
+ handleFatalError(client: PgClientLike, { err, fatalError, jobId }: {
27
+ err?: Error;
28
+ fatalError: unknown;
29
+ jobId: ScheduledJobRow['id'];
30
+ }): Promise<void>;
31
+ handleError(client: PgClientLike, { err, job, duration }: {
32
+ err: Error;
33
+ job: ScheduledJobRow;
34
+ duration: string;
35
+ }): Promise<void>;
36
+ handleSuccess(client: PgClientLike, { job, duration }: {
37
+ job: ScheduledJobRow;
38
+ duration: string;
39
+ }): Promise<void>;
40
+ scheduleJob(client: PgClientLike, job: ScheduledJobRow): Promise<void>;
41
+ doNext(client: PgClientLike): Promise<void>;
42
+ listen(): void;
43
+ }
44
+ export { Scheduler };
package/dist/index.js ADDED
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.Scheduler = void 0;
40
+ const jobs = __importStar(require("@constructive-io/job-utils"));
41
+ const node_schedule_1 = __importDefault(require("node-schedule"));
42
+ const job_pg_1 = __importDefault(require("@constructive-io/job-pg"));
43
+ const logger_1 = require("@pgpmjs/logger");
44
+ const log = new logger_1.Logger('jobs:scheduler');
45
+ class Scheduler {
46
+ idleDelay;
47
+ supportedTaskNames;
48
+ workerId;
49
+ doNextTimer;
50
+ pgPool;
51
+ jobs;
52
+ _initialized;
53
+ constructor({ tasks, idleDelay = 15000, pgPool = job_pg_1.default.getPool(), workerId = 'scheduler-0' }) {
54
+ /*
55
+ * idleDelay: This is how long to wait between polling for jobs.
56
+ *
57
+ * Note: this does NOT need to be short, because we use LISTEN/NOTIFY to be
58
+ * notified when new jobs are added - this is just used in the case where
59
+ * LISTEN/NOTIFY fails for whatever reason.
60
+ */
61
+ this.idleDelay = idleDelay;
62
+ this.supportedTaskNames = tasks;
63
+ this.workerId = workerId;
64
+ this.doNextTimer = undefined;
65
+ this.pgPool = pgPool;
66
+ this.jobs = {};
67
+ job_pg_1.default.onClose(async () => {
68
+ await jobs.releaseScheduledJobs(pgPool, {
69
+ workerId: this.workerId,
70
+ // When ids is omitted the DB function releases all scheduled jobs
71
+ ids: undefined
72
+ });
73
+ });
74
+ }
75
+ async initialize(client) {
76
+ if (this._initialized === true)
77
+ return;
78
+ await jobs.releaseScheduledJobs(client, {
79
+ workerId: this.workerId,
80
+ // When ids is omitted the DB function releases all scheduled jobs
81
+ ids: undefined
82
+ });
83
+ this._initialized = true;
84
+ await this.doNext(client);
85
+ }
86
+ async handleFatalError(client, { err, fatalError, jobId }) {
87
+ const when = err ? `after failure '${err.message}'` : 'after success';
88
+ log.error(`Failed to release job '${jobId}' ${when}; committing seppuku`);
89
+ log.error(String(fatalError));
90
+ await job_pg_1.default.close();
91
+ process.exit(1);
92
+ }
93
+ async handleError(client, { err, job, duration }) {
94
+ log.error(`Failed to initialize scheduler for ${job.id} (${job.task_identifier}) with error ${err.message} (${duration}ms)`);
95
+ const j = this.jobs[job.id];
96
+ if (j)
97
+ j.cancel();
98
+ await jobs.releaseScheduledJobs(client, {
99
+ workerId: this.workerId,
100
+ ids: [job.id]
101
+ });
102
+ }
103
+ async handleSuccess(client, { job, duration }) {
104
+ log.info(`initialized ${job.id} (${job.task_identifier}) with success (${duration}ms)`);
105
+ }
106
+ async scheduleJob(client, job) {
107
+ const { id, task_identifier, schedule_info } = job;
108
+ const j = node_schedule_1.default.scheduleJob(schedule_info, async () => {
109
+ const newjob = (await jobs.runScheduledJob(client, {
110
+ jobId: id
111
+ }));
112
+ if (newjob) {
113
+ if (newjob.id) {
114
+ log.info(`spinning up job[${newjob.task_identifier}]`);
115
+ }
116
+ else {
117
+ // this means the scheduled_job has been deleted from db, so cancel it
118
+ log.info(`attempted job[${job.task_identifier}] but it's probably non existent, unscheduling...`);
119
+ const scheduledJob = this.jobs[job.id];
120
+ if (scheduledJob)
121
+ scheduledJob.cancel();
122
+ }
123
+ }
124
+ else {
125
+ log.info(`job already scheduled but not yet run or complete: [${job.task_identifier}]`);
126
+ }
127
+ });
128
+ this.jobs[id] = j;
129
+ }
130
+ async doNext(client) {
131
+ if (!this._initialized) {
132
+ return await this.initialize(client);
133
+ }
134
+ if (this.doNextTimer) {
135
+ clearTimeout(this.doNextTimer);
136
+ this.doNextTimer = undefined;
137
+ }
138
+ try {
139
+ const job = await jobs.getScheduledJob(client, {
140
+ workerId: this.workerId,
141
+ supportedTaskNames: jobs.getJobSupportAny()
142
+ ? null
143
+ : this.supportedTaskNames
144
+ });
145
+ if (!job || !job.id) {
146
+ this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
147
+ return;
148
+ }
149
+ const start = process.hrtime();
150
+ let err = null;
151
+ try {
152
+ await this.scheduleJob(client, job);
153
+ }
154
+ catch (error) {
155
+ err = error;
156
+ }
157
+ const durationRaw = process.hrtime(start);
158
+ const duration = ((durationRaw[0] * 1e9 + durationRaw[1]) / 1e6).toFixed(2);
159
+ const jobId = job.id;
160
+ try {
161
+ if (err) {
162
+ await this.handleError(client, { err, job, duration });
163
+ }
164
+ else {
165
+ await this.handleSuccess(client, { job, duration });
166
+ }
167
+ }
168
+ catch (fatalError) {
169
+ await this.handleFatalError(client, { err, fatalError, jobId });
170
+ }
171
+ return this.doNext(client);
172
+ }
173
+ catch (err) {
174
+ this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
175
+ }
176
+ }
177
+ listen() {
178
+ const listenForChanges = (err, client, release) => {
179
+ if (err) {
180
+ log.error('Error connecting with notify listener', err);
181
+ if (err instanceof Error && err.stack) {
182
+ log.debug(err.stack);
183
+ }
184
+ // Try again in 5 seconds
185
+ // should this really be done in the node process?
186
+ setTimeout(this.listen, 5000);
187
+ return;
188
+ }
189
+ client.on('notification', () => {
190
+ log.info('a NEW scheduled JOB!');
191
+ if (this.doNextTimer) {
192
+ // Must be idle, do something!
193
+ this.doNext(client);
194
+ }
195
+ });
196
+ client.query('LISTEN "scheduled_jobs:insert"');
197
+ client.on('error', (e) => {
198
+ log.error('Error with database notify listener', e);
199
+ if (e instanceof Error && e.stack) {
200
+ log.debug(e.stack);
201
+ }
202
+ release();
203
+ this.listen();
204
+ });
205
+ log.info(`${this.workerId} connected and looking for scheduled jobs...`);
206
+ this.doNext(client);
207
+ };
208
+ this.pgPool.connect(listenForChanges);
209
+ }
210
+ }
211
+ exports.default = Scheduler;
212
+ exports.Scheduler = Scheduler;
package/dist/run.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/run.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const index_1 = __importDefault(require("./index"));
8
+ const job_pg_1 = __importDefault(require("@constructive-io/job-pg"));
9
+ const job_utils_1 = require("@constructive-io/job-utils");
10
+ const pgPool = job_pg_1.default.getPool();
11
+ const scheduler = new index_1.default({
12
+ pgPool,
13
+ workerId: (0, job_utils_1.getSchedulerHostname)(),
14
+ tasks: (0, job_utils_1.getJobSupported)()
15
+ });
16
+ scheduler.listen();
package/jest.config.js ADDED
@@ -0,0 +1,18 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ transform: {
6
+ '^.+\\.tsx?$': [
7
+ 'ts-jest',
8
+ {
9
+ babelConfig: false,
10
+ tsconfig: 'tsconfig.json',
11
+ },
12
+ ],
13
+ },
14
+ transformIgnorePatterns: [`/node_modules/*`],
15
+ testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
16
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
17
+ modulePathIgnorePatterns: ['dist/*'],
18
+ };
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@constructive-io/job-scheduler",
3
+ "version": "0.3.7",
4
+ "description": "job scheduler",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "homepage": "https://github.com/constructive-io/jobs/tree/master/packages/job-scheduler#readme",
7
+ "license": "SEE LICENSE IN LICENSE",
8
+ "main": "dist/index.js",
9
+ "directories": {
10
+ "lib": "src",
11
+ "test": "__tests__"
12
+ },
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/constructive-io/jobs"
19
+ },
20
+ "scripts": {
21
+ "test": "jest",
22
+ "test:watch": "jest --watch",
23
+ "test:debug": "node --inspect node_modules/.bin/jest --runInBand",
24
+ "build": "tsc -p tsconfig.json",
25
+ "build:watch": "tsc -p tsconfig.json -w"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/constructive-io/jobs/issues"
29
+ },
30
+ "dependencies": {
31
+ "@constructive-io/job-pg": "^0.3.5",
32
+ "@constructive-io/job-utils": "^0.5.0",
33
+ "@pgpmjs/logger": "^1.3.3",
34
+ "node-schedule": "1.3.2"
35
+ },
36
+ "gitHead": "86d74dc4fce9051df0d2b5bcc163607aba42f009"
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,229 @@
1
+ import * as jobs from '@constructive-io/job-utils';
2
+ import type { PgClientLike } from '@constructive-io/job-utils';
3
+ import schedule from 'node-schedule';
4
+ import poolManager from '@constructive-io/job-pg';
5
+ import type { Pool, PoolClient } from 'pg';
6
+ import { Logger } from '@pgpmjs/logger';
7
+
8
+ export interface ScheduledJobRow {
9
+ id: number | string;
10
+ task_identifier: string;
11
+ schedule_info: unknown;
12
+ }
13
+
14
+ interface SchedulerJobHandle {
15
+ cancel(): void;
16
+ }
17
+
18
+ const log = new Logger('jobs:scheduler');
19
+
20
+ export default class Scheduler {
21
+ idleDelay: number;
22
+ supportedTaskNames: string[];
23
+ workerId: string;
24
+ doNextTimer?: NodeJS.Timeout;
25
+ pgPool: Pool;
26
+ jobs: Record<ScheduledJobRow['id'], SchedulerJobHandle>;
27
+ _initialized?: boolean;
28
+
29
+ constructor({
30
+ tasks,
31
+ idleDelay = 15000,
32
+ pgPool = poolManager.getPool(),
33
+ workerId = 'scheduler-0'
34
+ }: {
35
+ tasks: string[];
36
+ idleDelay?: number;
37
+ pgPool?: Pool;
38
+ workerId?: string;
39
+ }) {
40
+ /*
41
+ * idleDelay: This is how long to wait between polling for jobs.
42
+ *
43
+ * Note: this does NOT need to be short, because we use LISTEN/NOTIFY to be
44
+ * notified when new jobs are added - this is just used in the case where
45
+ * LISTEN/NOTIFY fails for whatever reason.
46
+ */
47
+ this.idleDelay = idleDelay;
48
+ this.supportedTaskNames = tasks;
49
+ this.workerId = workerId;
50
+ this.doNextTimer = undefined;
51
+ this.pgPool = pgPool;
52
+ this.jobs = {};
53
+ poolManager.onClose(async () => {
54
+ await jobs.releaseScheduledJobs(pgPool, {
55
+ workerId: this.workerId,
56
+ // When ids is omitted the DB function releases all scheduled jobs
57
+ ids: undefined as unknown as Array<number | string>
58
+ });
59
+ });
60
+ }
61
+ async initialize(client: PgClientLike) {
62
+ if (this._initialized === true) return;
63
+ await jobs.releaseScheduledJobs(client, {
64
+ workerId: this.workerId,
65
+ // When ids is omitted the DB function releases all scheduled jobs
66
+ ids: undefined as unknown as Array<number | string>
67
+ });
68
+ this._initialized = true;
69
+ await this.doNext(client);
70
+ }
71
+ async handleFatalError(
72
+ client: PgClientLike,
73
+ {
74
+ err,
75
+ fatalError,
76
+ jobId
77
+ }: { err?: Error; fatalError: unknown; jobId: ScheduledJobRow['id'] }
78
+ ) {
79
+ const when = err ? `after failure '${err.message}'` : 'after success';
80
+ log.error(`Failed to release job '${jobId}' ${when}; committing seppuku`);
81
+ log.error(String(fatalError));
82
+ await poolManager.close();
83
+ process.exit(1);
84
+ }
85
+ async handleError(
86
+ client: PgClientLike,
87
+ {
88
+ err,
89
+ job,
90
+ duration
91
+ }: { err: Error; job: ScheduledJobRow; duration: string }
92
+ ) {
93
+ log.error(
94
+ `Failed to initialize scheduler for ${job.id} (${job.task_identifier}) with error ${err.message} (${duration}ms)`
95
+ );
96
+ const j = this.jobs[job.id];
97
+ if (j) j.cancel();
98
+ await jobs.releaseScheduledJobs(client, {
99
+ workerId: this.workerId,
100
+ ids: [job.id]
101
+ });
102
+ }
103
+ async handleSuccess(
104
+ client: PgClientLike,
105
+ { job, duration }: { job: ScheduledJobRow; duration: string }
106
+ ) {
107
+ log.info(
108
+ `initialized ${job.id} (${job.task_identifier}) with success (${duration}ms)`
109
+ );
110
+ }
111
+ async scheduleJob(client: PgClientLike, job: ScheduledJobRow) {
112
+ const { id, task_identifier, schedule_info } = job;
113
+ const j = schedule.scheduleJob(schedule_info as never, async () => {
114
+ const newjob = (await jobs.runScheduledJob(client, {
115
+ jobId: id
116
+ })) as ScheduledJobRow | null;
117
+
118
+ if (newjob) {
119
+ if (newjob.id) {
120
+ log.info(`spinning up job[${newjob.task_identifier}]`);
121
+ } else {
122
+ // this means the scheduled_job has been deleted from db, so cancel it
123
+ log.info(
124
+ `attempted job[${job.task_identifier}] but it's probably non existent, unscheduling...`
125
+ );
126
+ const scheduledJob = this.jobs[job.id];
127
+ if (scheduledJob) scheduledJob.cancel();
128
+ }
129
+ } else {
130
+ log.info(
131
+ `job already scheduled but not yet run or complete: [${job.task_identifier}]`
132
+ );
133
+ }
134
+ });
135
+ this.jobs[id] = j as SchedulerJobHandle;
136
+ }
137
+ async doNext(client: PgClientLike): Promise<void> {
138
+ if (!this._initialized) {
139
+ return await this.initialize(client);
140
+ }
141
+
142
+ if (this.doNextTimer) {
143
+ clearTimeout(this.doNextTimer);
144
+ this.doNextTimer = undefined;
145
+ }
146
+ try {
147
+ const job = await jobs.getScheduledJob<ScheduledJobRow>(client, {
148
+ workerId: this.workerId,
149
+ supportedTaskNames: jobs.getJobSupportAny()
150
+ ? null
151
+ : this.supportedTaskNames
152
+ });
153
+ if (!job || !job.id) {
154
+ this.doNextTimer = setTimeout(
155
+ () => this.doNext(client),
156
+ this.idleDelay
157
+ );
158
+ return;
159
+ }
160
+ const start = process.hrtime();
161
+
162
+ let err: Error | null = null;
163
+ try {
164
+ await this.scheduleJob(client, job);
165
+ } catch (error) {
166
+ err = error as Error;
167
+ }
168
+
169
+ const durationRaw = process.hrtime(start);
170
+ const duration = ((durationRaw[0] * 1e9 + durationRaw[1]) / 1e6).toFixed(
171
+ 2
172
+ );
173
+ const jobId = job.id;
174
+ try {
175
+ if (err) {
176
+ await this.handleError(client, { err, job, duration });
177
+ } else {
178
+ await this.handleSuccess(client, { job, duration });
179
+ }
180
+ } catch (fatalError: unknown) {
181
+ await this.handleFatalError(client, { err, fatalError, jobId });
182
+ }
183
+ return this.doNext(client);
184
+ } catch (err: unknown) {
185
+ this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
186
+ }
187
+ }
188
+ listen() {
189
+ const listenForChanges = (
190
+ err: Error | null,
191
+ client: PoolClient,
192
+ release: () => void
193
+ ) => {
194
+ if (err) {
195
+ log.error('Error connecting with notify listener', err);
196
+ if (err instanceof Error && err.stack) {
197
+ log.debug(err.stack);
198
+ }
199
+ // Try again in 5 seconds
200
+ // should this really be done in the node process?
201
+ setTimeout(this.listen, 5000);
202
+ return;
203
+ }
204
+ client.on('notification', () => {
205
+ log.info('a NEW scheduled JOB!');
206
+ if (this.doNextTimer) {
207
+ // Must be idle, do something!
208
+ this.doNext(client);
209
+ }
210
+ });
211
+ client.query('LISTEN "scheduled_jobs:insert"');
212
+ client.on('error', (e: unknown) => {
213
+ log.error('Error with database notify listener', e);
214
+ if (e instanceof Error && e.stack) {
215
+ log.debug(e.stack);
216
+ }
217
+ release();
218
+ this.listen();
219
+ });
220
+ log.info(
221
+ `${this.workerId} connected and looking for scheduled jobs...`
222
+ );
223
+ this.doNext(client);
224
+ };
225
+ this.pgPool.connect(listenForChanges);
226
+ }
227
+ }
228
+
229
+ export { Scheduler };
package/src/run.ts ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+
3
+ import Scheduler from './index';
4
+ import poolManager from '@constructive-io/job-pg';
5
+ import {
6
+ getSchedulerHostname,
7
+ getJobSupported
8
+ } from '@constructive-io/job-utils';
9
+
10
+ const pgPool = poolManager.getPool();
11
+
12
+ const scheduler = new Scheduler({
13
+ pgPool,
14
+ workerId: getSchedulerHostname(),
15
+ tasks: getJobSupported()
16
+ });
17
+
18
+ scheduler.listen();
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist/esm",
5
+ "module": "es2022",
6
+ "rootDir": "src/",
7
+ "declaration": false
8
+ }
9
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src/"
6
+ },
7
+ "include": ["src/**/*.ts", "../../types/**/*.d.ts"],
8
+ "exclude": ["dist", "node_modules", "**/*.spec.*", "**/*.test.*"]
9
+ }