@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
@@ -3,7 +3,7 @@ import { NonRetryableError } from 'cloudflare:workflows';
3
3
  import { LimitExceeded, Misconfigured, Unavailable, } from '../../contracts/index.js';
4
4
  import { toFault } from './faults.js';
5
5
  import { CLOUDFLARE_MANIFEST } from './manifest.js';
6
- const TOOL = 'jobs';
6
+ const TOOL = 'pipelines';
7
7
  const NAME = /^[A-Za-z0-9_]{1,64}$/;
8
8
  const KEY = /^[A-Za-z0-9_-]+$/;
9
9
  const ID = /^[A-Za-z0-9_]+-[A-Za-z0-9_-]+$/;
@@ -32,7 +32,7 @@ const HANDLER_STEP = {
32
32
  retries: { limit: 10_000, delay: 60_000, backoff: 'constant' },
33
33
  };
34
34
  /**
35
- * Workflows step names. A user step is `step:<name>`, so no step name a Job
35
+ * Workflows step names. A user step is `step:<name>`, so no step name a Pipeline
36
36
  * chooses can be the handler's: the handler's step has no `:`-prefix of that
37
37
  * form, and Workflows caches a step's result by its name.
38
38
  */
@@ -53,8 +53,8 @@ const HANDLER_STEP_NAME = 'onExhausted';
53
53
  * terminal step is reported to the handler as `retries-exhausted`. It is
54
54
  * still not retried.
55
55
  */
56
- const MARKER = 'anatta-jobs:';
57
- const MARKED = /anatta-jobs:(terminal|result-too-large):(\S*)/;
56
+ const MARKER = 'anatta-pipelines:';
57
+ const MARKED = /anatta-pipelines:(terminal|result-too-large):(\S*)/;
58
58
  const mark = (cause, reasonCode = '') => `${MARKER}${cause}:${encodeURIComponent(reasonCode)}`;
59
59
  function exhaustionOf(step, error) {
60
60
  const message = error instanceof Error ? error.message : String(error);
@@ -76,7 +76,7 @@ const bytes = (json) => new TextEncoder().encode(json).byteLength;
76
76
  * `create()` with an id that Workflows still retains. Deployed, the message
77
77
  * is `(instance.already_exists) Instance already exists` (PR #89,
78
78
  * docs/platform-facts.md "Deployed"). The test pool's miniflare does not
79
- * throw at all, so only the unit test in workflow-jobs.spec.ts shows this mapping.
79
+ * throw at all, so only the unit test in workflow-pipelines.spec.ts shows this mapping.
80
80
  */
81
81
  const alreadyExists = (e) => e instanceof Error && e.message.includes('instance.already_exists');
82
82
  /**
@@ -123,31 +123,31 @@ function unpack(registration) {
123
123
  }
124
124
  /**
125
125
  * Every registration, by name. Throws for a name that breaks the rule or is
126
- * registered twice, and for a Job with two steps of the same name: each is a
126
+ * registered twice, and for a Pipeline with two steps of the same name: each is a
127
127
  * defect in the definition, found when the executor is built (rule 7,
128
- * `Job.name`, `Step`). A repeated step name would also give two `step.do`
128
+ * `PipelineDefinition.name`, `Step`). A repeated step name would also give two `step.do`
129
129
  * calls one name, and Workflows caches a step's result by its name.
130
130
  */
131
131
  function registry(registrations) {
132
- const jobs = new Map();
132
+ const pipelines = new Map();
133
133
  for (const registration of registrations) {
134
- const job = unpack(registration);
135
- if (!NAME.test(job.name)) {
136
- throw new LimitExceeded(TOOL, `Job name ${JSON.stringify(job.name)} must be 1 to 64 characters of [A-Za-z0-9_]`);
134
+ const pipeline = unpack(registration);
135
+ if (!NAME.test(pipeline.name)) {
136
+ throw new LimitExceeded(TOOL, `Pipeline name ${JSON.stringify(pipeline.name)} must be 1 to 64 characters of [A-Za-z0-9_]`);
137
137
  }
138
138
  const stepNames = new Set();
139
- for (const step of job.steps) {
139
+ for (const step of pipeline.steps) {
140
140
  if (stepNames.has(step.name)) {
141
- throw new Misconfigured(TOOL, `Job ${job.name} has two steps named ${JSON.stringify(step.name)}`);
141
+ throw new Misconfigured(TOOL, `Pipeline ${pipeline.name} has two steps named ${JSON.stringify(step.name)}`);
142
142
  }
143
143
  stepNames.add(step.name);
144
144
  }
145
- if (jobs.has(job.name)) {
146
- throw new Misconfigured(TOOL, `Job name ${job.name} is registered twice`);
145
+ if (pipelines.has(pipeline.name)) {
146
+ throw new Misconfigured(TOOL, `Pipeline name ${pipeline.name} is registered twice`);
147
147
  }
148
- jobs.set(job.name, job);
148
+ pipelines.set(pipeline.name, pipeline);
149
149
  }
150
- return jobs;
150
+ return pipelines;
151
151
  }
152
152
  /** The contract's retries, in Workflows' words. Both count retries. */
153
153
  const stepConfig = (s) => ({
@@ -178,27 +178,31 @@ async function attempt(s, base, maxBytes) {
178
178
  * The generic Workflow class. `registrations` is called with the Worker's
179
179
  * `env` in each invocation, so a deps builder can close over the bindings:
180
180
  *
181
- * export const JobsWorkflow = workflowJobsEntrypoint((env: Env) => [
182
- * (register) => register(selfSignUp, () => createSignUpDeps(env)),
183
- * ])
181
+ * export const PipelinesWorkflow = workflowPipelinesEntrypoint(
182
+ * (env: Env) => [
183
+ * (register) => register(selfSignUp, () => createSignUpDeps(env)),
184
+ * ],
185
+ * { toolkit: (env: Env) => toolkitFor(env) },
186
+ * )
184
187
  *
185
- * It must return the same registrations `createWorkflowJobs` was given.
188
+ * It must return the same registrations `createWorkflowPipelines` was given.
186
189
  */
187
- export function workflowJobsEntrypoint(registrations, options = {}) {
190
+ export function workflowPipelinesEntrypoint(registrations, options) {
188
191
  const maxBytes = options.stepResultMaxBytes ?? CLOUDFLARE_MANIFEST.stepResultMaxBytes;
189
- return class JobsEntrypoint extends WorkflowEntrypoint {
192
+ return class PipelinesEntrypoint extends WorkflowEntrypoint {
190
193
  async run(event, step) {
191
194
  const id = event.instanceId;
192
195
  const name = id.slice(0, Math.max(0, id.indexOf('-')));
193
- const job = registry(registrations(this.env)).get(name);
194
- if (job === undefined) {
195
- throw new NonRetryableError(`${TOOL}: no Job is registered for ${id}`);
196
+ const pipeline = registry(registrations(this.env)).get(name);
197
+ if (pipeline === undefined) {
198
+ throw new NonRetryableError(`${TOOL}: no Pipeline is registered for ${id}`);
196
199
  }
197
200
  const base = {
198
201
  instanceId: id,
199
202
  runId: event.payload.runId,
200
203
  unitKey: id.slice(name.length + 1),
201
204
  input: event.payload.input,
205
+ toolkit: options.toolkit(this.env),
202
206
  };
203
207
  const results = {};
204
208
  // `step.do`'s `Rpc.Serializable<T>` check recurses without end on the
@@ -207,7 +211,7 @@ export function workflowJobsEntrypoint(registrations, options = {}) {
207
211
  // is called on it, not bound.
208
212
  const steps = step;
209
213
  let exhaustion;
210
- for (const s of job.steps) {
214
+ for (const s of pipeline.steps) {
211
215
  const context = { ...base, results: { ...results } };
212
216
  try {
213
217
  results[s.name] = await steps.do(stepName(s.name), stepConfig(s), async () => attempt(s, context, maxBytes));
@@ -220,7 +224,7 @@ export function workflowJobsEntrypoint(registrations, options = {}) {
220
224
  if (exhaustion === undefined) {
221
225
  return null;
222
226
  }
223
- const handler = job.onExhausted;
227
+ const handler = pipeline.onExhausted;
224
228
  const failed = exhaustion;
225
229
  if (handler !== undefined) {
226
230
  const context = { ...base, results: { ...results } };
@@ -235,26 +239,26 @@ export function workflowJobsEntrypoint(registrations, options = {}) {
235
239
  };
236
240
  }
237
241
  /**
238
- * `Jobs` over the Workflow binding that `workflowJobsEntrypoint`'s class is
242
+ * `Pipelines` over the Workflow binding that `workflowPipelinesEntrypoint`'s class is
239
243
  * bound to. Throws when it is built if a registration's name breaks the rule.
240
244
  */
241
- export function createWorkflowJobs(options) {
242
- return new WorkflowJobs(options.workflow, registry(options.registrations));
245
+ export function createWorkflowPipelines(options) {
246
+ return new WorkflowPipelines(options.workflow, registry(options.registrations));
243
247
  }
244
- class WorkflowJobs {
248
+ class WorkflowPipelines {
245
249
  workflow;
246
- jobs;
247
- constructor(workflow, jobs) {
250
+ pipelines;
251
+ constructor(workflow, pipelines) {
248
252
  this.workflow = workflow;
249
- this.jobs = jobs;
253
+ this.pipelines = pipelines;
250
254
  }
251
255
  async dispatch(definition, input, options) {
252
- const job = this.jobs.get(definition.name);
253
- if (job === undefined) {
254
- throw new Misconfigured(TOOL, `Job ${definition.name} is not registered with this executor`);
256
+ const pipeline = this.pipelines.get(definition.name);
257
+ if (pipeline === undefined) {
258
+ throw new Misconfigured(TOOL, `Pipeline ${definition.name} is not registered with this executor`);
255
259
  }
256
- const key = job.key(input);
257
- const id = `${job.name}-${key}`;
260
+ const key = pipeline.key(input);
261
+ const id = `${pipeline.name}-${key}`;
258
262
  if (!KEY.test(key) || id.length > ID_MAX) {
259
263
  throw new LimitExceeded(TOOL, `key ${JSON.stringify(key)} must be [A-Za-z0-9_-], at least one character, and fit an id of ${ID_MAX}`);
260
264
  }
@@ -275,9 +279,9 @@ class WorkflowJobs {
275
279
  }
276
280
  async status(id) {
277
281
  const name = id.slice(0, Math.max(0, id.indexOf('-')));
278
- // An id that breaks the rule, or names no registered Job, was never
282
+ // An id that breaks the rule, or names no registered Pipeline, was never
279
283
  // started here. The platform is not asked.
280
- if (!ID.test(id) || id.length > ID_MAX || !this.jobs.has(name)) {
284
+ if (!ID.test(id) || id.length > ID_MAX || !this.pipelines.has(name)) {
281
285
  return { status: 'unknown' };
282
286
  }
283
287
  let instance;
@@ -60,10 +60,11 @@ export type DeliveryRecord = {
60
60
  };
61
61
  export type TaskRecord = {
62
62
  delivery_id: string;
63
- action: string;
63
+ use_case: string;
64
64
  state: string;
65
65
  updated_at: Big;
66
66
  reason_code: string | null;
67
+ requeues: number;
67
68
  };
68
69
  /** The same defaults the memory adapter uses, so a limit means one thing. */
69
70
  export declare const DEFAULT_UNIT_LIMIT = 100;
@@ -61,14 +61,15 @@ export const toDeliveryRow = (r) => ({
61
61
  });
62
62
  export const toTaskRow = (r) => ({
63
63
  deliveryId: r.delivery_id,
64
- action: r.action,
64
+ useCase: r.use_case,
65
65
  state: r.state,
66
66
  updatedAt: fromEpochMs(Number(r.updated_at)),
67
67
  ...optional('reasonCode', r.reason_code),
68
+ requeues: Number(r.requeues),
68
69
  });
69
70
  /** Before every real row, so a first page needs no second query. */
70
71
  export const FIRST_TASK = {
71
72
  updatedAt: fromEpochMs(Number.MIN_SAFE_INTEGER),
72
73
  deliveryId: '',
73
- action: '',
74
+ useCase: '',
74
75
  };
@@ -8,4 +8,4 @@ export * from './manifest.js';
8
8
  export * from './session-storage.js';
9
9
  export * from './cache.js';
10
10
  export * from './toolkit.js';
11
- export * from './jobs.js';
11
+ export * from './pipelines.js';
@@ -8,4 +8,4 @@ export * from './manifest.js';
8
8
  export * from './session-storage.js';
9
9
  export * from './cache.js';
10
10
  export * from './toolkit.js';
11
- export * from './jobs.js';
11
+ export * from './pipelines.js';
@@ -19,16 +19,17 @@ export declare class MemoryJournal implements Journal {
19
19
  latestForUnit(unitKey: UnitKey): Promise<UnitRow | undefined>;
20
20
  failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
21
21
  recentRuns(limit?: number): Promise<readonly RunRow[]>;
22
- recordDelivery(delivery: DeliveryRow, actions: readonly string[]): Promise<void>;
23
- moveTask(deliveryId: string, action: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
22
+ recordDelivery(delivery: DeliveryRow, useCases: readonly string[]): Promise<void>;
23
+ moveTask(deliveryId: string, useCase: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
24
24
  delivery(deliveryId: string): Promise<{
25
25
  delivery: DeliveryRow;
26
26
  tasks: readonly TaskRow[];
27
27
  } | undefined>;
28
- deadTasks({ action, after, limit, }?: {
29
- readonly action?: string;
28
+ deadTasks({ useCase, after, limit, }?: {
29
+ readonly useCase?: string;
30
30
  readonly after?: TaskCursor;
31
31
  readonly limit?: number;
32
32
  }): Promise<readonly TaskRow[]>;
33
33
  stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
34
+ reclaimStuckTask({ deliveryId, useCase, updatedAt, }: Pick<TaskRow, 'deliveryId' | 'useCase' | 'updatedAt'>, at: Instant, to: 'requeued' | 'dead'): Promise<boolean>;
34
35
  }
@@ -1,8 +1,13 @@
1
1
  import { TASK_TRANSITIONS, } from '../../contracts/index.js';
2
- /** The SQL adapters' order: updated_at, then delivery_id, then action. Strings by code unit, as D1 does; Postgres uses its collation. */
2
+ const STUCK_STATES = [
3
+ 'received',
4
+ 'processing',
5
+ 'replayed',
6
+ ];
7
+ /** The SQL adapters' order: updated_at, then delivery_id, then use_case. Strings by code unit, as D1 does; Postgres uses its collation. */
3
8
  const byTaskOrder = (a, b) => a.updatedAt - b.updatedAt ||
4
9
  (a.deliveryId < b.deliveryId ? -1 : a.deliveryId > b.deliveryId ? 1 : 0) ||
5
- (a.action < b.action ? -1 : a.action > b.action ? 1 : 0);
10
+ (a.useCase < b.useCase ? -1 : a.useCase > b.useCase ? 1 : 0);
6
11
  export class MemoryJournal {
7
12
  #runs = new Map();
8
13
  #units = [];
@@ -74,24 +79,25 @@ export class MemoryJournal {
74
79
  .sort((a, b) => b.startedAt - a.startedAt)
75
80
  .slice(0, limit);
76
81
  }
77
- async recordDelivery(delivery, actions) {
82
+ async recordDelivery(delivery, useCases) {
78
83
  if (!this.#deliveries.has(delivery.deliveryId)) {
79
84
  this.#deliveries.set(delivery.deliveryId, delivery);
80
85
  }
81
- for (const action of actions) {
82
- const key = JSON.stringify([delivery.deliveryId, action]);
86
+ for (const useCase of useCases) {
87
+ const key = JSON.stringify([delivery.deliveryId, useCase]);
83
88
  if (!this.#tasks.has(key)) {
84
89
  this.#tasks.set(key, {
85
90
  deliveryId: delivery.deliveryId,
86
- action,
91
+ useCase,
87
92
  state: 'received',
88
93
  updatedAt: delivery.receivedAt,
94
+ requeues: 0,
89
95
  });
90
96
  }
91
97
  }
92
98
  }
93
- async moveTask(deliveryId, action, to, at, reasonCode) {
94
- const key = JSON.stringify([deliveryId, action]);
99
+ async moveTask(deliveryId, useCase, to, at, reasonCode) {
100
+ const key = JSON.stringify([deliveryId, useCase]);
95
101
  const task = this.#tasks.get(key);
96
102
  if (task === undefined || !TASK_TRANSITIONS[to].includes(task.state)) {
97
103
  return false;
@@ -102,6 +108,7 @@ export class MemoryJournal {
102
108
  state: to,
103
109
  updatedAt: at,
104
110
  ...(reasonCode === undefined ? {} : { reasonCode }),
111
+ requeues: to === 'replayed' ? 0 : task.requeues,
105
112
  });
106
113
  return true;
107
114
  }
@@ -114,22 +121,34 @@ export class MemoryJournal {
114
121
  delivery,
115
122
  tasks: [...this.#tasks.values()]
116
123
  .filter((t) => t.deliveryId === deliveryId)
117
- .sort((a, b) => (a.action < b.action ? -1 : 1)),
124
+ .sort((a, b) => (a.useCase < b.useCase ? -1 : 1)),
118
125
  };
119
126
  }
120
- async deadTasks({ action, after, limit = 100, } = {}) {
127
+ async deadTasks({ useCase, after, limit = 100, } = {}) {
121
128
  return [...this.#tasks.values()]
122
129
  .filter((t) => t.state === 'dead' &&
123
- (action === undefined || t.action === action) &&
130
+ (useCase === undefined || t.useCase === useCase) &&
124
131
  (after === undefined || byTaskOrder(t, after) > 0))
125
132
  .sort(byTaskOrder)
126
133
  .slice(0, limit);
127
134
  }
128
135
  async stuckTasks(before, limit = 100) {
129
136
  return [...this.#tasks.values()]
130
- .filter((t) => (t.state === 'received' || t.state === 'processing') &&
131
- t.updatedAt < before)
137
+ .filter((t) => STUCK_STATES.includes(t.state) && t.updatedAt < before)
132
138
  .sort(byTaskOrder)
133
139
  .slice(0, limit);
134
140
  }
141
+ async reclaimStuckTask({ deliveryId, useCase, updatedAt, }, at, to) {
142
+ const key = JSON.stringify([deliveryId, useCase]);
143
+ const task = this.#tasks.get(key);
144
+ if (task === undefined ||
145
+ !STUCK_STATES.includes(task.state) ||
146
+ task.updatedAt !== updatedAt) {
147
+ return false;
148
+ }
149
+ this.#tasks.set(key, to === 'dead'
150
+ ? { ...task, state: 'dead', updatedAt: at, reasonCode: 'stuck' }
151
+ : { ...task, updatedAt: at, requeues: task.requeues + 1 });
152
+ return true;
153
+ }
135
154
  }
@@ -46,7 +46,7 @@ export declare const LOCAL_MANIFEST: {
46
46
  readonly cacheMinTtlSeconds: 1;
47
47
  /**
48
48
  * 1 MiB, the same as Workflows, and deliberately not larger although a Map
49
- * has no ceiling. A Job definition is written once and run here locally and
49
+ * has no ceiling. A Pipeline definition is written once and run here locally and
50
50
  * on Workflows when deployed. A larger local limit would let a step pass
51
51
  * every local test and fail in production, which is the failure decision
52
52
  * 0003 found when local Queues enforced nothing.
@@ -46,7 +46,7 @@ export const LOCAL_MANIFEST = {
46
46
  cacheMinTtlSeconds: 1,
47
47
  /**
48
48
  * 1 MiB, the same as Workflows, and deliberately not larger although a Map
49
- * has no ceiling. A Job definition is written once and run here locally and
49
+ * has no ceiling. A Pipeline definition is written once and run here locally and
50
50
  * on Workflows when deployed. A larger local limit would let a step pass
51
51
  * every local test and fail in production, which is the failure decision
52
52
  * 0003 found when local Queues enforced nothing.
@@ -1,31 +1,31 @@
1
- import type { Instant, JobInstanceId, JobRegistration, Jobs, Toolkit } from '../../contracts/index.js';
1
+ import type { Instant, PipelineInstanceId, PipelineRegistration, Pipelines, Toolkit } from '../../contracts/index.js';
2
2
  import type { InstanceChange, InstanceRow, Interrupt, ReferenceStore, WakeUp } from '../reference-executor.js';
3
3
  import { LocalQueue } from './queue.js';
4
4
  /**
5
- * `job_instances` and `job_steps` (decision 0006) as two Maps. Each method is
5
+ * `pipeline_instances` and `pipeline_steps` (decision 0006) as two Maps. Each method is
6
6
  * one statement of the protocol, and none of them awaits between its read
7
7
  * and its write, so each is atomic in one isolate as the D1 statement is.
8
8
  */
9
- export declare class MemoryJobStore implements ReferenceStore {
9
+ export declare class MemoryPipelineStore implements ReferenceStore {
10
10
  #private;
11
11
  insert(row: InstanceRow): Promise<'inserted' | 'exists'>;
12
- get(id: JobInstanceId): Promise<InstanceRow | undefined>;
13
- update(id: JobInstanceId, version: number, change: InstanceChange): Promise<boolean>;
14
- remove(id: JobInstanceId, cutoff: Instant): Promise<void>;
15
- storeResult(id: JobInstanceId, stepIndex: number, result: string, _completedAt: Instant): Promise<void>;
16
- results(id: JobInstanceId): Promise<ReadonlyMap<number, string>>;
12
+ get(id: PipelineInstanceId): Promise<InstanceRow | undefined>;
13
+ update(id: PipelineInstanceId, version: number, change: InstanceChange): Promise<boolean>;
14
+ remove(id: PipelineInstanceId, cutoff: Instant): Promise<void>;
15
+ storeResult(id: PipelineInstanceId, stepIndex: number, result: string, _completedAt: Instant): Promise<void>;
16
+ results(id: PipelineInstanceId): Promise<ReadonlyMap<number, string>>;
17
17
  due(now: Instant): Promise<readonly InstanceRow[]>;
18
18
  removeEndedBefore(cutoff: Instant): Promise<void>;
19
19
  }
20
20
  /**
21
- * THE REFERENCE EXECUTOR ON THE MEMORY ADAPTER. Every local test of a Job
21
+ * THE REFERENCE EXECUTOR ON THE MEMORY ADAPTER. Every local test of a Pipeline
22
22
  * runs here.
23
23
  *
24
24
  * Nothing delivers an in-process queue on its own schedule, so `settle` and
25
25
  * `wake` are how a test or `npm run dev` drives it. They are affordances of
26
- * this adapter, as `LocalQueue.drain` is, and not part of `Jobs`.
26
+ * this adapter, as `LocalQueue.drain` is, and not part of `Pipelines`.
27
27
  */
28
- export type MemoryJobs = Jobs & {
28
+ export type MemoryPipelines = Pipelines & {
29
29
  /**
30
30
  * Runs the sweeper and delivers every wake-up that is due at the clock's
31
31
  * current time, one at a time, until nothing more is due. It never moves
@@ -39,10 +39,10 @@ export type MemoryJobs = Jobs & {
39
39
  * reordered message would, and returns once it is handled. Without
40
40
  * `stepIndex` it names the instance's current step.
41
41
  */
42
- wake(id: JobInstanceId, stepIndex?: number): Promise<void>;
42
+ wake(id: PipelineInstanceId, stepIndex?: number): Promise<void>;
43
43
  };
44
- export type MemoryJobsOptions = {
45
- readonly registrations: readonly JobRegistration[];
44
+ export type MemoryPipelinesOptions = {
45
+ readonly registrations: readonly PipelineRegistration[];
46
46
  /**
47
47
  * TEST SEAMS. A restarted process is a second executor over the same
48
48
  * store and queue, and `interrupt` parks a consumer between two writes.
@@ -54,9 +54,9 @@ export type MemoryJobsOptions = {
54
54
  };
55
55
  /**
56
56
  * Builds the executor. It throws when a registration is refused, as for a
57
- * Job name outside `[A-Za-z0-9_]{1,64}`.
57
+ * Pipeline name outside `[A-Za-z0-9_]{1,64}`.
58
58
  *
59
59
  * The toolkit supplies the clock (rule 3: backoff and leases are read from
60
60
  * it), the logger (rule 4) and the journal its Step rows go to.
61
61
  */
62
- export declare function createMemoryJobs(toolkit: Pick<Toolkit, 'clock' | 'logger' | 'journal'>, options: MemoryJobsOptions): MemoryJobs;
62
+ export declare function createMemoryPipelines(toolkit: Pick<Toolkit, 'clock' | 'logger' | 'journal'>, options: MemoryPipelinesOptions): MemoryPipelines;
@@ -3,11 +3,11 @@ import { ReferenceExecutor } from '../reference-executor.js';
3
3
  import { LOCAL_MANIFEST } from './manifest.js';
4
4
  import { LocalQueue } from './queue.js';
5
5
  /**
6
- * `job_instances` and `job_steps` (decision 0006) as two Maps. Each method is
6
+ * `pipeline_instances` and `pipeline_steps` (decision 0006) as two Maps. Each method is
7
7
  * one statement of the protocol, and none of them awaits between its read
8
8
  * and its write, so each is atomic in one isolate as the D1 statement is.
9
9
  */
10
- export class MemoryJobStore {
10
+ export class MemoryPipelineStore {
11
11
  #instances = new Map();
12
12
  #steps = new Map();
13
13
  async insert(row) {
@@ -66,14 +66,14 @@ export class MemoryJobStore {
66
66
  const MAX_ROUNDS = 10_000;
67
67
  /**
68
68
  * Builds the executor. It throws when a registration is refused, as for a
69
- * Job name outside `[A-Za-z0-9_]{1,64}`.
69
+ * Pipeline name outside `[A-Za-z0-9_]{1,64}`.
70
70
  *
71
71
  * The toolkit supplies the clock (rule 3: backoff and leases are read from
72
72
  * it), the logger (rule 4) and the journal its Step rows go to.
73
73
  */
74
- export function createMemoryJobs(toolkit, options) {
74
+ export function createMemoryPipelines(toolkit, options) {
75
75
  const { clock, logger, journal } = toolkit;
76
- const store = options.store ?? new MemoryJobStore();
76
+ const store = options.store ?? new MemoryPipelineStore();
77
77
  const queue = options.queue ??
78
78
  new LocalQueue({
79
79
  clock,
@@ -174,7 +174,7 @@ export function createMemoryJobs(toolkit, options) {
174
174
  return;
175
175
  }
176
176
  }
177
- throw new Error(`jobs: settle() did not converge in ${MAX_ROUNDS} rounds`);
177
+ throw new Error(`pipelines: settle() did not converge in ${MAX_ROUNDS} rounds`);
178
178
  },
179
179
  async wake(id, stepIndex) {
180
180
  const row = await store.get(id);
@@ -14,8 +14,9 @@ import { type CallRow, type DeliveryRow, type Instant, type Journal, type Logger
14
14
  * failuresByReason journal_units_recorded_at
15
15
  * delivery webhook_deliveries_pkey, webhook_tasks_pkey
16
16
  * deadTasks webhook_tasks_state
17
- * deadTasksByAction webhook_tasks_action_state
17
+ * deadTasksByUseCase webhook_tasks_use_case_state
18
18
  * stuckTasks webhook_tasks_state
19
+ * reclaimStuckTask webhook_tasks_pkey or webhook_tasks_action_state
19
20
  */
20
21
  declare const Q: {
21
22
  readonly startRun: "\n INSERT INTO journal_runs\n (run_id, job, trigger, mode, started_at, identity)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (run_id) DO UPDATE SET\n job = $2, trigger = $3, mode = $4, started_at = $5, identity = $6\n ";
@@ -31,13 +32,14 @@ declare const Q: {
31
32
  readonly latestForUnit: "\n SELECT * FROM journal_units\n WHERE unit_key = $1 ORDER BY recorded_at DESC LIMIT 1\n ";
32
33
  readonly failuresByReason: "\n SELECT reason_code, COUNT(*) AS count\n FROM journal_units\n WHERE recorded_at >= $1\n AND reason_code IS NOT NULL\n AND outcome != 'written'\n GROUP BY reason_code\n ORDER BY count DESC, reason_code ASC\n ";
33
34
  readonly recentRuns: "SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT $1";
34
- readonly recordDelivery: "\n WITH delivery AS (\n INSERT INTO webhook_deliveries\n (delivery_id, source, topic, shop, webhook_id, body_key, received_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (delivery_id) DO NOTHING\n )\n INSERT INTO webhook_tasks (delivery_id, action, state, updated_at)\n SELECT $1, action, 'received', $7 FROM unnest($8::text[]) AS action\n ON CONFLICT (delivery_id, action) DO NOTHING\n ";
35
- readonly moveTask: "\n UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6\n WHERE delivery_id = $1 AND action = $2 AND state = ANY($5::text[])\n ";
35
+ readonly recordDelivery: "\n WITH delivery AS (\n INSERT INTO webhook_deliveries\n (delivery_id, source, topic, shop, webhook_id, body_key, received_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (delivery_id) DO NOTHING\n )\n INSERT INTO webhook_tasks (delivery_id, use_case, state, updated_at)\n SELECT $1, use_case, 'received', $7 FROM unnest($8::text[]) AS use_case\n ON CONFLICT (delivery_id, use_case) DO NOTHING\n ";
36
+ readonly moveTask: "\n UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6,\n requeues = CASE WHEN $3 = 'replayed' THEN 0 ELSE requeues END\n WHERE delivery_id = $1 AND use_case = $2 AND state = ANY($5::text[])\n ";
36
37
  readonly delivery: "SELECT * FROM webhook_deliveries WHERE delivery_id = $1";
37
- readonly tasksForDelivery: "\n SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY action\n ";
38
- readonly deadTasks: "\n SELECT * FROM webhook_tasks\n WHERE state = 'dead' AND (updated_at, delivery_id, action) > ($1, $2, $3)\n ORDER BY updated_at, delivery_id, action LIMIT $4\n ";
39
- readonly deadTasksByAction: "\n SELECT * FROM webhook_tasks\n WHERE action = $5 AND state = 'dead'\n AND (updated_at, delivery_id, action) > ($1, $2, $3)\n ORDER BY updated_at, delivery_id LIMIT $4\n ";
40
- readonly stuckTasks: "\n SELECT * FROM webhook_tasks\n WHERE state IN ('received', 'processing') AND updated_at < $1\n ORDER BY updated_at, delivery_id, action LIMIT $2\n ";
38
+ readonly tasksForDelivery: "\n SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY use_case\n ";
39
+ readonly deadTasks: "\n SELECT * FROM webhook_tasks\n WHERE state = 'dead' AND (updated_at, delivery_id, use_case) > ($1, $2, $3)\n ORDER BY updated_at, delivery_id, use_case LIMIT $4\n ";
40
+ readonly deadTasksByUseCase: "\n SELECT * FROM webhook_tasks\n WHERE use_case = $5 AND state = 'dead'\n AND (updated_at, delivery_id, use_case) > ($1, $2, $3)\n ORDER BY updated_at, delivery_id LIMIT $4\n ";
41
+ readonly stuckTasks: "\n SELECT * FROM webhook_tasks\n WHERE state IN ('received', 'processing', 'replayed') AND updated_at < $1\n ORDER BY updated_at, delivery_id, use_case LIMIT $2\n ";
42
+ readonly reclaimStuckTask: "\n UPDATE webhook_tasks SET\n updated_at = $5,\n state = CASE WHEN $4 = 'dead' THEN 'dead' ELSE state END,\n reason_code = CASE WHEN $4 = 'dead' THEN 'stuck' ELSE reason_code END,\n requeues = CASE WHEN $4 = 'dead' THEN requeues ELSE requeues + 1 END\n WHERE delivery_id = $1 AND use_case = $2 AND updated_at = $3\n AND state IN ('received', 'processing', 'replayed')\n ";
41
43
  };
42
44
  export type PostgresJournalOptions = {
43
45
  /** The app's pool. The journal never opens its own. docs/decisions/0007. */
@@ -67,17 +69,18 @@ export declare class PostgresJournal implements Journal {
67
69
  latestForUnit(unitKey: UnitKey): Promise<UnitRow | undefined>;
68
70
  failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
69
71
  recentRuns(limit?: number): Promise<readonly RunRow[]>;
70
- recordDelivery(delivery: DeliveryRow, actions: readonly string[]): Promise<void>;
71
- moveTask(deliveryId: string, action: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
72
+ recordDelivery(delivery: DeliveryRow, useCases: readonly string[]): Promise<void>;
73
+ moveTask(deliveryId: string, useCase: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
72
74
  delivery(deliveryId: string): Promise<{
73
75
  delivery: DeliveryRow;
74
76
  tasks: readonly TaskRow[];
75
77
  } | undefined>;
76
- deadTasks({ action, after, limit, }?: {
77
- readonly action?: string;
78
+ deadTasks({ useCase, after, limit, }?: {
79
+ readonly useCase?: string;
78
80
  readonly after?: TaskCursor;
79
81
  readonly limit?: number;
80
82
  }): Promise<readonly TaskRow[]>;
81
83
  stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
84
+ reclaimStuckTask(task: Pick<TaskRow, 'deliveryId' | 'useCase' | 'updatedAt'>, at: Instant, to: 'requeued' | 'dead'): Promise<boolean>;
82
85
  }
83
86
  export { Q as JOURNAL_QUERIES };