@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,47 @@
|
|
|
1
|
+
import { LimitExceeded, Misconfigured, Throttled, Unavailable, } from '../../contracts/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Postgres reports a failure with a SQLSTATE `code`, whose first two
|
|
4
|
+
* characters are its class. That code is read here, in one place, and the
|
|
5
|
+
* vendor error is kept as `cause`, never in the caller's message.
|
|
6
|
+
*
|
|
7
|
+
* https://www.postgresql.org/docs/current/errcodes-appendix.html
|
|
8
|
+
*/
|
|
9
|
+
const MISCONFIGURED = new Set([
|
|
10
|
+
'28', // invalid authorization: wrong user or password
|
|
11
|
+
'3D', // invalid catalog name: no such database
|
|
12
|
+
'3F', // invalid schema name
|
|
13
|
+
'42', // syntax error or access rule violation: no such table, no privilege
|
|
14
|
+
]);
|
|
15
|
+
const codeOf = (e) => {
|
|
16
|
+
const code = e?.code;
|
|
17
|
+
return typeof code === 'string' && code.length === 5 ? code : undefined;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* 40001, serialization_failure. Under REPEATABLE READ or SERIALIZABLE, a write
|
|
21
|
+
* that meets a row committed after its snapshot fails with this, where READ
|
|
22
|
+
* COMMITTED would have seen the row.
|
|
23
|
+
*/
|
|
24
|
+
export const isSerializationFailure = (e) => codeOf(e) === '40001';
|
|
25
|
+
/**
|
|
26
|
+
* Unknown failures, including a refused connection, which carries a Node
|
|
27
|
+
* error code rather than a SQLSTATE, are Unavailable and so retryable. A
|
|
28
|
+
* retryable answer to something permanent costs a few attempts; a permanent
|
|
29
|
+
* answer to something transient loses the work.
|
|
30
|
+
*/
|
|
31
|
+
export function toFault(tool, operation, e) {
|
|
32
|
+
const sqlClass = codeOf(e)?.slice(0, 2);
|
|
33
|
+
const where = `${operation} failed`;
|
|
34
|
+
const options = { cause: e };
|
|
35
|
+
// Class 53, insufficient resources: too many connections, out of memory.
|
|
36
|
+
if (sqlClass === '53') {
|
|
37
|
+
return new Throttled(tool, where, options);
|
|
38
|
+
}
|
|
39
|
+
if (sqlClass !== undefined && MISCONFIGURED.has(sqlClass)) {
|
|
40
|
+
return new Misconfigured(tool, where, options);
|
|
41
|
+
}
|
|
42
|
+
// Class 22, data exception: a value out of range or too long.
|
|
43
|
+
if (sqlClass === '22') {
|
|
44
|
+
return new LimitExceeded(tool, where, options);
|
|
45
|
+
}
|
|
46
|
+
return new Unavailable(tool, where, options);
|
|
47
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './cache.js';
|
|
2
|
+
export * from './config.js';
|
|
3
|
+
export { toFault } from './faults.js';
|
|
4
|
+
export * from './journal.js';
|
|
5
|
+
export * from './ledger.js';
|
|
6
|
+
export * from './logger.js';
|
|
7
|
+
export * from './manifest.js';
|
|
8
|
+
export { applyMigrations, pendingMigrations } from './migrate.js';
|
|
9
|
+
export * from './queue.js';
|
|
10
|
+
export * from './retention.js';
|
|
11
|
+
export * from './session-storage.js';
|
|
12
|
+
export * from './toolkit.js';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './cache.js';
|
|
2
|
+
export * from './config.js';
|
|
3
|
+
export { toFault } from './faults.js';
|
|
4
|
+
export * from './journal.js';
|
|
5
|
+
export * from './ledger.js';
|
|
6
|
+
export * from './logger.js';
|
|
7
|
+
export * from './manifest.js';
|
|
8
|
+
export { applyMigrations, pendingMigrations } from './migrate.js';
|
|
9
|
+
export * from './queue.js';
|
|
10
|
+
export * from './retention.js';
|
|
11
|
+
export * from './session-storage.js';
|
|
12
|
+
export * from './toolkit.js';
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type pg from 'pg';
|
|
2
|
+
import { type CallRow, type DeliveryRow, type Instant, type Journal, type Logger, type ReasonCount, type RunId, type RunRow, type StepRow, type TaskCursor, type TaskRow, type TaskState, type UnitKey, type UnitRow } from '../../contracts/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Every query this adapter can run, in one place. The D1 journal's queries
|
|
5
|
+
* with `$n` placeholders; its comments say why each one is shaped as it is.
|
|
6
|
+
*
|
|
7
|
+
* Which index serves which read, asserted by `journal.spec.ts` with EXPLAIN:
|
|
8
|
+
*
|
|
9
|
+
* recentRuns journal_runs_started_at
|
|
10
|
+
* unitsForRun journal_units_pkey
|
|
11
|
+
* unit journal_units_pkey, journal_steps_unit,
|
|
12
|
+
* journal_calls_pkey
|
|
13
|
+
* latestForUnit journal_units_unit_key
|
|
14
|
+
* failuresByReason journal_units_recorded_at
|
|
15
|
+
* delivery webhook_deliveries_pkey, webhook_tasks_pkey
|
|
16
|
+
* deadTasks webhook_tasks_state
|
|
17
|
+
* deadTasksByUseCase webhook_tasks_use_case_state
|
|
18
|
+
* stuckTasks webhook_tasks_state
|
|
19
|
+
* reclaimStuckTask webhook_tasks_pkey or webhook_tasks_action_state
|
|
20
|
+
*/
|
|
21
|
+
declare const Q: {
|
|
22
|
+
readonly startRun: "\n INSERT INTO journal_runs\n (run_id, job, trigger, mode, started_at, identity)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (run_id) DO UPDATE SET\n job = $2, trigger = $3, mode = $4, started_at = $5, identity = $6\n ";
|
|
23
|
+
readonly finishRun: "UPDATE journal_runs SET ended_at = $2 WHERE run_id = $1";
|
|
24
|
+
readonly recordUnit: "\n INSERT INTO journal_units\n (run_id, unit_key, unit_type, recorded_at, outcome,\n reason_code, plan_hash, plan_ref, duration_ms, external_ids)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (run_id, unit_key) DO UPDATE SET\n unit_type = $3, recorded_at = $4, outcome = $5,\n reason_code = $6, plan_hash = $7, plan_ref = $8,\n duration_ms = $9, external_ids = $10\n ";
|
|
25
|
+
readonly clearCalls: "DELETE FROM journal_calls WHERE run_id = $1 AND unit_key = $2";
|
|
26
|
+
readonly recordCalls: "\n INSERT INTO journal_calls\n (run_id, unit_key, seq, system, operation,\n status, http_status, idempotency_key, duration_ms)\n SELECT c.run_id, c.unit_key, c.ord - 1, c.system, c.operation,\n c.status, c.http_status, c.idempotency_key, c.duration_ms\n FROM unnest(\n $1::text[], $2::text[], $3::text[], $4::text[], $5::text[],\n $6::integer[], $7::text[], $8::bigint[]\n ) WITH ORDINALITY\n AS c (run_id, unit_key, system, operation, status,\n http_status, idempotency_key, duration_ms, ord)\n ";
|
|
27
|
+
readonly recordStep: "\n INSERT INTO journal_steps\n (run_id, unit_key, step, attempt, outcome,\n reason_code, duration_ms, recorded_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ";
|
|
28
|
+
readonly unitsForRun: "\n SELECT * FROM journal_units\n WHERE run_id = $1 ORDER BY unit_key LIMIT $2\n ";
|
|
29
|
+
readonly unit: "SELECT * FROM journal_units WHERE run_id = $1 AND unit_key = $2";
|
|
30
|
+
readonly stepsForUnit: "\n SELECT * FROM journal_steps\n WHERE run_id = $1 AND unit_key = $2 ORDER BY recorded_at, seq\n ";
|
|
31
|
+
readonly callsForUnit: "\n SELECT * FROM journal_calls\n WHERE run_id = $1 AND unit_key = $2 ORDER BY seq\n ";
|
|
32
|
+
readonly latestForUnit: "\n SELECT * FROM journal_units\n WHERE unit_key = $1 ORDER BY recorded_at DESC LIMIT 1\n ";
|
|
33
|
+
readonly failuresByReason: "\n SELECT reason_code, COUNT(*) AS count\n FROM journal_units\n WHERE recorded_at >= $1\n AND reason_code IS NOT NULL\n AND outcome != 'written'\n GROUP BY reason_code\n ORDER BY count DESC, reason_code ASC\n ";
|
|
34
|
+
readonly recentRuns: "SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT $1";
|
|
35
|
+
readonly recordDelivery: "\n WITH delivery AS (\n INSERT INTO webhook_deliveries\n (delivery_id, source, topic, shop, webhook_id, body_key, received_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (delivery_id) DO NOTHING\n )\n INSERT INTO webhook_tasks (delivery_id, use_case, state, updated_at)\n SELECT $1, use_case, 'received', $7 FROM unnest($8::text[]) AS use_case\n ON CONFLICT (delivery_id, use_case) DO NOTHING\n ";
|
|
36
|
+
readonly moveTask: "\n UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6,\n requeues = CASE WHEN $3 = 'replayed' THEN 0 ELSE requeues END\n WHERE delivery_id = $1 AND use_case = $2 AND state = ANY($5::text[])\n ";
|
|
37
|
+
readonly delivery: "SELECT * FROM webhook_deliveries WHERE delivery_id = $1";
|
|
38
|
+
readonly tasksForDelivery: "\n SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY use_case\n ";
|
|
39
|
+
readonly deadTasks: "\n SELECT * FROM webhook_tasks\n WHERE state = 'dead' AND (updated_at, delivery_id, use_case) > ($1, $2, $3)\n ORDER BY updated_at, delivery_id, use_case LIMIT $4\n ";
|
|
40
|
+
readonly deadTasksByUseCase: "\n SELECT * FROM webhook_tasks\n WHERE use_case = $5 AND state = 'dead'\n AND (updated_at, delivery_id, use_case) > ($1, $2, $3)\n ORDER BY updated_at, delivery_id LIMIT $4\n ";
|
|
41
|
+
readonly stuckTasks: "\n SELECT * FROM webhook_tasks\n WHERE state IN ('received', 'processing', 'replayed') AND updated_at < $1\n ORDER BY updated_at, delivery_id, use_case LIMIT $2\n ";
|
|
42
|
+
readonly reclaimStuckTask: "\n UPDATE webhook_tasks SET\n updated_at = $5,\n state = CASE WHEN $4 = 'dead' THEN 'dead' ELSE state END,\n reason_code = CASE WHEN $4 = 'dead' THEN 'stuck' ELSE reason_code END,\n requeues = CASE WHEN $4 = 'dead' THEN requeues ELSE requeues + 1 END\n WHERE delivery_id = $1 AND use_case = $2 AND updated_at = $3\n AND state IN ('received', 'processing', 'replayed')\n ";
|
|
43
|
+
};
|
|
44
|
+
export type PostgresJournalOptions = {
|
|
45
|
+
/** The app's pool. The journal never opens its own. docs/decisions/0007. */
|
|
46
|
+
readonly pool: pg.Pool;
|
|
47
|
+
/** Where a failed step-row write goes, because `recordStep` must not reject. */
|
|
48
|
+
readonly logger: Logger;
|
|
49
|
+
};
|
|
50
|
+
export declare class PostgresJournal implements Journal {
|
|
51
|
+
#private;
|
|
52
|
+
private readonly o;
|
|
53
|
+
constructor(o: PostgresJournalOptions);
|
|
54
|
+
startRun(row: RunRow): Promise<void>;
|
|
55
|
+
finishRun(runId: RunId, endedAt: Instant): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* One transaction, so a unit is never half recorded: the unit row, the
|
|
58
|
+
* clear of its previous calls, and all its calls in one INSERT.
|
|
59
|
+
*/
|
|
60
|
+
recordUnit(unit: UnitRow, calls: readonly CallRow[]): Promise<void>;
|
|
61
|
+
/** Catches every failure and logs it, as the contract requires. */
|
|
62
|
+
recordStep(step: StepRow): Promise<void>;
|
|
63
|
+
unitsForRun(runId: RunId, limit?: number): Promise<readonly UnitRow[]>;
|
|
64
|
+
unit(runId: RunId, unitKey: UnitKey): Promise<{
|
|
65
|
+
unit: UnitRow;
|
|
66
|
+
steps: readonly StepRow[];
|
|
67
|
+
calls: readonly CallRow[];
|
|
68
|
+
} | undefined>;
|
|
69
|
+
latestForUnit(unitKey: UnitKey): Promise<UnitRow | undefined>;
|
|
70
|
+
failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
|
|
71
|
+
recentRuns(limit?: number): Promise<readonly RunRow[]>;
|
|
72
|
+
recordDelivery(delivery: DeliveryRow, useCases: readonly string[]): Promise<void>;
|
|
73
|
+
moveTask(deliveryId: string, useCase: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
|
|
74
|
+
delivery(deliveryId: string): Promise<{
|
|
75
|
+
delivery: DeliveryRow;
|
|
76
|
+
tasks: readonly TaskRow[];
|
|
77
|
+
} | undefined>;
|
|
78
|
+
deadTasks({ useCase, after, limit, }?: {
|
|
79
|
+
readonly useCase?: string;
|
|
80
|
+
readonly after?: TaskCursor;
|
|
81
|
+
readonly limit?: number;
|
|
82
|
+
}): Promise<readonly TaskRow[]>;
|
|
83
|
+
stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
|
|
84
|
+
reclaimStuckTask(task: Pick<TaskRow, 'deliveryId' | 'useCase' | 'updatedAt'>, at: Instant, to: 'requeued' | 'dead'): Promise<boolean>;
|
|
85
|
+
}
|
|
86
|
+
export { Q as JOURNAL_QUERIES };
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { TASK_TRANSITIONS, } from '../../contracts/index.js';
|
|
2
|
+
import { DEFAULT_RUN_LIMIT, DEFAULT_UNIT_LIMIT, FIRST_TASK, toCallRow, toDeliveryRow, toTaskRow, toRunRow, toStepRow, toUnitRow, } from '../journal-records.js';
|
|
3
|
+
import { toFault } from './faults.js';
|
|
4
|
+
import { withClient } from './with-client.js';
|
|
5
|
+
const TOOL = 'journal';
|
|
6
|
+
/**
|
|
7
|
+
* Every query this adapter can run, in one place. The D1 journal's queries
|
|
8
|
+
* with `$n` placeholders; its comments say why each one is shaped as it is.
|
|
9
|
+
*
|
|
10
|
+
* Which index serves which read, asserted by `journal.spec.ts` with EXPLAIN:
|
|
11
|
+
*
|
|
12
|
+
* recentRuns journal_runs_started_at
|
|
13
|
+
* unitsForRun journal_units_pkey
|
|
14
|
+
* unit journal_units_pkey, journal_steps_unit,
|
|
15
|
+
* journal_calls_pkey
|
|
16
|
+
* latestForUnit journal_units_unit_key
|
|
17
|
+
* failuresByReason journal_units_recorded_at
|
|
18
|
+
* delivery webhook_deliveries_pkey, webhook_tasks_pkey
|
|
19
|
+
* deadTasks webhook_tasks_state
|
|
20
|
+
* deadTasksByUseCase webhook_tasks_use_case_state
|
|
21
|
+
* stuckTasks webhook_tasks_state
|
|
22
|
+
* reclaimStuckTask webhook_tasks_pkey or webhook_tasks_action_state
|
|
23
|
+
*/
|
|
24
|
+
const Q = {
|
|
25
|
+
startRun: `
|
|
26
|
+
INSERT INTO journal_runs
|
|
27
|
+
(run_id, job, trigger, mode, started_at, identity)
|
|
28
|
+
VALUES ($1, $2, $3, $4, $5, $6)
|
|
29
|
+
ON CONFLICT (run_id) DO UPDATE SET
|
|
30
|
+
job = $2, trigger = $3, mode = $4, started_at = $5, identity = $6
|
|
31
|
+
`,
|
|
32
|
+
finishRun: `UPDATE journal_runs SET ended_at = $2 WHERE run_id = $1`,
|
|
33
|
+
recordUnit: `
|
|
34
|
+
INSERT INTO journal_units
|
|
35
|
+
(run_id, unit_key, unit_type, recorded_at, outcome,
|
|
36
|
+
reason_code, plan_hash, plan_ref, duration_ms, external_ids)
|
|
37
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
38
|
+
ON CONFLICT (run_id, unit_key) DO UPDATE SET
|
|
39
|
+
unit_type = $3, recorded_at = $4, outcome = $5,
|
|
40
|
+
reason_code = $6, plan_hash = $7, plan_ref = $8,
|
|
41
|
+
duration_ms = $9, external_ids = $10
|
|
42
|
+
`,
|
|
43
|
+
clearCalls: `DELETE FROM journal_calls WHERE run_id = $1 AND unit_key = $2`,
|
|
44
|
+
// Every call of a unit in one statement, one array per column, so a unit
|
|
45
|
+
// with fifty calls is still one round trip. `seq` is the array position.
|
|
46
|
+
// Each call keeps its own run and unit keys, as on D1 and in memory.
|
|
47
|
+
recordCalls: `
|
|
48
|
+
INSERT INTO journal_calls
|
|
49
|
+
(run_id, unit_key, seq, system, operation,
|
|
50
|
+
status, http_status, idempotency_key, duration_ms)
|
|
51
|
+
SELECT c.run_id, c.unit_key, c.ord - 1, c.system, c.operation,
|
|
52
|
+
c.status, c.http_status, c.idempotency_key, c.duration_ms
|
|
53
|
+
FROM unnest(
|
|
54
|
+
$1::text[], $2::text[], $3::text[], $4::text[], $5::text[],
|
|
55
|
+
$6::integer[], $7::text[], $8::bigint[]
|
|
56
|
+
) WITH ORDINALITY
|
|
57
|
+
AS c (run_id, unit_key, system, operation, status,
|
|
58
|
+
http_status, idempotency_key, duration_ms, ord)
|
|
59
|
+
`,
|
|
60
|
+
recordStep: `
|
|
61
|
+
INSERT INTO journal_steps
|
|
62
|
+
(run_id, unit_key, step, attempt, outcome,
|
|
63
|
+
reason_code, duration_ms, recorded_at)
|
|
64
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
65
|
+
`,
|
|
66
|
+
unitsForRun: `
|
|
67
|
+
SELECT * FROM journal_units
|
|
68
|
+
WHERE run_id = $1 ORDER BY unit_key LIMIT $2
|
|
69
|
+
`,
|
|
70
|
+
unit: `SELECT * FROM journal_units WHERE run_id = $1 AND unit_key = $2`,
|
|
71
|
+
stepsForUnit: `
|
|
72
|
+
SELECT * FROM journal_steps
|
|
73
|
+
WHERE run_id = $1 AND unit_key = $2 ORDER BY recorded_at, seq
|
|
74
|
+
`,
|
|
75
|
+
callsForUnit: `
|
|
76
|
+
SELECT * FROM journal_calls
|
|
77
|
+
WHERE run_id = $1 AND unit_key = $2 ORDER BY seq
|
|
78
|
+
`,
|
|
79
|
+
latestForUnit: `
|
|
80
|
+
SELECT * FROM journal_units
|
|
81
|
+
WHERE unit_key = $1 ORDER BY recorded_at DESC LIMIT 1
|
|
82
|
+
`,
|
|
83
|
+
// Unquoted aliases fold to lower case in Postgres, so the row keys stay
|
|
84
|
+
// snake_case and are renamed in code.
|
|
85
|
+
failuresByReason: `
|
|
86
|
+
SELECT reason_code, COUNT(*) AS count
|
|
87
|
+
FROM journal_units
|
|
88
|
+
WHERE recorded_at >= $1
|
|
89
|
+
AND reason_code IS NOT NULL
|
|
90
|
+
AND outcome != 'written'
|
|
91
|
+
GROUP BY reason_code
|
|
92
|
+
ORDER BY count DESC, reason_code ASC
|
|
93
|
+
`,
|
|
94
|
+
recentRuns: `SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT $1`,
|
|
95
|
+
// One statement, so the delivery and its tasks land together or not at
|
|
96
|
+
// all. A retried delivery records again and touches no row already there.
|
|
97
|
+
recordDelivery: `
|
|
98
|
+
WITH delivery AS (
|
|
99
|
+
INSERT INTO webhook_deliveries
|
|
100
|
+
(delivery_id, source, topic, shop, webhook_id, body_key, received_at)
|
|
101
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
102
|
+
ON CONFLICT (delivery_id) DO NOTHING
|
|
103
|
+
)
|
|
104
|
+
INSERT INTO webhook_tasks (delivery_id, use_case, state, updated_at)
|
|
105
|
+
SELECT $1, use_case, 'received', $7 FROM unnest($8::text[]) AS use_case
|
|
106
|
+
ON CONFLICT (delivery_id, use_case) DO NOTHING
|
|
107
|
+
`,
|
|
108
|
+
// $5 is the states TASK_TRANSITIONS allows the move from.
|
|
109
|
+
moveTask: `
|
|
110
|
+
UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6,
|
|
111
|
+
requeues = CASE WHEN $3 = 'replayed' THEN 0 ELSE requeues END
|
|
112
|
+
WHERE delivery_id = $1 AND use_case = $2 AND state = ANY($5::text[])
|
|
113
|
+
`,
|
|
114
|
+
delivery: `SELECT * FROM webhook_deliveries WHERE delivery_id = $1`,
|
|
115
|
+
tasksForDelivery: `
|
|
116
|
+
SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY use_case
|
|
117
|
+
`,
|
|
118
|
+
deadTasks: `
|
|
119
|
+
SELECT * FROM webhook_tasks
|
|
120
|
+
WHERE state = 'dead' AND (updated_at, delivery_id, use_case) > ($1, $2, $3)
|
|
121
|
+
ORDER BY updated_at, delivery_id, use_case LIMIT $4
|
|
122
|
+
`,
|
|
123
|
+
deadTasksByUseCase: `
|
|
124
|
+
SELECT * FROM webhook_tasks
|
|
125
|
+
WHERE use_case = $5 AND state = 'dead'
|
|
126
|
+
AND (updated_at, delivery_id, use_case) > ($1, $2, $3)
|
|
127
|
+
ORDER BY updated_at, delivery_id LIMIT $4
|
|
128
|
+
`,
|
|
129
|
+
stuckTasks: `
|
|
130
|
+
SELECT * FROM webhook_tasks
|
|
131
|
+
WHERE state IN ('received', 'processing', 'replayed') AND updated_at < $1
|
|
132
|
+
ORDER BY updated_at, delivery_id, use_case LIMIT $2
|
|
133
|
+
`,
|
|
134
|
+
// The state and updated_at the sweeper read are re-checked in the write, so
|
|
135
|
+
// a task that moved since, or another sweeper's claim, makes it change no row.
|
|
136
|
+
reclaimStuckTask: `
|
|
137
|
+
UPDATE webhook_tasks SET
|
|
138
|
+
updated_at = $5,
|
|
139
|
+
state = CASE WHEN $4 = 'dead' THEN 'dead' ELSE state END,
|
|
140
|
+
reason_code = CASE WHEN $4 = 'dead' THEN 'stuck' ELSE reason_code END,
|
|
141
|
+
requeues = CASE WHEN $4 = 'dead' THEN requeues ELSE requeues + 1 END
|
|
142
|
+
WHERE delivery_id = $1 AND use_case = $2 AND updated_at = $3
|
|
143
|
+
AND state IN ('received', 'processing', 'replayed')
|
|
144
|
+
`,
|
|
145
|
+
};
|
|
146
|
+
export class PostgresJournal {
|
|
147
|
+
o;
|
|
148
|
+
constructor(o) {
|
|
149
|
+
this.o = o;
|
|
150
|
+
}
|
|
151
|
+
async startRun(row) {
|
|
152
|
+
await this.#call('startRun', async () => this.o.pool.query(Q.startRun, [
|
|
153
|
+
row.runId,
|
|
154
|
+
row.job,
|
|
155
|
+
row.trigger,
|
|
156
|
+
row.mode,
|
|
157
|
+
row.startedAt,
|
|
158
|
+
JSON.stringify(row.identity),
|
|
159
|
+
]));
|
|
160
|
+
}
|
|
161
|
+
async finishRun(runId, endedAt) {
|
|
162
|
+
await this.#call('finishRun', async () => this.o.pool.query(Q.finishRun, [runId, endedAt]));
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* One transaction, so a unit is never half recorded: the unit row, the
|
|
166
|
+
* clear of its previous calls, and all its calls in one INSERT.
|
|
167
|
+
*/
|
|
168
|
+
async recordUnit(unit, calls) {
|
|
169
|
+
await this.#call('recordUnit', async () => withClient(this.o.pool, async (client) => {
|
|
170
|
+
try {
|
|
171
|
+
await client.query('BEGIN');
|
|
172
|
+
await client.query(Q.recordUnit, [
|
|
173
|
+
unit.runId,
|
|
174
|
+
unit.unitKey,
|
|
175
|
+
unit.unitType,
|
|
176
|
+
unit.recordedAt,
|
|
177
|
+
unit.outcome,
|
|
178
|
+
unit.reasonCode ?? null,
|
|
179
|
+
unit.planHash ?? null,
|
|
180
|
+
unit.planRef ?? null,
|
|
181
|
+
unit.durationMs,
|
|
182
|
+
unit.externalIds === undefined
|
|
183
|
+
? null
|
|
184
|
+
: JSON.stringify(unit.externalIds),
|
|
185
|
+
]);
|
|
186
|
+
await client.query(Q.clearCalls, [unit.runId, unit.unitKey]);
|
|
187
|
+
if (calls.length > 0) {
|
|
188
|
+
await client.query(Q.recordCalls, [
|
|
189
|
+
calls.map((c) => c.runId),
|
|
190
|
+
calls.map((c) => c.unitKey),
|
|
191
|
+
calls.map((c) => c.system),
|
|
192
|
+
calls.map((c) => c.operation),
|
|
193
|
+
calls.map((c) => c.status),
|
|
194
|
+
calls.map((c) => c.httpStatus ?? null),
|
|
195
|
+
calls.map((c) => c.idempotencyKey ?? null),
|
|
196
|
+
calls.map((c) => c.durationMs ?? null),
|
|
197
|
+
]);
|
|
198
|
+
}
|
|
199
|
+
await client.query('COMMIT');
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
203
|
+
throw error;
|
|
204
|
+
}
|
|
205
|
+
}));
|
|
206
|
+
}
|
|
207
|
+
/** Catches every failure and logs it, as the contract requires. */
|
|
208
|
+
async recordStep(step) {
|
|
209
|
+
try {
|
|
210
|
+
await this.#call('recordStep', async () => this.o.pool.query(Q.recordStep, [
|
|
211
|
+
step.runId,
|
|
212
|
+
step.unitKey,
|
|
213
|
+
step.step,
|
|
214
|
+
step.attempt,
|
|
215
|
+
step.outcome,
|
|
216
|
+
step.reasonCode ?? null,
|
|
217
|
+
step.durationMs,
|
|
218
|
+
step.recordedAt,
|
|
219
|
+
]));
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
this.o.logger.error('journal step row not recorded', {
|
|
223
|
+
tool: TOOL,
|
|
224
|
+
operation: 'recordStep',
|
|
225
|
+
fault: e instanceof Error ? e.name : 'unknown',
|
|
226
|
+
runId: step.runId,
|
|
227
|
+
unitKey: step.unitKey,
|
|
228
|
+
step: step.step,
|
|
229
|
+
attempt: step.attempt,
|
|
230
|
+
outcome: step.outcome,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async unitsForRun(runId, limit = DEFAULT_UNIT_LIMIT) {
|
|
235
|
+
const { rows } = await this.#call('unitsForRun', async () => this.o.pool.query(Q.unitsForRun, [runId, limit]));
|
|
236
|
+
return rows.map(toUnitRow);
|
|
237
|
+
}
|
|
238
|
+
async unit(runId, unitKey) {
|
|
239
|
+
const [units, steps, calls] = await this.#call('unit', async () => Promise.all([
|
|
240
|
+
this.o.pool.query(Q.unit, [runId, unitKey]),
|
|
241
|
+
this.o.pool.query(Q.stepsForUnit, [runId, unitKey]),
|
|
242
|
+
this.o.pool.query(Q.callsForUnit, [runId, unitKey]),
|
|
243
|
+
]));
|
|
244
|
+
const record = units.rows[0];
|
|
245
|
+
if (record === undefined) {
|
|
246
|
+
return undefined;
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
unit: toUnitRow(record),
|
|
250
|
+
steps: steps.rows.map(toStepRow),
|
|
251
|
+
calls: calls.rows.map(toCallRow),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
async latestForUnit(unitKey) {
|
|
255
|
+
const { rows } = await this.#call('latestForUnit', async () => this.o.pool.query(Q.latestForUnit, [unitKey]));
|
|
256
|
+
const record = rows[0];
|
|
257
|
+
return record === undefined ? undefined : toUnitRow(record);
|
|
258
|
+
}
|
|
259
|
+
async failuresByReason(since) {
|
|
260
|
+
const { rows } = await this.#call('failuresByReason', async () => this.o.pool.query(Q.failuresByReason, [since]));
|
|
261
|
+
// COUNT(*) is a BIGINT, which arrives as a string.
|
|
262
|
+
return rows.map((r) => ({
|
|
263
|
+
reasonCode: r.reason_code,
|
|
264
|
+
count: Number(r.count),
|
|
265
|
+
}));
|
|
266
|
+
}
|
|
267
|
+
async recentRuns(limit = DEFAULT_RUN_LIMIT) {
|
|
268
|
+
const { rows } = await this.#call('recentRuns', async () => this.o.pool.query(Q.recentRuns, [limit]));
|
|
269
|
+
return rows.map(toRunRow);
|
|
270
|
+
}
|
|
271
|
+
async recordDelivery(delivery, useCases) {
|
|
272
|
+
await this.#call('recordDelivery', async () => this.o.pool.query(Q.recordDelivery, [
|
|
273
|
+
delivery.deliveryId,
|
|
274
|
+
delivery.source,
|
|
275
|
+
delivery.topic,
|
|
276
|
+
delivery.shop,
|
|
277
|
+
delivery.webhookId,
|
|
278
|
+
delivery.bodyKey,
|
|
279
|
+
delivery.receivedAt,
|
|
280
|
+
useCases,
|
|
281
|
+
]));
|
|
282
|
+
}
|
|
283
|
+
async moveTask(deliveryId, useCase, to, at, reasonCode) {
|
|
284
|
+
const { rowCount } = await this.#call('moveTask', async () => this.o.pool.query(Q.moveTask, [
|
|
285
|
+
deliveryId,
|
|
286
|
+
useCase,
|
|
287
|
+
to,
|
|
288
|
+
at,
|
|
289
|
+
TASK_TRANSITIONS[to],
|
|
290
|
+
reasonCode ?? null,
|
|
291
|
+
]));
|
|
292
|
+
return rowCount === 1;
|
|
293
|
+
}
|
|
294
|
+
async delivery(deliveryId) {
|
|
295
|
+
const [delivery, tasks] = await this.#call('delivery', async () => Promise.all([
|
|
296
|
+
this.o.pool.query(Q.delivery, [deliveryId]),
|
|
297
|
+
this.o.pool.query(Q.tasksForDelivery, [deliveryId]),
|
|
298
|
+
]));
|
|
299
|
+
const record = delivery.rows[0];
|
|
300
|
+
return record === undefined
|
|
301
|
+
? undefined
|
|
302
|
+
: { delivery: toDeliveryRow(record), tasks: tasks.rows.map(toTaskRow) };
|
|
303
|
+
}
|
|
304
|
+
async deadTasks({ useCase, after = FIRST_TASK, limit = DEFAULT_UNIT_LIMIT, } = {}) {
|
|
305
|
+
const cursor = [after.updatedAt, after.deliveryId, after.useCase, limit];
|
|
306
|
+
const { rows } = await this.#call('deadTasks', async () => useCase === undefined
|
|
307
|
+
? this.o.pool.query(Q.deadTasks, cursor)
|
|
308
|
+
: this.o.pool.query(Q.deadTasksByUseCase, [
|
|
309
|
+
...cursor,
|
|
310
|
+
useCase,
|
|
311
|
+
]));
|
|
312
|
+
return rows.map(toTaskRow);
|
|
313
|
+
}
|
|
314
|
+
async stuckTasks(before, limit = DEFAULT_UNIT_LIMIT) {
|
|
315
|
+
const { rows } = await this.#call('stuckTasks', async () => this.o.pool.query(Q.stuckTasks, [before, limit]));
|
|
316
|
+
return rows.map(toTaskRow);
|
|
317
|
+
}
|
|
318
|
+
async reclaimStuckTask(task, at, to) {
|
|
319
|
+
const { rowCount } = await this.#call('reclaimStuckTask', async () => this.o.pool.query(Q.reclaimStuckTask, [
|
|
320
|
+
task.deliveryId,
|
|
321
|
+
task.useCase,
|
|
322
|
+
task.updatedAt,
|
|
323
|
+
to,
|
|
324
|
+
at,
|
|
325
|
+
]));
|
|
326
|
+
return rowCount === 1;
|
|
327
|
+
}
|
|
328
|
+
async #call(operation, f) {
|
|
329
|
+
try {
|
|
330
|
+
return await f();
|
|
331
|
+
}
|
|
332
|
+
catch (e) {
|
|
333
|
+
throw toFault(TOOL, operation, e);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
export { Q as JOURNAL_QUERIES };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type pg from 'pg';
|
|
2
|
+
import type { ClaimResult, Clock, Ledger } from '../../contracts/index.js';
|
|
3
|
+
export type PostgresLedgerOptions = {
|
|
4
|
+
/** The app's pool. The ledger never opens its own. docs/decisions/0007. */
|
|
5
|
+
readonly pool: pg.Pool;
|
|
6
|
+
readonly clock: Clock;
|
|
7
|
+
};
|
|
8
|
+
export declare class PostgresLedger implements Ledger {
|
|
9
|
+
#private;
|
|
10
|
+
private readonly o;
|
|
11
|
+
constructor(o: PostgresLedgerOptions);
|
|
12
|
+
claim(key: string, leaseSeconds: number): Promise<ClaimResult>;
|
|
13
|
+
complete(key: string, ttlSeconds: number): Promise<void>;
|
|
14
|
+
/** Releasing a key that was never claimed deletes nothing and is not an error. */
|
|
15
|
+
release(key: string): Promise<void>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { Unavailable, fromEpochMs, toIso } from '../../contracts/index.js';
|
|
2
|
+
import { isSerializationFailure, toFault } from './faults.js';
|
|
3
|
+
const TOOL = 'ledger';
|
|
4
|
+
/**
|
|
5
|
+
* One conditional write, as in the D1 ledger, whose comments say why a
|
|
6
|
+
* SELECT-then-INSERT would lose a race. `key` is the primary key, so two
|
|
7
|
+
* concurrent claims cannot both insert. The loser of an insert race waits for
|
|
8
|
+
* the winner to commit, then evaluates the `WHERE` against the winner's row,
|
|
9
|
+
* which refuses while the lease is live.
|
|
10
|
+
*
|
|
11
|
+
* `$2` is the caller's `now`, from the injected Clock, never `now()`: the
|
|
12
|
+
* suite advances a test clock and expects a reclaim.
|
|
13
|
+
*/
|
|
14
|
+
const CLAIM = `
|
|
15
|
+
INSERT INTO ledger_claims (key, claimed_at, expires_at)
|
|
16
|
+
VALUES ($1, $2, $3)
|
|
17
|
+
ON CONFLICT (key) DO UPDATE SET claimed_at = $2, expires_at = $3,
|
|
18
|
+
completed_at = NULL
|
|
19
|
+
WHERE ledger_claims.expires_at <= $2
|
|
20
|
+
RETURNING claimed_at
|
|
21
|
+
`;
|
|
22
|
+
/** Only ever asked after the write above has already decided we lost. */
|
|
23
|
+
const HOLDER = `SELECT claimed_at, completed_at FROM ledger_claims WHERE key = $1`;
|
|
24
|
+
/**
|
|
25
|
+
* An upsert, not an update: there is no token to check the holder against, and
|
|
26
|
+
* a row that was released or swept still had its work done.
|
|
27
|
+
*/
|
|
28
|
+
const COMPLETE = `
|
|
29
|
+
INSERT INTO ledger_claims (key, claimed_at, expires_at, completed_at)
|
|
30
|
+
VALUES ($1, $2, $3, $2)
|
|
31
|
+
ON CONFLICT (key) DO UPDATE SET completed_at = $2, expires_at = $3
|
|
32
|
+
`;
|
|
33
|
+
const RELEASE = `DELETE FROM ledger_claims WHERE key = $1`;
|
|
34
|
+
/** As in the D1 ledger: a holder that vanished three times running is a fault. */
|
|
35
|
+
const ATTEMPTS = 3;
|
|
36
|
+
export class PostgresLedger {
|
|
37
|
+
o;
|
|
38
|
+
constructor(o) {
|
|
39
|
+
this.o = o;
|
|
40
|
+
}
|
|
41
|
+
async claim(key, leaseSeconds) {
|
|
42
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
|
|
43
|
+
const now = this.o.clock.now();
|
|
44
|
+
const expiresAt = now + leaseSeconds * 1000;
|
|
45
|
+
const won = await this.#call('claim', async () => {
|
|
46
|
+
try {
|
|
47
|
+
return await this.o.pool.query(CLAIM, [key, now, expiresAt]);
|
|
48
|
+
}
|
|
49
|
+
catch (e) {
|
|
50
|
+
// The app may run its pool at REPEATABLE READ or SERIALIZABLE. There
|
|
51
|
+
// a lost race is this error rather than an empty RETURNING, and the
|
|
52
|
+
// read below finds the winner either way.
|
|
53
|
+
if (isSerializationFailure(e)) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
if (won?.rowCount === 1) {
|
|
60
|
+
return { status: 'claimed' };
|
|
61
|
+
}
|
|
62
|
+
const holder = await this.#call('claim', async () => this.o.pool.query(HOLDER, [key]));
|
|
63
|
+
const row = holder.rows[0];
|
|
64
|
+
if (row !== undefined) {
|
|
65
|
+
// BIGINT arrives as a string. Exact up to 2^53 ms. docs/decisions/0007.
|
|
66
|
+
return row.completed_at === null
|
|
67
|
+
? {
|
|
68
|
+
status: 'in-progress',
|
|
69
|
+
claimedAt: toIso(fromEpochMs(Number(row.claimed_at))),
|
|
70
|
+
}
|
|
71
|
+
: {
|
|
72
|
+
status: 'completed',
|
|
73
|
+
completedAt: toIso(fromEpochMs(Number(row.completed_at))),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
throw new Unavailable(TOOL, `claim on '${key}' found neither a winner nor a holder in ${ATTEMPTS} attempts`);
|
|
78
|
+
}
|
|
79
|
+
async complete(key, ttlSeconds) {
|
|
80
|
+
const now = this.o.clock.now();
|
|
81
|
+
await this.#call('complete', async () => this.o.pool.query(COMPLETE, [key, now, now + ttlSeconds * 1000]));
|
|
82
|
+
}
|
|
83
|
+
/** Releasing a key that was never claimed deletes nothing and is not an error. */
|
|
84
|
+
async release(key) {
|
|
85
|
+
await this.#call('release', async () => this.o.pool.query(RELEASE, [key]));
|
|
86
|
+
}
|
|
87
|
+
async #call(operation, f) {
|
|
88
|
+
try {
|
|
89
|
+
return await f();
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
// A unique violation is absent on purpose: ON CONFLICT handles the
|
|
93
|
+
// collision, so losing a race is an empty RETURNING, never an error.
|
|
94
|
+
throw toFault(TOOL, operation, e);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { DeploymentIdentity, LogFields, Logger } from '../../contracts/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* One JSON object per line on stdout, which is where a container platform
|
|
4
|
+
* collects a process's logs. The level is a field, so every level goes to the
|
|
5
|
+
* same stream and a reader filters on it.
|
|
6
|
+
*
|
|
7
|
+
* `identity` and `correlationId` are written last, after `fields`, so a field
|
|
8
|
+
* a caller passes can never shadow them. CloudflareLogger does the same.
|
|
9
|
+
*/
|
|
10
|
+
export declare class StdoutLogger implements Logger {
|
|
11
|
+
#private;
|
|
12
|
+
readonly identity: DeploymentIdentity;
|
|
13
|
+
readonly correlationId: string;
|
|
14
|
+
constructor(identity: DeploymentIdentity, correlationId: string);
|
|
15
|
+
info(message: string, fields?: LogFields): void;
|
|
16
|
+
warn(message: string, fields?: LogFields): void;
|
|
17
|
+
error(message: string, fields?: LogFields): void;
|
|
18
|
+
child(correlationId: string): Logger;
|
|
19
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One JSON object per line on stdout, which is where a container platform
|
|
3
|
+
* collects a process's logs. The level is a field, so every level goes to the
|
|
4
|
+
* same stream and a reader filters on it.
|
|
5
|
+
*
|
|
6
|
+
* `identity` and `correlationId` are written last, after `fields`, so a field
|
|
7
|
+
* a caller passes can never shadow them. CloudflareLogger does the same.
|
|
8
|
+
*/
|
|
9
|
+
export class StdoutLogger {
|
|
10
|
+
identity;
|
|
11
|
+
correlationId;
|
|
12
|
+
constructor(identity, correlationId) {
|
|
13
|
+
this.identity = identity;
|
|
14
|
+
this.correlationId = correlationId;
|
|
15
|
+
}
|
|
16
|
+
info(message, fields = {}) {
|
|
17
|
+
this.#write('info', message, fields);
|
|
18
|
+
}
|
|
19
|
+
warn(message, fields = {}) {
|
|
20
|
+
this.#write('warn', message, fields);
|
|
21
|
+
}
|
|
22
|
+
error(message, fields = {}) {
|
|
23
|
+
this.#write('error', message, fields);
|
|
24
|
+
}
|
|
25
|
+
child(correlationId) {
|
|
26
|
+
return new StdoutLogger(this.identity, correlationId);
|
|
27
|
+
}
|
|
28
|
+
#write(level, message, fields) {
|
|
29
|
+
process.stdout.write(JSON.stringify({
|
|
30
|
+
...fields,
|
|
31
|
+
level,
|
|
32
|
+
message,
|
|
33
|
+
identity: this.identity,
|
|
34
|
+
correlationId: this.correlationId,
|
|
35
|
+
}) + '\n');
|
|
36
|
+
}
|
|
37
|
+
}
|