@anatta.io/tva 0.1.0 → 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.
Files changed (75) hide show
  1. package/README.md +1 -1
  2. package/dist/adapters/cloudflare/index.d.ts +3 -3
  3. package/dist/adapters/cloudflare/index.js +2 -2
  4. package/dist/adapters/cloudflare/journal.d.ts +14 -11
  5. package/dist/adapters/cloudflare/journal.js +43 -23
  6. package/dist/adapters/cloudflare/{jobs.d.ts → pipelines.d.ts} +23 -23
  7. package/dist/adapters/cloudflare/{jobs.js → pipelines.js} +21 -21
  8. package/dist/adapters/cloudflare/workflow-pipelines.d.ts +66 -0
  9. package/dist/adapters/cloudflare/{workflow-jobs.js → workflow-pipelines.js} +46 -42
  10. package/dist/adapters/journal-records.d.ts +2 -1
  11. package/dist/adapters/journal-records.js +3 -2
  12. package/dist/adapters/memory/index.d.ts +1 -1
  13. package/dist/adapters/memory/index.js +1 -1
  14. package/dist/adapters/memory/journal.d.ts +5 -4
  15. package/dist/adapters/memory/journal.js +32 -13
  16. package/dist/adapters/memory/manifest.d.ts +1 -1
  17. package/dist/adapters/memory/manifest.js +1 -1
  18. package/dist/adapters/memory/{jobs.d.ts → pipelines.d.ts} +16 -16
  19. package/dist/adapters/memory/{jobs.js → pipelines.js} +6 -6
  20. package/dist/adapters/postgres/journal.d.ts +14 -11
  21. package/dist/adapters/postgres/journal.js +46 -23
  22. package/dist/adapters/postgres/manifest.d.ts +1 -1
  23. package/dist/adapters/postgres/manifest.js +1 -1
  24. package/dist/adapters/reference-executor.d.ts +26 -26
  25. package/dist/adapters/reference-executor.js +62 -57
  26. package/dist/contracts/index.d.ts +1 -1
  27. package/dist/contracts/index.js +1 -1
  28. package/dist/contracts/journal.d.ts +26 -16
  29. package/dist/contracts/manifest.d.ts +2 -2
  30. package/dist/contracts/{jobs.d.ts → pipelines.d.ts} +64 -51
  31. package/dist/pipelines/index.d.ts +1 -0
  32. package/dist/pipelines/index.js +2 -0
  33. package/dist/pipelines/pipeline.d.ts +142 -0
  34. package/dist/pipelines/pipeline.js +140 -0
  35. package/dist/pipelines/use-case-step.d.ts +24 -0
  36. package/dist/pipelines/use-case-step.js +34 -0
  37. package/dist/use-cases/index.d.ts +3 -0
  38. package/dist/use-cases/index.js +3 -0
  39. package/dist/use-cases/run-use-case.d.ts +33 -0
  40. package/dist/{actions/run-action.js → use-cases/run-use-case.js} +22 -18
  41. package/dist/{actions/action-consumer.d.ts → use-cases/use-case-consumer.d.ts} +11 -12
  42. package/dist/use-cases/use-case-consumer.js +98 -0
  43. package/dist/use-cases/use-case.d.ts +116 -0
  44. package/dist/use-cases/use-case.js +75 -0
  45. package/dist/webhooks/create-webhook-handler.d.ts +6 -6
  46. package/dist/webhooks/create-webhook-handler.js +32 -25
  47. package/dist/webhooks/dead-letter-consumer.d.ts +1 -1
  48. package/dist/webhooks/dead-letter-consumer.js +5 -5
  49. package/dist/webhooks/define-registry.d.ts +13 -13
  50. package/dist/webhooks/define-registry.js +15 -15
  51. package/dist/webhooks/once.d.ts +3 -3
  52. package/dist/webhooks/once.js +5 -5
  53. package/dist/webhooks/redact-customer-bodies.d.ts +1 -1
  54. package/dist/webhooks/redact-customer-bodies.js +1 -1
  55. package/dist/webhooks/replay-webhooks.d.ts +8 -8
  56. package/dist/webhooks/replay-webhooks.js +29 -26
  57. package/dist/webhooks/sweep-stuck-tasks.d.ts +32 -0
  58. package/dist/webhooks/sweep-stuck-tasks.js +73 -0
  59. package/dist/webhooks/webhook-consumer.d.ts +19 -18
  60. package/dist/webhooks/webhook-consumer.js +29 -24
  61. package/migrations/0012_rename_webhook_task_action_to_use_case.sql +11 -0
  62. package/migrations/0013_rename_job_tables_to_pipeline.sql +24 -0
  63. package/migrations/0016_add_webhook_task_requeues.sql +3 -0
  64. package/migrations/postgres/0012_rename_webhook_task_action_to_use_case.sql +5 -0
  65. package/migrations/postgres/0013_rename_job_tables_to_pipeline.sql +22 -0
  66. package/migrations/postgres/0016_add_webhook_task_requeues.sql +3 -0
  67. package/package.json +13 -6
  68. package/dist/actions/action-consumer.js +0 -90
  69. package/dist/actions/action.d.ts +0 -67
  70. package/dist/actions/action.js +0 -12
  71. package/dist/actions/index.d.ts +0 -3
  72. package/dist/actions/index.js +0 -4
  73. package/dist/actions/run-action.d.ts +0 -31
  74. package/dist/adapters/cloudflare/workflow-jobs.d.ts +0 -57
  75. /package/dist/contracts/{jobs.js → pipelines.js} +0 -0
@@ -6,7 +6,7 @@ import type { WebhookRegistry } from './define-registry.js';
6
6
  * (https://shopify.dev/docs/apps/build/events/delivery-structure, 2026-11-11).
7
7
  */
8
8
  export declare const WEBHOOK_MAX_BODY_BYTES: number;
9
- /** What the edge sends to `webhookQueue`: one per Action of each delivery it accepts. */
9
+ /** What the edge sends to `webhookQueue`: one per use case of each delivery it accepts. */
10
10
  export type WebhookMessage = {
11
11
  readonly source: string;
12
12
  /** As Shopify sends it, for example `orders/create`. */
@@ -16,8 +16,8 @@ export type WebhookMessage = {
16
16
  readonly webhookId: string;
17
17
  /** The raw body's key in `blobStore`, written before this message was sent. */
18
18
  readonly bodyKey: string;
19
- /** The registered Action this message runs: one task of the delivery's receipt. */
20
- readonly action: string;
19
+ /** The registered use case this message runs: one task of the delivery's receipt. */
20
+ readonly useCase: string;
21
21
  };
22
22
  /** A delivery's dedup key, and its id in the journal's receipts. Scoped by shop, as the #126 spike recommends. */
23
23
  export declare const webhookDeliveryId: ({ source, shop, topic, webhookId, }: Pick<WebhookMessage, "source" | "shop" | "topic" | "webhookId">) => string;
@@ -25,11 +25,11 @@ export type WebhookHandlerOptions = {
25
25
  /** Names the app. Part of every dedup key, so keep it once deliveries arrive. */
26
26
  readonly source: string;
27
27
  /**
28
- * The consumer's registry. A delivery is receipted with one task per Action
28
+ * The consumer's registry. A delivery is receipted with one task per use case
29
29
  * of its `(source, topic)`, and queued as one message per task. A topic with
30
30
  * none is receipted, answered 200 as `unknown-topic` and not queued.
31
31
  */
32
- readonly registry: Pick<WebhookRegistry<never>, 'actionsFor'>;
32
+ readonly registry: Pick<WebhookRegistry<never>, 'useCasesFor'>;
33
33
  /** The app's client secret, which signs every delivery. */
34
34
  readonly secret: string;
35
35
  /**
@@ -57,7 +57,7 @@ export type WebhookHandlerOptions = {
57
57
  /**
58
58
  * The edge for Shopify webhooks: replay window, size, signature, shop, dedup
59
59
  * claim, raw body to `blobStore`, a receipt in the journal, then one pointer
60
- * per registered Action on `webhookQueue`, in one `sendBatch`, before the 200. Each answer is one journal unit. Throws unless retry horizon ≤ replay
60
+ * per registered use case on `webhookQueue`, in one `sendBatch`, before the 200. Each answer is one journal unit. Throws unless retry horizon ≤ replay
61
61
  * window ≤ dedup TTL, so a misconfigured app fails at start-up.
62
62
  */
63
63
  export declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
@@ -1,6 +1,5 @@
1
1
  import { checkDuration, instant, toIso, } from '../contracts/index.js';
2
- import { failed, skipped, written, } from '../actions/action.js';
3
- import { runAction, withRun } from '../actions/run-action.js';
2
+ import { UseCase, failed, skipped, written, } from '../use-cases/use-case.js';
4
3
  /**
5
4
  * The largest body the edge reads. Shopify publishes no cap for classic
6
5
  * webhooks; its Events API caps an HTTPS delivery at 5 MB
@@ -26,10 +25,12 @@ const REJECTION_STATUS = {
26
25
  'invalid-hmac': 401,
27
26
  'body-too-large': 413,
28
27
  };
29
- const receiveWebhook = {
30
- name: 'receive-webhook',
31
- unitType: 'webhook',
32
- key: ({ unitKey }) => unitKey,
28
+ class ReceiveWebhook extends UseCase {
29
+ name = 'receive-webhook';
30
+ unitType = 'webhook';
31
+ key({ unitKey }) {
32
+ return unitKey;
33
+ }
33
34
  async run({ request }, { deps, logger, track }) {
34
35
  const { source, secret, previousSecret, toolkit, sessionStorage } = deps;
35
36
  const hmac = request.headers.get('X-Shopify-Hmac-Sha256');
@@ -76,9 +77,9 @@ const receiveWebhook = {
76
77
  // 0010). Dated by Triggered-At, so a retry after midnight overwrites the
77
78
  // same key with the same bytes.
78
79
  const bodyKey = `webhooks/${source}/${shop}/${toIso(triggeredAt).slice(0, 10)}/${webhookId}`;
79
- const actions = deps.registry
80
- .actionsFor(source, topic)
81
- .map((registration) => registration.action.name);
80
+ const useCases = deps.registry
81
+ .useCasesFor(source, topic)
82
+ .map((registration) => registration.useCase.name);
82
83
  try {
83
84
  await track('blob', 'put', async () => toolkit.blobStore.put(bodyKey, body, {
84
85
  contentType: 'application/json',
@@ -100,7 +101,7 @@ const receiveWebhook = {
100
101
  webhookId,
101
102
  bodyKey,
102
103
  receivedAt: toolkit.clock.now(),
103
- }, actions));
104
+ }, useCases));
104
105
  }
105
106
  catch (error) {
106
107
  logger.error('receipt failed', { error: String(error) });
@@ -109,20 +110,20 @@ const receiveWebhook = {
109
110
  }
110
111
  // Recorded, so the unhandled-topic alarm can count it, and never 4xx:
111
112
  // design §7.1. Completed, so Shopify's redelivery is a duplicate.
112
- if (actions.length === 0) {
113
+ if (useCases.length === 0) {
113
114
  await toolkit.ledger.complete(key, deps.dedupTtlSeconds);
114
115
  return skipped('unknown-topic', ids);
115
116
  }
116
117
  // One call, so a throw means resend all: Postgres sends none, and each
117
- // Action's task makes a resent pointer harmless where some were sent (#127).
118
+ // use case's task makes a resent pointer harmless where some were sent (#127).
118
119
  try {
119
- await track('queue', 'sendBatch', async () => toolkit.webhookQueue.sendBatch(actions.map((action) => ({
120
+ await track('queue', 'sendBatch', async () => toolkit.webhookQueue.sendBatch(useCases.map((useCase) => ({
120
121
  source,
121
122
  topic,
122
123
  shop,
123
124
  webhookId,
124
125
  bodyKey,
125
- action,
126
+ useCase,
126
127
  }))));
127
128
  }
128
129
  catch (error) {
@@ -136,12 +137,13 @@ const receiveWebhook = {
136
137
  // delivery a second time.
137
138
  await toolkit.ledger.complete(key, deps.dedupTtlSeconds);
138
139
  return written(ids);
139
- },
140
- };
140
+ }
141
+ }
142
+ const receiveWebhook = new ReceiveWebhook();
141
143
  /**
142
144
  * The edge for Shopify webhooks: replay window, size, signature, shop, dedup
143
145
  * claim, raw body to `blobStore`, a receipt in the journal, then one pointer
144
- * per registered Action on `webhookQueue`, in one `sendBatch`, before the 200. Each answer is one journal unit. Throws unless retry horizon ≤ replay
146
+ * per registered use case on `webhookQueue`, in one `sendBatch`, before the 200. Each answer is one journal unit. Throws unless retry horizon ≤ replay
145
147
  * window ≤ dedup TTL, so a misconfigured app fails at start-up.
146
148
  */
147
149
  export function createWebhookHandler(options) {
@@ -166,15 +168,20 @@ export function createWebhookHandler(options) {
166
168
  const deps = { ...options, replayWindowSeconds, dedupTtlSeconds };
167
169
  return async (request) => {
168
170
  const topic = request.headers.get('X-Shopify-Topic') || 'unknown';
169
- const decision = await withRun(options.toolkit, {
170
- // Named the way @shopify/shopify-api names topics, as the example's runs are.
171
- job: `webhook.${topic.toUpperCase().replace(/[/.]/g, '_')}`,
172
- trigger: 'http',
173
- mode: 'live',
174
- }, async (scope) => runAction(receiveWebhook, {
171
+ // Chosen here, so a request with no webhook id is keyed by its run.
172
+ const runId = crypto.randomUUID();
173
+ const input = {
175
174
  request,
176
- unitKey: request.headers.get('X-Shopify-Webhook-Id') || scope.runId,
177
- }, scope, deps));
175
+ unitKey: request.headers.get('X-Shopify-Webhook-Id') || runId,
176
+ };
177
+ const decision = await receiveWebhook.execute(input, {
178
+ toolkit: options.toolkit,
179
+ trigger: 'http',
180
+ // Named the way @shopify/shopify-api names topics.
181
+ job: `webhook.${topic.toUpperCase().replace(/[/.]/g, '_')}`,
182
+ runId,
183
+ deps,
184
+ });
178
185
  return new Response(null, { status: statusFor(decision) });
179
186
  };
180
187
  }
@@ -1,5 +1,5 @@
1
1
  import type { QueueConsumer } from '../contracts/index.js';
2
- import type { JournalDeps } from '../actions/run-action.js';
2
+ import type { JournalDeps } from '../use-cases/run-use-case.js';
3
3
  import { type WebhookMessage } from './create-webhook-handler.js';
4
4
  /**
5
5
  * The consumer of the webhook queue's dead-letter queue: design §7.1, "a DLQ
@@ -14,15 +14,15 @@ export function createDeadLetterConsumer(toolkit) {
14
14
  return async (batch) => {
15
15
  for (const message of batch.messages) {
16
16
  const deliveryId = webhookDeliveryId(message.body);
17
- const { action } = message.body;
18
- const context = { deliveryId, action, messageId: message.id };
17
+ const { useCase } = message.body;
18
+ const context = { deliveryId, useCase, messageId: message.id };
19
19
  try {
20
- const task = (await journal.delivery(deliveryId))?.tasks.find((t) => t.action === action);
20
+ const task = (await journal.delivery(deliveryId))?.tasks.find((t) => t.useCase === useCase);
21
21
  if (task !== undefined &&
22
22
  ['received', 'processing', 'failed'].includes(task.state)) {
23
23
  // `dead` is reachable only from `processing`.
24
- await journal.moveTask(deliveryId, action, 'processing', clock.now());
25
- await journal.moveTask(deliveryId, action, 'dead', clock.now(), 'dead-lettered');
24
+ await journal.moveTask(deliveryId, useCase, 'processing', clock.now());
25
+ await journal.moveTask(deliveryId, useCase, 'dead', clock.now(), 'dead-lettered');
26
26
  }
27
27
  logger.warn('webhook dead-lettered', {
28
28
  ...context,
@@ -1,17 +1,17 @@
1
- import type { WebhookAction } from './webhook-consumer.js';
1
+ import type { WebhookUseCase } from './webhook-consumer.js';
2
2
  /**
3
- * The most Actions one topic may have: the edge sends one pointer per Action
3
+ * The most use cases one topic may have: the edge sends one pointer per use case
4
4
  * in one `sendBatch`, which Cloudflare caps at 100 messages (#127,
5
5
  * docs/platform-facts.md "`sendBatch` cap").
6
6
  */
7
- export declare const WEBHOOK_MAX_ACTIONS_PER_TOPIC = 100;
8
- /** One Action for one `(source, topic)`, with its own retry settings. */
7
+ export declare const WEBHOOK_MAX_USE_CASES_PER_TOPIC = 100;
8
+ /** One use case for one `(source, topic)`, with its own retry settings. */
9
9
  export type WebhookRegistration<Deps> = {
10
10
  readonly source: string;
11
11
  /** As Shopify sends it, for example `orders/create`. */
12
12
  readonly topic: string;
13
- readonly action: WebhookAction<Deps>;
14
- /** Overrides the consumer's `retryDelaySeconds` for this Action. */
13
+ readonly useCase: WebhookUseCase<Deps>;
14
+ /** Overrides the consumer's `retryDelaySeconds` for this use case. */
15
15
  readonly retryDelaySeconds?: number;
16
16
  /**
17
17
  * Overrides the consumer's `maxAttempts`, which it must not exceed. Below
@@ -28,15 +28,15 @@ export type WebhookTopicSettings = {
28
28
  readonly quietPeriodSeconds: number;
29
29
  };
30
30
  export type WebhookRegistry<Deps> = {
31
- readonly actions: readonly WebhookRegistration<Deps>[];
31
+ readonly useCases: readonly WebhookRegistration<Deps>[];
32
32
  readonly topics: readonly WebhookTopicSettings[];
33
- /** The topic's Actions, in registration order; none for an unknown topic. */
34
- actionsFor(source: string, topic: string): readonly WebhookRegistration<Deps>[];
33
+ /** The topic's use cases, in registration order; none for an unknown topic. */
34
+ useCasesFor(source: string, topic: string): readonly WebhookRegistration<Deps>[];
35
35
  };
36
36
  /**
37
- * The `(source, topic, action)` table the edge and the consumer share, as
38
- * data. Throws on a duplicate, on more than `WEBHOOK_MAX_ACTIONS_PER_TOPIC`
39
- * Actions for a topic, on settings for a topic with no Action and on a bad
37
+ * The `(source, topic, useCase)` table the edge and the consumer share, as
38
+ * data. Throws on a duplicate, on more than `WEBHOOK_MAX_USE_CASES_PER_TOPIC`
39
+ * use cases for a topic, on settings for a topic with no use case and on a bad
40
40
  * duration, so a misconfigured app fails at start-up.
41
41
  */
42
- export declare function defineRegistry<Deps>(actions: readonly WebhookRegistration<Deps>[], topics?: readonly WebhookTopicSettings[]): WebhookRegistry<Deps>;
42
+ export declare function defineRegistry<Deps>(useCases: readonly WebhookRegistration<Deps>[], topics?: readonly WebhookTopicSettings[]): WebhookRegistry<Deps>;
@@ -1,28 +1,28 @@
1
1
  import { checkDuration } from '../contracts/index.js';
2
2
  /**
3
- * The most Actions one topic may have: the edge sends one pointer per Action
3
+ * The most use cases one topic may have: the edge sends one pointer per use case
4
4
  * in one `sendBatch`, which Cloudflare caps at 100 messages (#127,
5
5
  * docs/platform-facts.md "`sendBatch` cap").
6
6
  */
7
- export const WEBHOOK_MAX_ACTIONS_PER_TOPIC = 100;
7
+ export const WEBHOOK_MAX_USE_CASES_PER_TOPIC = 100;
8
8
  /**
9
- * The `(source, topic, action)` table the edge and the consumer share, as
10
- * data. Throws on a duplicate, on more than `WEBHOOK_MAX_ACTIONS_PER_TOPIC`
11
- * Actions for a topic, on settings for a topic with no Action and on a bad
9
+ * The `(source, topic, useCase)` table the edge and the consumer share, as
10
+ * data. Throws on a duplicate, on more than `WEBHOOK_MAX_USE_CASES_PER_TOPIC`
11
+ * use cases for a topic, on settings for a topic with no use case and on a bad
12
12
  * duration, so a misconfigured app fails at start-up.
13
13
  */
14
- export function defineRegistry(actions, topics = []) {
14
+ export function defineRegistry(useCases, topics = []) {
15
15
  const byTopic = new Map();
16
- for (const registration of actions) {
17
- const { source, topic, action } = registration;
18
- const label = `${source} ${topic} ${action.name}`;
16
+ for (const registration of useCases) {
17
+ const { source, topic, useCase } = registration;
18
+ const label = `${source} ${topic} ${useCase.name}`;
19
19
  const key = topicKey(source, topic);
20
20
  const registered = byTopic.get(key) ?? [];
21
- if (registered.some((other) => other.action.name === action.name)) {
21
+ if (registered.some((other) => other.useCase.name === useCase.name)) {
22
22
  throw new TypeError(`webhook registry: ${label} is registered twice`);
23
23
  }
24
- if (registered.length === WEBHOOK_MAX_ACTIONS_PER_TOPIC) {
25
- throw new TypeError(`webhook registry: ${source} ${topic} has more than ${WEBHOOK_MAX_ACTIONS_PER_TOPIC} Actions`);
24
+ if (registered.length === WEBHOOK_MAX_USE_CASES_PER_TOPIC) {
25
+ throw new TypeError(`webhook registry: ${source} ${topic} has more than ${WEBHOOK_MAX_USE_CASES_PER_TOPIC} use cases`);
26
26
  }
27
27
  if (registration.retryDelaySeconds !== undefined) {
28
28
  checkDuration(label, 'retryDelaySeconds', registration.retryDelaySeconds);
@@ -38,7 +38,7 @@ export function defineRegistry(actions, topics = []) {
38
38
  for (const { source, topic, quietPeriodSeconds } of topics) {
39
39
  const key = topicKey(source, topic);
40
40
  if (!byTopic.has(key)) {
41
- throw new TypeError(`webhook registry: ${source} ${topic} has settings but no Action`);
41
+ throw new TypeError(`webhook registry: ${source} ${topic} has settings but no use case`);
42
42
  }
43
43
  if (settled.has(key)) {
44
44
  throw new TypeError(`webhook registry: ${source} ${topic} has settings twice`);
@@ -47,9 +47,9 @@ export function defineRegistry(actions, topics = []) {
47
47
  checkDuration(`${source} ${topic}`, 'quietPeriodSeconds', quietPeriodSeconds);
48
48
  }
49
49
  return {
50
- actions,
50
+ useCases,
51
51
  topics,
52
- actionsFor: (source, topic) => byTopic.get(topicKey(source, topic)) ?? [],
52
+ useCasesFor: (source, topic) => byTopic.get(topicKey(source, topic)) ?? [],
53
53
  };
54
54
  }
55
55
  // JSON, so no source or topic can collide with another through a separator.
@@ -2,14 +2,14 @@ import type { Ledger } from '../contracts/index.js';
2
2
  export interface OnceOptions {
3
3
  readonly ledger: Ledger;
4
4
  readonly source: string;
5
- readonly action: string;
5
+ readonly useCase: string;
6
6
  /** How long a run may take before another attempt can claim the key. */
7
7
  readonly leaseSeconds: number;
8
8
  }
9
9
  /**
10
- * Runs an Action's side effect once per key: claim, run, complete.
10
+ * Runs a use case's side effect once per key: claim, run, complete.
11
11
  * `'already-done'` does not carry the first run's result; it is not stored.
12
12
  * `'in-progress'` means another run holds the lease; retry the task later.
13
13
  */
14
14
  export type Once = <T>(key: string, ttlSeconds: number, fn: () => Promise<T>) => Promise<T | 'already-done' | 'in-progress'>;
15
- export declare function createOnce({ ledger, source, action, leaseSeconds, }: OnceOptions): Once;
15
+ export declare function createOnce({ ledger, source, useCase, leaseSeconds, }: OnceOptions): Once;
@@ -1,10 +1,10 @@
1
- export function createOnce({ ledger, source, action, leaseSeconds, }) {
2
- // A ':' in either would let two Actions build the same ledger key.
3
- if (`${source}${action}`.includes(':')) {
4
- throw new TypeError(`source and action must not contain ':'`);
1
+ export function createOnce({ ledger, source, useCase, leaseSeconds, }) {
2
+ // A ':' in either would let two use cases build the same ledger key.
3
+ if (`${source}${useCase}`.includes(':')) {
4
+ throw new TypeError(`source and useCase must not contain ':'`);
5
5
  }
6
6
  return async (key, ttlSeconds, fn) => {
7
- const ledgerKey = `${source}:${action}:${key}`;
7
+ const ledgerKey = `${source}:${useCase}:${key}`;
8
8
  const claim = await ledger.claim(ledgerKey, leaseSeconds);
9
9
  if (claim.status === 'completed') {
10
10
  return 'already-done';
@@ -21,7 +21,7 @@ export type CustomersRedactPayload = {
21
21
  *
22
22
  * shortcut: reads every body the shop has in one call, which on Workers can
23
23
  * pass the per-invocation operation limit for a very busy shop; make it a paged
24
- * Job when one does.
24
+ * Pipeline when one does.
25
25
  */
26
26
  export declare function redactCustomerBodies(blobStore: BlobStore, payload: CustomersRedactPayload, options: {
27
27
  readonly source: string;
@@ -18,7 +18,7 @@ const numericId = (id) => {
18
18
  *
19
19
  * shortcut: reads every body the shop has in one call, which on Workers can
20
20
  * pass the per-invocation operation limit for a very busy shop; make it a paged
21
- * Job when one does.
21
+ * Pipeline when one does.
22
22
  */
23
23
  export async function redactCustomerBodies(blobStore, payload, options) {
24
24
  const shop = payload.shop_domain;
@@ -5,7 +5,7 @@ import type { WebhookRegistry } from './define-registry.js';
5
5
  export type ReplayOutcome = 'replayed'
6
6
  /** The raw body is gone: swept past retention, or redacted. */
7
7
  | 'body-missing'
8
- /** The registry has no such Action for the delivery's topic. */
8
+ /** The registry has no such use case for the delivery's topic. */
9
9
  | 'not-registered'
10
10
  /** Not `dead` or `replayed`: done, or still in flight. */
11
11
  | 'not-replayable';
@@ -14,26 +14,26 @@ export type ReplayResult = {
14
14
  } | {
15
15
  readonly found: true;
16
16
  readonly tasks: readonly {
17
- readonly action: string;
17
+ readonly useCase: string;
18
18
  readonly outcome: ReplayOutcome;
19
19
  }[];
20
20
  };
21
21
  export type ReplayDeps = Pick<Toolkit<unknown, WebhookMessage>, 'journal' | 'clock' | 'logger' | 'blobStore' | 'webhookQueue'>;
22
22
  /**
23
- * Re-queues a delivery's tasks: each `dead` one moves to `replayed`, and an
24
- * Action registered since the delivery arrived gets its task, which backfills
23
+ * Re-queues a delivery's tasks: each `dead` one moves to `replayed`, and a
24
+ * use case registered since the delivery arrived gets its task, which backfills
25
25
  * it. Each sends one message, and the consumer reads the raw body again from
26
- * the blob store. `actions` narrows it, `[name]` to one task; the default is
27
- * every Action the registry has for the delivery's topic.
26
+ * the blob store. `useCases` narrows it, `[name]` to one task; the default is
27
+ * every use case the registry has for the delivery's topic.
28
28
  *
29
29
  * Journaled as a `replay` run with one unit per task, `actor` in its
30
- * `externalIds` (docs/operator-ledger.md §4). An Action that already did its
30
+ * `externalIds` (docs/operator-ledger.md §4). A use case that already did its
31
31
  * work is kept from doing it twice by its own `once()` keys, not by replay.
32
32
  *
33
33
  * A send that rejects leaves the task `replayed` and rejects; replaying it
34
34
  * again sends it again.
35
35
  */
36
36
  export declare function replayWebhooks<Deps>(deps: ReplayDeps, registry: WebhookRegistry<Deps>, deliveryId: string, options: {
37
- readonly actions?: readonly string[];
37
+ readonly useCases?: readonly string[];
38
38
  readonly actor: string;
39
39
  }): Promise<ReplayResult>;
@@ -1,14 +1,14 @@
1
- import { runAction, withRun } from '../actions/run-action.js';
2
- import { skipped, written } from '../actions/action.js';
1
+ import { runUnit, withRun } from '../use-cases/run-use-case.js';
2
+ import { skipped, written } from '../use-cases/use-case.js';
3
3
  /**
4
- * Re-queues a delivery's tasks: each `dead` one moves to `replayed`, and an
5
- * Action registered since the delivery arrived gets its task, which backfills
4
+ * Re-queues a delivery's tasks: each `dead` one moves to `replayed`, and a
5
+ * use case registered since the delivery arrived gets its task, which backfills
6
6
  * it. Each sends one message, and the consumer reads the raw body again from
7
- * the blob store. `actions` narrows it, `[name]` to one task; the default is
8
- * every Action the registry has for the delivery's topic.
7
+ * the blob store. `useCases` narrows it, `[name]` to one task; the default is
8
+ * every use case the registry has for the delivery's topic.
9
9
  *
10
10
  * Journaled as a `replay` run with one unit per task, `actor` in its
11
- * `externalIds` (docs/operator-ledger.md §4). An Action that already did its
11
+ * `externalIds` (docs/operator-ledger.md §4). A use case that already did its
12
12
  * work is kept from doing it twice by its own `once()` keys, not by replay.
13
13
  *
14
14
  * A send that rejects leaves the task `replayed` and rejects; replaying it
@@ -20,41 +20,41 @@ export async function replayWebhooks(deps, registry, deliveryId, options) {
20
20
  const externalIds = { actor: options.actor };
21
21
  return withRun(deps, { job: 'webhooks.replay', trigger: 'replay', mode: 'live' }, async (scope) => {
22
22
  if (found === undefined) {
23
- await runAction(unit(deliveryId, async () => skipped('not-found', { externalIds })), deliveryId, scope, null);
23
+ await runUnit(REPLAY_UNIT, deliveryId, scope, null, async () => skipped('not-found', { externalIds }));
24
24
  return { found: false };
25
25
  }
26
26
  const { delivery, tasks } = found;
27
27
  const registered = registry
28
- .actionsFor(delivery.source, delivery.topic)
29
- .map((r) => r.action.name);
28
+ .useCasesFor(delivery.source, delivery.topic)
29
+ .map((r) => r.useCase.name);
30
30
  // Checked before any task moves, so a swept body moves none. A sweep
31
31
  // racing this leaves a replayed task whose run fails visibly (#141).
32
32
  const hasBody = (await blobStore.get(delivery.bodyKey)) !== undefined;
33
33
  const results = [];
34
- for (const action of options.actions ?? registered) {
35
- const outcome = await replayOne(action);
36
- results.push({ action, outcome });
37
- await runAction(unit(`${deliveryId}:${action}`, async () => outcome === 'replayed'
34
+ for (const useCase of options.useCases ?? registered) {
35
+ const outcome = await replayOne(useCase);
36
+ results.push({ useCase, outcome });
37
+ await runUnit(REPLAY_UNIT, `${deliveryId}:${useCase}`, scope, null, async () => outcome === 'replayed'
38
38
  ? written({ externalIds })
39
- : skipped(outcome, { externalIds })), action, scope, null);
39
+ : skipped(outcome, { externalIds }));
40
40
  }
41
41
  return { found: true, tasks: results };
42
- async function replayOne(action) {
43
- if (!registered.includes(action)) {
42
+ async function replayOne(useCase) {
43
+ if (!registered.includes(useCase)) {
44
44
  return 'not-registered';
45
45
  }
46
46
  if (!hasBody) {
47
47
  return 'body-missing';
48
48
  }
49
- const task = tasks.find((t) => t.action === action);
49
+ const task = tasks.find((t) => t.useCase === useCase);
50
50
  if (task === undefined) {
51
- await journal.recordDelivery(delivery, [action]);
51
+ await journal.recordDelivery(delivery, [useCase]);
52
52
  }
53
53
  else if (
54
54
  // Already `replayed`: an earlier replay's send may have failed, and
55
55
  // nothing else re-sends it. A second message is safe: once() keys.
56
56
  task.state !== 'replayed' &&
57
- !(await journal.moveTask(deliveryId, action, 'replayed', clock.now()))) {
57
+ !(await journal.moveTask(deliveryId, useCase, 'replayed', clock.now()))) {
58
58
  return 'not-replayable';
59
59
  }
60
60
  const { source, topic, shop, webhookId, bodyKey } = delivery;
@@ -64,16 +64,19 @@ export async function replayWebhooks(deps, registry, deliveryId, options) {
64
64
  shop,
65
65
  webhookId,
66
66
  bodyKey,
67
- action,
67
+ useCase,
68
68
  });
69
69
  return 'replayed';
70
70
  }
71
71
  });
72
72
  }
73
- /** One replay unit, keyed by its task, whose decision was made before it runs. */
74
- const unit = (key, decide) => ({
73
+ /**
74
+ * A replay unit, keyed by its task, whose decision is made before it is
75
+ * recorded. Not a use case: replay records many of them in one run, which a
76
+ * use case's `execute` never does (decision 0013).
77
+ */
78
+ const REPLAY_UNIT = {
75
79
  name: 'webhooks.replay',
76
80
  unitType: 'webhook-task',
77
- key: () => key,
78
- run: decide,
79
- });
81
+ key: (unitKey) => unitKey,
82
+ };
@@ -0,0 +1,32 @@
1
+ import { type Toolkit } from '../contracts/index.js';
2
+ import type { WebhookMessage } from './create-webhook-handler.js';
3
+ export type SweepStuckTasksDeps = Pick<Toolkit<unknown, WebhookMessage>, 'journal' | 'clock' | 'logger' | 'webhookQueue'>;
4
+ export type SweepStuckTasksOptions = {
5
+ /** How long a task may sit in `received`, `processing` or `replayed` before it counts as stuck. */
6
+ readonly stuckAfterSeconds?: number;
7
+ /** Re-sends before a stuck task is marked `dead` with reason `stuck`. */
8
+ readonly maxRequeues?: number;
9
+ /** Tasks per sweep. A sweep that hits it leaves the rest to the next one. */
10
+ readonly limit?: number;
11
+ };
12
+ export type SweepStuckTasksResult = {
13
+ readonly requeued: number;
14
+ readonly dead: number;
15
+ };
16
+ /** Longer than a queue's backlog under normal load, so a waiting task is not re-sent. */
17
+ export declare const DEFAULT_STUCK_AFTER_SECONDS: number;
18
+ export declare const DEFAULT_MAX_REQUEUES = 3;
19
+ /**
20
+ * Finds tasks stuck in `received`, `processing` or `replayed` (a lost send, a
21
+ * consumer that died, a partial `sendBatch`) and re-sends each one's message,
22
+ * or marks it `dead` with reason `stuck` once it has been re-sent
23
+ * `maxRequeues` times. So no task is left silent.
24
+ *
25
+ * Each task is claimed with `reclaimStuckTask` before it is sent, so two
26
+ * overlapping sweeps send it once, and a task that moved since it was read is
27
+ * left alone. A send that rejects rejects the sweep, and the task, already
28
+ * counted, is sent again by a later sweep.
29
+ *
30
+ * Journaled as a `webhooks.sweep-stuck` run with one unit per task it claimed.
31
+ */
32
+ export declare function sweepStuckTasks(deps: SweepStuckTasksDeps, { stuckAfterSeconds, maxRequeues, limit, }?: SweepStuckTasksOptions): Promise<SweepStuckTasksResult>;
@@ -0,0 +1,73 @@
1
+ import { plusSeconds } from '../contracts/index.js';
2
+ import { runUnit, withRun } from '../use-cases/run-use-case.js';
3
+ import { skipped, written } from '../use-cases/use-case.js';
4
+ /** Longer than a queue's backlog under normal load, so a waiting task is not re-sent. */
5
+ export const DEFAULT_STUCK_AFTER_SECONDS = 15 * 60;
6
+ export const DEFAULT_MAX_REQUEUES = 3;
7
+ /**
8
+ * Finds tasks stuck in `received`, `processing` or `replayed` (a lost send, a
9
+ * consumer that died, a partial `sendBatch`) and re-sends each one's message,
10
+ * or marks it `dead` with reason `stuck` once it has been re-sent
11
+ * `maxRequeues` times. So no task is left silent.
12
+ *
13
+ * Each task is claimed with `reclaimStuckTask` before it is sent, so two
14
+ * overlapping sweeps send it once, and a task that moved since it was read is
15
+ * left alone. A send that rejects rejects the sweep, and the task, already
16
+ * counted, is sent again by a later sweep.
17
+ *
18
+ * Journaled as a `webhooks.sweep-stuck` run with one unit per task it claimed.
19
+ */
20
+ export async function sweepStuckTasks(deps, { stuckAfterSeconds = DEFAULT_STUCK_AFTER_SECONDS, maxRequeues = DEFAULT_MAX_REQUEUES, limit = 100, } = {}) {
21
+ // At zero or below, a claim could rewrite updated_at to the value it matched, and a second sweep would send again.
22
+ if (!(stuckAfterSeconds > 0)) {
23
+ throw new RangeError(`stuckAfterSeconds must be positive, not ${stuckAfterSeconds}`);
24
+ }
25
+ const { journal, clock, webhookQueue } = deps;
26
+ const stuck = await journal.stuckTasks(plusSeconds(clock.now(), -stuckAfterSeconds), limit);
27
+ const result = { requeued: 0, dead: 0 };
28
+ if (stuck.length === 0) {
29
+ return result;
30
+ }
31
+ async function send(task) {
32
+ const found = await journal.delivery(task.deliveryId);
33
+ if (found === undefined) {
34
+ throw new Error(`webhook delivery missing: ${task.deliveryId}`);
35
+ }
36
+ const { source, topic, shop, webhookId, bodyKey } = found.delivery;
37
+ await webhookQueue.send({
38
+ source,
39
+ topic,
40
+ shop,
41
+ webhookId,
42
+ bodyKey,
43
+ useCase: task.useCase,
44
+ });
45
+ }
46
+ return withRun(deps, { job: 'webhooks.sweep-stuck', trigger: 'schedule', mode: 'live' }, async (scope) => {
47
+ for (const task of stuck) {
48
+ const to = task.requeues < maxRequeues ? 'requeued' : 'dead';
49
+ if (!(await journal.reclaimStuckTask(task, clock.now(), to))) {
50
+ continue;
51
+ }
52
+ result[to]++;
53
+ // Claimed already, so the unit's decision is made; it only sends.
54
+ await runUnit(SWEEP_UNIT, task, scope, null, async ({ track }) => {
55
+ if (to === 'dead') {
56
+ return skipped('stuck');
57
+ }
58
+ await track('queue', 'send', async () => send(task));
59
+ return written();
60
+ });
61
+ }
62
+ return result;
63
+ });
64
+ }
65
+ /**
66
+ * A sweep unit, keyed by its task. Not a use case: a sweep records many of
67
+ * them in one run, which a use case's `execute` never does (decision 0013).
68
+ */
69
+ const SWEEP_UNIT = {
70
+ name: 'webhooks.sweep-stuck',
71
+ unitType: 'webhook-task',
72
+ key: (task) => `${task.deliveryId}:${task.useCase}`,
73
+ };