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