@keetanetwork/anchor 0.0.111 → 0.0.112

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.
@@ -31,6 +31,11 @@ export type KeetaAnchorQueueStorageDriverPostgresVacuumPolicy = {
31
31
  */
32
32
  analyzeScaleFactor: number;
33
33
  };
34
+ /**
35
+ * The longest table prefix that keeps every table and index name within
36
+ * the 63 bytes Postgres allows
37
+ */
38
+ export declare const MaxTablePrefixLength = 24;
34
39
  type KeetaAnchorQueueStorageDriverPostgresOptions = {
35
40
  /**
36
41
  * Function that returns a Postgres connection pool.
@@ -39,7 +44,8 @@ type KeetaAnchorQueueStorageDriverPostgresOptions = {
39
44
  /**
40
45
  * The prefix to use for the database tables. Defaults to 'queue',
41
46
  * resulting in table names 'queue_entries', 'queue_idempotent_keys',
42
- * and `queue_schema_version`.
47
+ * and `queue_schema_version`. At most {@link MaxTablePrefixLength}
48
+ * bytes.
43
49
  */
44
50
  tablePrefix?: string | undefined;
45
51
  /**
@@ -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,EAC3B,wBAAwB,EACxB,MAAM,aAAa,CAAC;AAWrB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,OAAO,KAAK,KAAK,EAAE,MAAM,IAAI,CAAC;AAkB9B;;;;;;;;GAQG;AACH,MAAM,MAAM,iDAAiD,GAAG;IAC/D;;;OAGG;IACH,eAAe,EAAE,MAAM,CAAC;IAExB;;;;;;;OAOG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,kBAAk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AW,CAAC,GAAG,IAAI,CAAC;IAwBnJ;;;;;OAKG;IACH,OAAO,CAAC,aAAa;IA8Bf,KAAK,CAAC,MAAM,CAAC,EAAE,sBAAsB,GAAG,OAAO,CAAC,qBAAqB,CAAC,YAAY,EAAE,WAAW,CAAC,EAAE,CAAC;IAkBnG,MAAM,CAAC,KAAK,EAAE,2BAA2B,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAsC3D,SAAS,CAAC,IAAI,EAAE,MAAM,GAAI,OAAO,CAAC,6BAA6B,CAAC,YAAY,EAAE,WAAW,CAAC,CAAC;IAmB3F,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAMxB,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;CAkD5C"}
@@ -14,6 +14,11 @@ const MaxScaleFactor = 100;
14
14
  * The SQLSTATE Postgres returns when the role does not own the table
15
15
  */
16
16
  const InsufficientPrivilegeSQLState = '42501';
17
+ /**
18
+ * The longest table prefix that keeps every table and index name within
19
+ * the 63 bytes Postgres allows
20
+ */
21
+ export const MaxTablePrefixLength = 24;
17
22
  /**
18
23
  * Check the vacuum policy and build the table storage parameters for it.
19
24
  * The values are written into the ALTER TABLE statement (storage
@@ -63,6 +68,9 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
63
68
  this.id = options?.id ?? crypto.randomUUID();
64
69
  this.logger = options?.logger;
65
70
  this.tablePrefix = options?.tablePrefix;
71
+ if (this.tablePrefix !== undefined && new TextEncoder().encode(this.tablePrefix).length > MaxTablePrefixLength) {
72
+ throw (new Error(`Invalid tablePrefix: must be at most ${MaxTablePrefixLength} bytes`));
73
+ }
66
74
  this.poolInternal = options.pool;
67
75
  this.vacuumPolicy = options.vacuumPolicy ?? {};
68
76
  this.vacuumStorageParameters = null;
@@ -184,6 +192,10 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
184
192
  logger?.debug('Applying schema version 3: Queue order index');
185
193
  await client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');
186
194
  try {
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`);
187
199
  /*
188
200
  * This blocks writes to the entries table while
189
201
  * the index builds. For a large table, an operator
@@ -192,10 +204,6 @@ export default class KeetaAnchorQueueStorageDriverPostgres {
192
204
  * and this step then only drops the old index.
193
205
  */
194
206
  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
207
  await client.query(`INSERT INTO ${this.tableNameSchemaVersion} (version, applied_at) VALUES (3, $1)`, [Date.now()]);
200
208
  await client.query('COMMIT');
201
209
  logger?.debug('Applied schema version 3');
@@ -1 +1 @@
1
- {"version":3,"file":"queue_postgres.js","sourceRoot":"","sources":["../../../../src/lib/queue/drivers/queue_postgres.ts"],"names":[],"mappings":"AAeA,OAAO,EACN,YAAY,EACZ,mBAAmB,EACnB,wBAAwB,EACxB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAwD/C,MAAM,mBAAmB,GAAsD;IAC9E,eAAe,EAAE,MAAM;IACvB,iBAAiB,EAAE,KAAK;IACxB,kBAAkB,EAAE,IAAI;CACxB,CAAC;AAEF;;GAEG;AACH,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B;;GAEG;AACH,MAAM,6BAA6B,GAAG,OAAO,CAAC;AAE9C;;;;;GAKG;AACH,SAAS,6BAA6B,CAAC,MAAyD;IAC/F,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,MAAM,CAAC,eAAe,GAAG,CAAC,EAAE,C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AG,CAAC,CAAC;YAClC,CAAC;YACD,yBAAyB,EAAE,GAAS,EAAE;gBACrC,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC;YACjC,CAAC;YACD,0BAA0B,EAAE,GAAS,EAAE;gBACtC,IAAI,CAAC,mBAAmB,GAAG,KAAK,CAAC;YAClC,CAAC;YACD,YAAY,EAAE,KAAK,EAAE,MAA+B,EAAmB,EAAE;gBACxE,OAAM,CAAC,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,EAAE,KAAK,EAAE,MAAM,EAAmB,EAAE;oBACjF,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;oBACpD,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,KAAK,CAA2B,WAAW,IAAI,EAAE,EAAE,MAAM,CAAC,CAAC;oBACrF,OAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,UAAS,GAAG;wBAChC,OAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC;oBAC3B,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;gBAChB,CAAC,CAAC,CAAC,CAAC;YACL,CAAC;SACD,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["// cspell:ignore seqscan autovacuum regclass reloptions SQLSTATE\n\nimport type {\n\tKeetaAnchorQueueStorageDriver,\n\tKeetaAnchorQueueStorageDriverConstructor,\n\tKeetaAnchorQueueRequest,\n\tKeetaAnchorQueueRequestID,\n\tKeetaAnchorQueueEntry,\n\tKeetaAnchorQueueEntryExtra,\n\tKeetaAnchorQueueEntryAncillaryData,\n\tKeetaAnchorQueueStatus,\n\tKeetaAnchorQueueFilter,\n\tKeetaAnchorQueueDeleteInput,\n\tKeetaAnchorQueueWorkerID\n} from '../index.ts';\nimport {\n\tMethodLogger,\n\tManageStatusUpdates,\n\tConvertStringToRequestID\n} from '../internal.js';\nimport { Errors } from '../common.js';\n\nimport { asleep } from '../../utils/asleep.js';\n\nimport type { Logger } from '../../log/index.ts';\nimport type { JSONSerializable } from '../../utils/json.js';\n\nimport type * as pg from 'pg';\n\ntype QueueEntryRow = {\n\tid: string;\n\trequest: string;\n\toutput: string | null;\n\tlast_error: string | null;\n\tstatus: KeetaAnchorQueueStatus;\n\tcreated: Date;\n\tupdated: Date;\n\tworker: number | null;\n\tfailures: number;\n};\n\ntype IdempotentRow = {\n\tidempotent_id: string;\n};\n\n/**\n * How often Postgres vacuums the queue's entries table.\n *\n * Every status change is an update to a column the queue's indexes are\n * keyed on, so it leaves a dead index entry at the oldest end of the\n * status range the entry left. That is exactly where the next query()\n * starts reading, so until a vacuum cleans the index each pick reads\n * past every entry processed since the last vacuum.\n */\nexport type KeetaAnchorQueueStorageDriverPostgresVacuumPolicy = {\n\t/**\n\t * Number of updated or deleted rows that triggers an autovacuum of\n\t * the entries table (autovacuum_vacuum_threshold)\n\t */\n\tvacuumThreshold: number;\n\n\t/**\n\t * Fraction of the table added to `vacuumThreshold`\n\t * (autovacuum_vacuum_scale_factor). A pick slows with the number of\n\t * dead entries ahead of it, but each vacuum reads every index in\n\t * full, so its cost grows with the table. A small fraction lets a\n\t * large table vacuum less often, so it does not vacuum almost\n\t * constantly.\n\t */\n\tvacuumScaleFactor: number;\n\n\t/**\n\t * Fraction of the table changed that triggers an automatic ANALYZE\n\t * (autovacuum_analyze_scale_factor)\n\t */\n\tanalyzeScaleFactor: number;\n};\n\nconst DefaultVacuumPolicy: KeetaAnchorQueueStorageDriverPostgresVacuumPolicy = {\n\tvacuumThreshold: 10_000,\n\tvacuumScaleFactor: 0.001,\n\tanalyzeScaleFactor: 0.02\n};\n\n/**\n * Postgres accepts scale factors from 0 to 100\n */\nconst MaxScaleFactor = 100;\n\n/**\n * The SQLSTATE Postgres returns when the role does not own the table\n */\nconst InsufficientPrivilegeSQLState = '42501';\n\n/**\n * Check the vacuum policy and build the table storage parameters for it.\n * The values are written into the ALTER TABLE statement (storage\n * parameters cannot be bound), so each one must be a finite number in\n * the range Postgres accepts.\n */\nfunction VacuumPolicyStorageParameters(policy: KeetaAnchorQueueStorageDriverPostgresVacuumPolicy): { [name: string]: string } {\n\tif (!Number.isSafeInteger(policy.vacuumThreshold) || policy.vacuumThreshold < 0) {\n\t\tthrow(new Error(`Invalid vacuumThreshold ${String(policy.vacuumThreshold)}: must be a non-negative integer`));\n\t}\n\n\tfor (const [name, value] of [['vacuumScaleFactor', policy.vacuumScaleFactor], ['analyzeScaleFactor', policy.analyzeScaleFactor]] as const) {\n\t\tif (!Number.isFinite(value) || value < 0 || value > MaxScaleFactor) {\n\t\t\tthrow(new Error(`Invalid ${name} ${String(value)}: must be a number from 0 to ${MaxScaleFactor}`));\n\t\t}\n\t}\n\n\treturn({\n\t\t/*\n\t\t * Without this, a vacuum skips cleaning the indexes when\n\t\t * fewer than about 2% of the table's pages hold dead rows,\n\t\t * which is always the case for a drained range of a large\n\t\t * queue, and the dead index entries the pick reads past stay\n\t\t */\n\t\tvacuum_index_cleanup: 'on',\n\t\tautovacuum_vacuum_threshold: String(policy.vacuumThreshold),\n\t\tautovacuum_vacuum_scale_factor: String(policy.vacuumScaleFactor),\n\t\tautovacuum_analyze_scale_factor: String(policy.analyzeScaleFactor)\n\t});\n}\n\ntype KeetaAnchorQueueStorageDriverPostgresOptions = {\n\t/**\n\t * Function that returns a Postgres connection pool.\n\t */\n\tpool: () => Promise<pg.Pool>;\n\n\t/**\n\t * The prefix to use for the database tables. Defaults to 'queue',\n\t * resulting in table names 'queue_entries', 'queue_idempotent_keys',\n\t * and `queue_schema_version`.\n\t */\n\ttablePrefix?: string | undefined;\n\n\t/**\n\t * Vacuum settings for the entries table, applied each time the\n\t * driver initializes. Any value left out uses the default\n\t * ({@link DefaultVacuumPolicy}). Pass `false` to leave the table's\n\t * vacuum settings alone, for example when an operator manages them.\n\t */\n\tvacuumPolicy?: Partial<KeetaAnchorQueueStorageDriverPostgresVacuumPolicy> | false;\n};\n\nexport default class KeetaAnchorQueueStorageDriverPostgres<QueueRequest extends JSONSerializable = JSONSerializable, QueueResult extends JSONSerializable = JSONSerializable> implements KeetaAnchorQueueStorageDriver<QueueRequest, QueueResult> {\n\tprivate readonly logger: Logger | undefined;\n\tprivate poolInternal: (() => Promise<pg.Pool>) | null = null;\n\tprivate tablePrefix: string | undefined;\n\tprivate tableNameEntries: string;\n\tprivate tableNameSchemaVersion: string;\n\tprivate tableNameIdempotentKeys: string;\n\tprivate dbInitializationPromise: Promise<boolean> | null = null;\n\tprivate serializationRetryCount = 0;\n\tprivate debugForceIndexScan = false;\n\n\treadonly name = 'KeetaAnchorQueueStorageDriverPostgres';\n\treadonly id: string;\n\treadonly path: string[] = [];\n\tprivate readonly pathStr: string;\n\tprivate toctouDelay: (() => Promise<void>) | undefined = undefined;\n\tprivate readonly vacuumPolicy: Partial<KeetaAnchorQueueStorageDriverPostgresVacuumPolicy> | false;\n\tprivate readonly vacuumStorageParameters: { [name: string]: string } | null;\n\n\tconstructor(options: NonNullable<ConstructorParameters<KeetaAnchorQueueStorageDriverConstructor<QueueRequest, QueueResult>>[0]> & KeetaAnchorQueueStorageDriverPostgresOptions) {\n\t\tthis.id = options?.id ?? crypto.randomUUID();\n\t\tthis.logger = options?.logger;\n\t\tthis.tablePrefix = options?.tablePrefix;\n\t\tthis.poolInternal = options.pool;\n\t\tthis.vacuumPolicy = options.vacuumPolicy ?? {};\n\t\tthis.vacuumStorageParameters = null;\n\t\tif (this.vacuumPolicy !== false) {\n\t\t\tthis.vacuumStorageParameters = VacuumPolicyStorageParameters({ ...DefaultVacuumPolicy, ...this.vacuumPolicy });\n\t\t}\n\t\tthis.path = options.path ?? [];\n\t\tthis.pathStr = ['root', ...this.path].join('.');\n\t\tObject.freeze(this.path);\n\n\t\tthis.tableNameEntries = `${this.tablePrefix ?? 'queue'}_entries`;\n\t\tthis.tableNameIdempotentKeys = `${this.tablePrefix ?? 'queue'}_idempotent_keys`;\n\t\tthis.tableNameSchemaVersion = `${this.tablePrefix ?? 'queue'}_schema_version`;\n\n\t\tthis.methodLogger('new')?.debug('Initialized Postgres queue storage driver');\n\t}\n\n\tprivate async initializeDBConnection(pool: pg.Pool): Promise<pg.Pool> {\n\t\tconst logger = this.methodLogger('initializeDBConnection');\n\n\t\tif (this.dbInitializationPromise !== null) {\n\t\t\tlogger?.debug('DB schema initialization already in progress or completed, waiting for it to finish');\n\n\t\t\tawait this.dbInitializationPromise;\n\t\t\treturn(pool);\n\t\t}\n\n\t\tthis.dbInitializationPromise = (async () => {\n\t\t\tlogger?.debug('Initializing DB schema for queue storage driver on tables', [this.tableNameEntries, this.tableNameIdempotentKeys]);\n\n\t\t\tconst client = await pool.connect();\n\t\t\ttry {\n\t\t\t\t/*\n\t\t\t\t * Random lock key (32-bit integer), to ensure\n\t\t\t\t * that multiple instances of this driver\n\t\t\t\t * (potentially across different\n\t\t\t\t * instances/process) will run the migration\n\t\t\t\t * sequentially to avoid multiple concurrent\n\t\t\t\t * migrations from competing with each other\n\t\t\t\t * and causing delays\n\t\t\t\t */\n\t\t\t\tconst lockId = 0x24995E48;\n\t\t\t\tlogger?.debug('Acquiring advisory lock for schema migration');\n\t\t\t\tawait client.query('SELECT pg_advisory_lock($1)', [lockId]);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Create schema version table if it doesn't exist\n\t\t\t\t\tawait client.query(`\n\t\t\t\t\t\tCREATE TABLE IF NOT EXISTS ${this.tableNameSchemaVersion} (\n\t\t\t\t\t\t\tversion INTEGER NOT NULL,\n\t\t\t\t\t\t\tapplied_at BIGINT NOT NULL,\n\t\t\t\t\t\t\tPRIMARY KEY (version)\n\t\t\t\t\t\t)`);\n\n\t\t\t\t\t// Check current schema version\n\t\t\t\t\tconst versionResult = await client.query<{ version: number }>(`SELECT MAX(version) as version FROM ${this.tableNameSchemaVersion}`);\n\t\t\t\t\tconst currentVersion = versionResult.rows[0]?.version ?? 0;\n\n\t\t\t\t\tlogger?.debug(`Current queue schema version: ${currentVersion}`);\n\n\t\t\t\t\t// Version 1: Initial schema\n\t\t\t\t\tif (currentVersion < 1) {\n\t\t\t\t\t\tlogger?.debug('Applying schema version 1: Initial tables and indexes');\n\n\t\t\t\t\t\tawait client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait client.query(`\n\t\t\t\t\t\t\t\tCREATE TABLE IF NOT EXISTS ${this.tableNameEntries} (\n\t\t\t\t\t\t\t\t\tid TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tpath TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\trequest TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\toutput TEXT,\n\t\t\t\t\t\t\t\t\tlast_error TEXT,\n\t\t\t\t\t\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tcreated BIGINT NOT NULL,\n\t\t\t\t\t\t\t\t\tupdated BIGINT NOT NULL,\n\t\t\t\t\t\t\t\t\tworker BIGINT,\n\t\t\t\t\t\t\t\t\tfailures INTEGER NOT NULL DEFAULT 0,\n\t\t\t\t\t\t\t\t\tPRIMARY KEY (id, path)\n\t\t\t\t\t\t\t\t)`);\n\n\t\t\t\t\t\t\tawait client.query(`\n\t\t\t\t\t\t\t\tCREATE TABLE IF NOT EXISTS ${this.tableNameIdempotentKeys} (\n\t\t\t\t\t\t\t\t\tentry_id TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tidempotent_id TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tpath TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tUNIQUE (idempotent_id, path),\n\t\t\t\t\t\t\t\t\tPRIMARY KEY (entry_id, idempotent_id, path),\n\t\t\t\t\t\t\t\t\tFOREIGN KEY (entry_id, path) REFERENCES ${this.tableNameEntries}(id, path)\n\t\t\t\t\t\t\t\t)`);\n\n\t\t\t\t\t\t\t// Old single-column indexes (for pre-version-2 schemas)\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_status ON ${this.tableNameEntries}(status)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_updated ON ${this.tableNameEntries}(updated)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameIdempotentKeys}_idempotent_id ON ${this.tableNameIdempotentKeys}(idempotent_id)`);\n\n\t\t\t\t\t\t\tawait client.query(`INSERT INTO ${this.tableNameSchemaVersion} (version, applied_at) VALUES (1, $1)`, [Date.now()]);\n\t\t\t\t\t\t\tawait client.query('COMMIT');\n\t\t\t\t\t\t\tlogger?.debug('Applied schema version 1');\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\t\t\t\tthrow(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Version 2: Partition-aware composite indexes\n\t\t\t\t\tif (currentVersion < 2) {\n\t\t\t\t\t\tlogger?.debug('Applying schema version 2: Partition-aware composite indexes');\n\n\t\t\t\t\t\t// Now drop old indexes and record version\n\t\t\t\t\t\tawait client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Create new partition-aware indexes\n\t\t\t\t\t\t\tlogger?.debug('Creating partition-aware indexes...');\n\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_status ON ${this.tableNameEntries}(path, status)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_updated ON ${this.tableNameEntries}(path, updated)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_status_updated ON ${this.tableNameEntries}(path, status, updated)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameIdempotentKeys}_path_idempotent_id ON ${this.tableNameIdempotentKeys}(path, idempotent_id)`);\n\n\t\t\t\t\t\t\t// Drop old indexes that are now redundant (these will fail gracefully if indexes don't exist)\n\t\t\t\t\t\t\tlogger?.debug('Dropping old single-column indexes...');\n\t\t\t\t\t\t\tawait client.query(`DROP INDEX IF EXISTS idx_${this.tableNameEntries}_status`);\n\t\t\t\t\t\t\tawait client.query(`DROP INDEX IF EXISTS idx_${this.tableNameEntries}_updated`);\n\t\t\t\t\t\t\tawait client.query(`DROP INDEX IF EXISTS idx_${this.tableNameIdempotentKeys}_idempotent_id`);\n\n\t\t\t\t\t\t\tawait client.query(`INSERT INTO ${this.tableNameSchemaVersion} (version, applied_at) VALUES (2, $1)`, [Date.now()]);\n\t\t\t\t\t\t\tawait client.query('COMMIT');\n\t\t\t\t\t\t\tlogger?.debug('Applied schema version 2');\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\t\t\t\tthrow(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Version 3: Index that serves the query() order (oldest updated first, ties by id)\n\t\t\t\t\tif (currentVersion < 3) {\n\t\t\t\t\t\tlogger?.debug('Applying schema version 3: Queue order index');\n\n\t\t\t\t\t\tawait client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * This blocks writes to the entries table while\n\t\t\t\t\t\t\t * the index builds. For a large table, an operator\n\t\t\t\t\t\t\t * can build it ahead of time with\n\t\t\t\t\t\t\t * \"CREATE INDEX CONCURRENTLY\" under the same name,\n\t\t\t\t\t\t\t * and this step then only drops the old index.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_status_updated_id ON ${this.tableNameEntries}(path, status, updated, id)`);\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * The new index serves every query the old one did\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tawait client.query(`DROP INDEX IF EXISTS idx_${this.tableNameEntries}_path_status_updated`);\n\n\t\t\t\t\t\t\tawait client.query(`INSERT INTO ${this.tableNameSchemaVersion} (version, applied_at) VALUES (3, $1)`, [Date.now()]);\n\t\t\t\t\t\t\tawait client.query('COMMIT');\n\t\t\t\t\t\t\tlogger?.debug('Applied schema version 3');\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\t\t\t\tthrow(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tlogger?.debug('Schema is up to date');\n\n\t\t\t\t\tawait this.applyVacuumPolicy(client);\n\t\t\t\t} finally {\n\t\t\t\t\t// Always release the advisory lock\n\t\t\t\t\t// Note: Advisory locks are session-based and auto-release on disconnect,\n\t\t\t\t\t// but we explicitly unlock for clarity and to avoid holding locks longer than needed\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlogger?.debug('Releasing advisory lock');\n\t\t\t\t\t\tawait client.query('SELECT pg_advisory_unlock($1)', [lockId]);\n\t\t\t\t\t} catch (unlockError) {\n\t\t\t\t\t\t// Log but don't throw - the lock will be auto-released when connection closes\n\t\t\t\t\t\tlogger?.debug('Failed to explicitly release advisory lock (will auto-release on disconnect):', unlockError);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tclient.release();\n\t\t\t}\n\n\t\t\tlogger?.debug('Completed DB schema initialization for queue storage driver');\n\n\t\t\treturn(true);\n\t\t})();\n\n\t\tawait this.dbInitializationPromise;\n\n\t\treturn(pool);\n\t}\n\n\t/**\n\t * Set the entries table's vacuum storage parameters to the\n\t * configured policy. This runs on every initialization rather than\n\t * as a versioned migration, so an upgraded database gets the\n\t * settings and a changed policy takes effect. The table is only\n\t * altered when its settings differ.\n\t *\n\t * Changing storage parameters requires owning the table. Without\n\t * that privilege the queue still works, only more slowly while a\n\t * large backlog drains, so a warning is logged and startup goes on.\n\t */\n\tprivate async applyVacuumPolicy(client: pg.PoolClient): Promise<void> {\n\t\tconst logger = this.methodLogger('applyVacuumPolicy');\n\t\tconst wanted = this.vacuumStorageParameters;\n\t\tif (wanted === null) {\n\t\t\tlogger?.debug('Vacuum policy disabled, leaving the entries table settings alone');\n\t\t\treturn;\n\t\t}\n\n\t\tconst current = await client.query<{ reloptions: string[] | null }>('SELECT reloptions FROM pg_class WHERE oid = to_regclass($1)', [this.tableNameEntries]);\n\t\tconst currentParameters = new Map<string, string>();\n\t\tfor (const option of current.rows[0]?.reloptions ?? []) {\n\t\t\tconst separator = option.indexOf('=');\n\t\t\tcurrentParameters.set(option.slice(0, separator), option.slice(separator + 1));\n\t\t}\n\n\t\tconst differs = Object.entries(wanted).some(function([name, value]) {\n\t\t\treturn(currentParameters.get(name) !== value);\n\t\t});\n\t\tif (!differs) {\n\t\t\tlogger?.debug('Entries table vacuum settings are up to date');\n\t\t\treturn;\n\t\t}\n\n\t\tconst assignments = Object.entries(wanted).map(function([name, value]) {\n\t\t\treturn(`${name} = ${value}`);\n\t\t});\n\n\t\ttry {\n\t\t\tawait client.query(`ALTER TABLE ${this.tableNameEntries} SET (${assignments.join(', ')})`);\n\t\t\tlogger?.debug('Applied entries table vacuum settings:', assignments);\n\t\t} catch (error: unknown) {\n\t\t\tif (typeof error === 'object' && error !== null && 'code' in error && error.code === InsufficientPrivilegeSQLState) {\n\t\t\t\tlogger?.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);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow(error);\n\t\t}\n\t}\n\n\tprivate methodLogger(method: string): Logger | undefined {\n\t\treturn(MethodLogger(this.logger, {\n\t\t\tclass: 'KeetaAnchorQueueStorageDriverPostgres',\n\t\t\tfile: 'src/lib/queue/drivers/queue_postgres.ts',\n\t\t\tmethod: method,\n\t\t\tinstanceID: this.id\n\t\t}));\n\t}\n\n\tprivate async runWithRetry<T>(fn: () => Promise<T>): Promise<T> {\n\t\tconst logger = this.methodLogger('runWithRetry');\n\n\t\tlet lastError: unknown;\n\t\tfor (let retry = 0; retry < 16; retry++) {\n\t\t\tif (this.poolInternal === null) {\n\t\t\t\tlogger?.debug('Aborting DB operation retries because the instance was destroyed');\n\n\t\t\t\tif (lastError !== undefined) {\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/only-throw-error\n\t\t\t\t\tthrow(lastError);\n\t\t\t\t}\n\t\t\t\tthrow(new Error('Aborting because the instance was destroyed'));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\treturn(await fn());\n\t\t\t} catch (error: unknown) {\n\t\t\t\tlastError = error;\n\n\t\t\t\tlet detectedRetryableError = false;\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconst errorCode = 'code' in error ? error.code : null;\n\t\t\t\t\tif (errorCode === '40001' || errorCode === '40P01') {\n\t\t\t\t\t\t// Track serialization retries for instrumentation\n\t\t\t\t\t\tthis.serializationRetryCount++;\n\n\t\t\t\t\t\tdetectedRetryableError = true;\n\t\t\t\t\t\tlogger?.debug('Detected retryable error with code', errorCode);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (detectedRetryableError) {\n\t\t\t\t\tconst minBackoff = 100;\n\t\t\t\t\tconst maxBackoff = 30_000;\n\t\t\t\t\tconst backoffIntervalSize = Math.min(maxBackoff - minBackoff, (retry + 50) ** 2);\n\t\t\t\t\tconst backoff = Math.round((Math.random() * backoffIntervalSize)) + minBackoff;\n\n\t\t\t\t\tlogger?.debug(`Retrying DB operation in ${backoff}ms (retry #${retry}) from`, new Error().stack);\n\t\t\t\t\tawait asleep(backoff);\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tthrow(error);\n\t\t\t}\n\t\t}\n\t\tthrow(lastError);\n\t}\n\n\tprivate async newDBConnection(): Promise<pg.Pool> {\n\t\tif (this.poolInternal === null) {\n\t\t\tthrow(new Error('Database connection is not available'));\n\t\t}\n\n\t\treturn(await this.runWithRetry(async () => {\n\t\t\tif (this.poolInternal === null) {\n\t\t\t\tthrow(new Error('Database connection is not available'));\n\t\t\t}\n\n\t\t\tthis.methodLogger('newDBConnection')?.debug('Getting DB pool');\n\t\t\tconst pool = await this.poolInternal();\n\n\t\t\treturn(await this.initializeDBConnection(pool));\n\t\t}));\n\t}\n\n\tprivate async dbTransaction<T>(className: string, fn: (client: pg.PoolClient) => Promise<T>): Promise<T> {\n\t\tconst pool = await this.newDBConnection();\n\t\tconst logger = this.methodLogger(className);\n\n\t\tconst debugForceIndexScan = this.debugForceIndexScan;\n\n\t\tconst result = await this.runWithRetry(async function() {\n\t\t\tconst client = await pool.connect();\n\n\t\t\ttry {\n\t\t\t\tlogger?.debug('Starting DB transaction');\n\t\t\t\tawait client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');\n\t\t\t\tlogger?.debug('DB transaction started');\n\n\t\t\t\tif (debugForceIndexScan) {\n\t\t\t\t\tawait client.query('SET LOCAL enable_seqscan TO off');\n\t\t\t\t}\n\n\t\t\t\tconst retval = await fn(client);\n\n\t\t\t\tlogger?.debug('Committing DB transaction');\n\t\t\t\tawait client.query('COMMIT');\n\t\t\t\tlogger?.debug('DB transaction committed');\n\n\t\t\t\treturn(retval);\n\t\t\t} catch (error: unknown) {\n\t\t\t\ttry {\n\t\t\t\t\tlogger?.debug('Rolling back DB transaction due to error:', error);\n\t\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\t\tlogger?.debug('DB transaction rolled back');\n\t\t\t\t} catch {\n\t\t\t\t\tlogger?.debug('Error rolling back DB transaction !!');\n\t\t\t\t}\n\t\t\t\tthrow(error);\n\t\t\t} finally {\n\t\t\t\tclient.release();\n\t\t\t}\n\t\t});\n\n\t\treturn(result);\n\t}\n\n\tasync add(request: KeetaAnchorQueueRequest<QueueRequest>, info?: KeetaAnchorQueueEntryExtra): Promise<KeetaAnchorQueueRequestID> {\n\t\treturn(await this.dbTransaction('add', async (client): Promise<KeetaAnchorQueueRequestID> => {\n\t\t\tconst logger = this.methodLogger('add');\n\t\t\tlet entryID = ConvertStringToRequestID(info?.id);\n\t\t\tentryID ??= ConvertStringToRequestID(crypto.randomUUID());\n\n\t\t\tlogger?.debug(`Enqueuing request with id ${String(entryID)}`);\n\n\t\t\tconst currentTime = Date.now();\n\t\t\tconst requestJSON = JSON.stringify(request);\n\n\t\t\t/**\n\t\t\t * The status to use for the new entry\n\t\t\t */\n\t\t\tconst status = info?.status ?? 'pending';\n\n\n\t\t\tconst insertedEntry = await client.query<{ id: string }>(`\n\t\t\t\tINSERT INTO ${this.tableNameEntries} (\n\t\t\t\t\tid, path, request, output, last_error, status,\n\t\t\t\t\tcreated, updated, worker, failures\n\t\t\t\t) VALUES ($1, $2, $3, NULL, NULL, $4, $5, $6, NULL, 0)\n\t\t\t\tON CONFLICT (id, path) DO NOTHING\n\t\t\t\tRETURNING id`,\n\t\t\t[entryID, this.pathStr, requestJSON, status, currentTime, currentTime]);\n\n\t\t\tif (insertedEntry.rows.length === 0) {\n\t\t\t\tlogger?.debug(`Request with id ${String(entryID)} already exists, ignoring`);\n\t\t\t\treturn(entryID);\n\t\t\t}\n\n\t\t\tawait this.toctouDelay?.();\n\n\t\t\tconst idempotentIDs = info?.idempotentKeys;\n\t\t\tif (idempotentIDs && idempotentIDs.size > 0) {\n\t\t\t\tconst keys = Array.from(idempotentIDs);\n\n\t\t\t\tconst insertedKeys = await client.query<{ idempotent_id: string }>(`\n\t\t\t\t\tINSERT INTO ${this.tableNameIdempotentKeys}(entry_id, path, idempotent_id)\n\t\t\t\t\tSELECT $1, $2, unnest($3::text[])\n\t\t\t\t\tON CONFLICT (idempotent_id, path) DO NOTHING\n\t\t\t\t\tRETURNING idempotent_id`,\n\t\t\t\t[entryID, this.pathStr, keys]);\n\n\t\t\t\tconst foundKeySet = new Set(keys);\n\t\t\t\tfor (const row of insertedKeys.rows) {\n\t\t\t\t\tfoundKeySet.delete(ConvertStringToRequestID(row.idempotent_id));\n\t\t\t\t}\n\n\t\t\t\tif (insertedKeys.rows.length !== keys.length) {\n\t\t\t\t\tthrow(new Errors.IdempotentExistsError('One or more idempotent entries already exist in the queue', foundKeySet));\n\t\t\t\t}\n\n\t\t\t\tawait this.toctouDelay?.();\n\t\t\t}\n\n\t\t\treturn(entryID);\n\t\t}));\n\t}\n\n\tasync setStatus(id: KeetaAnchorQueueRequestID, status: KeetaAnchorQueueStatus, ancillary?: KeetaAnchorQueueEntryAncillaryData<QueueResult>): Promise<void> {\n\t\tconst { oldStatus } = ancillary ?? {};\n\n\t\treturn(await this.dbTransaction('setStatus', async (client): Promise<void> => {\n\t\t\tconst logger = this.methodLogger('setStatus');\n\t\t\tconst existingEntry = await client.query<{ status: KeetaAnchorQueueStatus; failures: number; last_error: string | null; output: string | null }>(`SELECT status, failures, last_error, output FROM ${this.tableNameEntries} WHERE id = $1 AND path = $2 FOR UPDATE`, [id, this.pathStr]);\n\t\t\tif (existingEntry.rows.length === 0) {\n\t\t\t\tthrow(new Error(`Request with ID ${String(id)} not found`));\n\t\t\t}\n\n\t\t\tawait this.toctouDelay?.();\n\n\t\t\tconst currentEntry = existingEntry.rows[0];\n\t\t\tif (!currentEntry) {\n\t\t\t\tthrow(new Error(`Request with ID ${String(id)} not found`));\n\t\t\t}\n\n\t\t\tconst result = await this.writeStatusUpdate(client, id, currentEntry, status, ancillary, logger);\n\n\t\t\tawait this.toctouDelay?.();\n\n\t\t\tif (oldStatus && result.rowCount === 0) {\n\t\t\t\tconst currentEntry = await client.query<{ status: KeetaAnchorQueueStatus }>(`SELECT status FROM ${this.tableNameEntries} WHERE id = $1 AND path = $2`, [id, this.pathStr]);\n\t\t\t\tconst currentStatus = currentEntry.rows[0]?.status;\n\t\t\t\tif (currentEntry.rows.length > 0) {\n\t\t\t\t\tif (currentStatus === undefined) {\n\t\t\t\t\t\tthrow(new Error(`internal error: could not retrieve current status for request with ID ${String(id)}`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow(new Errors.IncorrectStateAssertedError(id, oldStatus, currentStatus));\n\t\t\t\t} else {\n\t\t\t\t\tthrow(new Error(`Request with ID ${String(id)} not found`));\n\t\t\t\t}\n\t\t\t}\n\t\t}));\n\t}\n\n\t/**\n\t * Write a status change to an entry whose current values the\n\t * caller has read (and locked), so every status change goes through\n\t * {@link ManageStatusUpdates}. With `oldStatus` the UPDATE also\n\t * requires the entry to still be in that status.\n\t */\n\tprivate async writeStatusUpdate(client: pg.PoolClient, id: KeetaAnchorQueueRequestID, currentEntry: Pick<QueueEntryRow, 'status' | 'failures' | 'last_error' | 'output'>, status: KeetaAnchorQueueStatus, ancillary: KeetaAnchorQueueEntryAncillaryData<QueueResult> | undefined, logger: Logger | undefined): Promise<pg.QueryResult> {\n\t\tconst newEntry = ManageStatusUpdates<QueueResult>(id, currentEntry, status, ancillary, logger);\n\t\tlet newLastError = currentEntry.last_error;\n\t\tif (newEntry.lastError !== undefined) {\n\t\t\tnewLastError = newEntry.lastError;\n\t\t}\n\t\tlet newOutput = currentEntry.output;\n\t\tif (newEntry.output !== undefined) {\n\t\t\tnewOutput = JSON.stringify(newEntry.output);\n\t\t}\n\n\t\tconst params: (KeetaAnchorQueueRequestID | string | number | null)[] = [status, newEntry.updated.getTime(), newEntry.worker, newEntry.failures ?? currentEntry.failures, newLastError, newOutput, id, this.pathStr];\n\t\tlet text = `UPDATE ${this.tableNameEntries}\n\t\t SET status = $1, updated = $2, worker = $3, failures = $4, last_error = $5, output = $6\n\t\t WHERE id = $7 AND path = $8`;\n\t\tif (ancillary?.oldStatus) {\n\t\t\ttext += ' AND status = $9';\n\t\t\tparams.push(ancillary.oldStatus);\n\t\t}\n\n\t\treturn(await client.query(text, params));\n\t}\n\n\tasync get(id: KeetaAnchorQueueRequestID): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null> {\n\t\treturn(await this.dbTransaction('get', async (client): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null> => {\n\t\t\tconst row = await client.query<QueueEntryRow>(\n\t\t\t\t`SELECT id, request, output, last_error, status, created, updated, worker, failures\n\t\t\t\t FROM ${this.tableNameEntries} WHERE id = $1 AND path = $2`,\n\t\t\t\t[id, this.pathStr]\n\t\t\t);\n\n\t\t\tif (row.rows.length === 0) {\n\t\t\t\treturn(null);\n\t\t\t}\n\n\t\t\tconst entry = row.rows[0];\n\t\t\tif (!entry) {\n\t\t\t\treturn(null);\n\t\t\t}\n\n\t\t\treturn(await this.decodeEntryRow(client, entry));\n\t\t}));\n\t}\n\n\t/**\n\t * Turn an entries row into a queue entry, with its idempotent keys\n\t */\n\tprivate async decodeEntryRow(client: pg.PoolClient, row: QueueEntryRow): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult>> {\n\t\tconst idempotentRows = await client.query<IdempotentRow>(\n\t\t\t`SELECT idempotent_id FROM ${this.tableNameIdempotentKeys} WHERE entry_id = $1 AND path = $2`,\n\t\t\t[row.id, this.pathStr]\n\t\t);\n\n\t\tlet idempotentKeys: Set<KeetaAnchorQueueRequestID> | undefined = undefined;\n\t\tif (idempotentRows.rows.length > 0) {\n\t\t\tidempotentKeys = new Set(idempotentRows.rows.map(function(idempotentRow: IdempotentRow) {\n\t\t\t\treturn(ConvertStringToRequestID(idempotentRow.idempotent_id));\n\t\t\t}));\n\t\t}\n\n\t\treturn({\n\t\t\tid: ConvertStringToRequestID(row.id),\n\t\t\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n\t\t\trequest: JSON.parse(row.request) as QueueRequest,\n\t\t\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n\t\t\toutput: row.output ? JSON.parse(row.output) as QueueResult : null,\n\t\t\tlastError: row.last_error,\n\t\t\tstatus: row.status,\n\t\t\tcreated: new Date(Number(row.created)),\n\t\t\tupdated: new Date(Number(row.updated)),\n\t\t\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n\t\t\tworker: row.worker as unknown as KeetaAnchorQueueWorkerID | null,\n\t\t\tfailures: row.failures,\n\t\t\tidempotentKeys: idempotentKeys\n\t\t});\n\t}\n\n\t/**\n\t * Move the oldest entry in a status to \"processing\" for a worker.\n\t *\n\t * SKIP LOCKED makes concurrent claims lock different rows.\n\t * Postgres locks rows below the LIMIT, so a row that left the status\n\t * after the statement started is re-checked and passed over, and\n\t * the scan moves on to the next one. The row stays locked until\n\t * the transaction commits, so the UPDATE cannot lose it. The entry\n\t * is returned as it was before the claim.\n\t */\n\tasync claimNext(status: KeetaAnchorQueueStatus, worker: KeetaAnchorQueueWorkerID): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null> {\n\t\treturn(await this.dbTransaction('claimNext', async (client): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null> => {\n\t\t\tconst result = await client.query<QueueEntryRow>(\n\t\t\t\t`SELECT id, request, output, last_error, status, created, updated, worker, failures\n\t\t\t\t FROM ${this.tableNameEntries}\n\t\t\t\t WHERE path = $1 AND status = $2\n\t\t\t\t ORDER BY updated, id\n\t\t\t\t LIMIT 1\n\t\t\t\t FOR UPDATE SKIP LOCKED`,\n\t\t\t\t[this.pathStr, status]\n\t\t\t);\n\n\t\t\tconst row = result.rows[0];\n\t\t\tif (row === undefined) {\n\t\t\t\treturn(null);\n\t\t\t}\n\n\t\t\tconst id = ConvertStringToRequestID(row.id);\n\t\t\tawait this.writeStatusUpdate(client, id, row, 'processing', { oldStatus: status, by: worker }, this.methodLogger('claimNext'));\n\n\t\t\treturn(await this.decodeEntryRow(client, row));\n\t\t}));\n\t}\n\n\t/**\n\t * Build the SQL for {@link query}, ordered as the storage driver\n\t * contract requires (oldest updated first, ties by id) so that the\n\t * (path, status, updated, id) index serves both the filter and the\n\t * order\n\t */\n\tprivate buildQuerySQL(filter?: KeetaAnchorQueueFilter): { text: string; params: (string | number)[]; } {\n\t\tconst conditions: string[] = [];\n\t\tconst params: (string | number)[] = [];\n\t\tlet paramIndex = 1;\n\n\t\tconditions.push(`path = $${paramIndex++}`);\n\t\tparams.push(this.pathStr);\n\n\t\tif (filter?.status) {\n\t\t\tconditions.push(`status = $${paramIndex++}`);\n\t\t\tparams.push(filter.status);\n\t\t}\n\n\t\tif (filter?.updatedBefore) {\n\t\t\tconditions.push(`updated < $${paramIndex++}`);\n\t\t\tparams.push(filter.updatedBefore.getTime());\n\t\t}\n\n\t\tlet text = `SELECT id, request, output, last_error, status, created, updated, worker, failures FROM ${this.tableNameEntries}`;\n\t\ttext += ' WHERE ' + conditions.join(' AND ');\n\t\ttext += ' ORDER BY updated, id';\n\n\t\tif (filter?.limit !== undefined) {\n\t\t\ttext += ` LIMIT $${paramIndex++}`;\n\t\t\tparams.push(filter.limit);\n\t\t}\n\n\t\treturn({ text: text, params: params });\n\t}\n\n\tasync query(filter?: KeetaAnchorQueueFilter): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult>[]> {\n\t\treturn(await this.dbTransaction('query', async (client): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult>[]> => {\n\t\t\tconst logger = this.methodLogger('query');\n\t\t\tlogger?.debug(`Querying queue with id ${this.id} with filter:`, filter);\n\n\t\t\tconst { text, params } = this.buildQuerySQL(filter);\n\t\t\tconst rows = await client.query<QueueEntryRow>(text, params);\n\n\t\t\tconst entries = await Promise.all(rows.rows.map(async (row) => {\n\t\t\t\treturn(await this.decodeEntryRow(client, row));\n\t\t\t}));\n\n\t\t\tlogger?.debug(`Queried queue with id ${this.id} with filter:`, filter, '-- found', entries.length, 'entries');\n\n\t\t\treturn(entries);\n\t\t}));\n\t}\n\n\tasync delete(input: KeetaAnchorQueueDeleteInput[]): Promise<void> {\n\t\tif (input.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.dbTransaction('delete', async (client): Promise<void> => {\n\t\t\tconst logger = this.methodLogger('delete');\n\t\t\tconst ids = input.map(function(entry) {\n\t\t\t\treturn(String(entry.id));\n\t\t\t});\n\t\t\tconst statuses = input.map(function(entry) {\n\t\t\t\treturn(entry.status);\n\t\t\t});\n\n\t\t\tconst deletedRows = await client.query<{ id: string }>(\n\t\t\t\t`WITH targets(id, status) AS (\n\t\t\t\t\tSELECT * FROM unnest($2::text[], $3::text[])\n\t\t\t\t),\n\t\t\t\tdeleted_idempotent AS (\n\t\t\t\t\tDELETE FROM ${this.tableNameIdempotentKeys} k\n\t\t\t\t\tUSING ${this.tableNameEntries} e, targets t\n\t\t\t\t\tWHERE k.path = $1 AND k.entry_id = e.id AND e.path = $1\n\t\t\t\t\t\tAND e.id = t.id AND e.status = t.status\n\t\t\t\t)\n\t\t\t\tDELETE FROM ${this.tableNameEntries} e\n\t\t\t\tUSING targets t\n\t\t\t\tWHERE e.path = $1 AND e.id = t.id AND e.status = t.status\n\t\t\t\tRETURNING e.id`,\n\t\t\t\t[this.pathStr, ids, statuses]\n\t\t\t);\n\n\t\t\tconst deleted = deletedRows.rowCount ?? 0;\n\t\t\tif (deleted > 0) {\n\t\t\t\tlogger?.debug(`Deleted ${deleted} entries from queue ${this.id}`);\n\t\t\t}\n\t\t});\n\t}\n\n\tasync partition(path: string) : Promise<KeetaAnchorQueueStorageDriver<QueueRequest, QueueResult>> {\n\t\tthis.methodLogger('partition')?.debug(`Creating partitioned queue storage driver for path: ${path}`);\n\n\t\tif (this.poolInternal === null) {\n\t\t\tthrow(new Error('Asked to partition but the instance has been destroyed'));\n\t\t}\n\n\t\tconst retval = new KeetaAnchorQueueStorageDriverPostgres<QueueRequest, QueueResult>({\n\t\t\tid: `${this.id}::${path}`,\n\t\t\tlogger: this.logger,\n\t\t\tpool: this.poolInternal,\n\t\t\tpath: [...this.path, path],\n\t\t\ttablePrefix: this.tablePrefix,\n\t\t\tvacuumPolicy: this.vacuumPolicy\n\t\t});\n\n\t\treturn(retval);\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tthis.methodLogger('destroy')?.debug('Destroying instance');\n\n\t\tthis.poolInternal = null;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\treturn(await this.destroy());\n\t}\n\n\t/** @internal */\n\t_Testing(key: string): {\n\t\tsetToctouDelay(delay: number): void;\n\t\tunsetToctouDelay(): void;\n\t\tgetSerializationRetryCount(): number;\n\t\tresetSerializationRetryCount(): void;\n\t\tenableDebugForceIndexScan(): void;\n\t\tdisableDebugForceIndexScan(): void;\n\t\texplainQuery(filter?: KeetaAnchorQueueFilter): Promise<string>;\n\t} {\n\t\tif (key !== 'bc81abf8-e43b-490b-b486-744fb49a5082') {\n\t\t\tthrow(new Error('This is a testing only method'));\n\t\t}\n\n\t\treturn({\n\t\t\tsetToctouDelay: (delay: number): void => {\n\t\t\t\tthis.toctouDelay = async (): Promise<void> => {\n\t\t\t\t\treturn(await asleep(delay));\n\t\t\t\t};\n\t\t\t},\n\t\t\tunsetToctouDelay: (): void => {\n\t\t\t\tthis.toctouDelay = undefined;\n\t\t\t},\n\t\t\tgetSerializationRetryCount: (): number => {\n\t\t\t\treturn(this.serializationRetryCount);\n\t\t\t},\n\t\t\tresetSerializationRetryCount: (): void => {\n\t\t\t\tthis.serializationRetryCount = 0;\n\t\t\t},\n\t\t\tenableDebugForceIndexScan: (): void => {\n\t\t\t\tthis.debugForceIndexScan = true;\n\t\t\t},\n\t\t\tdisableDebugForceIndexScan: (): void => {\n\t\t\t\tthis.debugForceIndexScan = false;\n\t\t\t},\n\t\t\texplainQuery: async (filter?: KeetaAnchorQueueFilter): Promise<string> => {\n\t\t\t\treturn(await this.dbTransaction('explainQuery', async (client): Promise<string> => {\n\t\t\t\t\tconst { text, params } = this.buildQuerySQL(filter);\n\t\t\t\t\tconst plan = await client.query<{ 'QUERY PLAN': string }>(`EXPLAIN ${text}`, params);\n\t\t\t\t\treturn(plan.rows.map(function(row) {\n\t\t\t\t\t\treturn(row['QUERY PLAN']);\n\t\t\t\t\t}).join('\\n'));\n\t\t\t\t}));\n\t\t\t}\n\t\t});\n\t}\n}\n"]}
1
+ {"version":3,"file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,CAAC,cAAc,EAAE,KAAK,EAAE,MAAM,EAAmB,EAAE;oBACjF,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;oBACpD,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,KAAK,CAA2B,WAAW,IAAI,EAAE,EAAE,MAAM,CAAC,CAAC;oBACrF,OAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,UAAS,GAAG;wBAChC,OAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC;oBAC3B,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;gBAChB,CAAC,CAAC,CAAC,CAAC;YACL,CAAC;SACD,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["// cspell:ignore seqscan autovacuum regclass reloptions SQLSTATE\n\nimport type {\n\tKeetaAnchorQueueStorageDriver,\n\tKeetaAnchorQueueStorageDriverConstructor,\n\tKeetaAnchorQueueRequest,\n\tKeetaAnchorQueueRequestID,\n\tKeetaAnchorQueueEntry,\n\tKeetaAnchorQueueEntryExtra,\n\tKeetaAnchorQueueEntryAncillaryData,\n\tKeetaAnchorQueueStatus,\n\tKeetaAnchorQueueFilter,\n\tKeetaAnchorQueueDeleteInput,\n\tKeetaAnchorQueueWorkerID\n} from '../index.ts';\nimport {\n\tMethodLogger,\n\tManageStatusUpdates,\n\tConvertStringToRequestID\n} from '../internal.js';\nimport { Errors } from '../common.js';\n\nimport { asleep } from '../../utils/asleep.js';\n\nimport type { Logger } from '../../log/index.ts';\nimport type { JSONSerializable } from '../../utils/json.js';\n\nimport type * as pg from 'pg';\n\ntype QueueEntryRow = {\n\tid: string;\n\trequest: string;\n\toutput: string | null;\n\tlast_error: string | null;\n\tstatus: KeetaAnchorQueueStatus;\n\tcreated: Date;\n\tupdated: Date;\n\tworker: number | null;\n\tfailures: number;\n};\n\ntype IdempotentRow = {\n\tidempotent_id: string;\n};\n\n/**\n * How often Postgres vacuums the queue's entries table.\n *\n * Every status change is an update to a column the queue's indexes are\n * keyed on, so it leaves a dead index entry at the oldest end of the\n * status range the entry left. That is exactly where the next query()\n * starts reading, so until a vacuum cleans the index each pick reads\n * past every entry processed since the last vacuum.\n */\nexport type KeetaAnchorQueueStorageDriverPostgresVacuumPolicy = {\n\t/**\n\t * Number of updated or deleted rows that triggers an autovacuum of\n\t * the entries table (autovacuum_vacuum_threshold)\n\t */\n\tvacuumThreshold: number;\n\n\t/**\n\t * Fraction of the table added to `vacuumThreshold`\n\t * (autovacuum_vacuum_scale_factor). A pick slows with the number of\n\t * dead entries ahead of it, but each vacuum reads every index in\n\t * full, so its cost grows with the table. A small fraction lets a\n\t * large table vacuum less often, so it does not vacuum almost\n\t * constantly.\n\t */\n\tvacuumScaleFactor: number;\n\n\t/**\n\t * Fraction of the table changed that triggers an automatic ANALYZE\n\t * (autovacuum_analyze_scale_factor)\n\t */\n\tanalyzeScaleFactor: number;\n};\n\nconst DefaultVacuumPolicy: KeetaAnchorQueueStorageDriverPostgresVacuumPolicy = {\n\tvacuumThreshold: 10_000,\n\tvacuumScaleFactor: 0.001,\n\tanalyzeScaleFactor: 0.02\n};\n\n/**\n * Postgres accepts scale factors from 0 to 100\n */\nconst MaxScaleFactor = 100;\n\n/**\n * The SQLSTATE Postgres returns when the role does not own the table\n */\nconst InsufficientPrivilegeSQLState = '42501';\n\n/**\n * The longest table prefix that keeps every table and index name within\n * the 63 bytes Postgres allows\n */\nexport const MaxTablePrefixLength = 24;\n\n/**\n * Check the vacuum policy and build the table storage parameters for it.\n * The values are written into the ALTER TABLE statement (storage\n * parameters cannot be bound), so each one must be a finite number in\n * the range Postgres accepts.\n */\nfunction VacuumPolicyStorageParameters(policy: KeetaAnchorQueueStorageDriverPostgresVacuumPolicy): { [name: string]: string } {\n\tif (!Number.isSafeInteger(policy.vacuumThreshold) || policy.vacuumThreshold < 0) {\n\t\tthrow(new Error(`Invalid vacuumThreshold ${String(policy.vacuumThreshold)}: must be a non-negative integer`));\n\t}\n\n\tfor (const [name, value] of [['vacuumScaleFactor', policy.vacuumScaleFactor], ['analyzeScaleFactor', policy.analyzeScaleFactor]] as const) {\n\t\tif (!Number.isFinite(value) || value < 0 || value > MaxScaleFactor) {\n\t\t\tthrow(new Error(`Invalid ${name} ${String(value)}: must be a number from 0 to ${MaxScaleFactor}`));\n\t\t}\n\t}\n\n\treturn({\n\t\t/*\n\t\t * Without this, a vacuum skips cleaning the indexes when\n\t\t * fewer than about 2% of the table's pages hold dead rows,\n\t\t * which is always the case for a drained range of a large\n\t\t * queue, and the dead index entries the pick reads past stay\n\t\t */\n\t\tvacuum_index_cleanup: 'on',\n\t\tautovacuum_vacuum_threshold: String(policy.vacuumThreshold),\n\t\tautovacuum_vacuum_scale_factor: String(policy.vacuumScaleFactor),\n\t\tautovacuum_analyze_scale_factor: String(policy.analyzeScaleFactor)\n\t});\n}\n\ntype KeetaAnchorQueueStorageDriverPostgresOptions = {\n\t/**\n\t * Function that returns a Postgres connection pool.\n\t */\n\tpool: () => Promise<pg.Pool>;\n\n\t/**\n\t * The prefix to use for the database tables. Defaults to 'queue',\n\t * resulting in table names 'queue_entries', 'queue_idempotent_keys',\n\t * and `queue_schema_version`. At most {@link MaxTablePrefixLength}\n\t * bytes.\n\t */\n\ttablePrefix?: string | undefined;\n\n\t/**\n\t * Vacuum settings for the entries table, applied each time the\n\t * driver initializes. Any value left out uses the default\n\t * ({@link DefaultVacuumPolicy}). Pass `false` to leave the table's\n\t * vacuum settings alone, for example when an operator manages them.\n\t */\n\tvacuumPolicy?: Partial<KeetaAnchorQueueStorageDriverPostgresVacuumPolicy> | false;\n};\n\nexport default class KeetaAnchorQueueStorageDriverPostgres<QueueRequest extends JSONSerializable = JSONSerializable, QueueResult extends JSONSerializable = JSONSerializable> implements KeetaAnchorQueueStorageDriver<QueueRequest, QueueResult> {\n\tprivate readonly logger: Logger | undefined;\n\tprivate poolInternal: (() => Promise<pg.Pool>) | null = null;\n\tprivate tablePrefix: string | undefined;\n\tprivate tableNameEntries: string;\n\tprivate tableNameSchemaVersion: string;\n\tprivate tableNameIdempotentKeys: string;\n\tprivate dbInitializationPromise: Promise<boolean> | null = null;\n\tprivate serializationRetryCount = 0;\n\tprivate debugForceIndexScan = false;\n\n\treadonly name = 'KeetaAnchorQueueStorageDriverPostgres';\n\treadonly id: string;\n\treadonly path: string[] = [];\n\tprivate readonly pathStr: string;\n\tprivate toctouDelay: (() => Promise<void>) | undefined = undefined;\n\tprivate readonly vacuumPolicy: Partial<KeetaAnchorQueueStorageDriverPostgresVacuumPolicy> | false;\n\tprivate readonly vacuumStorageParameters: { [name: string]: string } | null;\n\n\tconstructor(options: NonNullable<ConstructorParameters<KeetaAnchorQueueStorageDriverConstructor<QueueRequest, QueueResult>>[0]> & KeetaAnchorQueueStorageDriverPostgresOptions) {\n\t\tthis.id = options?.id ?? crypto.randomUUID();\n\t\tthis.logger = options?.logger;\n\t\tthis.tablePrefix = options?.tablePrefix;\n\t\tif (this.tablePrefix !== undefined && new TextEncoder().encode(this.tablePrefix).length > MaxTablePrefixLength) {\n\t\t\tthrow(new Error(`Invalid tablePrefix: must be at most ${MaxTablePrefixLength} bytes`));\n\t\t}\n\t\tthis.poolInternal = options.pool;\n\t\tthis.vacuumPolicy = options.vacuumPolicy ?? {};\n\t\tthis.vacuumStorageParameters = null;\n\t\tif (this.vacuumPolicy !== false) {\n\t\t\tthis.vacuumStorageParameters = VacuumPolicyStorageParameters({ ...DefaultVacuumPolicy, ...this.vacuumPolicy });\n\t\t}\n\t\tthis.path = options.path ?? [];\n\t\tthis.pathStr = ['root', ...this.path].join('.');\n\t\tObject.freeze(this.path);\n\n\t\tthis.tableNameEntries = `${this.tablePrefix ?? 'queue'}_entries`;\n\t\tthis.tableNameIdempotentKeys = `${this.tablePrefix ?? 'queue'}_idempotent_keys`;\n\t\tthis.tableNameSchemaVersion = `${this.tablePrefix ?? 'queue'}_schema_version`;\n\n\t\tthis.methodLogger('new')?.debug('Initialized Postgres queue storage driver');\n\t}\n\n\tprivate async initializeDBConnection(pool: pg.Pool): Promise<pg.Pool> {\n\t\tconst logger = this.methodLogger('initializeDBConnection');\n\n\t\tif (this.dbInitializationPromise !== null) {\n\t\t\tlogger?.debug('DB schema initialization already in progress or completed, waiting for it to finish');\n\n\t\t\tawait this.dbInitializationPromise;\n\t\t\treturn(pool);\n\t\t}\n\n\t\tthis.dbInitializationPromise = (async () => {\n\t\t\tlogger?.debug('Initializing DB schema for queue storage driver on tables', [this.tableNameEntries, this.tableNameIdempotentKeys]);\n\n\t\t\tconst client = await pool.connect();\n\t\t\ttry {\n\t\t\t\t/*\n\t\t\t\t * Random lock key (32-bit integer), to ensure\n\t\t\t\t * that multiple instances of this driver\n\t\t\t\t * (potentially across different\n\t\t\t\t * instances/process) will run the migration\n\t\t\t\t * sequentially to avoid multiple concurrent\n\t\t\t\t * migrations from competing with each other\n\t\t\t\t * and causing delays\n\t\t\t\t */\n\t\t\t\tconst lockId = 0x24995E48;\n\t\t\t\tlogger?.debug('Acquiring advisory lock for schema migration');\n\t\t\t\tawait client.query('SELECT pg_advisory_lock($1)', [lockId]);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Create schema version table if it doesn't exist\n\t\t\t\t\tawait client.query(`\n\t\t\t\t\t\tCREATE TABLE IF NOT EXISTS ${this.tableNameSchemaVersion} (\n\t\t\t\t\t\t\tversion INTEGER NOT NULL,\n\t\t\t\t\t\t\tapplied_at BIGINT NOT NULL,\n\t\t\t\t\t\t\tPRIMARY KEY (version)\n\t\t\t\t\t\t)`);\n\n\t\t\t\t\t// Check current schema version\n\t\t\t\t\tconst versionResult = await client.query<{ version: number }>(`SELECT MAX(version) as version FROM ${this.tableNameSchemaVersion}`);\n\t\t\t\t\tconst currentVersion = versionResult.rows[0]?.version ?? 0;\n\n\t\t\t\t\tlogger?.debug(`Current queue schema version: ${currentVersion}`);\n\n\t\t\t\t\t// Version 1: Initial schema\n\t\t\t\t\tif (currentVersion < 1) {\n\t\t\t\t\t\tlogger?.debug('Applying schema version 1: Initial tables and indexes');\n\n\t\t\t\t\t\tawait client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait client.query(`\n\t\t\t\t\t\t\t\tCREATE TABLE IF NOT EXISTS ${this.tableNameEntries} (\n\t\t\t\t\t\t\t\t\tid TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tpath TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\trequest TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\toutput TEXT,\n\t\t\t\t\t\t\t\t\tlast_error TEXT,\n\t\t\t\t\t\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tcreated BIGINT NOT NULL,\n\t\t\t\t\t\t\t\t\tupdated BIGINT NOT NULL,\n\t\t\t\t\t\t\t\t\tworker BIGINT,\n\t\t\t\t\t\t\t\t\tfailures INTEGER NOT NULL DEFAULT 0,\n\t\t\t\t\t\t\t\t\tPRIMARY KEY (id, path)\n\t\t\t\t\t\t\t\t)`);\n\n\t\t\t\t\t\t\tawait client.query(`\n\t\t\t\t\t\t\t\tCREATE TABLE IF NOT EXISTS ${this.tableNameIdempotentKeys} (\n\t\t\t\t\t\t\t\t\tentry_id TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tidempotent_id TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tpath TEXT NOT NULL,\n\t\t\t\t\t\t\t\t\tUNIQUE (idempotent_id, path),\n\t\t\t\t\t\t\t\t\tPRIMARY KEY (entry_id, idempotent_id, path),\n\t\t\t\t\t\t\t\t\tFOREIGN KEY (entry_id, path) REFERENCES ${this.tableNameEntries}(id, path)\n\t\t\t\t\t\t\t\t)`);\n\n\t\t\t\t\t\t\t// Old single-column indexes (for pre-version-2 schemas)\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_status ON ${this.tableNameEntries}(status)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_updated ON ${this.tableNameEntries}(updated)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameIdempotentKeys}_idempotent_id ON ${this.tableNameIdempotentKeys}(idempotent_id)`);\n\n\t\t\t\t\t\t\tawait client.query(`INSERT INTO ${this.tableNameSchemaVersion} (version, applied_at) VALUES (1, $1)`, [Date.now()]);\n\t\t\t\t\t\t\tawait client.query('COMMIT');\n\t\t\t\t\t\t\tlogger?.debug('Applied schema version 1');\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\t\t\t\tthrow(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Version 2: Partition-aware composite indexes\n\t\t\t\t\tif (currentVersion < 2) {\n\t\t\t\t\t\tlogger?.debug('Applying schema version 2: Partition-aware composite indexes');\n\n\t\t\t\t\t\t// Now drop old indexes and record version\n\t\t\t\t\t\tawait client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Create new partition-aware indexes\n\t\t\t\t\t\t\tlogger?.debug('Creating partition-aware indexes...');\n\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_status ON ${this.tableNameEntries}(path, status)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_updated ON ${this.tableNameEntries}(path, updated)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_status_updated ON ${this.tableNameEntries}(path, status, updated)`);\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameIdempotentKeys}_path_idempotent_id ON ${this.tableNameIdempotentKeys}(path, idempotent_id)`);\n\n\t\t\t\t\t\t\t// Drop old indexes that are now redundant (these will fail gracefully if indexes don't exist)\n\t\t\t\t\t\t\tlogger?.debug('Dropping old single-column indexes...');\n\t\t\t\t\t\t\tawait client.query(`DROP INDEX IF EXISTS idx_${this.tableNameEntries}_status`);\n\t\t\t\t\t\t\tawait client.query(`DROP INDEX IF EXISTS idx_${this.tableNameEntries}_updated`);\n\t\t\t\t\t\t\tawait client.query(`DROP INDEX IF EXISTS idx_${this.tableNameIdempotentKeys}_idempotent_id`);\n\n\t\t\t\t\t\t\tawait client.query(`INSERT INTO ${this.tableNameSchemaVersion} (version, applied_at) VALUES (2, $1)`, [Date.now()]);\n\t\t\t\t\t\t\tawait client.query('COMMIT');\n\t\t\t\t\t\t\tlogger?.debug('Applied schema version 2');\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\t\t\t\tthrow(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Version 3: Index that serves the query() order (oldest updated first, ties by id)\n\t\t\t\t\tif (currentVersion < 3) {\n\t\t\t\t\t\tlogger?.debug('Applying schema version 3: Queue order index');\n\n\t\t\t\t\t\tawait client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * The new index serves every query the old one did\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tawait client.query(`DROP INDEX IF EXISTS idx_${this.tableNameEntries}_path_status_updated`);\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * This blocks writes to the entries table while\n\t\t\t\t\t\t\t * the index builds. For a large table, an operator\n\t\t\t\t\t\t\t * can build it ahead of time with\n\t\t\t\t\t\t\t * \"CREATE INDEX CONCURRENTLY\" under the same name,\n\t\t\t\t\t\t\t * and this step then only drops the old index.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tawait client.query(`CREATE INDEX IF NOT EXISTS idx_${this.tableNameEntries}_path_status_updated_id ON ${this.tableNameEntries}(path, status, updated, id)`);\n\n\t\t\t\t\t\t\tawait client.query(`INSERT INTO ${this.tableNameSchemaVersion} (version, applied_at) VALUES (3, $1)`, [Date.now()]);\n\t\t\t\t\t\t\tawait client.query('COMMIT');\n\t\t\t\t\t\t\tlogger?.debug('Applied schema version 3');\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\t\t\t\tthrow(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tlogger?.debug('Schema is up to date');\n\n\t\t\t\t\tawait this.applyVacuumPolicy(client);\n\t\t\t\t} finally {\n\t\t\t\t\t// Always release the advisory lock\n\t\t\t\t\t// Note: Advisory locks are session-based and auto-release on disconnect,\n\t\t\t\t\t// but we explicitly unlock for clarity and to avoid holding locks longer than needed\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlogger?.debug('Releasing advisory lock');\n\t\t\t\t\t\tawait client.query('SELECT pg_advisory_unlock($1)', [lockId]);\n\t\t\t\t\t} catch (unlockError) {\n\t\t\t\t\t\t// Log but don't throw - the lock will be auto-released when connection closes\n\t\t\t\t\t\tlogger?.debug('Failed to explicitly release advisory lock (will auto-release on disconnect):', unlockError);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tclient.release();\n\t\t\t}\n\n\t\t\tlogger?.debug('Completed DB schema initialization for queue storage driver');\n\n\t\t\treturn(true);\n\t\t})();\n\n\t\tawait this.dbInitializationPromise;\n\n\t\treturn(pool);\n\t}\n\n\t/**\n\t * Set the entries table's vacuum storage parameters to the\n\t * configured policy. This runs on every initialization rather than\n\t * as a versioned migration, so an upgraded database gets the\n\t * settings and a changed policy takes effect. The table is only\n\t * altered when its settings differ.\n\t *\n\t * Changing storage parameters requires owning the table. Without\n\t * that privilege the queue still works, only more slowly while a\n\t * large backlog drains, so a warning is logged and startup goes on.\n\t */\n\tprivate async applyVacuumPolicy(client: pg.PoolClient): Promise<void> {\n\t\tconst logger = this.methodLogger('applyVacuumPolicy');\n\t\tconst wanted = this.vacuumStorageParameters;\n\t\tif (wanted === null) {\n\t\t\tlogger?.debug('Vacuum policy disabled, leaving the entries table settings alone');\n\t\t\treturn;\n\t\t}\n\n\t\tconst current = await client.query<{ reloptions: string[] | null }>('SELECT reloptions FROM pg_class WHERE oid = to_regclass($1)', [this.tableNameEntries]);\n\t\tconst currentParameters = new Map<string, string>();\n\t\tfor (const option of current.rows[0]?.reloptions ?? []) {\n\t\t\tconst separator = option.indexOf('=');\n\t\t\tcurrentParameters.set(option.slice(0, separator), option.slice(separator + 1));\n\t\t}\n\n\t\tconst differs = Object.entries(wanted).some(function([name, value]) {\n\t\t\treturn(currentParameters.get(name) !== value);\n\t\t});\n\t\tif (!differs) {\n\t\t\tlogger?.debug('Entries table vacuum settings are up to date');\n\t\t\treturn;\n\t\t}\n\n\t\tconst assignments = Object.entries(wanted).map(function([name, value]) {\n\t\t\treturn(`${name} = ${value}`);\n\t\t});\n\n\t\ttry {\n\t\t\tawait client.query(`ALTER TABLE ${this.tableNameEntries} SET (${assignments.join(', ')})`);\n\t\t\tlogger?.debug('Applied entries table vacuum settings:', assignments);\n\t\t} catch (error: unknown) {\n\t\t\tif (typeof error === 'object' && error !== null && 'code' in error && error.code === InsufficientPrivilegeSQLState) {\n\t\t\t\tlogger?.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);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow(error);\n\t\t}\n\t}\n\n\tprivate methodLogger(method: string): Logger | undefined {\n\t\treturn(MethodLogger(this.logger, {\n\t\t\tclass: 'KeetaAnchorQueueStorageDriverPostgres',\n\t\t\tfile: 'src/lib/queue/drivers/queue_postgres.ts',\n\t\t\tmethod: method,\n\t\t\tinstanceID: this.id\n\t\t}));\n\t}\n\n\tprivate async runWithRetry<T>(fn: () => Promise<T>): Promise<T> {\n\t\tconst logger = this.methodLogger('runWithRetry');\n\n\t\tlet lastError: unknown;\n\t\tfor (let retry = 0; retry < 16; retry++) {\n\t\t\tif (this.poolInternal === null) {\n\t\t\t\tlogger?.debug('Aborting DB operation retries because the instance was destroyed');\n\n\t\t\t\tif (lastError !== undefined) {\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/only-throw-error\n\t\t\t\t\tthrow(lastError);\n\t\t\t\t}\n\t\t\t\tthrow(new Error('Aborting because the instance was destroyed'));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\treturn(await fn());\n\t\t\t} catch (error: unknown) {\n\t\t\t\tlastError = error;\n\n\t\t\t\tlet detectedRetryableError = false;\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tconst errorCode = 'code' in error ? error.code : null;\n\t\t\t\t\tif (errorCode === '40001' || errorCode === '40P01') {\n\t\t\t\t\t\t// Track serialization retries for instrumentation\n\t\t\t\t\t\tthis.serializationRetryCount++;\n\n\t\t\t\t\t\tdetectedRetryableError = true;\n\t\t\t\t\t\tlogger?.debug('Detected retryable error with code', errorCode);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (detectedRetryableError) {\n\t\t\t\t\tconst minBackoff = 100;\n\t\t\t\t\tconst maxBackoff = 30_000;\n\t\t\t\t\tconst backoffIntervalSize = Math.min(maxBackoff - minBackoff, (retry + 50) ** 2);\n\t\t\t\t\tconst backoff = Math.round((Math.random() * backoffIntervalSize)) + minBackoff;\n\n\t\t\t\t\tlogger?.debug(`Retrying DB operation in ${backoff}ms (retry #${retry}) from`, new Error().stack);\n\t\t\t\t\tawait asleep(backoff);\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tthrow(error);\n\t\t\t}\n\t\t}\n\t\tthrow(lastError);\n\t}\n\n\tprivate async newDBConnection(): Promise<pg.Pool> {\n\t\tif (this.poolInternal === null) {\n\t\t\tthrow(new Error('Database connection is not available'));\n\t\t}\n\n\t\treturn(await this.runWithRetry(async () => {\n\t\t\tif (this.poolInternal === null) {\n\t\t\t\tthrow(new Error('Database connection is not available'));\n\t\t\t}\n\n\t\t\tthis.methodLogger('newDBConnection')?.debug('Getting DB pool');\n\t\t\tconst pool = await this.poolInternal();\n\n\t\t\treturn(await this.initializeDBConnection(pool));\n\t\t}));\n\t}\n\n\tprivate async dbTransaction<T>(className: string, fn: (client: pg.PoolClient) => Promise<T>): Promise<T> {\n\t\tconst pool = await this.newDBConnection();\n\t\tconst logger = this.methodLogger(className);\n\n\t\tconst debugForceIndexScan = this.debugForceIndexScan;\n\n\t\tconst result = await this.runWithRetry(async function() {\n\t\t\tconst client = await pool.connect();\n\n\t\t\ttry {\n\t\t\t\tlogger?.debug('Starting DB transaction');\n\t\t\t\tawait client.query('BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED');\n\t\t\t\tlogger?.debug('DB transaction started');\n\n\t\t\t\tif (debugForceIndexScan) {\n\t\t\t\t\tawait client.query('SET LOCAL enable_seqscan TO off');\n\t\t\t\t}\n\n\t\t\t\tconst retval = await fn(client);\n\n\t\t\t\tlogger?.debug('Committing DB transaction');\n\t\t\t\tawait client.query('COMMIT');\n\t\t\t\tlogger?.debug('DB transaction committed');\n\n\t\t\t\treturn(retval);\n\t\t\t} catch (error: unknown) {\n\t\t\t\ttry {\n\t\t\t\t\tlogger?.debug('Rolling back DB transaction due to error:', error);\n\t\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t\t\tlogger?.debug('DB transaction rolled back');\n\t\t\t\t} catch {\n\t\t\t\t\tlogger?.debug('Error rolling back DB transaction !!');\n\t\t\t\t}\n\t\t\t\tthrow(error);\n\t\t\t} finally {\n\t\t\t\tclient.release();\n\t\t\t}\n\t\t});\n\n\t\treturn(result);\n\t}\n\n\tasync add(request: KeetaAnchorQueueRequest<QueueRequest>, info?: KeetaAnchorQueueEntryExtra): Promise<KeetaAnchorQueueRequestID> {\n\t\treturn(await this.dbTransaction('add', async (client): Promise<KeetaAnchorQueueRequestID> => {\n\t\t\tconst logger = this.methodLogger('add');\n\t\t\tlet entryID = ConvertStringToRequestID(info?.id);\n\t\t\tentryID ??= ConvertStringToRequestID(crypto.randomUUID());\n\n\t\t\tlogger?.debug(`Enqueuing request with id ${String(entryID)}`);\n\n\t\t\tconst currentTime = Date.now();\n\t\t\tconst requestJSON = JSON.stringify(request);\n\n\t\t\t/**\n\t\t\t * The status to use for the new entry\n\t\t\t */\n\t\t\tconst status = info?.status ?? 'pending';\n\n\n\t\t\tconst insertedEntry = await client.query<{ id: string }>(`\n\t\t\t\tINSERT INTO ${this.tableNameEntries} (\n\t\t\t\t\tid, path, request, output, last_error, status,\n\t\t\t\t\tcreated, updated, worker, failures\n\t\t\t\t) VALUES ($1, $2, $3, NULL, NULL, $4, $5, $6, NULL, 0)\n\t\t\t\tON CONFLICT (id, path) DO NOTHING\n\t\t\t\tRETURNING id`,\n\t\t\t[entryID, this.pathStr, requestJSON, status, currentTime, currentTime]);\n\n\t\t\tif (insertedEntry.rows.length === 0) {\n\t\t\t\tlogger?.debug(`Request with id ${String(entryID)} already exists, ignoring`);\n\t\t\t\treturn(entryID);\n\t\t\t}\n\n\t\t\tawait this.toctouDelay?.();\n\n\t\t\tconst idempotentIDs = info?.idempotentKeys;\n\t\t\tif (idempotentIDs && idempotentIDs.size > 0) {\n\t\t\t\tconst keys = Array.from(idempotentIDs);\n\n\t\t\t\tconst insertedKeys = await client.query<{ idempotent_id: string }>(`\n\t\t\t\t\tINSERT INTO ${this.tableNameIdempotentKeys}(entry_id, path, idempotent_id)\n\t\t\t\t\tSELECT $1, $2, unnest($3::text[])\n\t\t\t\t\tON CONFLICT (idempotent_id, path) DO NOTHING\n\t\t\t\t\tRETURNING idempotent_id`,\n\t\t\t\t[entryID, this.pathStr, keys]);\n\n\t\t\t\tconst foundKeySet = new Set(keys);\n\t\t\t\tfor (const row of insertedKeys.rows) {\n\t\t\t\t\tfoundKeySet.delete(ConvertStringToRequestID(row.idempotent_id));\n\t\t\t\t}\n\n\t\t\t\tif (insertedKeys.rows.length !== keys.length) {\n\t\t\t\t\tthrow(new Errors.IdempotentExistsError('One or more idempotent entries already exist in the queue', foundKeySet));\n\t\t\t\t}\n\n\t\t\t\tawait this.toctouDelay?.();\n\t\t\t}\n\n\t\t\treturn(entryID);\n\t\t}));\n\t}\n\n\tasync setStatus(id: KeetaAnchorQueueRequestID, status: KeetaAnchorQueueStatus, ancillary?: KeetaAnchorQueueEntryAncillaryData<QueueResult>): Promise<void> {\n\t\tconst { oldStatus } = ancillary ?? {};\n\n\t\treturn(await this.dbTransaction('setStatus', async (client): Promise<void> => {\n\t\t\tconst logger = this.methodLogger('setStatus');\n\t\t\tconst existingEntry = await client.query<{ status: KeetaAnchorQueueStatus; failures: number; last_error: string | null; output: string | null }>(`SELECT status, failures, last_error, output FROM ${this.tableNameEntries} WHERE id = $1 AND path = $2 FOR UPDATE`, [id, this.pathStr]);\n\t\t\tif (existingEntry.rows.length === 0) {\n\t\t\t\tthrow(new Error(`Request with ID ${String(id)} not found`));\n\t\t\t}\n\n\t\t\tawait this.toctouDelay?.();\n\n\t\t\tconst currentEntry = existingEntry.rows[0];\n\t\t\tif (!currentEntry) {\n\t\t\t\tthrow(new Error(`Request with ID ${String(id)} not found`));\n\t\t\t}\n\n\t\t\tconst result = await this.writeStatusUpdate(client, id, currentEntry, status, ancillary, logger);\n\n\t\t\tawait this.toctouDelay?.();\n\n\t\t\tif (oldStatus && result.rowCount === 0) {\n\t\t\t\tconst currentEntry = await client.query<{ status: KeetaAnchorQueueStatus }>(`SELECT status FROM ${this.tableNameEntries} WHERE id = $1 AND path = $2`, [id, this.pathStr]);\n\t\t\t\tconst currentStatus = currentEntry.rows[0]?.status;\n\t\t\t\tif (currentEntry.rows.length > 0) {\n\t\t\t\t\tif (currentStatus === undefined) {\n\t\t\t\t\t\tthrow(new Error(`internal error: could not retrieve current status for request with ID ${String(id)}`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow(new Errors.IncorrectStateAssertedError(id, oldStatus, currentStatus));\n\t\t\t\t} else {\n\t\t\t\t\tthrow(new Error(`Request with ID ${String(id)} not found`));\n\t\t\t\t}\n\t\t\t}\n\t\t}));\n\t}\n\n\t/**\n\t * Write a status change to an entry whose current values the\n\t * caller has read (and locked), so every status change goes through\n\t * {@link ManageStatusUpdates}. With `oldStatus` the UPDATE also\n\t * requires the entry to still be in that status.\n\t */\n\tprivate async writeStatusUpdate(client: pg.PoolClient, id: KeetaAnchorQueueRequestID, currentEntry: Pick<QueueEntryRow, 'status' | 'failures' | 'last_error' | 'output'>, status: KeetaAnchorQueueStatus, ancillary: KeetaAnchorQueueEntryAncillaryData<QueueResult> | undefined, logger: Logger | undefined): Promise<pg.QueryResult> {\n\t\tconst newEntry = ManageStatusUpdates<QueueResult>(id, currentEntry, status, ancillary, logger);\n\t\tlet newLastError = currentEntry.last_error;\n\t\tif (newEntry.lastError !== undefined) {\n\t\t\tnewLastError = newEntry.lastError;\n\t\t}\n\t\tlet newOutput = currentEntry.output;\n\t\tif (newEntry.output !== undefined) {\n\t\t\tnewOutput = JSON.stringify(newEntry.output);\n\t\t}\n\n\t\tconst params: (KeetaAnchorQueueRequestID | string | number | null)[] = [status, newEntry.updated.getTime(), newEntry.worker, newEntry.failures ?? currentEntry.failures, newLastError, newOutput, id, this.pathStr];\n\t\tlet text = `UPDATE ${this.tableNameEntries}\n\t\t SET status = $1, updated = $2, worker = $3, failures = $4, last_error = $5, output = $6\n\t\t WHERE id = $7 AND path = $8`;\n\t\tif (ancillary?.oldStatus) {\n\t\t\ttext += ' AND status = $9';\n\t\t\tparams.push(ancillary.oldStatus);\n\t\t}\n\n\t\treturn(await client.query(text, params));\n\t}\n\n\tasync get(id: KeetaAnchorQueueRequestID): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null> {\n\t\treturn(await this.dbTransaction('get', async (client): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null> => {\n\t\t\tconst row = await client.query<QueueEntryRow>(\n\t\t\t\t`SELECT id, request, output, last_error, status, created, updated, worker, failures\n\t\t\t\t FROM ${this.tableNameEntries} WHERE id = $1 AND path = $2`,\n\t\t\t\t[id, this.pathStr]\n\t\t\t);\n\n\t\t\tif (row.rows.length === 0) {\n\t\t\t\treturn(null);\n\t\t\t}\n\n\t\t\tconst entry = row.rows[0];\n\t\t\tif (!entry) {\n\t\t\t\treturn(null);\n\t\t\t}\n\n\t\t\treturn(await this.decodeEntryRow(client, entry));\n\t\t}));\n\t}\n\n\t/**\n\t * Turn an entries row into a queue entry, with its idempotent keys\n\t */\n\tprivate async decodeEntryRow(client: pg.PoolClient, row: QueueEntryRow): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult>> {\n\t\tconst idempotentRows = await client.query<IdempotentRow>(\n\t\t\t`SELECT idempotent_id FROM ${this.tableNameIdempotentKeys} WHERE entry_id = $1 AND path = $2`,\n\t\t\t[row.id, this.pathStr]\n\t\t);\n\n\t\tlet idempotentKeys: Set<KeetaAnchorQueueRequestID> | undefined = undefined;\n\t\tif (idempotentRows.rows.length > 0) {\n\t\t\tidempotentKeys = new Set(idempotentRows.rows.map(function(idempotentRow: IdempotentRow) {\n\t\t\t\treturn(ConvertStringToRequestID(idempotentRow.idempotent_id));\n\t\t\t}));\n\t\t}\n\n\t\treturn({\n\t\t\tid: ConvertStringToRequestID(row.id),\n\t\t\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n\t\t\trequest: JSON.parse(row.request) as QueueRequest,\n\t\t\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n\t\t\toutput: row.output ? JSON.parse(row.output) as QueueResult : null,\n\t\t\tlastError: row.last_error,\n\t\t\tstatus: row.status,\n\t\t\tcreated: new Date(Number(row.created)),\n\t\t\tupdated: new Date(Number(row.updated)),\n\t\t\t// eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n\t\t\tworker: row.worker as unknown as KeetaAnchorQueueWorkerID | null,\n\t\t\tfailures: row.failures,\n\t\t\tidempotentKeys: idempotentKeys\n\t\t});\n\t}\n\n\t/**\n\t * Move the oldest entry in a status to \"processing\" for a worker.\n\t *\n\t * SKIP LOCKED makes concurrent claims lock different rows.\n\t * Postgres locks rows below the LIMIT, so a row that left the status\n\t * after the statement started is re-checked and passed over, and\n\t * the scan moves on to the next one. The row stays locked until\n\t * the transaction commits, so the UPDATE cannot lose it. The entry\n\t * is returned as it was before the claim.\n\t */\n\tasync claimNext(status: KeetaAnchorQueueStatus, worker: KeetaAnchorQueueWorkerID): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null> {\n\t\treturn(await this.dbTransaction('claimNext', async (client): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult> | null> => {\n\t\t\tconst result = await client.query<QueueEntryRow>(\n\t\t\t\t`SELECT id, request, output, last_error, status, created, updated, worker, failures\n\t\t\t\t FROM ${this.tableNameEntries}\n\t\t\t\t WHERE path = $1 AND status = $2\n\t\t\t\t ORDER BY updated, id\n\t\t\t\t LIMIT 1\n\t\t\t\t FOR UPDATE SKIP LOCKED`,\n\t\t\t\t[this.pathStr, status]\n\t\t\t);\n\n\t\t\tconst row = result.rows[0];\n\t\t\tif (row === undefined) {\n\t\t\t\treturn(null);\n\t\t\t}\n\n\t\t\tconst id = ConvertStringToRequestID(row.id);\n\t\t\tawait this.writeStatusUpdate(client, id, row, 'processing', { oldStatus: status, by: worker }, this.methodLogger('claimNext'));\n\n\t\t\treturn(await this.decodeEntryRow(client, row));\n\t\t}));\n\t}\n\n\t/**\n\t * Build the SQL for {@link query}, ordered as the storage driver\n\t * contract requires (oldest updated first, ties by id) so that the\n\t * (path, status, updated, id) index serves both the filter and the\n\t * order\n\t */\n\tprivate buildQuerySQL(filter?: KeetaAnchorQueueFilter): { text: string; params: (string | number)[]; } {\n\t\tconst conditions: string[] = [];\n\t\tconst params: (string | number)[] = [];\n\t\tlet paramIndex = 1;\n\n\t\tconditions.push(`path = $${paramIndex++}`);\n\t\tparams.push(this.pathStr);\n\n\t\tif (filter?.status) {\n\t\t\tconditions.push(`status = $${paramIndex++}`);\n\t\t\tparams.push(filter.status);\n\t\t}\n\n\t\tif (filter?.updatedBefore) {\n\t\t\tconditions.push(`updated < $${paramIndex++}`);\n\t\t\tparams.push(filter.updatedBefore.getTime());\n\t\t}\n\n\t\tlet text = `SELECT id, request, output, last_error, status, created, updated, worker, failures FROM ${this.tableNameEntries}`;\n\t\ttext += ' WHERE ' + conditions.join(' AND ');\n\t\ttext += ' ORDER BY updated, id';\n\n\t\tif (filter?.limit !== undefined) {\n\t\t\ttext += ` LIMIT $${paramIndex++}`;\n\t\t\tparams.push(filter.limit);\n\t\t}\n\n\t\treturn({ text: text, params: params });\n\t}\n\n\tasync query(filter?: KeetaAnchorQueueFilter): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult>[]> {\n\t\treturn(await this.dbTransaction('query', async (client): Promise<KeetaAnchorQueueEntry<QueueRequest, QueueResult>[]> => {\n\t\t\tconst logger = this.methodLogger('query');\n\t\t\tlogger?.debug(`Querying queue with id ${this.id} with filter:`, filter);\n\n\t\t\tconst { text, params } = this.buildQuerySQL(filter);\n\t\t\tconst rows = await client.query<QueueEntryRow>(text, params);\n\n\t\t\tconst entries = await Promise.all(rows.rows.map(async (row) => {\n\t\t\t\treturn(await this.decodeEntryRow(client, row));\n\t\t\t}));\n\n\t\t\tlogger?.debug(`Queried queue with id ${this.id} with filter:`, filter, '-- found', entries.length, 'entries');\n\n\t\t\treturn(entries);\n\t\t}));\n\t}\n\n\tasync delete(input: KeetaAnchorQueueDeleteInput[]): Promise<void> {\n\t\tif (input.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.dbTransaction('delete', async (client): Promise<void> => {\n\t\t\tconst logger = this.methodLogger('delete');\n\t\t\tconst ids = input.map(function(entry) {\n\t\t\t\treturn(String(entry.id));\n\t\t\t});\n\t\t\tconst statuses = input.map(function(entry) {\n\t\t\t\treturn(entry.status);\n\t\t\t});\n\n\t\t\tconst deletedRows = await client.query<{ id: string }>(\n\t\t\t\t`WITH targets(id, status) AS (\n\t\t\t\t\tSELECT * FROM unnest($2::text[], $3::text[])\n\t\t\t\t),\n\t\t\t\tdeleted_idempotent AS (\n\t\t\t\t\tDELETE FROM ${this.tableNameIdempotentKeys} k\n\t\t\t\t\tUSING ${this.tableNameEntries} e, targets t\n\t\t\t\t\tWHERE k.path = $1 AND k.entry_id = e.id AND e.path = $1\n\t\t\t\t\t\tAND e.id = t.id AND e.status = t.status\n\t\t\t\t)\n\t\t\t\tDELETE FROM ${this.tableNameEntries} e\n\t\t\t\tUSING targets t\n\t\t\t\tWHERE e.path = $1 AND e.id = t.id AND e.status = t.status\n\t\t\t\tRETURNING e.id`,\n\t\t\t\t[this.pathStr, ids, statuses]\n\t\t\t);\n\n\t\t\tconst deleted = deletedRows.rowCount ?? 0;\n\t\t\tif (deleted > 0) {\n\t\t\t\tlogger?.debug(`Deleted ${deleted} entries from queue ${this.id}`);\n\t\t\t}\n\t\t});\n\t}\n\n\tasync partition(path: string) : Promise<KeetaAnchorQueueStorageDriver<QueueRequest, QueueResult>> {\n\t\tthis.methodLogger('partition')?.debug(`Creating partitioned queue storage driver for path: ${path}`);\n\n\t\tif (this.poolInternal === null) {\n\t\t\tthrow(new Error('Asked to partition but the instance has been destroyed'));\n\t\t}\n\n\t\tconst retval = new KeetaAnchorQueueStorageDriverPostgres<QueueRequest, QueueResult>({\n\t\t\tid: `${this.id}::${path}`,\n\t\t\tlogger: this.logger,\n\t\t\tpool: this.poolInternal,\n\t\t\tpath: [...this.path, path],\n\t\t\ttablePrefix: this.tablePrefix,\n\t\t\tvacuumPolicy: this.vacuumPolicy\n\t\t});\n\n\t\treturn(retval);\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tthis.methodLogger('destroy')?.debug('Destroying instance');\n\n\t\tthis.poolInternal = null;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\treturn(await this.destroy());\n\t}\n\n\t/** @internal */\n\t_Testing(key: string): {\n\t\tsetToctouDelay(delay: number): void;\n\t\tunsetToctouDelay(): void;\n\t\tgetSerializationRetryCount(): number;\n\t\tresetSerializationRetryCount(): void;\n\t\tenableDebugForceIndexScan(): void;\n\t\tdisableDebugForceIndexScan(): void;\n\t\texplainQuery(filter?: KeetaAnchorQueueFilter): Promise<string>;\n\t} {\n\t\tif (key !== 'bc81abf8-e43b-490b-b486-744fb49a5082') {\n\t\t\tthrow(new Error('This is a testing only method'));\n\t\t}\n\n\t\treturn({\n\t\t\tsetToctouDelay: (delay: number): void => {\n\t\t\t\tthis.toctouDelay = async (): Promise<void> => {\n\t\t\t\t\treturn(await asleep(delay));\n\t\t\t\t};\n\t\t\t},\n\t\t\tunsetToctouDelay: (): void => {\n\t\t\t\tthis.toctouDelay = undefined;\n\t\t\t},\n\t\t\tgetSerializationRetryCount: (): number => {\n\t\t\t\treturn(this.serializationRetryCount);\n\t\t\t},\n\t\t\tresetSerializationRetryCount: (): void => {\n\t\t\t\tthis.serializationRetryCount = 0;\n\t\t\t},\n\t\t\tenableDebugForceIndexScan: (): void => {\n\t\t\t\tthis.debugForceIndexScan = true;\n\t\t\t},\n\t\t\tdisableDebugForceIndexScan: (): void => {\n\t\t\t\tthis.debugForceIndexScan = false;\n\t\t\t},\n\t\t\texplainQuery: async (filter?: KeetaAnchorQueueFilter): Promise<string> => {\n\t\t\t\treturn(await this.dbTransaction('explainQuery', async (client): Promise<string> => {\n\t\t\t\t\tconst { text, params } = this.buildQuerySQL(filter);\n\t\t\t\t\tconst plan = await client.query<{ 'QUERY PLAN': string }>(`EXPLAIN ${text}`, params);\n\t\t\t\t\treturn(plan.rows.map(function(row) {\n\t\t\t\t\t\treturn(row['QUERY PLAN']);\n\t\t\t\t\t}).join('\\n'));\n\t\t\t\t}));\n\t\t\t}\n\t\t});\n\t}\n}\n"]}
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@keetanetwork/anchor",
3
- "version": "0.0.111",
3
+ "version": "0.0.112",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@keetanetwork/anchor",
9
- "version": "0.0.111",
9
+ "version": "0.0.112",
10
10
  "license": "SEE LICENSE IN LICENSE",
11
11
  "dependencies": {
12
12
  "@keetanetwork/currency-info": "1.2.9",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keetanetwork/anchor",
3
- "version": "0.0.111",
3
+ "version": "0.0.112",
4
4
  "description": "KeetaNetwork Network Anchor",
5
5
  "main": "client/index.js",
6
6
  "scripts": {
@@ -5,7 +5,7 @@ import type { Logger } from '../../lib/log/index.ts';
5
5
  import type Resolver from '../../lib/resolver.ts';
6
6
  import type { ServiceMetadata, SharedLookupCriteria } from '../../lib/resolver.ts';
7
7
  import type { BrandedString } from '../../lib/utils/brand.ts';
8
- import type { ConversionInput, ConversionInputCanonical, KeetaFXAnchorEstimate, KeetaFXAnchorExchange, KeetaFXAnchorMarketPrices, KeetaFXAnchorMarketPricesRequest, KeetaFXAnchorMarketPriceRatio, KeetaFXAnchorQuote, KeetaNetTokenPublicKeyString } from './common.ts';
8
+ import type { ConversionInput, ConversionInputCanonical, KeetaFXAnchorEstimate, KeetaFXAnchorExchange, KeetaFXAnchorMarketPrices, KeetaFXAnchorMarketPricesRequest, KeetaFXAnchorMarketPriceRatio, KeetaFXAnchorQuote, KeetaNetToken, KeetaNetTokenPublicKeyString } from './common.ts';
9
9
  import type { AnchorExternalInput } from '../../lib/anchor-external.js';
10
10
  import type { AnchorMetadataLegalField, SharedAnchorMetadataLegalExtension } from '../../lib/metadata.types.js';
11
11
  import type { AnchorReference } from '../../lib/anchor-status.js';
@@ -92,6 +92,11 @@ export type KeetaFXAnchorClientConfig = {
92
92
  * - `{ waitMs, maxWaitMs? }` - custom timing (`maxWaitMs` defaults to `4 * waitMs`)
93
93
  */
94
94
  getPricesBatching?: KeetaFXAnchorClientGetPricesBatching | boolean;
95
+ /**
96
+ * Caps the client applies to every quote and estimate. See
97
+ * {@link KeetaFXAnchorClientDefaultLimits}.
98
+ */
99
+ defaultLimits?: KeetaFXAnchorClientDefaultLimits;
95
100
  } & Omit<NonNullable<Parameters<typeof getDefaultResolver>[1]>, 'client'> & AccountOptions;
96
101
  type KeetaFXAnchorOperations = {
97
102
  [operation in keyof NonNullable<ServiceMetadata['services']['fx']>[string]['operations']]: (params?: {
@@ -104,6 +109,66 @@ interface KeetaFXServiceInfo extends SharedAnchorMetadataLegalExtension {
104
109
  };
105
110
  from: NonNullable<ServiceMetadata['services']['fx']>[string]['from'];
106
111
  }
112
+ /**
113
+ * Limits the caller sets on the block that `createExchange` builds, from
114
+ * the terms it showed the user. The limits apply only when
115
+ * `createExchange` builds the block, not to a block the caller gives.
116
+ *
117
+ * The limits add to the client's `defaultLimits`; they never lift them.
118
+ * - With affinity `to`, the anchor sets the amount sent, so `maxSend` is
119
+ * required. With affinity `from`, it sets the amount received, so
120
+ * `minReceive` is required.
121
+ * - A fee in a token other than `from` or `to` needs `maxCost`, since no
122
+ * default can price it.
123
+ * - A fee in `from` or `to` must also be within `defaultLimits.maxCostBps`.
124
+ * - An estimate bound must also be within
125
+ * `defaultLimits.maxEstimateBoundBps` of its converted amount.
126
+ */
127
+ export interface KeetaFXAnchorExchangeLimits {
128
+ /**
129
+ * The most of the `from` token the block may send for the conversion,
130
+ * not counting the fee. Required for affinity `to`.
131
+ */
132
+ maxSend?: bigint;
133
+ /**
134
+ * The least of the `to` token the block may receive. Required for
135
+ * affinity `from`.
136
+ */
137
+ minReceive?: bigint;
138
+ /**
139
+ * The most the fee may be. A non-zero fee must also be in this token.
140
+ * A fee in `from` or `to` must also be within the default fee cap.
141
+ */
142
+ maxCost?: {
143
+ token: KeetaNetToken;
144
+ amount: bigint;
145
+ };
146
+ }
147
+ export interface KeetaFXAnchorCreateExchangeOptions {
148
+ inputs?: readonly AnchorExternalInput[];
149
+ limits?: KeetaFXAnchorExchangeLimits;
150
+ }
151
+ /**
152
+ * Caps `createExchange` applies to every block it builds, on top of any
153
+ * caller limits. They do not filter quotes or estimates. Set a cap to
154
+ * `null` to turn it off, or raise it to accept larger terms.
155
+ */
156
+ export interface KeetaFXAnchorClientDefaultLimits {
157
+ /**
158
+ * The most a fee in the `from` or `to` token may be, in basis points
159
+ * of the amount the conversion sends or receives in that token.
160
+ *
161
+ * Defaults to `100` (1%).
162
+ */
163
+ maxCostBps?: number | null;
164
+ /**
165
+ * The furthest an estimate's bound may be from its converted amount,
166
+ * in basis points of the converted amount.
167
+ *
168
+ * Defaults to `500` (5%).
169
+ */
170
+ maxEstimateBoundBps?: number | null;
171
+ }
107
172
  interface KeetaFXAnchorBaseConfig {
108
173
  client: KeetaNetUserClient;
109
174
  logger?: Logger | undefined;
@@ -135,13 +200,21 @@ export declare class KeetaFXAnchorProviderBase extends KeetaFXAnchorBase {
135
200
  * @returns A promise that resolves to the quote response
136
201
  */
137
202
  getQuote(estimate?: KeetaFXAnchorEstimate, tolerance?: number): Promise<KeetaFXAnchorQuote>;
203
+ /**
204
+ * Checks the terms of a quote or estimate as `createExchange` would
205
+ * before it signs, without building or sending anything. Throws the
206
+ * same errors `createExchange` would.
207
+ */
208
+ checkExchange(input: {
209
+ quote: KeetaFXAnchorQuote;
210
+ } | {
211
+ estimate: KeetaFXAnchorEstimate;
212
+ }, options?: Pick<KeetaFXAnchorCreateExchangeOptions, 'limits'>): void;
138
213
  createExchange(input: {
139
214
  quote: KeetaFXAnchorQuote;
140
215
  } | {
141
216
  estimate: KeetaFXAnchorEstimate;
142
- }, block?: InstanceType<typeof KeetaNetLib.Block>, options?: {
143
- inputs?: readonly AnchorExternalInput[];
144
- }): Promise<KeetaFXAnchorExchange>;
217
+ }, block?: InstanceType<typeof KeetaNetLib.Block>, options?: KeetaFXAnchorCreateExchangeOptions): Promise<KeetaFXAnchorExchange>;
145
218
  getMarketPrices(request: KeetaFXAnchorMarketPricesRequest): Promise<KeetaFXAnchorMarketPrices>;
146
219
  getExchangeStatus(exchangeID: string): Promise<KeetaFXAnchorExchange>;
147
220
  }
@@ -154,9 +227,8 @@ declare class KeetaFXAnchorExchangeWithProvider {
154
227
  interface CanCreateExchange {
155
228
  readonly isQuote: boolean;
156
229
  get request(): ConversionInputCanonical;
157
- createExchange(block?: InstanceType<typeof KeetaNetLib.Block>, options?: {
158
- inputs?: readonly AnchorExternalInput[];
159
- }): Promise<KeetaFXAnchorExchangeWithProvider>;
230
+ createExchange(block?: InstanceType<typeof KeetaNetLib.Block>, options?: KeetaFXAnchorCreateExchangeOptions): Promise<KeetaFXAnchorExchangeWithProvider>;
231
+ checkExchange(options?: Pick<KeetaFXAnchorCreateExchangeOptions, 'limits'>): void;
160
232
  }
161
233
  declare class KeetaFXAnchorQuoteWithProvider implements CanCreateExchange {
162
234
  readonly provider: KeetaFXAnchorProviderBase;
@@ -164,9 +236,12 @@ declare class KeetaFXAnchorQuoteWithProvider implements CanCreateExchange {
164
236
  readonly isQuote: true;
165
237
  constructor(provider: KeetaFXAnchorProviderBase, quote: KeetaFXAnchorQuote);
166
238
  get request(): ConversionInputCanonical;
167
- createExchange(block?: InstanceType<typeof KeetaNetLib.Block>, options?: {
168
- inputs?: readonly AnchorExternalInput[];
169
- }): Promise<KeetaFXAnchorExchangeWithProvider>;
239
+ createExchange(block?: InstanceType<typeof KeetaNetLib.Block>, options?: KeetaFXAnchorCreateExchangeOptions): Promise<KeetaFXAnchorExchangeWithProvider>;
240
+ /**
241
+ * Checks this quote's terms as `createExchange` would, without
242
+ * signing. See {@link KeetaFXAnchorProviderBase.checkExchange}.
243
+ */
244
+ checkExchange(options?: Pick<KeetaFXAnchorCreateExchangeOptions, 'limits'>): void;
170
245
  /**
171
246
  * Re-fetch the quote from the provider.
172
247
  *
@@ -181,9 +256,12 @@ declare class KeetaFXAnchorEstimateWithProvider implements CanCreateExchange {
181
256
  constructor(provider: KeetaFXAnchorProviderBase, estimate: KeetaFXAnchorEstimate);
182
257
  get request(): ConversionInputCanonical;
183
258
  getQuote(tolerance?: number): Promise<KeetaFXAnchorQuoteWithProvider>;
184
- createExchange(block?: InstanceType<typeof KeetaNetLib.Block>, options?: {
185
- inputs?: readonly AnchorExternalInput[];
186
- }): Promise<KeetaFXAnchorExchangeWithProvider>;
259
+ createExchange(block?: InstanceType<typeof KeetaNetLib.Block>, options?: KeetaFXAnchorCreateExchangeOptions): Promise<KeetaFXAnchorExchangeWithProvider>;
260
+ /**
261
+ * Checks this estimate's terms as `createExchange` would, without
262
+ * signing. See {@link KeetaFXAnchorProviderBase.checkExchange}.
263
+ */
264
+ checkExchange(options?: Pick<KeetaFXAnchorCreateExchangeOptions, 'limits'>): void;
187
265
  /**
188
266
  * Re-fetch the estimate from the provider.
189
267
  *
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/services/fx/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,IAAI,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EACX,UAAU,IAAI,kBAAkB,EAChC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,QAAQ,MAAM,uBAAuB,CAAC;AAClD,OAAO,KAAK,EAAE,eAAe,EAAyB,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAI1G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAS9D,OAAO,KAAK,EACX,eAAe,EACf,wBAAwB,EAExB,qBAAqB,EACrB,qBAAqB,EACrB,yBAAyB,EACzB,gCAAgC,EAChC,6BAA6B,EAC7B,kBAAkB,EAClB,4BAA4B,EAC5B,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAGxE,OAAO,KAAK,EAAE,wB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