@keetanetwork/anchor 0.0.107 → 0.0.110

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,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);
@@ -131,7 +179,34 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
131
179
  throw (error);
132
180
  }
133
181
  }
182
+ // Version 3: Index that serves the query() order (oldest updated first, ties by id)
183
+ if (currentVersion < 3) {
184
+ logger?.debug('Applying schema version 3: Queue order index');
185
+ await client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');
186
+ try {
187
+ /*
188
+ * This blocks writes to the entries table while
189
+ * the index builds. For a large table, an operator
190
+ * can build it ahead of time with
191
+ * "CREATE INDEX CONCURRENTLY" under the same name,
192
+ * and this step then only drops the old index.
193
+ */
194
+ await client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_status_updated_id ON ${this.tableNameEntries}(path, status, updated, id)`);
195
+ /*
196
+ * The new index serves every query the old one did
197
+ */
198
+ await client.query(`DROP INDEX IF EXISTS idx_${this.tableNameEntries}_path_status_updated`);
199
+ await client.query(`INSERT INTO ${this.tableNameSchemaVersion} (version, applied_at) VALUES (3, $1)`, [Date.now()]);
200
+ await client.query('COMMIT');
201
+ logger?.debug('Applied schema version 3');
202
+ }
203
+ catch (error) {
204
+ await client.query('ROLLBACK');
205
+ throw (error);
206
+ }
207
+ }
134
208
  logger?.debug('Schema is up to date');
209
+ await this.applyVacuumPolicy(client);
135
210
  }
136
211
  finally {
137
212
  // Always release the advisory lock
@@ -156,6 +231,52 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
156
231
  await this.dbInitializationPromise;
157
232
  return (pool);
158
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
+ }
159
280
  methodLogger(method) {
160
281
  return (MethodLogger(this.logger, {
161
282
  class: 'KeetaAnchorQueueStorageDriverPostgres',
@@ -311,27 +432,7 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
311
432
  if (!currentEntry) {
312
433
  throw (new Error(`Request with ID ${String(id)} not found`));
313
434
  }
314
- const newEntry = ManageStatusUpdates(id, currentEntry, status, ancillary, logger);
315
- const currentTime = newEntry.updated.getTime();
316
- const workerValue = newEntry.worker;
317
- const newFailures = newEntry.failures ?? currentEntry.failures;
318
- const newLastError = newEntry.lastError !== undefined ? newEntry.lastError : currentEntry.last_error;
319
- const newOutput = newEntry.output !== undefined ? JSON.stringify(newEntry.output) : currentEntry.output;
320
- let updateQuery;
321
- let updateParams;
322
- if (oldStatus) {
323
- updateQuery = `UPDATE ${this.tableNameEntries}
324
- SET status = $1, updated = $2, worker = $3, failures = $4, last_error = $5, output = $6
325
- WHERE id = $7 AND path = $8 AND status = $9`;
326
- updateParams = [status, currentTime, workerValue, newFailures, newLastError, newOutput, id, this.pathStr, oldStatus];
327
- }
328
- else {
329
- updateQuery = `UPDATE ${this.tableNameEntries}
330
- SET status = $1, updated = $2, worker = $3, failures = $4, last_error = $5, output = $6
331
- WHERE id = $7 AND path = $8`;
332
- updateParams = [status, currentTime, workerValue, newFailures, newLastError, newOutput, id, this.pathStr];
333
- }
334
- const result = await client.query(updateQuery, updateParams);
435
+ const result = await this.writeStatusUpdate(client, id, currentEntry, status, ancillary, logger);
335
436
  await this.toctouDelay?.();
336
437
  if (oldStatus && result.rowCount === 0) {
337
438
  const currentEntry = await client.query(`SELECT status FROM ${this.tableNameEntries} WHERE id = $1 AND path = $2`, [id, this.pathStr]);
@@ -348,6 +449,32 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
348
449
  }
349
450
  }));
350
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
+ }
351
478
  async get(id) {
352
479
  return (await this.dbTransaction('get', async (client) => {
353
480
  const row = await client.query(`SELECT id, request, output, last_error, status, created, updated, worker, failures
@@ -359,82 +486,101 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
359
486
  if (!entry) {
360
487
  return (null);
361
488
  }
362
- const idempotentRows = await client.query(`SELECT idempotent_id FROM ${this.tableNameIdempotentKeys} WHERE entry_id = $1 AND path = $2`, [id, this.pathStr]);
363
- const idempotentKeys = idempotentRows.rows.length > 0
364
- ? new Set(idempotentRows.rows.map(function (idempotentRow) {
365
- return (ConvertStringToRequestID(idempotentRow.idempotent_id));
366
- }))
367
- : undefined;
368
- return ({
369
- id: ConvertStringToRequestID(entry.id),
370
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
371
- request: JSON.parse(entry.request),
372
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
373
- output: entry.output ? JSON.parse(entry.output) : null,
374
- lastError: entry.last_error,
375
- status: entry.status,
376
- created: new Date(Number(entry.created)),
377
- updated: new Date(Number(entry.updated)),
378
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
379
- worker: entry.worker,
380
- failures: entry.failures,
381
- idempotentKeys: idempotentKeys
382
- });
489
+ return (await this.decodeEntryRow(client, entry));
383
490
  }));
384
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));
544
+ }));
545
+ }
546
+ /**
547
+ * Build the SQL for {@link query}, ordered as the storage driver
548
+ * contract requires (oldest updated first, ties by id) so that the
549
+ * (path, status, updated, id) index serves both the filter and the
550
+ * order
551
+ */
552
+ buildQuerySQL(filter) {
553
+ const conditions = [];
554
+ const params = [];
555
+ let paramIndex = 1;
556
+ conditions.push(`path = $${paramIndex++}`);
557
+ params.push(this.pathStr);
558
+ if (filter?.status) {
559
+ conditions.push(`status = $${paramIndex++}`);
560
+ params.push(filter.status);
561
+ }
562
+ if (filter?.updatedBefore) {
563
+ conditions.push(`updated < $${paramIndex++}`);
564
+ params.push(filter.updatedBefore.getTime());
565
+ }
566
+ let text = `SELECT id, request, output, last_error, status, created, updated, worker, failures FROM ${this.tableNameEntries}`;
567
+ text += ' WHERE ' + conditions.join(' AND ');
568
+ text += ' ORDER BY updated, id';
569
+ if (filter?.limit !== undefined) {
570
+ text += ` LIMIT $${paramIndex++}`;
571
+ params.push(filter.limit);
572
+ }
573
+ return ({ text: text, params: params });
574
+ }
385
575
  async query(filter) {
386
576
  return (await this.dbTransaction('query', async (client) => {
387
577
  const logger = this.methodLogger('query');
388
578
  logger?.debug(`Querying queue with id ${this.id} with filter:`, filter);
389
- const conditions = [];
390
- const params = [];
391
- let paramIndex = 1;
392
- conditions.push(`path = $${paramIndex++}`);
393
- params.push(this.pathStr);
394
- if (filter?.status) {
395
- conditions.push(`status = $${paramIndex++}`);
396
- params.push(filter.status);
397
- }
398
- if (filter?.updatedBefore) {
399
- conditions.push(`updated < $${paramIndex++}`);
400
- params.push(filter.updatedBefore.getTime());
401
- }
402
- let query = `SELECT id, request, output, last_error, status, created, updated, worker, failures FROM ${this.tableNameEntries}`;
403
- if (conditions.length > 0) {
404
- query += ' WHERE ' + conditions.join(' AND ');
405
- }
406
- // Use random ordering to prevent multiple workers from contending for the same rows
407
- // This spreads the load when multiple workers query simultaneously
408
- query += ' ORDER BY RANDOM()';
409
- if (filter?.limit !== undefined) {
410
- query += ` LIMIT $${paramIndex++}`;
411
- params.push(filter.limit);
412
- }
413
- const rows = await client.query(query, params);
414
- const entries = [];
415
- for (const row of rows.rows) {
416
- const idempotentRows = await client.query(`SELECT idempotent_id FROM ${this.tableNameIdempotentKeys} WHERE entry_id = $1 AND path = $2`, [row.id, this.pathStr]);
417
- const idempotentKeys = idempotentRows.rows.length > 0
418
- ? new Set(idempotentRows.rows.map(function (idempotentRow) {
419
- return (ConvertStringToRequestID(idempotentRow.idempotent_id));
420
- }))
421
- : undefined;
422
- entries.push({
423
- id: ConvertStringToRequestID(row.id),
424
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
425
- request: JSON.parse(row.request),
426
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
427
- output: row.output ? JSON.parse(row.output) : null,
428
- lastError: row.last_error,
429
- status: row.status,
430
- created: new Date(Number(row.created)),
431
- updated: new Date(Number(row.updated)),
432
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
433
- worker: row.worker,
434
- failures: row.failures,
435
- idempotentKeys: idempotentKeys
436
- });
437
- }
579
+ const { text, params } = this.buildQuerySQL(filter);
580
+ const rows = await client.query(text, params);
581
+ const entries = await Promise.all(rows.rows.map(async (row) => {
582
+ return (await this.decodeEntryRow(client, row));
583
+ }));
438
584
  logger?.debug(`Queried queue with id ${this.id} with filter:`, filter, '-- found', entries.length, 'entries');
439
585
  return (entries);
440
586
  }));
@@ -480,7 +626,8 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
480
626
  logger: this.logger,
481
627
  pool: this.poolInternal,
482
628
  path: [...this.path, path],
483
- tablePrefix: this.tablePrefix
629
+ tablePrefix: this.tablePrefix,
630
+ vacuumPolicy: this.vacuumPolicy
484
631
  });
485
632
  return (retval);
486
633
  }
@@ -516,6 +663,15 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
516
663
  },
517
664
  disableDebugForceIndexScan: () => {
518
665
  this.debugForceIndexScan = false;
666
+ },
667
+ explainQuery: async (filter) => {
668
+ return (await this.dbTransaction('explainQuery', async (client) => {
669
+ const { text, params } = this.buildQuerySQL(filter);
670
+ const plan = await client.query(`EXPLAIN ${text}`, params);
671
+ return (plan.rows.map(function (row) {
672
+ return (row['QUERY PLAN']);
673
+ }).join('\n'));
674
+ }));
519
675
  }
520
676
  });
521
677
  }