@balena/pinejs 18.1.0-build-joshbwlng-listener-0b0f8758d06970eeb1cc188b8a5e3301897ba8ab-1 → 18.1.0-build-joshbwlng-tasks-549a839468147b5001ee42e5124cce89b03b9c81-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.
@@ -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,289 @@
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 } 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.
53
+ // It 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 polling for tasks
253
+ public async start(): Promise<void> {
254
+ // Tasks only support postgres for now
255
+ if (sbvrUtils.db.engine !== 'postgres') {
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
+ // Spawn children to poll for and execute tasks
285
+ for (let i = 0; i < this.concurrency; i++) {
286
+ this.poll();
287
+ }
288
+ }
289
+ }