The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as eventbridge from "@distilled.cloud/aws/eventbridge"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import type { Input } from "alchemy/Input"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource } from "alchemy/Resource"; |
| 8 | import { |
| 9 | createInternalTags, |
| 10 | createTagsList, |
| 11 | diffTags, |
| 12 | hasAlchemyTags, |
| 13 | tagRecord, |
| 14 | } from "alchemy/Tags"; |
| 15 | import * as Data from "effect/Data"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import { AWSEnvironment, type AccountID } from "../Environment.ts"; |
| 18 | import { canonicalJson } from "../internal/Observe.ts"; |
| 19 | import type { Providers } from "../Providers.ts"; |
| 20 | import type { RegionID } from "../Region.ts"; |
| 21 | |
| 22 | export class RuleInvalidProps extends Data.TaggedError("RuleInvalidProps")<{ |
| 23 | readonly message: string; |
| 24 | readonly cause?: unknown; |
| 25 | }> {} |
| 26 | |
| 27 | export class RuleOperationFailed extends Data.TaggedError("RuleOperationFailed")<{ |
| 28 | readonly message: string; |
| 29 | readonly cause?: unknown; |
| 30 | }> {} |
| 31 | |
| 32 | export type { |
| 33 | AppSyncParameters, |
| 34 | AssignPublicIp, |
| 35 | AwsVpcConfiguration, |
| 36 | CapacityProviderStrategyItem, |
| 37 | HttpParameters, |
| 38 | InputTransformer, |
| 39 | KinesisParameters, |
| 40 | LaunchType, |
| 41 | NetworkConfiguration, |
| 42 | PlacementConstraint, |
| 43 | PlacementConstraintType, |
| 44 | PlacementStrategy, |
| 45 | PlacementStrategyType, |
| 46 | PropagateTags, |
| 47 | RedshiftDataParameters, |
| 48 | RetryPolicy, |
| 49 | RuleState, |
| 50 | RunCommandParameters, |
| 51 | RunCommandTarget, |
| 52 | SageMakerPipelineParameter, |
| 53 | SageMakerPipelineParameters, |
| 54 | SqsParameters, |
| 55 | } from "@distilled.cloud/aws/eventbridge"; |
| 56 | |
| 57 | export type RuleName = string; |
| 58 | |
| 59 | export type RuleArn = `arn:aws:events:${RegionID}:${AccountID}:rule/${string}`; |
| 60 | |
| 61 | export interface RuleTarget { |
| 62 | /** Unique identifier for this target within the rule. */ |
| 63 | Id: string; |
| 64 | /** ARN of the target resource. */ |
| 65 | Arn: string; |
| 66 | /** ARN of the IAM role to use for this target when the rule is triggered. */ |
| 67 | RoleArn?: string; |
| 68 | /** Valid JSON text passed to the target. Mutually exclusive with InputPath and InputTransformer. */ |
| 69 | Input?: string; |
| 70 | /** JSONPath expression to extract from the event and send to the target. Mutually exclusive with Input and InputTransformer. */ |
| 71 | InputPath?: string; |
| 72 | /** Settings to transform input before sending to the target. Mutually exclusive with Input and InputPath. */ |
| 73 | InputTransformer?: eventbridge.InputTransformer; |
| 74 | /** Settings for a Kinesis Data Stream target. */ |
| 75 | KinesisParameters?: eventbridge.KinesisParameters; |
| 76 | /** Parameters for Systems Manager Run Command targets. */ |
| 77 | RunCommandParameters?: eventbridge.RunCommandParameters; |
| 78 | /** Parameters for ECS task targets. */ |
| 79 | EcsParameters?: RuleTargetEcsParameters; |
| 80 | /** Parameters for AWS Batch job targets. */ |
| 81 | BatchParameters?: RuleTargetBatchParameters; |
| 82 | /** Parameters for SQS queue targets (e.g., FIFO message group ID). */ |
| 83 | SqsParameters?: eventbridge.SqsParameters; |
| 84 | /** Parameters for HTTP endpoint targets (API Gateway, API Destinations). */ |
| 85 | HttpParameters?: eventbridge.HttpParameters; |
| 86 | /** Parameters for Amazon Redshift Data API targets. */ |
| 87 | RedshiftDataParameters?: eventbridge.RedshiftDataParameters; |
| 88 | /** Parameters for SageMaker Pipeline targets. */ |
| 89 | SageMakerPipelineParameters?: eventbridge.SageMakerPipelineParameters; |
| 90 | /** Dead-letter queue configuration for failed event delivery. */ |
| 91 | DeadLetterConfig?: RuleTargetDeadLetterConfig; |
| 92 | /** Retry policy settings for the target. */ |
| 93 | RetryPolicy?: eventbridge.RetryPolicy; |
| 94 | /** Parameters for AWS AppSync GraphQL API targets. */ |
| 95 | AppSyncParameters?: eventbridge.AppSyncParameters; |
| 96 | } |
| 97 | |
| 98 | /** ECS parameters for a rule target with Input-wrapped ARN fields. */ |
| 99 | export interface RuleTargetEcsParameters extends Omit< |
| 100 | eventbridge.EcsParameters, |
| 101 | "TaskDefinitionArn" |
| 102 | > { |
| 103 | /** ARN of the ECS task definition to run. */ |
| 104 | TaskDefinitionArn: string; |
| 105 | } |
| 106 | |
| 107 | /** Batch parameters for a rule target with Input-wrapped ARN fields. */ |
| 108 | export interface RuleTargetBatchParameters extends Omit< |
| 109 | eventbridge.BatchParameters, |
| 110 | "JobDefinition" |
| 111 | > { |
| 112 | /** ARN or name of the Batch job definition. */ |
| 113 | JobDefinition: string; |
| 114 | } |
| 115 | |
| 116 | /** Dead-letter config for a rule target with Input-wrapped ARN. */ |
| 117 | export interface RuleTargetDeadLetterConfig { |
| 118 | /** ARN of the SQS queue used as the dead-letter queue. */ |
| 119 | Arn?: string; |
| 120 | } |
| 121 | |
| 122 | export interface RuleProps { |
| 123 | /** |
| 124 | * Name of the rule. Must match [\.\-_A-Za-z0-9]+, 1-64 characters. |
| 125 | * If omitted, a unique name will be generated. |
| 126 | */ |
| 127 | name?: string; |
| 128 | |
| 129 | /** |
| 130 | * Description of the rule. Max 512 characters. |
| 131 | */ |
| 132 | description?: string; |
| 133 | |
| 134 | /** |
| 135 | * The name or ARN of the event bus to associate with this rule. |
| 136 | * If omitted, the default event bus is used. |
| 137 | */ |
| 138 | eventBusName?: string; |
| 139 | |
| 140 | /** |
| 141 | * The event pattern that triggers this rule. Specified as a JSON-compatible object. |
| 142 | * A rule must contain at least an eventPattern or scheduleExpression. |
| 143 | */ |
| 144 | eventPattern?: Record<string, any>; |
| 145 | |
| 146 | /** |
| 147 | * The scheduling expression (e.g. "rate(5 minutes)", "cron(0 20 * * ? *)"). |
| 148 | * A rule must contain at least an eventPattern or scheduleExpression. |
| 149 | */ |
| 150 | scheduleExpression?: string; |
| 151 | |
| 152 | /** |
| 153 | * Whether the rule is enabled or disabled. |
| 154 | * @default "ENABLED" |
| 155 | */ |
| 156 | state?: eventbridge.RuleState; |
| 157 | |
| 158 | /** |
| 159 | * ARN of the IAM role associated with the rule. Required for targets that need |
| 160 | * IAM roles (e.g. Kinesis, Step Functions, ECS, API Gateway). |
| 161 | */ |
| 162 | roleArn?: string; |
| 163 | |
| 164 | /** |
| 165 | * The targets to invoke when this rule is triggered. Maximum 5 targets per rule. |
| 166 | */ |
| 167 | targets?: RuleTarget[]; |
| 168 | |
| 169 | /** |
| 170 | * Tags to assign to the rule. |
| 171 | */ |
| 172 | tags?: Record<string, string>; |
| 173 | } |
| 174 | |
| 175 | /** |
| 176 | * An Amazon EventBridge rule that matches events and routes them to targets. |
| 177 | * ### Creating Rules |
| 178 | * **Example:** Event Pattern Rule |
| 179 | * ```typescript |
| 180 | * const rule = yield* Rule("S3Events", { |
| 181 | * eventPattern: { |
| 182 | * source: ["aws.s3"], |
| 183 | * "detail-type": ["Object Created"], |
| 184 | * }, |
| 185 | * targets: [{ |
| 186 | * Id: "MyTarget", |
| 187 | * Arn: yield* queue.queueArn, |
| 188 | * }], |
| 189 | * }); |
| 190 | * ``` |
| 191 | * |
| 192 | * **Example:** Scheduled Rule |
| 193 | * ```typescript |
| 194 | * const rule = yield* Rule("EveryFiveMinutes", { |
| 195 | * scheduleExpression: "rate(5 minutes)", |
| 196 | * targets: [{ |
| 197 | * Id: "LambdaTarget", |
| 198 | * Arn: yield* fn.functionArn(), |
| 199 | * }], |
| 200 | * }); |
| 201 | * ``` |
| 202 | * |
| 203 | * ### Targeting |
| 204 | * **Example:** Rule with Input Transformer |
| 205 | * ```typescript |
| 206 | * const rule = yield* Rule("TransformedEvents", { |
| 207 | * eventPattern: { |
| 208 | * source: ["aws.ec2"], |
| 209 | * "detail-type": ["EC2 Instance State-change Notification"], |
| 210 | * }, |
| 211 | * targets: [{ |
| 212 | * Id: "SqsTarget", |
| 213 | * Arn: yield* queue.queueArn, |
| 214 | * InputTransformer: { |
| 215 | * InputPathsMap: { |
| 216 | * instance: "$.detail.instance-id", |
| 217 | * state: "$.detail.state", |
| 218 | * }, |
| 219 | * InputTemplate: '{"instanceId": <instance>, "newState": <state>}', |
| 220 | * }, |
| 221 | * }], |
| 222 | * }); |
| 223 | * ``` |
| 224 | * |
| 225 | * **Example:** Rule with Dead Letter Queue |
| 226 | * ```typescript |
| 227 | * const rule = yield* Rule("ReliableEvents", { |
| 228 | * eventPattern: { source: ["my.app"] }, |
| 229 | * targets: [{ |
| 230 | * Id: "Target", |
| 231 | * Arn: yield* fn.functionArn(), |
| 232 | * DeadLetterConfig: { |
| 233 | * Arn: yield* dlq.queueArn, |
| 234 | * }, |
| 235 | * RetryPolicy: { |
| 236 | * MaximumRetryAttempts: 3, |
| 237 | * MaximumEventAgeInSeconds: 3600, |
| 238 | * }, |
| 239 | * }], |
| 240 | * }); |
| 241 | * ``` |
| 242 | * |
| 243 | * **Example:** Rule with ECS Target |
| 244 | * ```typescript |
| 245 | * const rule = yield* Rule("EcsSchedule", { |
| 246 | * scheduleExpression: "rate(1 hour)", |
| 247 | * roleArn: yield* role.roleArn(), |
| 248 | * targets: [{ |
| 249 | * Id: "EcsTask", |
| 250 | * Arn: yield* cluster.clusterArn(), |
| 251 | * RoleArn: yield* ecsRole.roleArn(), |
| 252 | * EcsParameters: { |
| 253 | * TaskDefinitionArn: yield* taskDef.taskDefinitionArn(), |
| 254 | * TaskCount: 1, |
| 255 | * LaunchType: "FARGATE", |
| 256 | * NetworkConfiguration: { |
| 257 | * awsvpcConfiguration: { |
| 258 | * Subnets: ["subnet-abc123"], |
| 259 | * AssignPublicIp: "ENABLED", |
| 260 | * }, |
| 261 | * }, |
| 262 | * }, |
| 263 | * }], |
| 264 | * }); |
| 265 | * ``` |
| 266 | * |
| 267 | * @resource |
| 268 | */ |
| 269 | export interface Rule extends Resource< |
| 270 | "AWS.EventBridge.Rule", |
| 271 | RuleProps, |
| 272 | { |
| 273 | /** The name of the rule. */ |
| 274 | ruleName: RuleName; |
| 275 | /** The ARN of the rule. */ |
| 276 | ruleArn: RuleArn; |
| 277 | /** The event bus associated with the rule. */ |
| 278 | eventBusName: string; |
| 279 | /** |
| 280 | * The rule definition (pattern, schedule, state, role, description), its |
| 281 | * targets and its tags, as observed. Lets `alchemy drift` detect |
| 282 | * out-of-band changes. |
| 283 | */ |
| 284 | configuration?: { |
| 285 | description?: string; |
| 286 | eventPattern?: string; |
| 287 | scheduleExpression?: string; |
| 288 | state?: string; |
| 289 | roleArn?: string; |
| 290 | targets: eventbridge.Target[]; |
| 291 | tags: Record<string, string>; |
| 292 | }; |
| 293 | }, |
| 294 | never, |
| 295 | Providers |
| 296 | > {} |
| 297 | export const Rule = Resource<Rule>("AWS.EventBridge.Rule"); |
| 298 | |
| 299 | export const RuleProvider = () => |
| 300 | Provider.effect( |
| 301 | Rule, |
| 302 | Effect.gen(function* () { |
| 303 | const createRuleName = (id: string, props: { name?: string } = {}) => { |
| 304 | if (props.name) { |
| 305 | return Effect.succeed(props.name); |
| 306 | } |
| 307 | return createPhysicalName({ |
| 308 | id, |
| 309 | maxLength: 64, |
| 310 | }); |
| 311 | }; |
| 312 | |
| 313 | /** |
| 314 | * Everything reconcile converges on a rule, as observed. `read` and |
| 315 | * `reconcile` share it so a converged rule reads unchanged. |
| 316 | */ |
| 317 | const observeRuleConfiguration = Effect.fn(function* ( |
| 318 | described: eventbridge.DescribeRuleResponse, |
| 319 | eventBusParam: string | undefined, |
| 320 | tags: eventbridge.Tag[], |
| 321 | ) { |
| 322 | const targets = yield* eventbridge |
| 323 | .listTargetsByRule({ Rule: described.Name!, EventBusName: eventBusParam }) |
| 324 | .pipe( |
| 325 | Effect.map((r) => r.Targets ?? []), |
| 326 | Effect.catchTag("ResourceNotFoundException", () => |
| 327 | Effect.succeed([] as eventbridge.Target[]), |
| 328 | ), |
| 329 | ); |
| 330 | return { |
| 331 | description: described.Description || undefined, |
| 332 | eventPattern: canonicalJson(described.EventPattern), |
| 333 | scheduleExpression: described.ScheduleExpression, |
| 334 | state: described.State, |
| 335 | roleArn: described.RoleArn, |
| 336 | targets: [...targets].sort((a, b) => a.Id.localeCompare(b.Id)), |
| 337 | tags: tagRecord(tags), |
| 338 | }; |
| 339 | }); |
| 340 | |
| 341 | return { |
| 342 | stables: ["ruleName", "ruleArn", "eventBusName"], |
| 343 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 344 | if (!isResolved(news)) return; |
| 345 | const oldName = yield* createRuleName(id, olds); |
| 346 | const newName = yield* createRuleName(id, news); |
| 347 | if (oldName !== newName) { |
| 348 | return { action: "replace" } as const; |
| 349 | } |
| 350 | const oldBus = (olds.eventBusName as string | undefined) ?? "default"; |
| 351 | const newBus = (news.eventBusName as string | undefined) ?? "default"; |
| 352 | if (oldBus !== newBus) { |
| 353 | return { action: "replace" } as const; |
| 354 | } |
| 355 | }), |
| 356 | read: Effect.fn(function* ({ id, olds, output }) { |
| 357 | const { accountId, region } = yield* AWSEnvironment.current; |
| 358 | // The engine guarantees `olds` is fully resolved before calling |
| 359 | // `read` (Plan.ts guards every read site with `isResolved`), so |
| 360 | // props can be used directly to derive identity. |
| 361 | const ruleName = output?.ruleName ?? (yield* createRuleName(id, { name: olds?.name })); |
| 362 | const eventBusName = output?.eventBusName ?? olds?.eventBusName ?? "default"; |
| 363 | const described = yield* eventbridge |
| 364 | .describeRule({ |
| 365 | Name: ruleName, |
| 366 | EventBusName: eventBusName !== "default" ? eventBusName : undefined, |
| 367 | }) |
| 368 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 369 | |
| 370 | if (!described?.Name) { |
| 371 | return undefined; |
| 372 | } |
| 373 | |
| 374 | const resolvedEventBusName = described.EventBusName ?? eventBusName; |
| 375 | const ruleArn = toRuleArn(region, accountId, resolvedEventBusName, described.Name); |
| 376 | const { Tags } = yield* eventbridge.listTagsForResource({ |
| 377 | ResourceARN: described.Arn ?? ruleArn, |
| 378 | }); |
| 379 | const attrs = { |
| 380 | ruleName: described.Name, |
| 381 | ruleArn, |
| 382 | eventBusName: resolvedEventBusName, |
| 383 | configuration: yield* observeRuleConfiguration( |
| 384 | described, |
| 385 | resolvedEventBusName !== "default" ? resolvedEventBusName : undefined, |
| 386 | Tags ?? [], |
| 387 | ), |
| 388 | }; |
| 389 | return (yield* hasAlchemyTags(id, Tags ?? [])) ? attrs : Unowned(attrs); |
| 390 | }), |
| 391 | list: () => |
| 392 | Effect.gen(function* () { |
| 393 | const { accountId, region } = yield* AWSEnvironment.current; |
| 394 | // A Rule belongs to an event bus and `listRules` is scoped to one |
| 395 | // bus (defaulting to "default"). To enumerate every rule in the |
| 396 | // account/region we first enumerate all event buses (manual |
| 397 | // NextToken pagination — neither op is a paginated distilled op), |
| 398 | // then list rules per bus with bounded concurrency. |
| 399 | const busNames: string[] = []; |
| 400 | let busToken: string | undefined; |
| 401 | do { |
| 402 | const page = yield* eventbridge.listEventBuses({ |
| 403 | NextToken: busToken, |
| 404 | }); |
| 405 | for (const bus of page.EventBuses ?? []) { |
| 406 | if (bus.Name) { |
| 407 | busNames.push(bus.Name); |
| 408 | } |
| 409 | } |
| 410 | busToken = page.NextToken; |
| 411 | } while (busToken); |
| 412 | // `listEventBuses` should include the default bus, but guarantee it. |
| 413 | if (!busNames.includes("default")) { |
| 414 | busNames.push("default"); |
| 415 | } |
| 416 | |
| 417 | const perBus = yield* Effect.forEach( |
| 418 | busNames, |
| 419 | (busName) => |
| 420 | Effect.gen(function* () { |
| 421 | const eventBusParam = busName !== "default" ? busName : undefined; |
| 422 | const attrs: { |
| 423 | ruleName: RuleName; |
| 424 | ruleArn: RuleArn; |
| 425 | eventBusName: string; |
| 426 | }[] = []; |
| 427 | let ruleToken: string | undefined; |
| 428 | do { |
| 429 | // A peer reconciler may delete an event bus between our |
| 430 | // `listEventBuses` snapshot and this `listRules` call — |
| 431 | // treat a vanished bus as contributing zero rules rather |
| 432 | // than failing the whole enumeration. |
| 433 | const page = yield* eventbridge |
| 434 | .listRules({ |
| 435 | EventBusName: eventBusParam, |
| 436 | NextToken: ruleToken, |
| 437 | }) |
| 438 | .pipe( |
| 439 | Effect.catchTag("ResourceNotFoundException", () => |
| 440 | Effect.succeed(undefined as eventbridge.ListRulesResponse | undefined), |
| 441 | ), |
| 442 | ); |
| 443 | if (!page) { |
| 444 | break; |
| 445 | } |
| 446 | for (const rule of page.Rules ?? []) { |
| 447 | if (!rule.Name) { |
| 448 | continue; |
| 449 | } |
| 450 | // Rules created and owned by another AWS service (e.g. |
| 451 | // B2BI's DO-NOT-DELETE-* or DevOpsGuru's managed rules) |
| 452 | // reject DeleteRule without Force and are recreated by |
| 453 | // the owning service anyway — skip them in enumeration |
| 454 | // for account-wide teardown (nuke). |
| 455 | if (rule.ManagedBy) { |
| 456 | continue; |
| 457 | } |
| 458 | const resolvedBus = rule.EventBusName ?? busName; |
| 459 | attrs.push({ |
| 460 | ruleName: rule.Name, |
| 461 | ruleArn: |
| 462 | (rule.Arn as RuleArn | undefined) ?? |
| 463 | toRuleArn(region, accountId, resolvedBus, rule.Name), |
| 464 | eventBusName: resolvedBus, |
| 465 | }); |
| 466 | } |
| 467 | ruleToken = page.NextToken; |
| 468 | } while (ruleToken); |
| 469 | return attrs; |
| 470 | }), |
| 471 | { concurrency: 5 }, |
| 472 | ); |
| 473 | return perBus.flat(); |
| 474 | }), |
| 475 | reconcile: Effect.fn(function* ({ id, news = {}, output, session }) { |
| 476 | const { accountId, region } = yield* AWSEnvironment.current; |
| 477 | yield* validateRuleProps(news); |
| 478 | const ruleName = output?.ruleName ?? (yield* createRuleName(id, news)); |
| 479 | const eventBusName = |
| 480 | output?.eventBusName ?? (news.eventBusName as string | undefined) ?? "default"; |
| 481 | const eventBusParam = eventBusName !== "default" ? eventBusName : undefined; |
| 482 | const internalTags = yield* createInternalTags(id); |
| 483 | const desiredTags = { |
| 484 | ...internalTags, |
| 485 | ...(news.tags as Record<string, string> | undefined), |
| 486 | }; |
| 487 | |
| 488 | // Ensure + Sync rule definition — `putRule` is the single |
| 489 | // create-or-update API for the rule itself. It's idempotent on |
| 490 | // matching params and overwrites schedule/eventPattern/state/etc. |
| 491 | // on differences, so we call it unconditionally. `Tags` only |
| 492 | // applies when creating; tags are reconciled separately below |
| 493 | // against observed cloud tags. |
| 494 | const { RuleArn } = yield* eventbridge.putRule({ |
| 495 | Name: ruleName, |
| 496 | Description: news.description, |
| 497 | EventBusName: eventBusParam, |
| 498 | EventPattern: news.eventPattern ? JSON.stringify(news.eventPattern) : undefined, |
| 499 | ScheduleExpression: news.scheduleExpression, |
| 500 | State: news.state ?? "ENABLED", |
| 501 | RoleArn: news.roleArn as string | undefined, |
| 502 | Tags: createTagsList(desiredTags), |
| 503 | }); |
| 504 | const ruleArn = |
| 505 | (RuleArn as RuleArn | undefined) ?? |
| 506 | toRuleArn(region, accountId, eventBusName, ruleName); |
| 507 | |
| 508 | // Sync targets — observed cloud targets vs desired. `listTargetsByRule` |
| 509 | // gives us the live target ids; we remove anything no longer desired, |
| 510 | // and `putTargets` overwrites/upserts the rest. |
| 511 | const resolvedTargets = (news.targets as Input.Resolve<RuleTarget>[] | undefined) ?? []; |
| 512 | const desiredTargetIds = new Set(resolvedTargets.map((t) => t.Id)); |
| 513 | const observedTargets = yield* eventbridge |
| 514 | .listTargetsByRule({ |
| 515 | Rule: ruleName, |
| 516 | EventBusName: eventBusParam, |
| 517 | }) |
| 518 | .pipe( |
| 519 | Effect.map((r) => r.Targets ?? []), |
| 520 | Effect.catchTag("ResourceNotFoundException", () => |
| 521 | Effect.succeed([] as eventbridge.Target[]), |
| 522 | ), |
| 523 | ); |
| 524 | const removedTargetIds = observedTargets |
| 525 | .map((t) => t.Id) |
| 526 | .filter((tid): tid is string => !!tid && !desiredTargetIds.has(tid)); |
| 527 | |
| 528 | if (removedTargetIds.length > 0) { |
| 529 | const response = yield* eventbridge |
| 530 | .removeTargets({ |
| 531 | Rule: ruleName, |
| 532 | EventBusName: eventBusParam, |
| 533 | Ids: removedTargetIds, |
| 534 | }) |
| 535 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 536 | |
| 537 | if (response) { |
| 538 | yield* assertRemoveTargetsSucceeded(response); |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | if (resolvedTargets.length > 0) { |
| 543 | const response = yield* eventbridge.putTargets({ |
| 544 | Rule: ruleName, |
| 545 | EventBusName: eventBusParam, |
| 546 | Targets: resolvedTargets.map(toTarget), |
| 547 | }); |
| 548 | yield* assertPutTargetsSucceeded(response); |
| 549 | } |
| 550 | |
| 551 | // Sync tags — diff observed cloud tags against desired. Adoption |
| 552 | // and partial prior runs both converge here. |
| 553 | const observedTagsList = yield* eventbridge |
| 554 | .listTagsForResource({ |
| 555 | ResourceARN: ruleArn, |
| 556 | }) |
| 557 | .pipe(Effect.map((r) => r.Tags ?? [])); |
| 558 | const observedTags: Record<string, string> = {}; |
| 559 | for (const tag of observedTagsList) { |
| 560 | if (tag.Key && tag.Value !== undefined) { |
| 561 | observedTags[tag.Key] = tag.Value; |
| 562 | } |
| 563 | } |
| 564 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 565 | |
| 566 | if (removed.length > 0) { |
| 567 | yield* eventbridge.untagResource({ |
| 568 | ResourceARN: ruleArn, |
| 569 | TagKeys: removed, |
| 570 | }); |
| 571 | } |
| 572 | |
| 573 | if (upsert.length > 0) { |
| 574 | yield* eventbridge.tagResource({ |
| 575 | ResourceARN: ruleArn, |
| 576 | Tags: upsert, |
| 577 | }); |
| 578 | } |
| 579 | |
| 580 | yield* session.note(ruleArn); |
| 581 | const described = yield* eventbridge.describeRule({ |
| 582 | Name: ruleName, |
| 583 | EventBusName: eventBusParam, |
| 584 | }); |
| 585 | return { |
| 586 | ruleName, |
| 587 | ruleArn, |
| 588 | eventBusName, |
| 589 | configuration: yield* observeRuleConfiguration( |
| 590 | described, |
| 591 | eventBusParam, |
| 592 | createTagsList(desiredTags), |
| 593 | ), |
| 594 | }; |
| 595 | }), |
| 596 | delete: Effect.fn(function* (input) { |
| 597 | const ruleName = input.output.ruleName; |
| 598 | const eventBusName = input.output.eventBusName; |
| 599 | const eventBusParam = eventBusName !== "default" ? eventBusName : undefined; |
| 600 | |
| 601 | const { Targets } = yield* eventbridge |
| 602 | .listTargetsByRule({ |
| 603 | Rule: ruleName, |
| 604 | EventBusName: eventBusParam, |
| 605 | }) |
| 606 | .pipe( |
| 607 | Effect.catchTag("ResourceNotFoundException", () => |
| 608 | Effect.succeed({ Targets: undefined }), |
| 609 | ), |
| 610 | ); |
| 611 | |
| 612 | if (Targets && Targets.length > 0) { |
| 613 | const response = yield* eventbridge |
| 614 | .removeTargets({ |
| 615 | Rule: ruleName, |
| 616 | EventBusName: eventBusParam, |
| 617 | Ids: Targets.map((t) => t.Id), |
| 618 | }) |
| 619 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 620 | if (response) { |
| 621 | yield* assertRemoveTargetsSucceeded(response); |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | yield* eventbridge |
| 626 | .deleteRule({ |
| 627 | Name: ruleName, |
| 628 | EventBusName: eventBusParam, |
| 629 | }) |
| 630 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 631 | }), |
| 632 | }; |
| 633 | }), |
| 634 | ); |
| 635 | |
| 636 | const toTarget = (target: Input.Resolve<RuleTarget>): eventbridge.Target => ({ |
| 637 | Id: target.Id, |
| 638 | Arn: target.Arn, |
| 639 | RoleArn: target.RoleArn, |
| 640 | Input: target.Input, |
| 641 | InputPath: target.InputPath, |
| 642 | InputTransformer: target.InputTransformer, |
| 643 | KinesisParameters: target.KinesisParameters, |
| 644 | RunCommandParameters: target.RunCommandParameters, |
| 645 | EcsParameters: target.EcsParameters |
| 646 | ? { |
| 647 | ...target.EcsParameters, |
| 648 | TaskDefinitionArn: target.EcsParameters.TaskDefinitionArn, |
| 649 | } |
| 650 | : undefined, |
| 651 | BatchParameters: target.BatchParameters |
| 652 | ? { |
| 653 | ...target.BatchParameters, |
| 654 | JobDefinition: target.BatchParameters.JobDefinition, |
| 655 | } |
| 656 | : undefined, |
| 657 | SqsParameters: target.SqsParameters, |
| 658 | HttpParameters: target.HttpParameters, |
| 659 | RedshiftDataParameters: target.RedshiftDataParameters, |
| 660 | SageMakerPipelineParameters: target.SageMakerPipelineParameters, |
| 661 | DeadLetterConfig: target.DeadLetterConfig ? { Arn: target.DeadLetterConfig.Arn } : undefined, |
| 662 | RetryPolicy: target.RetryPolicy, |
| 663 | AppSyncParameters: target.AppSyncParameters, |
| 664 | }); |
| 665 | |
| 666 | const toRuleArn = ( |
| 667 | region: RegionID, |
| 668 | accountId: AccountID, |
| 669 | eventBusName: string, |
| 670 | ruleName: string, |
| 671 | ): RuleArn => |
| 672 | (eventBusName === "default" |
| 673 | ? `arn:aws:events:${region}:${accountId}:rule/${ruleName}` |
| 674 | : `arn:aws:events:${region}:${accountId}:rule/${eventBusName}/${ruleName}`) as RuleArn; |
| 675 | |
| 676 | const validateRuleProps = Effect.fn(function* (props: RuleProps) { |
| 677 | if (!props.eventPattern && !props.scheduleExpression) { |
| 678 | return yield* new RuleInvalidProps({ |
| 679 | message: "EventBridge Rule requires either `eventPattern` or `scheduleExpression`", |
| 680 | }); |
| 681 | } |
| 682 | }); |
| 683 | |
| 684 | const assertPutTargetsSucceeded = Effect.fn(function* (response: eventbridge.PutTargetsResponse) { |
| 685 | if ((response.FailedEntryCount ?? 0) > 0) { |
| 686 | return yield* new RuleOperationFailed({ |
| 687 | message: `Failed to attach EventBridge targets: ${JSON.stringify(response.FailedEntries ?? [])}`, |
| 688 | }); |
| 689 | } |
| 690 | }); |
| 691 | |
| 692 | const assertRemoveTargetsSucceeded = Effect.fn(function* ( |
| 693 | response: eventbridge.RemoveTargetsResponse, |
| 694 | ) { |
| 695 | if ((response.FailedEntryCount ?? 0) > 0) { |
| 696 | return yield* new RuleOperationFailed({ |
| 697 | message: `Failed to remove EventBridge targets: ${JSON.stringify(response.FailedEntries ?? [])}`, |
| 698 | }); |
| 699 | } |
| 700 | }); |