@balena/pinejs 17.2.0-build-joshbwlng-tasks-b246a5244eeb1c020c533c54d6fb2f112a0ed972-1 → 17.2.0-build-select-model-98a9614ef7e5b70c9d4260521f3a6fce6dac0df1-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.
Files changed (59) hide show
  1. package/.pinejs-cache.json +1 -1
  2. package/.versionbot/CHANGELOG.yml +20 -5
  3. package/CHANGELOG.md +7 -2
  4. package/out/bin/abstract-sql-compiler.js +4 -3
  5. package/out/bin/abstract-sql-compiler.js.map +1 -1
  6. package/out/bin/odata-compiler.js +6 -4
  7. package/out/bin/odata-compiler.js.map +1 -1
  8. package/out/bin/utils.d.ts +1 -1
  9. package/out/bin/utils.js +17 -2
  10. package/out/bin/utils.js.map +1 -1
  11. package/out/config-loader/env.d.ts +0 -4
  12. package/out/config-loader/env.js +1 -5
  13. package/out/config-loader/env.js.map +1 -1
  14. package/out/data-server/sbvr-server.d.ts +3 -2
  15. package/out/data-server/sbvr-server.js +347 -384
  16. package/out/data-server/sbvr-server.js.map +1 -1
  17. package/out/database-layer/db.d.ts +0 -3
  18. package/out/database-layer/db.js +0 -17
  19. package/out/database-layer/db.js.map +1 -1
  20. package/out/sbvr-api/sbvr-utils.d.ts +0 -1
  21. package/out/sbvr-api/sbvr-utils.js +1 -3
  22. package/out/sbvr-api/sbvr-utils.js.map +1 -1
  23. package/out/server-glue/module.d.ts +0 -1
  24. package/out/server-glue/module.js +1 -4
  25. package/out/server-glue/module.js.map +1 -1
  26. package/package.json +6 -9
  27. package/src/bin/abstract-sql-compiler.ts +12 -2
  28. package/src/bin/odata-compiler.ts +25 -5
  29. package/src/bin/utils.ts +23 -2
  30. package/src/config-loader/env.ts +1 -6
  31. package/src/data-server/{sbvr-server.js → sbvr-server.ts} +47 -49
  32. package/src/database-layer/db.ts +0 -25
  33. package/src/migrator/migrations.ts +1 -1
  34. package/src/sbvr-api/dev.ts +1 -1
  35. package/src/sbvr-api/sbvr-utils.ts +1 -2
  36. package/src/sbvr-api/user.ts +1 -1
  37. package/src/server-glue/module.ts +0 -3
  38. package/out/tasks/common.d.ts +0 -4
  39. package/out/tasks/common.js +0 -11
  40. package/out/tasks/common.js.map +0 -1
  41. package/out/tasks/index.d.ts +0 -7
  42. package/out/tasks/index.js +0 -160
  43. package/out/tasks/index.js.map +0 -1
  44. package/out/tasks/out.d.ts +0 -40
  45. package/out/tasks/out.js +0 -3
  46. package/out/tasks/out.js.map +0 -1
  47. package/out/tasks/tasks.sbvr +0 -55
  48. package/out/tasks/types.d.ts +0 -40
  49. package/out/tasks/types.js +0 -3
  50. package/out/tasks/types.js.map +0 -1
  51. package/out/tasks/worker.d.ts +0 -32
  52. package/out/tasks/worker.js +0 -204
  53. package/out/tasks/worker.js.map +0 -1
  54. package/src/tasks/common.ts +0 -9
  55. package/src/tasks/index.ts +0 -176
  56. package/src/tasks/out.ts +0 -46
  57. package/src/tasks/tasks.sbvr +0 -55
  58. package/src/tasks/types.ts +0 -44
  59. package/src/tasks/worker.ts +0 -282
@@ -1,44 +0,0 @@
1
- // These types were generated by @balena/abstract-sql-to-typescript v3.2.1
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
- }
@@ -1,282 +0,0 @@
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 './types';
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
- })
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
- if (handler == null) {
80
- await this.update(
81
- tx,
82
- task,
83
- startedOnTime,
84
- 'failed',
85
- 'Matching task handler not found',
86
- );
87
- return;
88
- }
89
-
90
- // Validate parameters before execution so we can fail early if
91
- // the parameter set is invalid. This can happen if the handler
92
- // definition changes after a task is added to the queue.
93
- if (
94
- handler.validate != null &&
95
- !handler.validate(task.is_executed_with__parameter_set)
96
- ) {
97
- await this.update(
98
- tx,
99
- task,
100
- startedOnTime,
101
- 'failed',
102
- `Invalid parameter set: ${ajv.errorsText(handler.validate.errors)}`,
103
- );
104
- return;
105
- }
106
-
107
- // Execute handler and update task with results
108
- let status: Task['Read']['status'] = 'queued';
109
- let error: string | undefined;
110
- try {
111
- const results = await handler.fn({
112
- api: new PinejsClient({}),
113
- params: task.is_executed_with__parameter_set ?? {},
114
- });
115
- status = results.status;
116
- error = results.error;
117
- } finally {
118
- await this.update(tx, task, startedOnTime, status, error);
119
- }
120
- } catch (err) {
121
- // This shouldn't happen, but if it does we want to log and kill the process
122
- console.error(
123
- `Failed to execute task ${task.id} with handler ${task.is_executed_by__handler}:`,
124
- err,
125
- );
126
- process.exit(1);
127
- } finally {
128
- this.executing--;
129
- }
130
- }
131
-
132
- // Update task and schedule next attempt if needed
133
- private async update(
134
- tx: Db.Tx,
135
- task: PartialTask,
136
- startedOnTime: Date,
137
- status: Task['Read']['status'],
138
- errorMessage?: string,
139
- ): Promise<void> {
140
- const attemptCount = task.attempt_count + 1;
141
- const body: AnyObject = {
142
- started_on__time: startedOnTime,
143
- ended_on__time: new Date(),
144
- status,
145
- attempt_count: attemptCount,
146
- ...(errorMessage != null && { error_message: errorMessage }),
147
- };
148
-
149
- // Re-enqueue if the task failed but has retries left, remember that
150
- // attemptCount includes the initial attempt while attempt_limit does not
151
- if (status === 'failed' && attemptCount < task.attempt_limit) {
152
- body.status = 'queued';
153
-
154
- // Schedule next attempt using exponential backoff
155
- body.is_scheduled_to_execute_on__time =
156
- this.getNextAttemptTime(attemptCount);
157
- }
158
-
159
- // Patch current task
160
- await this.client.patch({
161
- resource: 'task',
162
- passthrough: {
163
- tx,
164
- req: permissions.root,
165
- },
166
- id: task.id,
167
- body,
168
- });
169
-
170
- // Create new task with same configuration if previous
171
- // iteration completed and has a cron expression
172
- if (
173
- ['failed', 'succeeded'].includes(body.status) &&
174
- task.is_scheduled_with__cron_expression != null
175
- ) {
176
- await this.client.post({
177
- resource: 'task',
178
- passthrough: {
179
- tx,
180
- req: permissions.root,
181
- },
182
- options: {
183
- returnResource: false,
184
- },
185
- body: {
186
- attempt_limit: task.attempt_limit,
187
- is_created_by__actor: task.is_created_by__actor,
188
- is_executed_by__handler: task.is_executed_by__handler,
189
- is_executed_with__parameter_set: task.is_executed_with__parameter_set,
190
- is_scheduled_with__cron_expression:
191
- task.is_scheduled_with__cron_expression,
192
- },
193
- });
194
- }
195
- }
196
-
197
- // Calculate next attempt time using exponential backoff
198
- private getNextAttemptTime(attempt: number): Date | null {
199
- const delay = Math.ceil(Math.exp(Math.min(10, attempt)));
200
- return new Date(Date.now() + delay);
201
- }
202
-
203
- // Poll for tasks and execute them
204
- // This is recursive and is spawned once per concurrency limit
205
- private poll(): void {
206
- let executed = false;
207
- void (async () => {
208
- try {
209
- if (!this.canExecute()) {
210
- return;
211
- }
212
- const handlerNames = Object.keys(this.handlers);
213
- await sbvrUtils.db.transaction(async (tx) => {
214
- const result = await sbvrUtils.db.executeSql(
215
- `SELECT ${selectColumns}
216
- FROM task AS t
217
- WHERE
218
- t."is executed by-handler" IN (${handlerNames.map((_, index) => `$${index + 1}`).join(', ')}) AND
219
- t."status" = 'queued' AND
220
- t."attempt count" <= t."attempt limit" AND
221
- (
222
- t."is scheduled to execute on-time" IS NULL OR
223
- t."is scheduled to execute on-time" <= CURRENT_TIMESTAMP + $${handlerNames.length + 1} * INTERVAL '1 SECOND'
224
- )
225
- ORDER BY
226
- t."is scheduled to execute on-time" ASC,
227
- t."id" ASC
228
- LIMIT 1 FOR UPDATE SKIP LOCKED`,
229
- [...handlerNames, Math.ceil(this.interval / 1000)],
230
- );
231
-
232
- // Execute task if one was found
233
- if (result.rows.length > 0) {
234
- await this.execute(result.rows[0] as PartialTask, tx);
235
- executed = true;
236
- }
237
- });
238
- } catch (err) {
239
- console.error('Failed polling for tasks:', err);
240
- } finally {
241
- if (!executed) {
242
- await setTimeout(this.interval);
243
- }
244
- this.poll();
245
- }
246
- })();
247
- }
248
-
249
- // Start listening and polling for tasks
250
- public start(): void {
251
- // Tasks only support postgres for now
252
- if (sbvrUtils.db.engine !== 'postgres' || sbvrUtils.db.on == null) {
253
- throw new Error(
254
- 'Database does not support tasks, giving up on starting worker',
255
- );
256
- }
257
- sbvrUtils.db.on(
258
- 'notification',
259
- async (msg) => {
260
- if (this.canExecute()) {
261
- await sbvrUtils.db.transaction(async (tx) => {
262
- const result = await sbvrUtils.db.executeSql(
263
- `SELECT ${selectColumns} FROM task AS t WHERE id = $1 FOR UPDATE SKIP LOCKED`,
264
- [msg.payload],
265
- );
266
- if (result.rows.length > 0) {
267
- await this.execute(result.rows[0] as PartialTask, tx);
268
- }
269
- });
270
- }
271
- },
272
- {
273
- channel,
274
- },
275
- );
276
-
277
- // Spawn children to poll for and execute tasks
278
- for (let i = 0; i < this.concurrency; i++) {
279
- this.poll();
280
- }
281
- }
282
- }