@keetanetwork/anchor 0.0.109 → 0.0.111

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.
@@ -1,6 +1,36 @@
1
- import type { KeetaAnchorQueueStorageDriver, KeetaAnchorQueueStorageDriverConstructor, KeetaAnchorQueueRequest, KeetaAnchorQueueRequestID, KeetaAnchorQueueEntry, KeetaAnchorQueueEntryExtra, KeetaAnchorQueueEntryAncillaryData, KeetaAnchorQueueStatus, KeetaAnchorQueueFilter, KeetaAnchorQueueDeleteInput } from '../index.ts';
1
+ import type { KeetaAnchorQueueStorageDriver, KeetaAnchorQueueStorageDriverConstructor, KeetaAnchorQueueRequest, KeetaAnchorQueueRequestID, KeetaAnchorQueueEntry, KeetaAnchorQueueEntryExtra, KeetaAnchorQueueEntryAncillaryData, KeetaAnchorQueueStatus, KeetaAnchorQueueFilter, KeetaAnchorQueueDeleteInput, KeetaAnchorQueueWorkerID } from '../index.ts';
2
2
  import type { JSONSerializable } from '../../utils/json.js';
3
3
  import type * as pg from 'pg';
4
+ /**
5
+ * How often Postgres vacuums the queue's entries table.
6
+ *
7
+ * Every status change is an update to a column the queue's indexes are
8
+ * keyed on, so it leaves a dead index entry at the oldest end of the
9
+ * status range the entry left. That is exactly where the next query()
10
+ * starts reading, so until a vacuum cleans the index each pick reads
11
+ * past every entry processed since the last vacuum.
12
+ */
13
+ export type KeetaAnchorQueueStorageDriverPostgresVacuumPolicy = {
14
+ /**
15
+ * Number of updated or deleted rows that triggers an autovacuum of
16
+ * the entries table (autovacuum_vacuum_threshold)
17
+ */
18
+ vacuumThreshold: number;
19
+ /**
20
+ * Fraction of the table added to `vacuumThreshold`
21
+ * (autovacuum_vacuum_scale_factor). A pick slows with the number of
22
+ * dead entries ahead of it, but each vacuum reads every index in
23
+ * full, so its cost grows with the table. A small fraction lets a
24
+ * large table vacuum less often, so it does not vacuum almost
25
+ * constantly.
26
+ */
27
+ vacuumScaleFactor: number;
28
+ /**
29
+ * Fraction of the table changed that triggers an automatic ANALYZE
30
+ * (autovacuum_analyze_scale_factor)
31
+ */
32
+ analyzeScaleFactor: number;
33
+ };
4
34
  type KeetaAnchorQueueStorageDriverPostgresOptions = {
5
35
  /**
6
36
  * Function that returns a Postgres connection pool.
@@ -12,6 +42,13 @@ type KeetaAnchorQueueStorageDriverPostgresOptions = {
12
42
  * and `queue_schema_version`.
13
43
  */
14
44
  tablePrefix?: string | undefined;
45
+ /**
46
+ * Vacuum settings for the entries table, applied each time the
47
+ * driver initializes. Any value left out uses the default
48
+ * ({@link DefaultVacuumPolicy}). Pass `false` to leave the table's
49
+ * vacuum settings alone, for example when an operator manages them.
50
+ */
51
+ vacuumPolicy?: Partial<KeetaAnchorQueueStorageDriverPostgresVacuumPolicy> | false;
15
52
  };
16
53
  export default class KeetaAnchorQueueStorageDriverPostgres<QueueRequest extends JSONSerializable = JSONSerializable, QueueResult extends JSONSerializable = JSONSerializable> implements KeetaAnchorQueueStorageDriver<QueueRequest, QueueResult> {
17
54
  private readonly logger;
@@ -28,15 +65,51 @@ export default class KeetaAnchorQueueStorageDriverPostgres<QueueRequest extends
28
65
  readonly path: string[];
29
66
  private readonly pathStr;
30
67
  private toctouDelay;
68
+ private readonly vacuumPolicy;
69
+ private readonly vacuumStorageParameters;
31
70
  constructor(options: NonNullable<ConstructorParameters<KeetaAnchorQueueStorageDriverConstructor<QueueRequest, QueueResult>>[0]> & KeetaAnchorQueueStorageDriverPostgresOptions);
32
71
  private initializeDBConnection;
72
+ /**
73
+ * Set the entries table's vacuum storage parameters to the
74
+ * configured policy. This runs on every initialization rather than
75
+ * as a versioned migration, so an upgraded database gets the
76
+ * settings and a changed policy takes effect. The table is only
77
+ * altered when its settings differ.
78
+ *
79
+ * Changing storage parameters requires owning the table. Without
80
+ * that privilege the queue still works, only more slowly while a
81
+ * large backlog drains, so a warning is logged and startup goes on.
82
+ */
83
+ private applyVacuumPolicy;
33
84
  private methodLogger;
34
85
  private runWithRetry;
35
86
  private newDBConnection;
36
87
  private dbTransaction;
37
88
  add(request: KeetaAnchorQueueRequest<QueueRequest>, info?: KeetaAnchorQueueEntryExtra): Promise<KeetaAnchorQueueRequestID>;
38
89
  setStatus(id: KeetaAnchorQueueRequestID, status: KeetaAnchorQueueStatus, ancillary?: KeetaAnchorQueueEntryAncillaryData<QueueResult>): Promise<void>;
90
+ /**
91
+ * Write a status change to an entry whose current values the
92
+ * caller has read (and locked), so every status change goes through
93
+ * {@link ManageStatusUpdates}. With `oldStatus` the UPDATE also
94
+ * requires the entry to still be in that status.
95
+ */
96
+ private writeStatusUpdate;
39
97
  get(id: KeetaAnchorQueueRequestID): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null>;
98
+ /**
99
+ * Turn an entries row into a queue entry, with its idempotent keys
100
+ */
101
+ private decodeEntryRow;
102
+ /**
103
+ * Move the oldest entry in a status to "processing" for a worker.
104
+ *
105
+ * SKIP LOCKED makes concurrent claims lock different rows.
106
+ * Postgres locks rows below the LIMIT, so a row that left the status
107
+ * after the statement started is re-checked and passed over, and
108
+ * the scan moves on to the next one. The row stays locked until
109
+ * the transaction commits, so the UPDATE cannot lose it. The entry
110
+ * is returned as it was before the claim.
111
+ */
112
+ claimNext(status: KeetaAnchorQueueStatus, worker: KeetaAnchorQueueWorkerID): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null>;
40
113
  /**
41
114
  * Build the SQL for {@link query}, ordered as the storage driver
42
115
  * contract requires (oldest updated first, ties by id) so that the
@@ -1 +1 @@
1
- {"version":3,"file":"queue_postgres.d.ts","sourceRoot":"","sources":["../../../../src/lib/queue/drivers/queue_postgres.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACX,6BAA6B,EAC7B,wCAAwC,EACxC,uBAAuB,EACvB,yBAAyB,EACzB,qBAAqB,EACrB,0BAA0B,EAC1B,kCAAkC,EAClC,sBAAsB,EACtB,sBAAsB,EACtB,2BAA2B,EAE3B,MAAM,aAAa,CAAC;AAWrB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C,MAAM,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;CAkD5C"}
@@ -1,6 +1,47 @@
1
1
  import { MethodLogger, ManageStatusUpdates, ConvertStringToRequestID } from '../internal.js';
2
2
  import { Errors } from '../common.js';
3
3
  import { asleep } from '../../utils/asleep.js';
4
+ const DefaultVacuumPolicy = {
5
+ vacuumThreshold: 10_000,
6
+ vacuumScaleFactor: 0.001,
7
+ analyzeScaleFactor: 0.02
8
+ };
9
+ /**
10
+ * Postgres accepts scale factors from 0 to 100
11
+ */
12
+ const MaxScaleFactor = 100;
13
+ /**
14
+ * The SQLSTATE Postgres returns when the role does not own the table
15
+ */
16
+ const InsufficientPrivilegeSQLState = '42501';
17
+ /**
18
+ * Check the vacuum policy and build the table storage parameters for it.
19
+ * The values are written into the ALTER TABLE statement (storage
20
+ * parameters cannot be bound), so each one must be a finite number in
21
+ * the range Postgres accepts.
22
+ */
23
+ function VacuumPolicyStorageParameters(policy) {
24
+ if (!Number.isSafeInteger(policy.vacuumThreshold) || policy.vacuumThreshold < 0) {
25
+ throw (new Error(`Invalid vacuumThreshold ${String(policy.vacuumThreshold)}: must be a non-negative integer`));
26
+ }
27
+ for (const [name, value] of [['vacuumScaleFactor', policy.vacuumScaleFactor], ['analyzeScaleFactor', policy.analyzeScaleFactor]]) {
28
+ if (!Number.isFinite(value) || value < 0 || value > MaxScaleFactor) {
29
+ throw (new Error(`Invalid ${name} ${String(value)}: must be a number from 0 to ${MaxScaleFactor}`));
30
+ }
31
+ }
32
+ return ({
33
+ /*
34
+ * Without this, a vacuum skips cleaning the indexes when
35
+ * fewer than about 2% of the table's pages hold dead rows,
36
+ * which is always the case for a drained range of a large
37
+ * queue, and the dead index entries the pick reads past stay
38
+ */
39
+ vacuum_index_cleanup: 'on',
40
+ autovacuum_vacuum_threshold: String(policy.vacuumThreshold),
41
+ autovacuum_vacuum_scale_factor: String(policy.vacuumScaleFactor),
42
+ autovacuum_analyze_scale_factor: String(policy.analyzeScaleFactor)
43
+ });
44
+ }
4
45
  export default class KeetaAnchorQueueStorageDriverPostgres {
5
46
  logger;
6
47
  poolInternal = null;
@@ -16,11 +57,18 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
16
57
  path = [];
17
58
  pathStr;
18
59
  toctouDelay = undefined;
60
+ vacuumPolicy;
61
+ vacuumStorageParameters;
19
62
  constructor(options) {
20
63
  this.id = options?.id ?? crypto.randomUUID();
21
64
  this.logger = options?.logger;
22
65
  this.tablePrefix = options?.tablePrefix;
23
66
  this.poolInternal = options.pool;
67
+ this.vacuumPolicy = options.vacuumPolicy ?? {};
68
+ this.vacuumStorageParameters = null;
69
+ if (this.vacuumPolicy !== false) {
70
+ this.vacuumStorageParameters = VacuumPolicyStorageParameters({ ...DefaultVacuumPolicy, ...this.vacuumPolicy });
71
+ }
24
72
  this.path = options.path ?? [];
25
73
  this.pathStr = ['root', ...this.path].join('.');
26
74
  Object.freeze(this.path);
@@ -158,6 +206,7 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
158
206
  }
159
207
  }
160
208
  logger?.debug('Schema is up to date');
209
+ await this.applyVacuumPolicy(client);
161
210
  }
162
211
  finally {
163
212
  // Always release the advisory lock
@@ -182,6 +231,52 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
182
231
  await this.dbInitializationPromise;
183
232
  return (pool);
184
233
  }
234
+ /**
235
+ * Set the entries table's vacuum storage parameters to the
236
+ * configured policy. This runs on every initialization rather than
237
+ * as a versioned migration, so an upgraded database gets the
238
+ * settings and a changed policy takes effect. The table is only
239
+ * altered when its settings differ.
240
+ *
241
+ * Changing storage parameters requires owning the table. Without
242
+ * that privilege the queue still works, only more slowly while a
243
+ * large backlog drains, so a warning is logged and startup goes on.
244
+ */
245
+ async applyVacuumPolicy(client) {
246
+ const logger = this.methodLogger('applyVacuumPolicy');
247
+ const wanted = this.vacuumStorageParameters;
248
+ if (wanted === null) {
249
+ logger?.debug('Vacuum policy disabled, leaving the entries table settings alone');
250
+ return;
251
+ }
252
+ const current = await client.query('SELECT reloptions FROM pg_class WHERE oid = to_regclass($1)', [this.tableNameEntries]);
253
+ const currentParameters = new Map();
254
+ for (const option of current.rows[0]?.reloptions ?? []) {
255
+ const separator = option.indexOf('=');
256
+ currentParameters.set(option.slice(0, separator), option.slice(separator + 1));
257
+ }
258
+ const differs = Object.entries(wanted).some(function ([name, value]) {
259
+ return (currentParameters.get(name) !== value);
260
+ });
261
+ if (!differs) {
262
+ logger?.debug('Entries table vacuum settings are up to date');
263
+ return;
264
+ }
265
+ const assignments = Object.entries(wanted).map(function ([name, value]) {
266
+ return (`${name} = ${value}`);
267
+ });
268
+ try {
269
+ await client.query(`ALTER TABLE ${this.tableNameEntries} SET (${assignments.join(', ')})`);
270
+ logger?.debug('Applied entries table vacuum settings:', assignments);
271
+ }
272
+ catch (error) {
273
+ if (typeof error === 'object' && error !== null && 'code' in error && error.code === InsufficientPrivilegeSQLState) {
274
+ logger?.warn(`Could not set vacuum settings on ${this.tableNameEntries} (the role does not own it); a large backlog may drain more slowly between vacuums:`, error);
275
+ return;
276
+ }
277
+ throw (error);
278
+ }
279
+ }
185
280
  methodLogger(method) {
186
281
  return (MethodLogger(this.logger, {
187
282
  class: 'KeetaAnchorQueueStorageDriverPostgres',
@@ -337,27 +432,7 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
337
432
  if (!currentEntry) {
338
433
  throw (new Error(`Request with ID ${String(id)} not found`));
339
434
  }
340
- const newEntry = ManageStatusUpdates(id, currentEntry, status, ancillary, logger);
341
- const currentTime = newEntry.updated.getTime();
342
- const workerValue = newEntry.worker;
343
- const newFailures = newEntry.failures ?? currentEntry.failures;
344
- const newLastError = newEntry.lastError !== undefined ? newEntry.lastError : currentEntry.last_error;
345
- const newOutput = newEntry.output !== undefined ? JSON.stringify(newEntry.output) : currentEntry.output;
346
- let updateQuery;
347
- let updateParams;
348
- if (oldStatus) {
349
- updateQuery = `UPDATE ${this.tableNameEntries}
350
- SET status = $1, updated = $2, worker = $3, failures = $4, last_error = $5, output = $6
351
- WHERE id = $7 AND path = $8 AND status = $9`;
352
- updateParams = [status, currentTime, workerValue, newFailures, newLastError, newOutput, id, this.pathStr, oldStatus];
353
- }
354
- else {
355
- updateQuery = `UPDATE ${this.tableNameEntries}
356
- SET status = $1, updated = $2, worker = $3, failures = $4, last_error = $5, output = $6
357
- WHERE id = $7 AND path = $8`;
358
- updateParams = [status, currentTime, workerValue, newFailures, newLastError, newOutput, id, this.pathStr];
359
- }
360
- const result = await client.query(updateQuery, updateParams);
435
+ const result = await this.writeStatusUpdate(client, id, currentEntry, status, ancillary, logger);
361
436
  await this.toctouDelay?.();
362
437
  if (oldStatus && result.rowCount === 0) {
363
438
  const currentEntry = await client.query(`SELECT status FROM ${this.tableNameEntries} WHERE id = $1 AND path = $2`, [id, this.pathStr]);
@@ -374,6 +449,32 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
374
449
  }
375
450
  }));
376
451
  }
452
+ /**
453
+ * Write a status change to an entry whose current values the
454
+ * caller has read (and locked), so every status change goes through
455
+ * {@link ManageStatusUpdates}. With `oldStatus` the UPDATE also
456
+ * requires the entry to still be in that status.
457
+ */
458
+ async writeStatusUpdate(client, id, currentEntry, status, ancillary, logger) {
459
+ const newEntry = ManageStatusUpdates(id, currentEntry, status, ancillary, logger);
460
+ let newLastError = currentEntry.last_error;
461
+ if (newEntry.lastError !== undefined) {
462
+ newLastError = newEntry.lastError;
463
+ }
464
+ let newOutput = currentEntry.output;
465
+ if (newEntry.output !== undefined) {
466
+ newOutput = JSON.stringify(newEntry.output);
467
+ }
468
+ const params = [status, newEntry.updated.getTime(), newEntry.worker, newEntry.failures ?? currentEntry.failures, newLastError, newOutput, id, this.pathStr];
469
+ let text = `UPDATE ${this.tableNameEntries}
470
+ SET status = $1, updated = $2, worker = $3, failures = $4, last_error = $5, output = $6
471
+ WHERE id = $7 AND path = $8`;
472
+ if (ancillary?.oldStatus) {
473
+ text += ' AND status = $9';
474
+ params.push(ancillary.oldStatus);
475
+ }
476
+ return (await client.query(text, params));
477
+ }
377
478
  async get(id) {
378
479
  return (await this.dbTransaction('get', async (client) => {
379
480
  const row = await client.query(`SELECT id, request, output, last_error, status, created, updated, worker, failures
@@ -385,27 +486,61 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
385
486
  if (!entry) {
386
487
  return (null);
387
488
  }
388
- const idempotentRows = await client.query(`SELECT idempotent_id FROM ${this.tableNameIdempotentKeys} WHERE entry_id = $1 AND path = $2`, [id, this.pathStr]);
389
- const idempotentKeys = idempotentRows.rows.length > 0
390
- ? new Set(idempotentRows.rows.map(function (idempotentRow) {
391
- return (ConvertStringToRequestID(idempotentRow.idempotent_id));
392
- }))
393
- : undefined;
394
- return ({
395
- id: ConvertStringToRequestID(entry.id),
396
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
397
- request: JSON.parse(entry.request),
398
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
399
- output: entry.output ? JSON.parse(entry.output) : null,
400
- lastError: entry.last_error,
401
- status: entry.status,
402
- created: new Date(Number(entry.created)),
403
- updated: new Date(Number(entry.updated)),
404
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
405
- worker: entry.worker,
406
- failures: entry.failures,
407
- idempotentKeys: idempotentKeys
408
- });
489
+ return (await this.decodeEntryRow(client, entry));
490
+ }));
491
+ }
492
+ /**
493
+ * Turn an entries row into a queue entry, with its idempotent keys
494
+ */
495
+ async decodeEntryRow(client, row) {
496
+ const idempotentRows = await client.query(`SELECT idempotent_id FROM ${this.tableNameIdempotentKeys} WHERE entry_id = $1 AND path = $2`, [row.id, this.pathStr]);
497
+ let idempotentKeys = undefined;
498
+ if (idempotentRows.rows.length > 0) {
499
+ idempotentKeys = new Set(idempotentRows.rows.map(function (idempotentRow) {
500
+ return (ConvertStringToRequestID(idempotentRow.idempotent_id));
501
+ }));
502
+ }
503
+ return ({
504
+ id: ConvertStringToRequestID(row.id),
505
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
506
+ request: JSON.parse(row.request),
507
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
508
+ output: row.output ? JSON.parse(row.output) : null,
509
+ lastError: row.last_error,
510
+ status: row.status,
511
+ created: new Date(Number(row.created)),
512
+ updated: new Date(Number(row.updated)),
513
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
514
+ worker: row.worker,
515
+ failures: row.failures,
516
+ idempotentKeys: idempotentKeys
517
+ });
518
+ }
519
+ /**
520
+ * Move the oldest entry in a status to "processing" for a worker.
521
+ *
522
+ * SKIP LOCKED makes concurrent claims lock different rows.
523
+ * Postgres locks rows below the LIMIT, so a row that left the status
524
+ * after the statement started is re-checked and passed over, and
525
+ * the scan moves on to the next one. The row stays locked until
526
+ * the transaction commits, so the UPDATE cannot lose it. The entry
527
+ * is returned as it was before the claim.
528
+ */
529
+ async claimNext(status, worker) {
530
+ return (await this.dbTransaction('claimNext', async (client) => {
531
+ const result = await client.query(`SELECT id, request, output, last_error, status, created, updated, worker, failures
532
+ FROM ${this.tableNameEntries}
533
+ WHERE path = $1 AND status = $2
534
+ ORDER BY updated, id
535
+ LIMIT 1
536
+ FOR UPDATE SKIP LOCKED`, [this.pathStr, status]);
537
+ const row = result.rows[0];
538
+ if (row === undefined) {
539
+ return (null);
540
+ }
541
+ const id = ConvertStringToRequestID(row.id);
542
+ await this.writeStatusUpdate(client, id, row, 'processing', { oldStatus: status, by: worker }, this.methodLogger('claimNext'));
543
+ return (await this.decodeEntryRow(client, row));
409
544
  }));
410
545
  }
411
546
  /**
@@ -443,30 +578,9 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
443
578
  logger?.debug(`Querying queue with id ${this.id} with filter:`, filter);
444
579
  const { text, params } = this.buildQuerySQL(filter);
445
580
  const rows = await client.query(text, params);
446
- const entries = [];
447
- for (const row of rows.rows) {
448
- const idempotentRows = await client.query(`SELECT idempotent_id FROM ${this.tableNameIdempotentKeys} WHERE entry_id = $1 AND path = $2`, [row.id, this.pathStr]);
449
- const idempotentKeys = idempotentRows.rows.length > 0
450
- ? new Set(idempotentRows.rows.map(function (idempotentRow) {
451
- return (ConvertStringToRequestID(idempotentRow.idempotent_id));
452
- }))
453
- : undefined;
454
- entries.push({
455
- id: ConvertStringToRequestID(row.id),
456
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
457
- request: JSON.parse(row.request),
458
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
459
- output: row.output ? JSON.parse(row.output) : null,
460
- lastError: row.last_error,
461
- status: row.status,
462
- created: new Date(Number(row.created)),
463
- updated: new Date(Number(row.updated)),
464
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
465
- worker: row.worker,
466
- failures: row.failures,
467
- idempotentKeys: idempotentKeys
468
- });
469
- }
581
+ const entries = await Promise.all(rows.rows.map(async (row) => {
582
+ return (await this.decodeEntryRow(client, row));
583
+ }));
470
584
  logger?.debug(`Queried queue with id ${this.id} with filter:`, filter, '-- found', entries.length, 'entries');
471
585
  return (entries);
472
586
  }));
@@ -512,7 +626,8 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
512
626
  logger: this.logger,
513
627
  pool: this.poolInternal,
514
628
  path: [...this.path, path],
515
- tablePrefix: this.tablePrefix
629
+ tablePrefix: this.tablePrefix,
630
+ vacuumPolicy: this.vacuumPolicy
516
631
  });
517
632
  return (retval);
518
633
  }