@balena/pinejs 18.0.0 → 18.1.0-build-joshbwlng-tasks-671c1667086b4af10d82d4c08df482c8b0a83384-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 +13 -1
- package/CHANGELOG.md +5 -0
- 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 -0
- package/out/database-layer/db.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 +7 -4
- package/src/config-loader/env.ts +6 -1
- package/src/database-layer/db.ts +30 -0
- package/src/sbvr-api/sbvr-utils.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 +310 -0
@@ -0,0 +1,310 @@
|
|
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
|
+
// @ts-expect-error Need to add support for big integers
|
169
|
+
id: task.id,
|
170
|
+
body,
|
171
|
+
});
|
172
|
+
|
173
|
+
// Create new task with same configuration if previous
|
174
|
+
// iteration completed and has a cron expression
|
175
|
+
if (
|
176
|
+
body.status != null &&
|
177
|
+
['failed', 'succeeded'].includes(body.status) &&
|
178
|
+
task.is_scheduled_with__cron_expression != null
|
179
|
+
) {
|
180
|
+
await this.client.post({
|
181
|
+
resource: 'task',
|
182
|
+
passthrough: {
|
183
|
+
tx,
|
184
|
+
req: permissions.root,
|
185
|
+
},
|
186
|
+
options: {
|
187
|
+
returnResource: false,
|
188
|
+
},
|
189
|
+
body: {
|
190
|
+
attempt_limit: task.attempt_limit,
|
191
|
+
is_created_by__actor: task.is_created_by__actor,
|
192
|
+
is_executed_by__handler: task.is_executed_by__handler,
|
193
|
+
is_executed_with__parameter_set: task.is_executed_with__parameter_set,
|
194
|
+
is_scheduled_with__cron_expression:
|
195
|
+
task.is_scheduled_with__cron_expression,
|
196
|
+
},
|
197
|
+
});
|
198
|
+
}
|
199
|
+
}
|
200
|
+
|
201
|
+
// Calculate next attempt time using exponential backoff
|
202
|
+
private getNextAttemptTime(attempt: number): Date | null {
|
203
|
+
const delay = Math.ceil(Math.exp(Math.min(10, attempt)));
|
204
|
+
return new Date(Date.now() + delay);
|
205
|
+
}
|
206
|
+
|
207
|
+
// Poll for tasks and execute them
|
208
|
+
// This is recursive and is spawned once per concurrency limit
|
209
|
+
private poll(): void {
|
210
|
+
let executed = false;
|
211
|
+
void (async () => {
|
212
|
+
try {
|
213
|
+
if (!this.canExecute()) {
|
214
|
+
return;
|
215
|
+
}
|
216
|
+
const handlerNames = Object.keys(this.handlers);
|
217
|
+
await sbvrUtils.db.transaction(async (tx) => {
|
218
|
+
const result = await sbvrUtils.db.executeSql(
|
219
|
+
`SELECT ${selectColumns}
|
220
|
+
FROM task AS t
|
221
|
+
WHERE
|
222
|
+
t."is executed by-handler" IN (${handlerNames.map((_, index) => `$${index + 1}`).join(', ')}) AND
|
223
|
+
t."status" = 'queued' AND
|
224
|
+
t."attempt count" <= t."attempt limit" AND
|
225
|
+
(
|
226
|
+
t."is scheduled to execute on-time" IS NULL OR
|
227
|
+
t."is scheduled to execute on-time" <= CURRENT_TIMESTAMP + $${handlerNames.length + 1} * INTERVAL '1 SECOND'
|
228
|
+
)
|
229
|
+
ORDER BY
|
230
|
+
t."is scheduled to execute on-time" ASC,
|
231
|
+
t."id" ASC
|
232
|
+
LIMIT 1 FOR UPDATE SKIP LOCKED`,
|
233
|
+
[...handlerNames, Math.ceil(this.interval / 1000)],
|
234
|
+
);
|
235
|
+
|
236
|
+
// Execute task if one was found
|
237
|
+
if (result.rows.length > 0) {
|
238
|
+
await this.execute(result.rows[0] as PartialTask, tx);
|
239
|
+
executed = true;
|
240
|
+
}
|
241
|
+
});
|
242
|
+
} catch (err) {
|
243
|
+
console.error('Failed polling for tasks:', err);
|
244
|
+
} finally {
|
245
|
+
if (!executed) {
|
246
|
+
await setTimeout(this.interval);
|
247
|
+
}
|
248
|
+
this.poll();
|
249
|
+
}
|
250
|
+
})();
|
251
|
+
}
|
252
|
+
|
253
|
+
// Start listening and polling for tasks
|
254
|
+
public async start(): Promise<void> {
|
255
|
+
// Tasks only support postgres for now
|
256
|
+
if (sbvrUtils.db.engine !== 'postgres' || sbvrUtils.db.on == null) {
|
257
|
+
throw new Error(
|
258
|
+
'Database does not support tasks, giving up on starting worker',
|
259
|
+
);
|
260
|
+
}
|
261
|
+
|
262
|
+
// Check for any pending tasks with unknown handlers
|
263
|
+
const tasksWithUnknownHandlers = await this.client.get({
|
264
|
+
resource: 'task',
|
265
|
+
passthrough: {
|
266
|
+
req: permissions.root,
|
267
|
+
},
|
268
|
+
options: {
|
269
|
+
$filter: {
|
270
|
+
status: 'queued',
|
271
|
+
$not: {
|
272
|
+
is_executed_by__handler: { $in: Object.keys(this.handlers) },
|
273
|
+
},
|
274
|
+
},
|
275
|
+
},
|
276
|
+
});
|
277
|
+
if (tasksWithUnknownHandlers.length > 0) {
|
278
|
+
throw new Error(
|
279
|
+
`Found tasks with unknown handlers: ${tasksWithUnknownHandlers
|
280
|
+
.map((task) => `${task.id}(${task.is_executed_by__handler})`)
|
281
|
+
.join(', ')}`,
|
282
|
+
);
|
283
|
+
}
|
284
|
+
|
285
|
+
sbvrUtils.db.on(
|
286
|
+
'notification',
|
287
|
+
async (msg) => {
|
288
|
+
if (this.canExecute()) {
|
289
|
+
await sbvrUtils.db.transaction(async (tx) => {
|
290
|
+
const result = await sbvrUtils.db.executeSql(
|
291
|
+
`SELECT ${selectColumns} FROM task AS t WHERE id = $1 FOR UPDATE SKIP LOCKED`,
|
292
|
+
[msg.payload],
|
293
|
+
);
|
294
|
+
if (result.rows.length > 0) {
|
295
|
+
await this.execute(result.rows[0] as PartialTask, tx);
|
296
|
+
}
|
297
|
+
});
|
298
|
+
}
|
299
|
+
},
|
300
|
+
{
|
301
|
+
channel,
|
302
|
+
},
|
303
|
+
);
|
304
|
+
|
305
|
+
// Spawn children to poll for and execute tasks
|
306
|
+
for (let i = 0; i < this.concurrency; i++) {
|
307
|
+
this.poll();
|
308
|
+
}
|
309
|
+
}
|
310
|
+
}
|