The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as iam from "@distilled.cloud/aws/iam"; |
| 2 | import * as sfn from "@distilled.cloud/aws/sfn"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource, type ResourceBinding } from "alchemy/Resource"; |
| 8 | import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Redacted from "effect/Redacted"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import { AWSEnvironment } from "../Environment.ts"; |
| 15 | import type { PolicyStatement } from "../IAM/Policy.ts"; |
| 16 | import type { Providers } from "../Providers.ts"; |
| 17 | import { compileProgram, SfnCompileError } from "./Asl/compile.ts"; |
| 18 | import type { SfnEffect } from "./Asl/Program.ts"; |
| 19 | |
| 20 | /** |
| 21 | * The workflow type. `STANDARD` workflows are durable (up to one year), |
| 22 | * exactly-once, and support execution history; `EXPRESS` workflows are |
| 23 | * high-throughput, at-least-once, cheaper, and support synchronous |
| 24 | * invocation via `StartSyncExecution`. |
| 25 | */ |
| 26 | export type StateMachineType = "STANDARD" | "EXPRESS"; |
| 27 | |
| 28 | /** |
| 29 | * Log level for a state machine's CloudWatch Logs configuration. |
| 30 | */ |
| 31 | export type StateMachineLogLevel = "ALL" | "ERROR" | "FATAL" | "OFF"; |
| 32 | |
| 33 | export interface StateMachineLogging { |
| 34 | /** |
| 35 | * Which execution history events are logged. |
| 36 | */ |
| 37 | level: StateMachineLogLevel; |
| 38 | /** |
| 39 | * Whether execution input, data passed between states, and output are |
| 40 | * included in the log events. |
| 41 | * @default false |
| 42 | */ |
| 43 | includeExecutionData?: boolean; |
| 44 | /** |
| 45 | * CloudWatch log group ARNs to deliver logs to. The `:*` suffix is |
| 46 | * appended automatically when missing (the API requires it). |
| 47 | */ |
| 48 | destinations?: string[]; |
| 49 | } |
| 50 | |
| 51 | export interface StateMachineProps { |
| 52 | /** |
| 53 | * Name of the state machine (1-80 characters; letters, digits, dashes and |
| 54 | * underscores). If omitted, a deterministic physical name is generated |
| 55 | * from the app, stage, and logical ID. Changing the name triggers a |
| 56 | * replacement. |
| 57 | */ |
| 58 | stateMachineName?: string; |
| 59 | /** |
| 60 | * The Amazon States Language (ASL) definition of the workflow. Accepts a |
| 61 | * plain object (recommended — `Output` values such as function ARNs are |
| 62 | * resolved before serialization) or a pre-serialized JSON string. |
| 63 | */ |
| 64 | definition: Record<string, unknown> | string; |
| 65 | /** |
| 66 | * Literal substitutions applied to the serialized definition: every |
| 67 | * occurrence of `${key}` is replaced with the mapped value. Useful when |
| 68 | * the definition is authored as a static JSON string. |
| 69 | */ |
| 70 | definitionSubstitutions?: Record<string, string>; |
| 71 | /** |
| 72 | * The ARN of an existing IAM role for the state machine to use. When |
| 73 | * omitted, an execution role is created automatically with |
| 74 | * `states.amazonaws.com` trust; `lambda:InvokeFunction` is granted for |
| 75 | * every Lambda function ARN referenced in the definition, and |
| 76 | * {@link StateMachineProps.policyStatements} are attached as an inline |
| 77 | * policy. |
| 78 | */ |
| 79 | roleArn?: string; |
| 80 | /** |
| 81 | * Additional IAM policy statements attached to the auto-created |
| 82 | * execution role (ignored when {@link StateMachineProps.roleArn} is |
| 83 | * provided). Use this to authorize service integrations such as |
| 84 | * `sqs:SendMessage` or `dynamodb:PutItem` task states. |
| 85 | */ |
| 86 | policyStatements?: PolicyStatement[]; |
| 87 | /** |
| 88 | * The workflow type. Changing the type triggers a replacement. |
| 89 | * @default "STANDARD" |
| 90 | */ |
| 91 | type?: StateMachineType; |
| 92 | /** |
| 93 | * CloudWatch Logs configuration. Required (with level `ALL`/`ERROR`/ |
| 94 | * `FATAL`) to observe `EXPRESS` workflow executions. The auto-created |
| 95 | * execution role is granted the CloudWatch Logs delivery permissions |
| 96 | * automatically. |
| 97 | */ |
| 98 | logging?: StateMachineLogging; |
| 99 | /** |
| 100 | * Whether AWS X-Ray tracing is enabled. |
| 101 | * @default false |
| 102 | */ |
| 103 | tracingEnabled?: boolean; |
| 104 | /** |
| 105 | * Tags to apply to the state machine. Merged with internal Alchemy tags. |
| 106 | */ |
| 107 | tags?: Record<string, string>; |
| 108 | } |
| 109 | |
| 110 | export interface StateMachine extends Resource< |
| 111 | "AWS.StepFunctions.StateMachine", |
| 112 | StateMachineProps, |
| 113 | { |
| 114 | /** |
| 115 | * Physical name of the state machine. |
| 116 | */ |
| 117 | stateMachineName: string; |
| 118 | /** |
| 119 | * ARN of the state machine — pass it to `StartExecution` or reference it |
| 120 | * from other workflows. |
| 121 | */ |
| 122 | stateMachineArn: string; |
| 123 | /** |
| 124 | * Workflow type (`STANDARD` or `EXPRESS`). |
| 125 | */ |
| 126 | type: StateMachineType; |
| 127 | /** |
| 128 | * ARN of the IAM execution role the workflow assumes. |
| 129 | */ |
| 130 | roleArn: string; |
| 131 | /** |
| 132 | * Name of the auto-created execution role. `undefined` when an explicit |
| 133 | * {@link StateMachineProps.roleArn} is used. |
| 134 | */ |
| 135 | roleName: string | undefined; |
| 136 | /** |
| 137 | * The definition, logging, tracing, tags and (for the auto-created role) |
| 138 | * the execution-role inline policy, as observed. Lets `alchemy drift` |
| 139 | * detect out-of-band changes. |
| 140 | */ |
| 141 | configuration?: { |
| 142 | definition: string; |
| 143 | logging: { |
| 144 | level: string; |
| 145 | includeExecutionData?: boolean; |
| 146 | destinations?: string[]; |
| 147 | }; |
| 148 | tracingEnabled: boolean; |
| 149 | tags: Record<string, string>; |
| 150 | executionRolePolicy?: unknown; |
| 151 | }; |
| 152 | }, |
| 153 | { |
| 154 | /** |
| 155 | * IAM policy statements bindings attach to the auto-created execution |
| 156 | * role (e.g. service-integration permissions collected by `fromProgram`). |
| 157 | */ |
| 158 | policyStatements: PolicyStatement[]; |
| 159 | }, |
| 160 | Providers |
| 161 | > {} |
| 162 | |
| 163 | /** |
| 164 | * The definition failed AWS's `validateStateMachineDefinition` pre-flight |
| 165 | * check (run in reconcile before create/update). Carries the validator's |
| 166 | * ERROR-severity diagnostics. |
| 167 | */ |
| 168 | export class InvalidStateMachineDefinition extends Data.TaggedError( |
| 169 | "InvalidStateMachineDefinition", |
| 170 | )<{ |
| 171 | readonly diagnostics: readonly { |
| 172 | readonly severity: string; |
| 173 | readonly code: string; |
| 174 | readonly message: string; |
| 175 | readonly location: string | undefined; |
| 176 | }[]; |
| 177 | }> {} |
| 178 | |
| 179 | const StateMachineResource = Resource<StateMachine>("AWS.StepFunctions.StateMachine"); |
| 180 | |
| 181 | /** |
| 182 | * Props for {@link StateMachine.fromProgram} — everything a raw |
| 183 | * `StateMachine` accepts except the `definition` (which is compiled from |
| 184 | * the program). User `policyStatements` are merged with the statements the |
| 185 | * compiler collects from `Sfn.invoke`/`Sfn.integrate` task states. |
| 186 | */ |
| 187 | export interface FromProgramProps extends Omit< |
| 188 | StateMachineProps, |
| 189 | "definition" | "definitionSubstitutions" |
| 190 | > { |
| 191 | /** The typed Step Functions program to compile (built with `Sfn.gen`). */ |
| 192 | program: SfnEffect<any, any>; |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * Sugar over the raw `StateMachine` resource: compile a typed `Sfn` program |
| 197 | * to a plain ASL definition object plus collected IAM policy statements, |
| 198 | * then register the same `StateMachine` resource the raw path uses. Nothing |
| 199 | * engine-level — the raw `definition` escape hatch stays first-class. |
| 200 | */ |
| 201 | const fromProgram = (id: string, props: FromProgramProps) => |
| 202 | Effect.gen(function* () { |
| 203 | const { program, policyStatements, ...rest } = props; |
| 204 | const compiled = yield* Effect.try({ |
| 205 | try: () => compileProgram(program), |
| 206 | catch: (error) => |
| 207 | error instanceof SfnCompileError ? error : new SfnCompileError({ message: String(error) }), |
| 208 | }); |
| 209 | return yield* StateMachineResource(id, { |
| 210 | ...rest, |
| 211 | definition: compiled.definition, |
| 212 | policyStatements: [...compiled.policyStatements, ...(policyStatements ?? [])], |
| 213 | }); |
| 214 | }); |
| 215 | |
| 216 | /** |
| 217 | * An AWS Step Functions state machine (workflow). |
| 218 | * |
| 219 | * `StateMachine` owns the lifecycle of a `STANDARD` or `EXPRESS` workflow. |
| 220 | * The Amazon States Language definition may be provided as a plain object — |
| 221 | * `Output` values (like Lambda function ARNs) inside it are resolved before |
| 222 | * serialization — and an execution role is created automatically unless an |
| 223 | * explicit `roleArn` is given. Lambda functions referenced in the definition |
| 224 | * are granted `lambda:InvokeFunction` on the auto-created role. |
| 225 | * ### Creating State Machines |
| 226 | * **Example:** Standard Workflow with a Pass State |
| 227 | * ```typescript |
| 228 | * import * as StepFunctions from "@alchemy.run/aws/StepFunctions"; |
| 229 | * |
| 230 | * const machine = yield* StepFunctions.StateMachine("OrderWorkflow", { |
| 231 | * definition: { |
| 232 | * StartAt: "Done", |
| 233 | * States: { |
| 234 | * Done: { Type: "Pass", End: true }, |
| 235 | * }, |
| 236 | * }, |
| 237 | * }); |
| 238 | * ``` |
| 239 | * |
| 240 | * **Example:** Express Workflow |
| 241 | * ```typescript |
| 242 | * const machine = yield* StepFunctions.StateMachine("FastWorkflow", { |
| 243 | * type: "EXPRESS", |
| 244 | * definition: { |
| 245 | * StartAt: "Echo", |
| 246 | * States: { |
| 247 | * Echo: { Type: "Pass", End: true }, |
| 248 | * }, |
| 249 | * }, |
| 250 | * }); |
| 251 | * ``` |
| 252 | * |
| 253 | * ### Orchestrating Lambda Functions |
| 254 | * Reference a function ARN in a Task state — `lambda:InvokeFunction` is |
| 255 | * granted on the auto-created execution role automatically. |
| 256 | * |
| 257 | * **Example:** Invoke a Lambda Function |
| 258 | * ```typescript |
| 259 | * const machine = yield* StepFunctions.StateMachine("Pipeline", { |
| 260 | * definition: { |
| 261 | * StartAt: "Process", |
| 262 | * States: { |
| 263 | * Process: { |
| 264 | * Type: "Task", |
| 265 | * Resource: fn.functionArn, |
| 266 | * End: true, |
| 267 | * }, |
| 268 | * }, |
| 269 | * }, |
| 270 | * }); |
| 271 | * ``` |
| 272 | * |
| 273 | * ### Service Integrations |
| 274 | * **Example:** Send a Task Token to SQS (callback pattern) |
| 275 | * ```typescript |
| 276 | * const machine = yield* StepFunctions.StateMachine("Callback", { |
| 277 | * definition: { |
| 278 | * StartAt: "WaitForApproval", |
| 279 | * States: { |
| 280 | * WaitForApproval: { |
| 281 | * Type: "Task", |
| 282 | * Resource: "arn:aws:states:::sqs:sendMessage.waitForTaskToken", |
| 283 | * Parameters: { |
| 284 | * QueueUrl: queue.queueUrl, |
| 285 | * MessageBody: { "token.$": "$$.Task.Token" }, |
| 286 | * }, |
| 287 | * End: true, |
| 288 | * }, |
| 289 | * }, |
| 290 | * }, |
| 291 | * policyStatements: [ |
| 292 | * { |
| 293 | * Effect: "Allow", |
| 294 | * Action: ["sqs:SendMessage"], |
| 295 | * Resource: [queue.queueArn], |
| 296 | * }, |
| 297 | * ], |
| 298 | * }); |
| 299 | * ``` |
| 300 | * |
| 301 | * ### Starting Executions at Runtime |
| 302 | * Bind execution operations in the init phase and use them in runtime |
| 303 | * handlers. |
| 304 | * |
| 305 | * **Example:** Start a workflow from a handler |
| 306 | * ```typescript |
| 307 | * // init |
| 308 | * const startExecution = yield* StepFunctions.StartExecution(machine); |
| 309 | * |
| 310 | * return { |
| 311 | * fetch: Effect.gen(function* () { |
| 312 | * // runtime |
| 313 | * const execution = yield* startExecution({ |
| 314 | * input: JSON.stringify({ orderId: "123" }), |
| 315 | * }); |
| 316 | * return HttpServerResponse.json({ executionArn: execution.executionArn }); |
| 317 | * }), |
| 318 | * }; |
| 319 | * ``` |
| 320 | * |
| 321 | * **Example:** Run an EXPRESS workflow synchronously |
| 322 | * ```typescript |
| 323 | * // init |
| 324 | * const startSyncExecution = yield* StepFunctions.StartSyncExecution(machine); |
| 325 | * |
| 326 | * // runtime |
| 327 | * const result = yield* startSyncExecution({ |
| 328 | * input: JSON.stringify({ value: 21 }), |
| 329 | * }); |
| 330 | * // result.status === "SUCCEEDED", result.output is the workflow output |
| 331 | * ``` |
| 332 | * |
| 333 | * ### Typed Programs |
| 334 | * Author the workflow as a typed `Sfn` program (mirroring Effect's names — |
| 335 | * `Sfn.gen`, `Sfn.invoke`, `Sfn.when`, `Sfn.forEach`, `Sfn.catchTag`, ...) |
| 336 | * and compile it with `StateMachine.fromProgram`. The compiler emits a plain |
| 337 | * ASL definition plus the IAM policy statements its task states need; the |
| 338 | * raw `definition` path above stays fully usable underneath. |
| 339 | * |
| 340 | * **Example:** Compile a typed program |
| 341 | * ```typescript |
| 342 | * import { Sfn, StateMachine } from "@alchemy.run/aws/StepFunctions"; |
| 343 | * |
| 344 | * const machine = yield* StateMachine.fromProgram("OrderWorkflow", { |
| 345 | * type: "EXPRESS", |
| 346 | * program: Sfn.gen(function* (input: Sfn.Expr<{ value: number }>) { |
| 347 | * const result = yield* Sfn.invoke<{ doubled: number }>(doubler, { |
| 348 | * value: input.value, |
| 349 | * }); |
| 350 | * const size = yield* Sfn.when( |
| 351 | * Sfn.gt(result.doubled, 10), |
| 352 | * Sfn.succeed("big"), |
| 353 | * Sfn.succeed("small"), |
| 354 | * ); |
| 355 | * return { doubled: result.doubled, size }; |
| 356 | * }), |
| 357 | * }); |
| 358 | * ``` |
| 359 | * |
| 360 | * @resource |
| 361 | */ |
| 362 | export const StateMachine: typeof StateMachineResource & { |
| 363 | fromProgram: typeof fromProgram; |
| 364 | } = Object.assign(StateMachineResource, { fromProgram }); |
| 365 | |
| 366 | /** Normalize a plain or redacted string to its plain value. */ |
| 367 | const plain = (value: string | Redacted.Redacted<string>): string => |
| 368 | typeof value === "string" ? value : Redacted.value(value); |
| 369 | |
| 370 | /** Convert a tag record to the SFN wire shape (lowercase key/value). */ |
| 371 | const toSfnTags = (tags: Record<string, string>): sfn.Tag[] => |
| 372 | Object.entries(tags).map(([key, value]) => ({ key, value })); |
| 373 | |
| 374 | /** Convert an SFN wire tag list back to a record. */ |
| 375 | const fromSfnTags = (tags: ReadonlyArray<sfn.Tag> | undefined): Record<string, string> => |
| 376 | Object.fromEntries( |
| 377 | (tags ?? []) |
| 378 | .filter( |
| 379 | (tag): tag is { key: string; value: string } => |
| 380 | typeof tag.key === "string" && typeof tag.value === "string", |
| 381 | ) |
| 382 | .map((tag) => [tag.key, tag.value]), |
| 383 | ); |
| 384 | |
| 385 | /** |
| 386 | * Serialize the desired definition to its ASL JSON string, applying |
| 387 | * `${key}` substitutions. |
| 388 | */ |
| 389 | const serializeDefinition = (props: { |
| 390 | definition: Record<string, unknown> | string; |
| 391 | definitionSubstitutions?: Record<string, string>; |
| 392 | }): string => { |
| 393 | let definition = |
| 394 | typeof props.definition === "string" |
| 395 | ? props.definition |
| 396 | : JSON.stringify(props.definition, null, 2); |
| 397 | for (const [key, value] of Object.entries(props.definitionSubstitutions ?? {})) { |
| 398 | definition = definition.replaceAll(`\${${key}}`, value); |
| 399 | } |
| 400 | return definition; |
| 401 | }; |
| 402 | |
| 403 | /** |
| 404 | * Canonicalize an ASL JSON string for drift comparison (whitespace/key-order |
| 405 | * insensitive). Falls back to the raw string when unparsable. |
| 406 | */ |
| 407 | const normalizeDefinition = (definition: string): string => { |
| 408 | try { |
| 409 | const stable = (value: unknown): unknown => |
| 410 | Array.isArray(value) |
| 411 | ? value.map(stable) |
| 412 | : value !== null && typeof value === "object" |
| 413 | ? Object.fromEntries( |
| 414 | Object.entries(value as Record<string, unknown>) |
| 415 | .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) |
| 416 | .map(([k, v]) => [k, stable(v)]), |
| 417 | ) |
| 418 | : value; |
| 419 | return JSON.stringify(stable(JSON.parse(definition))); |
| 420 | } catch { |
| 421 | return definition; |
| 422 | } |
| 423 | }; |
| 424 | |
| 425 | /** |
| 426 | * Extract every Lambda function ARN referenced in a serialized definition so |
| 427 | * the auto-created execution role can be granted `lambda:InvokeFunction`. |
| 428 | */ |
| 429 | const scanLambdaArns = (definition: string): string[] => { |
| 430 | const matches = definition.match( |
| 431 | /arn:aws[a-z0-9-]*:lambda:[a-z0-9-]+:\d{12}:function:[A-Za-z0-9_.-]+(?::[A-Za-z0-9_$-]+)?/g, |
| 432 | ); |
| 433 | return [...new Set(matches ?? [])]; |
| 434 | }; |
| 435 | |
| 436 | /** |
| 437 | * CloudWatch Logs delivery permissions required by Step Functions logging. |
| 438 | * These actions do not support resource-level scoping. |
| 439 | */ |
| 440 | const LOG_DELIVERY_ACTIONS = [ |
| 441 | "logs:CreateLogDelivery", |
| 442 | "logs:CreateLogStream", |
| 443 | "logs:GetLogDelivery", |
| 444 | "logs:UpdateLogDelivery", |
| 445 | "logs:DeleteLogDelivery", |
| 446 | "logs:ListLogDeliveries", |
| 447 | "logs:PutLogEvents", |
| 448 | "logs:PutResourcePolicy", |
| 449 | "logs:DescribeResourcePolicies", |
| 450 | "logs:DescribeLogGroups", |
| 451 | ]; |
| 452 | |
| 453 | /** Map the `logging` prop to the wire `LoggingConfiguration`. */ |
| 454 | const toWireLogging = ( |
| 455 | logging: StateMachineLogging | undefined, |
| 456 | ): sfn.LoggingConfiguration | undefined => |
| 457 | logging === undefined |
| 458 | ? undefined |
| 459 | : { |
| 460 | level: logging.level, |
| 461 | includeExecutionData: logging.includeExecutionData ?? false, |
| 462 | destinations: (logging.destinations ?? []).map((arn) => ({ |
| 463 | cloudWatchLogsLogGroup: { |
| 464 | logGroupArn: arn.endsWith(":*") ? arn : `${arn}:*`, |
| 465 | }, |
| 466 | })), |
| 467 | }; |
| 468 | |
| 469 | /** Compare observed logging configuration against the desired one. */ |
| 470 | const loggingDrifted = ( |
| 471 | observed: sfn.LoggingConfiguration | undefined, |
| 472 | desired: sfn.LoggingConfiguration | undefined, |
| 473 | ): boolean => { |
| 474 | const observedLevel = observed?.level ?? "OFF"; |
| 475 | const desiredLevel = desired?.level ?? "OFF"; |
| 476 | if (observedLevel !== desiredLevel) return true; |
| 477 | if (desiredLevel === "OFF") return false; |
| 478 | if ((observed?.includeExecutionData ?? false) !== (desired?.includeExecutionData ?? false)) { |
| 479 | return true; |
| 480 | } |
| 481 | const arnsOf = (config: sfn.LoggingConfiguration | undefined) => |
| 482 | (config?.destinations ?? []) |
| 483 | .map((d) => d.cloudWatchLogsLogGroup?.logGroupArn ?? "") |
| 484 | .sort() |
| 485 | .join(","); |
| 486 | return arnsOf(observed) !== arnsOf(desired); |
| 487 | }; |
| 488 | |
| 489 | /** |
| 490 | * IAM changes (new roles, fresh trust policies) propagate to Step Functions |
| 491 | * eventually; a create right after role creation can transiently fail with |
| 492 | * `AccessDeniedException`. Bounded retry, explicitly typed so declaration |
| 493 | * emit never widens the provider layer (see PATTERNS §7). |
| 494 | */ |
| 495 | const retryWhileRolePropagates = <A, E extends { _tag: string }, R>( |
| 496 | self: Effect.Effect<A, E, R>, |
| 497 | ): Effect.Effect<A, E, R> => |
| 498 | Effect.retry(self, { |
| 499 | while: (e) => e._tag === "AccessDeniedException", |
| 500 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]), |
| 501 | }); |
| 502 | |
| 503 | /** |
| 504 | * A state machine of the same name may still be `DELETING` from a prior |
| 505 | * destroy; creation returns the typed `StateMachineDeleting` until the |
| 506 | * deletion completes. Bounded retry (~60s). |
| 507 | */ |
| 508 | const retryWhileDeleting = <A, E extends { _tag: string }, R>( |
| 509 | self: Effect.Effect<A, E, R>, |
| 510 | ): Effect.Effect<A, E, R> => |
| 511 | Effect.retry(self, { |
| 512 | while: (e) => e._tag === "StateMachineDeleting", |
| 513 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]), |
| 514 | }); |
| 515 | |
| 516 | export const StateMachineProvider = () => |
| 517 | Provider.effect( |
| 518 | StateMachine, |
| 519 | Effect.gen(function* () { |
| 520 | const createName = Effect.fn(function* ( |
| 521 | id: string, |
| 522 | props: Pick<StateMachineProps, "stateMachineName">, |
| 523 | ) { |
| 524 | return props.stateMachineName ?? (yield* createPhysicalName({ id, maxLength: 80 })); |
| 525 | }); |
| 526 | |
| 527 | const createRoleName = (id: string) => createPhysicalName({ id, maxLength: 64 }); |
| 528 | |
| 529 | const createPolicyName = (id: string) => createPhysicalName({ id, maxLength: 128 }); |
| 530 | |
| 531 | const stateMachineArnOf = (region: string, accountId: string, name: string) => |
| 532 | `arn:aws:states:${region}:${accountId}:stateMachine:${name}`; |
| 533 | |
| 534 | const describeOrUndefined = Effect.fn(function* (stateMachineArn: string) { |
| 535 | return yield* sfn |
| 536 | .describeStateMachine({ stateMachineArn }) |
| 537 | .pipe(Effect.catchTag("StateMachineDoesNotExist", () => Effect.undefined)); |
| 538 | }); |
| 539 | |
| 540 | /** |
| 541 | * Pre-flight the serialized definition through the vendor validator |
| 542 | * so a definitively invalid document fails with typed diagnostics |
| 543 | * before any create/update call. Best-effort: if the validate call |
| 544 | * itself fails (missing IAM permission, throttling), reconcile |
| 545 | * proceeds and create/updateStateMachine remains the authority. |
| 546 | */ |
| 547 | const preflightValidateDefinition = Effect.fn(function* ( |
| 548 | definition: string, |
| 549 | type: StateMachineType, |
| 550 | ) { |
| 551 | const report = yield* sfn |
| 552 | .validateStateMachineDefinition({ |
| 553 | definition, |
| 554 | type, |
| 555 | severity: "ERROR", |
| 556 | }) |
| 557 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 558 | if (report !== undefined && report.result === "FAIL") { |
| 559 | return yield* new InvalidStateMachineDefinition({ |
| 560 | diagnostics: report.diagnostics.map((diagnostic) => ({ |
| 561 | severity: diagnostic.severity, |
| 562 | code: plain(diagnostic.code), |
| 563 | message: plain(diagnostic.message), |
| 564 | location: diagnostic.location === undefined ? undefined : plain(diagnostic.location), |
| 565 | })), |
| 566 | }); |
| 567 | } |
| 568 | }); |
| 569 | |
| 570 | const fetchObservedTags = Effect.fn(function* (resourceArn: string) { |
| 571 | return yield* sfn.listTagsForResource({ resourceArn }).pipe( |
| 572 | Effect.map((r) => fromSfnTags(r.tags)), |
| 573 | Effect.catchTag("ResourceNotFound", () => Effect.succeed({} as Record<string, string>)), |
| 574 | ); |
| 575 | }); |
| 576 | |
| 577 | /** |
| 578 | * Compute the full inline-policy statement list for the auto-created |
| 579 | * execution role: Lambda invoke grants scanned from the definition, |
| 580 | * user statements, binding-contributed statements, and CloudWatch |
| 581 | * Logs delivery permissions when logging is enabled. |
| 582 | */ |
| 583 | const buildRolePolicyStatements = ( |
| 584 | definition: string, |
| 585 | news: StateMachineProps, |
| 586 | bindings: ResourceBinding<StateMachine["Binding"]>[], |
| 587 | ): PolicyStatement[] => { |
| 588 | const statements: PolicyStatement[] = []; |
| 589 | const lambdaArns = scanLambdaArns(definition); |
| 590 | if (lambdaArns.length > 0) { |
| 591 | statements.push({ |
| 592 | Effect: "Allow", |
| 593 | Action: ["lambda:InvokeFunction"], |
| 594 | Resource: [ |
| 595 | ...lambdaArns, |
| 596 | // cover qualified invocations (versions/aliases) |
| 597 | ...lambdaArns.filter((arn) => !/:function:[^:]+:/.test(arn)).map((arn) => `${arn}:*`), |
| 598 | ], |
| 599 | }); |
| 600 | } |
| 601 | if (news.logging && news.logging.level !== "OFF") { |
| 602 | statements.push({ |
| 603 | Effect: "Allow", |
| 604 | Action: LOG_DELIVERY_ACTIONS, |
| 605 | Resource: ["*"], |
| 606 | }); |
| 607 | } |
| 608 | if (news.tracingEnabled) { |
| 609 | statements.push({ |
| 610 | Effect: "Allow", |
| 611 | Action: [ |
| 612 | "xray:PutTraceSegments", |
| 613 | "xray:PutTelemetryRecords", |
| 614 | "xray:GetSamplingRules", |
| 615 | "xray:GetSamplingTargets", |
| 616 | ], |
| 617 | Resource: ["*"], |
| 618 | }); |
| 619 | } |
| 620 | statements.push(...(news.policyStatements ?? [])); |
| 621 | statements.push(...bindings.flatMap((b) => b.data.policyStatements)); |
| 622 | return statements; |
| 623 | }; |
| 624 | |
| 625 | /** |
| 626 | * Ensure the auto-created execution role exists with the |
| 627 | * `states.amazonaws.com` trust policy and the desired inline policy. |
| 628 | * Idempotent: tolerates the role already existing and converges the |
| 629 | * inline policy on every reconcile. |
| 630 | */ |
| 631 | const ensureExecutionRole = Effect.fn(function* ({ |
| 632 | id, |
| 633 | roleName, |
| 634 | policyName, |
| 635 | statements, |
| 636 | }: { |
| 637 | id: string; |
| 638 | roleName: string; |
| 639 | policyName: string; |
| 640 | statements: PolicyStatement[]; |
| 641 | }) { |
| 642 | const tags = yield* createInternalTags(id); |
| 643 | const role = yield* iam |
| 644 | .createRole({ |
| 645 | RoleName: roleName, |
| 646 | AssumeRolePolicyDocument: JSON.stringify({ |
| 647 | Version: "2012-10-17", |
| 648 | Statement: [ |
| 649 | { |
| 650 | Effect: "Allow", |
| 651 | Principal: { Service: "states.amazonaws.com" }, |
| 652 | Action: "sts:AssumeRole", |
| 653 | }, |
| 654 | ], |
| 655 | }), |
| 656 | Tags: Object.entries(tags).map(([Key, Value]) => ({ Key, Value })), |
| 657 | }) |
| 658 | .pipe( |
| 659 | Effect.catchTag("EntityAlreadyExistsException", () => |
| 660 | iam.getRole({ RoleName: roleName }), |
| 661 | ), |
| 662 | ); |
| 663 | |
| 664 | if (statements.length > 0) { |
| 665 | yield* iam.putRolePolicy({ |
| 666 | RoleName: roleName, |
| 667 | PolicyName: policyName, |
| 668 | PolicyDocument: JSON.stringify({ |
| 669 | Version: "2012-10-17", |
| 670 | Statement: statements, |
| 671 | }), |
| 672 | }); |
| 673 | } else { |
| 674 | yield* iam |
| 675 | .deleteRolePolicy({ RoleName: roleName, PolicyName: policyName }) |
| 676 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 677 | } |
| 678 | |
| 679 | return role.Role.Arn; |
| 680 | }); |
| 681 | |
| 682 | /** |
| 683 | * Everything reconcile converges on a state machine, as observed. |
| 684 | * `read` and `reconcile` share it so a converged machine reads |
| 685 | * unchanged. |
| 686 | */ |
| 687 | const observeStateMachineConfiguration = Effect.fn(function* ( |
| 688 | id: string, |
| 689 | machine: sfn.DescribeStateMachineOutput, |
| 690 | roleName: string | undefined, |
| 691 | ) { |
| 692 | const level = machine.loggingConfiguration?.level ?? "OFF"; |
| 693 | const [tags, executionRolePolicy] = yield* Effect.all( |
| 694 | [ |
| 695 | fetchObservedTags(machine.stateMachineArn), |
| 696 | roleName === undefined |
| 697 | ? Effect.undefined |
| 698 | : iam |
| 699 | .getRolePolicy({ |
| 700 | RoleName: roleName, |
| 701 | PolicyName: yield* createPolicyName(id), |
| 702 | }) |
| 703 | .pipe( |
| 704 | Effect.map((policy): unknown => |
| 705 | JSON.parse(decodeURIComponent(policy.PolicyDocument)), |
| 706 | ), |
| 707 | Effect.catchTag("NoSuchEntityException", () => Effect.undefined), |
| 708 | ), |
| 709 | ], |
| 710 | { concurrency: "unbounded" }, |
| 711 | ); |
| 712 | return { |
| 713 | definition: normalizeDefinition(plain(machine.definition)), |
| 714 | logging: |
| 715 | level === "OFF" |
| 716 | ? { level } |
| 717 | : { |
| 718 | level, |
| 719 | includeExecutionData: machine.loggingConfiguration?.includeExecutionData ?? false, |
| 720 | destinations: (machine.loggingConfiguration?.destinations ?? []) |
| 721 | .map((d) => d.cloudWatchLogsLogGroup?.logGroupArn ?? "") |
| 722 | .sort(), |
| 723 | }, |
| 724 | tracingEnabled: machine.tracingConfiguration?.enabled ?? false, |
| 725 | tags, |
| 726 | executionRolePolicy, |
| 727 | }; |
| 728 | }); |
| 729 | |
| 730 | return StateMachine.Provider.of({ |
| 731 | stables: ["stateMachineName", "stateMachineArn", "type"], |
| 732 | |
| 733 | list: () => |
| 734 | Effect.gen(function* () { |
| 735 | const pages = yield* sfn.listStateMachines.pages({}).pipe(Stream.runCollect); |
| 736 | const items = Array.from(pages).flatMap((page) => page.stateMachines ?? []); |
| 737 | const results = yield* Effect.forEach( |
| 738 | items, |
| 739 | (item) => |
| 740 | sfn |
| 741 | .describeStateMachine({ |
| 742 | stateMachineArn: item.stateMachineArn, |
| 743 | }) |
| 744 | .pipe( |
| 745 | // name/roleArn are optional on the wire; a machine |
| 746 | // missing either cannot be expressed as Attributes. |
| 747 | Effect.map((machine) => |
| 748 | machine.name != null && |
| 749 | machine.stateMachineArn != null && |
| 750 | machine.roleArn != null |
| 751 | ? { |
| 752 | stateMachineName: machine.name, |
| 753 | stateMachineArn: machine.stateMachineArn, |
| 754 | type: machine.type as StateMachineType, |
| 755 | roleArn: machine.roleArn, |
| 756 | roleName: undefined as string | undefined, |
| 757 | } |
| 758 | : undefined, |
| 759 | ), |
| 760 | Effect.catchTag("StateMachineDoesNotExist", () => Effect.undefined), |
| 761 | ), |
| 762 | { concurrency: 5 }, |
| 763 | ); |
| 764 | return results.filter((item): item is StateMachine["Attributes"] => item !== undefined); |
| 765 | }), |
| 766 | |
| 767 | read: Effect.fn(function* ({ id, olds, output }) { |
| 768 | const { accountId, region } = yield* AWSEnvironment.current; |
| 769 | const name = output?.stateMachineName ?? (yield* createName(id, olds ?? {})); |
| 770 | const stateMachineArn = |
| 771 | output?.stateMachineArn ?? stateMachineArnOf(region, accountId, name); |
| 772 | const found = yield* describeOrUndefined(stateMachineArn); |
| 773 | if (!found || found.status === "DELETING") return undefined; |
| 774 | const configuration = yield* observeStateMachineConfiguration( |
| 775 | id, |
| 776 | found, |
| 777 | output?.roleName, |
| 778 | ); |
| 779 | const attrs = { |
| 780 | stateMachineName: found.name, |
| 781 | stateMachineArn: found.stateMachineArn, |
| 782 | type: found.type as StateMachineType, |
| 783 | roleArn: found.roleArn, |
| 784 | roleName: output?.roleName, |
| 785 | configuration, |
| 786 | }; |
| 787 | return (yield* hasAlchemyTags(id, configuration.tags)) ? attrs : Unowned(attrs); |
| 788 | }), |
| 789 | |
| 790 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 791 | if (!isResolved(news)) return undefined; |
| 792 | const oldName = yield* createName(id, olds ?? {}); |
| 793 | const newName = yield* createName(id, news ?? {}); |
| 794 | if (oldName !== newName) { |
| 795 | return { action: "replace" } as const; |
| 796 | } |
| 797 | if ((olds?.type ?? "STANDARD") !== (news?.type ?? "STANDARD")) { |
| 798 | return { action: "replace" } as const; |
| 799 | } |
| 800 | // definition/role/logging/tracing/tags converge via update |
| 801 | }), |
| 802 | |
| 803 | reconcile: Effect.fn(function* ({ id, news, output, session, bindings }) { |
| 804 | const { accountId, region } = yield* AWSEnvironment.current; |
| 805 | const name = output?.stateMachineName ?? (yield* createName(id, news)); |
| 806 | const stateMachineArn = stateMachineArnOf(region, accountId, name); |
| 807 | const type = (news.type ?? "STANDARD") as StateMachineType; |
| 808 | const definition = serializeDefinition(news); |
| 809 | const desiredLogging = toWireLogging(news.logging); |
| 810 | const desiredTracing = { enabled: news.tracingEnabled ?? false }; |
| 811 | const internalTags = yield* createInternalTags(id); |
| 812 | const desiredTags = { ...news.tags, ...internalTags }; |
| 813 | |
| 814 | // Pre-flight: fail with typed diagnostics before touching IAM or |
| 815 | // the machine when the definition is definitively invalid. |
| 816 | yield* preflightValidateDefinition(definition, type); |
| 817 | |
| 818 | // Ensure the execution role first — the machine cannot exist |
| 819 | // without one. Managed unless an explicit roleArn is provided. |
| 820 | let roleArn = news.roleArn; |
| 821 | let roleName: string | undefined; |
| 822 | if (roleArn === undefined) { |
| 823 | roleName = yield* createRoleName(id); |
| 824 | const policyName = yield* createPolicyName(id); |
| 825 | roleArn = yield* ensureExecutionRole({ |
| 826 | id, |
| 827 | roleName, |
| 828 | policyName, |
| 829 | statements: buildRolePolicyStatements(definition, news, bindings), |
| 830 | }); |
| 831 | } |
| 832 | |
| 833 | // 1. OBSERVE — cloud state is authoritative; `output` is only a |
| 834 | // name cache. A machine still DELETING from a prior destroy |
| 835 | // must finish deleting before we can recreate it. |
| 836 | const observed = yield* describeOrUndefined(stateMachineArn).pipe( |
| 837 | Effect.map((machine) => (machine?.status === "DELETING" ? undefined : machine)), |
| 838 | ); |
| 839 | |
| 840 | if (observed === undefined) { |
| 841 | // 2. ENSURE — create; tolerate the concurrent-create race and |
| 842 | // wait out a same-name deletion or IAM propagation delay. |
| 843 | yield* sfn |
| 844 | .createStateMachine({ |
| 845 | name, |
| 846 | definition, |
| 847 | roleArn, |
| 848 | type, |
| 849 | loggingConfiguration: desiredLogging, |
| 850 | tracingConfiguration: desiredTracing, |
| 851 | tags: toSfnTags(desiredTags), |
| 852 | }) |
| 853 | .pipe( |
| 854 | Effect.catchTag("StateMachineAlreadyExists", () => Effect.undefined), |
| 855 | retryWhileDeleting, |
| 856 | retryWhileRolePropagates, |
| 857 | ); |
| 858 | } else { |
| 859 | // 3. SYNC — diff OBSERVED cloud state against desired and issue |
| 860 | // a single update only when something actually drifted. |
| 861 | const drifted = |
| 862 | normalizeDefinition(plain(observed.definition)) !== normalizeDefinition(definition) || |
| 863 | observed.roleArn !== roleArn || |
| 864 | loggingDrifted(observed.loggingConfiguration, desiredLogging) || |
| 865 | (observed.tracingConfiguration?.enabled ?? false) !== desiredTracing.enabled; |
| 866 | if (drifted) { |
| 867 | yield* retryWhileRolePropagates( |
| 868 | sfn.updateStateMachine({ |
| 869 | stateMachineArn, |
| 870 | definition, |
| 871 | roleArn, |
| 872 | loggingConfiguration: desiredLogging ?? { level: "OFF" }, |
| 873 | tracingConfiguration: desiredTracing, |
| 874 | }), |
| 875 | ); |
| 876 | // Updates propagate eventually (typically seconds). Poll the |
| 877 | // describe endpoint (bounded) so subsequent reads observe the |
| 878 | // new revision; proceed best-effort if it hasn't settled. |
| 879 | yield* describeOrUndefined(stateMachineArn).pipe( |
| 880 | Effect.repeat({ |
| 881 | schedule: Schedule.fixed("1 second"), |
| 882 | until: (machine) => |
| 883 | machine === undefined || |
| 884 | normalizeDefinition(plain(machine.definition)) === |
| 885 | normalizeDefinition(definition), |
| 886 | times: 20, |
| 887 | }), |
| 888 | ); |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | // 3b. SYNC TAGS — against OBSERVED cloud tags so adoption |
| 893 | // converges (create-time tags only apply on first create). |
| 894 | const observedTags = yield* fetchObservedTags(stateMachineArn); |
| 895 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 896 | if (upsert.length > 0) { |
| 897 | yield* sfn.tagResource({ |
| 898 | resourceArn: stateMachineArn, |
| 899 | tags: upsert.map(({ Key, Value }) => ({ |
| 900 | key: Key, |
| 901 | value: Value, |
| 902 | })), |
| 903 | }); |
| 904 | } |
| 905 | if (removed.length > 0) { |
| 906 | yield* sfn.untagResource({ |
| 907 | resourceArn: stateMachineArn, |
| 908 | tagKeys: removed, |
| 909 | }); |
| 910 | } |
| 911 | |
| 912 | yield* session.note(stateMachineArn); |
| 913 | const final = yield* sfn.describeStateMachine({ stateMachineArn }); |
| 914 | return { |
| 915 | stateMachineName: name, |
| 916 | stateMachineArn, |
| 917 | type, |
| 918 | roleArn, |
| 919 | roleName, |
| 920 | configuration: yield* observeStateMachineConfiguration(id, final, roleName), |
| 921 | }; |
| 922 | }), |
| 923 | |
| 924 | delete: Effect.fn(function* ({ output }) { |
| 925 | // deleteStateMachine is idempotent (no error when already gone) |
| 926 | // and asynchronous — the machine transitions through DELETING. |
| 927 | yield* sfn.deleteStateMachine({ |
| 928 | stateMachineArn: output.stateMachineArn, |
| 929 | }); |
| 930 | |
| 931 | // Tear down the managed execution role (absent when the user |
| 932 | // supplied an explicit roleArn). Every step tolerates the role |
| 933 | // being partially or fully gone already. |
| 934 | if (output.roleName !== undefined) { |
| 935 | const roleName = output.roleName; |
| 936 | yield* iam.listRolePolicies.items({ RoleName: roleName }).pipe( |
| 937 | Stream.mapEffect((policyName) => |
| 938 | iam |
| 939 | .deleteRolePolicy({ |
| 940 | RoleName: roleName, |
| 941 | PolicyName: policyName, |
| 942 | }) |
| 943 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)), |
| 944 | ), |
| 945 | Stream.runDrain, |
| 946 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 947 | ); |
| 948 | yield* iam |
| 949 | .deleteRole({ RoleName: roleName }) |
| 950 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 951 | } |
| 952 | }), |
| 953 | }); |
| 954 | }), |
| 955 | ); |