@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,104 @@
|
|
|
1
|
+
import { sweepBounds } from '../retention.js';
|
|
2
|
+
import { toFault } from './faults.js';
|
|
3
|
+
import { withClient } from './with-client.js';
|
|
4
|
+
export { DEFAULT_RETENTION_SECONDS } from '../retention.js';
|
|
5
|
+
/**
|
|
6
|
+
* The twin of the D1 sweep in ../cloudflare/retention.ts, which says why. The
|
|
7
|
+
* outer `expires_at < $1` is what Postgres re-checks on a row a concurrent
|
|
8
|
+
* claim just renewed; the subquery's rows come from the statement's snapshot.
|
|
9
|
+
* Without it the sweep waits on that claim, then deletes its live lease.
|
|
10
|
+
*/
|
|
11
|
+
const SWEEP_LEDGER = `
|
|
12
|
+
DELETE FROM ledger_claims WHERE expires_at < $1 AND key IN (
|
|
13
|
+
SELECT key FROM ledger_claims WHERE expires_at < $1
|
|
14
|
+
ORDER BY expires_at LIMIT $2
|
|
15
|
+
)
|
|
16
|
+
`;
|
|
17
|
+
const SWEPT_DELIVERIES = `
|
|
18
|
+
SELECT delivery_id, body_key FROM webhook_deliveries d
|
|
19
|
+
WHERE received_at < $1 AND NOT EXISTS (
|
|
20
|
+
SELECT 1 FROM webhook_tasks t
|
|
21
|
+
WHERE t.delivery_id = d.delivery_id AND t.state NOT IN ('done', 'dead')
|
|
22
|
+
)
|
|
23
|
+
ORDER BY received_at LIMIT $2
|
|
24
|
+
`;
|
|
25
|
+
/**
|
|
26
|
+
* Run in one READ COMMITTED transaction, in this order. A replay may move a
|
|
27
|
+
* task dead → replayed while the bodies are deleted; its rows must then stay,
|
|
28
|
+
* so its retry fails visibly. One statement cannot promise that: its CTEs all
|
|
29
|
+
* read the snapshot it started with. So the tasks are locked first, which makes
|
|
30
|
+
* a concurrent move wait or be seen, and each delete after it is a new
|
|
31
|
+
* statement that reads every move committed before the lock.
|
|
32
|
+
*/
|
|
33
|
+
const LOCK_TASKS = `
|
|
34
|
+
SELECT 1 FROM webhook_tasks WHERE delivery_id = ANY($1::text[]) FOR UPDATE
|
|
35
|
+
`;
|
|
36
|
+
const DELETE_TASKS = `
|
|
37
|
+
DELETE FROM webhook_tasks
|
|
38
|
+
WHERE delivery_id = ANY($1::text[])
|
|
39
|
+
AND NOT EXISTS (
|
|
40
|
+
SELECT 1 FROM webhook_tasks k
|
|
41
|
+
WHERE k.delivery_id = webhook_tasks.delivery_id
|
|
42
|
+
AND k.state NOT IN ('done', 'dead')
|
|
43
|
+
)
|
|
44
|
+
`;
|
|
45
|
+
// After DELETE_TASKS, so a delivery that kept a task keeps its row.
|
|
46
|
+
const DELETE_DELIVERIES = `
|
|
47
|
+
DELETE FROM webhook_deliveries
|
|
48
|
+
WHERE delivery_id = ANY($1::text[])
|
|
49
|
+
AND NOT EXISTS (
|
|
50
|
+
SELECT 1 FROM webhook_tasks t
|
|
51
|
+
WHERE t.delivery_id = webhook_deliveries.delivery_id
|
|
52
|
+
)
|
|
53
|
+
`;
|
|
54
|
+
/** Deletes one batch of ledger claims whose lease ended `olderThanSeconds` ago. */
|
|
55
|
+
export async function sweepLedger(deps, options = {}) {
|
|
56
|
+
const { cutoff, limit } = sweepBounds('ledger', deps.clock, options, 1_000);
|
|
57
|
+
try {
|
|
58
|
+
const result = await deps.pool.query(SWEEP_LEDGER, [cutoff, limit]);
|
|
59
|
+
return result.rowCount ?? 0;
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
throw toFault('ledger', 'sweepLedger', e);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Deletes one batch of webhook receipts past retention, and their raw bodies,
|
|
67
|
+
* bodies first. Returns how many deliveries it deleted.
|
|
68
|
+
*/
|
|
69
|
+
export async function sweepWebhookReceipts(deps, options = {}) {
|
|
70
|
+
const { cutoff, limit } = sweepBounds('journal', deps.clock, options, 100);
|
|
71
|
+
let rows;
|
|
72
|
+
try {
|
|
73
|
+
;
|
|
74
|
+
({ rows } = await deps.pool.query(SWEPT_DELIVERIES, [cutoff, limit]));
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
throw toFault('journal', 'sweepWebhookReceipts', e);
|
|
78
|
+
}
|
|
79
|
+
if (rows.length === 0) {
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
await Promise.all(rows.map(async (r) => deps.blobStore.delete(r.body_key)));
|
|
83
|
+
const ids = [rows.map((r) => r.delivery_id)];
|
|
84
|
+
try {
|
|
85
|
+
await withClient(deps.pool, async (client) => {
|
|
86
|
+
try {
|
|
87
|
+
// Pinned, since the order above relies on it whatever the app's default.
|
|
88
|
+
await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
|
|
89
|
+
await client.query(LOCK_TASKS, ids);
|
|
90
|
+
await client.query(DELETE_TASKS, ids);
|
|
91
|
+
await client.query(DELETE_DELIVERIES, ids);
|
|
92
|
+
await client.query('COMMIT');
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
throw toFault('journal', 'sweepWebhookReceipts', e);
|
|
102
|
+
}
|
|
103
|
+
return rows.length;
|
|
104
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Session } from '@shopify/shopify-api';
|
|
2
|
+
import type pg from 'pg';
|
|
3
|
+
import type { SessionStorage } from '../../contracts/index.js';
|
|
4
|
+
export type PostgresSessionStorageOptions = {
|
|
5
|
+
/** The app's pool. The storage never opens its own. docs/decisions/0007. */
|
|
6
|
+
readonly pool: pg.Pool;
|
|
7
|
+
/** The raw secret, base64 decoding to 32 bytes. docs/decisions/0005. */
|
|
8
|
+
readonly key: string;
|
|
9
|
+
};
|
|
10
|
+
export declare class PostgresSessionStorage implements SessionStorage {
|
|
11
|
+
#private;
|
|
12
|
+
private readonly o;
|
|
13
|
+
constructor(o: PostgresSessionStorageOptions);
|
|
14
|
+
storeSession(session: Session): Promise<boolean>;
|
|
15
|
+
loadSession(id: string): Promise<Session | undefined>;
|
|
16
|
+
/** True even when nothing was stored, as Shopify's own storages answer. */
|
|
17
|
+
deleteSession(id: string): Promise<boolean>;
|
|
18
|
+
deleteSessions(ids: string[]): Promise<boolean>;
|
|
19
|
+
findSessionsByShop(shop: string): Promise<Session[]>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { SessionEnvelope } from '../session-envelope.js';
|
|
2
|
+
import { toFault } from './faults.js';
|
|
3
|
+
const TOOL = 'sessions';
|
|
4
|
+
/**
|
|
5
|
+
* The D1 session storage's queries with `$n` placeholders. `id` and `shop`
|
|
6
|
+
* are the only plaintext columns, the only two things looked up by.
|
|
7
|
+
*/
|
|
8
|
+
const Q = {
|
|
9
|
+
store: `
|
|
10
|
+
INSERT INTO shopify_sessions (id, shop, version, iv, ciphertext)
|
|
11
|
+
VALUES ($1, $2, $3, $4, $5)
|
|
12
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
13
|
+
shop = $2, version = $3, iv = $4, ciphertext = $5
|
|
14
|
+
`,
|
|
15
|
+
load: `SELECT shop, iv, ciphertext FROM shopify_sessions WHERE id = $1`,
|
|
16
|
+
deleteMany: `DELETE FROM shopify_sessions WHERE id = ANY($1::text[])`,
|
|
17
|
+
findByShop: `
|
|
18
|
+
SELECT id, shop, iv, ciphertext FROM shopify_sessions WHERE shop = $1
|
|
19
|
+
`,
|
|
20
|
+
};
|
|
21
|
+
/** A copy into its own ArrayBuffer, which WebCrypto's types ask for. */
|
|
22
|
+
const bytes = (b) => new Uint8Array(b);
|
|
23
|
+
export class PostgresSessionStorage {
|
|
24
|
+
o;
|
|
25
|
+
#envelope;
|
|
26
|
+
constructor(o) {
|
|
27
|
+
this.o = o;
|
|
28
|
+
this.#envelope = new SessionEnvelope(o.key);
|
|
29
|
+
}
|
|
30
|
+
async storeSession(session) {
|
|
31
|
+
const { version, iv, ciphertext } = await this.#envelope.seal(session);
|
|
32
|
+
await this.#call('storeSession', async () => this.o.pool.query(Q.store, [
|
|
33
|
+
session.id,
|
|
34
|
+
session.shop,
|
|
35
|
+
version,
|
|
36
|
+
Buffer.from(iv),
|
|
37
|
+
Buffer.from(ciphertext),
|
|
38
|
+
]));
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
async loadSession(id) {
|
|
42
|
+
const { rows } = await this.#call('loadSession', async () => this.o.pool.query(Q.load, [id]));
|
|
43
|
+
const row = rows[0];
|
|
44
|
+
return row === undefined
|
|
45
|
+
? undefined
|
|
46
|
+
: this.#envelope.open(id, row.shop, bytes(row.iv), bytes(row.ciphertext));
|
|
47
|
+
}
|
|
48
|
+
/** True even when nothing was stored, as Shopify's own storages answer. */
|
|
49
|
+
async deleteSession(id) {
|
|
50
|
+
return this.#delete('deleteSession', [id]);
|
|
51
|
+
}
|
|
52
|
+
async deleteSessions(ids) {
|
|
53
|
+
return this.#delete('deleteSessions', ids);
|
|
54
|
+
}
|
|
55
|
+
async findSessionsByShop(shop) {
|
|
56
|
+
const { rows } = await this.#call('findSessionsByShop', async () => this.o.pool.query(Q.findByShop, [shop]));
|
|
57
|
+
return Promise.all(rows.map(async (row) => this.#envelope.open(row.id, row.shop, bytes(row.iv), bytes(row.ciphertext))));
|
|
58
|
+
}
|
|
59
|
+
async #delete(operation, ids) {
|
|
60
|
+
await this.#call(operation, async () => this.o.pool.query(Q.deleteMany, [ids]));
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
async #call(operation, f) {
|
|
64
|
+
try {
|
|
65
|
+
return await f();
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
throw toFault(TOOL, operation, e);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type pg from 'pg';
|
|
2
|
+
import type { DeploymentIdentity, Toolkit } from '../../contracts/index.js';
|
|
3
|
+
import type { PostgresToolkitConfig } from './config.js';
|
|
4
|
+
import { PostgresQueue } from './queue.js';
|
|
5
|
+
export type PostgresToolkitOptions = {
|
|
6
|
+
/** The app's pool, built with its own timeouts. docs/decisions/0007. */
|
|
7
|
+
readonly pool: pg.Pool;
|
|
8
|
+
readonly config: PostgresToolkitConfig;
|
|
9
|
+
readonly identity: DeploymentIdentity;
|
|
10
|
+
readonly correlationId?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Deliveries before either queue dead-letters a message. Default 5. Give
|
|
13
|
+
* the queues' consumers the same `maxAttempts`, or the last attempt they
|
|
14
|
+
* record is not the queue's last.
|
|
15
|
+
*/
|
|
16
|
+
readonly queueMaxAttempts?: number;
|
|
17
|
+
};
|
|
18
|
+
/** The queues are the concrete type, so a Node worker can call `run`. */
|
|
19
|
+
export type PostgresToolkit<QueueBody = unknown, WebhookBody = unknown> = Toolkit<QueueBody, WebhookBody> & {
|
|
20
|
+
readonly queue: PostgresQueue<QueueBody>;
|
|
21
|
+
readonly webhookQueue: PostgresQueue<WebhookBody>;
|
|
22
|
+
/** Ends the pool and the S3 client. Call once, after the queue loops stop. */
|
|
23
|
+
close(): Promise<void>;
|
|
24
|
+
};
|
|
25
|
+
export declare function createPostgresToolkit<QueueBody = unknown, WebhookBody = unknown>(o: PostgresToolkitOptions): PostgresToolkit<QueueBody, WebhookBody>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { S3Client } from '@aws-sdk/client-s3';
|
|
3
|
+
import { S3BlobStore } from '../s3/blob-store.js';
|
|
4
|
+
import { systemClock } from '../system-clock.js';
|
|
5
|
+
import { PostgresCache } from './cache.js';
|
|
6
|
+
import { PostgresJournal } from './journal.js';
|
|
7
|
+
import { PostgresLedger } from './ledger.js';
|
|
8
|
+
import { StdoutLogger } from './logger.js';
|
|
9
|
+
import { POSTGRES_MANIFEST } from './manifest.js';
|
|
10
|
+
import { PostgresQueue } from './queue.js';
|
|
11
|
+
/**
|
|
12
|
+
* One table serves every queue. A toolkit has two: the app's, and the webhook
|
|
13
|
+
* pointers', which keep their own attempts and dead letters. docs/decisions/0011.
|
|
14
|
+
*/
|
|
15
|
+
const QUEUE_NAME = 'default';
|
|
16
|
+
const WEBHOOK_QUEUE_NAME = 'webhooks';
|
|
17
|
+
export function createPostgresToolkit(o) {
|
|
18
|
+
const clock = systemClock();
|
|
19
|
+
const queueOptions = {
|
|
20
|
+
pool: o.pool,
|
|
21
|
+
clock,
|
|
22
|
+
identity: o.identity,
|
|
23
|
+
maxDelaySeconds: POSTGRES_MANIFEST.queueDelayMaxSeconds,
|
|
24
|
+
maxBytes: POSTGRES_MANIFEST.messageMaxBytes,
|
|
25
|
+
...(o.queueMaxAttempts === undefined
|
|
26
|
+
? {}
|
|
27
|
+
: { maxAttempts: o.queueMaxAttempts }),
|
|
28
|
+
};
|
|
29
|
+
const logger = new StdoutLogger(o.identity, o.correlationId ?? randomUUID());
|
|
30
|
+
// No credentials means the SDK's default chain: the host's role on AWS.
|
|
31
|
+
const { bucket, ...client } = o.config.s3;
|
|
32
|
+
const s3 = new S3Client(client);
|
|
33
|
+
return {
|
|
34
|
+
cache: new PostgresCache({
|
|
35
|
+
pool: o.pool,
|
|
36
|
+
clock,
|
|
37
|
+
minTtlSeconds: POSTGRES_MANIFEST.cacheMinTtlSeconds,
|
|
38
|
+
}),
|
|
39
|
+
blobStore: new S3BlobStore({
|
|
40
|
+
client: s3,
|
|
41
|
+
bucket,
|
|
42
|
+
maxBytes: POSTGRES_MANIFEST.blobMaxBytes,
|
|
43
|
+
}),
|
|
44
|
+
queue: new PostgresQueue({ ...queueOptions, name: QUEUE_NAME }),
|
|
45
|
+
webhookQueue: new PostgresQueue({
|
|
46
|
+
...queueOptions,
|
|
47
|
+
name: WEBHOOK_QUEUE_NAME,
|
|
48
|
+
}),
|
|
49
|
+
ledger: new PostgresLedger({ pool: o.pool, clock }),
|
|
50
|
+
journal: new PostgresJournal({ pool: o.pool, logger }),
|
|
51
|
+
logger,
|
|
52
|
+
clock,
|
|
53
|
+
close: async () => {
|
|
54
|
+
s3.destroy();
|
|
55
|
+
await o.pool.end();
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type pg from 'pg';
|
|
2
|
+
/**
|
|
3
|
+
* Lends `f` one client from the pool, for statements that must share a
|
|
4
|
+
* connection: a transaction, or a lock held across them.
|
|
5
|
+
*
|
|
6
|
+
* pg-pool takes its own 'error' listener off a client while it is lent out,
|
|
7
|
+
* so a connection that dropped then (a restart, a failover) would be an
|
|
8
|
+
* unhandled 'error' event, and Node would exit. The drop still rejects the
|
|
9
|
+
* query `f` is waiting on, so the caller sees it as a failure.
|
|
10
|
+
*/
|
|
11
|
+
export declare function withClient<T>(pool: pg.Pool, f: (client: pg.PoolClient) => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lends `f` one client from the pool, for statements that must share a
|
|
3
|
+
* connection: a transaction, or a lock held across them.
|
|
4
|
+
*
|
|
5
|
+
* pg-pool takes its own 'error' listener off a client while it is lent out,
|
|
6
|
+
* so a connection that dropped then (a restart, a failover) would be an
|
|
7
|
+
* unhandled 'error' event, and Node would exit. The drop still rejects the
|
|
8
|
+
* query `f` is waiting on, so the caller sees it as a failure.
|
|
9
|
+
*/
|
|
10
|
+
export async function withClient(pool, f) {
|
|
11
|
+
const client = await pool.connect();
|
|
12
|
+
const ignore = () => { };
|
|
13
|
+
let failed = false;
|
|
14
|
+
client.on('error', ignore);
|
|
15
|
+
try {
|
|
16
|
+
return await f(client);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
failed = true;
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
finally {
|
|
23
|
+
client.removeListener('error', ignore);
|
|
24
|
+
// A failed client may sit on a dead connection. Ending it, rather than
|
|
25
|
+
// returning it, means that connection cannot raise its error later, in
|
|
26
|
+
// the pool, after this listener is gone.
|
|
27
|
+
client.release(failed);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import type { Clock, DispatchOptions, DispatchResult, Exhaustion, Instant, PipelineDefinition, PipelineInstanceId, PipelineRegistration, PipelineStatus, Pipelines, Journal, JsonValue, Logger, Queue, QueueBatch, ToolManifest } from '../contracts/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* THE REFERENCE EXECUTOR'S ALGORITHM, ONCE, FOR EVERY ADAPTER THAT SHIPS IT.
|
|
4
|
+
*
|
|
5
|
+
* docs/decisions/0006 is the specification. This file is that protocol and
|
|
6
|
+
* nothing else: every adapter that runs Pipelines without a native executor (the
|
|
7
|
+
* memory adapter, D1 on Cloudflare, Postgres later) builds this class over its
|
|
8
|
+
* own `ReferenceStore` and its own queue. Two executors that share a name but
|
|
9
|
+
* not an algorithm double the bugs (#69), so the storage is the only thing an
|
|
10
|
+
* adapter writes.
|
|
11
|
+
*
|
|
12
|
+
* It lives above the adapters, as `system-clock.ts` does, because a real
|
|
13
|
+
* adapter needs it and must not import it from `adapters/memory`.
|
|
14
|
+
*/
|
|
15
|
+
/** A wake-up. The state tables are the truth; a message only says "look". */
|
|
16
|
+
export type WakeUp = {
|
|
17
|
+
readonly instanceId: PipelineInstanceId;
|
|
18
|
+
readonly stepIndex: number;
|
|
19
|
+
};
|
|
20
|
+
/** The `status` column of `pipeline_instances` (decision 0006). */
|
|
21
|
+
export type InstanceState = 'running' | 'failing' | 'completed' | 'failed';
|
|
22
|
+
/**
|
|
23
|
+
* One row of `pipeline_instances`. Times are epoch milliseconds from the injected
|
|
24
|
+
* `Clock`. `input` is the Pipeline input as JSON.
|
|
25
|
+
*
|
|
26
|
+
* `cause` is not one of decision 0006's columns. Without it the exhaustion
|
|
27
|
+
* handler cannot be told whether a step was terminal, ran out of retries or
|
|
28
|
+
* returned too large a result, and `reason_code` holds the domain's code
|
|
29
|
+
* only when the cause is `terminal`.
|
|
30
|
+
*/
|
|
31
|
+
export type InstanceRow = {
|
|
32
|
+
readonly instanceId: PipelineInstanceId;
|
|
33
|
+
readonly pipeline: string;
|
|
34
|
+
readonly input: string;
|
|
35
|
+
readonly runId: string;
|
|
36
|
+
readonly unitKey: string;
|
|
37
|
+
readonly status: InstanceState;
|
|
38
|
+
readonly cause: Exhaustion['cause'] | null;
|
|
39
|
+
readonly reasonCode: string | null;
|
|
40
|
+
readonly currentStep: number;
|
|
41
|
+
readonly attempts: number;
|
|
42
|
+
readonly version: number;
|
|
43
|
+
readonly leaseExpiresAt: Instant | null;
|
|
44
|
+
readonly nextWakeAt: Instant | null;
|
|
45
|
+
readonly createdAt: Instant;
|
|
46
|
+
readonly endedAt: Instant | null;
|
|
47
|
+
};
|
|
48
|
+
/** The columns a conditional write may change. `version` is the store's. */
|
|
49
|
+
export type InstanceChange = Partial<Pick<InstanceRow, 'status' | 'cause' | 'reasonCode' | 'currentStep' | 'attempts' | 'leaseExpiresAt' | 'nextWakeAt' | 'endedAt'>>;
|
|
50
|
+
/**
|
|
51
|
+
* THE ONLY THING AN ADAPTER IMPLEMENTS. The two tables of decision 0006,
|
|
52
|
+
* `pipeline_instances` and `pipeline_steps`, behind the writes the protocol makes.
|
|
53
|
+
*
|
|
54
|
+
* This is not a tool and has no conformance suite of its own: 0006 rejected a
|
|
55
|
+
* `PipelineStore` tool, and the Pipelines suite tests it through the executor. It is
|
|
56
|
+
* the seam that keeps the algorithm in one place.
|
|
57
|
+
*
|
|
58
|
+
* NO ADAPTER NEEDS A TRANSACTION. Every method but two writes one table.
|
|
59
|
+
* `remove` and `removeEndedBefore` write both, and each one deletes in a fixed
|
|
60
|
+
* order: the `pipeline_steps` rows first, then the `pipeline_instances` row, both only
|
|
61
|
+
* for an instance whose `ended_at` is at or before the cutoff. A crash between
|
|
62
|
+
* the two deletes leaves an ended instance with no stored results, which the
|
|
63
|
+
* next removal deletes. A new instance cannot take the id while the old
|
|
64
|
+
* instance row exists, so it never inherits the old instance's results, and
|
|
65
|
+
* the condition on `ended_at` means a late removal never deletes a newer
|
|
66
|
+
* instance's results.
|
|
67
|
+
*/
|
|
68
|
+
export interface ReferenceStore {
|
|
69
|
+
/** Inserts the row, or reports that its id is already taken. */
|
|
70
|
+
insert(row: InstanceRow): Promise<'inserted' | 'exists'>;
|
|
71
|
+
get(id: PipelineInstanceId): Promise<InstanceRow | undefined>;
|
|
72
|
+
/**
|
|
73
|
+
* `UPDATE … WHERE instance_id = ? AND version = ?`, which also sets
|
|
74
|
+
* `version = version + 1`. Exactly one more: the executor computes the
|
|
75
|
+
* row's next version itself and conditions its next write on it. False
|
|
76
|
+
* when the version did not match: another consumer won.
|
|
77
|
+
*/
|
|
78
|
+
update(id: PipelineInstanceId, version: number, change: InstanceChange): Promise<boolean>;
|
|
79
|
+
/**
|
|
80
|
+
* Deletes the instance and its stored results if it ended at or before
|
|
81
|
+
* `cutoff`: the `pipeline_steps` rows first, then the instance row (above). Used
|
|
82
|
+
* only for an instance whose retention has passed.
|
|
83
|
+
*/
|
|
84
|
+
remove(id: PipelineInstanceId, cutoff: Instant): Promise<void>;
|
|
85
|
+
/**
|
|
86
|
+
* `INSERT OR IGNORE` into `pipeline_steps`: the first result stored for a step
|
|
87
|
+
* is the one that stays. `result` is the step result as JSON.
|
|
88
|
+
*/
|
|
89
|
+
storeResult(id: PipelineInstanceId, stepIndex: number, result: string, completedAt: Instant): Promise<void>;
|
|
90
|
+
/** The stored results of the instance, as JSON, by step index. */
|
|
91
|
+
results(id: PipelineInstanceId): Promise<ReadonlyMap<number, string>>;
|
|
92
|
+
/**
|
|
93
|
+
* `status IN ('running', 'failing') AND next_wake_at <= now AND
|
|
94
|
+
* (lease_expires_at IS NULL OR lease_expires_at <= now)`.
|
|
95
|
+
*/
|
|
96
|
+
due(now: Instant): Promise<readonly InstanceRow[]>;
|
|
97
|
+
/**
|
|
98
|
+
* Instances with `ended_at <= cutoff`, with their `pipeline_steps` rows: the
|
|
99
|
+
* `pipeline_steps` rows first, then the instance rows (above).
|
|
100
|
+
*/
|
|
101
|
+
removeEndedBefore(cutoff: Instant): Promise<void>;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The points between the executor's writes where a process can die
|
|
105
|
+
* (decision 0006's crash windows, and decision 0008's `before-result-stored`).
|
|
106
|
+
* The names are the conformance suite's `InterruptWindow`.
|
|
107
|
+
*/
|
|
108
|
+
export type ExecutorWindow = 'after-dispatch-insert' | 'before-result-stored' | 'after-result-stored' | 'after-advance' | 'after-failing-stored';
|
|
109
|
+
/**
|
|
110
|
+
* A TEST SEAM. Called at each window. `undefined` goes on at once; a promise
|
|
111
|
+
* parks the caller until it settles, as a stalled process would. Production
|
|
112
|
+
* code passes nothing.
|
|
113
|
+
*/
|
|
114
|
+
export type Interrupt = (window: ExecutorWindow, at: {
|
|
115
|
+
readonly instanceId: PipelineInstanceId;
|
|
116
|
+
readonly stepIndex: number;
|
|
117
|
+
}) => Promise<void> | undefined;
|
|
118
|
+
export type ReferenceExecutorOptions = {
|
|
119
|
+
readonly registrations: readonly PipelineRegistration[];
|
|
120
|
+
readonly store: ReferenceStore;
|
|
121
|
+
readonly queue: Queue<WakeUp>;
|
|
122
|
+
readonly clock: Clock;
|
|
123
|
+
readonly logger: Logger;
|
|
124
|
+
readonly journal: Journal;
|
|
125
|
+
readonly manifest: Pick<ToolManifest, 'stepResultMaxBytes' | 'queueDelayMaxSeconds'>;
|
|
126
|
+
readonly interrupt?: Interrupt;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* How long an ended instance is kept, so that `dispatch` with its id still
|
|
130
|
+
* says `already-started`. 30 days, the same as Workflows on Workers Paid
|
|
131
|
+
* (decision 0006 and its amendment). The contract has no field to change it.
|
|
132
|
+
*/
|
|
133
|
+
export declare const RETENTION_MS: number;
|
|
134
|
+
/**
|
|
135
|
+
* The exhaustion handler's lease. The contract gives the handler no timeout,
|
|
136
|
+
* so the executor chooses one: 15 minutes. A handler that runs longer can be
|
|
137
|
+
* started a second time beside itself, which its idempotency already covers.
|
|
138
|
+
*/
|
|
139
|
+
export declare const HANDLER_LEASE_MS: number;
|
|
140
|
+
/**
|
|
141
|
+
* The wait before a handler that threw runs again. The contract names none.
|
|
142
|
+
* The handler runs at least once and never gives up, because `failed` means
|
|
143
|
+
* the handler finished, so a fixed minute keeps a handler that always throws
|
|
144
|
+
* from spinning.
|
|
145
|
+
*/
|
|
146
|
+
export declare const HANDLER_RETRY_MS = 60000;
|
|
147
|
+
/**
|
|
148
|
+
* `Pipelines` over a `ReferenceStore` and a queue of wake-ups, by the protocol of
|
|
149
|
+
* docs/decisions/0006. The adapter delivers the queue's batches to `consume`
|
|
150
|
+
* and calls `sweep` on a schedule.
|
|
151
|
+
*/
|
|
152
|
+
export declare class ReferenceExecutor implements Pipelines {
|
|
153
|
+
#private;
|
|
154
|
+
private readonly o;
|
|
155
|
+
constructor(o: ReferenceExecutorOptions);
|
|
156
|
+
dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: PipelineDefinition<Input, Results, Deps>, input: Input, options: DispatchOptions): Promise<DispatchResult>;
|
|
157
|
+
status(id: PipelineInstanceId): Promise<PipelineStatus>;
|
|
158
|
+
/**
|
|
159
|
+
* THE QUEUE CONSUMER. Each message is acknowledged or retried on its own.
|
|
160
|
+
* A message whose handling throws is neither, so the queue redelivers it:
|
|
161
|
+
* a store fault is the platform's, and the state tables are unchanged by a
|
|
162
|
+
* write that did not happen.
|
|
163
|
+
*/
|
|
164
|
+
consume(batch: QueueBatch<WakeUp>): Promise<void>;
|
|
165
|
+
/**
|
|
166
|
+
* THE SWEEPER. Wakes every instance that is due and holds no live lease,
|
|
167
|
+
* and deletes ended instances whose retention has passed. A duplicate
|
|
168
|
+
* wake-up is harmless, so it coordinates with nothing.
|
|
169
|
+
*/
|
|
170
|
+
sweep(): Promise<void>;
|
|
171
|
+
}
|