@constructive-io/knative-job-worker 0.7.15 → 0.8.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 +58 -0
- package/esm/index.js +208 -0
- package/esm/req.js +55 -0
- package/{src/run.ts → esm/run.js} +4 -11
- package/{dist/index.d.ts → index.d.ts} +5 -1
- package/{dist/index.js → index.js} +55 -5
- package/package.json +22 -13
- package/CHANGELOG.md +0 -228
- package/__tests__/req.test.ts +0 -130
- package/__tests__/worker.integration.test.ts +0 -117
- package/jest.config.js +0 -18
- package/src/index.ts +0 -210
- package/src/req.ts +0 -82
- package/tsconfig.esm.json +0 -9
- package/tsconfig.json +0 -9
- /package/{dist/req.d.ts → req.d.ts} +0 -0
- /package/{dist/req.js → req.js} +0 -0
- /package/{dist/run.d.ts → run.d.ts} +0 -0
- /package/{dist/run.js → run.js} +0 -0
package/src/index.ts
DELETED
|
@@ -1,210 +0,0 @@
|
|
|
1
|
-
import poolManager from '@constructive-io/job-pg';
|
|
2
|
-
import * as jobs from '@constructive-io/job-utils';
|
|
3
|
-
import type { PgClientLike } from '@constructive-io/job-utils';
|
|
4
|
-
import type { Pool, PoolClient } from 'pg';
|
|
5
|
-
import { Logger } from '@pgpmjs/logger';
|
|
6
|
-
import { request as req } from './req';
|
|
7
|
-
|
|
8
|
-
export interface JobRow {
|
|
9
|
-
id: number | string;
|
|
10
|
-
task_identifier: string;
|
|
11
|
-
payload?: unknown;
|
|
12
|
-
database_id?: string;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
const log = new Logger('jobs:worker');
|
|
16
|
-
|
|
17
|
-
export default class Worker {
|
|
18
|
-
idleDelay: number;
|
|
19
|
-
supportedTaskNames: string[];
|
|
20
|
-
workerId: string;
|
|
21
|
-
doNextTimer?: NodeJS.Timeout;
|
|
22
|
-
pgPool: Pool;
|
|
23
|
-
_initialized?: boolean;
|
|
24
|
-
|
|
25
|
-
constructor({
|
|
26
|
-
tasks,
|
|
27
|
-
idleDelay = 15000,
|
|
28
|
-
pgPool = poolManager.getPool(),
|
|
29
|
-
workerId = 'worker-0'
|
|
30
|
-
}: {
|
|
31
|
-
tasks: string[];
|
|
32
|
-
idleDelay?: number;
|
|
33
|
-
pgPool?: Pool;
|
|
34
|
-
workerId?: string;
|
|
35
|
-
}) {
|
|
36
|
-
/*
|
|
37
|
-
* idleDelay: This is how long to wait between polling for jobs.
|
|
38
|
-
*
|
|
39
|
-
* Note: this does NOT need to be short, because we use LISTEN/NOTIFY to be
|
|
40
|
-
* notified when new jobs are added - this is just used in the case where
|
|
41
|
-
* LISTEN/NOTIFY fails for whatever reason.
|
|
42
|
-
*/
|
|
43
|
-
|
|
44
|
-
this.idleDelay = idleDelay;
|
|
45
|
-
this.supportedTaskNames = tasks;
|
|
46
|
-
this.workerId = workerId;
|
|
47
|
-
this.doNextTimer = undefined;
|
|
48
|
-
this.pgPool = pgPool;
|
|
49
|
-
poolManager.onClose(async () => {
|
|
50
|
-
await jobs.releaseJobs(pgPool, { workerId: this.workerId });
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
async initialize(client: PgClientLike) {
|
|
54
|
-
if (this._initialized === true) return;
|
|
55
|
-
|
|
56
|
-
// release any jobs not finished from before if fatal error prevented cleanup
|
|
57
|
-
await jobs.releaseJobs(client, { workerId: this.workerId });
|
|
58
|
-
|
|
59
|
-
this._initialized = true;
|
|
60
|
-
await this.doNext(client);
|
|
61
|
-
}
|
|
62
|
-
async handleFatalError(
|
|
63
|
-
client: PgClientLike,
|
|
64
|
-
{
|
|
65
|
-
err,
|
|
66
|
-
fatalError,
|
|
67
|
-
jobId
|
|
68
|
-
}: { err?: Error; fatalError: unknown; jobId: JobRow['id'] }
|
|
69
|
-
) {
|
|
70
|
-
const when = err ? `after failure '${err.message}'` : 'after success';
|
|
71
|
-
log.error(`Failed to release job '${jobId}' ${when}; committing seppuku`);
|
|
72
|
-
await poolManager.close();
|
|
73
|
-
log.error(String(fatalError));
|
|
74
|
-
process.exit(1);
|
|
75
|
-
}
|
|
76
|
-
async handleError(
|
|
77
|
-
client: PgClientLike,
|
|
78
|
-
{ err, job, duration }: { err: Error; job: JobRow; duration: string }
|
|
79
|
-
) {
|
|
80
|
-
log.error(
|
|
81
|
-
`Failed task ${job.id} (${job.task_identifier}) with error ${err.message} (${duration}ms)`
|
|
82
|
-
);
|
|
83
|
-
if (err.stack) {
|
|
84
|
-
log.debug(err.stack);
|
|
85
|
-
}
|
|
86
|
-
await jobs.failJob(client, {
|
|
87
|
-
workerId: this.workerId,
|
|
88
|
-
jobId: job.id,
|
|
89
|
-
message: err.message
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
async handleSuccess(
|
|
93
|
-
client: PgClientLike,
|
|
94
|
-
{ job, duration }: { job: JobRow; duration: string }
|
|
95
|
-
) {
|
|
96
|
-
log.info(
|
|
97
|
-
`Async task ${job.id} (${job.task_identifier}) to be processed`
|
|
98
|
-
);
|
|
99
|
-
}
|
|
100
|
-
async doWork(job: JobRow) {
|
|
101
|
-
const { payload, task_identifier } = job;
|
|
102
|
-
log.debug('starting work on job', {
|
|
103
|
-
id: job.id,
|
|
104
|
-
task: task_identifier,
|
|
105
|
-
databaseId: job.database_id
|
|
106
|
-
});
|
|
107
|
-
if (
|
|
108
|
-
!jobs.getJobSupportAny() &&
|
|
109
|
-
!this.supportedTaskNames.includes(task_identifier)
|
|
110
|
-
) {
|
|
111
|
-
throw new Error('Unsupported task');
|
|
112
|
-
}
|
|
113
|
-
await req(task_identifier, {
|
|
114
|
-
body: payload,
|
|
115
|
-
databaseId: job.database_id,
|
|
116
|
-
workerId: this.workerId,
|
|
117
|
-
jobId: job.id
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
async doNext(client: PgClientLike): Promise<void> {
|
|
121
|
-
if (!this._initialized) {
|
|
122
|
-
return await this.initialize(client);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
log.debug('checking for jobs...');
|
|
126
|
-
if (this.doNextTimer) {
|
|
127
|
-
clearTimeout(this.doNextTimer);
|
|
128
|
-
this.doNextTimer = undefined;
|
|
129
|
-
}
|
|
130
|
-
try {
|
|
131
|
-
const job = (await jobs.getJob<JobRow>(client, {
|
|
132
|
-
workerId: this.workerId,
|
|
133
|
-
supportedTaskNames: jobs.getJobSupportAny()
|
|
134
|
-
? null
|
|
135
|
-
: this.supportedTaskNames
|
|
136
|
-
})) as JobRow | undefined;
|
|
137
|
-
|
|
138
|
-
if (!job || !job.id) {
|
|
139
|
-
this.doNextTimer = setTimeout(
|
|
140
|
-
() => this.doNext(client),
|
|
141
|
-
this.idleDelay
|
|
142
|
-
);
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
const start = process.hrtime();
|
|
146
|
-
|
|
147
|
-
let err: Error | null = null;
|
|
148
|
-
try {
|
|
149
|
-
await this.doWork(job);
|
|
150
|
-
} catch (error) {
|
|
151
|
-
err = error as Error;
|
|
152
|
-
}
|
|
153
|
-
const durationRaw = process.hrtime(start);
|
|
154
|
-
const duration = ((durationRaw[0] * 1e9 + durationRaw[1]) / 1e6).toFixed(
|
|
155
|
-
2
|
|
156
|
-
);
|
|
157
|
-
const jobId = job.id;
|
|
158
|
-
try {
|
|
159
|
-
if (err) {
|
|
160
|
-
await this.handleError(client, { err, job, duration });
|
|
161
|
-
} else {
|
|
162
|
-
await this.handleSuccess(client, { job, duration });
|
|
163
|
-
}
|
|
164
|
-
} catch (fatalError: unknown) {
|
|
165
|
-
await this.handleFatalError(client, { err, fatalError, jobId });
|
|
166
|
-
}
|
|
167
|
-
return this.doNext(client);
|
|
168
|
-
} catch (err: unknown) {
|
|
169
|
-
this.doNextTimer = setTimeout(() => this.doNext(client), this.idleDelay);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
listen() {
|
|
173
|
-
const listenForChanges = (
|
|
174
|
-
err: Error | null,
|
|
175
|
-
client: PoolClient,
|
|
176
|
-
release: () => void
|
|
177
|
-
) => {
|
|
178
|
-
if (err) {
|
|
179
|
-
log.error('Error connecting with notify listener', err);
|
|
180
|
-
if (err instanceof Error && err.stack) {
|
|
181
|
-
log.debug(err.stack);
|
|
182
|
-
}
|
|
183
|
-
// Try again in 5 seconds
|
|
184
|
-
// should this really be done in the node process?
|
|
185
|
-
setTimeout(this.listen, 5000);
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
client.on('notification', () => {
|
|
189
|
-
if (this.doNextTimer) {
|
|
190
|
-
// Must be idle, do something!
|
|
191
|
-
this.doNext(client);
|
|
192
|
-
}
|
|
193
|
-
});
|
|
194
|
-
client.query('LISTEN "jobs:insert"');
|
|
195
|
-
client.on('error', (e: unknown) => {
|
|
196
|
-
log.error('Error with database notify listener', e);
|
|
197
|
-
if (e instanceof Error && e.stack) {
|
|
198
|
-
log.debug(e.stack);
|
|
199
|
-
}
|
|
200
|
-
release();
|
|
201
|
-
this.listen();
|
|
202
|
-
});
|
|
203
|
-
log.info(`${this.workerId} connected and looking for jobs...`);
|
|
204
|
-
this.doNext(client);
|
|
205
|
-
};
|
|
206
|
-
this.pgPool.connect(listenForChanges);
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
export { Worker };
|
package/src/req.ts
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import requestLib from 'request';
|
|
2
|
-
import {
|
|
3
|
-
getCallbackBaseUrl,
|
|
4
|
-
getJobGatewayConfig,
|
|
5
|
-
getJobGatewayDevMap,
|
|
6
|
-
getNodeEnvironment
|
|
7
|
-
} from '@constructive-io/job-utils';
|
|
8
|
-
import { Logger } from '@pgpmjs/logger';
|
|
9
|
-
|
|
10
|
-
const log = new Logger('jobs:req');
|
|
11
|
-
|
|
12
|
-
// callback URL for job completion
|
|
13
|
-
const completeUrl = getCallbackBaseUrl();
|
|
14
|
-
|
|
15
|
-
// Development override map (e.g. point a function name at localhost)
|
|
16
|
-
const nodeEnv = getNodeEnvironment();
|
|
17
|
-
const DEV_MAP = nodeEnv !== 'production' ? getJobGatewayDevMap() : null;
|
|
18
|
-
|
|
19
|
-
const getFunctionUrl = (fn: string): string => {
|
|
20
|
-
if (DEV_MAP && DEV_MAP[fn]) {
|
|
21
|
-
return DEV_MAP[fn] || completeUrl;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
const { gatewayUrl } = getJobGatewayConfig();
|
|
25
|
-
const base = gatewayUrl.replace(/\/$/, '');
|
|
26
|
-
return `${base}/${fn}`;
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
interface RequestOptions {
|
|
30
|
-
body: unknown;
|
|
31
|
-
databaseId: string;
|
|
32
|
-
workerId: string;
|
|
33
|
-
jobId: string | number;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const request = (
|
|
37
|
-
fn: string,
|
|
38
|
-
{ body, databaseId, workerId, jobId }: RequestOptions
|
|
39
|
-
) => {
|
|
40
|
-
const url = getFunctionUrl(fn);
|
|
41
|
-
log.info(`dispatching job`, {
|
|
42
|
-
fn,
|
|
43
|
-
url,
|
|
44
|
-
callbackUrl: completeUrl,
|
|
45
|
-
workerId,
|
|
46
|
-
jobId,
|
|
47
|
-
databaseId
|
|
48
|
-
});
|
|
49
|
-
return new Promise<boolean>((resolve, reject) => {
|
|
50
|
-
requestLib.post(
|
|
51
|
-
{
|
|
52
|
-
headers: {
|
|
53
|
-
'Content-Type': 'application/json',
|
|
54
|
-
|
|
55
|
-
// these are used by job-worker/job-fn
|
|
56
|
-
'X-Worker-Id': workerId,
|
|
57
|
-
'X-Job-Id': jobId,
|
|
58
|
-
'X-Database-Id': databaseId,
|
|
59
|
-
|
|
60
|
-
// async HTTP completion callback
|
|
61
|
-
'X-Callback-Url': completeUrl
|
|
62
|
-
},
|
|
63
|
-
url,
|
|
64
|
-
json: true,
|
|
65
|
-
body
|
|
66
|
-
},
|
|
67
|
-
function (error: unknown) {
|
|
68
|
-
if (error) {
|
|
69
|
-
log.error(`request error for job[${jobId}] fn[${fn}]`, error);
|
|
70
|
-
if (error instanceof Error && error.stack) {
|
|
71
|
-
log.debug(error.stack);
|
|
72
|
-
}
|
|
73
|
-
return reject(error);
|
|
74
|
-
}
|
|
75
|
-
log.debug(`request success for job[${jobId}] fn[${fn}]`);
|
|
76
|
-
return resolve(true);
|
|
77
|
-
}
|
|
78
|
-
);
|
|
79
|
-
});
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
export { request };
|
package/tsconfig.esm.json
DELETED
package/tsconfig.json
DELETED
|
File without changes
|
/package/{dist/req.js → req.js}
RENAMED
|
File without changes
|
|
File without changes
|
/package/{dist/run.js → run.js}
RENAMED
|
File without changes
|