@constructive-io/job-worker 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 +12 -0
- package/LICENSE +23 -0
- package/README.md +1 -0
- package/dist/env.d.ts +11 -0
- package/dist/env.js +11 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +192 -0
- package/dist/run.d.ts +1 -0
- package/dist/run.js +16 -0
- package/jest.config.js +18 -0
- package/package.json +35 -0
- package/src/index.ts +220 -0
- package/src/run.ts +16 -0
- package/tsconfig.esm.json +9 -0
- package/tsconfig.json +9 -0
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-worker
|
|
9
|
+
|
|
10
|
+
## [0.3.6](https://github.com/constructive-io/jobs/compare/@launchql/job-worker@0.3.5...@launchql/job-worker@0.3.6) (2025-12-17)
|
|
11
|
+
|
|
12
|
+
**Note:** Version bump only for package @launchql/job-worker
|
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-worker
|
package/dist/env.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
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
|
+
}> & import("envalid").CleanEnv & {
|
|
9
|
+
readonly [varName: string]: string;
|
|
10
|
+
};
|
|
11
|
+
export default _default;
|
package/dist/env.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const envalid_1 = require("envalid");
|
|
4
|
+
exports.default = (0, envalid_1.cleanEnv)(process.env, {
|
|
5
|
+
PGUSER: (0, envalid_1.str)({ default: 'postgres' }),
|
|
6
|
+
PGHOST: (0, envalid_1.str)({ default: 'localhost' }),
|
|
7
|
+
PGPASSWORD: (0, envalid_1.str)({ default: 'password' }),
|
|
8
|
+
PGPORT: (0, envalid_1.port)({ default: 5432 }),
|
|
9
|
+
PGDATABASE: (0, envalid_1.str)({ default: 'jobs' }),
|
|
10
|
+
JOBS_SCHEMA: (0, envalid_1.str)({ default: 'app_jobs' })
|
|
11
|
+
}, { dotEnvPath: null });
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
import type { PgClientLike } from '@constructive-io/job-utils';
|
|
3
|
+
export interface JobRow {
|
|
4
|
+
id: number | string;
|
|
5
|
+
task_identifier: string;
|
|
6
|
+
payload?: unknown;
|
|
7
|
+
}
|
|
8
|
+
export interface WorkerContext {
|
|
9
|
+
pgPool: Pool;
|
|
10
|
+
workerId: string;
|
|
11
|
+
}
|
|
12
|
+
export type TaskHandler = (ctx: WorkerContext, job: JobRow) => Promise<void> | void;
|
|
13
|
+
export default class Worker {
|
|
14
|
+
tasks: Record<string, TaskHandler>;
|
|
15
|
+
idleDelay: number;
|
|
16
|
+
supportedTaskNames: string[];
|
|
17
|
+
workerId: string;
|
|
18
|
+
doNextTimer?: NodeJS.Timeout;
|
|
19
|
+
pgPool: Pool;
|
|
20
|
+
_ended?: boolean;
|
|
21
|
+
constructor({ tasks, idleDelay, pgPool, workerId }: {
|
|
22
|
+
tasks: Record<string, TaskHandler>;
|
|
23
|
+
idleDelay?: number;
|
|
24
|
+
pgPool?: Pool;
|
|
25
|
+
workerId?: string;
|
|
26
|
+
});
|
|
27
|
+
close(): void;
|
|
28
|
+
handleFatalError({ err, fatalError, jobId }: {
|
|
29
|
+
err?: Error;
|
|
30
|
+
fatalError: unknown;
|
|
31
|
+
jobId: JobRow['id'];
|
|
32
|
+
}): void;
|
|
33
|
+
handleError(client: PgClientLike, { err, job, duration }: {
|
|
34
|
+
err: Error;
|
|
35
|
+
job: JobRow;
|
|
36
|
+
duration: string;
|
|
37
|
+
}): Promise<void>;
|
|
38
|
+
handleSuccess(client: PgClientLike, { job, duration }: {
|
|
39
|
+
job: JobRow;
|
|
40
|
+
duration: string;
|
|
41
|
+
}): Promise<void>;
|
|
42
|
+
doWork(job: JobRow): Promise<void>;
|
|
43
|
+
doNext(client: PgClientLike): Promise<void>;
|
|
44
|
+
listen(): void;
|
|
45
|
+
}
|
|
46
|
+
export { Worker };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
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.Worker = void 0;
|
|
40
|
+
const pg_1 = __importDefault(require("pg"));
|
|
41
|
+
const jobs = __importStar(require("@constructive-io/job-utils"));
|
|
42
|
+
const pgPoolConfig = {
|
|
43
|
+
connectionString: jobs.getJobConnectionString()
|
|
44
|
+
};
|
|
45
|
+
function once(fn, context) {
|
|
46
|
+
let result;
|
|
47
|
+
return function (...args) {
|
|
48
|
+
if (fn) {
|
|
49
|
+
result = fn.apply((context ?? this), args);
|
|
50
|
+
fn = null;
|
|
51
|
+
}
|
|
52
|
+
return result;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/* eslint-disable no-console */
|
|
56
|
+
class Worker {
|
|
57
|
+
tasks;
|
|
58
|
+
idleDelay;
|
|
59
|
+
supportedTaskNames;
|
|
60
|
+
workerId;
|
|
61
|
+
doNextTimer;
|
|
62
|
+
pgPool;
|
|
63
|
+
_ended;
|
|
64
|
+
// tasks is required; other options are optional
|
|
65
|
+
constructor({ tasks, idleDelay = 15000, pgPool = new pg_1.default.Pool(pgPoolConfig), workerId = jobs.getWorkerHostname() }) {
|
|
66
|
+
this.tasks = tasks;
|
|
67
|
+
/*
|
|
68
|
+
* idleDelay: This is how long to wait between polling for jobs.
|
|
69
|
+
*
|
|
70
|
+
* Note: this does NOT need to be short, because we use LISTEN/NOTIFY to be
|
|
71
|
+
* notified when new jobs are added - this is just used in the case where
|
|
72
|
+
* LISTEN/NOTIFY fails for whatever reason.
|
|
73
|
+
*/
|
|
74
|
+
this.idleDelay = idleDelay;
|
|
75
|
+
this.supportedTaskNames = Object.keys(this.tasks);
|
|
76
|
+
this.workerId = workerId;
|
|
77
|
+
this.doNextTimer = undefined;
|
|
78
|
+
this.pgPool = pgPool;
|
|
79
|
+
const close = () => {
|
|
80
|
+
console.log('closing connection...');
|
|
81
|
+
this.close();
|
|
82
|
+
};
|
|
83
|
+
process.once('SIGTERM', close);
|
|
84
|
+
process.once('SIGINT', close);
|
|
85
|
+
}
|
|
86
|
+
close() {
|
|
87
|
+
if (!this._ended) {
|
|
88
|
+
this.pgPool.end();
|
|
89
|
+
}
|
|
90
|
+
this._ended = true;
|
|
91
|
+
}
|
|
92
|
+
handleFatalError({ err, fatalError, jobId }) {
|
|
93
|
+
const when = err ? `after failure '${err.message}'` : 'after success';
|
|
94
|
+
console.error(`Failed to release job '${jobId}' ${when}; committing seppuku`);
|
|
95
|
+
console.error(fatalError);
|
|
96
|
+
process.exit(1);
|
|
97
|
+
}
|
|
98
|
+
async handleError(client, { err, job, duration }) {
|
|
99
|
+
console.error(`Failed task ${job.id} (${job.task_identifier}) with error ${err.message} (${duration}ms)`, { err, stack: err.stack });
|
|
100
|
+
console.error(err.stack);
|
|
101
|
+
await jobs.failJob(client, {
|
|
102
|
+
workerId: this.workerId,
|
|
103
|
+
jobId: job.id,
|
|
104
|
+
message: err.message
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
async handleSuccess(client, { job, duration }) {
|
|
108
|
+
console.log(`Completed task ${job.id} (${job.task_identifier}) with success (${duration}ms)`);
|
|
109
|
+
await jobs.completeJob(client, { workerId: this.workerId, jobId: job.id });
|
|
110
|
+
}
|
|
111
|
+
async doWork(job) {
|
|
112
|
+
const { task_identifier } = job;
|
|
113
|
+
const worker = this.tasks[task_identifier];
|
|
114
|
+
if (!worker) {
|
|
115
|
+
throw new Error('Unsupported task');
|
|
116
|
+
}
|
|
117
|
+
await worker({
|
|
118
|
+
pgPool: this.pgPool,
|
|
119
|
+
workerId: this.workerId
|
|
120
|
+
}, job);
|
|
121
|
+
}
|
|
122
|
+
async doNext(client) {
|
|
123
|
+
if (this.doNextTimer) {
|
|
124
|
+
clearTimeout(this.doNextTimer);
|
|
125
|
+
this.doNextTimer = undefined;
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
const job = (await jobs.getJob(client, {
|
|
129
|
+
workerId: this.workerId,
|
|
130
|
+
supportedTaskNames: this.supportedTaskNames
|
|
131
|
+
}));
|
|
132
|
+
if (!job || !job.id) {
|
|
133
|
+
this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const start = process.hrtime();
|
|
137
|
+
let err = null;
|
|
138
|
+
try {
|
|
139
|
+
await this.doWork(job);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
err = error;
|
|
143
|
+
}
|
|
144
|
+
const durationRaw = process.hrtime(start);
|
|
145
|
+
const duration = ((durationRaw[0] * 1e9 + durationRaw[1]) / 1e6).toFixed(2);
|
|
146
|
+
const jobId = job.id;
|
|
147
|
+
try {
|
|
148
|
+
if (err) {
|
|
149
|
+
await this.handleError(client, { err, job, duration });
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
await this.handleSuccess(client, { job, duration });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
catch (fatalError) {
|
|
156
|
+
this.handleFatalError({ err, fatalError, jobId });
|
|
157
|
+
}
|
|
158
|
+
return this.doNext(client);
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
listen() {
|
|
165
|
+
const listenForChanges = (err, client, release) => {
|
|
166
|
+
if (err) {
|
|
167
|
+
console.error('Error connecting with notify listener', err);
|
|
168
|
+
// Try again in 5 seconds
|
|
169
|
+
// should this really be done in the node process?
|
|
170
|
+
setTimeout(this.listen, 5000);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
client.on('notification', () => {
|
|
174
|
+
if (this.doNextTimer) {
|
|
175
|
+
// Must be idle, do something!
|
|
176
|
+
this.doNext(client);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
client.query('LISTEN "jobs:insert"');
|
|
180
|
+
client.on('error', (e) => {
|
|
181
|
+
console.error('Error with database notify listener', e);
|
|
182
|
+
release();
|
|
183
|
+
this.listen();
|
|
184
|
+
});
|
|
185
|
+
console.log(`${this.workerId} connected and looking for jobs...`);
|
|
186
|
+
this.doNext(client);
|
|
187
|
+
};
|
|
188
|
+
this.pgPool.connect(listenForChanges);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
exports.default = Worker;
|
|
192
|
+
exports.Worker = Worker;
|
package/dist/run.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/run.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
const index_1 = __importDefault(require("./index"));
|
|
7
|
+
const worker = new index_1.default({
|
|
8
|
+
tasks: {
|
|
9
|
+
hello: async ({ pgPool, workerId }, job) => {
|
|
10
|
+
console.log('hello');
|
|
11
|
+
await pgPool.query('select 1');
|
|
12
|
+
console.log(JSON.stringify(job, null, 2));
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
worker.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,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@constructive-io/job-worker",
|
|
3
|
+
"version": "0.3.7",
|
|
4
|
+
"description": "job worker",
|
|
5
|
+
"author": "Constructive <developers@constructive.io>",
|
|
6
|
+
"homepage": "https://github.com/constructive-io/jobs/tree/master/packages/job-worker#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-utils": "^0.5.0",
|
|
32
|
+
"pg": "8.16.3"
|
|
33
|
+
},
|
|
34
|
+
"gitHead": "86d74dc4fce9051df0d2b5bcc163607aba42f009"
|
|
35
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
import type { Pool, PoolClient } from 'pg';
|
|
3
|
+
import * as jobs from '@constructive-io/job-utils';
|
|
4
|
+
import type { PgClientLike } from '@constructive-io/job-utils';
|
|
5
|
+
|
|
6
|
+
const pgPoolConfig = {
|
|
7
|
+
connectionString: jobs.getJobConnectionString()
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
function once<T extends (...args: unknown[]) => unknown>(
|
|
11
|
+
fn: T,
|
|
12
|
+
context?: unknown
|
|
13
|
+
): (...args: Parameters<T>) => ReturnType<T> | undefined {
|
|
14
|
+
let result: ReturnType<T> | undefined;
|
|
15
|
+
return function (this: unknown, ...args: Parameters<T>) {
|
|
16
|
+
if (fn) {
|
|
17
|
+
result = fn.apply((context ?? this) as never, args) as ReturnType<T>;
|
|
18
|
+
fn = null as unknown as T;
|
|
19
|
+
}
|
|
20
|
+
return result;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface JobRow {
|
|
25
|
+
id: number | string;
|
|
26
|
+
task_identifier: string;
|
|
27
|
+
payload?: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface WorkerContext {
|
|
31
|
+
pgPool: Pool;
|
|
32
|
+
workerId: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type TaskHandler = (
|
|
36
|
+
ctx: WorkerContext,
|
|
37
|
+
job: JobRow
|
|
38
|
+
) => Promise<void> | void;
|
|
39
|
+
|
|
40
|
+
/* eslint-disable no-console */
|
|
41
|
+
|
|
42
|
+
export default class Worker {
|
|
43
|
+
tasks: Record<string, TaskHandler>;
|
|
44
|
+
idleDelay: number;
|
|
45
|
+
supportedTaskNames: string[];
|
|
46
|
+
workerId: string;
|
|
47
|
+
doNextTimer?: NodeJS.Timeout;
|
|
48
|
+
pgPool: Pool;
|
|
49
|
+
_ended?: boolean;
|
|
50
|
+
|
|
51
|
+
// tasks is required; other options are optional
|
|
52
|
+
constructor({
|
|
53
|
+
tasks,
|
|
54
|
+
idleDelay = 15000,
|
|
55
|
+
pgPool = new (pg as any).Pool(pgPoolConfig),
|
|
56
|
+
workerId = jobs.getWorkerHostname()
|
|
57
|
+
}: {
|
|
58
|
+
tasks: Record<string, TaskHandler>;
|
|
59
|
+
idleDelay?: number;
|
|
60
|
+
pgPool?: Pool;
|
|
61
|
+
workerId?: string;
|
|
62
|
+
}) {
|
|
63
|
+
this.tasks = tasks;
|
|
64
|
+
/*
|
|
65
|
+
* idleDelay: This is how long to wait between polling for jobs.
|
|
66
|
+
*
|
|
67
|
+
* Note: this does NOT need to be short, because we use LISTEN/NOTIFY to be
|
|
68
|
+
* notified when new jobs are added - this is just used in the case where
|
|
69
|
+
* LISTEN/NOTIFY fails for whatever reason.
|
|
70
|
+
*/
|
|
71
|
+
this.idleDelay = idleDelay;
|
|
72
|
+
|
|
73
|
+
this.supportedTaskNames = Object.keys(this.tasks);
|
|
74
|
+
this.workerId = workerId;
|
|
75
|
+
this.doNextTimer = undefined;
|
|
76
|
+
this.pgPool = pgPool;
|
|
77
|
+
const close = () => {
|
|
78
|
+
console.log('closing connection...');
|
|
79
|
+
this.close();
|
|
80
|
+
};
|
|
81
|
+
process.once('SIGTERM', close);
|
|
82
|
+
process.once('SIGINT', close);
|
|
83
|
+
}
|
|
84
|
+
close() {
|
|
85
|
+
if (!this._ended) {
|
|
86
|
+
this.pgPool.end();
|
|
87
|
+
}
|
|
88
|
+
this._ended = true;
|
|
89
|
+
}
|
|
90
|
+
handleFatalError({
|
|
91
|
+
err,
|
|
92
|
+
fatalError,
|
|
93
|
+
jobId
|
|
94
|
+
}: {
|
|
95
|
+
err?: Error;
|
|
96
|
+
fatalError: unknown;
|
|
97
|
+
jobId: JobRow['id'];
|
|
98
|
+
}) {
|
|
99
|
+
const when = err ? `after failure '${err.message}'` : 'after success';
|
|
100
|
+
console.error(
|
|
101
|
+
`Failed to release job '${jobId}' ${when}; committing seppuku`
|
|
102
|
+
);
|
|
103
|
+
console.error(fatalError);
|
|
104
|
+
process.exit(1);
|
|
105
|
+
}
|
|
106
|
+
async handleError(
|
|
107
|
+
client: PgClientLike,
|
|
108
|
+
{ err, job, duration }: { err: Error; job: JobRow; duration: string }
|
|
109
|
+
) {
|
|
110
|
+
console.error(
|
|
111
|
+
`Failed task ${job.id} (${job.task_identifier}) with error ${err.message} (${duration}ms)`,
|
|
112
|
+
{ err, stack: err.stack }
|
|
113
|
+
);
|
|
114
|
+
console.error(err.stack);
|
|
115
|
+
await jobs.failJob(client, {
|
|
116
|
+
workerId: this.workerId,
|
|
117
|
+
jobId: job.id,
|
|
118
|
+
message: err.message
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
async handleSuccess(
|
|
122
|
+
client: PgClientLike,
|
|
123
|
+
{ job, duration }: { job: JobRow; duration: string }
|
|
124
|
+
) {
|
|
125
|
+
console.log(
|
|
126
|
+
`Completed task ${job.id} (${job.task_identifier}) with success (${duration}ms)`
|
|
127
|
+
);
|
|
128
|
+
await jobs.completeJob(client, { workerId: this.workerId, jobId: job.id });
|
|
129
|
+
}
|
|
130
|
+
async doWork(job: JobRow) {
|
|
131
|
+
const { task_identifier } = job;
|
|
132
|
+
const worker = this.tasks[task_identifier];
|
|
133
|
+
if (!worker) {
|
|
134
|
+
throw new Error('Unsupported task');
|
|
135
|
+
}
|
|
136
|
+
await worker(
|
|
137
|
+
{
|
|
138
|
+
pgPool: this.pgPool,
|
|
139
|
+
workerId: this.workerId
|
|
140
|
+
},
|
|
141
|
+
job
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
async doNext(client: PgClientLike): Promise<void> {
|
|
145
|
+
if (this.doNextTimer) {
|
|
146
|
+
clearTimeout(this.doNextTimer);
|
|
147
|
+
this.doNextTimer = undefined;
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const job = (await jobs.getJob<JobRow>(client, {
|
|
151
|
+
workerId: this.workerId,
|
|
152
|
+
supportedTaskNames: this.supportedTaskNames
|
|
153
|
+
})) as JobRow | undefined;
|
|
154
|
+
if (!job || !job.id) {
|
|
155
|
+
this.doNextTimer = setTimeout(
|
|
156
|
+
() => this.doNext(client),
|
|
157
|
+
this.idleDelay
|
|
158
|
+
);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const start = process.hrtime();
|
|
162
|
+
|
|
163
|
+
let err: Error | null = null;
|
|
164
|
+
try {
|
|
165
|
+
await this.doWork(job);
|
|
166
|
+
} catch (error) {
|
|
167
|
+
err = error as Error;
|
|
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
|
+
this.handleFatalError({ 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
|
+
console.error('Error connecting with notify listener', err);
|
|
196
|
+
// Try again in 5 seconds
|
|
197
|
+
// should this really be done in the node process?
|
|
198
|
+
setTimeout(this.listen, 5000);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
client.on('notification', () => {
|
|
202
|
+
if (this.doNextTimer) {
|
|
203
|
+
// Must be idle, do something!
|
|
204
|
+
this.doNext(client);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
client.query('LISTEN "jobs:insert"');
|
|
208
|
+
client.on('error', (e: unknown) => {
|
|
209
|
+
console.error('Error with database notify listener', e);
|
|
210
|
+
release();
|
|
211
|
+
this.listen();
|
|
212
|
+
});
|
|
213
|
+
console.log(`${this.workerId} connected and looking for jobs...`);
|
|
214
|
+
this.doNext(client);
|
|
215
|
+
};
|
|
216
|
+
this.pgPool.connect(listenForChanges);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export { Worker };
|
package/src/run.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import Worker, { WorkerContext, JobRow } from './index';
|
|
2
|
+
|
|
3
|
+
const worker = new Worker({
|
|
4
|
+
tasks: {
|
|
5
|
+
hello: async (
|
|
6
|
+
{ pgPool, workerId }: WorkerContext,
|
|
7
|
+
job: JobRow
|
|
8
|
+
) => {
|
|
9
|
+
console.log('hello');
|
|
10
|
+
await pgPool.query('select 1');
|
|
11
|
+
console.log(JSON.stringify(job, null, 2));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
worker.listen();
|