@balena/pinejs 18.0.1-build-fisehara-reproduce-patch-translation-issue-d7aff91660b81d1683ba85c91d788c707dc81023-1 → 18.1.0-build-joshbwlng-tasks-79d39d05d88bf5f8e2ad08ed75694a2a728dc9a3-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/.pinejs-cache.json +1 -1
- package/.versionbot/CHANGELOG.yml +6 -16
- package/CHANGELOG.md +3 -4
- package/VERSION +1 -1
- package/out/config-loader/env.d.ts +4 -0
- package/out/config-loader/env.js +5 -1
- package/out/config-loader/env.js.map +1 -1
- package/out/database-layer/db.d.ts +3 -0
- package/out/database-layer/db.js +20 -3
- package/out/database-layer/db.js.map +1 -1
- package/out/sbvr-api/permissions.js +0 -4
- package/out/sbvr-api/permissions.js.map +1 -1
- package/out/server-glue/module.d.ts +1 -0
- package/out/server-glue/module.js +4 -1
- package/out/server-glue/module.js.map +1 -1
- package/out/tasks/common.d.ts +4 -0
- package/out/tasks/common.js +11 -0
- package/out/tasks/common.js.map +1 -0
- package/out/tasks/index.d.ts +9 -0
- package/out/tasks/index.js +134 -0
- package/out/tasks/index.js.map +1 -0
- package/out/tasks/tasks.d.ts +40 -0
- package/out/tasks/tasks.js +3 -0
- package/out/tasks/tasks.js.map +1 -0
- package/out/tasks/tasks.sbvr +55 -0
- package/out/tasks/worker.d.ts +32 -0
- package/out/tasks/worker.js +224 -0
- package/out/tasks/worker.js.map +1 -0
- package/package.json +9 -6
- package/src/config-loader/env.ts +6 -1
- package/src/database-layer/db.ts +30 -3
- package/src/migrator/migrations.ts +1 -1
- package/src/sbvr-api/dev.ts +1 -1
- package/src/sbvr-api/permissions.ts +0 -14
- package/src/sbvr-api/sbvr-utils.ts +1 -1
- package/src/sbvr-api/user.ts +1 -1
- package/src/server-glue/module.ts +3 -0
- package/src/tasks/common.ts +9 -0
- package/src/tasks/index.ts +152 -0
- package/src/tasks/tasks.sbvr +55 -0
- package/src/tasks/tasks.ts +46 -0
- package/src/tasks/worker.ts +309 -0
@@ -692,7 +692,6 @@ const onceGetter = <T, U extends keyof T>(
|
|
692
692
|
// after we have called fn
|
693
693
|
let nullableFn: undefined | typeof fn = fn;
|
694
694
|
let thrownErr: Error | undefined;
|
695
|
-
// OVERWRITING definition property here, removing the previously existing alias
|
696
695
|
Object.defineProperty(obj, propName, {
|
697
696
|
enumerable: true,
|
698
697
|
configurable: true,
|
@@ -1044,14 +1043,7 @@ const getBoundConstrainedMemoizer = memoizeWeak(
|
|
1044
1043
|
const permissionsTable = (tables[permissionResourceName] = {
|
1045
1044
|
...table,
|
1046
1045
|
});
|
1047
|
-
if (permissionResourceName === 'student$permissions"update"') {
|
1048
|
-
// console.log(`=== tables[${permissionResourceName}]-1:`, JSON.stringify(tables[permissionResourceName], null, 2)); // HAS THE ALIAS
|
1049
|
-
// console.log(`=== permissionsTable-1:`, JSON.stringify(permissionsTable, null, 2)); // HAS THE ALIAS
|
1050
|
-
permissionsTable.resourceName = permissionResourceName;
|
1051
|
-
return permissionsTable;
|
1052
|
-
}
|
1053
1046
|
permissionsTable.resourceName = permissionResourceName;
|
1054
|
-
|
1055
1047
|
onceGetter(permissionsTable, 'definition', () =>
|
1056
1048
|
// For $filter on eg a DELETE you need read permissions on the sub-resources,
|
1057
1049
|
// you only need delete permissions on the resource being deleted
|
@@ -1064,12 +1056,6 @@ const getBoundConstrainedMemoizer = memoizeWeak(
|
|
1064
1056
|
),
|
1065
1057
|
),
|
1066
1058
|
);
|
1067
|
-
/*
|
1068
|
-
if (permissionResourceName === 'student$permissions"update"') {
|
1069
|
-
console.log(`=== tables[${permissionResourceName}]-2:`, JSON.stringify(tables[permissionResourceName], null, 2)); // DOES NOT HAVE THE ALIAS
|
1070
|
-
console.log(`=== permissionsTable-2:`, JSON.stringify(permissionsTable, null, 2)); // DOES NOT HAVE THE ALIAS
|
1071
|
-
}
|
1072
|
-
*/
|
1073
1059
|
|
1074
1060
|
return permissionsTable;
|
1075
1061
|
},
|
@@ -777,7 +777,7 @@ export const postExecuteModels = async (tx: Db.Tx): Promise<void> => {
|
|
777
777
|
// Hence, skipped migrations from earlier models are not set as executed as the `migration` table is missing
|
778
778
|
// Here the skipped migrations that haven't been set properly are covered
|
779
779
|
// This is mostly an edge case when running on an empty database schema and migrations model hasn't been executed, yet.
|
780
|
-
// One
|
780
|
+
// One specific case are tests to run tests against migrated and unmigrated database states
|
781
781
|
|
782
782
|
for (const modelKey of Object.keys(models)) {
|
783
783
|
const pendingToSetExecutedMigrations =
|
package/src/sbvr-api/user.ts
CHANGED
@@ -6,6 +6,7 @@ import * as dbModule from '../database-layer/db';
|
|
6
6
|
import * as configLoader from '../config-loader/config-loader';
|
7
7
|
import * as migrator from '../migrator/sync';
|
8
8
|
import type * as migratorUtils from '../migrator/utils';
|
9
|
+
import * as tasks from '../tasks';
|
9
10
|
|
10
11
|
import * as sbvrUtils from '../sbvr-api/sbvr-utils';
|
11
12
|
import { PINEJS_ADVISORY_LOCK } from '../config-loader/env';
|
@@ -19,6 +20,7 @@ export * as errors from '../sbvr-api/errors';
|
|
19
20
|
export * as env from '../config-loader/env';
|
20
21
|
export * as types from '../sbvr-api/common-types';
|
21
22
|
export * as hooks from '../sbvr-api/hooks';
|
23
|
+
export * as tasks from '../tasks';
|
22
24
|
export * as webResourceHandler from '../webresource-handler';
|
23
25
|
export type { configLoader as ConfigLoader };
|
24
26
|
export type { migratorUtils as Migrator };
|
@@ -63,6 +65,7 @@ export const init = async <T extends string>(
|
|
63
65
|
await sbvrUtils.setup(app, db);
|
64
66
|
const cfgLoader = configLoader.setup(app);
|
65
67
|
await cfgLoader.loadConfig(migrator.config);
|
68
|
+
await cfgLoader.loadConfig(tasks.config);
|
66
69
|
|
67
70
|
const promises: Array<Promise<void>> = [];
|
68
71
|
if (process.env.SBVR_SERVER_ENABLED) {
|
@@ -0,0 +1,152 @@
|
|
1
|
+
import type { Schema } from 'ajv';
|
2
|
+
import * as cronParser from 'cron-parser';
|
3
|
+
import { tasks as tasksEnv } from '../config-loader/env';
|
4
|
+
import { addPureHook } from '../sbvr-api/hooks';
|
5
|
+
import * as sbvrUtils from '../sbvr-api/sbvr-utils';
|
6
|
+
import type { ConfigLoader } from '../server-glue/module';
|
7
|
+
import { ajv, apiRoot, channel } from './common';
|
8
|
+
import type { TaskHandler } from './worker';
|
9
|
+
import { Worker } from './worker';
|
10
|
+
|
11
|
+
export type * from './tasks';
|
12
|
+
|
13
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
14
|
+
const modelText: string = require('./tasks.sbvr');
|
15
|
+
|
16
|
+
// Create trigger for handling new tasks
|
17
|
+
// Create index for polling tasks table
|
18
|
+
const initSql = `
|
19
|
+
CREATE OR REPLACE FUNCTION notify_task_insert()
|
20
|
+
RETURNS TRIGGER AS $$
|
21
|
+
BEGIN
|
22
|
+
PERFORM pg_notify('${channel}', NEW.id::text);
|
23
|
+
RETURN NEW;
|
24
|
+
END;
|
25
|
+
$$ LANGUAGE plpgsql;
|
26
|
+
|
27
|
+
CREATE OR REPLACE TRIGGER task_insert_trigger
|
28
|
+
AFTER INSERT ON task
|
29
|
+
FOR EACH ROW WHEN (NEW.status = 'queued' AND NEW."is scheduled to execute on-time" IS NULL)
|
30
|
+
EXECUTE FUNCTION notify_task_insert();
|
31
|
+
|
32
|
+
CREATE INDEX IF NOT EXISTS idx_task_poll ON task USING btree (
|
33
|
+
"is executed by-handler",
|
34
|
+
"is scheduled to execute on-time" ASC,
|
35
|
+
"id" ASC
|
36
|
+
) WHERE status = 'queued';
|
37
|
+
`;
|
38
|
+
|
39
|
+
export const config: ConfigLoader.Config = {
|
40
|
+
models: [
|
41
|
+
{
|
42
|
+
modelName: apiRoot,
|
43
|
+
apiRoot,
|
44
|
+
modelText,
|
45
|
+
customServerCode: exports,
|
46
|
+
initSql,
|
47
|
+
},
|
48
|
+
],
|
49
|
+
};
|
50
|
+
|
51
|
+
export let worker: Worker | null = null;
|
52
|
+
export async function setup(): Promise<void> {
|
53
|
+
// Async task functionality is only supported on Postgres
|
54
|
+
if (sbvrUtils.db.engine !== 'postgres') {
|
55
|
+
console.warn('Skipping task setup as database not supported');
|
56
|
+
return;
|
57
|
+
}
|
58
|
+
|
59
|
+
const client = sbvrUtils.api[apiRoot];
|
60
|
+
worker = new Worker(client);
|
61
|
+
|
62
|
+
// Add resource hooks
|
63
|
+
addPureHook('POST', apiRoot, 'task', {
|
64
|
+
POSTPARSE: async ({ req, request }) => {
|
65
|
+
// Set the actor
|
66
|
+
request.values.is_created_by__actor =
|
67
|
+
req.user?.actor ?? req.apiKey?.actor;
|
68
|
+
if (request.values.is_created_by__actor == null) {
|
69
|
+
throw new Error(
|
70
|
+
'Creating tasks with missing actor on req is not allowed',
|
71
|
+
);
|
72
|
+
}
|
73
|
+
|
74
|
+
// Set defaults
|
75
|
+
request.values.status = 'queued';
|
76
|
+
request.values.attempt_count = 0;
|
77
|
+
request.values.attempt_limit ??= 1;
|
78
|
+
|
79
|
+
// Set scheduled start time using cron expression if provided
|
80
|
+
if (
|
81
|
+
request.values.is_scheduled_with__cron_expression != null &&
|
82
|
+
request.values.is_scheduled_to_execute_on__time == null
|
83
|
+
) {
|
84
|
+
try {
|
85
|
+
request.values.is_scheduled_to_execute_on__time = cronParser
|
86
|
+
.parseExpression(request.values.is_scheduled_with__cron_expression)
|
87
|
+
.next()
|
88
|
+
.toDate()
|
89
|
+
.toISOString();
|
90
|
+
} catch {
|
91
|
+
throw new Error(
|
92
|
+
`Invalid cron expression: ${request.values.is_scheduled_with__cron_expression}`,
|
93
|
+
);
|
94
|
+
}
|
95
|
+
}
|
96
|
+
|
97
|
+
// Assert that the provided start time is far enough in the future
|
98
|
+
if (request.values.is_scheduled_to_execute_on__time != null) {
|
99
|
+
const now = new Date(Date.now() + tasksEnv.queueIntervalMS);
|
100
|
+
const startTime = new Date(
|
101
|
+
request.values.is_scheduled_to_execute_on__time,
|
102
|
+
);
|
103
|
+
if (startTime < now) {
|
104
|
+
throw new Error(
|
105
|
+
`Task scheduled start time must be greater than ${tasksEnv.queueIntervalMS} milliseconds in the future`,
|
106
|
+
);
|
107
|
+
}
|
108
|
+
}
|
109
|
+
|
110
|
+
// Assert that the requested handler exists
|
111
|
+
const handlerName = request.values.is_executed_by__handler;
|
112
|
+
if (handlerName == null) {
|
113
|
+
throw new Error(`Must specify a task handler to execute`);
|
114
|
+
}
|
115
|
+
const handler = worker?.handlers[handlerName];
|
116
|
+
if (handler == null) {
|
117
|
+
throw new Error(
|
118
|
+
`No task handler with name '${handlerName}' registered`,
|
119
|
+
);
|
120
|
+
}
|
121
|
+
|
122
|
+
// Assert that the provided parameter set is valid
|
123
|
+
if (handler.validate != null) {
|
124
|
+
if (!handler.validate(request.values.is_executed_with__parameter_set)) {
|
125
|
+
throw new Error(
|
126
|
+
`Invalid parameter set: ${ajv.errorsText(handler.validate.errors)}`,
|
127
|
+
);
|
128
|
+
}
|
129
|
+
}
|
130
|
+
},
|
131
|
+
});
|
132
|
+
}
|
133
|
+
|
134
|
+
// Register a task handler
|
135
|
+
export function addTaskHandler(
|
136
|
+
name: string,
|
137
|
+
fn: TaskHandler['fn'],
|
138
|
+
schema?: Schema,
|
139
|
+
): void {
|
140
|
+
if (worker == null) {
|
141
|
+
throw new Error('Database does not support tasks');
|
142
|
+
}
|
143
|
+
|
144
|
+
if (worker.handlers[name] != null) {
|
145
|
+
throw new Error(`Task handler with name '${name}' already registered`);
|
146
|
+
}
|
147
|
+
worker.handlers[name] = {
|
148
|
+
name,
|
149
|
+
fn,
|
150
|
+
validate: schema != null ? ajv.compile(schema) : undefined,
|
151
|
+
};
|
152
|
+
}
|
@@ -0,0 +1,55 @@
|
|
1
|
+
Vocabulary: tasks
|
2
|
+
|
3
|
+
Term: id
|
4
|
+
Concept Type: Big Serial (Type)
|
5
|
+
Term: actor
|
6
|
+
Concept Type: Integer (Type)
|
7
|
+
Term: attempt count
|
8
|
+
Concept Type: Integer (Type)
|
9
|
+
Term: attempt limit
|
10
|
+
Concept Type: Integer (Type)
|
11
|
+
Term: cron expression
|
12
|
+
Concept Type: Short Text (Type)
|
13
|
+
Term: error message
|
14
|
+
Concept Type: Short Text (Type)
|
15
|
+
Term: handler
|
16
|
+
Concept Type: Short Text (Type)
|
17
|
+
Term: key
|
18
|
+
Concept Type: Short Text (Type)
|
19
|
+
Term: parameter set
|
20
|
+
Concept Type: JSON (Type)
|
21
|
+
Term: status
|
22
|
+
Concept Type: Short Text (Type)
|
23
|
+
Term: time
|
24
|
+
Concept Type: Date Time (Type)
|
25
|
+
|
26
|
+
Term: task
|
27
|
+
Fact type: task has id
|
28
|
+
Necessity: each task has exactly one id
|
29
|
+
Fact type: task has key
|
30
|
+
Necessity: each task has at most one key
|
31
|
+
Fact type: task is created by actor
|
32
|
+
Necessity: each task is created by exactly one actor
|
33
|
+
Fact type: task is executed by handler
|
34
|
+
Necessity: each task is executed by exactly one handler
|
35
|
+
Fact type: task is executed with parameter set
|
36
|
+
Necessity: each task is executed with at most one parameter set
|
37
|
+
Fact type: task is scheduled with cron expression
|
38
|
+
Necessity: each task is scheduled with at most one cron expression
|
39
|
+
Fact type: task is scheduled to execute on time
|
40
|
+
Necessity: each task is scheduled to execute on at most one time
|
41
|
+
Fact type: task has status
|
42
|
+
Necessity: each task has exactly one status
|
43
|
+
Definition: "queued" or "cancelled" or "succeeded" or "failed"
|
44
|
+
Fact type: task started on time
|
45
|
+
Necessity: each task started on at most one time
|
46
|
+
Fact type: task ended on time
|
47
|
+
Necessity: each task ended on at most one time
|
48
|
+
Fact type: task has error message
|
49
|
+
Necessity: each task has at most one error message
|
50
|
+
Fact type: task has attempt count
|
51
|
+
Necessity: each task has exactly one attempt count
|
52
|
+
Fact type: task has attempt limit
|
53
|
+
Necessity: each task has exactly one attempt limit
|
54
|
+
Necessity: each task has an attempt limit that is greater than or equal to 1
|
55
|
+
|
@@ -0,0 +1,46 @@
|
|
1
|
+
// These types were generated by @balena/abstract-sql-to-typescript v4.0.0
|
2
|
+
|
3
|
+
import type { Types } from '@balena/abstract-sql-to-typescript';
|
4
|
+
|
5
|
+
export interface Task {
|
6
|
+
Read: {
|
7
|
+
created_at: Types['Date Time']['Read'];
|
8
|
+
modified_at: Types['Date Time']['Read'];
|
9
|
+
id: Types['Big Serial']['Read'];
|
10
|
+
key: Types['Short Text']['Read'] | null;
|
11
|
+
is_created_by__actor: Types['Integer']['Read'];
|
12
|
+
is_executed_by__handler: Types['Short Text']['Read'];
|
13
|
+
is_executed_with__parameter_set: Types['JSON']['Read'] | null;
|
14
|
+
is_scheduled_with__cron_expression: Types['Short Text']['Read'] | null;
|
15
|
+
is_scheduled_to_execute_on__time: Types['Date Time']['Read'] | null;
|
16
|
+
status: 'queued' | 'cancelled' | 'succeeded' | 'failed';
|
17
|
+
started_on__time: Types['Date Time']['Read'] | null;
|
18
|
+
ended_on__time: Types['Date Time']['Read'] | null;
|
19
|
+
error_message: Types['Short Text']['Read'] | null;
|
20
|
+
attempt_count: Types['Integer']['Read'];
|
21
|
+
attempt_limit: Types['Integer']['Read'];
|
22
|
+
};
|
23
|
+
Write: {
|
24
|
+
created_at: Types['Date Time']['Write'];
|
25
|
+
modified_at: Types['Date Time']['Write'];
|
26
|
+
id: Types['Big Serial']['Write'];
|
27
|
+
key: Types['Short Text']['Write'] | null;
|
28
|
+
is_created_by__actor: Types['Integer']['Write'];
|
29
|
+
is_executed_by__handler: Types['Short Text']['Write'];
|
30
|
+
is_executed_with__parameter_set: Types['JSON']['Write'] | null;
|
31
|
+
is_scheduled_with__cron_expression: Types['Short Text']['Write'] | null;
|
32
|
+
is_scheduled_to_execute_on__time: Types['Date Time']['Write'] | null;
|
33
|
+
status: 'queued' | 'cancelled' | 'succeeded' | 'failed';
|
34
|
+
started_on__time: Types['Date Time']['Write'] | null;
|
35
|
+
ended_on__time: Types['Date Time']['Write'] | null;
|
36
|
+
error_message: Types['Short Text']['Write'] | null;
|
37
|
+
attempt_count: Types['Integer']['Write'];
|
38
|
+
attempt_limit: Types['Integer']['Write'];
|
39
|
+
};
|
40
|
+
}
|
41
|
+
|
42
|
+
export default interface $Model {
|
43
|
+
task: Task;
|
44
|
+
|
45
|
+
|
46
|
+
}
|
@@ -0,0 +1,309 @@
|
|
1
|
+
import type { ValidateFunction } from 'ajv';
|
2
|
+
import { setTimeout } from 'node:timers/promises';
|
3
|
+
import type { AnyObject } from 'pinejs-client-core';
|
4
|
+
import { tasks as tasksEnv } from '../config-loader/env';
|
5
|
+
import type * as Db from '../database-layer/db';
|
6
|
+
import * as permissions from '../sbvr-api/permissions';
|
7
|
+
import { PinejsClient } from '../sbvr-api/sbvr-utils';
|
8
|
+
import { sbvrUtils } from '../server-glue/module';
|
9
|
+
import { ajv, channel } from './common';
|
10
|
+
import type { Task } from './tasks';
|
11
|
+
|
12
|
+
interface TaskArgs {
|
13
|
+
api: PinejsClient;
|
14
|
+
params: AnyObject;
|
15
|
+
}
|
16
|
+
|
17
|
+
type TaskResponse = Promise<{
|
18
|
+
status: Task['Read']['status'];
|
19
|
+
error?: string;
|
20
|
+
}>;
|
21
|
+
|
22
|
+
export interface TaskHandler {
|
23
|
+
name: string;
|
24
|
+
fn: (options: TaskArgs) => TaskResponse;
|
25
|
+
validate?: ValidateFunction;
|
26
|
+
}
|
27
|
+
|
28
|
+
type PartialTask = Pick<
|
29
|
+
Task['Read'],
|
30
|
+
| 'id'
|
31
|
+
| 'is_created_by__actor'
|
32
|
+
| 'is_executed_by__handler'
|
33
|
+
| 'is_executed_with__parameter_set'
|
34
|
+
| 'is_scheduled_with__cron_expression'
|
35
|
+
| 'attempt_count'
|
36
|
+
| 'attempt_limit'
|
37
|
+
>;
|
38
|
+
|
39
|
+
// Map of column names with SBVR names used in SELECT queries
|
40
|
+
const selectColumns = Object.entries({
|
41
|
+
id: 'id',
|
42
|
+
'is executed by-handler': 'is_executed_by__handler',
|
43
|
+
'is executed with-parameter set': 'is_executed_with__parameter_set',
|
44
|
+
'is scheduled with-cron expression': 'is_scheduled_with__cron_expression',
|
45
|
+
'attempt count': 'attempt_count',
|
46
|
+
'attempt limit': 'attempt_limit',
|
47
|
+
'is created by-actor': 'is_created_by__actor',
|
48
|
+
} satisfies Record<string, keyof Task['Read']>)
|
49
|
+
.map(([key, value]) => `t."${key}" AS "${value}"`)
|
50
|
+
.join(', ');
|
51
|
+
|
52
|
+
// The worker is responsible for executing tasks in the queue. It listens for
|
53
|
+
// notifications and polls the database for tasks to execute. It will execute
|
54
|
+
// tasks in parallel up to a certain concurrency limit.
|
55
|
+
export class Worker {
|
56
|
+
public handlers: Record<string, TaskHandler> = {};
|
57
|
+
private readonly concurrency: number;
|
58
|
+
private readonly interval: number;
|
59
|
+
private executing = 0;
|
60
|
+
|
61
|
+
constructor(private readonly client: PinejsClient) {
|
62
|
+
this.concurrency = tasksEnv.queueConcurrency;
|
63
|
+
this.interval = tasksEnv.queueIntervalMS;
|
64
|
+
}
|
65
|
+
|
66
|
+
// Check if instance can execute more tasks
|
67
|
+
private canExecute(): boolean {
|
68
|
+
return (
|
69
|
+
this.executing < this.concurrency && Object.keys(this.handlers).length > 0
|
70
|
+
);
|
71
|
+
}
|
72
|
+
|
73
|
+
private async execute(task: PartialTask, tx: Db.Tx): Promise<void> {
|
74
|
+
this.executing++;
|
75
|
+
try {
|
76
|
+
// Get specified handler
|
77
|
+
const handler = this.handlers[task.is_executed_by__handler];
|
78
|
+
const startedOnTime = new Date();
|
79
|
+
|
80
|
+
// This should never actually happen
|
81
|
+
if (handler == null) {
|
82
|
+
await this.update(
|
83
|
+
tx,
|
84
|
+
task,
|
85
|
+
startedOnTime,
|
86
|
+
'failed',
|
87
|
+
'Matching task handler not found, this should never happen!',
|
88
|
+
);
|
89
|
+
return;
|
90
|
+
}
|
91
|
+
|
92
|
+
// Validate parameters before execution so we can fail early if
|
93
|
+
// the parameter set is invalid. This can happen if the handler
|
94
|
+
// definition changes after a task is added to the queue.
|
95
|
+
if (
|
96
|
+
handler.validate != null &&
|
97
|
+
!handler.validate(task.is_executed_with__parameter_set)
|
98
|
+
) {
|
99
|
+
await this.update(
|
100
|
+
tx,
|
101
|
+
task,
|
102
|
+
startedOnTime,
|
103
|
+
'failed',
|
104
|
+
`Invalid parameter set: ${ajv.errorsText(handler.validate.errors)}`,
|
105
|
+
);
|
106
|
+
return;
|
107
|
+
}
|
108
|
+
|
109
|
+
// Execute handler and update task with results
|
110
|
+
let status: Task['Read']['status'] = 'queued';
|
111
|
+
let error: string | undefined;
|
112
|
+
try {
|
113
|
+
const results = await handler.fn({
|
114
|
+
api: new PinejsClient({}),
|
115
|
+
params: task.is_executed_with__parameter_set ?? {},
|
116
|
+
});
|
117
|
+
status = results.status;
|
118
|
+
error = results.error;
|
119
|
+
} finally {
|
120
|
+
await this.update(tx, task, startedOnTime, status, error);
|
121
|
+
}
|
122
|
+
} catch (err) {
|
123
|
+
// This shouldn't happen, but if it does we want to log and kill the process
|
124
|
+
console.error(
|
125
|
+
`Failed to execute task ${task.id} with handler ${task.is_executed_by__handler}:`,
|
126
|
+
err,
|
127
|
+
);
|
128
|
+
process.exit(1);
|
129
|
+
} finally {
|
130
|
+
this.executing--;
|
131
|
+
}
|
132
|
+
}
|
133
|
+
|
134
|
+
// Update task and schedule next attempt if needed
|
135
|
+
private async update(
|
136
|
+
tx: Db.Tx,
|
137
|
+
task: PartialTask,
|
138
|
+
startedOnTime: Date,
|
139
|
+
status: Task['Read']['status'],
|
140
|
+
errorMessage?: string,
|
141
|
+
): Promise<void> {
|
142
|
+
const attemptCount = task.attempt_count + 1;
|
143
|
+
const body: Partial<Task['Write']> = {
|
144
|
+
started_on__time: startedOnTime,
|
145
|
+
ended_on__time: new Date(),
|
146
|
+
status,
|
147
|
+
attempt_count: attemptCount,
|
148
|
+
...(errorMessage != null && { error_message: errorMessage }),
|
149
|
+
};
|
150
|
+
|
151
|
+
// Re-enqueue if the task failed but has retries left, remember that
|
152
|
+
// attemptCount includes the initial attempt while attempt_limit does not
|
153
|
+
if (status === 'failed' && attemptCount < task.attempt_limit) {
|
154
|
+
body.status = 'queued';
|
155
|
+
|
156
|
+
// Schedule next attempt using exponential backoff
|
157
|
+
body.is_scheduled_to_execute_on__time =
|
158
|
+
this.getNextAttemptTime(attemptCount);
|
159
|
+
}
|
160
|
+
|
161
|
+
// Patch current task
|
162
|
+
await this.client.patch({
|
163
|
+
resource: 'task',
|
164
|
+
passthrough: {
|
165
|
+
tx,
|
166
|
+
req: permissions.root,
|
167
|
+
},
|
168
|
+
id: task.id,
|
169
|
+
body,
|
170
|
+
});
|
171
|
+
|
172
|
+
// Create new task with same configuration if previous
|
173
|
+
// iteration completed and has a cron expression
|
174
|
+
if (
|
175
|
+
body.status != null &&
|
176
|
+
['failed', 'succeeded'].includes(body.status) &&
|
177
|
+
task.is_scheduled_with__cron_expression != null
|
178
|
+
) {
|
179
|
+
await this.client.post({
|
180
|
+
resource: 'task',
|
181
|
+
passthrough: {
|
182
|
+
tx,
|
183
|
+
req: permissions.root,
|
184
|
+
},
|
185
|
+
options: {
|
186
|
+
returnResource: false,
|
187
|
+
},
|
188
|
+
body: {
|
189
|
+
attempt_limit: task.attempt_limit,
|
190
|
+
is_created_by__actor: task.is_created_by__actor,
|
191
|
+
is_executed_by__handler: task.is_executed_by__handler,
|
192
|
+
is_executed_with__parameter_set: task.is_executed_with__parameter_set,
|
193
|
+
is_scheduled_with__cron_expression:
|
194
|
+
task.is_scheduled_with__cron_expression,
|
195
|
+
},
|
196
|
+
});
|
197
|
+
}
|
198
|
+
}
|
199
|
+
|
200
|
+
// Calculate next attempt time using exponential backoff
|
201
|
+
private getNextAttemptTime(attempt: number): Date | null {
|
202
|
+
const delay = Math.ceil(Math.exp(Math.min(10, attempt)));
|
203
|
+
return new Date(Date.now() + delay);
|
204
|
+
}
|
205
|
+
|
206
|
+
// Poll for tasks and execute them
|
207
|
+
// This is recursive and is spawned once per concurrency limit
|
208
|
+
private poll(): void {
|
209
|
+
let executed = false;
|
210
|
+
void (async () => {
|
211
|
+
try {
|
212
|
+
if (!this.canExecute()) {
|
213
|
+
return;
|
214
|
+
}
|
215
|
+
const handlerNames = Object.keys(this.handlers);
|
216
|
+
await sbvrUtils.db.transaction(async (tx) => {
|
217
|
+
const result = await sbvrUtils.db.executeSql(
|
218
|
+
`SELECT ${selectColumns}
|
219
|
+
FROM task AS t
|
220
|
+
WHERE
|
221
|
+
t."is executed by-handler" IN (${handlerNames.map((_, index) => `$${index + 1}`).join(', ')}) AND
|
222
|
+
t."status" = 'queued' AND
|
223
|
+
t."attempt count" <= t."attempt limit" AND
|
224
|
+
(
|
225
|
+
t."is scheduled to execute on-time" IS NULL OR
|
226
|
+
t."is scheduled to execute on-time" <= CURRENT_TIMESTAMP + $${handlerNames.length + 1} * INTERVAL '1 SECOND'
|
227
|
+
)
|
228
|
+
ORDER BY
|
229
|
+
t."is scheduled to execute on-time" ASC,
|
230
|
+
t."id" ASC
|
231
|
+
LIMIT 1 FOR UPDATE SKIP LOCKED`,
|
232
|
+
[...handlerNames, Math.ceil(this.interval / 1000)],
|
233
|
+
);
|
234
|
+
|
235
|
+
// Execute task if one was found
|
236
|
+
if (result.rows.length > 0) {
|
237
|
+
await this.execute(result.rows[0] as PartialTask, tx);
|
238
|
+
executed = true;
|
239
|
+
}
|
240
|
+
});
|
241
|
+
} catch (err) {
|
242
|
+
console.error('Failed polling for tasks:', err);
|
243
|
+
} finally {
|
244
|
+
if (!executed) {
|
245
|
+
await setTimeout(this.interval);
|
246
|
+
}
|
247
|
+
this.poll();
|
248
|
+
}
|
249
|
+
})();
|
250
|
+
}
|
251
|
+
|
252
|
+
// Start listening and polling for tasks
|
253
|
+
public async start(): Promise<void> {
|
254
|
+
// Tasks only support postgres for now
|
255
|
+
if (sbvrUtils.db.engine !== 'postgres' || sbvrUtils.db.on == null) {
|
256
|
+
throw new Error(
|
257
|
+
'Database does not support tasks, giving up on starting worker',
|
258
|
+
);
|
259
|
+
}
|
260
|
+
|
261
|
+
// Check for any pending tasks with unknown handlers
|
262
|
+
const tasksWithUnknownHandlers = await this.client.get({
|
263
|
+
resource: 'task',
|
264
|
+
passthrough: {
|
265
|
+
req: permissions.root,
|
266
|
+
},
|
267
|
+
options: {
|
268
|
+
$filter: {
|
269
|
+
status: 'queued',
|
270
|
+
$not: {
|
271
|
+
is_executed_by__handler: { $in: Object.keys(this.handlers) },
|
272
|
+
},
|
273
|
+
},
|
274
|
+
},
|
275
|
+
});
|
276
|
+
if (tasksWithUnknownHandlers.length > 0) {
|
277
|
+
throw new Error(
|
278
|
+
`Found tasks with unknown handlers: ${tasksWithUnknownHandlers
|
279
|
+
.map((task) => `${task.id}(${task.is_executed_by__handler})`)
|
280
|
+
.join(', ')}`,
|
281
|
+
);
|
282
|
+
}
|
283
|
+
|
284
|
+
sbvrUtils.db.on(
|
285
|
+
'notification',
|
286
|
+
async (msg) => {
|
287
|
+
if (this.canExecute()) {
|
288
|
+
await sbvrUtils.db.transaction(async (tx) => {
|
289
|
+
const result = await sbvrUtils.db.executeSql(
|
290
|
+
`SELECT ${selectColumns} FROM task AS t WHERE id = $1 FOR UPDATE SKIP LOCKED`,
|
291
|
+
[msg.payload],
|
292
|
+
);
|
293
|
+
if (result.rows.length > 0) {
|
294
|
+
await this.execute(result.rows[0] as PartialTask, tx);
|
295
|
+
}
|
296
|
+
});
|
297
|
+
}
|
298
|
+
},
|
299
|
+
{
|
300
|
+
channel,
|
301
|
+
},
|
302
|
+
);
|
303
|
+
|
304
|
+
// Spawn children to poll for and execute tasks
|
305
|
+
for (let i = 0; i < this.concurrency; i++) {
|
306
|
+
this.poll();
|
307
|
+
}
|
308
|
+
}
|
309
|
+
}
|