@constructive-io/knative-job-service 0.6.15 → 0.7.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/src/index.ts CHANGED
@@ -1 +1,445 @@
1
- // noop
1
+ import jobServerFactory from '@constructive-io/knative-job-server';
2
+ import Worker from '@constructive-io/knative-job-worker';
3
+ import Scheduler from '@constructive-io/job-scheduler';
4
+ import poolManager from '@constructive-io/job-pg';
5
+ import {
6
+ getJobPgConfig,
7
+ getJobSchema,
8
+ getJobSupported,
9
+ getJobsCallbackPort,
10
+ getSchedulerHostname,
11
+ getWorkerHostname
12
+ } from '@constructive-io/job-utils';
13
+ import { parseEnvBoolean } from '@pgpmjs/env';
14
+ import { Logger } from '@pgpmjs/logger';
15
+ import retry from 'async-retry';
16
+ import { Client } from 'pg';
17
+ import { createRequire } from 'module';
18
+ import type { Server as HttpServer } from 'http';
19
+
20
+ import {
21
+ KnativeJobsSvcOptions,
22
+ KnativeJobsSvcResult,
23
+ FunctionName,
24
+ FunctionServiceConfig,
25
+ FunctionsOptions,
26
+ StartedFunction
27
+ } from './types';
28
+
29
+ type FunctionRegistryEntry = {
30
+ moduleName: string;
31
+ defaultPort: number;
32
+ };
33
+
34
+ const functionRegistry: Record<FunctionName, FunctionRegistryEntry> = {
35
+ 'simple-email': {
36
+ moduleName: '@constructive-io/simple-email-fn',
37
+ defaultPort: 8081
38
+ },
39
+ 'send-email-link': {
40
+ moduleName: '@constructive-io/send-email-link-fn',
41
+ defaultPort: 8082
42
+ }
43
+ };
44
+
45
+ const log = new Logger('knative-job-service');
46
+ const requireFn = createRequire(__filename);
47
+
48
+ const resolveFunctionEntry = (name: FunctionName): FunctionRegistryEntry => {
49
+ const entry = functionRegistry[name];
50
+ if (!entry) {
51
+ throw new Error(`Unknown function "${name}".`);
52
+ }
53
+ return entry;
54
+ };
55
+
56
+ const loadFunctionApp = (moduleName: string) => {
57
+ const knativeModuleId = requireFn.resolve('@constructive-io/knative-job-fn');
58
+ delete requireFn.cache[knativeModuleId];
59
+
60
+ const moduleId = requireFn.resolve(moduleName);
61
+ delete requireFn.cache[moduleId];
62
+
63
+ const mod = requireFn(moduleName) as { default?: { listen: (port: number, cb?: () => void) => unknown } };
64
+ const app = mod.default ?? mod;
65
+
66
+ if (!app || typeof (app as { listen?: unknown }).listen !== 'function') {
67
+ throw new Error(`Function module "${moduleName}" does not export a listenable app.`);
68
+ }
69
+
70
+ return app as { listen: (port: number, cb?: () => void) => unknown };
71
+ };
72
+
73
+ const shouldEnableFunctions = (options?: FunctionsOptions): boolean => {
74
+ if (!options) return false;
75
+ if (typeof options.enabled === 'boolean') return options.enabled;
76
+ return Boolean(options.services?.length);
77
+ };
78
+
79
+ const normalizeFunctionServices = (
80
+ options?: FunctionsOptions
81
+ ): FunctionServiceConfig[] => {
82
+ if (!shouldEnableFunctions(options)) return [];
83
+
84
+ if (!options?.services?.length) {
85
+ return Object.keys(functionRegistry).map((name) => ({
86
+ name: name as FunctionName
87
+ }));
88
+ }
89
+
90
+ return options.services;
91
+ };
92
+
93
+ const resolveFunctionPort = (service: FunctionServiceConfig): number => {
94
+ const entry = resolveFunctionEntry(service.name);
95
+ return service.port ?? entry.defaultPort;
96
+ };
97
+
98
+ const ensureUniquePorts = (services: FunctionServiceConfig[]) => {
99
+ const usedPorts = new Set<number>();
100
+ for (const service of services) {
101
+ const port = resolveFunctionPort(service);
102
+ if (usedPorts.has(port)) {
103
+ throw new Error(`Function port ${port} is assigned more than once.`);
104
+ }
105
+ usedPorts.add(port);
106
+ }
107
+ };
108
+
109
+ const startFunction = async (
110
+ service: FunctionServiceConfig,
111
+ functionServers: Map<FunctionName, HttpServer>
112
+ ): Promise<StartedFunction> => {
113
+ const entry = resolveFunctionEntry(service.name);
114
+ const port = resolveFunctionPort(service);
115
+ const app = loadFunctionApp(entry.moduleName);
116
+
117
+ await new Promise<void>((resolve, reject) => {
118
+ const server = app.listen(port, () => {
119
+ log.info(`function:${service.name} listening on ${port}`);
120
+ resolve();
121
+ }) as HttpServer & { on?: (event: string, cb: (err: Error) => void) => void };
122
+
123
+ if (server?.on) {
124
+ server.on('error', (err) => {
125
+ log.error(`function:${service.name} failed to start`, err);
126
+ reject(err);
127
+ });
128
+ }
129
+
130
+ functionServers.set(service.name, server);
131
+ });
132
+
133
+ return { name: service.name, port };
134
+ };
135
+
136
+ const startFunctions = async (
137
+ options: FunctionsOptions | undefined,
138
+ functionServers: Map<FunctionName, HttpServer>
139
+ ): Promise<StartedFunction[]> => {
140
+ const services = normalizeFunctionServices(options);
141
+ if (!services.length) return [];
142
+
143
+ ensureUniquePorts(services);
144
+
145
+ const started: StartedFunction[] = [];
146
+ for (const service of services) {
147
+ started.push(await startFunction(service, functionServers));
148
+ }
149
+
150
+ return started;
151
+ };
152
+
153
+ type JobRunner = {
154
+ listen: () => void;
155
+ stop?: () => Promise<void> | void;
156
+ };
157
+
158
+ const listenApp = async (
159
+ app: { listen: (port: number, host?: string) => HttpServer },
160
+ port: number,
161
+ host?: string
162
+ ): Promise<HttpServer> =>
163
+ new Promise((resolveListen, rejectListen) => {
164
+ const server = host ? app.listen(port, host) : app.listen(port);
165
+
166
+ const cleanup = () => {
167
+ server.off('listening', handleListen);
168
+ server.off('error', handleError);
169
+ };
170
+
171
+ const handleListen = () => {
172
+ cleanup();
173
+ resolveListen(server);
174
+ };
175
+
176
+ const handleError = (err: Error) => {
177
+ cleanup();
178
+ rejectListen(err);
179
+ };
180
+
181
+ server.once('listening', handleListen);
182
+ server.once('error', handleError);
183
+ });
184
+
185
+ const closeServer = async (server?: HttpServer | null): Promise<void> => {
186
+ if (!server || !server.listening) return;
187
+ await new Promise<void>((resolveClose, rejectClose) => {
188
+ server.close((err) => {
189
+ if (err) {
190
+ rejectClose(err);
191
+ return;
192
+ }
193
+ resolveClose();
194
+ });
195
+ });
196
+ };
197
+
198
+ export class KnativeJobsSvc {
199
+ private options: KnativeJobsSvcOptions;
200
+ private started = false;
201
+ private result: KnativeJobsSvcResult = {
202
+ functions: [],
203
+ jobs: false
204
+ };
205
+ private functionServers = new Map<FunctionName, HttpServer>();
206
+ private jobsHttpServer?: HttpServer;
207
+ private worker?: JobRunner;
208
+ private scheduler?: JobRunner;
209
+ private jobsPoolManager?: { close: () => Promise<void> };
210
+
211
+ constructor(options: KnativeJobsSvcOptions = {}) {
212
+ this.options = options;
213
+ }
214
+
215
+ async start(): Promise<KnativeJobsSvcResult> {
216
+ if (this.started) return this.result;
217
+ this.started = true;
218
+ this.result = {
219
+ functions: [],
220
+ jobs: false
221
+ };
222
+
223
+ if (shouldEnableFunctions(this.options.functions)) {
224
+ log.info('starting functions');
225
+ this.result.functions = await startFunctions(
226
+ this.options.functions,
227
+ this.functionServers
228
+ );
229
+ }
230
+
231
+ if (this.options.jobs?.enabled) {
232
+ log.info('starting jobs service');
233
+ await this.startJobs();
234
+ this.result.jobs = true;
235
+ }
236
+
237
+ return this.result;
238
+ }
239
+
240
+ async stop(): Promise<void> {
241
+ if (!this.started) return;
242
+ this.started = false;
243
+
244
+ if (this.worker?.stop) {
245
+ await this.worker.stop();
246
+ }
247
+ if (this.scheduler?.stop) {
248
+ await this.scheduler.stop();
249
+ }
250
+ this.worker = undefined;
251
+ this.scheduler = undefined;
252
+
253
+ await closeServer(this.jobsHttpServer);
254
+ this.jobsHttpServer = undefined;
255
+
256
+ if (this.jobsPoolManager) {
257
+ await this.jobsPoolManager.close();
258
+ this.jobsPoolManager = undefined;
259
+ }
260
+
261
+ for (const server of this.functionServers.values()) {
262
+ await closeServer(server);
263
+ }
264
+ this.functionServers.clear();
265
+ }
266
+
267
+ private async startJobs(): Promise<void> {
268
+ const pgPool = poolManager.getPool();
269
+ const jobsApp = jobServerFactory(pgPool);
270
+ const callbackPort = getJobsCallbackPort();
271
+ this.jobsHttpServer = await listenApp(jobsApp, callbackPort);
272
+
273
+ const tasks = getJobSupported();
274
+ this.worker = new Worker({
275
+ pgPool,
276
+ tasks,
277
+ workerId: getWorkerHostname()
278
+ });
279
+ this.scheduler = new Scheduler({
280
+ pgPool,
281
+ tasks,
282
+ workerId: getSchedulerHostname()
283
+ });
284
+
285
+ this.jobsPoolManager = poolManager;
286
+
287
+ this.worker.listen();
288
+ this.scheduler.listen();
289
+ }
290
+ }
291
+
292
+ const parseList = (value?: string): string[] => {
293
+ if (!value) return [];
294
+ return value
295
+ .split(',')
296
+ .map((item) => item.trim())
297
+ .filter(Boolean);
298
+ };
299
+
300
+ const parsePortMap = (value?: string): Record<string, number> => {
301
+ if (!value) return {};
302
+
303
+ const trimmed = value.trim();
304
+ if (!trimmed) return {};
305
+
306
+ if (trimmed.startsWith('{')) {
307
+ try {
308
+ const parsed = JSON.parse(trimmed) as Record<string, number>;
309
+ return Object.entries(parsed).reduce<Record<string, number>>((acc, [key, port]) => {
310
+ const portNumber = Number(port);
311
+ if (Number.isFinite(portNumber)) {
312
+ acc[key] = portNumber;
313
+ }
314
+ return acc;
315
+ }, {});
316
+ } catch {
317
+ return {};
318
+ }
319
+ }
320
+
321
+ return trimmed.split(',').reduce<Record<string, number>>((acc, pair) => {
322
+ const [rawName, rawPort] = pair.split(/[:=]/).map((item) => item.trim());
323
+ const port = Number(rawPort);
324
+ if (rawName && Number.isFinite(port)) {
325
+ acc[rawName] = port;
326
+ }
327
+ return acc;
328
+ }, {});
329
+ };
330
+
331
+ const buildFunctionsOptionsFromEnv = (): KnativeJobsSvcOptions['functions'] => {
332
+ const rawFunctions = (process.env.CONSTRUCTIVE_FUNCTIONS || '').trim();
333
+ if (!rawFunctions) return undefined;
334
+
335
+ const portMap = parsePortMap(process.env.CONSTRUCTIVE_FUNCTION_PORTS);
336
+ const normalized = rawFunctions.toLowerCase();
337
+
338
+ if (normalized === 'all' || normalized === '*') {
339
+ return { enabled: true };
340
+ }
341
+
342
+ const names = parseList(rawFunctions) as FunctionName[];
343
+ if (!names.length) return undefined;
344
+
345
+ const services: FunctionServiceConfig[] = names.map((name) => ({
346
+ name,
347
+ port: portMap[name]
348
+ }));
349
+
350
+ return {
351
+ enabled: true,
352
+ services
353
+ };
354
+ };
355
+
356
+ export const buildKnativeJobsSvcOptionsFromEnv = (): KnativeJobsSvcOptions => ({
357
+ jobs: {
358
+ enabled: parseEnvBoolean(process.env.CONSTRUCTIVE_JOBS_ENABLED) ?? true
359
+ },
360
+ functions: buildFunctionsOptionsFromEnv()
361
+ });
362
+
363
+ export const startKnativeJobsSvcFromEnv = async (): Promise<KnativeJobsSvcResult> => {
364
+ const server = new KnativeJobsSvc(buildKnativeJobsSvcOptionsFromEnv());
365
+ return server.start();
366
+ };
367
+
368
+ export const startJobsServices = () => {
369
+ log.info('starting jobs services...');
370
+ const pgPool = poolManager.getPool();
371
+ const app = jobServerFactory(pgPool);
372
+
373
+ const callbackPort = getJobsCallbackPort();
374
+ const httpServer = app.listen(callbackPort, () => {
375
+ log.info(`listening ON ${callbackPort}`);
376
+
377
+ const tasks = getJobSupported();
378
+
379
+ const worker = new Worker({
380
+ pgPool,
381
+ workerId: getWorkerHostname(),
382
+ tasks
383
+ });
384
+
385
+ const scheduler = new Scheduler({
386
+ pgPool,
387
+ workerId: getSchedulerHostname(),
388
+ tasks
389
+ });
390
+
391
+ worker.listen();
392
+ scheduler.listen();
393
+ });
394
+
395
+ return { pgPool, httpServer };
396
+ };
397
+
398
+ export const waitForJobsPrereqs = async (): Promise<void> => {
399
+ log.info('waiting for jobs prereqs');
400
+ let client: Client | null = null;
401
+ try {
402
+ const cfg = getJobPgConfig();
403
+ client = new Client({
404
+ host: cfg.host,
405
+ port: cfg.port,
406
+ user: cfg.user,
407
+ password: cfg.password,
408
+ database: cfg.database
409
+ });
410
+ await client.connect();
411
+ const schema = getJobSchema();
412
+ await client.query(`SELECT * FROM "${schema}".jobs LIMIT 1;`);
413
+ } catch (error) {
414
+ log.error(error);
415
+ throw new Error('jobs server boot failed...');
416
+ } finally {
417
+ if (client) {
418
+ void client.end();
419
+ }
420
+ }
421
+ };
422
+
423
+ export const bootJobs = async (): Promise<void> => {
424
+ log.info('attempting to boot jobs');
425
+ await retry(
426
+ async () => {
427
+ await waitForJobsPrereqs();
428
+ },
429
+ {
430
+ retries: 10,
431
+ factor: 2
432
+ }
433
+ );
434
+
435
+ const options = buildKnativeJobsSvcOptionsFromEnv();
436
+ if (options.jobs?.enabled === false) {
437
+ log.info('jobs disabled; skipping startup');
438
+ return;
439
+ }
440
+
441
+ const server = new KnativeJobsSvc(options);
442
+ await server.start();
443
+ };
444
+
445
+ export * from './types';
package/src/run.ts CHANGED
@@ -1,93 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import Scheduler from '@constructive-io/job-scheduler';
4
- import Worker from '@constructive-io/knative-job-worker';
5
- import server from '@constructive-io/knative-job-server';
6
- import poolManager from '@constructive-io/job-pg';
7
- import { Client } from 'pg';
8
- import retry from 'async-retry';
9
- import {
10
- getJobPgConfig,
11
- getJobSchema,
12
- getSchedulerHostname,
13
- getWorkerHostname,
14
- getJobSupported,
15
- getJobsCallbackPort,
16
- } from '@constructive-io/job-utils';
3
+ export { bootJobs, startJobsServices, waitForJobsPrereqs } from './index';
17
4
 
18
- export const startJobsServices = () => {
19
- // eslint-disable-next-line no-console
20
- console.log('starting jobs services...');
21
- const pgPool = poolManager.getPool();
22
- const app = server(pgPool);
23
-
24
- const callbackPort = getJobsCallbackPort();
25
- const httpServer = app.listen(callbackPort, () => {
26
- // eslint-disable-next-line no-console
27
- console.log(`[cb] listening ON ${callbackPort}`);
28
-
29
- const tasks = getJobSupported();
30
-
31
- const worker = new Worker({
32
- pgPool,
33
- workerId: getWorkerHostname(),
34
- tasks
35
- });
36
-
37
- const scheduler = new Scheduler({
38
- pgPool,
39
- workerId: getSchedulerHostname(),
40
- tasks
41
- });
42
-
43
- worker.listen();
44
- scheduler.listen();
45
- });
46
-
47
- return { pgPool, httpServer };
48
- };
49
-
50
- export const waitForJobsPrereqs = async (): Promise<void> => {
51
- // eslint-disable-next-line no-console
52
- console.log('waiting for jobs prereqs');
53
- let client: Client | null = null;
54
- try {
55
- const cfg = getJobPgConfig();
56
- client = new Client({
57
- host: cfg.host,
58
- port: cfg.port,
59
- user: cfg.user,
60
- password: cfg.password,
61
- database: cfg.database
62
- });
63
- await client.connect();
64
- const schema = getJobSchema();
65
- await client.query(`SELECT * FROM "${schema}".jobs LIMIT 1;`);
66
- } catch (error) {
67
- // eslint-disable-next-line no-console
68
- console.log(error);
69
- throw new Error('jobs server boot failed...');
70
- } finally {
71
- if (client) {
72
- void client.end();
73
- }
74
- }
75
- };
76
-
77
- export const bootJobs = async (): Promise<void> => {
78
- // eslint-disable-next-line no-console
79
- console.log('attempting to boot jobs');
80
- await retry(
81
- async () => {
82
- await waitForJobsPrereqs();
83
- },
84
- {
85
- retries: 10,
86
- factor: 2
87
- }
88
- );
89
- startJobsServices();
90
- };
5
+ import { bootJobs } from './index';
91
6
 
92
7
  if (require.main === module) {
93
8
  void bootJobs();
package/src/types.ts ADDED
@@ -0,0 +1,30 @@
1
+ export type FunctionName = 'simple-email' | 'send-email-link';
2
+
3
+ export type FunctionServiceConfig = {
4
+ name: FunctionName;
5
+ port?: number;
6
+ };
7
+
8
+ export type FunctionsOptions = {
9
+ enabled?: boolean;
10
+ services?: FunctionServiceConfig[];
11
+ };
12
+
13
+ export type JobsOptions = {
14
+ enabled?: boolean;
15
+ };
16
+
17
+ export type KnativeJobsSvcOptions = {
18
+ functions?: FunctionsOptions;
19
+ jobs?: JobsOptions;
20
+ };
21
+
22
+ export type StartedFunction = {
23
+ name: FunctionName;
24
+ port: number;
25
+ };
26
+
27
+ export type KnativeJobsSvcResult = {
28
+ functions: StartedFunction[];
29
+ jobs: boolean;
30
+ };