@anatta.io/tva 0.0.0-stage → 0.1.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/actions/action-consumer.d.ts +45 -0
- package/dist/actions/action-consumer.js +90 -0
- package/dist/actions/action.d.ts +67 -0
- package/dist/actions/action.js +12 -0
- package/dist/actions/index.d.ts +3 -0
- package/dist/actions/index.js +4 -0
- package/dist/actions/run-action.d.ts +31 -0
- package/dist/actions/run-action.js +113 -0
- 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/jobs.d.ts +97 -0
- package/dist/adapters/cloudflare/jobs.js +218 -0
- package/dist/adapters/cloudflare/journal.d.ts +107 -0
- package/dist/adapters/cloudflare/journal.js +305 -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/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-jobs.d.ts +57 -0
- package/dist/adapters/cloudflare/workflow-jobs.js +319 -0
- package/dist/adapters/journal-records.d.ts +79 -0
- package/dist/adapters/journal-records.js +74 -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/jobs.d.ts +62 -0
- package/dist/adapters/memory/jobs.js +219 -0
- package/dist/adapters/memory/journal.d.ts +34 -0
- package/dist/adapters/memory/journal.js +135 -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/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 +83 -0
- package/dist/adapters/postgres/journal.js +314 -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 +564 -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/jobs.d.ts +335 -0
- package/dist/contracts/jobs.js +1 -0
- package/dist/contracts/journal.d.ts +186 -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/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/schedule/schedule.d.ts +40 -0
- package/dist/schedule/schedule.js +135 -0
- package/dist/webhooks/create-webhook-handler.d.ts +63 -0
- package/dist/webhooks/create-webhook-handler.js +246 -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 +79 -0
- package/dist/webhooks/sign-shopify-webhook.d.ts +14 -0
- package/dist/webhooks/sign-shopify-webhook.js +31 -0
- package/dist/webhooks/webhook-consumer.d.ts +51 -0
- package/dist/webhooks/webhook-consumer.js +127 -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/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/package.json +137 -4
package/README.md
CHANGED
|
@@ -1,3 +1,51 @@
|
|
|
1
|
-
#
|
|
1
|
+
# TVA Library
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**The platform primitives a Shopify React Router app does not come with** — caching, blob storage, queues, durable jobs, an idempotency ledger, and a run journal you can actually read — behind interfaces that survive changing platform.
|
|
4
|
+
|
|
5
|
+
**Status: early. Built alongside a real engagement, not ahead of one.**
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## The problem
|
|
10
|
+
|
|
11
|
+
Shopify's React Router app template is an excellent server-rendered admin UI and backend-for-frontend, and it stops there. No cache, no blob storage, no queue, no straightforward way to use a database. So application data ends up in Shopify metafields, where it cannot be queried, indexed or audited.
|
|
12
|
+
|
|
13
|
+
**The doctrine this ships with, and it matters more than the code:**
|
|
14
|
+
|
|
15
|
+
> **Shopify remains the system of record for commerce objects.** Products, customers, companies, orders.
|
|
16
|
+
>
|
|
17
|
+
> **This library's store holds what your app knows about its own work.** Runs, decisions, reason codes, idempotency claims, receipts, configuration.
|
|
18
|
+
>
|
|
19
|
+
> **If a fact exists in both, Shopify wins, and ours is a cache with a stated staleness budget.**
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Layout
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
src/
|
|
27
|
+
contracts/ tool interfaces and their conformance suites. Zero dependencies
|
|
28
|
+
adapters/
|
|
29
|
+
memory/ in-process. Every test runs against it. Passes the suite
|
|
30
|
+
examples/
|
|
31
|
+
cloudflare/ a real engagement, importing the library
|
|
32
|
+
docs/
|
|
33
|
+
design.md what this is, how it is layered, and what it refuses
|
|
34
|
+
operator-ledger.md the run journal, and the screens that read it
|
|
35
|
+
etl.md a worked ETL design
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
**`src/contracts/` imports nothing.** Not an adapter, not a vendor SDK, not a third-party package. That one rule is the portability story; everything else follows from it.
|
|
39
|
+
|
|
40
|
+
**Two implementations of every interface, from day one.** The memory adapter is not extra work — the first test needs it — and two implementations passing one suite is the only evidence available that an interface is not one vendor's API in disguise.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Getting started
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npm install
|
|
48
|
+
npm run check # lint, typecheck, test
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Contributing, and how commits and pull requests are written here: **`CONTRIBUTING.md`**.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { QueueBatch, QueueConsumer, QueueMessage } from '../contracts/index.js';
|
|
2
|
+
import { type Action } from './action.js';
|
|
3
|
+
import { type JournalDeps } from './run-action.js';
|
|
4
|
+
export type ActionConsumerOptions<Deps> = {
|
|
5
|
+
/** Writes the journal and the fault log. A `Toolkit` is one. */
|
|
6
|
+
readonly toolkit: JournalDeps;
|
|
7
|
+
readonly deps: Deps;
|
|
8
|
+
/** The `job` of each message's run, for example `queue.order-tagger`. */
|
|
9
|
+
readonly job: string;
|
|
10
|
+
/**
|
|
11
|
+
* The first retry's delay, doubled on each attempt after it, up to a day.
|
|
12
|
+
* Required: a redelivery with no delay meets a throttled API at once.
|
|
13
|
+
*/
|
|
14
|
+
readonly retryDelaySeconds: number;
|
|
15
|
+
/**
|
|
16
|
+
* The queue's own limit, so the last attempt is known: Postgres
|
|
17
|
+
* `maxAttempts` (5 by default), Cloudflare `max_retries` + 1. Set it
|
|
18
|
+
* higher and a webhook task the queue dead-letters stays `failed`, where
|
|
19
|
+
* neither `deadTasks` nor `stuckTasks` finds it.
|
|
20
|
+
*/
|
|
21
|
+
readonly maxAttempts: number;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* The queue transport for an Action: one message, one run, one unit.
|
|
25
|
+
*
|
|
26
|
+
* A decision is acked unless it is `retryable`. A throw, a failed journal
|
|
27
|
+
* write among them, is logged and retried. Either way the message is settled
|
|
28
|
+
* on its own, and the rest of the batch is not run again.
|
|
29
|
+
*
|
|
30
|
+
* A run per message, not per batch: at-least-once delivery can put two
|
|
31
|
+
* messages for one unit in a batch, and in one run the second would trip
|
|
32
|
+
* `runAction`'s one-unit-per-run rule and spend a retry.
|
|
33
|
+
*/
|
|
34
|
+
export declare function createActionConsumer<Input, Reason extends string, Deps>(action: Action<Input, Reason, Deps>, options: ActionConsumerOptions<Deps>): QueueConsumer<Input>;
|
|
35
|
+
/**
|
|
36
|
+
* Runs `action` on one message and settles it. On the last attempt a
|
|
37
|
+
* retryable decision or a throw is recorded as `failed`, `retries-exhausted`,
|
|
38
|
+
* and the message is still retried, so the queue dead-letters it.
|
|
39
|
+
*
|
|
40
|
+
* Resolves to why it retried: the last retryable reason code, or `fault` for
|
|
41
|
+
* a throw. Undefined when it acked.
|
|
42
|
+
*/
|
|
43
|
+
export declare function settleActionMessage<Body, Input, Reason extends string, Deps>(batch: QueueBatch<Body>, message: QueueMessage<Body>, action: Action<Input, Reason, Deps>, toInput: (body: Body) => Input | Promise<Input>, { toolkit, deps, job, retryDelaySeconds, maxAttempts, }: ActionConsumerOptions<Deps>): Promise<string | undefined>;
|
|
44
|
+
/** The delay before `attempt`'s retry: `retryDelaySeconds` doubled per attempt, up to a day. */
|
|
45
|
+
export declare const retryDelayFor: (attempt: number, retryDelaySeconds: number) => number;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { failed } from './action.js';
|
|
2
|
+
import { runAction, withRun } from './run-action.js';
|
|
3
|
+
// Cloudflare's queueDelayMaxSeconds, the lowest of the adapters'.
|
|
4
|
+
const MAX_RETRY_DELAY_SECONDS = 86_400;
|
|
5
|
+
/**
|
|
6
|
+
* The queue transport for an Action: one message, one run, one unit.
|
|
7
|
+
*
|
|
8
|
+
* A decision is acked unless it is `retryable`. A throw, a failed journal
|
|
9
|
+
* write among them, is logged and retried. Either way the message is settled
|
|
10
|
+
* on its own, and the rest of the batch is not run again.
|
|
11
|
+
*
|
|
12
|
+
* A run per message, not per batch: at-least-once delivery can put two
|
|
13
|
+
* messages for one unit in a batch, and in one run the second would trip
|
|
14
|
+
* `runAction`'s one-unit-per-run rule and spend a retry.
|
|
15
|
+
*/
|
|
16
|
+
export function createActionConsumer(action, options) {
|
|
17
|
+
return async (batch) => {
|
|
18
|
+
for (const message of batch.messages) {
|
|
19
|
+
await settleActionMessage(batch, message, action, (body) => body, options);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Runs `action` on one message and settles it. On the last attempt a
|
|
25
|
+
* retryable decision or a throw is recorded as `failed`, `retries-exhausted`,
|
|
26
|
+
* and the message is still retried, so the queue dead-letters it.
|
|
27
|
+
*
|
|
28
|
+
* Resolves to why it retried: the last retryable reason code, or `fault` for
|
|
29
|
+
* a throw. Undefined when it acked.
|
|
30
|
+
*/
|
|
31
|
+
export async function settleActionMessage(batch, message, action, toInput, { toolkit, deps, job, retryDelaySeconds, maxAttempts, }) {
|
|
32
|
+
const runId = crypto.randomUUID();
|
|
33
|
+
const exhausted = { yes: false };
|
|
34
|
+
const retry = () => {
|
|
35
|
+
batch.retry(message.id, {
|
|
36
|
+
delaySeconds: retryDelayFor(message.attempt, retryDelaySeconds),
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
try {
|
|
40
|
+
const decision = await withRun(toolkit, { runId, job, trigger: 'queue', mode: 'live' }, async (scope) => runAction(message.attempt >= maxAttempts
|
|
41
|
+
? exhaustRetries(action, exhausted)
|
|
42
|
+
: action, await toInput(message.body), scope, deps));
|
|
43
|
+
if (exhausted.yes) {
|
|
44
|
+
retry();
|
|
45
|
+
return exhausted.reason;
|
|
46
|
+
}
|
|
47
|
+
if ('retryable' in decision && decision.retryable === true) {
|
|
48
|
+
retry();
|
|
49
|
+
return decision.reasonCode;
|
|
50
|
+
}
|
|
51
|
+
batch.ack(message.id);
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
toolkit.logger.error('action failed', {
|
|
56
|
+
action: action.name,
|
|
57
|
+
runId,
|
|
58
|
+
messageId: message.id,
|
|
59
|
+
error: String(error),
|
|
60
|
+
});
|
|
61
|
+
retry();
|
|
62
|
+
return 'fault';
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** The delay before `attempt`'s retry: `retryDelaySeconds` doubled per attempt, up to a day. */
|
|
66
|
+
export const retryDelayFor = (attempt, retryDelaySeconds) => Math.min(retryDelaySeconds * 2 ** (attempt - 1), MAX_RETRY_DELAY_SECONDS);
|
|
67
|
+
/** `action`, with a retryable decision or a throw turned into `retries-exhausted`. */
|
|
68
|
+
function exhaustRetries(action, exhausted) {
|
|
69
|
+
return {
|
|
70
|
+
...action,
|
|
71
|
+
async run(input, context) {
|
|
72
|
+
let lastReason;
|
|
73
|
+
try {
|
|
74
|
+
const decision = await action.run(input, context);
|
|
75
|
+
if (!('retryable' in decision && decision.retryable === true)) {
|
|
76
|
+
return decision;
|
|
77
|
+
}
|
|
78
|
+
lastReason = decision.reasonCode;
|
|
79
|
+
exhausted.reason = decision.reasonCode;
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
lastReason = String(error);
|
|
83
|
+
exhausted.reason = 'fault';
|
|
84
|
+
}
|
|
85
|
+
exhausted.yes = true;
|
|
86
|
+
context.logger.error('retries exhausted', { lastReason });
|
|
87
|
+
return failed('retries-exhausted');
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Logger, UnitKey } from '../contracts/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* AN ACTION TAKES TYPED INPUT AND RETURNS A DECISION: what the system chose to
|
|
4
|
+
* do with one unit, and why. It never writes to the journal. `runAction` is
|
|
5
|
+
* the only way to call one, and it records the decision, so the record does
|
|
6
|
+
* not depend on the author remembering to write it (#94).
|
|
7
|
+
*
|
|
8
|
+
* A definition value, like a `Job`, not a base class to extend. A class that
|
|
9
|
+
* `implements Action` is fine.
|
|
10
|
+
*
|
|
11
|
+
* An Action runs inline and reaches one outcome per unit. Work that needs
|
|
12
|
+
* retries between its steps, or must survive a restart part way through, is a
|
|
13
|
+
* `Job`.
|
|
14
|
+
*
|
|
15
|
+
* Cleanup happens inside `run`: free what it claimed, then return the
|
|
16
|
+
* decision.
|
|
17
|
+
*/
|
|
18
|
+
export type Action<Input, Reason extends string, Deps> = {
|
|
19
|
+
/** Added to every log line the Action writes. */
|
|
20
|
+
readonly name: string;
|
|
21
|
+
/** The journal's `unitType`, for example `order`. */
|
|
22
|
+
readonly unitType: string;
|
|
23
|
+
/** The journal's unit key. A pure function of the input. */
|
|
24
|
+
readonly key: (input: Input) => UnitKey;
|
|
25
|
+
run(input: Input, context: ActionContext<Deps>): Promise<Decision<Reason>>;
|
|
26
|
+
};
|
|
27
|
+
export type ActionContext<Deps> = {
|
|
28
|
+
readonly deps: Deps;
|
|
29
|
+
/** Adds `action`, `runId` and `unitKey` to every line. */
|
|
30
|
+
readonly logger: Logger;
|
|
31
|
+
/**
|
|
32
|
+
* Calls `fn` and records it as an `ok` or `failed` call with its duration.
|
|
33
|
+
* Returns what `fn` returns, and rethrows what it throws. A property, not a
|
|
34
|
+
* method, so an Action can destructure it from the context.
|
|
35
|
+
*/
|
|
36
|
+
readonly track: <T>(system: string, operation: string, fn: () => Promise<T>) => Promise<T>;
|
|
37
|
+
};
|
|
38
|
+
type DecisionExtras = {
|
|
39
|
+
readonly externalIds?: Readonly<Record<string, string>>;
|
|
40
|
+
};
|
|
41
|
+
type RetryableExtras = DecisionExtras & {
|
|
42
|
+
/**
|
|
43
|
+
* Try the unit again later: a queue retries the message, and an HTTP
|
|
44
|
+
* transport answers 500. Same word as `ToolFault.retryable`.
|
|
45
|
+
*/
|
|
46
|
+
readonly retryable?: boolean;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Every outcome but `written` carries a reason code from the domain's closed
|
|
50
|
+
* list, and only `failed` and `skipped` can be retryable: an `unchanged` unit
|
|
51
|
+
* has nothing left to do. A throw is not a decision: it is a fault, it records
|
|
52
|
+
* nothing, and the transport retries it.
|
|
53
|
+
*/
|
|
54
|
+
export type Decision<Reason extends string> = ({
|
|
55
|
+
readonly outcome: 'written';
|
|
56
|
+
} & DecisionExtras) | ({
|
|
57
|
+
readonly outcome: 'failed' | 'skipped';
|
|
58
|
+
readonly reasonCode: Reason;
|
|
59
|
+
} & RetryableExtras) | ({
|
|
60
|
+
readonly outcome: 'unchanged' | 'would-write';
|
|
61
|
+
readonly reasonCode: Reason;
|
|
62
|
+
} & DecisionExtras);
|
|
63
|
+
export declare function written(extras?: DecisionExtras): Decision<never>;
|
|
64
|
+
export declare function skipped<R extends string>(reasonCode: R, extras?: RetryableExtras): Decision<R>;
|
|
65
|
+
export declare function failed<R extends string>(reasonCode: R, extras?: RetryableExtras): Decision<R>;
|
|
66
|
+
export declare function unchanged<R extends string>(reasonCode: R, extras?: DecisionExtras): Decision<R>;
|
|
67
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export function written(extras = {}) {
|
|
2
|
+
return { outcome: 'written', ...extras };
|
|
3
|
+
}
|
|
4
|
+
export function skipped(reasonCode, extras = {}) {
|
|
5
|
+
return { outcome: 'skipped', reasonCode, ...extras };
|
|
6
|
+
}
|
|
7
|
+
export function failed(reasonCode, extras = {}) {
|
|
8
|
+
return { outcome: 'failed', reasonCode, ...extras };
|
|
9
|
+
}
|
|
10
|
+
export function unchanged(reasonCode, extras = {}) {
|
|
11
|
+
return { outcome: 'unchanged', reasonCode, ...extras };
|
|
12
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { RunId, RunRow, Toolkit } from '../contracts/index.js';
|
|
2
|
+
import type { Action, Decision } from './action.js';
|
|
3
|
+
/** What the runner writes with. A `Toolkit` is one. */
|
|
4
|
+
export type JournalDeps = Pick<Toolkit, 'journal' | 'clock' | 'logger'>;
|
|
5
|
+
/** A started run. Only `withRun` makes one. */
|
|
6
|
+
export type RunScope = {
|
|
7
|
+
readonly runId: RunId;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Starts a run, calls `fn` with it, and finishes the run when `fn` settles.
|
|
11
|
+
* The run id is the caller's, or a new UUID.
|
|
12
|
+
*
|
|
13
|
+
* A failed `startRun` rejects before `fn` runs. A failed `finishRun` is logged,
|
|
14
|
+
* not thrown: the units are already recorded, and a rejection here would make
|
|
15
|
+
* a transport retry work that is done, for the sake of an end time.
|
|
16
|
+
*/
|
|
17
|
+
export declare function withRun<T>(deps: JournalDeps, run: Pick<RunRow, 'job' | 'trigger' | 'mode'> & {
|
|
18
|
+
readonly runId?: RunId;
|
|
19
|
+
}, fn: (scope: RunScope) => Promise<T>): Promise<T>;
|
|
20
|
+
/**
|
|
21
|
+
* The only way to call an Action. Times it, collects the calls it tracks, and
|
|
22
|
+
* records its decision as one unit of `scope`'s run.
|
|
23
|
+
*
|
|
24
|
+
* A throw from the Action records nothing and is rethrown: a fault is not a
|
|
25
|
+
* decision, and the transport decides what it means. A rejected `recordUnit`
|
|
26
|
+
* reaches the caller too, so a queue consumer retries the message.
|
|
27
|
+
*
|
|
28
|
+
* A unit runs at most once per run, and a second call for its key throws:
|
|
29
|
+
* recording it again would replace the first decision's row and calls.
|
|
30
|
+
*/
|
|
31
|
+
export declare function runAction<Input, Reason extends string, Deps>(action: Action<Input, Reason, Deps>, input: Input, scope: RunScope, deps: Deps): Promise<Decision<Reason>>;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Private, so a RunScope built by hand, which skipped startRun, cannot run an
|
|
2
|
+
// Action: a unit row with no run never shows in `recentRuns`.
|
|
3
|
+
const openRuns = new WeakMap();
|
|
4
|
+
/**
|
|
5
|
+
* Starts a run, calls `fn` with it, and finishes the run when `fn` settles.
|
|
6
|
+
* The run id is the caller's, or a new UUID.
|
|
7
|
+
*
|
|
8
|
+
* A failed `startRun` rejects before `fn` runs. A failed `finishRun` is logged,
|
|
9
|
+
* not thrown: the units are already recorded, and a rejection here would make
|
|
10
|
+
* a transport retry work that is done, for the sake of an end time.
|
|
11
|
+
*/
|
|
12
|
+
export async function withRun(deps, run, fn) {
|
|
13
|
+
const runId = run.runId ?? crypto.randomUUID();
|
|
14
|
+
await deps.journal.startRun({
|
|
15
|
+
runId,
|
|
16
|
+
job: run.job,
|
|
17
|
+
trigger: run.trigger,
|
|
18
|
+
mode: run.mode,
|
|
19
|
+
startedAt: deps.clock.now(),
|
|
20
|
+
identity: deps.logger.identity,
|
|
21
|
+
});
|
|
22
|
+
const scope = { runId };
|
|
23
|
+
openRuns.set(scope, { deps, units: new Set() });
|
|
24
|
+
try {
|
|
25
|
+
return await fn(scope);
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
openRuns.delete(scope);
|
|
29
|
+
try {
|
|
30
|
+
await deps.journal.finishRun(runId, deps.clock.now());
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
deps.logger.error('journal run not finished', {
|
|
34
|
+
runId,
|
|
35
|
+
error: String(error),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The only way to call an Action. Times it, collects the calls it tracks, and
|
|
42
|
+
* records its decision as one unit of `scope`'s run.
|
|
43
|
+
*
|
|
44
|
+
* A throw from the Action records nothing and is rethrown: a fault is not a
|
|
45
|
+
* decision, and the transport decides what it means. A rejected `recordUnit`
|
|
46
|
+
* reaches the caller too, so a queue consumer retries the message.
|
|
47
|
+
*
|
|
48
|
+
* A unit runs at most once per run, and a second call for its key throws:
|
|
49
|
+
* recording it again would replace the first decision's row and calls.
|
|
50
|
+
*/
|
|
51
|
+
export async function runAction(action, input, scope, deps) {
|
|
52
|
+
const open = openRuns.get(scope);
|
|
53
|
+
if (open === undefined) {
|
|
54
|
+
throw new TypeError('runAction needs a run that withRun has open');
|
|
55
|
+
}
|
|
56
|
+
const unitKey = action.key(input);
|
|
57
|
+
if (open.units.has(unitKey)) {
|
|
58
|
+
throw new TypeError(`unit ${unitKey} has already run in ${scope.runId}`);
|
|
59
|
+
}
|
|
60
|
+
open.units.add(unitKey);
|
|
61
|
+
const { journal, clock, logger } = open.deps;
|
|
62
|
+
const { runId } = scope;
|
|
63
|
+
const startedAt = clock.now();
|
|
64
|
+
const calls = [];
|
|
65
|
+
const decision = await action.run(input, {
|
|
66
|
+
deps,
|
|
67
|
+
logger: withFields(logger, { action: action.name, runId, unitKey }),
|
|
68
|
+
async track(system, operation, fn) {
|
|
69
|
+
const callStartedAt = clock.now();
|
|
70
|
+
const call = (status) => calls.push({
|
|
71
|
+
runId,
|
|
72
|
+
unitKey,
|
|
73
|
+
system,
|
|
74
|
+
operation,
|
|
75
|
+
status,
|
|
76
|
+
durationMs: clock.now() - callStartedAt,
|
|
77
|
+
});
|
|
78
|
+
try {
|
|
79
|
+
const result = await fn();
|
|
80
|
+
call('ok');
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
call('failed');
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
const recordedAt = clock.now();
|
|
90
|
+
await journal.recordUnit({
|
|
91
|
+
runId,
|
|
92
|
+
unitKey,
|
|
93
|
+
unitType: action.unitType,
|
|
94
|
+
recordedAt,
|
|
95
|
+
outcome: decision.outcome,
|
|
96
|
+
durationMs: recordedAt - startedAt,
|
|
97
|
+
...(decision.outcome !== 'written' && {
|
|
98
|
+
reasonCode: decision.reasonCode,
|
|
99
|
+
}),
|
|
100
|
+
...(decision.externalIds && { externalIds: decision.externalIds }),
|
|
101
|
+
}, calls);
|
|
102
|
+
return decision;
|
|
103
|
+
}
|
|
104
|
+
function withFields(logger, fields) {
|
|
105
|
+
return {
|
|
106
|
+
identity: logger.identity,
|
|
107
|
+
correlationId: logger.correlationId,
|
|
108
|
+
info: (message, more) => logger.info(message, { ...fields, ...more }),
|
|
109
|
+
warn: (message, more) => logger.warn(message, { ...fields, ...more }),
|
|
110
|
+
error: (message, more) => logger.error(message, { ...fields, ...more }),
|
|
111
|
+
child: (correlationId) => withFields(logger.child(correlationId), fields),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Aliases for the Cloudflare binding types this adapter names.
|
|
3
|
+
*
|
|
4
|
+
* `Queue` is both a Cloudflare global and one of our contracts, and a module
|
|
5
|
+
* that imports ours cannot then name the global — the import shadows it for the
|
|
6
|
+
* whole file. This module imports nothing, so the globals are visible here and
|
|
7
|
+
* the collision is resolved once rather than worked around in each file.
|
|
8
|
+
*/
|
|
9
|
+
export type QueueBinding<Body = unknown> = Queue<Body>;
|
|
10
|
+
export type QueueMessageBatch<Body = unknown> = MessageBatch<Body>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { BlobKey, BlobStore, PutOptions } from '../../contracts/index.js';
|
|
2
|
+
export type CloudflareBlobStoreOptions = {
|
|
3
|
+
readonly bucket: R2Bucket;
|
|
4
|
+
readonly maxBytes: number;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* BlobStore over an R2 bucket.
|
|
8
|
+
*
|
|
9
|
+
* Two things R2 gives away for free that an emulation would get wrong, and are
|
|
10
|
+
* therefore NOT re-implemented here:
|
|
11
|
+
*
|
|
12
|
+
* - `prefix` is a string prefix. R2 has no directories, so `a/` does not
|
|
13
|
+
* match `ab` without anybody arranging for it.
|
|
14
|
+
* - `delete` on a key that does not exist resolves. A retry after an
|
|
15
|
+
* ambiguous response is safe.
|
|
16
|
+
*
|
|
17
|
+
* The one thing R2 does NOT give away is a complete listing: `list` returns at
|
|
18
|
+
* most 1,000 keys and truncates silently. See `list` below.
|
|
19
|
+
*/
|
|
20
|
+
export declare class CloudflareBlobStore implements BlobStore {
|
|
21
|
+
#private;
|
|
22
|
+
private readonly o;
|
|
23
|
+
constructor(o: CloudflareBlobStoreOptions);
|
|
24
|
+
put(key: BlobKey, body: Uint8Array | string, options?: PutOptions): Promise<void>;
|
|
25
|
+
get(key: BlobKey): Promise<Uint8Array | undefined>;
|
|
26
|
+
getText(key: BlobKey): Promise<string | undefined>;
|
|
27
|
+
delete(key: BlobKey): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* Pages to completion.
|
|
30
|
+
*
|
|
31
|
+
* R2 returns at most 1,000 keys and sets `truncated`. One un-paged `list()`
|
|
32
|
+
* returns a partial answer WITH NO ERROR, which is the worst shape a bug can
|
|
33
|
+
* take: the caller gets a plausible list and no reason to doubt it.
|
|
34
|
+
*
|
|
35
|
+
* `truncated` is the signal, not a short page — the documentation is explicit
|
|
36
|
+
* that comparing the count against the limit is the wrong check.
|
|
37
|
+
*/
|
|
38
|
+
list(prefix: string): Promise<readonly BlobKey[]>;
|
|
39
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { LimitExceeded } from '../../contracts/index.js';
|
|
2
|
+
import { toFault } from './faults.js';
|
|
3
|
+
/**
|
|
4
|
+
* The name this tool answers to in a fault message and a log line: `blobs: put
|
|
5
|
+
* failed`. It matches the binding an operator reads in wrangler.jsonc, which is
|
|
6
|
+
* the name they will be looking at when something goes wrong.
|
|
7
|
+
*/
|
|
8
|
+
const TOOL = 'blobs';
|
|
9
|
+
/**
|
|
10
|
+
* BlobStore over an R2 bucket.
|
|
11
|
+
*
|
|
12
|
+
* Two things R2 gives away for free that an emulation would get wrong, and are
|
|
13
|
+
* therefore NOT re-implemented here:
|
|
14
|
+
*
|
|
15
|
+
* - `prefix` is a string prefix. R2 has no directories, so `a/` does not
|
|
16
|
+
* match `ab` without anybody arranging for it.
|
|
17
|
+
* - `delete` on a key that does not exist resolves. A retry after an
|
|
18
|
+
* ambiguous response is safe.
|
|
19
|
+
*
|
|
20
|
+
* The one thing R2 does NOT give away is a complete listing: `list` returns at
|
|
21
|
+
* most 1,000 keys and truncates silently. See `list` below.
|
|
22
|
+
*/
|
|
23
|
+
export class CloudflareBlobStore {
|
|
24
|
+
o;
|
|
25
|
+
constructor(o) {
|
|
26
|
+
this.o = o;
|
|
27
|
+
}
|
|
28
|
+
async put(key, body, options) {
|
|
29
|
+
// Encoded before the size check, because a string's length is characters
|
|
30
|
+
// and the limit is bytes. 'é' is one of the first and two of the second.
|
|
31
|
+
const bytes = typeof body === 'string' ? new TextEncoder().encode(body) : body;
|
|
32
|
+
// The ADAPTER enforces its own manifest, before the call — the same rule
|
|
33
|
+
// the cache follows. Reaching R2 to be told no costs a round trip and can
|
|
34
|
+
// fail for a second, unrelated reason on the way.
|
|
35
|
+
if (bytes.byteLength > this.o.maxBytes) {
|
|
36
|
+
throw new LimitExceeded(TOOL, `body of ${bytes.byteLength} bytes is above blobMaxBytes ${this.o.maxBytes}`);
|
|
37
|
+
}
|
|
38
|
+
// exactOptionalPropertyTypes: passing `{ contentType: undefined }` is not
|
|
39
|
+
// the same as passing nothing, so the absent case passes no options at all.
|
|
40
|
+
const contentType = options?.contentType;
|
|
41
|
+
await this.#call('put', async () => contentType === undefined
|
|
42
|
+
? this.o.bucket.put(key, bytes)
|
|
43
|
+
: this.o.bucket.put(key, bytes, { httpMetadata: { contentType } }));
|
|
44
|
+
}
|
|
45
|
+
async get(key) {
|
|
46
|
+
return this.#call('get', async () => {
|
|
47
|
+
const object = await this.o.bucket.get(key);
|
|
48
|
+
return object === null ? undefined : await object.bytes();
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async getText(key) {
|
|
52
|
+
return this.#call('getText', async () => {
|
|
53
|
+
const object = await this.o.bucket.get(key);
|
|
54
|
+
return object === null ? undefined : await object.text();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
async delete(key) {
|
|
58
|
+
await this.#call('delete', async () => this.o.bucket.delete(key));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Pages to completion.
|
|
62
|
+
*
|
|
63
|
+
* R2 returns at most 1,000 keys and sets `truncated`. One un-paged `list()`
|
|
64
|
+
* returns a partial answer WITH NO ERROR, which is the worst shape a bug can
|
|
65
|
+
* take: the caller gets a plausible list and no reason to doubt it.
|
|
66
|
+
*
|
|
67
|
+
* `truncated` is the signal, not a short page — the documentation is explicit
|
|
68
|
+
* that comparing the count against the limit is the wrong check.
|
|
69
|
+
*/
|
|
70
|
+
async list(prefix) {
|
|
71
|
+
return this.#call('list', async () => {
|
|
72
|
+
const keys = [];
|
|
73
|
+
let cursor;
|
|
74
|
+
for (;;) {
|
|
75
|
+
const page = await this.o.bucket.list(cursor === undefined ? { prefix } : { prefix, cursor });
|
|
76
|
+
keys.push(...page.objects.map((o) => o.key));
|
|
77
|
+
if (!page.truncated) {
|
|
78
|
+
// Sorted because the contract says sorted. R2 already orders a page
|
|
79
|
+
// lexicographically and pages concatenate in order, so this is a
|
|
80
|
+
// no-op that costs nothing and stops the contract resting on it.
|
|
81
|
+
return keys.sort();
|
|
82
|
+
}
|
|
83
|
+
cursor = page.cursor;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
async #call(operation, f) {
|
|
88
|
+
try {
|
|
89
|
+
return await f();
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
throw toFault(TOOL, operation, e);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Cache, CacheKey, Clock } from '../../contracts/index.js';
|
|
2
|
+
export type CloudflareCacheOptions = {
|
|
3
|
+
readonly kv: KVNamespace;
|
|
4
|
+
readonly clock: Clock;
|
|
5
|
+
readonly minTtlSeconds: number;
|
|
6
|
+
};
|
|
7
|
+
export declare class CloudflareCache implements Cache {
|
|
8
|
+
#private;
|
|
9
|
+
private readonly o;
|
|
10
|
+
constructor(o: CloudflareCacheOptions);
|
|
11
|
+
get(key: CacheKey): Promise<string | undefined>;
|
|
12
|
+
put(key: CacheKey, value: string, ttlSeconds: number): Promise<void>;
|
|
13
|
+
delete(key: CacheKey): Promise<void>;
|
|
14
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { LimitExceeded, checkDuration, plusSeconds, } from '../../contracts/index.js';
|
|
2
|
+
import { toFault } from './faults.js';
|
|
3
|
+
export class CloudflareCache {
|
|
4
|
+
o;
|
|
5
|
+
constructor(o) {
|
|
6
|
+
this.o = o;
|
|
7
|
+
}
|
|
8
|
+
async get(key) {
|
|
9
|
+
const { value, metadata } = await this.#call('get', async () => this.o.kv.getWithMetadata(key, 'text'));
|
|
10
|
+
// The metadata is the hit signal, not the value: KV returns null for a
|
|
11
|
+
// stored empty string, and '' is a hit while undefined is a miss.
|
|
12
|
+
if (metadata === null) {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
// Inclusive: at exactly expiresAt the value is gone. Unlike the memory
|
|
16
|
+
// adapter this does not delete the key — KV removes it on its own ttl, and
|
|
17
|
+
// a delete here would spend a write to save a read that is already right.
|
|
18
|
+
if (metadata.expiresAt <= this.o.clock.now()) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
return value ?? '';
|
|
22
|
+
}
|
|
23
|
+
async put(key, value, ttlSeconds) {
|
|
24
|
+
// Before the manifest check, which cannot catch it: NaN < minTtlSeconds is
|
|
25
|
+
// false, so a NaN ttl would reach KV as an expirationTtl of NaN.
|
|
26
|
+
checkDuration('cache', 'ttlSeconds', ttlSeconds);
|
|
27
|
+
// The ADAPTER enforces its own manifest, before the call. KV has its own
|
|
28
|
+
// floor of 60 seconds, which is what the manifest field records.
|
|
29
|
+
if (ttlSeconds < this.o.minTtlSeconds) {
|
|
30
|
+
throw new LimitExceeded('cache', `ttlSeconds ${ttlSeconds} is below cacheMinTtlSeconds ${this.o.minTtlSeconds}`);
|
|
31
|
+
}
|
|
32
|
+
const metadata = {
|
|
33
|
+
expiresAt: plusSeconds(this.o.clock.now(), ttlSeconds),
|
|
34
|
+
};
|
|
35
|
+
await this.#call('put', async () => this.o.kv.put(key, value, { expirationTtl: ttlSeconds, metadata }));
|
|
36
|
+
}
|
|
37
|
+
async delete(key) {
|
|
38
|
+
await this.#call('delete', async () => this.o.kv.delete(key));
|
|
39
|
+
}
|
|
40
|
+
async #call(operation, f) {
|
|
41
|
+
try {
|
|
42
|
+
return await f();
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
throw toFault('cache', operation, e);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type ToolFault } from '../../contracts/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Unknown failures are Unavailable, which is retryable. A retryable answer to
|
|
4
|
+
* something permanent costs a few wasted attempts; a permanent answer to
|
|
5
|
+
* something transient loses the work.
|
|
6
|
+
*/
|
|
7
|
+
export declare function toFault(tool: string, operation: string, e: unknown): ToolFault;
|