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 redshift from "@distilled.cloud/aws/redshift"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { AWSEnvironment } from "../Environment.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { applyRedshiftTagDelta, redshiftArn, sameStringSet, toTagRecord } from "./internal.ts"; |
| 15 | |
| 16 | export class EventSubscriptionUnexpectedResponse extends Data.TaggedError( |
| 17 | "EventSubscriptionUnexpectedResponse", |
| 18 | )<{ |
| 19 | readonly message: string; |
| 20 | readonly cause?: unknown; |
| 21 | }> {} |
| 22 | |
| 23 | /** |
| 24 | * The kind of Redshift resource an {@link EventSubscription} filters on. |
| 25 | */ |
| 26 | export type EventSubscriptionSourceType = |
| 27 | | "cluster" |
| 28 | | "cluster-parameter-group" |
| 29 | | "cluster-security-group" |
| 30 | | "cluster-snapshot" |
| 31 | | "scheduled-action"; |
| 32 | |
| 33 | /** |
| 34 | * Redshift event categories an {@link EventSubscription} can filter on. |
| 35 | */ |
| 36 | export type EventSubscriptionCategory = |
| 37 | | "configuration" |
| 38 | | "management" |
| 39 | | "monitoring" |
| 40 | | "security" |
| 41 | | "pending"; |
| 42 | |
| 43 | export interface EventSubscriptionProps { |
| 44 | /** |
| 45 | * Name of the event subscription. Must be 1-255 ASCII letters, digits or |
| 46 | * hyphens, starting with a letter, and must not end with a hyphen or |
| 47 | * contain two consecutive hyphens. If omitted, a deterministic physical |
| 48 | * name is generated. Changing the name replaces the subscription. |
| 49 | */ |
| 50 | subscriptionName?: string; |
| 51 | /** |
| 52 | * ARN of the SNS topic Redshift publishes matching events to. The topic |
| 53 | * must exist and allow Redshift to publish. |
| 54 | */ |
| 55 | snsTopicArn: string; |
| 56 | /** |
| 57 | * The kind of source to filter on (e.g. `"cluster"`). Required when |
| 58 | * `sourceIds` is set. |
| 59 | * @default all source types |
| 60 | */ |
| 61 | sourceType?: EventSubscriptionSourceType; |
| 62 | /** |
| 63 | * Identifiers of the specific sources to filter on (e.g. cluster |
| 64 | * identifiers when `sourceType` is `"cluster"`). |
| 65 | * @default all sources of the subscribed type |
| 66 | */ |
| 67 | sourceIds?: string[]; |
| 68 | /** |
| 69 | * Event categories to subscribe to (e.g. `["monitoring", "management"]`). |
| 70 | * @default all categories |
| 71 | */ |
| 72 | eventCategories?: EventSubscriptionCategory[]; |
| 73 | /** |
| 74 | * Only deliver events of this severity. |
| 75 | * @default both `ERROR` and `INFO` |
| 76 | */ |
| 77 | severity?: "ERROR" | "INFO"; |
| 78 | /** |
| 79 | * Whether event delivery is active. |
| 80 | * @default true |
| 81 | */ |
| 82 | enabled?: boolean; |
| 83 | /** |
| 84 | * User-defined tags for the event subscription. |
| 85 | */ |
| 86 | tags?: Record<string, string>; |
| 87 | } |
| 88 | |
| 89 | export interface EventSubscription extends Resource< |
| 90 | "AWS.Redshift.EventSubscription", |
| 91 | EventSubscriptionProps, |
| 92 | { |
| 93 | /** |
| 94 | * Name of the event subscription. |
| 95 | */ |
| 96 | subscriptionName: string; |
| 97 | /** |
| 98 | * ARN of the event subscription. |
| 99 | */ |
| 100 | eventSubscriptionArn: string; |
| 101 | /** |
| 102 | * ARN of the SNS topic events are delivered to. |
| 103 | */ |
| 104 | snsTopicArn: string | undefined; |
| 105 | /** |
| 106 | * Status of the subscription (`"active"`, or `"no-permission"` / |
| 107 | * `"topic-not-exist"` when the SNS topic became unreachable after |
| 108 | * creation). |
| 109 | */ |
| 110 | status: string | undefined; |
| 111 | /** |
| 112 | * The source type filter, if any. |
| 113 | */ |
| 114 | sourceType: string | undefined; |
| 115 | /** |
| 116 | * The source identifier filters, if any. |
| 117 | */ |
| 118 | sourceIds: string[]; |
| 119 | /** |
| 120 | * The event category filters, if any. |
| 121 | */ |
| 122 | eventCategories: string[]; |
| 123 | /** |
| 124 | * The severity filter, if any. |
| 125 | */ |
| 126 | severity: string | undefined; |
| 127 | /** |
| 128 | * Whether event delivery is active. |
| 129 | */ |
| 130 | enabled: boolean | undefined; |
| 131 | /** |
| 132 | * Tags on the event subscription (including internal Alchemy tags). |
| 133 | */ |
| 134 | tags: Record<string, string>; |
| 135 | }, |
| 136 | never, |
| 137 | Providers |
| 138 | > {} |
| 139 | |
| 140 | /** |
| 141 | * An Amazon Redshift event notification subscription — routes provisioned |
| 142 | * cluster lifecycle events (maintenance, resizes, snapshots, failures, |
| 143 | * security changes) to an SNS topic. |
| 144 | * |
| 145 | * SNS is Redshift's native event channel for provisioned clusters: the only |
| 146 | * events Redshift publishes *directly* to EventBridge are the zero-ETL |
| 147 | * integration detail-types, so cluster events reach compute through an |
| 148 | * `EventSubscription` → `SNS.Topic` → `SNS.consumeTopicNotifications` chain. |
| 149 | * Subscriptions are free and provision instantly. |
| 150 | * ### Subscribing to Cluster Events |
| 151 | * **Example:** Route Cluster Events to an SNS Topic |
| 152 | * ```typescript |
| 153 | * const alerts = yield* SNS.Topic("WarehouseAlerts", {}); |
| 154 | * const subscription = yield* Redshift.EventSubscription("WarehouseEvents", { |
| 155 | * snsTopicArn: alerts.topicArn, |
| 156 | * sourceType: "cluster", |
| 157 | * sourceIds: [cluster.clusterIdentifier], |
| 158 | * }); |
| 159 | * ``` |
| 160 | * **Example:** Only Error-Severity Monitoring Events |
| 161 | * ```typescript |
| 162 | * const subscription = yield* Redshift.EventSubscription("WarehouseErrors", { |
| 163 | * snsTopicArn: alerts.topicArn, |
| 164 | * eventCategories: ["monitoring"], |
| 165 | * severity: "ERROR", |
| 166 | * }); |
| 167 | * ``` |
| 168 | * **Example:** Consume the Events in a Function |
| 169 | * ```typescript |
| 170 | * // inside a Lambda Function definition: |
| 171 | * yield* SNS.consumeTopicNotifications(alerts, (messages) => |
| 172 | * Stream.runForEach(messages, (message) => |
| 173 | * Effect.logInfo(`redshift event: ${message.Message}`), |
| 174 | * ), |
| 175 | * ); |
| 176 | * ``` |
| 177 | * |
| 178 | * @resource |
| 179 | */ |
| 180 | export const EventSubscription = Resource<EventSubscription>("AWS.Redshift.EventSubscription"); |
| 181 | |
| 182 | /** |
| 183 | * Retry an effect while the subscription is mid-transition |
| 184 | * (`InvalidSubscriptionStateFault`), bounded to ~2 minutes. |
| 185 | * |
| 186 | * Expressed as an explicitly-typed module-scope helper: inlining |
| 187 | * `Effect.retry` in a lifecycle operation leaves `Retry.Return`'s |
| 188 | * conditional type unresolved in the provider's inferred layer type, which |
| 189 | * declaration emit widens to an `unknown` R — poisoning `AWS.providers()` |
| 190 | * for every downstream consumer. |
| 191 | */ |
| 192 | const retryWhileSubscriptionTransitioning = <A, E extends { _tag: string }, R>( |
| 193 | self: Effect.Effect<A, E, R>, |
| 194 | ): Effect.Effect<A, E, R> => |
| 195 | Effect.retry(self, { |
| 196 | while: (e) => e._tag === "InvalidSubscriptionStateFault", |
| 197 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]), |
| 198 | }); |
| 199 | |
| 200 | export const EventSubscriptionProvider = () => |
| 201 | Provider.effect( |
| 202 | EventSubscription, |
| 203 | Effect.gen(function* () { |
| 204 | const toName = (id: string, props: Partial<EventSubscriptionProps>) => |
| 205 | props.subscriptionName |
| 206 | ? Effect.succeed(props.subscriptionName) |
| 207 | : createPhysicalName({ id, maxLength: 255, lowercase: true }); |
| 208 | |
| 209 | const readSubscription = Effect.fn(function* (name: string) { |
| 210 | const response = yield* redshift |
| 211 | .describeEventSubscriptions({ SubscriptionName: name }) |
| 212 | .pipe(Effect.catchTag("SubscriptionNotFoundFault", () => Effect.undefined)); |
| 213 | return response?.EventSubscriptionsList?.[0]; |
| 214 | }); |
| 215 | |
| 216 | const toAttrs = Effect.fn(function* (subscription: redshift.EventSubscription) { |
| 217 | const { accountId, region } = yield* AWSEnvironment.current; |
| 218 | if (!subscription.CustSubscriptionId) { |
| 219 | return yield* new EventSubscriptionUnexpectedResponse({ |
| 220 | message: "Event subscription is missing its name", |
| 221 | }); |
| 222 | } |
| 223 | return { |
| 224 | subscriptionName: subscription.CustSubscriptionId, |
| 225 | eventSubscriptionArn: redshiftArn( |
| 226 | region, |
| 227 | accountId, |
| 228 | "eventsubscription", |
| 229 | subscription.CustSubscriptionId, |
| 230 | ), |
| 231 | snsTopicArn: subscription.SnsTopicArn, |
| 232 | status: subscription.Status, |
| 233 | sourceType: subscription.SourceType, |
| 234 | sourceIds: subscription.SourceIdsList ?? [], |
| 235 | eventCategories: subscription.EventCategoriesList ?? [], |
| 236 | severity: subscription.Severity, |
| 237 | enabled: subscription.Enabled, |
| 238 | tags: toTagRecord(subscription.Tags), |
| 239 | }; |
| 240 | }); |
| 241 | |
| 242 | return { |
| 243 | stables: ["subscriptionName", "eventSubscriptionArn"], |
| 244 | |
| 245 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 246 | if (!isResolved(news)) return undefined; |
| 247 | if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) { |
| 248 | return { action: "replace" } as const; |
| 249 | } |
| 250 | }), |
| 251 | |
| 252 | read: Effect.fn(function* ({ id, olds, output }) { |
| 253 | const name = output?.subscriptionName ?? (yield* toName(id, olds ?? {})); |
| 254 | const subscription = yield* readSubscription(name); |
| 255 | if (!subscription?.CustSubscriptionId) return undefined; |
| 256 | const attrs = yield* toAttrs(subscription); |
| 257 | return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs); |
| 258 | }), |
| 259 | |
| 260 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 261 | const name = output?.subscriptionName ?? (yield* toName(id, news)); |
| 262 | const internalTags = yield* createInternalTags(id); |
| 263 | const desiredTags = { ...internalTags, ...news.tags }; |
| 264 | |
| 265 | // 1. Observe — cloud state is authoritative. |
| 266 | let observed = yield* readSubscription(name); |
| 267 | |
| 268 | // 2. Ensure — create if missing; tolerate AlreadyExists as a race |
| 269 | // with a peer reconciler by re-reading. |
| 270 | if (!observed?.CustSubscriptionId) { |
| 271 | yield* redshift |
| 272 | .createEventSubscription({ |
| 273 | SubscriptionName: name, |
| 274 | SnsTopicArn: news.snsTopicArn, |
| 275 | SourceType: news.sourceType, |
| 276 | SourceIds: news.sourceIds, |
| 277 | EventCategories: news.eventCategories, |
| 278 | Severity: news.severity, |
| 279 | Enabled: news.enabled ?? true, |
| 280 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 281 | Key, |
| 282 | Value, |
| 283 | })), |
| 284 | }) |
| 285 | .pipe(Effect.catchTag("SubscriptionAlreadyExistFault", () => Effect.void)); |
| 286 | observed = yield* readSubscription(name); |
| 287 | if (!observed?.CustSubscriptionId) { |
| 288 | return yield* new EventSubscriptionUnexpectedResponse({ |
| 289 | message: `Failed to create event subscription '${name}'`, |
| 290 | }); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // 3. Sync — diff OBSERVED filters against desired; modify replaces |
| 295 | // the whole filter configuration, so send the full desired |
| 296 | // shape when anything drifted. |
| 297 | const desiredEnabled = news.enabled ?? true; |
| 298 | if ( |
| 299 | observed.SnsTopicArn !== news.snsTopicArn || |
| 300 | observed.SourceType !== news.sourceType || |
| 301 | !sameStringSet(observed.SourceIdsList, news.sourceIds) || |
| 302 | !sameStringSet(observed.EventCategoriesList, news.eventCategories) || |
| 303 | observed.Severity !== news.severity || |
| 304 | observed.Enabled !== desiredEnabled |
| 305 | ) { |
| 306 | yield* retryWhileSubscriptionTransitioning( |
| 307 | redshift.modifyEventSubscription({ |
| 308 | SubscriptionName: name, |
| 309 | SnsTopicArn: news.snsTopicArn, |
| 310 | SourceType: news.sourceType, |
| 311 | SourceIds: news.sourceIds, |
| 312 | EventCategories: news.eventCategories, |
| 313 | Severity: news.severity, |
| 314 | Enabled: desiredEnabled, |
| 315 | }), |
| 316 | ); |
| 317 | observed = yield* readSubscription(name); |
| 318 | if (!observed?.CustSubscriptionId) { |
| 319 | return yield* new EventSubscriptionUnexpectedResponse({ |
| 320 | message: `Event subscription '${name}' not found after update`, |
| 321 | }); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | // 3b. Sync tags — diff against OBSERVED cloud tags (describe |
| 326 | // surfaces them inline). |
| 327 | const { accountId, region } = yield* AWSEnvironment.current; |
| 328 | const arn = redshiftArn(region, accountId, "eventsubscription", name); |
| 329 | const { removed, upsert } = diffTags(toTagRecord(observed.Tags), desiredTags); |
| 330 | yield* applyRedshiftTagDelta({ arn, upsert, removed }); |
| 331 | |
| 332 | yield* session.note(arn); |
| 333 | const attrs = yield* toAttrs(observed); |
| 334 | return { ...attrs, tags: desiredTags }; |
| 335 | }), |
| 336 | |
| 337 | delete: Effect.fn(function* ({ output }) { |
| 338 | yield* retryWhileSubscriptionTransitioning( |
| 339 | redshift |
| 340 | .deleteEventSubscription({ |
| 341 | SubscriptionName: output.subscriptionName, |
| 342 | }) |
| 343 | .pipe(Effect.catchTag("SubscriptionNotFoundFault", () => Effect.undefined)), |
| 344 | ); |
| 345 | }), |
| 346 | |
| 347 | list: () => |
| 348 | // Top-level account/region collection: exhaustively paginate |
| 349 | // describeEventSubscriptions; tags come inline on each entry. |
| 350 | redshift.describeEventSubscriptions.pages({}).pipe( |
| 351 | Stream.runCollect, |
| 352 | Effect.map((chunk) => |
| 353 | Array.from(chunk).flatMap((page) => |
| 354 | (page.EventSubscriptionsList ?? []).filter( |
| 355 | (subscription) => subscription.CustSubscriptionId !== undefined, |
| 356 | ), |
| 357 | ), |
| 358 | ), |
| 359 | Effect.flatMap( |
| 360 | Effect.forEach((subscription) => toAttrs(subscription), { |
| 361 | concurrency: 4, |
| 362 | }), |
| 363 | ), |
| 364 | ), |
| 365 | }; |
| 366 | }), |
| 367 | ); |