The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type * as runtime from "@cloudflare/workers-types"; |
| 2 | import * as workflows from "@distilled.cloud/cloudflare/workflows"; |
| 3 | import { OwnedBySomeoneElse, Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { havePropsChanged, isResolved } from "alchemy/Diff"; |
| 5 | import type { Input } from "alchemy/Input"; |
| 6 | import * as ProviderLayer from "alchemy/Local/ProviderLayer"; |
| 7 | import type * as Output from "alchemy/Output"; |
| 8 | import { ALCHEMY_PHASE } from "alchemy/Phase"; |
| 9 | import type { PlatformServices } from "alchemy/Platform"; |
| 10 | import * as Provider from "alchemy/Provider"; |
| 11 | import { Resource } from "alchemy/Resource"; |
| 12 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 13 | import { effectClass, taggedFunction } from "alchemy/Util/effect"; |
| 14 | import type { ConfigError } from "effect/Config"; |
| 15 | import * as Context from "effect/Context"; |
| 16 | import * as Data from "effect/Data"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import { Scope } from "effect/Scope"; |
| 19 | import * as Stream from "effect/Stream"; |
| 20 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 21 | import { localAccountId } from "../LocalAccount.ts"; |
| 22 | import { generateLocalId } from "../LocalRuntime.ts"; |
| 23 | import { Worker, WorkerEnvironment, type WorkerServices } from "../Workers/Worker.ts"; |
| 24 | import { generateWorkflowName } from "./WorkflowName.ts"; |
| 25 | import { type WorkflowEvent, WorkflowStep, WorkflowStepContext } from "./WorkflowRuntime.ts"; |
| 26 | |
| 27 | export class WorkflowInvalidProps extends Data.TaggedError("WorkflowInvalidProps")<{ |
| 28 | readonly message: string; |
| 29 | readonly cause?: unknown; |
| 30 | }> {} |
| 31 | |
| 32 | export { WorkflowEvent, WorkflowStep, WorkflowStepContext } from "./WorkflowRuntime.ts"; |
| 33 | |
| 34 | type TypeId = "Cloudflare.Workflow"; |
| 35 | const TypeId = "Cloudflare.Workflow" as const; |
| 36 | |
| 37 | /** |
| 38 | * Cron trigger metadata on a Workflow instance created by a native |
| 39 | * `schedules` expression. Mirrors Cloudflare's `event.schedule`. |
| 40 | */ |
| 41 | export interface WorkflowCronSchedule { |
| 42 | /** |
| 43 | * The matching cron expression that created this instance. |
| 44 | */ |
| 45 | cron: string; |
| 46 | /** |
| 47 | * The scheduled fire time, milliseconds since the Unix epoch. |
| 48 | */ |
| 49 | scheduledTime: number; |
| 50 | } |
| 51 | |
| 52 | export type WorkflowBackoff = "constant" | "linear" | "exponential"; |
| 53 | |
| 54 | export interface WorkflowStepConfig { |
| 55 | retries?: { |
| 56 | limit: number; |
| 57 | delay: string | number; |
| 58 | backoff?: WorkflowBackoff; |
| 59 | }; |
| 60 | timeout?: string | number; |
| 61 | } |
| 62 | |
| 63 | export interface WorkflowStepContextData { |
| 64 | step: { |
| 65 | name: string; |
| 66 | count: number; |
| 67 | }; |
| 68 | attempt: number; |
| 69 | config: WorkflowStepConfig; |
| 70 | } |
| 71 | |
| 72 | export interface WorkflowRollbackContext<Output = unknown> { |
| 73 | error: Error; |
| 74 | output: Output | undefined; |
| 75 | } |
| 76 | |
| 77 | export interface WorkflowRollbackOptions<Output = unknown, R = never> { |
| 78 | rollback: (context: WorkflowRollbackContext<Output>) => Effect.Effect<void, unknown, R>; |
| 79 | rollbackConfig?: WorkflowStepConfig; |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Optional configuration for a `task` step: retry policy, timeout, and a |
| 84 | * rollback handler with its own retry config. |
| 85 | */ |
| 86 | export interface WorkflowTaskConfig< |
| 87 | Output = unknown, |
| 88 | RollbackReq = never, |
| 89 | > extends WorkflowStepConfig { |
| 90 | rollback?: ( |
| 91 | context: WorkflowRollbackContext<Output>, |
| 92 | ) => Effect.Effect<void, unknown, RollbackReq>; |
| 93 | rollbackConfig?: WorkflowStepConfig; |
| 94 | } |
| 95 | |
| 96 | /** |
| 97 | * Internal step descriptor passed from `task` to the bridge. Bundles the step |
| 98 | * name and Effect together with the `WorkflowTaskConfig` fields. |
| 99 | */ |
| 100 | export interface WorkflowTaskOptions< |
| 101 | Output = unknown, |
| 102 | R = never, |
| 103 | RollbackReq = never, |
| 104 | E = never, |
| 105 | > extends WorkflowTaskConfig<Output, RollbackReq> { |
| 106 | name: string; |
| 107 | effect: Effect.Effect<Output, E, R>; |
| 108 | } |
| 109 | |
| 110 | export interface WorkflowWaitForEventOptions { |
| 111 | type: string; |
| 112 | timeout?: string | number; |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * The event delivered to a `waitForEvent` step. Mirrors the native |
| 117 | * `WorkflowStepEvent` shape from `cloudflare:workers` 1:1. |
| 118 | */ |
| 119 | export interface WorkflowStepEvent<Payload = unknown> { |
| 120 | payload: Payload; |
| 121 | timestamp: Date; |
| 122 | type: string; |
| 123 | } |
| 124 | |
| 125 | type ExcludeWorkflowStepContext<R> = R extends { |
| 126 | readonly key: "Cloudflare.WorkflowStepContext"; |
| 127 | } |
| 128 | ? never |
| 129 | : R; |
| 130 | |
| 131 | // --------------------------------------------------------------------------- |
| 132 | // User-facing step primitives |
| 133 | // --------------------------------------------------------------------------- |
| 134 | |
| 135 | /** |
| 136 | * Execute a named, durable workflow step. The effect is run inside the |
| 137 | * Cloudflare step transaction so its result is automatically persisted |
| 138 | * and replayed on retries. |
| 139 | * |
| 140 | * Any services the inner effect requires (e.g. `WorkerEnvironment` from a |
| 141 | * binding like `kv.put` / `kv.get`) are threaded through automatically by |
| 142 | * capturing the surrounding workflow body's context and providing it to |
| 143 | * the inner effect before it runs inside `step.do`. |
| 144 | * |
| 145 | * The step name comes first, followed by the Effect. Retry config, timeout, |
| 146 | * and a rollback handler can be passed in the optional third `options` arg. |
| 147 | * Each attempt and rollback handler has a fresh Scope; its resources close |
| 148 | * before that callback completes. Interrupting a task waits for the active |
| 149 | * attempt's cleanup without waiting for Cloudflare's native retry delays. |
| 150 | * |
| 151 | * `Effect.fail` uses the native retry policy. On exhaustion, application failure |
| 152 | * data is returned in the error channel, including on cached rejection replay. |
| 153 | * The active invocation retains its original Cause; replay restores serialized |
| 154 | * tags and fields, not custom prototypes, methods, or object identity. |
| 155 | * Failure data supports primitives, dense arrays, records, errors, Date, bigint, |
| 156 | * Uint8Array, ArrayBuffer, Map, and Set, within a 16 KiB encoded / 64-level limit. |
| 157 | * Functions, symbols, cycles, shared object references, accessors, and unsupported |
| 158 | * class instances fail explicitly as terminal serialization defects. Error data |
| 159 | * must form a tree, including objects used as Map keys or Set members. |
| 160 | * `Effect.die` and `Effect.orDie` |
| 161 | * stop retries. Native timeout, validation, pause, and abort errors stay defects. |
| 162 | */ |
| 163 | export function task<T, R = never, RollbackReq = never, E = never>( |
| 164 | name: string, |
| 165 | effect: Effect.Effect<T, E, R>, |
| 166 | options?: WorkflowTaskConfig<T, RollbackReq>, |
| 167 | ): Effect.Effect<T, E, WorkflowStep | ExcludeWorkflowStepContext<Exclude<R | RollbackReq, Scope>>> { |
| 168 | return Effect.gen(function* () { |
| 169 | const step = yield* WorkflowStep; |
| 170 | const context = (yield* Effect.context< |
| 171 | ExcludeWorkflowStepContext<Exclude<R | RollbackReq, Scope>> |
| 172 | >()).pipe(Context.omit(Scope, WorkflowStepContext)); |
| 173 | const rollbackEffect = options?.rollback; |
| 174 | return yield* step.do({ |
| 175 | ...options, |
| 176 | name, |
| 177 | effect: effect.pipe(Effect.provide(context)), |
| 178 | rollback: rollbackEffect |
| 179 | ? (rollbackContext: WorkflowRollbackContext<T>) => |
| 180 | rollbackEffect(rollbackContext).pipe(Effect.provide(context)) |
| 181 | : undefined, |
| 182 | } as WorkflowTaskOptions<T, any, any, E>); |
| 183 | }); |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Pause the workflow for the given duration. |
| 188 | */ |
| 189 | export const sleep = ( |
| 190 | name: string, |
| 191 | duration: string | number, |
| 192 | ): Effect.Effect<void, never, WorkflowStep> => |
| 193 | Effect.gen(function* () { |
| 194 | const step = yield* WorkflowStep; |
| 195 | yield* step.sleep(name, duration); |
| 196 | }).pipe(Effect.orDie); |
| 197 | |
| 198 | /** |
| 199 | * Pause the workflow until the given timestamp. |
| 200 | */ |
| 201 | export const sleepUntil = ( |
| 202 | name: string, |
| 203 | timestamp: Date | number, |
| 204 | ): Effect.Effect<void, never, WorkflowStep> => |
| 205 | Effect.gen(function* () { |
| 206 | const step = yield* WorkflowStep; |
| 207 | yield* step.sleepUntil(name, timestamp); |
| 208 | }).pipe(Effect.orDie); |
| 209 | |
| 210 | /** |
| 211 | * Pause the workflow until an external event is delivered with |
| 212 | * `WorkflowInstance.sendEvent`. Resolves with the full |
| 213 | * {@link WorkflowStepEvent} (`{ payload, timestamp, type }`), exactly like |
| 214 | * the native `step.waitForEvent`. |
| 215 | */ |
| 216 | export const waitForEvent = <T = unknown>( |
| 217 | name: string, |
| 218 | options: WorkflowWaitForEventOptions, |
| 219 | ): Effect.Effect<WorkflowStepEvent<T>, never, WorkflowStep> => |
| 220 | Effect.gen(function* () { |
| 221 | const step = yield* WorkflowStep; |
| 222 | return yield* step.waitForEvent<T>(name, options); |
| 223 | }).pipe(Effect.orDie); |
| 224 | |
| 225 | /** |
| 226 | * The services available inside a workflow run body. |
| 227 | * |
| 228 | * `WorkerEnvironment` is provided to the body at runtime by the workflow |
| 229 | * export wrapper (see `make(env)` below), so users can access env bindings |
| 230 | * from inside workflow steps via `yield* WorkerEnvironment` — the type must |
| 231 | * reflect that or `yield* WorkerEnvironment` fails to type-check inside a |
| 232 | * body even though it succeeds at runtime. |
| 233 | * |
| 234 | * A fresh `Scope` is provided per run-invocation by `WorkflowBridge.run` and |
| 235 | * threaded into every `task` via the surrounding body context, so `@binding` |
| 236 | * helpers that acquire per-run resources against the ambient scope (e.g. |
| 237 | * `Drizzle.Postgres`) resolve them inside workflow steps just as they do in |
| 238 | * a Worker `fetch`/`queue` handler. |
| 239 | */ |
| 240 | export type WorkflowRunServices = WorkflowEvent | WorkflowStep | WorkerServices | Scope; |
| 241 | |
| 242 | export type WorkflowServices = WorkflowRunServices | PlatformServices | RuntimeContext; |
| 243 | |
| 244 | /** |
| 245 | * Metadata stored in the worker export map to distinguish workflow exports |
| 246 | * from durable object exports at bundle-generation time. |
| 247 | */ |
| 248 | export interface WorkflowExport { |
| 249 | readonly kind: "workflow"; |
| 250 | readonly make: (env: unknown) => Effect.Effect<WorkflowImpl<any, any, unknown>>; |
| 251 | } |
| 252 | |
| 253 | /** |
| 254 | * A workflow implementation is a function from a typed `Input` payload to |
| 255 | * an Effect that produces the workflow's `Result`. The Effect requires |
| 256 | * `WorkflowRunServices` (event + step + env) to execute. |
| 257 | */ |
| 258 | export type WorkflowImpl<Input = unknown, Result = unknown, E = never> = ( |
| 259 | input: Input, |
| 260 | ) => Effect.Effect<Result, E, WorkflowServices>; |
| 261 | |
| 262 | export const isWorkflowExport = (value: unknown): value is WorkflowExport => |
| 263 | typeof value === "object" && |
| 264 | value !== null && |
| 265 | "kind" in value && |
| 266 | (value as any).kind === "workflow"; |
| 267 | |
| 268 | /** |
| 269 | * Limits applied to the workflow on create or update. |
| 270 | */ |
| 271 | export interface WorkflowLimits { |
| 272 | /** |
| 273 | * Maximum number of steps a single workflow instance may execute. |
| 274 | */ |
| 275 | steps?: number; |
| 276 | } |
| 277 | |
| 278 | /** |
| 279 | * Jurisdiction where a Workflow's instances run and store data: |
| 280 | * `"eu"` (the European Union), `"us"` (the United States), or `"fedramp"` |
| 281 | * (FedRAMP-Moderate data centers). |
| 282 | */ |
| 283 | export type WorkflowJurisdiction = workflows.WorkflowJurisdiction; |
| 284 | |
| 285 | /** |
| 286 | * Props for the reference (async) form of {@link Workflow}. Used when binding |
| 287 | * a Workflow class to a plain async Worker (one without an Effect runtime) via |
| 288 | * the Worker's `env`. Mirrors `DurableObjectProps`. |
| 289 | */ |
| 290 | export interface WorkflowRefProps { |
| 291 | /** |
| 292 | * Account-global Workflow name. Adopting an existing Workflow requires |
| 293 | * `--adopt`; unused names do not. If omitted, Alchemy preserves the deployed |
| 294 | * name or derives a stage-scoped default from the hosting Worker and class. |
| 295 | * Changing this name replaces the Workflow. Fixed names must be unique to |
| 296 | * each independently managed stack and stage. |
| 297 | */ |
| 298 | workflowName?: string; |
| 299 | /** |
| 300 | * Name of the exported `WorkflowEntrypoint` class. |
| 301 | * |
| 302 | * @default name |
| 303 | */ |
| 304 | className?: string; |
| 305 | /** |
| 306 | * Worker script that hosts the Workflow class. Omit this when the workflow |
| 307 | * is hosted by the Worker that declares the binding. |
| 308 | */ |
| 309 | scriptName?: Input<string>; |
| 310 | /** |
| 311 | * Limits applied to the workflow. Only applies when the workflow is hosted by |
| 312 | * the Worker that declares the binding; ignored when `scriptName` is set. |
| 313 | */ |
| 314 | limits?: WorkflowLimits; |
| 315 | /** |
| 316 | * Cron expressions that create a new Workflow instance on each match. |
| 317 | * Wrangler-compatible: `schedules: ["0 * * * *"]`. |
| 318 | * |
| 319 | * Native Workflow schedules replace a Worker Cron Trigger whose |
| 320 | * `scheduled` handler called `workflow.create()`. Pass an empty |
| 321 | * array to remove all schedules. |
| 322 | * |
| 323 | * Only applies when the workflow is hosted by the Worker that declares |
| 324 | * the binding; ignored when `scriptName` is set. |
| 325 | * |
| 326 | * Account-wide limit: 100 cron expressions. |
| 327 | */ |
| 328 | schedules?: string[]; |
| 329 | /** |
| 330 | * Restrict where the Workflow's instances run and store data, e.g. for |
| 331 | * GDPR or FedRAMP. Workers anywhere can still create and manage instances. |
| 332 | * |
| 333 | * Cloudflare sets the jurisdiction when it creates the Workflow and can't |
| 334 | * change it, so changing or removing it replaces the Workflow and deletes |
| 335 | * its instances. Ignored when `scriptName` is set; set it on the Worker |
| 336 | * that hosts the Workflow. Local development ignores it. |
| 337 | */ |
| 338 | jurisdiction?: WorkflowJurisdiction; |
| 339 | } |
| 340 | |
| 341 | /** |
| 342 | * Props for the Effect-native form of {@link Workflow} |
| 343 | * (`Workflow(name, props, impl)`). Used when the workflow's implementation is |
| 344 | * defined inline by the hosting Worker. |
| 345 | */ |
| 346 | export interface WorkflowProps { |
| 347 | /** |
| 348 | * Account-global Workflow name. Adopting an existing Workflow requires |
| 349 | * `--adopt`; unused names do not. If omitted, Alchemy preserves the deployed |
| 350 | * name or derives a stage-scoped default from the hosting Worker and class. |
| 351 | * Changing this name replaces the Workflow. Fixed names must be unique to |
| 352 | * each independently managed stack and stage. |
| 353 | */ |
| 354 | workflowName?: string; |
| 355 | /** |
| 356 | * Limits applied to the workflow. |
| 357 | */ |
| 358 | limits?: WorkflowLimits; |
| 359 | /** |
| 360 | * Cron expressions that create a new Workflow instance on each match. |
| 361 | * Wrangler-compatible: `schedules: ["0 * * * *"]`. |
| 362 | * |
| 363 | * Native Workflow schedules replace a Worker Cron Trigger whose |
| 364 | * `scheduled` handler called `workflow.create()`. Pass an empty |
| 365 | * array to remove all schedules. |
| 366 | * |
| 367 | * Account-wide limit: 100 cron expressions. |
| 368 | */ |
| 369 | schedules?: string[]; |
| 370 | /** |
| 371 | * Restrict where the Workflow's instances run and store data, e.g. for |
| 372 | * GDPR or FedRAMP. Workers anywhere can still create and manage instances. |
| 373 | * |
| 374 | * Cloudflare sets the jurisdiction when it creates the Workflow and can't |
| 375 | * change it, so changing or removing it replaces the Workflow and deletes |
| 376 | * its instances. Local development ignores it. |
| 377 | */ |
| 378 | jurisdiction?: WorkflowJurisdiction; |
| 379 | } |
| 380 | |
| 381 | /** |
| 382 | * A lightweight reference to a Workflow, produced by the props-only form of |
| 383 | * {@link Workflow} (`Workflow(name, { className })`). Carries just enough |
| 384 | * metadata to emit the `workflow` binding for an async Worker and to drive |
| 385 | * the `putWorkflow` lifecycle. Mirrors `DurableObjectLike`. |
| 386 | */ |
| 387 | export interface WorkflowLike<Params = unknown> { |
| 388 | kind: TypeId; |
| 389 | name: string; |
| 390 | /** Account-global Workflow name, when explicitly configured. */ |
| 391 | workflowName?: string; |
| 392 | /** @internal phantom */ |
| 393 | className?: string; |
| 394 | /** @internal phantom */ |
| 395 | scriptName?: Input<string>; |
| 396 | /** @internal phantom */ |
| 397 | limits?: WorkflowLimits; |
| 398 | /** @internal phantom */ |
| 399 | schedules?: string[]; |
| 400 | /** @internal phantom */ |
| 401 | jurisdiction?: WorkflowJurisdiction; |
| 402 | /** @internal phantom */ |
| 403 | Params?: Params; |
| 404 | } |
| 405 | |
| 406 | /** |
| 407 | * A Workflow bound on an external/async Worker's `env`, exposed on |
| 408 | * `worker.env.<name>` at declaration time, not on persisted Worker references |
| 409 | * or Effect-native Workers. Carries the binding's identity as `Output`s |
| 410 | * of the current deploy pass, so a sibling resource in the same stack — a |
| 411 | * Queue subscription to the Workflow's lifecycle events, for instance — can |
| 412 | * consume the Workflow's physical name on its very first deployment without |
| 413 | * reading persisted state or re-deriving the name. |
| 414 | * |
| 415 | * For a locally-hosted Workflow, `workflowName` and `scriptName` resolve from |
| 416 | * the {@link WorkflowResource} the binding registers, so a consumer deploys |
| 417 | * after `putWorkflow` has run. A cross-script reference (`scriptName` set) |
| 418 | * registers no resource; both outputs derive from the declared host script. |
| 419 | */ |
| 420 | export interface WorkflowBinding<Params = unknown> { |
| 421 | kind: TypeId; |
| 422 | /** Logical name of the Workflow, as passed to `Workflow(name, …)`. */ |
| 423 | name: string; |
| 424 | /** Name of the exported `WorkflowEntrypoint` class. */ |
| 425 | className: string; |
| 426 | /** Account-global physical Workflow name, resolved in the current deploy. */ |
| 427 | workflowName: Output.Output<string>; |
| 428 | /** Script name of the Worker hosting the Workflow class. */ |
| 429 | scriptName: Output.Output<string>; |
| 430 | /** @internal phantom */ |
| 431 | Params?: Params; |
| 432 | } |
| 433 | |
| 434 | /** |
| 435 | * Type guard for the reference (async) form of a Workflow. |
| 436 | */ |
| 437 | export const isWorkflowLike = (value: unknown): value is WorkflowLike => |
| 438 | typeof value === "object" && value !== null && (value as { kind?: unknown }).kind === TypeId; |
| 439 | |
| 440 | /** |
| 441 | * Type guard for workflow binding metadata in the Worker binding contract. |
| 442 | */ |
| 443 | export const isWorkflowBinding = (binding: { |
| 444 | type: string; |
| 445 | }): binding is { |
| 446 | type: "workflow"; |
| 447 | name: string; |
| 448 | workflowName: string; |
| 449 | className: string; |
| 450 | scriptName?: string; |
| 451 | } => binding.type === "workflow"; |
| 452 | |
| 453 | export type WorkflowBatchDeleteResult = runtime.WorkflowBatchDeleteResult; |
| 454 | export type WorkflowSubscriptionEvent = runtime.WorkflowInstanceEvent; |
| 455 | export type WorkflowInstanceSubscribeOptions = runtime.WorkflowInstanceSubscribeOptions; |
| 456 | |
| 457 | /** |
| 458 | * Handle returned to the caller at deploy/bind time. Allows starting |
| 459 | * workflow instances and checking their status from the Api layer. |
| 460 | */ |
| 461 | export interface WorkflowHandle<Input = unknown, Result = unknown> { |
| 462 | Type: TypeId; |
| 463 | name: string; |
| 464 | /** Account-global physical Workflow name, for a resource that starts runs through the API. */ |
| 465 | workflowName: Output.Output<string> | string; |
| 466 | /** |
| 467 | * Start a workflow instance. Pass payload through `params`; omit `id` to let |
| 468 | * Cloudflare generate an instance ID. |
| 469 | */ |
| 470 | create(options?: WorkflowInstanceCreateOptions<Input>): Effect.Effect<WorkflowInstance<Result>>; |
| 471 | createBatch( |
| 472 | batch: WorkflowInstanceCreateOptions<Input>[], |
| 473 | ): Effect.Effect<WorkflowInstance<Result>[]>; |
| 474 | get(instanceId: string): Effect.Effect<WorkflowInstance<Result>>; |
| 475 | /** Delete up to 100 instances and their stored state, returning per-instance results. */ |
| 476 | deleteBatch(instanceIds: string[]): Effect.Effect<WorkflowBatchDeleteResult>; |
| 477 | } |
| 478 | |
| 479 | /** Options for starting a workflow instance. */ |
| 480 | export interface WorkflowInstanceCreateOptions<Input = unknown> { |
| 481 | id?: string; |
| 482 | params?: Input; |
| 483 | retention?: WorkflowInstanceRetention; |
| 484 | } |
| 485 | |
| 486 | export interface WorkflowInstanceRetention { |
| 487 | successRetention?: string | number; |
| 488 | errorRetention?: string | number; |
| 489 | } |
| 490 | |
| 491 | /** Handle for a single Cloudflare workflow instance. */ |
| 492 | export interface WorkflowInstance<Result = unknown> { |
| 493 | id: string; |
| 494 | status(): Effect.Effect<WorkflowInstanceStatus<Result>>; |
| 495 | pause(): Effect.Effect<void>; |
| 496 | resume(): Effect.Effect<void>; |
| 497 | restart(options?: WorkflowInstanceRestartOptions): Effect.Effect<void>; |
| 498 | terminate(): Effect.Effect<void>; |
| 499 | /** Stop execution and delete this instance and its stored state. */ |
| 500 | delete(): Effect.Effect<void>; |
| 501 | /** Stream historical and new events; release the subscription when consumption ends. */ |
| 502 | subscribe(options?: WorkflowInstanceSubscribeOptions): Stream.Stream<WorkflowSubscriptionEvent>; |
| 503 | sendEvent<Event = unknown>(event: WorkflowInstanceEvent<Event>): Effect.Effect<void>; |
| 504 | } |
| 505 | |
| 506 | export interface WorkflowInstanceRestartOptions { |
| 507 | from?: { |
| 508 | name: string; |
| 509 | count?: number; |
| 510 | type?: "do" | "sleep" | "waitForEvent"; |
| 511 | }; |
| 512 | } |
| 513 | |
| 514 | export interface WorkflowInstanceEvent<Payload = unknown> { |
| 515 | type: string; |
| 516 | payload?: Payload; |
| 517 | } |
| 518 | |
| 519 | export interface WorkflowInstanceStatus<Result = unknown> { |
| 520 | status: |
| 521 | | "queued" |
| 522 | | "running" |
| 523 | | "paused" |
| 524 | | "errored" |
| 525 | | "terminated" |
| 526 | | "complete" |
| 527 | | "waiting" |
| 528 | | "waitingForPause" |
| 529 | | "unknown" |
| 530 | | (string & {}); |
| 531 | output?: Result; |
| 532 | error?: { name: string; message: string } | null; |
| 533 | rollback?: { |
| 534 | outcome: "complete" | "failed"; |
| 535 | error: { name: string; message: string } | null; |
| 536 | } | null; |
| 537 | } |
| 538 | |
| 539 | export interface WorkflowClass extends Effect.Effect<WorkflowHandle, never, WorkflowHandle> { |
| 540 | /** Reference a deployed Workflow by logical ID, optionally in another stack or stage. */ |
| 541 | ref: typeof WorkflowResource.ref; |
| 542 | <_Self>(): { |
| 543 | <Input = unknown, Result = unknown, InitReq = never, E = never>( |
| 544 | name: string, |
| 545 | impl: Effect.Effect<WorkflowImpl<Input, Result, E>, ConfigError, InitReq>, |
| 546 | ): Effect.Effect< |
| 547 | WorkflowHandle<Input, Result>, |
| 548 | never, |
| 549 | Worker | Exclude<InitReq, WorkflowServices> |
| 550 | > & { |
| 551 | new (_: never): WorkflowImpl<Input, Result, E>; |
| 552 | }; |
| 553 | <Input = unknown, Result = unknown, InitReq = never, E = never>( |
| 554 | name: string, |
| 555 | props: WorkflowProps, |
| 556 | impl: Effect.Effect<WorkflowImpl<Input, Result, E>, ConfigError, InitReq>, |
| 557 | ): Effect.Effect< |
| 558 | WorkflowHandle<Input, Result>, |
| 559 | never, |
| 560 | Worker | Exclude<InitReq, WorkflowServices> |
| 561 | > & { |
| 562 | new (_: never): WorkflowImpl<Input, Result, E>; |
| 563 | }; |
| 564 | }; |
| 565 | <Params = unknown>(name: string, props?: WorkflowRefProps): WorkflowLike<Params>; |
| 566 | <Input = unknown, Result = unknown, InitReq = never, E = never>( |
| 567 | name: string, |
| 568 | impl: Effect.Effect<WorkflowImpl<Input, Result, E>, ConfigError, InitReq>, |
| 569 | ): Effect.Effect< |
| 570 | WorkflowHandle<Input, Result>, |
| 571 | never, |
| 572 | Worker | Exclude<InitReq, WorkflowServices> |
| 573 | >; |
| 574 | <Input = unknown, Result = unknown, InitReq = never, E = never>( |
| 575 | name: string, |
| 576 | props: WorkflowProps, |
| 577 | impl: Effect.Effect<WorkflowImpl<Input, Result, E>, ConfigError, InitReq>, |
| 578 | ): Effect.Effect< |
| 579 | WorkflowHandle<Input, Result>, |
| 580 | never, |
| 581 | Worker | Exclude<InitReq, WorkflowServices> |
| 582 | >; |
| 583 | } |
| 584 | |
| 585 | export class WorkflowScope extends Context.Service<WorkflowScope, WorkflowHandle>()( |
| 586 | "Cloudflare.Workflow", |
| 587 | ) {} |
| 588 | |
| 589 | /** |
| 590 | * A Cloudflare Workflow that orchestrates durable, multi-step tasks with |
| 591 | * automatic retries and at-least-once delivery. |
| 592 | * |
| 593 | * A Workflow follows the same two-phase pattern as Workers and Durable |
| 594 | * Objects. The outer `Effect.gen` resolves shared dependencies. The inner |
| 595 | * `Effect.fn` is the workflow body — a function from a typed `input` |
| 596 | * payload to an Effect that runs steps using `task`, `sleep`, and |
| 597 | * `sleepUntil`. `task` takes the step name and Effect, plus an optional |
| 598 | * config object for retries, timeout, and a rollback handler. |
| 599 | * |
| 600 | * ```typescript |
| 601 | * Effect.gen(function* () { |
| 602 | * // Phase 1: resolve dependencies |
| 603 | * const notifier = yield* NotificationService; |
| 604 | * |
| 605 | * return Effect.fn(function* (input: { orderId: string }) { |
| 606 | * // Phase 2: workflow body (durable steps) |
| 607 | * const result = yield* Cloudflare.Workflows.task("process", doWork(input.orderId)); |
| 608 | * yield* Cloudflare.Workflows.sleep("cooldown", "10 seconds"); |
| 609 | * return result; |
| 610 | * }); |
| 611 | * }) |
| 612 | * ``` |
| 613 | * |
| 614 | * |
| 615 | * ### Defining a Workflow |
| 616 | * **Example:** Minimal workflow |
| 617 | * ```typescript |
| 618 | * export default class MyWorkflow extends Cloudflare.Workflow<MyWorkflow>()( |
| 619 | * "MyWorkflow", |
| 620 | * Effect.gen(function* () { |
| 621 | * return Effect.fn(function* (input: { name: string }) { |
| 622 | * return { received: input.name }; |
| 623 | * }); |
| 624 | * }), |
| 625 | * ) {} |
| 626 | * ``` |
| 627 | * |
| 628 | * **Example:** Preserving an existing Workflow name |
| 629 | * |
| 630 | * An existing Workflow has no ownership marker, so the first deployment must |
| 631 | * opt in with `--adopt`. Keep fixed names unique per independently managed |
| 632 | * stack and stage; unlike the default, they are not stage-scoped by Alchemy. |
| 633 | * |
| 634 | * ```typescript |
| 635 | * export default class MyWorkflow extends Cloudflare.Workflow<MyWorkflow>()( |
| 636 | * "MyWorkflow", |
| 637 | * { workflowName: "my-existing-workflow" }, |
| 638 | * Effect.gen(function* () { |
| 639 | * return Effect.fn(function* (input: { name: string }) { |
| 640 | * return { received: input.name }; |
| 641 | * }); |
| 642 | * }), |
| 643 | * ) {} |
| 644 | * ``` |
| 645 | * |
| 646 | * **Example:** Setting a step limit |
| 647 | * ```typescript |
| 648 | * export default class MyWorkflow extends Cloudflare.Workflow<MyWorkflow>()( |
| 649 | * "MyWorkflow", |
| 650 | * { limits: { steps: 25000 } }, |
| 651 | * Effect.gen(function* () { |
| 652 | * return Effect.fn(function* (input: { name: string }) { |
| 653 | * return { received: input.name }; |
| 654 | * }); |
| 655 | * }), |
| 656 | * ) {} |
| 657 | * ``` |
| 658 | * |
| 659 | * ### Scheduling instances |
| 660 | * Each matching cron expression creates a new instance automatically — |
| 661 | * no Worker Cron Trigger or `scheduled` handler required. |
| 662 | * **Example:** Native cron schedules |
| 663 | * ```typescript |
| 664 | * export default class HourlyWorkflow extends Cloudflare.Workflow<HourlyWorkflow>()( |
| 665 | * "HourlyWorkflow", |
| 666 | * { schedules: ["0 * * * *"] }, |
| 667 | * Effect.gen(function* () { |
| 668 | * return Effect.fn(function* () { |
| 669 | * const event = yield* Cloudflare.Workflows.WorkflowEvent; |
| 670 | * if (event.schedule) { |
| 671 | * return { cron: event.schedule.cron }; |
| 672 | * } |
| 673 | * return {}; |
| 674 | * }); |
| 675 | * }), |
| 676 | * ) {} |
| 677 | * ``` |
| 678 | * |
| 679 | * ### Restricting data location |
| 680 | * `jurisdiction` keeps every instance's execution and stored state inside |
| 681 | * the EU, the US, or FedRAMP-Moderate data centers. Cloudflare fixes it at |
| 682 | * creation, so changing it replaces the Workflow and deletes its instances. |
| 683 | * **Example:** EU-only Workflow |
| 684 | * ```typescript |
| 685 | * export default class GdprWorkflow extends Cloudflare.Workflow<GdprWorkflow>()( |
| 686 | * "GdprWorkflow", |
| 687 | * { jurisdiction: "eu" }, |
| 688 | * Effect.gen(function* () { |
| 689 | * return Effect.fn(function* (input: { userId: string }) { |
| 690 | * return { processed: input.userId }; |
| 691 | * }); |
| 692 | * }), |
| 693 | * ) {} |
| 694 | * ``` |
| 695 | * |
| 696 | * **Example:** EU-only Workflow on an async Worker |
| 697 | * ```typescript |
| 698 | * export const Worker = Cloudflare.Worker("Worker", { |
| 699 | * main: "./src/worker.ts", |
| 700 | * env: { |
| 701 | * GDPR_WORKFLOW: Cloudflare.Workflow("GdprWorkflow", { |
| 702 | * className: "GdprWorkflow", |
| 703 | * jurisdiction: "eu", |
| 704 | * }), |
| 705 | * }, |
| 706 | * }); |
| 707 | * ``` |
| 708 | * |
| 709 | * ### Step Primitives |
| 710 | * **Example:** Running a named task |
| 711 | * ```typescript |
| 712 | * const result = yield* Cloudflare.Workflows.task( |
| 713 | * "process-order", |
| 714 | * Effect.succeed({ orderId: "abc", total: 42 }), |
| 715 | * ); |
| 716 | * ``` |
| 717 | * |
| 718 | * **Example:** Configuring retries and reading step context |
| 719 | * ```typescript |
| 720 | * const result = yield* Cloudflare.Workflows.task( |
| 721 | * "call-api", |
| 722 | * Effect.gen(function* () { |
| 723 | * const context = yield* Cloudflare.Workflows.WorkflowStepContext; |
| 724 | * return { attempt: context.attempt }; |
| 725 | * }), |
| 726 | * { retries: { limit: 3, delay: "5 seconds", backoff: "linear" } }, |
| 727 | * ); |
| 728 | * ``` |
| 729 | * |
| 730 | * **Example:** Registering rollback |
| 731 | * ```typescript |
| 732 | * yield* Cloudflare.Workflows.task("reserve-inventory", reserveInventory, { |
| 733 | * rollback: ({ output }) => |
| 734 | * output ? releaseInventory(output.reservationId) : Effect.void, |
| 735 | * rollbackConfig: { retries: { limit: 3, delay: "10 seconds" } }, |
| 736 | * }); |
| 737 | * ``` |
| 738 | * |
| 739 | * **Example:** Sleeping between steps |
| 740 | * ```typescript |
| 741 | * yield* Cloudflare.Workflows.sleep("cooldown", "30 seconds"); |
| 742 | * ``` |
| 743 | * |
| 744 | * **Example:** Waiting for an external event |
| 745 | * ```typescript |
| 746 | * const event = yield* Cloudflare.Workflows.waitForEvent<{ approved: boolean }>( |
| 747 | * "approval", |
| 748 | * { type: "approval", timeout: "1 day" }, |
| 749 | * ); |
| 750 | * // Same shape as the native step.waitForEvent result: |
| 751 | * event.payload.approved; |
| 752 | * ``` |
| 753 | * |
| 754 | * **Example:** Accessing env bindings inside a task |
| 755 | * Bind a resource (e.g. `Namespace`, `Bucket`) in the workflow's |
| 756 | * outer init phase to get a typed Effect-native client, then use it |
| 757 | * directly inside `task`. `task` threads the binding's service |
| 758 | * requirement (`WorkerEnvironment`) through automatically so the inner |
| 759 | * Effect needs no extra plumbing. |
| 760 | * |
| 761 | * ```typescript |
| 762 | * Effect.gen(function* () { |
| 763 | * const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV); |
| 764 | * |
| 765 | * return Effect.fn(function* (input: { roomId: string; message: string }) { |
| 766 | * const { roomId, message } = input; |
| 767 | * |
| 768 | * const stored = yield* Cloudflare.Workflows.task( |
| 769 | * "kv-roundtrip", |
| 770 | * Effect.gen(function* () { |
| 771 | * const key = `workflow:${roomId}`; |
| 772 | * yield* kv.put(key, message); |
| 773 | * return yield* kv.get(key); |
| 774 | * }).pipe(Effect.orDie), |
| 775 | * ); |
| 776 | * |
| 777 | * return stored; |
| 778 | * }); |
| 779 | * }); |
| 780 | * ``` |
| 781 | * |
| 782 | * ### Starting and Monitoring Instances |
| 783 | * `create` mirrors Cloudflare's native Workflow API: pass workflow input in |
| 784 | * `params`, pass `id` only when you need a deterministic instance ID, and omit |
| 785 | * `id` to let Cloudflare generate one. |
| 786 | * |
| 787 | * **Example:** Creating an instance from a Worker |
| 788 | * ```typescript |
| 789 | * const workflow = yield* MyWorkflow; |
| 790 | * const instance = yield* workflow.create({ params: { orderId: "abc" } }); |
| 791 | * ``` |
| 792 | * |
| 793 | * **Example:** Creating an instance with id and retention |
| 794 | * ```typescript |
| 795 | * const instance = yield* workflow.create({ |
| 796 | * id: "order-abc", |
| 797 | * params: { orderId: "abc" }, |
| 798 | * retention: { successRetention: "1 day", errorRetention: "7 days" }, |
| 799 | * }); |
| 800 | * ``` |
| 801 | * |
| 802 | * **Example:** Creating a batch |
| 803 | * ```typescript |
| 804 | * const instances = yield* workflow.createBatch([ |
| 805 | * { id: "order-a", params: { orderId: "a" } }, |
| 806 | * { id: "order-b", params: { orderId: "b" } }, |
| 807 | * ]); |
| 808 | * ``` |
| 809 | * |
| 810 | * **Example:** Checking instance status |
| 811 | * ```typescript |
| 812 | * const workflow = yield* MyWorkflow; |
| 813 | * const handle = yield* workflow.get(instanceId); |
| 814 | * const status = yield* handle.status(); |
| 815 | * ``` |
| 816 | * |
| 817 | * **Example:** Sending events and restarting instances |
| 818 | * ```typescript |
| 819 | * const instance = yield* workflow.get(instanceId); |
| 820 | * yield* instance.sendEvent({ type: "approval", payload: { approved: true } }); |
| 821 | * yield* instance.restart({ from: { name: "approval", type: "waitForEvent" } }); |
| 822 | * ``` |
| 823 | * |
| 824 | * ### Triggering from a Worker |
| 825 | * Wire the workflow into HTTP routes so callers can fire instances |
| 826 | * and poll for completion. |
| 827 | * |
| 828 | * **Example:** Workflow start + status routes |
| 829 | * ```typescript |
| 830 | * // src/worker.ts |
| 831 | * const notifier = yield* MyWorkflow; |
| 832 | * |
| 833 | * return { |
| 834 | * fetch: Effect.gen(function* () { |
| 835 | * const request = yield* HttpServerRequest; |
| 836 | * |
| 837 | * if (request.url.startsWith("/workflow/start/")) { |
| 838 | * const id = request.url.split("/").pop()!; |
| 839 | * const instance = yield* notifier.create({ params: { orderId: id } }); |
| 840 | * return HttpServerResponse.json({ instanceId: instance.id }); |
| 841 | * } |
| 842 | * |
| 843 | * if (request.url.startsWith("/workflow/status/")) { |
| 844 | * const id = request.url.split("/").pop()!; |
| 845 | * const instance = yield* notifier.get(id); |
| 846 | * return HttpServerResponse.json(yield* instance.status()); |
| 847 | * } |
| 848 | * |
| 849 | * return HttpServerResponse.text("Not Found", { status: 404 }); |
| 850 | * }), |
| 851 | * }; |
| 852 | * ``` |
| 853 | * |
| 854 | * ### Binding in an Async Worker |
| 855 | * When using an Async Worker (plain `async fetch` handler, no Effect |
| 856 | * runtime), declare Workflows in the `env` prop of the Worker resource. |
| 857 | * Pass a `Workflow` reference with a `className` matching the exported |
| 858 | * `WorkflowEntrypoint` subclass in your worker source file. If `className` |
| 859 | * is omitted, it defaults to the binding name. Use `Cloudflare.InferEnv` |
| 860 | * to get a fully typed `env` object that includes the workflow binding. |
| 861 | * |
| 862 | * **Example:** Declaring a Workflow binding in the stack |
| 863 | * ```typescript |
| 864 | * // alchemy.run.ts |
| 865 | * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>; |
| 866 | * |
| 867 | * export const Worker = Cloudflare.Worker("Worker", { |
| 868 | * main: "./src/worker.ts", |
| 869 | * env: { |
| 870 | * MY_WORKFLOW: Cloudflare.Workflow<{ value: string }>("MyWorkflow", { |
| 871 | * className: "MyWorkflow", |
| 872 | * workflowName: "my-existing-workflow", |
| 873 | * }), |
| 874 | * }, |
| 875 | * }); |
| 876 | * ``` |
| 877 | * |
| 878 | * **Example:** Native cron schedules on an async Workflow binding |
| 879 | * ```typescript |
| 880 | * export const Worker = Cloudflare.Worker("Worker", { |
| 881 | * main: "./src/worker.ts", |
| 882 | * env: { |
| 883 | * HOURLY: Cloudflare.Workflow("HourlyWorkflow", { |
| 884 | * className: "HourlyWorkflow", |
| 885 | * schedules: ["0 * * * *"], |
| 886 | * }), |
| 887 | * }, |
| 888 | * }); |
| 889 | * ``` |
| 890 | * |
| 891 | * **Example:** Using the Workflow from a plain async handler |
| 892 | * ```typescript |
| 893 | * // src/worker.ts |
| 894 | * import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers"; |
| 895 | * import type { WorkerEnv } from "../alchemy.run.ts"; |
| 896 | * |
| 897 | * export class MyWorkflow extends WorkflowEntrypoint<WorkerEnv, { value: string }> { |
| 898 | * async run(event: Readonly<WorkflowEvent<{ value: string }>>, step: WorkflowStep) { |
| 899 | * return await step.do("greet", async () => `Hello, ${event.payload.value}!`); |
| 900 | * } |
| 901 | * } |
| 902 | * |
| 903 | * export default { |
| 904 | * async fetch(request: Request, env: WorkerEnv) { |
| 905 | * const instance = await env.MY_WORKFLOW.create({ params: { value: "world" } }); |
| 906 | * return Response.json({ instanceId: instance.id }); |
| 907 | * }, |
| 908 | * }; |
| 909 | * ``` |
| 910 | * |
| 911 | * ### Consuming the Workflow's Physical Name |
| 912 | * An external/async Worker declaration exposes each Workflow binding on `worker.env` with |
| 913 | * the Workflow's account-global `workflowName` as an `Output` of the |
| 914 | * current deploy. Pass the binding directly as a Queue subscription's |
| 915 | * `source`; it deploys after the Workflow is registered, including on the |
| 916 | * first deployment. Explicit source descriptors remain supported for |
| 917 | * Workflows referenced by physical name. |
| 918 | * |
| 919 | * **Example:** Subscribing a Queue to the Workflow's events |
| 920 | * ```typescript |
| 921 | * const worker = yield* Cloudflare.Worker("Worker", { |
| 922 | * main: "./src/worker.ts", |
| 923 | * env: { |
| 924 | * FILE_URL_INGESTION: Cloudflare.Workflow("FileUrlIngestion", { |
| 925 | * className: "FileUrlIngestionWorkflow", |
| 926 | * }), |
| 927 | * }, |
| 928 | * }); |
| 929 | * |
| 930 | * yield* Cloudflare.Queues.Subscription("WorkflowEvents", { |
| 931 | * source: worker.env.FILE_URL_INGESTION, |
| 932 | * events: ["instance.completed", "instance.errored"], |
| 933 | * queueId: queue.queueId, |
| 934 | * }); |
| 935 | * ``` |
| 936 | * |
| 937 | * ### Referencing a Deployed Workflow |
| 938 | * `Workflow.ref` reads the same persisted resource as `WorkflowResource.ref`. |
| 939 | * Use its logical ID (including any namespace), not its physical name or |
| 940 | * Worker env key. Omitting `stack` and `stage` uses the current stack/stage. |
| 941 | * Deploy the host first; a reference does not register or own the Workflow |
| 942 | * and returns resource attributes, not a runtime `WorkflowHandle`. |
| 943 | * |
| 944 | * **Example:** Subscribe to a Workflow in another stack |
| 945 | * ```typescript |
| 946 | * yield* Cloudflare.Queues.Subscription("WorkflowEvents", { |
| 947 | * source: yield* Cloudflare.Workflow.ref("Ingestion", { |
| 948 | * stack: "workflow-host", |
| 949 | * stage: "production", |
| 950 | * }), |
| 951 | * events: ["instance.completed", "instance.errored"], |
| 952 | * queueId: queue.queueId, |
| 953 | * }); |
| 954 | * ``` |
| 955 | * |
| 956 | * ### Cross-Script Binding in an Async Worker |
| 957 | * Async Workers can also bind to a Workflow hosted by another Worker |
| 958 | * script. The host Worker declares and exports the `WorkflowEntrypoint` |
| 959 | * class. The consumer Worker declares a `Workflow` with `scriptName` set |
| 960 | * to the host Worker's script name. Cross-script references are bindings |
| 961 | * only — Alchemy does not drive `putWorkflow` for the foreign class, so |
| 962 | * deploy the host first. |
| 963 | * |
| 964 | * **Example:** Consumer Worker binds to the host script |
| 965 | * ```typescript |
| 966 | * const consumer = yield* Cloudflare.Worker("Consumer", { |
| 967 | * main: "./src/consumer.ts", |
| 968 | * env: { |
| 969 | * MY_WORKFLOW: Cloudflare.Workflow("MyWorkflow", { |
| 970 | * className: "MyWorkflow", |
| 971 | * scriptName: host.workerName, |
| 972 | * // Repeat the host's explicit or preserved physical name when it |
| 973 | * // does not use Alchemy's current generated default. |
| 974 | * workflowName: "my-existing-workflow", |
| 975 | * }), |
| 976 | * }, |
| 977 | * }); |
| 978 | * ``` |
| 979 | * |
| 980 | * ### Testing Workflows |
| 981 | * Workflows run asynchronously, so tests start an instance and poll until it |
| 982 | * reaches a terminal status. Keep polling bounded with `Effect.repeat`. |
| 983 | * |
| 984 | * **Example:** Polling for workflow completion |
| 985 | * ```typescript |
| 986 | * test( |
| 987 | * "workflow completes", |
| 988 | * Effect.gen(function* () { |
| 989 | * const { url } = yield* stack; |
| 990 | * |
| 991 | * const start = yield* HttpClient.post(`${url}/workflow/start/x`); |
| 992 | * const { instanceId } = (yield* start.json) as { instanceId: string }; |
| 993 | * |
| 994 | * const status = yield* HttpClient.get( |
| 995 | * `${url}/workflow/status/${instanceId}`, |
| 996 | * ).pipe( |
| 997 | * Effect.flatMap((res) => res.json), |
| 998 | * Effect.map((json) => json as { status: string }), |
| 999 | * Effect.repeat({ |
| 1000 | * schedule: Schedule.spaced("2 seconds"), |
| 1001 | * until: (status) => |
| 1002 | * status.status === "complete" || status.status === "errored", |
| 1003 | * times: 30, |
| 1004 | * }), |
| 1005 | * ); |
| 1006 | * |
| 1007 | * expect(status.status).toBe("complete"); |
| 1008 | * }), |
| 1009 | * { timeout: 120_000 }, |
| 1010 | * ); |
| 1011 | * ``` |
| 1012 | * |
| 1013 | * ### Observing and Deleting Instances |
| 1014 | * **Example:** Read an event and remove stored state |
| 1015 | * ```typescript |
| 1016 | * const instance = yield* workflow.get("report-123"); |
| 1017 | * const events = yield* instance.subscribe({ filter: ["workflow_queued"] }).pipe( |
| 1018 | * Stream.take(1), |
| 1019 | * Stream.runCollect, |
| 1020 | * ); |
| 1021 | * yield* instance.delete(); |
| 1022 | * const result = yield* workflow.deleteBatch(["report-456", "report-789"]); |
| 1023 | * // result.deleted contains successful IDs; result.errors contains per-instance failures. |
| 1024 | * ``` |
| 1025 | * |
| 1026 | * @resource |
| 1027 | * @product Workflows |
| 1028 | * @category Workers & Compute |
| 1029 | */ |
| 1030 | export const Workflow: WorkflowClass = taggedFunction(WorkflowScope, (( |
| 1031 | ...args: |
| 1032 | | [] |
| 1033 | | [name: string, impl: Effect.Effect<WorkflowImpl<any, any, unknown>>] |
| 1034 | | [name: string, props: WorkflowProps, impl: Effect.Effect<WorkflowImpl<any, any, unknown>>] |
| 1035 | | [name: string, props?: WorkflowRefProps] |
| 1036 | ) => { |
| 1037 | if (args.length === 0) { |
| 1038 | return Workflow; |
| 1039 | } |
| 1040 | const [name, second, third] = args; |
| 1041 | const impl = Effect.isEffect(second) ? second : Effect.isEffect(third) ? third : undefined; |
| 1042 | if (impl === undefined) { |
| 1043 | // Props-only (async) reference form: returns a plain `WorkflowLike` that an |
| 1044 | // async Worker binds via `env`. `WorkerAsyncBindings` emits the `workflow` |
| 1045 | // binding and drives `putWorkflow` for locally-hosted workflows. |
| 1046 | const refProps = second as WorkflowRefProps | undefined; |
| 1047 | return { |
| 1048 | kind: TypeId, |
| 1049 | name, |
| 1050 | workflowName: refProps?.workflowName, |
| 1051 | className: refProps?.className ?? name, |
| 1052 | scriptName: refProps?.scriptName, |
| 1053 | limits: refProps?.limits, |
| 1054 | schedules: refProps?.schedules, |
| 1055 | jurisdiction: refProps?.jurisdiction, |
| 1056 | } satisfies WorkflowLike; |
| 1057 | } |
| 1058 | const props = Effect.isEffect(second) ? undefined : (second as WorkflowProps); |
| 1059 | return effectClass( |
| 1060 | Effect.gen(function* () { |
| 1061 | const worker = yield* Worker; |
| 1062 | |
| 1063 | const workflow = yield* WorkflowResource(name, { |
| 1064 | workflowName: props?.workflowName, |
| 1065 | className: name, |
| 1066 | scriptName: props?.workflowName === undefined ? worker.workerName : undefined, |
| 1067 | limits: props?.limits, |
| 1068 | schedules: props?.schedules, |
| 1069 | jurisdiction: props?.jurisdiction, |
| 1070 | }); |
| 1071 | // Keep named identities resolvable for the engine's cold-adoption probe. |
| 1072 | if (props?.workflowName !== undefined) { |
| 1073 | yield* workflow.bind`${worker}`({ scriptName: worker.workerName }); |
| 1074 | } |
| 1075 | |
| 1076 | // Add the workflow binding to the Worker metadata |
| 1077 | yield* worker.bind`${name}`({ |
| 1078 | bindings: [ |
| 1079 | { |
| 1080 | type: "workflow", |
| 1081 | name, |
| 1082 | workflowName: props?.workflowName ?? workflow.workflowName, |
| 1083 | className: name, |
| 1084 | }, |
| 1085 | ], |
| 1086 | }); |
| 1087 | |
| 1088 | const services = yield* Effect.context<Effect.Services<typeof impl>>(); |
| 1089 | |
| 1090 | const binding = yield* Effect.all([WorkerEnvironment, ALCHEMY_PHASE]).pipe( |
| 1091 | Effect.flatMap(([env, phase]) => { |
| 1092 | if (env === undefined || phase === "plan") { |
| 1093 | return Effect.succeed(undefined as any); |
| 1094 | } |
| 1095 | const wf = env[name]; |
| 1096 | if (!wf) { |
| 1097 | return Effect.die(new Error(`Workflow '${name}' not found in env`)); |
| 1098 | } |
| 1099 | return Effect.succeed(wf); |
| 1100 | }), |
| 1101 | ); |
| 1102 | |
| 1103 | const self: WorkflowHandle<any, any> = { |
| 1104 | Type: TypeId, |
| 1105 | name, |
| 1106 | workflowName: props?.workflowName ?? workflow.workflowName, |
| 1107 | create: (options?: WorkflowInstanceCreateOptions<any>) => |
| 1108 | Effect.tryPromise(() => binding.create(options)).pipe( |
| 1109 | Effect.map(wrapInstance), |
| 1110 | Effect.orDie, |
| 1111 | ), |
| 1112 | createBatch: (batch: WorkflowInstanceCreateOptions<any>[]) => |
| 1113 | Effect.tryPromise(() => binding.createBatch(batch) as Promise<any[]>).pipe( |
| 1114 | Effect.map((instances: any[]) => instances.map(wrapInstance)), |
| 1115 | Effect.orDie, |
| 1116 | ), |
| 1117 | deleteBatch: (instanceIds) => |
| 1118 | Effect.tryPromise( |
| 1119 | () => binding.deleteBatch(instanceIds) as Promise<WorkflowBatchDeleteResult>, |
| 1120 | ).pipe(Effect.orDie), |
| 1121 | get: (instanceId: string) => |
| 1122 | Effect.tryPromise(() => binding.get(instanceId)).pipe( |
| 1123 | Effect.map(wrapInstance), |
| 1124 | Effect.orDie, |
| 1125 | ), |
| 1126 | }; |
| 1127 | |
| 1128 | const fn = yield* impl.pipe(Effect.provideService(WorkflowScope, self as any)); |
| 1129 | |
| 1130 | yield* worker.export(name, { |
| 1131 | kind: "workflow", |
| 1132 | make: (env: unknown) => |
| 1133 | Effect.succeed(((input: unknown) => |
| 1134 | fn(input).pipe( |
| 1135 | Effect.provideService(WorkerEnvironment, env as Record<string, any>), |
| 1136 | )) as WorkflowImpl<any, any, unknown>).pipe(Effect.provideContext(services)), |
| 1137 | } satisfies WorkflowExport); |
| 1138 | |
| 1139 | return self; |
| 1140 | }), |
| 1141 | ); |
| 1142 | }) as any); |
| 1143 | |
| 1144 | Workflow.ref = (id, options) => WorkflowResource.ref(id, options); |
| 1145 | |
| 1146 | // --------------------------------------------------------------------------- |
| 1147 | // WorkflowResource -- manages the Cloudflare Workflows API lifecycle |
| 1148 | // --------------------------------------------------------------------------- |
| 1149 | |
| 1150 | export interface WorkflowResourceProps { |
| 1151 | /** |
| 1152 | * Account-global Workflow name. If omitted, a deterministic name is derived |
| 1153 | * from `scriptName` and `className`. |
| 1154 | * |
| 1155 | * @internal |
| 1156 | */ |
| 1157 | workflowName?: string; |
| 1158 | className: string; |
| 1159 | /** Hosting Worker script, supplied here or through a host binding. */ |
| 1160 | scriptName?: string; |
| 1161 | limits?: WorkflowLimits; |
| 1162 | /** |
| 1163 | * Cron expressions that create a new Workflow instance on each match. |
| 1164 | * Pass an empty array to remove all schedules. |
| 1165 | */ |
| 1166 | schedules?: string[]; |
| 1167 | /** |
| 1168 | * Jurisdiction where instances run and store data. Fixed at creation; |
| 1169 | * changing it replaces the Workflow. |
| 1170 | */ |
| 1171 | jurisdiction?: WorkflowJurisdiction; |
| 1172 | } |
| 1173 | |
| 1174 | export interface WorkflowResourceAttrs { |
| 1175 | workflowId: string; |
| 1176 | workflowName: string; |
| 1177 | className: string; |
| 1178 | scriptName: string; |
| 1179 | accountId: string; |
| 1180 | /** |
| 1181 | * Cron expressions currently attached to this Workflow. |
| 1182 | */ |
| 1183 | schedules: string[]; |
| 1184 | /** |
| 1185 | * Jurisdiction where instances run and store data, or `undefined` when |
| 1186 | * unrestricted. |
| 1187 | */ |
| 1188 | jurisdiction: WorkflowJurisdiction | undefined; |
| 1189 | } |
| 1190 | |
| 1191 | const WorkflowResourceTypeId = "Cloudflare.Workflow"; |
| 1192 | |
| 1193 | export interface WorkflowResource extends Resource< |
| 1194 | typeof WorkflowResourceTypeId, |
| 1195 | WorkflowResourceProps, |
| 1196 | WorkflowResourceAttrs, |
| 1197 | { scriptName: string } |
| 1198 | > {} |
| 1199 | |
| 1200 | export const WorkflowResource = Resource<WorkflowResource>(WorkflowResourceTypeId); |
| 1201 | |
| 1202 | const getWorkflowOrUndefined = (accountId: string, workflowName: string) => |
| 1203 | workflows |
| 1204 | .getWorkflow({ accountId, workflowName }) |
| 1205 | .pipe(Effect.catchTag("WorkflowNotFound", () => Effect.undefined)); |
| 1206 | |
| 1207 | export const ProviderLive = () => |
| 1208 | Provider.succeed(WorkflowResource, { |
| 1209 | // `workflowId` is stable across live updates: `putWorkflow` is a |
| 1210 | // PUT-as-upsert keyed by the account-global `workflowName`, so re-putting |
| 1211 | // the same name (className/scriptName changes) preserves the workflow's |
| 1212 | // id. The dev→deploy id change that used to force `workflowId` out of |
| 1213 | // this list is now an engine-orchestrated mode-switch REPLACEMENT (the |
| 1214 | // persisted `providerMode` stamp differs), so the live provider never |
| 1215 | // sees a `dev:` id. |
| 1216 | stables: ["workflowId", "accountId", "workflowName"], |
| 1217 | // Workflows are account-scoped. Enumerate every workflow in the account |
| 1218 | // via the paginated list API and hydrate each into the same Attributes |
| 1219 | // shape `reconcile` returns (id/name/className/scriptName are all on the |
| 1220 | // list item, so no per-item get is needed). |
| 1221 | list: () => |
| 1222 | Effect.gen(function* () { |
| 1223 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 1224 | return yield* workflows.listWorkflows.pages({ accountId }).pipe( |
| 1225 | Stream.runCollect, |
| 1226 | Effect.map((chunk) => |
| 1227 | Array.from(chunk).flatMap((page) => |
| 1228 | (page.result ?? []).map((wf) => ({ |
| 1229 | workflowId: wf.id, |
| 1230 | workflowName: wf.name, |
| 1231 | // `className`/`scriptName` can be null/absent in the list |
| 1232 | // payload on some accounts — fall back so listing succeeds. |
| 1233 | className: wf.className ?? "", |
| 1234 | scriptName: wf.scriptName ?? "", |
| 1235 | accountId, |
| 1236 | schedules: fromObservedSchedules(wf.schedules), |
| 1237 | jurisdiction: wf.jurisdiction ?? undefined, |
| 1238 | })), |
| 1239 | ), |
| 1240 | ), |
| 1241 | ); |
| 1242 | }), |
| 1243 | diff: Effect.fn(function* ({ id, olds, news, output, oldBindings, newBindings }) { |
| 1244 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 1245 | if (output?.accountId !== undefined && output.accountId !== accountId) { |
| 1246 | return { action: "replace" } as const; |
| 1247 | } |
| 1248 | |
| 1249 | // The host script may be unresolved even when the physical name is known. |
| 1250 | const explicitName = |
| 1251 | "workflowName" in news && isResolved(news.workflowName) ? news.workflowName : undefined; |
| 1252 | const oldName = |
| 1253 | output?.workflowName ?? |
| 1254 | olds.workflowName ?? |
| 1255 | (olds.scriptName === undefined |
| 1256 | ? undefined |
| 1257 | : yield* generateWorkflowName(olds.scriptName, olds.className)); |
| 1258 | // Omitting the name preserves the deployed identity, including legacy names. |
| 1259 | if (explicitName !== undefined && explicitName !== oldName) { |
| 1260 | const existing = yield* getWorkflowOrUndefined(accountId, explicitName); |
| 1261 | if (existing !== undefined) { |
| 1262 | return yield* new OwnedBySomeoneElse({ |
| 1263 | message: `Cannot replace Workflow '${oldName}' with occupied name '${explicitName}'. Choose an unused name.`, |
| 1264 | resourceType: WorkflowResourceTypeId, |
| 1265 | logicalId: id, |
| 1266 | physicalName: explicitName, |
| 1267 | }); |
| 1268 | } |
| 1269 | return { action: "replace" } as const; |
| 1270 | } |
| 1271 | // Cloudflare fixes the jurisdiction at creation. The replacement keeps |
| 1272 | // the same account-global name, so the old Workflow goes first. |
| 1273 | if ( |
| 1274 | "jurisdiction" in news && |
| 1275 | isResolved(news.jurisdiction) && |
| 1276 | news.jurisdiction !== (output?.jurisdiction ?? olds.jurisdiction) |
| 1277 | ) { |
| 1278 | return { action: "replace", deleteFirst: true } as const; |
| 1279 | } |
| 1280 | if (!isResolved(newBindings) || havePropsChanged(oldBindings, newBindings)) { |
| 1281 | return { action: "update" } as const; |
| 1282 | } |
| 1283 | }), |
| 1284 | read: Effect.fn(function* ({ output, olds, previous }) { |
| 1285 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 1286 | const workflowName = |
| 1287 | output?.workflowName ?? |
| 1288 | olds?.workflowName ?? |
| 1289 | (olds?.scriptName === undefined |
| 1290 | ? undefined |
| 1291 | : yield* generateWorkflowName(olds.scriptName, olds.className)); |
| 1292 | if (workflowName === undefined) return undefined; |
| 1293 | |
| 1294 | const acct = output?.accountId ?? accountId; |
| 1295 | const workflow = yield* getWorkflowOrUndefined(acct, workflowName); |
| 1296 | if (workflow === undefined) return undefined; |
| 1297 | const attrs = { |
| 1298 | workflowId: workflow.id, |
| 1299 | workflowName: workflow.name, |
| 1300 | className: workflow.className, |
| 1301 | scriptName: workflow.scriptName, |
| 1302 | accountId: acct, |
| 1303 | schedules: fromObservedSchedules(workflow.schedules), |
| 1304 | jurisdiction: workflow.jurisdiction ?? undefined, |
| 1305 | }; |
| 1306 | // Explicit names carry no ownership marker; cold reads require adoption, |
| 1307 | // except of the generation a replacement is replacing. |
| 1308 | return output === undefined && |
| 1309 | olds?.workflowName !== undefined && |
| 1310 | previous?.workflowId !== workflow.id |
| 1311 | ? Unowned(attrs) |
| 1312 | : attrs; |
| 1313 | }), |
| 1314 | reconcile: Effect.fn(function* ({ id, news, output, bindings }) { |
| 1315 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 1316 | const scriptName = yield* resolveWorkflowScriptName(news, bindings); |
| 1317 | const acct = output?.accountId ?? accountId; |
| 1318 | const workflowName = |
| 1319 | news.workflowName ?? |
| 1320 | output?.workflowName ?? |
| 1321 | (yield* generateWorkflowName(scriptName, news.className)); |
| 1322 | |
| 1323 | if ( |
| 1324 | news.workflowName !== undefined && |
| 1325 | output?.workflowName !== undefined && |
| 1326 | news.workflowName !== output.workflowName |
| 1327 | ) { |
| 1328 | return yield* new WorkflowInvalidProps({ |
| 1329 | message: `Workflow physical name changed from '${output.workflowName}' to '${news.workflowName}' during an in-place update; a replacement is required.`, |
| 1330 | }); |
| 1331 | } |
| 1332 | |
| 1333 | const existing = yield* getWorkflowOrUndefined(acct, workflowName); |
| 1334 | // Re-check occupied names at apply time; replacement is not adoption. |
| 1335 | if (news.workflowName !== undefined && output === undefined && existing !== undefined) { |
| 1336 | return yield* new OwnedBySomeoneElse({ |
| 1337 | message: |
| 1338 | `Cannot create Workflow '${workflowName}': an existing ` + |
| 1339 | "Workflow has that account-global name. Choose an unused name, " + |
| 1340 | "or adopt it into a resource with no prior state by re-planning " + |
| 1341 | "with --adopt.", |
| 1342 | resourceType: WorkflowResourceTypeId, |
| 1343 | logicalId: id, |
| 1344 | physicalName: workflowName, |
| 1345 | }); |
| 1346 | } |
| 1347 | // PUT keeps an existing Workflow's jurisdiction, so a mismatch can't converge. |
| 1348 | if (existing !== undefined && (existing.jurisdiction ?? undefined) !== news.jurisdiction) { |
| 1349 | return yield* new WorkflowInvalidProps({ |
| 1350 | message: |
| 1351 | `Workflow '${workflowName}' has jurisdiction '${existing.jurisdiction ?? "none"}', ` + |
| 1352 | `but '${news.jurisdiction ?? "none"}' was requested. Cloudflare fixes a ` + |
| 1353 | "Workflow's jurisdiction at creation; use a new name or delete the Workflow first.", |
| 1354 | }); |
| 1355 | } |
| 1356 | // PUT clears omitted schedules; preserve observed state unless explicitly set. |
| 1357 | const schedules = news.schedules ?? fromObservedSchedules(existing?.schedules); |
| 1358 | |
| 1359 | yield* Effect.logInfo(`Cloudflare Workflow reconcile: ${workflowName}`); |
| 1360 | // Cloudflare's `putWorkflow` is a true PUT-as-upsert: identical |
| 1361 | // payloads converge to the same state and a missing workflow is |
| 1362 | // created on the spot. |
| 1363 | const result = yield* workflows.putWorkflow({ |
| 1364 | accountId: acct, |
| 1365 | workflowName, |
| 1366 | className: news.className, |
| 1367 | scriptName, |
| 1368 | limits: news.limits, |
| 1369 | schedules: toPutSchedules(schedules), |
| 1370 | jurisdiction: news.jurisdiction, |
| 1371 | }); |
| 1372 | return { |
| 1373 | workflowId: result.id, |
| 1374 | workflowName: result.name, |
| 1375 | className: result.className, |
| 1376 | scriptName: result.scriptName, |
| 1377 | accountId: acct, |
| 1378 | schedules, |
| 1379 | jurisdiction: result.jurisdiction ?? news.jurisdiction, |
| 1380 | }; |
| 1381 | }), |
| 1382 | delete: Effect.fn(function* ({ output }) { |
| 1383 | yield* Effect.logInfo(`Cloudflare Workflow delete: ${output.workflowName}`); |
| 1384 | yield* workflows |
| 1385 | .deleteWorkflow({ |
| 1386 | accountId: output.accountId, |
| 1387 | workflowName: output.workflowName, |
| 1388 | }) |
| 1389 | .pipe(Effect.catchTag("WorkflowNotFound", () => Effect.void)); |
| 1390 | }), |
| 1391 | }); |
| 1392 | |
| 1393 | /** |
| 1394 | * Local (dev) provider — the workflow is purely virtual: a `dev:` id keyed |
| 1395 | * into the local workerd workflow engine. The host worker's `workflow` |
| 1396 | * binding is lowered onto the local runtime's Workflow Engine DO by |
| 1397 | * `LocalWorkerProvider` (`Workflows.local(...)`), so no runtime layer is |
| 1398 | * needed here; instance state persists under the worker's local storage. |
| 1399 | */ |
| 1400 | export const ProviderLocal = () => |
| 1401 | Provider.succeed(WorkflowResource, { |
| 1402 | stables: ["accountId"], |
| 1403 | diff: Effect.fn(function* ({ news, output, oldBindings, newBindings }) { |
| 1404 | const accountId = yield* localAccountId; |
| 1405 | if (!output?.workflowId) return { action: "update" } as const; |
| 1406 | if (output.accountId !== accountId) { |
| 1407 | return { action: "replace" } as const; |
| 1408 | } |
| 1409 | // The host script may be unresolved even when the physical name is known. |
| 1410 | const explicitName = |
| 1411 | "workflowName" in news && isResolved(news.workflowName) ? news.workflowName : undefined; |
| 1412 | if (explicitName !== undefined && explicitName !== output.workflowName) { |
| 1413 | return { action: "replace" } as const; |
| 1414 | } |
| 1415 | if (!isResolved(newBindings) || havePropsChanged(oldBindings, newBindings)) { |
| 1416 | return { action: "update" } as const; |
| 1417 | } |
| 1418 | // Fall through to the engine's default prop diff (className / |
| 1419 | // scriptName changes update in place). |
| 1420 | }), |
| 1421 | read: Effect.fn(function* ({ output }) { |
| 1422 | // Purely virtual — the persisted state row is the source of truth. |
| 1423 | return output ?? undefined; |
| 1424 | }), |
| 1425 | reconcile: Effect.fn(function* ({ news, output, bindings }) { |
| 1426 | const accountId = yield* localAccountId; |
| 1427 | const scriptName = yield* resolveWorkflowScriptName(news, bindings); |
| 1428 | if ( |
| 1429 | news.workflowName !== undefined && |
| 1430 | output?.workflowName !== undefined && |
| 1431 | news.workflowName !== output.workflowName |
| 1432 | ) { |
| 1433 | return yield* new WorkflowInvalidProps({ |
| 1434 | message: `Workflow physical name changed from '${output.workflowName}' to '${news.workflowName}' during an in-place update; a replacement is required.`, |
| 1435 | }); |
| 1436 | } |
| 1437 | return { |
| 1438 | workflowId: output?.workflowId ?? generateLocalId(), |
| 1439 | workflowName: |
| 1440 | news.workflowName ?? |
| 1441 | output?.workflowName ?? |
| 1442 | (yield* generateWorkflowName(scriptName, news.className)), |
| 1443 | className: news.className, |
| 1444 | scriptName, |
| 1445 | accountId: output?.accountId ?? accountId, |
| 1446 | schedules: news.schedules ?? output?.schedules ?? [], |
| 1447 | jurisdiction: news.jurisdiction, |
| 1448 | }; |
| 1449 | }), |
| 1450 | delete: Effect.fn(function* () { |
| 1451 | // The simulator's on-disk instance state lives under the local worker's |
| 1452 | // storage; dropping the state row is enough — orphaned data is |
| 1453 | // reclaimed with `.alchemy`. |
| 1454 | }), |
| 1455 | }); |
| 1456 | |
| 1457 | export const WorkflowProvider = () => |
| 1458 | ProviderLayer.dual(WorkflowResource, { |
| 1459 | local: () => ProviderLocal(), |
| 1460 | live: () => ProviderLive(), |
| 1461 | }); |
| 1462 | |
| 1463 | // --------------------------------------------------------------------------- |
| 1464 | // Helpers |
| 1465 | // --------------------------------------------------------------------------- |
| 1466 | |
| 1467 | const resolveWorkflowScriptName = ( |
| 1468 | props: WorkflowResourceProps, |
| 1469 | bindings: ReadonlyArray<{ data: { scriptName: string } }>, |
| 1470 | ) => { |
| 1471 | const scripts = [ |
| 1472 | ...new Set( |
| 1473 | [props.scriptName, ...bindings.map((binding) => binding.data.scriptName)].filter( |
| 1474 | (name) => name !== undefined, |
| 1475 | ), |
| 1476 | ), |
| 1477 | ]; |
| 1478 | return scripts.length === 1 |
| 1479 | ? Effect.succeed(scripts[0]!) |
| 1480 | : Effect.fail( |
| 1481 | new WorkflowInvalidProps({ |
| 1482 | message: "Workflow requires exactly one hosting Worker script", |
| 1483 | }), |
| 1484 | ); |
| 1485 | }; |
| 1486 | |
| 1487 | const toPutSchedules = (schedules: string[]): workflows.UpdateRequestSchedulesList => |
| 1488 | schedules.map((cron) => ({ cron })); |
| 1489 | |
| 1490 | const fromObservedSchedules = (schedules?: ReadonlyArray<{ cron: string }> | null): string[] => |
| 1491 | (schedules ?? []).map((s) => s.cron); |
| 1492 | |
| 1493 | const wrapInstance = <Result>(raw: any): WorkflowInstance<Result> => ({ |
| 1494 | id: raw.id, |
| 1495 | status: () => |
| 1496 | Effect.tryPromise(() => raw.status()).pipe( |
| 1497 | Effect.map((s: any) => ({ |
| 1498 | status: s.status as string, |
| 1499 | output: s.output as Result, |
| 1500 | error: s.error, |
| 1501 | rollback: s.rollback, |
| 1502 | })), |
| 1503 | Effect.orDie, |
| 1504 | ), |
| 1505 | pause: () => Effect.tryPromise(() => raw.pause()).pipe(Effect.orDie), |
| 1506 | resume: () => Effect.tryPromise(() => raw.resume()).pipe(Effect.orDie), |
| 1507 | restart: (options?: WorkflowInstanceRestartOptions) => |
| 1508 | Effect.tryPromise(() => raw.restart(options)).pipe(Effect.orDie), |
| 1509 | terminate: () => Effect.tryPromise(() => raw.terminate()).pipe(Effect.orDie), |
| 1510 | delete: () => Effect.tryPromise(() => raw.delete()).pipe(Effect.orDie), |
| 1511 | subscribe: (options) => |
| 1512 | Effect.acquireDisposable( |
| 1513 | Effect.tryPromise( |
| 1514 | () => raw.subscribe(options) as Promise<runtime.WorkflowInstanceSubscription & Disposable>, |
| 1515 | ).pipe(Effect.orDie), |
| 1516 | ).pipe( |
| 1517 | Effect.map((subscription) => |
| 1518 | Stream.fromAsyncIterable( |
| 1519 | { |
| 1520 | [Symbol.asyncIterator]: () => ({ |
| 1521 | next: () => subscription.next(), |
| 1522 | }), |
| 1523 | }, |
| 1524 | (error) => error, |
| 1525 | ).pipe(Stream.orDie), |
| 1526 | ), |
| 1527 | Stream.unwrap, |
| 1528 | ), |
| 1529 | sendEvent: <Event = unknown>(event: WorkflowInstanceEvent<Event>) => |
| 1530 | Effect.tryPromise(() => raw.sendEvent(event)).pipe(Effect.orDie), |
| 1531 | }); |