@anatta.io/tva 0.0.0-stage → 0.2.0
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.
- package/README.md +50 -2
- package/dist/adapters/cloudflare/bindings.d.ts +10 -0
- package/dist/adapters/cloudflare/bindings.js +1 -0
- package/dist/adapters/cloudflare/blob-store.d.ts +39 -0
- package/dist/adapters/cloudflare/blob-store.js +95 -0
- package/dist/adapters/cloudflare/cache.d.ts +14 -0
- package/dist/adapters/cloudflare/cache.js +48 -0
- package/dist/adapters/cloudflare/faults.d.ts +7 -0
- package/dist/adapters/cloudflare/faults.js +39 -0
- package/dist/adapters/cloudflare/index.d.ts +15 -0
- package/dist/adapters/cloudflare/index.js +16 -0
- package/dist/adapters/cloudflare/journal.d.ts +110 -0
- package/dist/adapters/cloudflare/journal.js +325 -0
- package/dist/adapters/cloudflare/ledger.d.ts +14 -0
- package/dist/adapters/cloudflare/ledger.js +108 -0
- package/dist/adapters/cloudflare/logger.d.ts +22 -0
- package/dist/adapters/cloudflare/logger.js +49 -0
- package/dist/adapters/cloudflare/manifest.d.ts +81 -0
- package/dist/adapters/cloudflare/manifest.js +81 -0
- package/dist/adapters/cloudflare/pipelines.d.ts +97 -0
- package/dist/adapters/cloudflare/pipelines.js +218 -0
- package/dist/adapters/cloudflare/queue.d.ts +80 -0
- package/dist/adapters/cloudflare/queue.js +177 -0
- package/dist/adapters/cloudflare/retention.d.ts +24 -0
- package/dist/adapters/cloudflare/retention.js +103 -0
- package/dist/adapters/cloudflare/session-storage.d.ts +27 -0
- package/dist/adapters/cloudflare/session-storage.js +78 -0
- package/dist/adapters/cloudflare/toolkit.d.ts +16 -0
- package/dist/adapters/cloudflare/toolkit.js +57 -0
- package/dist/adapters/cloudflare/workflow-pipelines.d.ts +66 -0
- package/dist/adapters/cloudflare/workflow-pipelines.js +323 -0
- package/dist/adapters/journal-records.d.ts +80 -0
- package/dist/adapters/journal-records.js +75 -0
- package/dist/adapters/memory/blob-store.d.ts +9 -0
- package/dist/adapters/memory/blob-store.js +19 -0
- package/dist/adapters/memory/cache.d.ts +13 -0
- package/dist/adapters/memory/cache.js +36 -0
- package/dist/adapters/memory/clock.d.ts +1 -0
- package/dist/adapters/memory/clock.js +4 -0
- package/dist/adapters/memory/index.d.ts +11 -0
- package/dist/adapters/memory/index.js +11 -0
- package/dist/adapters/memory/journal.d.ts +35 -0
- package/dist/adapters/memory/journal.js +154 -0
- package/dist/adapters/memory/ledger.d.ts +9 -0
- package/dist/adapters/memory/ledger.js +33 -0
- package/dist/adapters/memory/logger.d.ts +16 -0
- package/dist/adapters/memory/logger.js +21 -0
- package/dist/adapters/memory/manifest.d.ts +59 -0
- package/dist/adapters/memory/manifest.js +59 -0
- package/dist/adapters/memory/pipelines.d.ts +62 -0
- package/dist/adapters/memory/pipelines.js +219 -0
- package/dist/adapters/memory/queue.d.ts +20 -0
- package/dist/adapters/memory/queue.js +102 -0
- package/dist/adapters/memory/session-storage.d.ts +20 -0
- package/dist/adapters/memory/session-storage.js +33 -0
- package/dist/adapters/memory/toolkit.d.ts +8 -0
- package/dist/adapters/memory/toolkit.js +31 -0
- package/dist/adapters/postgres/cache.d.ts +17 -0
- package/dist/adapters/postgres/cache.js +69 -0
- package/dist/adapters/postgres/config.d.ts +27 -0
- package/dist/adapters/postgres/config.js +45 -0
- package/dist/adapters/postgres/faults.d.ts +14 -0
- package/dist/adapters/postgres/faults.js +47 -0
- package/dist/adapters/postgres/index.d.ts +12 -0
- package/dist/adapters/postgres/index.js +12 -0
- package/dist/adapters/postgres/journal.d.ts +86 -0
- package/dist/adapters/postgres/journal.js +337 -0
- package/dist/adapters/postgres/ledger.d.ts +16 -0
- package/dist/adapters/postgres/ledger.js +97 -0
- package/dist/adapters/postgres/logger.d.ts +19 -0
- package/dist/adapters/postgres/logger.js +37 -0
- package/dist/adapters/postgres/manifest.d.ts +52 -0
- package/dist/adapters/postgres/manifest.js +53 -0
- package/dist/adapters/postgres/migrate.d.ts +20 -0
- package/dist/adapters/postgres/migrate.js +96 -0
- package/dist/adapters/postgres/queue.d.ts +64 -0
- package/dist/adapters/postgres/queue.js +333 -0
- package/dist/adapters/postgres/retention.d.ts +18 -0
- package/dist/adapters/postgres/retention.js +104 -0
- package/dist/adapters/postgres/session-storage.d.ts +20 -0
- package/dist/adapters/postgres/session-storage.js +71 -0
- package/dist/adapters/postgres/toolkit.d.ts +25 -0
- package/dist/adapters/postgres/toolkit.js +58 -0
- package/dist/adapters/postgres/with-client.d.ts +11 -0
- package/dist/adapters/postgres/with-client.js +29 -0
- package/dist/adapters/reference-executor.d.ts +171 -0
- package/dist/adapters/reference-executor.js +569 -0
- package/dist/adapters/retention.d.ts +18 -0
- package/dist/adapters/retention.js +13 -0
- package/dist/adapters/s3/blob-store.d.ts +35 -0
- package/dist/adapters/s3/blob-store.js +92 -0
- package/dist/adapters/s3/faults.d.ts +8 -0
- package/dist/adapters/s3/faults.js +34 -0
- package/dist/adapters/s3/index.d.ts +2 -0
- package/dist/adapters/s3/index.js +2 -0
- package/dist/adapters/session-envelope.d.ts +21 -0
- package/dist/adapters/session-envelope.js +122 -0
- package/dist/adapters/system-clock.d.ts +8 -0
- package/dist/adapters/system-clock.js +8 -0
- package/dist/contracts/blob-store.d.ts +11 -0
- package/dist/contracts/blob-store.js +1 -0
- package/dist/contracts/cache.d.ts +27 -0
- package/dist/contracts/cache.js +1 -0
- package/dist/contracts/duration.d.ts +23 -0
- package/dist/contracts/duration.js +27 -0
- package/dist/contracts/faults.d.ts +28 -0
- package/dist/contracts/faults.js +29 -0
- package/dist/contracts/identity.d.ts +12 -0
- package/dist/contracts/identity.js +1 -0
- package/dist/contracts/index.d.ts +14 -0
- package/dist/contracts/index.js +15 -0
- package/dist/contracts/instant.d.ts +17 -0
- package/dist/contracts/instant.js +12 -0
- package/dist/contracts/journal.d.ts +196 -0
- package/dist/contracts/journal.js +10 -0
- package/dist/contracts/ledger.d.ts +34 -0
- package/dist/contracts/ledger.js +1 -0
- package/dist/contracts/logger.d.ts +11 -0
- package/dist/contracts/logger.js +1 -0
- package/dist/contracts/manifest.d.ts +37 -0
- package/dist/contracts/manifest.js +30 -0
- package/dist/contracts/pipelines.d.ts +348 -0
- package/dist/contracts/pipelines.js +1 -0
- package/dist/contracts/queue.d.ts +55 -0
- package/dist/contracts/queue.js +1 -0
- package/dist/contracts/session-storage.d.ts +18 -0
- package/dist/contracts/session-storage.js +1 -0
- package/dist/contracts/toolkit.d.ts +21 -0
- package/dist/contracts/toolkit.js +1 -0
- package/dist/pipelines/index.d.ts +1 -0
- package/dist/pipelines/index.js +2 -0
- package/dist/pipelines/pipeline.d.ts +142 -0
- package/dist/pipelines/pipeline.js +140 -0
- package/dist/pipelines/use-case-step.d.ts +24 -0
- package/dist/pipelines/use-case-step.js +34 -0
- package/dist/schedule/schedule.d.ts +40 -0
- package/dist/schedule/schedule.js +135 -0
- package/dist/use-cases/index.d.ts +3 -0
- package/dist/use-cases/index.js +3 -0
- package/dist/use-cases/run-use-case.d.ts +33 -0
- package/dist/use-cases/run-use-case.js +117 -0
- package/dist/use-cases/use-case-consumer.d.ts +44 -0
- package/dist/use-cases/use-case-consumer.js +98 -0
- package/dist/use-cases/use-case.d.ts +116 -0
- package/dist/use-cases/use-case.js +75 -0
- package/dist/webhooks/create-webhook-handler.d.ts +63 -0
- package/dist/webhooks/create-webhook-handler.js +253 -0
- package/dist/webhooks/dead-letter-consumer.d.ts +14 -0
- package/dist/webhooks/dead-letter-consumer.js +42 -0
- package/dist/webhooks/define-registry.d.ts +42 -0
- package/dist/webhooks/define-registry.js +56 -0
- package/dist/webhooks/once.d.ts +15 -0
- package/dist/webhooks/once.js +29 -0
- package/dist/webhooks/redact-customer-bodies.d.ts +29 -0
- package/dist/webhooks/redact-customer-bodies.js +45 -0
- package/dist/webhooks/replay-webhooks.d.ts +39 -0
- package/dist/webhooks/replay-webhooks.js +82 -0
- package/dist/webhooks/sign-shopify-webhook.d.ts +14 -0
- package/dist/webhooks/sign-shopify-webhook.js +31 -0
- package/dist/webhooks/sweep-stuck-tasks.d.ts +32 -0
- package/dist/webhooks/sweep-stuck-tasks.js +73 -0
- package/dist/webhooks/webhook-consumer.d.ts +52 -0
- package/dist/webhooks/webhook-consumer.js +132 -0
- package/migrations/0001_create_ledger_claims.sql +23 -0
- package/migrations/0002_create_journal.sql +76 -0
- package/migrations/0003_create_shopify_sessions.sql +30 -0
- package/migrations/0004_create_journal_steps.sql +34 -0
- package/migrations/0007_create_job_tables.sql +71 -0
- package/migrations/0008_add_ledger_completed_at.sql +7 -0
- package/migrations/0009_create_webhook_receipts.sql +34 -0
- package/migrations/0010_index_webhook_deliveries_received_at.sql +2 -0
- package/migrations/0011_add_webhook_task_reason_code.sql +4 -0
- package/migrations/0012_rename_webhook_task_action_to_use_case.sql +11 -0
- package/migrations/0013_rename_job_tables_to_pipeline.sql +24 -0
- package/migrations/0016_add_webhook_task_requeues.sql +3 -0
- package/migrations/postgres/0001_create_ledger_claims.sql +13 -0
- package/migrations/postgres/0002_create_journal.sql +48 -0
- package/migrations/postgres/0003_create_shopify_sessions.sql +12 -0
- package/migrations/postgres/0004_create_journal_steps.sql +19 -0
- package/migrations/postgres/0005_create_cache_entries.sql +14 -0
- package/migrations/postgres/0006_create_queue.sql +42 -0
- package/migrations/postgres/0007_create_job_tables.sql +40 -0
- package/migrations/postgres/0008_add_ledger_completed_at.sql +3 -0
- package/migrations/postgres/0009_create_webhook_receipts.sql +23 -0
- package/migrations/postgres/0010_index_webhook_deliveries_received_at.sql +2 -0
- package/migrations/postgres/0011_add_webhook_task_reason_code.sql +3 -0
- package/migrations/postgres/0012_rename_webhook_task_action_to_use_case.sql +5 -0
- package/migrations/postgres/0013_rename_job_tables_to_pipeline.sql +22 -0
- package/migrations/postgres/0016_add_webhook_task_requeues.sql +3 -0
- package/package.json +144 -4
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WHAT POSTGRES PLUS S3-COMPATIBLE STORAGE ACTUALLY PROVIDES.
|
|
3
|
+
*
|
|
4
|
+
* Every value has a row in `docs/platform-facts.md`, in the table "The
|
|
5
|
+
* Postgres manifest, field by field". Postgres sets no ceiling on a delay, a
|
|
6
|
+
* message or a step result, so those three are the library's own limits, and
|
|
7
|
+
* their rows say so.
|
|
8
|
+
*/
|
|
9
|
+
export declare const POSTGRES_MANIFEST: {
|
|
10
|
+
/**
|
|
11
|
+
* `advisory`, for the reason the other two manifests give: `Ledger.claim`
|
|
12
|
+
* is a lease. A unique constraint decides a claim exactly once, but a holder
|
|
13
|
+
* that outlives its ttl is not stopped. docs/decisions/0002.
|
|
14
|
+
*/
|
|
15
|
+
readonly lock: "advisory";
|
|
16
|
+
/** `false`: `ClaimResult` carries no token to fence with. docs/decisions/0002. */
|
|
17
|
+
readonly lockFencing: false;
|
|
18
|
+
/**
|
|
19
|
+
* 7 days. `visible_at` is BIGINT milliseconds, which reaches far past this,
|
|
20
|
+
* so the limit is the library's: a delay of weeks is more likely seconds
|
|
21
|
+
* passed as milliseconds than a plan.
|
|
22
|
+
*/
|
|
23
|
+
readonly queueDelayMaxSeconds: 604800;
|
|
24
|
+
/**
|
|
25
|
+
* 1 MB. A body is TEXT, which holds about 1 GB, but a consumer claims a
|
|
26
|
+
* batch of rows at once. A payload that needs more belongs in the blob store.
|
|
27
|
+
*/
|
|
28
|
+
readonly messageMaxBytes: 1000000;
|
|
29
|
+
/** The largest single PUT, because S3BlobStore does no multipart upload. */
|
|
30
|
+
readonly blobMaxBytes: 5368709120;
|
|
31
|
+
/**
|
|
32
|
+
* Postgres expires rows by comparing epoch milliseconds, so it has no floor.
|
|
33
|
+
* 1 second is the smallest ttl a whole-second interface can ask for.
|
|
34
|
+
*/
|
|
35
|
+
readonly cacheMinTtlSeconds: 1;
|
|
36
|
+
readonly journalDialect: "postgres";
|
|
37
|
+
/** No cron here, only `startScheduler`'s intervals. A job that owes local time resolves it. */
|
|
38
|
+
readonly scheduleTimezone: "resolved-in-code";
|
|
39
|
+
/**
|
|
40
|
+
* `startScheduler` ticks as often as it is told, so the library's floor:
|
|
41
|
+
* one whole second, the smallest a whole-second interface can ask for.
|
|
42
|
+
*/
|
|
43
|
+
readonly scheduleMinIntervalSeconds: 1;
|
|
44
|
+
/**
|
|
45
|
+
* 1 MiB, the same as Workflows and the memory adapter. This target has no
|
|
46
|
+
* Pipelines executor yet. When it has one, a result is TEXT like every JSON
|
|
47
|
+
* column here (decision 0007), which holds about 1 GB, so this is the
|
|
48
|
+
* library's limit, not Postgres's. A larger one would let a step pass on
|
|
49
|
+
* Postgres and fail on Workflows.
|
|
50
|
+
*/
|
|
51
|
+
readonly stepResultMaxBytes: 1048576;
|
|
52
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { S3_MAX_PUT_BYTES } from '../s3/blob-store.js';
|
|
2
|
+
/**
|
|
3
|
+
* WHAT POSTGRES PLUS S3-COMPATIBLE STORAGE ACTUALLY PROVIDES.
|
|
4
|
+
*
|
|
5
|
+
* Every value has a row in `docs/platform-facts.md`, in the table "The
|
|
6
|
+
* Postgres manifest, field by field". Postgres sets no ceiling on a delay, a
|
|
7
|
+
* message or a step result, so those three are the library's own limits, and
|
|
8
|
+
* their rows say so.
|
|
9
|
+
*/
|
|
10
|
+
export const POSTGRES_MANIFEST = {
|
|
11
|
+
/**
|
|
12
|
+
* `advisory`, for the reason the other two manifests give: `Ledger.claim`
|
|
13
|
+
* is a lease. A unique constraint decides a claim exactly once, but a holder
|
|
14
|
+
* that outlives its ttl is not stopped. docs/decisions/0002.
|
|
15
|
+
*/
|
|
16
|
+
lock: 'advisory',
|
|
17
|
+
/** `false`: `ClaimResult` carries no token to fence with. docs/decisions/0002. */
|
|
18
|
+
lockFencing: false,
|
|
19
|
+
/**
|
|
20
|
+
* 7 days. `visible_at` is BIGINT milliseconds, which reaches far past this,
|
|
21
|
+
* so the limit is the library's: a delay of weeks is more likely seconds
|
|
22
|
+
* passed as milliseconds than a plan.
|
|
23
|
+
*/
|
|
24
|
+
queueDelayMaxSeconds: 604_800,
|
|
25
|
+
/**
|
|
26
|
+
* 1 MB. A body is TEXT, which holds about 1 GB, but a consumer claims a
|
|
27
|
+
* batch of rows at once. A payload that needs more belongs in the blob store.
|
|
28
|
+
*/
|
|
29
|
+
messageMaxBytes: 1_000_000,
|
|
30
|
+
/** The largest single PUT, because S3BlobStore does no multipart upload. */
|
|
31
|
+
blobMaxBytes: S3_MAX_PUT_BYTES,
|
|
32
|
+
/**
|
|
33
|
+
* Postgres expires rows by comparing epoch milliseconds, so it has no floor.
|
|
34
|
+
* 1 second is the smallest ttl a whole-second interface can ask for.
|
|
35
|
+
*/
|
|
36
|
+
cacheMinTtlSeconds: 1,
|
|
37
|
+
journalDialect: 'postgres',
|
|
38
|
+
/** No cron here, only `startScheduler`'s intervals. A job that owes local time resolves it. */
|
|
39
|
+
scheduleTimezone: 'resolved-in-code',
|
|
40
|
+
/**
|
|
41
|
+
* `startScheduler` ticks as often as it is told, so the library's floor:
|
|
42
|
+
* one whole second, the smallest a whole-second interface can ask for.
|
|
43
|
+
*/
|
|
44
|
+
scheduleMinIntervalSeconds: 1,
|
|
45
|
+
/**
|
|
46
|
+
* 1 MiB, the same as Workflows and the memory adapter. This target has no
|
|
47
|
+
* Pipelines executor yet. When it has one, a result is TEXT like every JSON
|
|
48
|
+
* column here (decision 0007), which holds about 1 GB, so this is the
|
|
49
|
+
* library's limit, not Postgres's. A larger one would let a step pass on
|
|
50
|
+
* Postgres and fail on Workflows.
|
|
51
|
+
*/
|
|
52
|
+
stepResultMaxBytes: 1_048_576,
|
|
53
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type pg from 'pg';
|
|
2
|
+
/** The library's Postgres set. docs/decisions/0007 says why it sits here. */
|
|
3
|
+
export declare const MIGRATIONS_DIR: string;
|
|
4
|
+
/**
|
|
5
|
+
* Applies every file in `dir` not yet recorded, in name order, and returns the
|
|
6
|
+
* names it applied. An empty result means there was nothing to do.
|
|
7
|
+
*
|
|
8
|
+
* Each file runs in its own transaction, which first takes a transaction-level
|
|
9
|
+
* advisory lock. Two containers starting together therefore apply each file
|
|
10
|
+
* once: the second waits, then finds it recorded. Postgres DDL is
|
|
11
|
+
* transactional, so a file that fails leaves nothing half-applied, and its
|
|
12
|
+
* name is not recorded. A recorded file whose contents changed stops the run.
|
|
13
|
+
*/
|
|
14
|
+
export declare function applyMigrations(pool: pg.Pool, dir?: string): Promise<string[]>;
|
|
15
|
+
/**
|
|
16
|
+
* The files in `dir` not yet recorded, in name order. For an app's start-up
|
|
17
|
+
* check: it only reads, so the app's role needs no DDL rights, and it never
|
|
18
|
+
* waits on a migrator's lock.
|
|
19
|
+
*/
|
|
20
|
+
export declare function pendingMigrations(pool: pg.Pool, dir?: string): Promise<string[]>;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile, readdir } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { withClient } from './with-client.js';
|
|
6
|
+
/** The library's Postgres set. docs/decisions/0007 says why it sits here. */
|
|
7
|
+
export const MIGRATIONS_DIR = fileURLToPath(new URL('../../../migrations/postgres/', import.meta.url));
|
|
8
|
+
/**
|
|
9
|
+
* The same name decision 0004 fixed for D1, so an operator looks in one place
|
|
10
|
+
* on either dialect. The app's own migrations keep their own table.
|
|
11
|
+
*
|
|
12
|
+
* `checksum` is what makes "forward-only" a check rather than a hope: a file
|
|
13
|
+
* edited after it was applied no longer matches, and the run stops instead
|
|
14
|
+
* of leaving databases that disagree about what that file did.
|
|
15
|
+
*/
|
|
16
|
+
const BOOKKEEPING = `
|
|
17
|
+
CREATE TABLE IF NOT EXISTS anatta_middleware_migrations (
|
|
18
|
+
name TEXT PRIMARY KEY,
|
|
19
|
+
checksum TEXT NOT NULL,
|
|
20
|
+
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
21
|
+
)
|
|
22
|
+
`;
|
|
23
|
+
/** CRLF is folded to LF first, so a Windows checkout of the same file matches. */
|
|
24
|
+
const checksumOf = (sql) => createHash('sha256').update(sql.replaceAll('\r\n', '\n')).digest('hex');
|
|
25
|
+
/**
|
|
26
|
+
* Any fixed key works, as long as nothing else in the database uses it. This
|
|
27
|
+
* one is the first eight bytes of sha256('anatta_middleware_migrations'), read
|
|
28
|
+
* as a signed big-endian integer.
|
|
29
|
+
*/
|
|
30
|
+
const LOCK_KEY = '-5465547643023699143';
|
|
31
|
+
const sqlFiles = async (dir) => (await readdir(dir)).filter((n) => n.endsWith('.sql')).sort();
|
|
32
|
+
/**
|
|
33
|
+
* Applies every file in `dir` not yet recorded, in name order, and returns the
|
|
34
|
+
* names it applied. An empty result means there was nothing to do.
|
|
35
|
+
*
|
|
36
|
+
* Each file runs in its own transaction, which first takes a transaction-level
|
|
37
|
+
* advisory lock. Two containers starting together therefore apply each file
|
|
38
|
+
* once: the second waits, then finds it recorded. Postgres DDL is
|
|
39
|
+
* transactional, so a file that fails leaves nothing half-applied, and its
|
|
40
|
+
* name is not recorded. A recorded file whose contents changed stops the run.
|
|
41
|
+
*/
|
|
42
|
+
export async function applyMigrations(pool, dir = MIGRATIONS_DIR) {
|
|
43
|
+
const names = await sqlFiles(dir);
|
|
44
|
+
return withClient(pool, async (client) => {
|
|
45
|
+
const applied = [];
|
|
46
|
+
for (const name of names) {
|
|
47
|
+
const sql = await readFile(path.join(dir, name), 'utf8');
|
|
48
|
+
if (await applyOne(client, name, sql)) {
|
|
49
|
+
applied.push(name);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return applied;
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The files in `dir` not yet recorded, in name order. For an app's start-up
|
|
57
|
+
* check: it only reads, so the app's role needs no DDL rights, and it never
|
|
58
|
+
* waits on a migrator's lock.
|
|
59
|
+
*/
|
|
60
|
+
export async function pendingMigrations(pool, dir = MIGRATIONS_DIR) {
|
|
61
|
+
const names = await sqlFiles(dir);
|
|
62
|
+
const { rows } = await pool.query("SELECT to_regclass('anatta_middleware_migrations') IS NOT NULL AS found");
|
|
63
|
+
if (rows[0]?.found !== true) {
|
|
64
|
+
return names;
|
|
65
|
+
}
|
|
66
|
+
const recorded = await pool.query('SELECT name FROM anatta_middleware_migrations');
|
|
67
|
+
const applied = new Set(recorded.rows.map((r) => r.name));
|
|
68
|
+
return names.filter((n) => !applied.has(n));
|
|
69
|
+
}
|
|
70
|
+
async function applyOne(client, name, sql) {
|
|
71
|
+
await client.query('BEGIN');
|
|
72
|
+
try {
|
|
73
|
+
await client.query('SELECT pg_advisory_xact_lock($1)', [LOCK_KEY]);
|
|
74
|
+
// Inside the lock: two first runs racing on CREATE TABLE IF NOT EXISTS
|
|
75
|
+
// can still collide in the catalog.
|
|
76
|
+
await client.query(BOOKKEEPING);
|
|
77
|
+
const checksum = checksumOf(sql);
|
|
78
|
+
const { rows } = await client.query('SELECT checksum FROM anatta_middleware_migrations WHERE name = $1', [name]);
|
|
79
|
+
const recorded = rows[0]?.checksum;
|
|
80
|
+
const pending = recorded === undefined;
|
|
81
|
+
if (pending) {
|
|
82
|
+
await client.query(sql);
|
|
83
|
+
await client.query('INSERT INTO anatta_middleware_migrations (name, checksum) VALUES ($1, $2)', [name, checksum]);
|
|
84
|
+
}
|
|
85
|
+
else if (recorded !== checksum) {
|
|
86
|
+
throw new Error(`Migration ${name} was edited after it was applied. Migrations are ` +
|
|
87
|
+
'forward-only: restore the file and put the change in a new one.');
|
|
88
|
+
}
|
|
89
|
+
await client.query('COMMIT');
|
|
90
|
+
return pending;
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
await client.query('ROLLBACK');
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type pg from 'pg';
|
|
2
|
+
import type { Clock, DeploymentIdentity, Logger, MessageId, Queue, QueueBatch, QueueMessage, SendOptions } from '../../contracts/index.js';
|
|
3
|
+
export type PostgresQueueOptions = {
|
|
4
|
+
/** The app's pool. The queue never opens its own. docs/decisions/0007. */
|
|
5
|
+
readonly pool: pg.Pool;
|
|
6
|
+
readonly clock: Clock;
|
|
7
|
+
readonly identity: DeploymentIdentity;
|
|
8
|
+
/** Which queue this is. One table serves every queue an app has. */
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly maxDelaySeconds: number;
|
|
11
|
+
readonly maxBytes: number;
|
|
12
|
+
/** Deliveries before a message goes to the dead letters. Default 5. */
|
|
13
|
+
readonly maxAttempts?: number;
|
|
14
|
+
/** How long a claimed message stays hidden from other consumers. Default 300. */
|
|
15
|
+
readonly leaseSeconds?: number;
|
|
16
|
+
};
|
|
17
|
+
export type RunOptions = {
|
|
18
|
+
/** Aborting stops the loop after the batch in hand is settled. */
|
|
19
|
+
readonly signal: AbortSignal;
|
|
20
|
+
/** Where a failing consumer and a database fault are reported. */
|
|
21
|
+
readonly logger: Logger;
|
|
22
|
+
readonly batchSize?: number;
|
|
23
|
+
/** The wait after an empty claim. Default 1,000 ms. */
|
|
24
|
+
readonly idleMs?: number;
|
|
25
|
+
};
|
|
26
|
+
export declare class PostgresQueue<T> implements Queue<T> {
|
|
27
|
+
#private;
|
|
28
|
+
private readonly o;
|
|
29
|
+
constructor(o: PostgresQueueOptions);
|
|
30
|
+
send(body: T, options?: SendOptions): Promise<MessageId>;
|
|
31
|
+
sendBatch(bodies: readonly T[], options?: SendOptions): Promise<readonly MessageId[]>;
|
|
32
|
+
/**
|
|
33
|
+
* Claims up to `batchSize` visible messages, hands them to `consumer`, and
|
|
34
|
+
* settles each one as the consumer said.
|
|
35
|
+
*
|
|
36
|
+
* Neither acked nor retried is a retry, as in the memory queue: at least
|
|
37
|
+
* once means an unhandled message is delivered again, never lost. A consumer
|
|
38
|
+
* that throws settles nothing, and its messages come back when their lease
|
|
39
|
+
* runs out, as they would after a crash.
|
|
40
|
+
*/
|
|
41
|
+
drain(consumer: (batch: QueueBatch<T>) => Promise<void>, batchSize?: number): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* The long-running consumer for a Node worker: drains until `signal` is
|
|
44
|
+
* aborted, waiting `idleMs` after an empty claim. Wire the signal to
|
|
45
|
+
* SIGTERM. A batch in hand is settled before the loop returns, and messages
|
|
46
|
+
* claimed but not settled are left to their lease.
|
|
47
|
+
*
|
|
48
|
+
* A consumer that throws is logged with its message ids, and the loop goes
|
|
49
|
+
* on: those messages come back when their lease runs out. A retryable fault
|
|
50
|
+
* in the database is logged and waited out, doubling from `idleMs` up to 30
|
|
51
|
+
* seconds. Any other fault, such as a missing table, ends the loop, so the
|
|
52
|
+
* worker fails where someone will see it.
|
|
53
|
+
*/
|
|
54
|
+
run(consumer: (batch: QueueBatch<T>) => Promise<void>, options: RunOptions): Promise<void>;
|
|
55
|
+
pendingCount(): Promise<number>;
|
|
56
|
+
deadCount(): Promise<number>;
|
|
57
|
+
/** The newest dead letters first, for an operator to read. */
|
|
58
|
+
deadLetters(limit?: number): Promise<readonly QueueMessage<T>[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Moves a dead letter back to the queue, visible now, with its attempt
|
|
61
|
+
* count reset. False when there is no such dead letter.
|
|
62
|
+
*/
|
|
63
|
+
replay(id: MessageId): Promise<boolean>;
|
|
64
|
+
}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
|
+
import { LimitExceeded, ToolFault, checkDuration, plusSeconds, toIso, fromEpochMs, } from '../../contracts/index.js';
|
|
4
|
+
import { toFault } from './faults.js';
|
|
5
|
+
import { withClient } from './with-client.js';
|
|
6
|
+
const TOOL = 'queue';
|
|
7
|
+
/**
|
|
8
|
+
* Long enough for one batch of the tagger's work, a few Admin API calls with
|
|
9
|
+
* their own retries, several times over. A lease that runs out while a
|
|
10
|
+
* consumer is still working delivers the message twice; one that is too long
|
|
11
|
+
* only delays recovery after a crash. Duplicates are allowed (delivery is at
|
|
12
|
+
* least once), so the default leans long.
|
|
13
|
+
*/
|
|
14
|
+
const DEFAULT_LEASE_SECONDS = 300;
|
|
15
|
+
/** As Cloudflare's default, so a message gets the same number of tries. */
|
|
16
|
+
const DEFAULT_MAX_ATTEMPTS = 5;
|
|
17
|
+
const DEFAULT_BATCH_SIZE = 10;
|
|
18
|
+
/** How long `run` waits before asking again when the queue was empty. */
|
|
19
|
+
const DEFAULT_IDLE_MS = 1_000;
|
|
20
|
+
/** The longest `run` waits after a fault, however many in a row. */
|
|
21
|
+
const MAX_BACKOFF_MS = 30_000;
|
|
22
|
+
const Q = {
|
|
23
|
+
// One statement for any number of bodies: one array per column.
|
|
24
|
+
send: `
|
|
25
|
+
INSERT INTO queue_messages
|
|
26
|
+
(id, queue, body, identity, enqueued_at, visible_at, attempt)
|
|
27
|
+
SELECT m.id, $1, m.body, $2, $3, $4, 0
|
|
28
|
+
FROM unnest($5::text[], $6::text[]) AS m (id, body)
|
|
29
|
+
`,
|
|
30
|
+
// A message that has used every attempt and is visible again, because its
|
|
31
|
+
// last consumer stopped without settling it, goes to the dead letters
|
|
32
|
+
// rather than round again. Without this a message that crashes its
|
|
33
|
+
// consumer would be delivered for ever.
|
|
34
|
+
bury: `
|
|
35
|
+
WITH dead AS (
|
|
36
|
+
DELETE FROM queue_messages WHERE id IN (
|
|
37
|
+
SELECT id FROM queue_messages
|
|
38
|
+
WHERE queue = $1 AND visible_at <= $2 AND attempt >= $3
|
|
39
|
+
FOR UPDATE SKIP LOCKED
|
|
40
|
+
)
|
|
41
|
+
RETURNING id, queue, body, identity, enqueued_at, attempt
|
|
42
|
+
)
|
|
43
|
+
INSERT INTO queue_dead_letters
|
|
44
|
+
(id, queue, body, identity, enqueued_at, attempt, dead_at)
|
|
45
|
+
SELECT id, queue, body, identity, enqueued_at, attempt, $2 FROM dead
|
|
46
|
+
`,
|
|
47
|
+
// The claim. SKIP LOCKED hands two consumers different messages instead of
|
|
48
|
+
// making one wait for the other. Moving `visible_at` to the end of the lease
|
|
49
|
+
// hides the message from every other claim until then.
|
|
50
|
+
claim: `
|
|
51
|
+
UPDATE queue_messages SET visible_at = $3, attempt = attempt + 1
|
|
52
|
+
WHERE id IN (
|
|
53
|
+
SELECT id FROM queue_messages
|
|
54
|
+
WHERE queue = $1 AND visible_at <= $2
|
|
55
|
+
ORDER BY visible_at
|
|
56
|
+
LIMIT $4
|
|
57
|
+
FOR UPDATE SKIP LOCKED
|
|
58
|
+
)
|
|
59
|
+
RETURNING id, body, identity, enqueued_at, attempt
|
|
60
|
+
`,
|
|
61
|
+
ack: `DELETE FROM queue_messages WHERE id = ANY($1::text[])`,
|
|
62
|
+
// Only while the row still holds the attempt this consumer was given. If
|
|
63
|
+
// the lease ran out and another consumer claimed the message, the attempt
|
|
64
|
+
// moved on, and this consumer's retry must not reset that one's lease.
|
|
65
|
+
retry: `
|
|
66
|
+
UPDATE queue_messages m SET visible_at = r.visible_at
|
|
67
|
+
FROM unnest($1::text[], $2::integer[], $3::bigint[])
|
|
68
|
+
AS r (id, attempt, visible_at)
|
|
69
|
+
WHERE m.id = r.id AND m.attempt = r.attempt
|
|
70
|
+
`,
|
|
71
|
+
// A retried message that has used every attempt goes to the dead letters
|
|
72
|
+
// now, rather than waiting to be claimed once more.
|
|
73
|
+
exhaust: `
|
|
74
|
+
WITH dead AS (
|
|
75
|
+
DELETE FROM queue_messages m
|
|
76
|
+
USING unnest($1::text[], $2::integer[]) AS r (id, attempt)
|
|
77
|
+
WHERE m.id = r.id AND m.attempt = r.attempt AND m.attempt >= $3
|
|
78
|
+
RETURNING m.id, m.queue, m.body, m.identity, m.enqueued_at, m.attempt
|
|
79
|
+
)
|
|
80
|
+
INSERT INTO queue_dead_letters
|
|
81
|
+
(id, queue, body, identity, enqueued_at, attempt, dead_at)
|
|
82
|
+
SELECT id, queue, body, identity, enqueued_at, attempt, $4 FROM dead
|
|
83
|
+
`,
|
|
84
|
+
pending: `SELECT COUNT(*) AS n FROM queue_messages WHERE queue = $1`,
|
|
85
|
+
deadCount: `SELECT COUNT(*) AS n FROM queue_dead_letters WHERE queue = $1`,
|
|
86
|
+
deadLetters: `
|
|
87
|
+
SELECT id, body, identity, enqueued_at, attempt FROM queue_dead_letters
|
|
88
|
+
WHERE queue = $1 ORDER BY dead_at DESC, id LIMIT $2
|
|
89
|
+
`,
|
|
90
|
+
// Back to the queue with a fresh count, visible now.
|
|
91
|
+
replay: `
|
|
92
|
+
WITH back AS (
|
|
93
|
+
DELETE FROM queue_dead_letters WHERE queue = $1 AND id = $2
|
|
94
|
+
RETURNING id, queue, body, identity, enqueued_at
|
|
95
|
+
)
|
|
96
|
+
INSERT INTO queue_messages
|
|
97
|
+
(id, queue, body, identity, enqueued_at, visible_at, attempt)
|
|
98
|
+
SELECT id, queue, body, identity, enqueued_at, $3, 0 FROM back
|
|
99
|
+
`,
|
|
100
|
+
};
|
|
101
|
+
const toMessage = (r) => ({
|
|
102
|
+
id: r.id,
|
|
103
|
+
body: JSON.parse(r.body),
|
|
104
|
+
attempt: r.attempt,
|
|
105
|
+
// BIGINT arrives as a string. docs/decisions/0007.
|
|
106
|
+
enqueuedAt: toIso(fromEpochMs(Number(r.enqueued_at))),
|
|
107
|
+
identity: JSON.parse(r.identity),
|
|
108
|
+
});
|
|
109
|
+
export class PostgresQueue {
|
|
110
|
+
o;
|
|
111
|
+
#maxAttempts;
|
|
112
|
+
#leaseSeconds;
|
|
113
|
+
constructor(o) {
|
|
114
|
+
this.o = o;
|
|
115
|
+
this.#maxAttempts = o.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
116
|
+
this.#leaseSeconds = o.leaseSeconds ?? DEFAULT_LEASE_SECONDS;
|
|
117
|
+
}
|
|
118
|
+
async send(body, options) {
|
|
119
|
+
const [id] = await this.#send('send', [body], options);
|
|
120
|
+
return id;
|
|
121
|
+
}
|
|
122
|
+
async sendBatch(bodies, options) {
|
|
123
|
+
return this.#send('sendBatch', bodies, options);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Claims up to `batchSize` visible messages, hands them to `consumer`, and
|
|
127
|
+
* settles each one as the consumer said.
|
|
128
|
+
*
|
|
129
|
+
* Neither acked nor retried is a retry, as in the memory queue: at least
|
|
130
|
+
* once means an unhandled message is delivered again, never lost. A consumer
|
|
131
|
+
* that throws settles nothing, and its messages come back when their lease
|
|
132
|
+
* runs out, as they would after a crash.
|
|
133
|
+
*/
|
|
134
|
+
async drain(consumer, batchSize = DEFAULT_BATCH_SIZE) {
|
|
135
|
+
await this.#drain(consumer, batchSize);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* `drain`, returning how many messages it delivered, for `run`. With
|
|
139
|
+
* `onConsumerError`, a consumer that throws is reported there instead of
|
|
140
|
+
* rethrown, and its messages are still left to their lease.
|
|
141
|
+
*/
|
|
142
|
+
async #drain(consumer, batchSize = DEFAULT_BATCH_SIZE, onConsumerError) {
|
|
143
|
+
const now = this.o.clock.now();
|
|
144
|
+
const leaseEnds = plusSeconds(now, this.#leaseSeconds);
|
|
145
|
+
const { rows } = await this.#call('drain', async () => {
|
|
146
|
+
await this.o.pool.query(Q.bury, [this.o.name, now, this.#maxAttempts]);
|
|
147
|
+
return this.o.pool.query(Q.claim, [
|
|
148
|
+
this.o.name,
|
|
149
|
+
now,
|
|
150
|
+
Math.ceil(leaseEnds),
|
|
151
|
+
batchSize,
|
|
152
|
+
]);
|
|
153
|
+
});
|
|
154
|
+
if (rows.length === 0) {
|
|
155
|
+
return 0;
|
|
156
|
+
}
|
|
157
|
+
const messages = rows.map((r) => toMessage(r));
|
|
158
|
+
const acked = new Set();
|
|
159
|
+
const retried = new Map();
|
|
160
|
+
try {
|
|
161
|
+
await consumer({
|
|
162
|
+
messages,
|
|
163
|
+
ack: (id) => {
|
|
164
|
+
acked.add(id);
|
|
165
|
+
retried.delete(id);
|
|
166
|
+
},
|
|
167
|
+
retry: (id, options) => {
|
|
168
|
+
retried.set(id, this.#checkedDelay(options?.delaySeconds));
|
|
169
|
+
acked.delete(id);
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
if (onConsumerError === undefined) {
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
onConsumerError(error, messages.map((m) => m.id));
|
|
178
|
+
return messages.length;
|
|
179
|
+
}
|
|
180
|
+
await this.#settle(messages, acked, retried);
|
|
181
|
+
return messages.length;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* The long-running consumer for a Node worker: drains until `signal` is
|
|
185
|
+
* aborted, waiting `idleMs` after an empty claim. Wire the signal to
|
|
186
|
+
* SIGTERM. A batch in hand is settled before the loop returns, and messages
|
|
187
|
+
* claimed but not settled are left to their lease.
|
|
188
|
+
*
|
|
189
|
+
* A consumer that throws is logged with its message ids, and the loop goes
|
|
190
|
+
* on: those messages come back when their lease runs out. A retryable fault
|
|
191
|
+
* in the database is logged and waited out, doubling from `idleMs` up to 30
|
|
192
|
+
* seconds. Any other fault, such as a missing table, ends the loop, so the
|
|
193
|
+
* worker fails where someone will see it.
|
|
194
|
+
*/
|
|
195
|
+
async run(consumer, options) {
|
|
196
|
+
const { signal, logger } = options;
|
|
197
|
+
const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
|
|
198
|
+
// The wait ends early on abort. Its AbortError is the stop, not a fault.
|
|
199
|
+
const wait = async (ms) => sleep(ms, undefined, { signal }).catch(() => { });
|
|
200
|
+
let faults = 0;
|
|
201
|
+
while (!signal.aborted) {
|
|
202
|
+
let delivered;
|
|
203
|
+
try {
|
|
204
|
+
delivered = await this.#drain(consumer, options.batchSize, (error, ids) => {
|
|
205
|
+
logger.error('queue consumer failed', {
|
|
206
|
+
queue: this.o.name,
|
|
207
|
+
ids: ids.join(','),
|
|
208
|
+
error: String(error),
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
faults = 0;
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (!(error instanceof ToolFault) || !error.retryable) {
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
faults += 1;
|
|
218
|
+
const backoffMs = Math.min(idleMs * 2 ** faults, MAX_BACKOFF_MS);
|
|
219
|
+
logger.warn('queue fault, retrying', {
|
|
220
|
+
queue: this.o.name,
|
|
221
|
+
error: String(error),
|
|
222
|
+
backoffMs,
|
|
223
|
+
});
|
|
224
|
+
await wait(backoffMs);
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (delivered === 0) {
|
|
228
|
+
await wait(idleMs);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
async pendingCount() {
|
|
233
|
+
return this.#count('pendingCount', Q.pending);
|
|
234
|
+
}
|
|
235
|
+
async deadCount() {
|
|
236
|
+
return this.#count('deadCount', Q.deadCount);
|
|
237
|
+
}
|
|
238
|
+
/** The newest dead letters first, for an operator to read. */
|
|
239
|
+
async deadLetters(limit = 100) {
|
|
240
|
+
const { rows } = await this.#call('deadLetters', async () => this.o.pool.query(Q.deadLetters, [this.o.name, limit]));
|
|
241
|
+
return rows.map((r) => toMessage(r));
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Moves a dead letter back to the queue, visible now, with its attempt
|
|
245
|
+
* count reset. False when there is no such dead letter.
|
|
246
|
+
*/
|
|
247
|
+
async replay(id) {
|
|
248
|
+
const { rowCount } = await this.#call('replay', async () => this.o.pool.query(Q.replay, [this.o.name, id, this.o.clock.now()]));
|
|
249
|
+
return rowCount === 1;
|
|
250
|
+
}
|
|
251
|
+
async #send(operation, bodies, options) {
|
|
252
|
+
const delay = this.#checkedDelay(options?.delaySeconds);
|
|
253
|
+
if (bodies.length === 0) {
|
|
254
|
+
return [];
|
|
255
|
+
}
|
|
256
|
+
const json = bodies.map((b) => {
|
|
257
|
+
const text = JSON.stringify(b);
|
|
258
|
+
// The adapter enforces its own manifest. Postgres would take far more.
|
|
259
|
+
const bytes = Buffer.byteLength(text);
|
|
260
|
+
if (bytes > this.o.maxBytes) {
|
|
261
|
+
throw new LimitExceeded(TOOL, `body of ${bytes} bytes exceeds messageMaxBytes ${this.o.maxBytes}`);
|
|
262
|
+
}
|
|
263
|
+
return text;
|
|
264
|
+
});
|
|
265
|
+
const ids = bodies.map(() => randomUUID());
|
|
266
|
+
const now = this.o.clock.now();
|
|
267
|
+
await this.#call(operation, async () => this.o.pool.query(Q.send, [
|
|
268
|
+
this.o.name,
|
|
269
|
+
JSON.stringify(this.o.identity),
|
|
270
|
+
now,
|
|
271
|
+
Math.ceil(plusSeconds(now, delay)),
|
|
272
|
+
ids,
|
|
273
|
+
json,
|
|
274
|
+
]));
|
|
275
|
+
return ids;
|
|
276
|
+
}
|
|
277
|
+
async #settle(messages, acked, retried) {
|
|
278
|
+
const now = this.o.clock.now();
|
|
279
|
+
const again = messages.filter((m) => !acked.has(m.id));
|
|
280
|
+
const ids = again.map((m) => m.id);
|
|
281
|
+
const attempts = again.map((m) => m.attempt);
|
|
282
|
+
await this.#call('drain', async () => withClient(this.o.pool, async (client) => {
|
|
283
|
+
try {
|
|
284
|
+
await client.query('BEGIN');
|
|
285
|
+
if (acked.size > 0) {
|
|
286
|
+
await client.query(Q.ack, [[...acked]]);
|
|
287
|
+
}
|
|
288
|
+
if (again.length > 0) {
|
|
289
|
+
await client.query(Q.exhaust, [
|
|
290
|
+
ids,
|
|
291
|
+
attempts,
|
|
292
|
+
this.#maxAttempts,
|
|
293
|
+
now,
|
|
294
|
+
]);
|
|
295
|
+
await client.query(Q.retry, [
|
|
296
|
+
ids,
|
|
297
|
+
attempts,
|
|
298
|
+
again.map((m) => Math.ceil(plusSeconds(now, retried.get(m.id) ?? 0))),
|
|
299
|
+
]);
|
|
300
|
+
}
|
|
301
|
+
await client.query('COMMIT');
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
}));
|
|
308
|
+
}
|
|
309
|
+
#checkedDelay(delaySeconds) {
|
|
310
|
+
const delay = delaySeconds ?? 0;
|
|
311
|
+
// Before the ceiling check, which cannot catch it: NaN > maxDelaySeconds
|
|
312
|
+
// is false, so a NaN delay would pass and the message would never be
|
|
313
|
+
// visible.
|
|
314
|
+
checkDuration(TOOL, 'delaySeconds', delay);
|
|
315
|
+
if (delay > this.o.maxDelaySeconds) {
|
|
316
|
+
throw new LimitExceeded(TOOL, `delaySeconds ${delay} exceeds queueDelayMaxSeconds ${this.o.maxDelaySeconds}`);
|
|
317
|
+
}
|
|
318
|
+
return delay;
|
|
319
|
+
}
|
|
320
|
+
async #count(operation, sql) {
|
|
321
|
+
const { rows } = await this.#call(operation, async () => this.o.pool.query(sql, [this.o.name]));
|
|
322
|
+
// COUNT(*) is a BIGINT, which arrives as a string.
|
|
323
|
+
return Number(rows[0]?.n ?? 0);
|
|
324
|
+
}
|
|
325
|
+
async #call(operation, f) {
|
|
326
|
+
try {
|
|
327
|
+
return await f();
|
|
328
|
+
}
|
|
329
|
+
catch (e) {
|
|
330
|
+
throw toFault(TOOL, operation, e);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type pg from 'pg';
|
|
2
|
+
import type { BlobStore, Clock } from '../../contracts/index.js';
|
|
3
|
+
import { type SweepOptions } from '../retention.js';
|
|
4
|
+
export { DEFAULT_RETENTION_SECONDS, type SweepOptions } from '../retention.js';
|
|
5
|
+
export type PostgresSweepDeps = {
|
|
6
|
+
/** The app's pool. docs/decisions/0007. */
|
|
7
|
+
readonly pool: pg.Pool;
|
|
8
|
+
readonly clock: Clock;
|
|
9
|
+
};
|
|
10
|
+
/** Deletes one batch of ledger claims whose lease ended `olderThanSeconds` ago. */
|
|
11
|
+
export declare function sweepLedger(deps: PostgresSweepDeps, options?: SweepOptions): Promise<number>;
|
|
12
|
+
/**
|
|
13
|
+
* Deletes one batch of webhook receipts past retention, and their raw bodies,
|
|
14
|
+
* bodies first. Returns how many deliveries it deleted.
|
|
15
|
+
*/
|
|
16
|
+
export declare function sweepWebhookReceipts(deps: PostgresSweepDeps & {
|
|
17
|
+
readonly blobStore: BlobStore;
|
|
18
|
+
}, options?: SweepOptions): Promise<number>;
|