@constructive-io/job-worker 0.4.0 → 0.5.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 +1,59 @@
1
- # job-worker
1
+ # job-worker
2
+
3
+ ---
4
+
5
+ ## Education and Tutorials
6
+
7
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
8
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
9
+
10
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
11
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
12
+
13
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
14
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
15
+
16
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
17
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
18
+
19
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
20
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
21
+
22
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
23
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
24
+
25
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
26
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
27
+
28
+ ## Related Constructive Tooling
29
+
30
+ ### 📦 Package Management
31
+
32
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
33
+
34
+ ### 🧪 Testing
35
+
36
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
37
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
38
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
39
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
40
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
41
+
42
+ ### 🧠 Parsing & AST
43
+
44
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
45
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
46
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
47
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
48
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
49
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
50
+
51
+ ## Credits
52
+
53
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
54
+
55
+ ## Disclaimer
56
+
57
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
58
+
59
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.js ADDED
@@ -0,0 +1,153 @@
1
+ import pg from 'pg';
2
+ import * as jobs from '@constructive-io/job-utils';
3
+ import { createLogger } from '@pgpmjs/logger';
4
+ const pgPoolConfig = {
5
+ connectionString: jobs.getJobConnectionString()
6
+ };
7
+ function once(fn, context) {
8
+ let result;
9
+ return function (...args) {
10
+ if (fn) {
11
+ result = fn.apply((context ?? this), args);
12
+ fn = null;
13
+ }
14
+ return result;
15
+ };
16
+ }
17
+ const logger = createLogger('job-worker');
18
+ export default class Worker {
19
+ tasks;
20
+ idleDelay;
21
+ supportedTaskNames;
22
+ workerId;
23
+ doNextTimer;
24
+ pgPool;
25
+ _ended;
26
+ // tasks is required; other options are optional
27
+ constructor({ tasks, idleDelay = 15000, pgPool = new pg.Pool(pgPoolConfig), workerId = jobs.getWorkerHostname() }) {
28
+ this.tasks = tasks;
29
+ /*
30
+ * idleDelay: This is how long to wait between polling for jobs.
31
+ *
32
+ * Note: this does NOT need to be short, because we use LISTEN/NOTIFY to be
33
+ * notified when new jobs are added - this is just used in the case where
34
+ * LISTEN/NOTIFY fails for whatever reason.
35
+ */
36
+ this.idleDelay = idleDelay;
37
+ this.supportedTaskNames = Object.keys(this.tasks);
38
+ this.workerId = workerId;
39
+ this.doNextTimer = undefined;
40
+ this.pgPool = pgPool;
41
+ const close = () => {
42
+ logger.info('closing connection...');
43
+ this.close();
44
+ };
45
+ process.once('SIGTERM', close);
46
+ process.once('SIGINT', close);
47
+ }
48
+ close() {
49
+ if (!this._ended) {
50
+ this.pgPool.end();
51
+ }
52
+ this._ended = true;
53
+ }
54
+ handleFatalError({ err, fatalError, jobId }) {
55
+ const when = err ? `after failure '${err.message}'` : 'after success';
56
+ logger.error(`Failed to release job '${jobId}' ${when}; committing seppuku`);
57
+ logger.error(fatalError);
58
+ process.exit(1);
59
+ }
60
+ async handleError(client, { err, job, duration }) {
61
+ logger.error(`Failed task ${job.id} (${job.task_identifier}) with error ${err.message} (${duration}ms)`, { err, stack: err.stack });
62
+ logger.error(err.stack);
63
+ await jobs.failJob(client, {
64
+ workerId: this.workerId,
65
+ jobId: job.id,
66
+ message: err.message
67
+ });
68
+ }
69
+ async handleSuccess(client, { job, duration }) {
70
+ logger.info(`Completed task ${job.id} (${job.task_identifier}) with success (${duration}ms)`);
71
+ await jobs.completeJob(client, { workerId: this.workerId, jobId: job.id });
72
+ }
73
+ async doWork(job) {
74
+ const { task_identifier } = job;
75
+ const worker = this.tasks[task_identifier];
76
+ if (!worker) {
77
+ throw new Error('Unsupported task');
78
+ }
79
+ await worker({
80
+ pgPool: this.pgPool,
81
+ workerId: this.workerId
82
+ }, job);
83
+ }
84
+ async doNext(client) {
85
+ if (this.doNextTimer) {
86
+ clearTimeout(this.doNextTimer);
87
+ this.doNextTimer = undefined;
88
+ }
89
+ try {
90
+ const job = (await jobs.getJob(client, {
91
+ workerId: this.workerId,
92
+ supportedTaskNames: this.supportedTaskNames
93
+ }));
94
+ if (!job || !job.id) {
95
+ this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
96
+ return;
97
+ }
98
+ const start = process.hrtime();
99
+ let err = null;
100
+ try {
101
+ await this.doWork(job);
102
+ }
103
+ catch (error) {
104
+ err = error;
105
+ }
106
+ const durationRaw = process.hrtime(start);
107
+ const duration = ((durationRaw[0] * 1e9 + durationRaw[1]) / 1e6).toFixed(2);
108
+ const jobId = job.id;
109
+ try {
110
+ if (err) {
111
+ await this.handleError(client, { err, job, duration });
112
+ }
113
+ else {
114
+ await this.handleSuccess(client, { job, duration });
115
+ }
116
+ }
117
+ catch (fatalError) {
118
+ this.handleFatalError({ err, fatalError, jobId });
119
+ }
120
+ return this.doNext(client);
121
+ }
122
+ catch (err) {
123
+ this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
124
+ }
125
+ }
126
+ listen() {
127
+ const listenForChanges = (err, client, release) => {
128
+ if (err) {
129
+ logger.error('Error connecting with notify listener', err);
130
+ // Try again in 5 seconds
131
+ // should this really be done in the node process?
132
+ setTimeout(this.listen, 5000);
133
+ return;
134
+ }
135
+ client.on('notification', () => {
136
+ if (this.doNextTimer) {
137
+ // Must be idle, do something!
138
+ this.doNext(client);
139
+ }
140
+ });
141
+ client.query('LISTEN "jobs:insert"');
142
+ client.on('error', (e) => {
143
+ logger.error('Error with database notify listener', e);
144
+ release();
145
+ this.listen();
146
+ });
147
+ logger.info(`${this.workerId} connected and looking for jobs...`);
148
+ this.doNext(client);
149
+ };
150
+ this.pgPool.connect(listenForChanges);
151
+ }
152
+ }
153
+ export { Worker };
package/esm/run.js ADDED
@@ -0,0 +1,13 @@
1
+ import Worker from './index';
2
+ import { createLogger } from '@pgpmjs/logger';
3
+ const logger = createLogger('job-worker-run');
4
+ const worker = new Worker({
5
+ tasks: {
6
+ hello: async ({ pgPool, workerId }, job) => {
7
+ logger.info('hello');
8
+ await pgPool.query('select 1');
9
+ logger.info(JSON.stringify(job, null, 2));
10
+ }
11
+ }
12
+ });
13
+ worker.listen();
package/package.json CHANGED
@@ -1,17 +1,20 @@
1
1
  {
2
2
  "name": "@constructive-io/job-worker",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "job worker",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "homepage": "https://github.com/constructive-io/jobs/tree/master/packages/job-worker#readme",
7
7
  "license": "SEE LICENSE IN LICENSE",
8
- "main": "dist/index.js",
8
+ "main": "index.js",
9
+ "module": "esm/index.js",
10
+ "types": "index.d.ts",
9
11
  "directories": {
10
12
  "lib": "src",
11
13
  "test": "__tests__"
12
14
  },
13
15
  "publishConfig": {
14
- "access": "public"
16
+ "access": "public",
17
+ "directory": "dist"
15
18
  },
16
19
  "repository": {
17
20
  "type": "git",
@@ -21,16 +24,21 @@
21
24
  "test": "jest --passWithNoTests",
22
25
  "test:watch": "jest --watch",
23
26
  "test:debug": "node --inspect node_modules/.bin/jest --runInBand",
24
- "build": "tsc -p tsconfig.json",
25
- "build:watch": "tsc -p tsconfig.json -w"
27
+ "clean": "makage clean",
28
+ "prepack": "npm run build",
29
+ "build": "makage build",
30
+ "build:dev": "makage build --dev"
26
31
  },
27
32
  "bugs": {
28
33
  "url": "https://github.com/constructive-io/jobs/issues"
29
34
  },
35
+ "devDependencies": {
36
+ "makage": "^0.1.10"
37
+ },
30
38
  "dependencies": {
31
- "@constructive-io/job-utils": "^0.6.0",
32
- "@pgpmjs/logger": "^1.4.0",
33
- "pg": "8.16.3"
39
+ "@constructive-io/job-utils": "^0.7.0",
40
+ "@pgpmjs/logger": "^1.5.0",
41
+ "pg": "8.17.1"
34
42
  },
35
- "gitHead": "481b3a50b4eec2da6b376c4cd1868065e1e28edb"
43
+ "gitHead": "ec2b5f644c479626305ef85a05a6e7105c2c58cd"
36
44
  }
package/CHANGELOG.md DELETED
@@ -1,80 +0,0 @@
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.4.0](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.23...@constructive-io/job-worker@0.4.0) (2026-01-18)
7
-
8
- **Note:** Version bump only for package @constructive-io/job-worker
9
-
10
- ## [0.3.23](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.22...@constructive-io/job-worker@0.3.23) (2026-01-18)
11
-
12
- **Note:** Version bump only for package @constructive-io/job-worker
13
-
14
- ## [0.3.22](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.21...@constructive-io/job-worker@0.3.22) (2026-01-09)
15
-
16
- **Note:** Version bump only for package @constructive-io/job-worker
17
-
18
- ## [0.3.21](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.20...@constructive-io/job-worker@0.3.21) (2026-01-07)
19
-
20
- **Note:** Version bump only for package @constructive-io/job-worker
21
-
22
- ## [0.3.20](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.19...@constructive-io/job-worker@0.3.20) (2026-01-02)
23
-
24
- **Note:** Version bump only for package @constructive-io/job-worker
25
-
26
- ## [0.3.19](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.18...@constructive-io/job-worker@0.3.19) (2026-01-02)
27
-
28
- **Note:** Version bump only for package @constructive-io/job-worker
29
-
30
- ## [0.3.18](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.17...@constructive-io/job-worker@0.3.18) (2025-12-31)
31
-
32
- **Note:** Version bump only for package @constructive-io/job-worker
33
-
34
- ## [0.3.17](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.16...@constructive-io/job-worker@0.3.17) (2025-12-31)
35
-
36
- **Note:** Version bump only for package @constructive-io/job-worker
37
-
38
- ## [0.3.16](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.15...@constructive-io/job-worker@0.3.16) (2025-12-27)
39
-
40
- **Note:** Version bump only for package @constructive-io/job-worker
41
-
42
- ## [0.3.15](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.14...@constructive-io/job-worker@0.3.15) (2025-12-26)
43
-
44
- **Note:** Version bump only for package @constructive-io/job-worker
45
-
46
- ## [0.3.14](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.13...@constructive-io/job-worker@0.3.14) (2025-12-26)
47
-
48
- **Note:** Version bump only for package @constructive-io/job-worker
49
-
50
- ## [0.3.13](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.12...@constructive-io/job-worker@0.3.13) (2025-12-24)
51
-
52
- **Note:** Version bump only for package @constructive-io/job-worker
53
-
54
- ## [0.3.12](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.11...@constructive-io/job-worker@0.3.12) (2025-12-23)
55
-
56
- **Note:** Version bump only for package @constructive-io/job-worker
57
-
58
- ## [0.3.11](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.10...@constructive-io/job-worker@0.3.11) (2025-12-22)
59
-
60
- **Note:** Version bump only for package @constructive-io/job-worker
61
-
62
- ## [0.3.10](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.9...@constructive-io/job-worker@0.3.10) (2025-12-22)
63
-
64
- **Note:** Version bump only for package @constructive-io/job-worker
65
-
66
- ## [0.3.9](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.8...@constructive-io/job-worker@0.3.9) (2025-12-21)
67
-
68
- **Note:** Version bump only for package @constructive-io/job-worker
69
-
70
- ## [0.3.8](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.7...@constructive-io/job-worker@0.3.8) (2025-12-19)
71
-
72
- **Note:** Version bump only for package @constructive-io/job-worker
73
-
74
- ## 0.3.7 (2025-12-18)
75
-
76
- **Note:** Version bump only for package @constructive-io/job-worker
77
-
78
- ## [0.3.6](https://github.com/constructive-io/jobs/compare/@constructive-io/job-worker@0.3.5...@constructive-io/job-worker@0.3.6) (2025-12-17)
79
-
80
- **Note:** Version bump only for package @constructive-io/job-worker
package/jest.config.js DELETED
@@ -1,18 +0,0 @@
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/src/index.ts DELETED
@@ -1,221 +0,0 @@
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
- import { createLogger } from '@pgpmjs/logger';
6
-
7
- const pgPoolConfig = {
8
- connectionString: jobs.getJobConnectionString()
9
- };
10
-
11
- function once<T extends (...args: unknown[]) => unknown>(
12
- fn: T,
13
- context?: unknown
14
- ): (...args: Parameters<T>) => ReturnType<T> | undefined {
15
- let result: ReturnType<T> | undefined;
16
- return function (this: unknown, ...args: Parameters<T>) {
17
- if (fn) {
18
- result = fn.apply((context ?? this) as never, args) as ReturnType<T>;
19
- fn = null as unknown as T;
20
- }
21
- return result;
22
- };
23
- }
24
-
25
- export interface JobRow {
26
- id: number | string;
27
- task_identifier: string;
28
- payload?: unknown;
29
- }
30
-
31
- export interface WorkerContext {
32
- pgPool: Pool;
33
- workerId: string;
34
- }
35
-
36
- export type TaskHandler = (
37
- ctx: WorkerContext,
38
- job: JobRow
39
- ) => Promise<void> | void;
40
-
41
- const logger = createLogger('job-worker');
42
-
43
- export default class Worker {
44
- tasks: Record<string, TaskHandler>;
45
- idleDelay: number;
46
- supportedTaskNames: string[];
47
- workerId: string;
48
- doNextTimer?: NodeJS.Timeout;
49
- pgPool: Pool;
50
- _ended?: boolean;
51
-
52
- // tasks is required; other options are optional
53
- constructor({
54
- tasks,
55
- idleDelay = 15000,
56
- pgPool = new (pg as any).Pool(pgPoolConfig),
57
- workerId = jobs.getWorkerHostname()
58
- }: {
59
- tasks: Record<string, TaskHandler>;
60
- idleDelay?: number;
61
- pgPool?: Pool;
62
- workerId?: string;
63
- }) {
64
- this.tasks = tasks;
65
- /*
66
- * idleDelay: This is how long to wait between polling for jobs.
67
- *
68
- * Note: this does NOT need to be short, because we use LISTEN/NOTIFY to be
69
- * notified when new jobs are added - this is just used in the case where
70
- * LISTEN/NOTIFY fails for whatever reason.
71
- */
72
- this.idleDelay = idleDelay;
73
-
74
- this.supportedTaskNames = Object.keys(this.tasks);
75
- this.workerId = workerId;
76
- this.doNextTimer = undefined;
77
- this.pgPool = pgPool;
78
- const close = () => {
79
- logger.info('closing connection...');
80
- this.close();
81
- };
82
- process.once('SIGTERM', close);
83
- process.once('SIGINT', close);
84
- }
85
- close() {
86
- if (!this._ended) {
87
- this.pgPool.end();
88
- }
89
- this._ended = true;
90
- }
91
- handleFatalError({
92
- err,
93
- fatalError,
94
- jobId
95
- }: {
96
- err?: Error;
97
- fatalError: unknown;
98
- jobId: JobRow['id'];
99
- }) {
100
- const when = err ? `after failure '${err.message}'` : 'after success';
101
- logger.error(
102
- `Failed to release job '${jobId}' ${when}; committing seppuku`
103
- );
104
- logger.error(fatalError);
105
- process.exit(1);
106
- }
107
- async handleError(
108
- client: PgClientLike,
109
- { err, job, duration }: { err: Error; job: JobRow; duration: string }
110
- ) {
111
- logger.error(
112
- `Failed task ${job.id} (${job.task_identifier}) with error ${err.message} (${duration}ms)`,
113
- { err, stack: err.stack }
114
- );
115
- logger.error(err.stack);
116
- await jobs.failJob(client, {
117
- workerId: this.workerId,
118
- jobId: job.id,
119
- message: err.message
120
- });
121
- }
122
- async handleSuccess(
123
- client: PgClientLike,
124
- { job, duration }: { job: JobRow; duration: string }
125
- ) {
126
- logger.info(
127
- `Completed task ${job.id} (${job.task_identifier}) with success (${duration}ms)`
128
- );
129
- await jobs.completeJob(client, { workerId: this.workerId, jobId: job.id });
130
- }
131
- async doWork(job: JobRow) {
132
- const { task_identifier } = job;
133
- const worker = this.tasks[task_identifier];
134
- if (!worker) {
135
- throw new Error('Unsupported task');
136
- }
137
- await worker(
138
- {
139
- pgPool: this.pgPool,
140
- workerId: this.workerId
141
- },
142
- job
143
- );
144
- }
145
- async doNext(client: PgClientLike): Promise<void> {
146
- if (this.doNextTimer) {
147
- clearTimeout(this.doNextTimer);
148
- this.doNextTimer = undefined;
149
- }
150
- try {
151
- const job = (await jobs.getJob<JobRow>(client, {
152
- workerId: this.workerId,
153
- supportedTaskNames: this.supportedTaskNames
154
- })) as JobRow | undefined;
155
- if (!job || !job.id) {
156
- this.doNextTimer = setTimeout(
157
- () => this.doNext(client),
158
- this.idleDelay
159
- );
160
- return;
161
- }
162
- const start = process.hrtime();
163
-
164
- let err: Error | null = null;
165
- try {
166
- await this.doWork(job);
167
- } catch (error) {
168
- err = error as Error;
169
- }
170
- const durationRaw = process.hrtime(start);
171
- const duration = ((durationRaw[0] * 1e9 + durationRaw[1]) / 1e6).toFixed(
172
- 2
173
- );
174
- const jobId = job.id;
175
- try {
176
- if (err) {
177
- await this.handleError(client, { err, job, duration });
178
- } else {
179
- await this.handleSuccess(client, { job, duration });
180
- }
181
- } catch (fatalError: unknown) {
182
- this.handleFatalError({ err, fatalError, jobId });
183
- }
184
- return this.doNext(client);
185
- } catch (err: unknown) {
186
- this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
187
- }
188
- }
189
- listen() {
190
- const listenForChanges = (
191
- err: Error | null,
192
- client: PoolClient,
193
- release: () => void
194
- ) => {
195
- if (err) {
196
- logger.error('Error connecting with notify listener', err);
197
- // Try again in 5 seconds
198
- // should this really be done in the node process?
199
- setTimeout(this.listen, 5000);
200
- return;
201
- }
202
- client.on('notification', () => {
203
- if (this.doNextTimer) {
204
- // Must be idle, do something!
205
- this.doNext(client);
206
- }
207
- });
208
- client.query('LISTEN "jobs:insert"');
209
- client.on('error', (e: unknown) => {
210
- logger.error('Error with database notify listener', e);
211
- release();
212
- this.listen();
213
- });
214
- logger.info(`${this.workerId} connected and looking for jobs...`);
215
- this.doNext(client);
216
- };
217
- this.pgPool.connect(listenForChanges);
218
- }
219
- }
220
-
221
- export { Worker };
package/src/run.ts DELETED
@@ -1,19 +0,0 @@
1
- import Worker, { WorkerContext, JobRow } from './index';
2
- import { createLogger } from '@pgpmjs/logger';
3
-
4
- const logger = createLogger('job-worker-run');
5
-
6
- const worker = new Worker({
7
- tasks: {
8
- hello: async (
9
- { pgPool, workerId }: WorkerContext,
10
- job: JobRow
11
- ) => {
12
- logger.info('hello');
13
- await pgPool.query('select 1');
14
- logger.info(JSON.stringify(job, null, 2));
15
- }
16
- }
17
- });
18
-
19
- worker.listen();
package/tsconfig.esm.json DELETED
@@ -1,9 +0,0 @@
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 DELETED
@@ -1,9 +0,0 @@
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
- }
File without changes
File without changes
File without changes
File without changes