@ezghcloud/workflows 0.0.0 → 1.0.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 (51) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +418 -1
  3. package/dist/client.d.ts +209 -0
  4. package/dist/client.js +259 -0
  5. package/dist/env.d.ts +2 -0
  6. package/dist/env.js +32 -0
  7. package/dist/index.d.ts +15 -0
  8. package/dist/index.js +7 -0
  9. package/dist/protocol/bytes.d.ts +8 -0
  10. package/dist/protocol/bytes.js +49 -0
  11. package/dist/protocol/callback.d.ts +6 -0
  12. package/dist/protocol/callback.js +31 -0
  13. package/dist/protocol/codec.d.ts +6 -0
  14. package/dist/protocol/codec.js +38 -0
  15. package/dist/protocol/derived.d.ts +5 -0
  16. package/dist/protocol/derived.js +41 -0
  17. package/dist/protocol/index.d.ts +14 -0
  18. package/dist/protocol/index.js +21 -0
  19. package/dist/protocol/public.d.ts +2 -0
  20. package/dist/protocol/public.js +1 -0
  21. package/dist/protocol/signature.d.ts +17 -0
  22. package/dist/protocol/signature.js +101 -0
  23. package/dist/protocol/stepid.d.ts +4 -0
  24. package/dist/protocol/stepid.js +9 -0
  25. package/dist/protocol/tokens.d.ts +2 -0
  26. package/dist/protocol/tokens.js +38 -0
  27. package/dist/protocol/types.d.ts +185 -0
  28. package/dist/protocol/types.js +1 -0
  29. package/dist/protocol/validate.d.ts +15 -0
  30. package/dist/protocol/validate.js +279 -0
  31. package/dist/queues.d.ts +47 -0
  32. package/dist/queues.js +126 -0
  33. package/dist/runtime/context.d.ts +82 -0
  34. package/dist/runtime/context.js +1 -0
  35. package/dist/runtime/errors.d.ts +49 -0
  36. package/dist/runtime/errors.js +160 -0
  37. package/dist/runtime/execution.d.ts +17 -0
  38. package/dist/runtime/execution.js +608 -0
  39. package/dist/runtime/invocation.d.ts +5 -0
  40. package/dist/runtime/invocation.js +47 -0
  41. package/dist/runtime/live.d.ts +23 -0
  42. package/dist/runtime/live.js +103 -0
  43. package/dist/runtime/workflow.d.ts +26 -0
  44. package/dist/runtime/workflow.js +49 -0
  45. package/dist/serve.d.ts +12 -0
  46. package/dist/serve.js +149 -0
  47. package/dist/version.d.ts +2 -0
  48. package/dist/version.js +2 -0
  49. package/dist/worker.d.ts +43 -0
  50. package/dist/worker.js +364 -0
  51. package/package.json +48 -4
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1 +1,418 @@
1
- Releases of @ezghcloud/workflows are published from https://github.com/ezgamehost/workflows-sdk-ts.
1
+ # @ezghcloud/workflows
2
+
3
+ The TypeScript SDK for [EZGH Workflows](https://ezghcloud.com): durable workflows as code. You
4
+ write a workflow as an async function whose side effects run in named steps. EZGH records each
5
+ step's result, so a workflow survives crashes, deploys and long sleeps, and resumes exactly where
6
+ it left off. Your code runs on your own HTTPS endpoint (Node, Bun, Deno, Cloudflare Workers,
7
+ Next.js), and EZGH pushes signed invocations to it.
8
+
9
+ ```sh
10
+ npm install @ezghcloud/workflows
11
+ # or
12
+ bun add @ezghcloud/workflows
13
+ pnpm add @ezghcloud/workflows
14
+ ```
15
+
16
+ The package is published to npm from this repository's tags (see [Releasing](#releasing)), with
17
+ npm provenance.
18
+
19
+ ## Quick start
20
+
21
+ **1. Define workflows.** Side effects go in named steps; their JSON results are recorded.
22
+
23
+ ```ts
24
+ import { workflow } from "@ezghcloud/workflows"
25
+
26
+ export const onboarding = workflow("onboarding", async ({ input, step }) => {
27
+ const user = await step.run("load-user", () => db.users.get(input.userId))
28
+ await step.run("welcome-email", () => email.send(user.email, "Welcome!"))
29
+ await step.sleep("cooldown", "3d")
30
+ return step.run("follow-up", () => email.send(user.email, "How is it going?"))
31
+ })
32
+ ```
33
+
34
+ **2. Serve them** from one HTTPS route, with the app's signing secret (`whsec_…`, returned once
35
+ when you create the app; pass two during a rotation):
36
+
37
+ ```ts
38
+ import { serve } from "@ezghcloud/workflows"
39
+
40
+ export const POST = serve({ workflows: [onboarding], signingSecrets: [process.env.EZGH_WORKFLOWS_SIGNING_SECRET] })
41
+ ```
42
+
43
+ `serve` returns a Fetch-API handler `(Request) => Promise<Response>`. Examples:
44
+ [Bun](examples/bun/server.ts), [Node](examples/node/server.ts),
45
+ [Cloudflare Workers](examples/cloudflare/worker.ts) and
46
+ [Next.js](examples/nextjs/app/api/workflows/route.ts). Set `maxInvocationSeconds` to your
47
+ platform's request limit (default 300, at most 900).
48
+
49
+ **3. Sync after each deploy,** so EZGH learns the endpoint and its workflows
50
+ ([example](examples/deploy-sync.ts)):
51
+
52
+ ```ts
53
+ import { Client } from "@ezghcloud/workflows"
54
+
55
+ const client = new Client({ apiKey, organizationId, projectId })
56
+ await client.sync(appId, { endpoint: "https://app.example.com/api/workflows" })
57
+ ```
58
+
59
+ **4. Start runs** and follow them:
60
+
61
+ ```ts
62
+ const run = await client.start(appId, "onboarding", { userId: "u_1" }, { runKey: "signup-u_1" })
63
+ const latest = await client.get(run.id) // status, attempt, steps
64
+ const output = await client.output(run.id) // once completed
65
+ await client.cancel(run.id) // or client.retry(run.id) after a failure
66
+ ```
67
+
68
+ ## Parallel steps
69
+
70
+ Steps started together run in parallel: `Promise.all` and `Promise.race` over `step.run` calls
71
+ (and sleeps, callbacks and child workflows) hand every step to EZGH at once, and each runs in its
72
+ own invocation, retried on its own.
73
+
74
+ ```ts
75
+ const sizes = await Promise.all(urls.map((url, i) => step.run(`size-${i}`, () => fetchSize(url))))
76
+ const first = await Promise.race([step.run("work", doWork), step.sleep("limit", "10m").then(() => "timed out")])
77
+ ```
78
+
79
+ A run has at most 32 step invocations at once; further steps wait their turn. Steps pending
80
+ together need distinct names (or `{ id }`s). Replays resolve steps in the order they completed,
81
+ so a race takes the same branch every time. A step's `signal` also aborts when the run is
82
+ cancelling (pull workers learn it from their heartbeats).
83
+
84
+ ## Callbacks
85
+
86
+ `step.createCallback(name, { timeoutMs })` creates a callback (default timeout 7 days, from 1 s to
87
+ a year). Its `url` is `https://workflows-api.ezghcloud.com/public/v1/callbacks/<token>`: give it
88
+ to whoever completes the callback (a webhook, an approval email). `wait()` suspends the run until
89
+ someone POSTs a JSON body (at most 1 MiB) to the URL, and resolves with that body:
90
+
91
+ ```ts
92
+ const cb = await step.createCallback<{ approved: boolean }>("approval", { timeoutMs: 3 * 86_400_000 })
93
+ await step.run("ask", () => email.send(manager, `Approve? POST to ${cb.url}`))
94
+ try {
95
+ const { approved } = await cb.wait()
96
+ } catch (e) {
97
+ if (e instanceof CallbackTimeout) { /* nobody answered in time */ }
98
+ }
99
+ ```
100
+
101
+ The first completion wins; repeating it with the same body succeeds, a different body is a `409
102
+ callback_completed`, and a completion after the timeout is a `410 callback_expired`. An
103
+ authenticated caller can complete it with `POST …/runs/:runId/callbacks/:stepId` instead
104
+ (`workflows.callbacks.complete`). The token is the URL's only credential: keep it private. The
105
+ URL is recorded before your code sees it, so replays rebuild the same one.
106
+
107
+ ## Child workflows
108
+
109
+ `step.invoke(name, { workflow, input })` starts a run of another workflow in the same app and
110
+ waits for it, resolving with its output. A failed child rejects with `ChildFailed` (code
111
+ `workflows.child_failed`), whose `cause` is the child's own error. The child's run ID is derived
112
+ from the parent's and the step's, so it starts exactly once. Children nest at most 10 deep, and
113
+ each counts as one of its parent's steps.
114
+
115
+ ```ts
116
+ const report = await step.invoke("report", { workflow: buildReport, input: { month: "2026-10" } })
117
+ ```
118
+
119
+ A run a schedule started sees `run.schedule` (`{ id, scheduledTime }`, the cron instant).
120
+
121
+ ## Sending to a queue
122
+
123
+ `step.sendToQueue(name, client, queueId, messages)` sends 1–10 messages to an
124
+ [EZGH Queues](https://ezghcloud.com) queue in a step, and resolves with the recorded result
125
+ (`{ messages: [{ messageId, seq?, duplicate? }] }`, one per message, in order). It's `step.run`
126
+ around `client.send`, so a replay returns the result without sending again. The client is a
127
+ `QueuesClient` with your own API key (it needs `queues.messages.send` on the queue): push apps
128
+ hold no API key, so the step never borrows a credential.
129
+
130
+ ```ts
131
+ import { QueuesClient, workflow } from "@ezghcloud/workflows"
132
+
133
+ const queues = new QueuesClient({ apiKey, organizationId, projectId }) // baseUrl: https://queues-api.ezghcloud.com
134
+
135
+ const order = workflow("order", async ({ input, step }) => {
136
+ const placed = await step.run("place", () => shop.place(input))
137
+ await step.sendToQueue("notify", queues, "que_…", [
138
+ { body: JSON.stringify(placed), attributes: { orderId: placed.id }, groupId: placed.accountId },
139
+ ])
140
+ })
141
+ ```
142
+
143
+ - **Sent once.** Every attempt of the step sends the `Idempotency-Key`
144
+ `wfq_<hex(SHA-256(runId + ":" + stepId))>`, which the Queues API honors for 48 hours: an attempt
145
+ that resends after a crash (between the send and the step's record) gets the first answer
146
+ instead of a second copy, on standard and FIFO queues alike. So keep `messages` deterministic:
147
+ the same key with a different body is a `409 idempotency_conflict`.
148
+ - **FIFO dedup IDs.** A message with a `groupId` (a FIFO queue's message) and no `dedupId` of
149
+ its own is sent with `dedupId` `<that hex>:<index>`; FIFO queues also drop a repeat within
150
+ their 5-minute window. Messages without a `groupId` are sent as they are, since standard queues
151
+ refuse `dedupId`.
152
+ - **Errors.** The client resends a 429 (but not `quota_exceeded`), any 5xx, a 409
153
+ `idempotency_in_progress` and network errors after `Retry-After` (default 3 resends, at most
154
+ 10 s apart, `retries` and `maxRetryDelayMs` to change), then throws `QueuesApiError` with the
155
+ HTTP `status`, the platform `code` and `retryAfterSeconds`. In the step, what's still failing is
156
+ retried by the step's retry policy, but another 4xx (a bad message, a missing queue, a refused
157
+ permission) fails the step at once: `NonRetriableError` with the `QueuesApiError` as its
158
+ `cause`.
159
+
160
+ `client.send(queueId, messages, { idempotencyKey? })` works outside workflows too (without a key,
161
+ each call gets a random one, kept across its resends).
162
+
163
+ ## Waiting for a message
164
+
165
+ `step.waitForMessage(name, { queueId, key, timeoutSeconds })` suspends the run until a message
166
+ arrives on an EZGH queue for `key`, and resolves with it, or with `null` once `timeoutSeconds` (1
167
+ to 2,592,000, 30 days) pass without one. A timeout isn't an error.
168
+
169
+ ```ts
170
+ const paid = await step.waitForMessage("paid", { queueId: "0199a3d0-…", key: `order:${input.orderId}`, timeoutSeconds: 86_400 })
171
+ if (paid === null) return step.run("cancel-order", () => shop.cancel(input.orderId))
172
+ await step.run("ship", () => shop.ship(input.orderId, JSON.parse(paid.body)))
173
+ ```
174
+
175
+ - **Delivery.** The queue needs a subscription that targets the app's workflow in `resume` mode
176
+ with a `correlationAttribute` (say `orderId`). Each message whose attribute equals a wait's `key`
177
+ resumes every run waiting on that queue and key at that moment. A message nobody waits for is
178
+ retried with the subscription's backoff, then dead-lettered.
179
+ - **The message** is `{ messageId, body, attributes, sentAt, queueId, groupId?, seq? }`
180
+ (`ReceivedMessage`). It's recorded, so replays return the same one.
181
+ - `queueId` is the queue's ID (a UUID, not its `que_` slug); `key` matches
182
+ `^[A-Za-z0-9_.:-]{1,256}$`. Cancelling the run throws `CancelledError` from a pending wait.
183
+ - Waits need a workflows-stack serving protocol 1.2; at 1.0 or 1.1 the run fails with
184
+ `NonRetriableError`.
185
+
186
+ Parallel steps, callbacks and child workflows need a workflows-stack serving protocol 1.1. An
187
+ invocation at protocol 1.0 runs steps one after another, and `createCallback` and `invoke` fail
188
+ the run with `NonRetriableError`.
189
+
190
+ ## Tracing
191
+
192
+ While the project's Workflows observability setting is on, EZGH sends each invocation a W3C
193
+ `traceparent` (the push request's header, or a pulled invocation's field), and the context exposes
194
+ it exactly as received as `traceparent`. It's `""` while the setting is off, so a parent-based
195
+ sampler never waits for a parent that won't arrive. The SDK has no OpenTelemetry dependency; with
196
+ `@opentelemetry/api` (and the W3C propagator, which the Node SDK registers by default), parent your
197
+ own spans on it. Start them inside step functions: code outside steps re-runs on every replay.
198
+
199
+ ```ts
200
+ import { context, propagation, trace } from "@opentelemetry/api"
201
+
202
+ const tracer = trace.getTracer("billing")
203
+
204
+ const charge = workflow("charge", async ({ input, step, traceparent }) =>
205
+ step.run("charge-card", () => {
206
+ const parent = propagation.extract(context.active(), { traceparent })
207
+ return tracer.startActiveSpan("charge card", {}, parent, async (span) => {
208
+ try { return await chargeCard(input) } finally { span.end() }
209
+ })
210
+ }))
211
+ ```
212
+
213
+ ## Pull workers
214
+
215
+ A pull worker polls EZGH for work instead of exposing an HTTPS endpoint: for code behind a
216
+ firewall, or long CPU-bound steps. A pull invocation's deadline is the longest `timeoutMs` the
217
+ app's workers announce, at least 15 minutes and at most 24 hours; heartbeats keep it honest. So
218
+ for a step longer than 15 minutes, give its workflow a `timeoutMs` (the workflow option, which
219
+ workers announce) that covers it. Create a
220
+ pull app (`kind: "pull"`, with a task queue and its partitions), then run a worker anywhere with
221
+ `fetch` (Node, Bun, Deno):
222
+
223
+ ```ts
224
+ import { worker } from "@ezghcloud/workflows"
225
+
226
+ const w = worker({ apiKey, organizationId, projectId, app: pullAppId, workflows: [resize], queue: "default" })
227
+ process.on("SIGTERM", () => void w.stop())
228
+ await w.run()
229
+ ```
230
+
231
+ - **Polling:** one long poll at a time (held up to 55 s) for up to `maxTasks` tasks (1–10, default
232
+ 4), never more than the free slots of `concurrency` (default 10 invocations at once). Each poll
233
+ announces the worker's workflows, so they show on the app. 429, 5xx and network errors are
234
+ retried with jittered backoff after any `Retry-After` (at most `backoffMaxMs`, default 30 s).
235
+ A refused API key or permission (`WorkerAuthError`) or an unknown app or queue
236
+ (`WorkerConfigError`) stops polling, lets running invocations finish (up to 30 s), then rejects
237
+ `run()`.
238
+ - **Heartbeats:** a running invocation heartbeats every `heartbeatIntervalMs` (default 20 s, at
239
+ most 30 s: EZGH re-dispatches after 60 s without one). A failed heartbeat (a refused token, the
240
+ network) goes to `onError`. When the run is cancelling, each running step's `signal`
241
+ aborts with a `CancelledError` (pass it on), no new step starts, and the invocation ends: the
242
+ next one carries the cancel, so your cleanup (`finally`) runs there.
243
+ - **`stop({ graceMs })`** stops polling at once (a poll still waiting is aborted; one whose answer
244
+ is arriving is run, since its tasks are started), waits up to `graceMs` (default 30 s) for
245
+ running invocations, then cancels their steps (`signal` aborts) and waits at most 5 s more,
246
+ then resolves `run()`; EZGH re-dispatches whatever was abandoned.
247
+ - **Limits:** a worker serves at most 1,000 workflows (checked by `worker()`), and an invocation's
248
+ result is at most 8 MiB of JSON: one bigger (say, many large child inputs at once) fails the run
249
+ with `NonRetriableError` instead of failing to send.
250
+
251
+ The API key needs `workflows.workers.poll` (and `workflows.apps.sync` to announce workflows).
252
+ [Example](examples/worker/worker.ts).
253
+
254
+ ## Dev mode
255
+
256
+ Each developer runs workflows on their own machine, with no tunnel, through a pull app of their
257
+ own: the live host serves only an app's own queue, so dev mode can't borrow the team's app.
258
+ `client.devApp()` creates (or finds) the pull app `dev-<user>` with the queue `dev-<user>` (from
259
+ `$USER`, `$USERNAME` or `$LOGNAME`, or `devApp({ user })`), and `worker({ dev: true })` polls that
260
+ queue:
261
+
262
+ ```ts
263
+ const app = await client.devApp()
264
+ await worker({ apiKey, organizationId, projectId, app: app.id, dev: true, workflows: [resize] }).run()
265
+ await client.start(app.id, "resize", { url }) // runs on this machine
266
+ ```
267
+
268
+ Developers sharing a project never take each other's runs. `devApp` needs `workflows.apps.create`
269
+ (and `workflows.apps.list` to find an existing one).
270
+
271
+ ## The Client
272
+
273
+ `new Client({ apiKey, organizationId, projectId, baseUrl?, retries?, maxRetryDelayMs?, timeoutMs? })`
274
+ calls the Workflows API at `baseUrl`, by default `https://workflows-api.ezghcloud.com`. Each
275
+ request times out after `timeoutMs` (default 30 s). It retries 429, 503, a 409
276
+ `idempotency_in_progress` and network errors after `Retry-After` (default 3 retries, at most 10 s
277
+ apart) with the same `Idempotency-Key` (an `idempotencyKey` you pass is a non-empty string), and
278
+ throws `WorkflowsApiError` with the HTTP `status` and the platform `code`. Redirects are never
279
+ followed: a 3xx is a `WorkflowsApiError` with code `redirect`.
280
+
281
+ | Methods | Credential |
282
+ | --- | --- |
283
+ | `start`, `get`, `cancel`, `retry`, `output`, `input`, `stepOutput`, `events` | an EZGH API key with the `workflows.runs.*` actions it uses, or an EZGH SSO token with the `workflows:runs` scope |
284
+ | `completeCallback` | `workflows.callbacks.complete`, which the `workflows:runs` scope includes |
285
+ | `createApp`, `getApp`, `sync`, `rotateSecret` | an EZGH API key with the `workflows.apps.*` actions it uses |
286
+ | `createSchedule`, `getSchedule`, `listSchedules`, `updateSchedule`, `pauseSchedule`, `resumeSchedule`, `deleteSchedule`, `triggerSchedule` | an EZGH API key with the `workflows.schedules.*` actions it uses (create, update of the workflow, resume and trigger also need `workflows.runs.start` on the workflow) |
287
+
288
+ `createApp` and `rotateSecret` return the signing secret once, and a resend's replay would answer
289
+ `signingSecret: null`. So any answer that leaves the outcome unknown (a network error or timeout,
290
+ a 503, a 409 `idempotency_in_progress`, or a push app's success without a secret) throws
291
+ `WorkflowsApiError` with status 0 and code `outcome_unknown`; only a 429 (not processed) is
292
+ retried. Check the app with `getApp`, and rotate its secret if you didn't receive one.
293
+
294
+ **Pull apps:** `createApp(name, { kind: "pull", queue, partitions })` creates an app for
295
+ [pull workers](#pull-workers); its partitions (1–32, default 4) may grow later but never shrink.
296
+
297
+ **Schedules** start runs of one workflow on a cron expression (5 fields or `@hourly`, `@daily`,
298
+ `@weekly`, `@monthly`, `@yearly`; at most once a minute) in an IANA time zone (default `UTC`):
299
+
300
+ ```ts
301
+ const s = await client.createSchedule({ appId, workflow: "nightly-report", name: "nightly", cron: "0 2 * * *", timeZone: "Europe/Berlin" })
302
+ await client.updateSchedule(s.id, { cron: "30 2 * * *" }, { revision: s.revision }) // 412 if it changed since
303
+ await client.triggerSchedule(s.id, { idempotencyKey: "rerun-2026-10-10" }) // a run now; the key names it
304
+ await client.pauseSchedule(s.id); await client.resumeSchedule(s.id); await client.deleteSchedule(s.id)
305
+ ```
306
+
307
+ Options: `overlap` (`skip`, the default, `allow` or `bufferOne`), `jitterSeconds` (0–3,600),
308
+ `catchupWindowSeconds` (default 3,600, at most 86,400) and `input` (JSON, at most 1 MiB). A run a
309
+ schedule started sees `run.schedule` (`{ id, scheduledTime }`).
310
+
311
+ **Callbacks** can also be completed by an authenticated caller: `completeCallback(runId, stepId,
312
+ value)` answers the run. Without a client, `completeCallbackURL(url, value)` POSTs the value to a
313
+ callback's URL (no credential: the URL's token is one).
314
+
315
+ ## Semantics
316
+
317
+ - **Steps run at least once.** A step can run again if the process dies after it ran but before
318
+ its result was recorded. Inside `step.run`, `step.idempotencyKey()` is
319
+ `<runId>:<stepId>:<attempt>`; pass it to APIs that deduplicate.
320
+ - **Values are JSON.** A step's result is what JSON makes of it, live and on replay alike: a
321
+ `Date` becomes an ISO string, `undefined` becomes `null`, and functions, symbols and bigints
322
+ fail the step without retries. A result over 1 MiB fails the step too.
323
+ - **Code between steps re-runs on every replay**, so keep it deterministic: read the time and
324
+ random values through `step.now(name)` and `step.uuid(name)`.
325
+ - **Step names identify steps.** A name is 1–256 bytes of UTF-8 without NUL, and the *n*th call
326
+ with a name is that name's *n*th step. Two steps pending at the same time (in `Promise.all` or
327
+ `Promise.race`) need distinct names or explicit `{ id }`s. An explicit id names one step for the
328
+ whole run: using it twice fails the run with `workflows.duplicate_step_name`. Replays resolve recorded steps in the order they completed, so races take
329
+ the same branch every time.
330
+ - **Retries:** a step that throws is retried with backoff (default 5 attempts, from 1 s doubling to
331
+ at most 10 minutes; override per step with `{ retry }`, or per workflow; partial policies are
332
+ merged with the defaults). Bounds: `maxAttempts` 1–100, `maxMs` up to 24 hours, `multiplier`
333
+ 1–10. Throw
334
+ `NonRetriableError` to fail at once, or `RetryAfterError(message, delayMs)` to pick the delay (0 to 24 hours),
335
+ directly or as any error's `cause` (an error whose `code` is `workflows.non_retriable` isn't
336
+ retried either).
337
+ On replay a recorded failure is rethrown as a `WorkflowError` (or the SDK class it was), with
338
+ its `code`, `name`, `data` and `cause`. Error codes on the wire are `user` or `workflows.*`: a
339
+ `WorkflowError` with another code is sent as `user`, its code kept as the name and in
340
+ `data.code`. Messages and stacks are cut to 8 KiB, and `data` over 64 KiB is dropped.
341
+ - **Timeouts:** with `{ timeoutMs }` (at most 24 hours; a step can't outlive its invocation, so
342
+ `serve()` refuses a workflow default longer than `maxInvocationSeconds`, and long steps need a
343
+ pull worker) a step
344
+ that runs too long fails with
345
+ `workflows.step_timeout` (retryable). The step function gets `{ signal, attempt,
346
+ idempotencyKey }`; `signal` aborts at the timeout, so pass it to `fetch`.
347
+ - **Invocation time:** an invocation stops starting steps when less than max(5 s, 10 %) of its
348
+ time is left, and EZGH invokes the workflow again. The deadline is measured on your machine's
349
+ clock from when the request arrived, so clock skew doesn't matter. Calls to EZGH that are
350
+ rate-limited or briefly unavailable are retried within that time. When EZGH can't store a step's
351
+ output (its payload store is down), the invocation is retried later without using a step
352
+ attempt.
353
+ - **Cancellation:** cancelling a run throws `CancelledError` from the call the workflow is
354
+ waiting on. `finally` and `catch` blocks can still run `step.run` cleanup steps; sleeps and
355
+ new values are refused. The run then ends `cancelled`.
356
+
357
+ The package has no runtime dependencies: it uses Web Crypto and `fetch` only. It's ESM only; in
358
+ TypeScript use `moduleResolution` `bundler`, `node16` or `nodenext` (TypeScript 5.4 or later).
359
+ `@ezghcloud/workflows/protocol` exports `sign`, `verify`, `decodeSecret`, `SignatureError` and the wire
360
+ types, for checking `EZGH-Signature` headers in a custom transport.
361
+
362
+ ## Development
363
+
364
+ ```sh
365
+ bun install
366
+ bun run check # typecheck, tests, build, a Node import smoke test, npm pack --dry-run
367
+ ```
368
+
369
+ `conformance/workflows.ts` holds the conformance workflows every EZGH Workflows SDK implements
370
+ (workflows-stack `protocol/conformance/workflows.md`), served by `conformance/app.ts` (push) and
371
+ `conformance/worker.ts` (a pull worker). `scripts/conformance.sh <workflows-stack checkout>`
372
+ builds workflows-stack's harness and runs its push and pull scenarios against them; CI does the same
373
+ at `.workflows-stack-rev` (it reads the internal workflows-stack repo with the
374
+ `WORKFLOWS_STACK_DEPLOY_KEY` secret, a read-only deploy key on workflows-stack, and skips with a notice without it).
375
+
376
+ `scripts/e2e.sh <workflows-stack checkout>` runs the SDK end to end against the real
377
+ workflows-stack (`workflows-stack all` on Postgres and an S3 fixture, with a fake org-api):
378
+ completion, idempotent start, sleep and payload replay, step retries, a process killed mid-step,
379
+ cancel with cleanup, retry from failure, exact JSON replay (key order and NUL characters), and
380
+ phase 2: a callback completed over its public URL (repeat and conflicting completions), a parent
381
+ and its child under the derived child run ID, a five-step parallel fan-out, a pull worker
382
+ (`e2e/worker.ts`) announcing and running a pull app's workflow, and a schedule firing a run
383
+ under its derived scheduled run ID, then trigger (idempotent by key), pause and delete. The CI
384
+ job `e2e` runs it with the same secret rule. Against a slow shared database, set
385
+ `E2E_TIME_SCALE` (for example `3`) to stretch every wait; no check changes.
386
+
387
+ Verified end to end against workflows-stack f717543: the CI job e2e ran the full suite, and
388
+ conformance passed all 61 scenarios (protocol 1.2's message waits included), push and pull.
389
+
390
+ `test/vectors` is a verbatim copy of workflows-stack's `protocol/vectors` at the commit in
391
+ `.workflows-stack-rev`; refresh it with `scripts/sync-vectors.sh <workflows-stack checkout> [<commit>]`.
392
+
393
+ ## Releasing
394
+
395
+ Releases are published to npm by `.github/workflows/release.yml` with npm trusted publishing
396
+ (GitHub Actions OIDC; there is no npm token, and npm adds provenance automatically).
397
+
398
+ 1. Bump `version` in `package.json` and `SDK_VERSION` in `src/version.ts` to the same `X.Y.Z` (a
399
+ unit test fails when they differ), and commit on main.
400
+ 2. Push the tag: `git tag -a vX.Y.Z -m vX.Y.Z && git push origin vX.Y.Z`.
401
+
402
+ On the tag, the workflow checks that the tag equals the `package.json` version, runs the same checks
403
+ as CI's `check` job (typecheck, tests, build, Node smoke test, consumer types on TypeScript 5.4 and
404
+ 5.6), packs the tarball, publishes it to npm as `@ezghcloud/workflows` (skipped when that version is
405
+ already on npm, so a re-run is safe) and creates the GitHub release with the tarball attached.
406
+
407
+ First-time owner setup, once, logged in to npm with 2FA (npm 11.15 or later):
408
+ `scripts/npm-trust.sh @ezghcloud/workflows`. npm can only trust an existing package, so it publishes
409
+ a deprecated `0.0.0` placeholder first, then trusts `release.yml` in this repository to publish and
410
+ requires 2FA for manual publishes.
411
+
412
+ Tags `v0.1.0` to `v0.3.0` predate npm publishing: they were installed from GitHub
413
+ (`npm i github:ezgamehost/workflows-sdk-ts#v0.3.0`, built on install by a `prepare` script, as
414
+ `@ezgh/workflows`). The first npm release is a later version.
415
+
416
+ ## License
417
+
418
+ Apache-2.0