@balena/pinejs 17.1.0-build-joshbwlng-tasks-0c116dc98102e3ddd4aa6e8a4f350a1e18891e1a-1 → 17.1.0-build-model-based-typings-437bb06f44567532aec78e550f3d545732466411-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 (64) hide show
  1. package/.pinejs-cache.json +1 -1
  2. package/.versionbot/CHANGELOG.yml +242 -4
  3. package/CHANGELOG.md +70 -1
  4. package/out/config-loader/env.d.ts +0 -4
  5. package/out/config-loader/env.js +1 -5
  6. package/out/config-loader/env.js.map +1 -1
  7. package/out/data-server/sbvr-server.js +3 -2
  8. package/out/data-server/sbvr-server.js.map +1 -1
  9. package/out/database-layer/db.d.ts +0 -3
  10. package/out/database-layer/db.js +0 -17
  11. package/out/database-layer/db.js.map +1 -1
  12. package/out/migrator/migrations.d.ts +58 -0
  13. package/out/migrator/migrations.js +3 -0
  14. package/out/migrator/migrations.js.map +1 -0
  15. package/out/migrator/sync.d.ts +17 -0
  16. package/out/migrator/sync.js +39 -40
  17. package/out/migrator/sync.js.map +1 -1
  18. package/out/sbvr-api/dev.d.ts +22 -0
  19. package/out/sbvr-api/dev.js +3 -0
  20. package/out/sbvr-api/dev.js.map +1 -0
  21. package/out/sbvr-api/hooks.d.ts +26 -26
  22. package/out/sbvr-api/hooks.js.map +1 -1
  23. package/out/sbvr-api/permissions.d.ts +26 -2
  24. package/out/sbvr-api/permissions.js +39 -40
  25. package/out/sbvr-api/permissions.js.map +1 -1
  26. package/out/sbvr-api/sbvr-utils.d.ts +46 -6
  27. package/out/sbvr-api/sbvr-utils.js +44 -44
  28. package/out/sbvr-api/sbvr-utils.js.map +1 -1
  29. package/out/sbvr-api/user.d.ts +236 -0
  30. package/out/sbvr-api/user.js +3 -0
  31. package/out/sbvr-api/user.js.map +1 -0
  32. package/out/server-glue/module.d.ts +0 -1
  33. package/out/server-glue/module.js +1 -4
  34. package/out/server-glue/module.js.map +1 -1
  35. package/package.json +19 -20
  36. package/src/config-loader/env.ts +1 -6
  37. package/src/data-server/sbvr-server.js +3 -2
  38. package/src/database-layer/db.ts +0 -25
  39. package/src/migrator/migrations.ts +64 -0
  40. package/src/migrator/sync.ts +46 -41
  41. package/src/sbvr-api/dev.ts +26 -0
  42. package/src/sbvr-api/hooks.ts +21 -18
  43. package/src/sbvr-api/permissions.ts +54 -48
  44. package/src/sbvr-api/sbvr-utils.ts +93 -53
  45. package/src/sbvr-api/user.ts +216 -0
  46. package/src/server-glue/module.ts +0 -3
  47. package/out/tasks/common.d.ts +0 -4
  48. package/out/tasks/common.js +0 -13
  49. package/out/tasks/common.js.map +0 -1
  50. package/out/tasks/index.d.ts +0 -8
  51. package/out/tasks/index.js +0 -142
  52. package/out/tasks/index.js.map +0 -1
  53. package/out/tasks/tasks.sbvr +0 -60
  54. package/out/tasks/types.d.ts +0 -38
  55. package/out/tasks/types.js +0 -10
  56. package/out/tasks/types.js.map +0 -1
  57. package/out/tasks/worker.d.ts +0 -16
  58. package/out/tasks/worker.js +0 -228
  59. package/out/tasks/worker.js.map +0 -1
  60. package/src/tasks/common.ts +0 -14
  61. package/src/tasks/index.ts +0 -158
  62. package/src/tasks/tasks.sbvr +0 -60
  63. package/src/tasks/types.ts +0 -58
  64. package/src/tasks/worker.ts +0 -278
@@ -1,278 +0,0 @@
1
- import { setTimeout } from 'node:timers/promises';
2
- import type { AnyObject } from 'pinejs-client-core';
3
- import { tasks as tasksEnv } from '../config-loader/env';
4
- import type * as Db from '../database-layer/db';
5
- import { TransactionClosedError } 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 { PartialTask, TaskHandler, TaskStatus } from './types';
11
-
12
- // Map of column names with SBVR names used in SELECT queries
13
- const selectColumns = Object.entries({
14
- id: 'id',
15
- 'is executed by-handler': 'is_executed_by__handler',
16
- 'is executed with-parameter set': 'is_executed_with__parameter_set',
17
- 'is scheduled with-cron expression': 'is_scheduled_with__cron_expression',
18
- 'attempt count': 'attempt_count',
19
- 'attempt limit': 'attempt_limit',
20
- priority: 'priority',
21
- 'is created by-actor': 'is_created_by__actor',
22
- })
23
- .map(([key, value]) => `t."${key}" AS "${value}"`)
24
- .join(', ');
25
-
26
- // The worker is responsible for executing tasks in the queue. It listens for
27
- // notifications and polls the database for tasks to execute. It will execute
28
- // tasks in parallel up to a certain concurrency limit.
29
- export class Worker {
30
- public handlers: Record<string, TaskHandler> = {};
31
- private readonly concurrency: number;
32
- private readonly interval: number;
33
- private executing = 0;
34
-
35
- constructor(private readonly client: PinejsClient) {
36
- this.concurrency = tasksEnv.queueConcurrency;
37
- this.interval = tasksEnv.queueIntervalMS;
38
- }
39
-
40
- // Check if instance can execute more tasks
41
- private canExecute(): boolean {
42
- return (
43
- this.executing < this.concurrency && Object.keys(this.handlers).length > 0
44
- );
45
- }
46
-
47
- private async execute(task: PartialTask, tx: Db.Tx): Promise<void> {
48
- this.executing++;
49
- try {
50
- // Get specified handler
51
- const handler = this.handlers[task.is_executed_by__handler];
52
- const startedOnTime = new Date();
53
- if (handler == null) {
54
- await this.finalize(
55
- tx,
56
- task,
57
- startedOnTime,
58
- 'failed',
59
- 'Matching task handler not found',
60
- );
61
- return;
62
- }
63
-
64
- // Validate parameters before execution so we can fail early if
65
- // the parameter set is invalid. This can happen if the handler
66
- // definition changes after a task is added to the queue.
67
- if (
68
- handler.validate != null &&
69
- !handler.validate(task.is_executed_with__parameter_set)
70
- ) {
71
- await this.finalize(
72
- tx,
73
- task,
74
- startedOnTime,
75
- 'failed',
76
- `Invalid parameter set: ${ajv.errorsText(handler.validate.errors)}`,
77
- );
78
- return;
79
- }
80
-
81
- // Execute handler
82
- let status: TaskStatus = 'queued';
83
- let error: string | undefined;
84
- try {
85
- await sbvrUtils.db.transaction(async (handlerTx) => {
86
- const results = await handler.fn({
87
- api: new PinejsClient({
88
- passthrough: {
89
- tx: handlerTx,
90
- },
91
- }),
92
- params: task.is_executed_with__parameter_set ?? {},
93
- tx: handlerTx,
94
- });
95
- status = results.status;
96
- error = results.error;
97
- if (results.status !== 'succeeded' && !handlerTx.isClosed()) {
98
- await handlerTx.rollback();
99
- }
100
- });
101
- } catch (err) {
102
- // Ignore closed/rollback errors
103
- if (!(err instanceof TransactionClosedError)) {
104
- throw err;
105
- }
106
- } finally {
107
- // Update task with results
108
- await this.finalize(tx, task, startedOnTime, status, error);
109
- }
110
- } catch (err) {
111
- // This shouldn't happen, but if it does we want to log and kill the process
112
- console.error(
113
- `Failed to execute task ${task.id} with handler ${task.is_executed_by__handler}:`,
114
- err,
115
- );
116
- process.exit(1);
117
- } finally {
118
- this.executing--;
119
- }
120
- }
121
-
122
- // Update task and schedule next attempt if needed
123
- private async finalize(
124
- tx: Db.Tx,
125
- task: PartialTask,
126
- startedOnTime: Date,
127
- status: TaskStatus,
128
- errorMessage?: string,
129
- ): Promise<void> {
130
- const attemptCount = task.attempt_count + 1;
131
- const body: AnyObject = {
132
- started_on__time: startedOnTime,
133
- ended_on__time: new Date(),
134
- status,
135
- attempt_count: attemptCount,
136
- ...(errorMessage != null && { error_message: errorMessage }),
137
- };
138
-
139
- // Re-enqueue if the task failed but has retries left, remember that
140
- // attemptCount includes the initial attempt while attempt_limit does not
141
- if (status === 'failed' && attemptCount < task.attempt_limit) {
142
- body.status = 'queued';
143
-
144
- // Schedule next attempt using exponential backoff
145
- body.is_scheduled_to_execute_on__time =
146
- this.getNextAttemptTime(attemptCount);
147
- }
148
-
149
- // Patch current task
150
- await this.client.patch({
151
- resource: 'task',
152
- passthrough: {
153
- tx,
154
- req: permissions.root,
155
- },
156
- id: task.id,
157
- body,
158
- });
159
-
160
- // Create new task with same configuration if previous
161
- // iteration completed and has a cron expression
162
- if (
163
- ['failed', 'succeeded'].includes(body.status) &&
164
- task.is_scheduled_with__cron_expression != null
165
- ) {
166
- await this.client.post({
167
- resource: 'task',
168
- passthrough: {
169
- tx,
170
- req: permissions.root,
171
- },
172
- options: {
173
- returnResource: false,
174
- },
175
- body: {
176
- attempt_limit: task.attempt_limit,
177
- is_created_by__actor: task.is_created_by__actor,
178
- is_executed_by__handler: task.is_executed_by__handler,
179
- is_executed_with__parameter_set: task.is_executed_with__parameter_set,
180
- is_scheduled_with__cron_expression:
181
- task.is_scheduled_with__cron_expression,
182
- priority: task.priority,
183
- },
184
- });
185
- }
186
- }
187
-
188
- // Calculate next attempt time using exponential backoff
189
- private getNextAttemptTime(attempt: number): Date | null {
190
- const delay = Math.ceil(Math.exp(Math.min(10, attempt)));
191
- return new Date(Date.now() + delay);
192
- }
193
-
194
- // Poll for tasks to execute
195
- private poll(): void {
196
- let executed = false;
197
- void (async () => {
198
- try {
199
- const handlerNames = Object.keys(this.handlers);
200
- const binds = handlerNames
201
- .map((_, index) => `$${index + 1}`)
202
- .join(', ');
203
- if (!this.canExecute()) {
204
- return;
205
- }
206
- await sbvrUtils.db.transaction(async (tx) => {
207
- const result = await tx.executeSql(
208
- `SELECT ${selectColumns}
209
- FROM task AS t
210
- WHERE
211
- t."is executed by-handler" IN (${binds}) AND
212
- t."status" = 'queued' AND
213
- t."attempt count" <= t."attempt limit" AND
214
- (
215
- t."is scheduled to execute on-time" IS NULL OR
216
- t."is scheduled to execute on-time" <= CURRENT_TIMESTAMP + INTERVAL '${Math.ceil(this.interval / 1000)} second'
217
- )
218
- ORDER BY
219
- t."is scheduled to execute on-time" ASC,
220
- t."priority" DESC,
221
- t."id" ASC
222
- LIMIT ${Math.max(this.concurrency - this.executing, 0)}
223
- FOR UPDATE SKIP LOCKED`,
224
- handlerNames,
225
- );
226
- if (result.rows.length === 0) {
227
- return;
228
- }
229
-
230
- // Tasks found, execute them in parallel
231
- await Promise.all(
232
- result.rows.map(async (row) => {
233
- await this.execute(row as PartialTask, tx);
234
- }),
235
- );
236
- executed = true;
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 tx.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
- this.poll();
277
- }
278
- }