@constructive-io/job-utils 0.6.0 → 0.6.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 +1,59 @@
1
- # job-utils
1
+ # job-utils
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,44 @@
1
+ import { getJobSchema, getJobPgConfig, getJobPool, getJobConnectionString, getJobSupportAny, getJobSupported, getWorkerHostname, getSchedulerHostname, getJobGatewayConfig, getJobGatewayDevMap, getJobsCallbackPort, getCallbackBaseUrl, getNodeEnvironment } from './runtime';
2
+ import { Logger } from '@pgpmjs/logger';
3
+ const log = new Logger('jobs:core');
4
+ export { getJobSchema, getJobPgConfig, getJobPool, getJobConnectionString, getJobSupportAny, getJobSupported, getWorkerHostname, getSchedulerHostname, getJobGatewayConfig, getJobGatewayDevMap, getJobsCallbackPort, getCallbackBaseUrl, getNodeEnvironment };
5
+ const JOBS_SCHEMA = getJobSchema();
6
+ export const failJob = async (client, { workerId, jobId, message }) => {
7
+ log.warn(`failJob worker[${workerId}] job[${jobId}] ${message}`);
8
+ await client.query(`SELECT * FROM "${JOBS_SCHEMA}".fail_job($1, $2, $3);`, [workerId, jobId, message]);
9
+ };
10
+ export const completeJob = async (client, { workerId, jobId }) => {
11
+ log.info(`completeJob worker[${workerId}] job[${jobId}]`);
12
+ await client.query(`SELECT * FROM "${JOBS_SCHEMA}".complete_job($1, $2);`, [workerId, jobId]);
13
+ };
14
+ export const getJob = async (client, { workerId, supportedTaskNames }) => {
15
+ log.debug(`getJob worker[${workerId}]`);
16
+ const { rows: [job] } = await client.query(`SELECT * FROM "${JOBS_SCHEMA}".get_job($1, $2::text[]);`, [workerId, supportedTaskNames]);
17
+ return job ?? null;
18
+ };
19
+ export const getScheduledJob = async (client, { workerId, supportedTaskNames }) => {
20
+ log.debug(`getScheduledJob worker[${workerId}]`);
21
+ const { rows: [job] } = await client.query(`SELECT * FROM "${JOBS_SCHEMA}".get_scheduled_job($1, $2::text[]);`, [workerId, supportedTaskNames]);
22
+ return job ?? null;
23
+ };
24
+ export const runScheduledJob = async (client, { jobId }) => {
25
+ log.info(`runScheduledJob job[${jobId}]`);
26
+ try {
27
+ const { rows: [job] } = await client.query(`SELECT * FROM "${JOBS_SCHEMA}".run_scheduled_job($1);`, [jobId]);
28
+ return job ?? null;
29
+ }
30
+ catch (e) {
31
+ if (e?.message === 'ALREADY_SCHEDULED') {
32
+ return null;
33
+ }
34
+ throw e;
35
+ }
36
+ };
37
+ export const releaseScheduledJobs = async (client, { workerId, ids }) => {
38
+ log.info(`releaseScheduledJobs worker[${workerId}]`);
39
+ return client.query(`SELECT "${JOBS_SCHEMA}".release_scheduled_jobs($1, $2::bigint[]);`, [workerId, ids ?? null]);
40
+ };
41
+ export const releaseJobs = async (client, { workerId }) => {
42
+ log.info(`releaseJobs worker[${workerId}]`);
43
+ return client.query(`SELECT "${JOBS_SCHEMA}".release_jobs($1);`, [workerId]);
44
+ };
package/esm/runtime.js ADDED
@@ -0,0 +1,112 @@
1
+ import { getEnvOptions, getNodeEnv, parseEnvBoolean } from '@pgpmjs/env';
2
+ import { defaultPgConfig, getPgEnvVars } from 'pg-env';
3
+ import { getPgPool } from 'pg-cache';
4
+ import { jobsDefaults } from '@pgpmjs/types';
5
+ const toStrArray = (v) => v ? v.split(',').map(s => s.trim()).filter(Boolean) : undefined;
6
+ // ---- PG config ----
7
+ export const getJobPgConfig = () => {
8
+ const opts = getEnvOptions();
9
+ const envOnly = getPgEnvVars();
10
+ return {
11
+ ...defaultPgConfig,
12
+ ...(opts.pg ?? {}),
13
+ ...envOnly
14
+ };
15
+ };
16
+ export const getJobPool = () => getPgPool(getJobPgConfig());
17
+ export const getJobConnectionString = () => {
18
+ const cfg = getJobPgConfig();
19
+ const auth = cfg.user
20
+ ? `${cfg.user}${cfg.password ? `:${cfg.password}` : ''}@`
21
+ : '';
22
+ return `postgres://${auth}${cfg.host}:${cfg.port}/${cfg.database}`;
23
+ };
24
+ // ---- Schema ----
25
+ export const getJobSchema = () => {
26
+ const opts = getEnvOptions();
27
+ const fromOpts = opts.jobs?.schema?.schema;
28
+ return (fromOpts ||
29
+ jobsDefaults.schema?.schema ||
30
+ 'app_jobs');
31
+ };
32
+ // ---- SupportAny / Supported ----
33
+ export const getJobSupportAny = () => {
34
+ const opts = getEnvOptions();
35
+ const envVal = parseEnvBoolean(process.env.JOBS_SUPPORT_ANY);
36
+ if (typeof envVal === 'boolean')
37
+ return envVal;
38
+ const worker = opts.jobs?.worker?.supportAny;
39
+ const scheduler = opts.jobs?.scheduler?.supportAny;
40
+ return (worker ??
41
+ scheduler ??
42
+ jobsDefaults.worker?.supportAny ??
43
+ true);
44
+ };
45
+ export const getJobSupported = () => {
46
+ const opts = getEnvOptions();
47
+ const worker = opts.jobs?.worker?.supported;
48
+ const scheduler = opts.jobs?.scheduler?.supported;
49
+ return (worker ??
50
+ scheduler ??
51
+ jobsDefaults.worker?.supported ??
52
+ []);
53
+ };
54
+ // ---- Hostnames ----
55
+ export const getWorkerHostname = () => {
56
+ const opts = getEnvOptions();
57
+ return (process.env.HOSTNAME ||
58
+ opts.jobs?.worker?.hostname ||
59
+ jobsDefaults.worker?.hostname ||
60
+ 'worker-0');
61
+ };
62
+ export const getSchedulerHostname = () => {
63
+ const opts = getEnvOptions();
64
+ return (process.env.HOSTNAME ||
65
+ opts.jobs?.scheduler?.hostname ||
66
+ jobsDefaults.scheduler?.hostname ||
67
+ 'scheduler-0');
68
+ };
69
+ // ---- Job gateway config (generic HTTP gateway) ----
70
+ export const getJobGatewayConfig = () => {
71
+ const opts = getEnvOptions();
72
+ const gateway = opts.jobs?.gateway ?? {};
73
+ const defaults = jobsDefaults.gateway ?? {
74
+ gatewayUrl: 'http://gateway:8080',
75
+ callbackUrl: 'http://callback:12345',
76
+ callbackPort: 12345
77
+ };
78
+ return {
79
+ gatewayUrl: gateway.gatewayUrl ||
80
+ defaults.gatewayUrl,
81
+ callbackUrl: gateway.callbackUrl ||
82
+ defaults.callbackUrl,
83
+ callbackPort: gateway.callbackPort ??
84
+ defaults.callbackPort
85
+ };
86
+ };
87
+ export const getJobGatewayDevMap = () => {
88
+ const map = process.env.INTERNAL_GATEWAY_DEVELOPMENT_MAP;
89
+ if (!map)
90
+ return null;
91
+ try {
92
+ return JSON.parse(map);
93
+ }
94
+ catch (err) {
95
+ console.warn('[getJobGatewayDevMap] Failed to parse INTERNAL_GATEWAY_DEVELOPMENT_MAP as JSON:', err, 'Value:', map);
96
+ return null;
97
+ }
98
+ };
99
+ export const getNodeEnvironment = getNodeEnv;
100
+ // Neutral callback helpers (generic HTTP callback)
101
+ export const getJobsCallbackPort = () => {
102
+ const { callbackPort } = getJobGatewayConfig();
103
+ return callbackPort;
104
+ };
105
+ export const getCallbackBaseUrl = () => {
106
+ if (process.env.INTERNAL_JOBS_CALLBACK_URL) {
107
+ return process.env.INTERNAL_JOBS_CALLBACK_URL;
108
+ }
109
+ const host = process.env.JOBS_CALLBACK_HOST || 'jobs-callback';
110
+ const port = getJobsCallbackPort();
111
+ return `http://${host}:${port}/callback`;
112
+ };
package/package.json CHANGED
@@ -1,17 +1,20 @@
1
1
  {
2
2
  "name": "@constructive-io/job-utils",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "job utils",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "homepage": "https://github.com/constructive-io/jobs/tree/master/packages/job-utils#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,18 +24,23 @@
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
39
  "@pgpmjs/env": "^2.10.0",
32
40
  "@pgpmjs/logger": "^1.4.0",
33
41
  "@pgpmjs/types": "^2.15.0",
34
- "pg-cache": "^1.7.0",
42
+ "pg-cache": "^1.7.1",
35
43
  "pg-env": "^1.3.0"
36
44
  },
37
- "gitHead": "481b3a50b4eec2da6b376c4cd1868065e1e28edb"
45
+ "gitHead": "3ffd5718e86ea5fa9ca6e0930aeb510cf392f343"
38
46
  }
@@ -117,8 +117,8 @@ const getJobsCallbackPort = () => {
117
117
  };
118
118
  exports.getJobsCallbackPort = getJobsCallbackPort;
119
119
  const getCallbackBaseUrl = () => {
120
- if (process.env.JOBS_CALLBACK_BASE_URL) {
121
- return process.env.JOBS_CALLBACK_BASE_URL;
120
+ if (process.env.INTERNAL_JOBS_CALLBACK_URL) {
121
+ return process.env.INTERNAL_JOBS_CALLBACK_URL;
122
122
  }
123
123
  const host = process.env.JOBS_CALLBACK_HOST || 'jobs-callback';
124
124
  const port = (0, exports.getJobsCallbackPort)();
package/CHANGELOG.md DELETED
@@ -1,82 +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.6.0](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.16...@constructive-io/job-utils@0.6.0) (2026-01-18)
7
-
8
- **Note:** Version bump only for package @constructive-io/job-utils
9
-
10
- ## [0.5.16](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.15...@constructive-io/job-utils@0.5.16) (2026-01-18)
11
-
12
- **Note:** Version bump only for package @constructive-io/job-utils
13
-
14
- ## [0.5.15](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.14...@constructive-io/job-utils@0.5.15) (2026-01-09)
15
-
16
- **Note:** Version bump only for package @constructive-io/job-utils
17
-
18
- ## [0.5.14](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.13...@constructive-io/job-utils@0.5.14) (2026-01-07)
19
-
20
- **Note:** Version bump only for package @constructive-io/job-utils
21
-
22
- ## [0.5.13](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.12...@constructive-io/job-utils@0.5.13) (2026-01-02)
23
-
24
- **Note:** Version bump only for package @constructive-io/job-utils
25
-
26
- ## [0.5.12](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.11...@constructive-io/job-utils@0.5.12) (2026-01-02)
27
-
28
- **Note:** Version bump only for package @constructive-io/job-utils
29
-
30
- ## [0.5.11](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.10...@constructive-io/job-utils@0.5.11) (2025-12-31)
31
-
32
- **Note:** Version bump only for package @constructive-io/job-utils
33
-
34
- ## [0.5.10](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.9...@constructive-io/job-utils@0.5.10) (2025-12-31)
35
-
36
- **Note:** Version bump only for package @constructive-io/job-utils
37
-
38
- ## [0.5.9](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.8...@constructive-io/job-utils@0.5.9) (2025-12-27)
39
-
40
- **Note:** Version bump only for package @constructive-io/job-utils
41
-
42
- ## [0.5.8](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.7...@constructive-io/job-utils@0.5.8) (2025-12-26)
43
-
44
- **Note:** Version bump only for package @constructive-io/job-utils
45
-
46
- ## [0.5.7](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.6...@constructive-io/job-utils@0.5.7) (2025-12-26)
47
-
48
- **Note:** Version bump only for package @constructive-io/job-utils
49
-
50
- ## [0.5.6](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.5...@constructive-io/job-utils@0.5.6) (2025-12-24)
51
-
52
- **Note:** Version bump only for package @constructive-io/job-utils
53
-
54
- ## [0.5.5](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.4...@constructive-io/job-utils@0.5.5) (2025-12-23)
55
-
56
- **Note:** Version bump only for package @constructive-io/job-utils
57
-
58
- ## [0.5.4](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.3...@constructive-io/job-utils@0.5.4) (2025-12-22)
59
-
60
- **Note:** Version bump only for package @constructive-io/job-utils
61
-
62
- ## [0.5.3](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.2...@constructive-io/job-utils@0.5.3) (2025-12-22)
63
-
64
- **Note:** Version bump only for package @constructive-io/job-utils
65
-
66
- ## [0.5.2](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.1...@constructive-io/job-utils@0.5.2) (2025-12-21)
67
-
68
- **Note:** Version bump only for package @constructive-io/job-utils
69
-
70
- ## [0.5.1](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.5.0...@constructive-io/job-utils@0.5.1) (2025-12-19)
71
-
72
- **Note:** Version bump only for package @constructive-io/job-utils
73
-
74
- # 0.5.0 (2025-12-18)
75
-
76
- ### Features
77
-
78
- - rebrand PGPM packages to @pgpmjs/\* ([734d865](https://github.com/constructive-io/jobs/commit/734d8655ced175f51567c513ac1ee4c843df98b7))
79
-
80
- ## [0.4.3](https://github.com/constructive-io/jobs/compare/@constructive-io/job-utils@0.4.2...@constructive-io/job-utils@0.4.3) (2025-12-17)
81
-
82
- **Note:** Version bump only for package @constructive-io/job-utils
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,144 +0,0 @@
1
- import type {
2
- FailJobParams,
3
- CompleteJobParams,
4
- GetJobParams,
5
- GetScheduledJobParams,
6
- RunScheduledJobParams,
7
- ReleaseScheduledJobsParams,
8
- ReleaseJobsParams
9
- } from '@pgpmjs/types';
10
-
11
- import {
12
- getJobSchema,
13
- getJobPgConfig,
14
- getJobPool,
15
- getJobConnectionString,
16
- getJobSupportAny,
17
- getJobSupported,
18
- getWorkerHostname,
19
- getSchedulerHostname,
20
- getJobGatewayConfig,
21
- getJobGatewayDevMap,
22
- getJobsCallbackPort,
23
- getCallbackBaseUrl,
24
- getNodeEnvironment
25
- } from './runtime';
26
-
27
- import { Logger } from '@pgpmjs/logger';
28
-
29
- const log = new Logger('jobs:core');
30
-
31
- export type PgClientLike = {
32
- query<T = any>(text: string, params?: any[]): Promise<{ rows: T[] }>;
33
- };
34
-
35
- export {
36
- getJobSchema,
37
- getJobPgConfig,
38
- getJobPool,
39
- getJobConnectionString,
40
- getJobSupportAny,
41
- getJobSupported,
42
- getWorkerHostname,
43
- getSchedulerHostname,
44
- getJobGatewayConfig,
45
- getJobGatewayDevMap,
46
- getJobsCallbackPort,
47
- getCallbackBaseUrl,
48
- getNodeEnvironment
49
- };
50
-
51
- const JOBS_SCHEMA = getJobSchema();
52
-
53
- export const failJob = async (
54
- client: PgClientLike,
55
- { workerId, jobId, message }: FailJobParams
56
- ) => {
57
- log.warn(`failJob worker[${workerId}] job[${jobId}] ${message}`);
58
- await client.query(
59
- `SELECT * FROM "${JOBS_SCHEMA}".fail_job($1, $2, $3);`,
60
- [workerId, jobId, message]
61
- );
62
- };
63
-
64
- export const completeJob = async (
65
- client: PgClientLike,
66
- { workerId, jobId }: CompleteJobParams
67
- ) => {
68
- log.info(`completeJob worker[${workerId}] job[${jobId}]`);
69
- await client.query(
70
- `SELECT * FROM "${JOBS_SCHEMA}".complete_job($1, $2);`,
71
- [workerId, jobId]
72
- );
73
- };
74
-
75
- export const getJob = async <T = any>(
76
- client: PgClientLike,
77
- { workerId, supportedTaskNames }: GetJobParams
78
- ): Promise<T | null> => {
79
- log.debug(`getJob worker[${workerId}]`);
80
- const {
81
- rows: [job]
82
- } = await client.query(
83
- `SELECT * FROM "${JOBS_SCHEMA}".get_job($1, $2::text[]);`,
84
- [workerId, supportedTaskNames]
85
- );
86
- return (job as T) ?? null;
87
- };
88
-
89
- export const getScheduledJob = async <T = any>(
90
- client: PgClientLike,
91
- { workerId, supportedTaskNames }: GetScheduledJobParams
92
- ): Promise<T | null> => {
93
- log.debug(`getScheduledJob worker[${workerId}]`);
94
- const {
95
- rows: [job]
96
- } = await client.query(
97
- `SELECT * FROM "${JOBS_SCHEMA}".get_scheduled_job($1, $2::text[]);`,
98
- [workerId, supportedTaskNames]
99
- );
100
- return (job as T) ?? null;
101
- };
102
-
103
- export const runScheduledJob = async (
104
- client: PgClientLike,
105
- { jobId }: RunScheduledJobParams
106
- ): Promise<any | null> => {
107
- log.info(`runScheduledJob job[${jobId}]`);
108
- try {
109
- const {
110
- rows: [job]
111
- } = await client.query(
112
- `SELECT * FROM "${JOBS_SCHEMA}".run_scheduled_job($1);`,
113
- [jobId]
114
- );
115
- return job ?? null;
116
- } catch (e: any) {
117
- if (e?.message === 'ALREADY_SCHEDULED') {
118
- return null;
119
- }
120
- throw e;
121
- }
122
- };
123
-
124
- export const releaseScheduledJobs = async (
125
- client: PgClientLike,
126
- { workerId, ids }: ReleaseScheduledJobsParams
127
- ) => {
128
- log.info(`releaseScheduledJobs worker[${workerId}]`);
129
- return client.query(
130
- `SELECT "${JOBS_SCHEMA}".release_scheduled_jobs($1, $2::bigint[]);`,
131
- [workerId, ids ?? null]
132
- );
133
- };
134
-
135
- export const releaseJobs = async (
136
- client: PgClientLike,
137
- { workerId }: ReleaseJobsParams
138
- ) => {
139
- log.info(`releaseJobs worker[${workerId}]`);
140
- return client.query(
141
- `SELECT "${JOBS_SCHEMA}".release_jobs($1);`,
142
- [workerId]
143
- );
144
- };
package/src/runtime.ts DELETED
@@ -1,154 +0,0 @@
1
- import { getEnvOptions, getNodeEnv, parseEnvBoolean } from '@pgpmjs/env';
2
- import { defaultPgConfig, getPgEnvVars, type PgConfig } from 'pg-env';
3
- import { getPgPool } from 'pg-cache';
4
- import type { Pool } from 'pg';
5
- import type { PgpmOptions } from '@pgpmjs/types';
6
- import { jobsDefaults } from '@pgpmjs/types';
7
-
8
- type Maybe<T> = T | null | undefined;
9
-
10
- const toStrArray = (v: Maybe<string>): string[] | undefined =>
11
- v ? v.split(',').map(s => s.trim()).filter(Boolean) : undefined;
12
-
13
- // ---- PG config ----
14
- export const getJobPgConfig = (): PgConfig => {
15
- const opts: PgpmOptions = getEnvOptions();
16
- const envOnly = getPgEnvVars();
17
-
18
- return {
19
- ...defaultPgConfig,
20
- ...(opts.pg ?? {}),
21
- ...envOnly
22
- };
23
- };
24
-
25
- export const getJobPool = (): Pool =>
26
- getPgPool(getJobPgConfig());
27
-
28
- export const getJobConnectionString = (): string => {
29
- const cfg = getJobPgConfig();
30
- const auth = cfg.user
31
- ? `${cfg.user}${cfg.password ? `:${cfg.password}` : ''}@`
32
- : '';
33
- return `postgres://${auth}${cfg.host}:${cfg.port}/${cfg.database}`;
34
- };
35
-
36
- // ---- Schema ----
37
- export const getJobSchema = (): string => {
38
- const opts: PgpmOptions = getEnvOptions();
39
- const fromOpts: string | undefined = opts.jobs?.schema?.schema;
40
- return (
41
- fromOpts ||
42
- jobsDefaults.schema?.schema ||
43
- 'app_jobs'
44
- );
45
- };
46
-
47
- // ---- SupportAny / Supported ----
48
- export const getJobSupportAny = (): boolean => {
49
- const opts: PgpmOptions = getEnvOptions();
50
- const envVal = parseEnvBoolean(process.env.JOBS_SUPPORT_ANY);
51
- if (typeof envVal === 'boolean') return envVal;
52
-
53
- const worker: boolean | undefined = opts.jobs?.worker?.supportAny;
54
- const scheduler: boolean | undefined = opts.jobs?.scheduler?.supportAny;
55
-
56
- return (
57
- worker ??
58
- scheduler ??
59
- jobsDefaults.worker?.supportAny ??
60
- true
61
- );
62
- };
63
-
64
- export const getJobSupported = (): string[] => {
65
- const opts: PgpmOptions = getEnvOptions();
66
- const worker: string[] | undefined = opts.jobs?.worker?.supported;
67
- const scheduler: string[] | undefined = opts.jobs?.scheduler?.supported;
68
-
69
- return (
70
- worker ??
71
- scheduler ??
72
- jobsDefaults.worker?.supported ??
73
- []
74
- );
75
- };
76
-
77
- // ---- Hostnames ----
78
- export const getWorkerHostname = (): string => {
79
- const opts: PgpmOptions = getEnvOptions();
80
- return (
81
- process.env.HOSTNAME ||
82
- opts.jobs?.worker?.hostname ||
83
- jobsDefaults.worker?.hostname ||
84
- 'worker-0'
85
- );
86
- };
87
-
88
- export const getSchedulerHostname = (): string => {
89
- const opts: PgpmOptions = getEnvOptions();
90
- return (
91
- process.env.HOSTNAME ||
92
- opts.jobs?.scheduler?.hostname ||
93
- jobsDefaults.scheduler?.hostname ||
94
- 'scheduler-0'
95
- );
96
- };
97
-
98
- // ---- Job gateway config (generic HTTP gateway) ----
99
- export const getJobGatewayConfig = () => {
100
- const opts: PgpmOptions = getEnvOptions();
101
- const gateway = opts.jobs?.gateway ?? {};
102
- const defaults = jobsDefaults.gateway ?? {
103
- gatewayUrl: 'http://gateway:8080',
104
- callbackUrl: 'http://callback:12345',
105
- callbackPort: 12345
106
- };
107
-
108
- return {
109
- gatewayUrl:
110
- gateway.gatewayUrl ||
111
- defaults.gatewayUrl,
112
- callbackUrl:
113
- gateway.callbackUrl ||
114
- defaults.callbackUrl,
115
- callbackPort:
116
- gateway.callbackPort ??
117
- defaults.callbackPort
118
- };
119
- };
120
-
121
- export const getJobGatewayDevMap = ():
122
- | Record<string, string>
123
- | null => {
124
- const map = process.env.INTERNAL_GATEWAY_DEVELOPMENT_MAP;
125
- if (!map) return null;
126
- try {
127
- return JSON.parse(map);
128
- } catch (err) {
129
- console.warn(
130
- '[getJobGatewayDevMap] Failed to parse INTERNAL_GATEWAY_DEVELOPMENT_MAP as JSON:',
131
- err,
132
- 'Value:',
133
- map
134
- );
135
- return null;
136
- }
137
- };
138
-
139
- export const getNodeEnvironment = getNodeEnv;
140
-
141
- // Neutral callback helpers (generic HTTP callback)
142
- export const getJobsCallbackPort = (): number => {
143
- const { callbackPort } = getJobGatewayConfig();
144
- return callbackPort;
145
- };
146
-
147
- export const getCallbackBaseUrl = (): string => {
148
- if (process.env.JOBS_CALLBACK_BASE_URL) {
149
- return process.env.JOBS_CALLBACK_BASE_URL;
150
- }
151
- const host = process.env.JOBS_CALLBACK_HOST || 'jobs-callback';
152
- const port = getJobsCallbackPort();
153
- return `http://${host}:${port}/callback`;
154
- };
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"],
8
- "exclude": ["dist", "node_modules", "**/*.spec.*", "**/*.test.*"]
9
- }
File without changes
File without changes
File without changes