@constructive-io/knative-job-fn 0.2.4
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/index.d.ts +5 -0
- package/dist/index.js +160 -0
- package/jest.config.js +18 -0
- package/package.json +35 -0
- package/src/index.ts +192 -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.2.4 (2025-12-18)
|
|
7
|
+
|
|
8
|
+
**Note:** Version bump only for package @constructive-io/knative-job-fn
|
|
9
|
+
|
|
10
|
+
## [0.2.3](https://github.com/constructive-io/jobs/compare/@launchql/knative-job-fn@0.2.2...@launchql/knative-job-fn@0.2.3) (2025-12-17)
|
|
11
|
+
|
|
12
|
+
**Note:** Version bump only for package @launchql/knative-job-fn
|
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
|
+
# knative-job-fn
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
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 express_1 = __importDefault(require("express"));
|
|
7
|
+
const body_parser_1 = __importDefault(require("body-parser"));
|
|
8
|
+
const node_http_1 = __importDefault(require("node:http"));
|
|
9
|
+
const node_https_1 = __importDefault(require("node:https"));
|
|
10
|
+
const node_url_1 = require("node:url");
|
|
11
|
+
const app = (0, express_1.default)();
|
|
12
|
+
app.use(body_parser_1.default.json());
|
|
13
|
+
// Echo job headers back on responses for debugging/traceability.
|
|
14
|
+
app.use((req, res, next) => {
|
|
15
|
+
res.set({
|
|
16
|
+
'Content-Type': 'application/json',
|
|
17
|
+
'X-Worker-Id': req.get('X-Worker-Id'),
|
|
18
|
+
'X-Database-Id': req.get('X-Database-Id'),
|
|
19
|
+
'X-Job-Id': req.get('X-Job-Id')
|
|
20
|
+
});
|
|
21
|
+
next();
|
|
22
|
+
});
|
|
23
|
+
// Normalize callback URL so it always points at the /callback endpoint.
|
|
24
|
+
const normalizeCallbackUrl = (rawUrl) => {
|
|
25
|
+
try {
|
|
26
|
+
const url = new node_url_1.URL(rawUrl);
|
|
27
|
+
if (!url.pathname || url.pathname === '/') {
|
|
28
|
+
url.pathname = '/callback';
|
|
29
|
+
}
|
|
30
|
+
return url.toString();
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return rawUrl;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
const postJson = (urlStr, headers, body) => {
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
let url;
|
|
39
|
+
try {
|
|
40
|
+
url = new node_url_1.URL(urlStr);
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
return reject(e);
|
|
44
|
+
}
|
|
45
|
+
const isHttps = url.protocol === 'https:';
|
|
46
|
+
const client = isHttps ? node_https_1.default : node_http_1.default;
|
|
47
|
+
const req = client.request({
|
|
48
|
+
hostname: url.hostname,
|
|
49
|
+
port: url.port || (isHttps ? 443 : 80),
|
|
50
|
+
path: url.pathname + url.search,
|
|
51
|
+
method: 'POST',
|
|
52
|
+
headers: {
|
|
53
|
+
'Content-Type': 'application/json',
|
|
54
|
+
...headers
|
|
55
|
+
}
|
|
56
|
+
}, (res) => {
|
|
57
|
+
// Drain response data but ignore contents; callback server
|
|
58
|
+
// only uses status for debugging.
|
|
59
|
+
res.on('data', () => { });
|
|
60
|
+
res.on('end', () => resolve());
|
|
61
|
+
});
|
|
62
|
+
req.on('error', (err) => reject(err));
|
|
63
|
+
req.write(JSON.stringify(body));
|
|
64
|
+
req.end();
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
const sendJobCallback = async (ctx, status, errorMessage) => {
|
|
68
|
+
const { callbackUrl, workerId, jobId, databaseId } = ctx;
|
|
69
|
+
if (!callbackUrl || !workerId || !jobId) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const target = normalizeCallbackUrl(callbackUrl);
|
|
73
|
+
const headers = {
|
|
74
|
+
'X-Worker-Id': workerId,
|
|
75
|
+
'X-Job-Id': jobId
|
|
76
|
+
};
|
|
77
|
+
if (databaseId) {
|
|
78
|
+
headers['X-Database-Id'] = databaseId;
|
|
79
|
+
}
|
|
80
|
+
const body = {
|
|
81
|
+
status
|
|
82
|
+
};
|
|
83
|
+
if (status === 'error') {
|
|
84
|
+
headers['X-Job-Error'] = 'true';
|
|
85
|
+
body.error = errorMessage || 'ERROR';
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
// eslint-disable-next-line no-console
|
|
89
|
+
console.log('[knative-job-fn] Sending job callback', {
|
|
90
|
+
status,
|
|
91
|
+
target: normalizeCallbackUrl(callbackUrl),
|
|
92
|
+
workerId,
|
|
93
|
+
jobId,
|
|
94
|
+
databaseId
|
|
95
|
+
});
|
|
96
|
+
await postJson(target, headers, body);
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
// eslint-disable-next-line no-console
|
|
100
|
+
console.error('[knative-job-fn] Failed to POST job callback', {
|
|
101
|
+
target,
|
|
102
|
+
status,
|
|
103
|
+
err
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
// Attach per-request context and a finish hook to send success callbacks.
|
|
108
|
+
app.use((req, res, next) => {
|
|
109
|
+
const ctx = {
|
|
110
|
+
callbackUrl: req.get('X-Callback-Url'),
|
|
111
|
+
workerId: req.get('X-Worker-Id'),
|
|
112
|
+
jobId: req.get('X-Job-Id'),
|
|
113
|
+
databaseId: req.get('X-Database-Id')
|
|
114
|
+
};
|
|
115
|
+
// Store on res.locals so the error middleware can also mark callbacks as sent.
|
|
116
|
+
res.locals = res.locals || {};
|
|
117
|
+
res.locals.jobContext = ctx;
|
|
118
|
+
res.locals.jobCallbackSent = false;
|
|
119
|
+
if (ctx.callbackUrl && ctx.workerId && ctx.jobId) {
|
|
120
|
+
res.on('finish', () => {
|
|
121
|
+
// If an error handler already sent a callback, skip.
|
|
122
|
+
if (res.locals.jobCallbackSent)
|
|
123
|
+
return;
|
|
124
|
+
res.locals.jobCallbackSent = true;
|
|
125
|
+
void sendJobCallback(ctx, 'success');
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
next();
|
|
129
|
+
});
|
|
130
|
+
exports.default = {
|
|
131
|
+
post: function (...args) {
|
|
132
|
+
return app.post.apply(app, args);
|
|
133
|
+
},
|
|
134
|
+
listen: (port, cb = () => { }) => {
|
|
135
|
+
// NOTE Remember that Express middleware executes in order.
|
|
136
|
+
// You should define error handlers last, after all other middleware.
|
|
137
|
+
// Otherwise, your error handler won't get called
|
|
138
|
+
// eslint-disable-next-line no-unused-vars
|
|
139
|
+
app.use(async (error, req, res, next) => {
|
|
140
|
+
res.set({
|
|
141
|
+
'Content-Type': 'application/json',
|
|
142
|
+
'X-Job-Error': true
|
|
143
|
+
});
|
|
144
|
+
// Mark job as having errored via callback, if available.
|
|
145
|
+
try {
|
|
146
|
+
const ctx = res.locals?.jobContext;
|
|
147
|
+
if (ctx && !res.locals.jobCallbackSent) {
|
|
148
|
+
res.locals.jobCallbackSent = true;
|
|
149
|
+
await sendJobCallback(ctx, 'error', error?.message);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
catch (err) {
|
|
153
|
+
// eslint-disable-next-line no-console
|
|
154
|
+
console.error('[knative-job-fn] Failed to send error callback', err);
|
|
155
|
+
}
|
|
156
|
+
res.status(200).json({ message: error.message });
|
|
157
|
+
});
|
|
158
|
+
app.listen(port, cb);
|
|
159
|
+
}
|
|
160
|
+
};
|
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/knative-job-fn",
|
|
3
|
+
"version": "0.2.4",
|
|
4
|
+
"description": "knative job fn",
|
|
5
|
+
"author": "Constructive <developers@constructive.io>",
|
|
6
|
+
"homepage": "https://github.com/constructive-io/jobs/tree/master/packages/knative-job-fn#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
|
+
"body-parser": "1.19.0",
|
|
32
|
+
"express": "4.17.1"
|
|
33
|
+
},
|
|
34
|
+
"gitHead": "86d74dc4fce9051df0d2b5bcc163607aba42f009"
|
|
35
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import bodyParser from 'body-parser';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import https from 'node:https';
|
|
5
|
+
import { URL } from 'node:url';
|
|
6
|
+
|
|
7
|
+
type JobCallbackStatus = 'success' | 'error';
|
|
8
|
+
|
|
9
|
+
type JobContext = {
|
|
10
|
+
callbackUrl: string | undefined;
|
|
11
|
+
workerId: string | undefined;
|
|
12
|
+
jobId: string | undefined;
|
|
13
|
+
databaseId: string | undefined;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const app: any = express();
|
|
17
|
+
|
|
18
|
+
app.use(bodyParser.json());
|
|
19
|
+
|
|
20
|
+
// Echo job headers back on responses for debugging/traceability.
|
|
21
|
+
app.use((req: any, res: any, next: any) => {
|
|
22
|
+
res.set({
|
|
23
|
+
'Content-Type': 'application/json',
|
|
24
|
+
'X-Worker-Id': req.get('X-Worker-Id'),
|
|
25
|
+
'X-Database-Id': req.get('X-Database-Id'),
|
|
26
|
+
'X-Job-Id': req.get('X-Job-Id')
|
|
27
|
+
});
|
|
28
|
+
next();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// Normalize callback URL so it always points at the /callback endpoint.
|
|
32
|
+
const normalizeCallbackUrl = (rawUrl: string): string => {
|
|
33
|
+
try {
|
|
34
|
+
const url = new URL(rawUrl);
|
|
35
|
+
if (!url.pathname || url.pathname === '/') {
|
|
36
|
+
url.pathname = '/callback';
|
|
37
|
+
}
|
|
38
|
+
return url.toString();
|
|
39
|
+
} catch {
|
|
40
|
+
return rawUrl;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const postJson = (
|
|
45
|
+
urlStr: string,
|
|
46
|
+
headers: Record<string, string>,
|
|
47
|
+
body: Record<string, unknown>
|
|
48
|
+
): Promise<void> => {
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
let url: URL;
|
|
51
|
+
try {
|
|
52
|
+
url = new URL(urlStr);
|
|
53
|
+
} catch (e) {
|
|
54
|
+
return reject(e);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const isHttps = url.protocol === 'https:';
|
|
58
|
+
const client = isHttps ? https : http;
|
|
59
|
+
|
|
60
|
+
const req = client.request(
|
|
61
|
+
{
|
|
62
|
+
hostname: url.hostname,
|
|
63
|
+
port: url.port || (isHttps ? 443 : 80),
|
|
64
|
+
path: url.pathname + url.search,
|
|
65
|
+
method: 'POST',
|
|
66
|
+
headers: {
|
|
67
|
+
'Content-Type': 'application/json',
|
|
68
|
+
...headers
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
(res) => {
|
|
72
|
+
// Drain response data but ignore contents; callback server
|
|
73
|
+
// only uses status for debugging.
|
|
74
|
+
res.on('data', () => {});
|
|
75
|
+
res.on('end', () => resolve());
|
|
76
|
+
}
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
req.on('error', (err) => reject(err));
|
|
80
|
+
req.write(JSON.stringify(body));
|
|
81
|
+
req.end();
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const sendJobCallback = async (
|
|
86
|
+
ctx: JobContext,
|
|
87
|
+
status: JobCallbackStatus,
|
|
88
|
+
errorMessage?: string
|
|
89
|
+
) => {
|
|
90
|
+
const { callbackUrl, workerId, jobId, databaseId } = ctx;
|
|
91
|
+
if (!callbackUrl || !workerId || !jobId) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const target = normalizeCallbackUrl(callbackUrl);
|
|
96
|
+
|
|
97
|
+
const headers: Record<string, string> = {
|
|
98
|
+
'X-Worker-Id': workerId,
|
|
99
|
+
'X-Job-Id': jobId
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
if (databaseId) {
|
|
103
|
+
headers['X-Database-Id'] = databaseId;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const body: Record<string, unknown> = {
|
|
107
|
+
status
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
if (status === 'error') {
|
|
111
|
+
headers['X-Job-Error'] = 'true';
|
|
112
|
+
body.error = errorMessage || 'ERROR';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
// eslint-disable-next-line no-console
|
|
117
|
+
console.log('[knative-job-fn] Sending job callback', {
|
|
118
|
+
status,
|
|
119
|
+
target: normalizeCallbackUrl(callbackUrl),
|
|
120
|
+
workerId,
|
|
121
|
+
jobId,
|
|
122
|
+
databaseId
|
|
123
|
+
});
|
|
124
|
+
await postJson(target, headers, body);
|
|
125
|
+
} catch (err) {
|
|
126
|
+
// eslint-disable-next-line no-console
|
|
127
|
+
console.error('[knative-job-fn] Failed to POST job callback', {
|
|
128
|
+
target,
|
|
129
|
+
status,
|
|
130
|
+
err
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
// Attach per-request context and a finish hook to send success callbacks.
|
|
136
|
+
app.use((req: any, res: any, next: any) => {
|
|
137
|
+
const ctx: JobContext = {
|
|
138
|
+
callbackUrl: req.get('X-Callback-Url'),
|
|
139
|
+
workerId: req.get('X-Worker-Id'),
|
|
140
|
+
jobId: req.get('X-Job-Id'),
|
|
141
|
+
databaseId: req.get('X-Database-Id')
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// Store on res.locals so the error middleware can also mark callbacks as sent.
|
|
145
|
+
res.locals = res.locals || {};
|
|
146
|
+
res.locals.jobContext = ctx;
|
|
147
|
+
res.locals.jobCallbackSent = false;
|
|
148
|
+
|
|
149
|
+
if (ctx.callbackUrl && ctx.workerId && ctx.jobId) {
|
|
150
|
+
res.on('finish', () => {
|
|
151
|
+
// If an error handler already sent a callback, skip.
|
|
152
|
+
if (res.locals.jobCallbackSent) return;
|
|
153
|
+
res.locals.jobCallbackSent = true;
|
|
154
|
+
void sendJobCallback(ctx, 'success');
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
next();
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
export default {
|
|
162
|
+
post: function (...args: any[]) {
|
|
163
|
+
return app.post.apply(app, args as any);
|
|
164
|
+
},
|
|
165
|
+
listen: (port: any, cb: () => void = () => {}) => {
|
|
166
|
+
// NOTE Remember that Express middleware executes in order.
|
|
167
|
+
// You should define error handlers last, after all other middleware.
|
|
168
|
+
// Otherwise, your error handler won't get called
|
|
169
|
+
// eslint-disable-next-line no-unused-vars
|
|
170
|
+
app.use(async (error: any, req: any, res: any, next: any) => {
|
|
171
|
+
res.set({
|
|
172
|
+
'Content-Type': 'application/json',
|
|
173
|
+
'X-Job-Error': true
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
// Mark job as having errored via callback, if available.
|
|
177
|
+
try {
|
|
178
|
+
const ctx: JobContext | undefined = res.locals?.jobContext;
|
|
179
|
+
if (ctx && !res.locals.jobCallbackSent) {
|
|
180
|
+
res.locals.jobCallbackSent = true;
|
|
181
|
+
await sendJobCallback(ctx, 'error', error?.message);
|
|
182
|
+
}
|
|
183
|
+
} catch (err) {
|
|
184
|
+
// eslint-disable-next-line no-console
|
|
185
|
+
console.error('[knative-job-fn] Failed to send error callback', err);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
res.status(200).json({ message: error.message });
|
|
189
|
+
});
|
|
190
|
+
app.listen(port, cb);
|
|
191
|
+
}
|
|
192
|
+
};
|