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 athena from "@distilled.cloud/aws/athena"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { createInternalTags, diffTags } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { AWSEnvironment, type AccountID } from "../Environment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import type { RegionID } from "../Region.ts"; |
| 12 | |
| 13 | export type WorkGroupName = string; |
| 14 | export type WorkGroupArn = `arn:aws:athena:${RegionID}:${AccountID}:workgroup/${WorkGroupName}`; |
| 15 | |
| 16 | export interface WorkGroupProps { |
| 17 | /** |
| 18 | * Name of the workgroup. If omitted, a unique name is generated. |
| 19 | * Changing this replaces the workgroup. Up to 128 characters. |
| 20 | */ |
| 21 | workGroupName?: string; |
| 22 | /** |
| 23 | * Human-readable description of the workgroup. |
| 24 | */ |
| 25 | description?: string; |
| 26 | /** |
| 27 | * S3 URI (`s3://bucket/prefix/`) where query results are written. |
| 28 | * Applied as the workgroup's `ResultConfiguration.OutputLocation`. |
| 29 | */ |
| 30 | outputLocation?: string; |
| 31 | /** |
| 32 | * Server-side encryption for query results written to S3. |
| 33 | */ |
| 34 | encryptionOption?: "SSE_S3" | "SSE_KMS" | "CSE_KMS"; |
| 35 | /** |
| 36 | * KMS key ARN/ID — required when `encryptionOption` is `SSE_KMS` or `CSE_KMS`. |
| 37 | */ |
| 38 | kmsKey?: string; |
| 39 | /** |
| 40 | * Force queries to use this workgroup's result configuration (output |
| 41 | * location, encryption) instead of client-side settings. |
| 42 | * @default true |
| 43 | */ |
| 44 | enforceWorkGroupConfiguration?: boolean; |
| 45 | /** |
| 46 | * Per-query data-scanned cutoff in bytes. Queries scanning more are |
| 47 | * cancelled. Minimum is 10 MB (10_000_000). |
| 48 | */ |
| 49 | bytesScannedCutoffPerQuery?: number; |
| 50 | /** |
| 51 | * Publish per-query CloudWatch metrics for this workgroup. |
| 52 | * @default false |
| 53 | */ |
| 54 | publishCloudWatchMetricsEnabled?: boolean; |
| 55 | /** |
| 56 | * Charge S3 data-transfer/request costs to the query requester. |
| 57 | * @default false |
| 58 | */ |
| 59 | requesterPaysEnabled?: boolean; |
| 60 | /** |
| 61 | * Selected Athena engine version (e.g. `"Athena engine version 3"`). |
| 62 | * If omitted, Athena picks the account default (AUTO). |
| 63 | */ |
| 64 | engineVersion?: string; |
| 65 | /** |
| 66 | * Whether the workgroup accepts queries. |
| 67 | * @default "ENABLED" |
| 68 | */ |
| 69 | state?: "ENABLED" | "DISABLED"; |
| 70 | /** |
| 71 | * User-defined tags to apply to the workgroup. |
| 72 | */ |
| 73 | tags?: Record<string, string>; |
| 74 | } |
| 75 | |
| 76 | export interface WorkGroup extends Resource< |
| 77 | "AWS.Athena.WorkGroup", |
| 78 | WorkGroupProps, |
| 79 | { |
| 80 | /** |
| 81 | * Name of the workgroup. |
| 82 | */ |
| 83 | workGroupName: WorkGroupName; |
| 84 | /** |
| 85 | * ARN of the workgroup. |
| 86 | */ |
| 87 | workGroupArn: WorkGroupArn; |
| 88 | /** |
| 89 | * Whether the workgroup accepts queries. |
| 90 | */ |
| 91 | state: "ENABLED" | "DISABLED"; |
| 92 | /** |
| 93 | * S3 location query results are written to (`s3://bucket/prefix/`). |
| 94 | */ |
| 95 | outputLocation: string | undefined; |
| 96 | /** |
| 97 | * Tags on the workgroup. |
| 98 | */ |
| 99 | tags: Record<string, string>; |
| 100 | }, |
| 101 | never, |
| 102 | Providers |
| 103 | > {} |
| 104 | |
| 105 | /** |
| 106 | * An Amazon Athena workgroup — an isolation boundary for queries that pins the |
| 107 | * S3 result-output location, result encryption, a bytes-scanned cutoff, and |
| 108 | * whether that configuration is enforced over per-query client settings. |
| 109 | * |
| 110 | * ### Creating Workgroups |
| 111 | * **Example:** Workgroup with an enforced result location |
| 112 | * ```typescript |
| 113 | * const results = yield* AWS.S3.Bucket("AthenaResults", {}); |
| 114 | * const wg = yield* AWS.Athena.WorkGroup("Analytics", { |
| 115 | * outputLocation: results.bucketName.pipe( |
| 116 | * Output.map((b) => `s3://${b}/results/`), |
| 117 | * ), |
| 118 | * enforceWorkGroupConfiguration: true, |
| 119 | * }); |
| 120 | * ``` |
| 121 | * |
| 122 | * **Example:** Workgroup with a bytes-scanned cost guardrail |
| 123 | * ```typescript |
| 124 | * const wg = yield* AWS.Athena.WorkGroup("Guarded", { |
| 125 | * outputLocation: "s3://my-results-bucket/prefix/", |
| 126 | * bytesScannedCutoffPerQuery: 10_000_000, // 10 MB per query |
| 127 | * publishCloudWatchMetricsEnabled: true, |
| 128 | * }); |
| 129 | * ``` |
| 130 | * |
| 131 | * @resource |
| 132 | */ |
| 133 | export const WorkGroup = Resource<WorkGroup>("AWS.Athena.WorkGroup"); |
| 134 | |
| 135 | const observedTagsOf = (tags: readonly athena.Tag[] | undefined) => |
| 136 | Object.fromEntries( |
| 137 | (tags ?? []).flatMap((t) => |
| 138 | t.Key !== undefined && t.Value !== undefined ? [[t.Key, t.Value]] : [], |
| 139 | ), |
| 140 | ); |
| 141 | |
| 142 | const outputLocationOf = (wg: athena.WorkGroup | undefined) => |
| 143 | wg?.Configuration?.ResultConfiguration?.OutputLocation; |
| 144 | |
| 145 | export const WorkGroupProvider = () => |
| 146 | Provider.effect( |
| 147 | WorkGroup, |
| 148 | Effect.gen(function* () { |
| 149 | const toName = (id: string, props: WorkGroupProps = {}) => |
| 150 | props.workGroupName |
| 151 | ? Effect.succeed(props.workGroupName) |
| 152 | : createPhysicalName({ id, maxLength: 128 }); |
| 153 | |
| 154 | const getOne = (name: string) => |
| 155 | athena.getWorkGroup({ WorkGroup: name }).pipe( |
| 156 | Effect.map((res) => res.WorkGroup), |
| 157 | Effect.catchTag("WorkGroupNotFound", () => Effect.undefined), |
| 158 | ); |
| 159 | |
| 160 | const fetchTags = (arn: string) => |
| 161 | athena.listTagsForResource.items({ ResourceARN: arn }).pipe( |
| 162 | Stream.runCollect, |
| 163 | Effect.map((chunk) => observedTagsOf(Array.from(chunk))), |
| 164 | Effect.orElseSucceed(() => ({}) as Record<string, string>), |
| 165 | ); |
| 166 | |
| 167 | return { |
| 168 | stables: ["workGroupName", "workGroupArn"], |
| 169 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 170 | if (!isResolved(news)) return; |
| 171 | if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) { |
| 172 | return { action: "replace" } as const; |
| 173 | } |
| 174 | }), |
| 175 | read: Effect.fn(function* ({ id, olds, output }) { |
| 176 | const { accountId, region } = yield* AWSEnvironment.current; |
| 177 | const name = output?.workGroupName ?? (yield* toName(id, olds ?? {})); |
| 178 | const wg = yield* getOne(name); |
| 179 | if (!wg) return undefined; |
| 180 | const arn = `arn:aws:athena:${region}:${accountId}:workgroup/${name}` as WorkGroupArn; |
| 181 | return { |
| 182 | workGroupName: name, |
| 183 | workGroupArn: arn, |
| 184 | state: (wg.State ?? "ENABLED") as "ENABLED" | "DISABLED", |
| 185 | outputLocation: outputLocationOf(wg), |
| 186 | tags: yield* fetchTags(arn), |
| 187 | }; |
| 188 | }), |
| 189 | list: () => |
| 190 | Effect.gen(function* () { |
| 191 | const { accountId, region } = yield* AWSEnvironment.current; |
| 192 | const pages = yield* athena.listWorkGroups.pages({}).pipe(Stream.runCollect); |
| 193 | return Array.from(pages) |
| 194 | .flatMap((page) => page.WorkGroups ?? []) |
| 195 | .flatMap((wg) => |
| 196 | // `primary` is the account's built-in default workgroup; |
| 197 | // DeleteWorkGroup always rejects it, so keep it out of |
| 198 | // enumeration for account-wide teardown (nuke). |
| 199 | wg.Name && wg.Name !== "primary" |
| 200 | ? [ |
| 201 | { |
| 202 | workGroupName: wg.Name, |
| 203 | workGroupArn: |
| 204 | `arn:aws:athena:${region}:${accountId}:workgroup/${wg.Name}` as WorkGroupArn, |
| 205 | state: (wg.State ?? "ENABLED") as "ENABLED" | "DISABLED", |
| 206 | outputLocation: undefined, |
| 207 | tags: {} as Record<string, string>, |
| 208 | }, |
| 209 | ] |
| 210 | : [], |
| 211 | ); |
| 212 | }), |
| 213 | reconcile: Effect.fn(function* ({ id, news = {}, output, session }) { |
| 214 | const { accountId, region } = yield* AWSEnvironment.current; |
| 215 | const name = output?.workGroupName ?? (yield* toName(id, news)); |
| 216 | const arn = `arn:aws:athena:${region}:${accountId}:workgroup/${name}` as WorkGroupArn; |
| 217 | const internalTags = yield* createInternalTags(id); |
| 218 | const desiredTags = { ...internalTags, ...news.tags }; |
| 219 | const desiredState = news.state ?? "ENABLED"; |
| 220 | const enforce = news.enforceWorkGroupConfiguration ?? true; |
| 221 | const encryption = news.encryptionOption |
| 222 | ? { |
| 223 | EncryptionOption: news.encryptionOption, |
| 224 | KmsKey: news.kmsKey, |
| 225 | } |
| 226 | : undefined; |
| 227 | |
| 228 | // Observe — cloud state is authoritative. |
| 229 | let wg = yield* getOne(name); |
| 230 | |
| 231 | // Ensure — create if missing. |
| 232 | if (!wg) { |
| 233 | yield* athena.createWorkGroup({ |
| 234 | Name: name, |
| 235 | Description: news.description, |
| 236 | Configuration: { |
| 237 | ResultConfiguration: news.outputLocation |
| 238 | ? { |
| 239 | OutputLocation: news.outputLocation, |
| 240 | EncryptionConfiguration: encryption, |
| 241 | } |
| 242 | : undefined, |
| 243 | EnforceWorkGroupConfiguration: enforce, |
| 244 | PublishCloudWatchMetricsEnabled: news.publishCloudWatchMetricsEnabled, |
| 245 | BytesScannedCutoffPerQuery: news.bytesScannedCutoffPerQuery, |
| 246 | RequesterPaysEnabled: news.requesterPaysEnabled, |
| 247 | EngineVersion: news.engineVersion |
| 248 | ? { SelectedEngineVersion: news.engineVersion } |
| 249 | : undefined, |
| 250 | }, |
| 251 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 252 | Key, |
| 253 | Value, |
| 254 | })), |
| 255 | }); |
| 256 | wg = yield* getOne(name); |
| 257 | } else { |
| 258 | // Sync — diff observed configuration against desired, apply the |
| 259 | // delta via UpdateWorkGroup (which takes a ConfigurationUpdates |
| 260 | // shape distinct from CreateWorkGroup's Configuration). |
| 261 | const cfg = wg.Configuration; |
| 262 | const updates: athena.WorkGroupConfigurationUpdates = {}; |
| 263 | let dirty = false; |
| 264 | |
| 265 | if ((cfg?.EnforceWorkGroupConfiguration ?? false) !== enforce) { |
| 266 | updates.EnforceWorkGroupConfiguration = enforce; |
| 267 | dirty = true; |
| 268 | } |
| 269 | if ( |
| 270 | news.outputLocation !== undefined && |
| 271 | cfg?.ResultConfiguration?.OutputLocation !== news.outputLocation |
| 272 | ) { |
| 273 | updates.ResultConfigurationUpdates = { |
| 274 | ...updates.ResultConfigurationUpdates, |
| 275 | OutputLocation: news.outputLocation, |
| 276 | }; |
| 277 | dirty = true; |
| 278 | } |
| 279 | if ( |
| 280 | encryption && |
| 281 | cfg?.ResultConfiguration?.EncryptionConfiguration?.EncryptionOption !== |
| 282 | encryption.EncryptionOption |
| 283 | ) { |
| 284 | updates.ResultConfigurationUpdates = { |
| 285 | ...updates.ResultConfigurationUpdates, |
| 286 | EncryptionConfiguration: encryption, |
| 287 | }; |
| 288 | dirty = true; |
| 289 | } |
| 290 | if ( |
| 291 | (cfg?.PublishCloudWatchMetricsEnabled ?? false) !== |
| 292 | (news.publishCloudWatchMetricsEnabled ?? false) |
| 293 | ) { |
| 294 | updates.PublishCloudWatchMetricsEnabled = |
| 295 | news.publishCloudWatchMetricsEnabled ?? false; |
| 296 | dirty = true; |
| 297 | } |
| 298 | if ((cfg?.RequesterPaysEnabled ?? false) !== (news.requesterPaysEnabled ?? false)) { |
| 299 | updates.RequesterPaysEnabled = news.requesterPaysEnabled ?? false; |
| 300 | dirty = true; |
| 301 | } |
| 302 | if ( |
| 303 | (cfg?.BytesScannedCutoffPerQuery ?? undefined) !== news.bytesScannedCutoffPerQuery |
| 304 | ) { |
| 305 | if (news.bytesScannedCutoffPerQuery === undefined) { |
| 306 | updates.RemoveBytesScannedCutoffPerQuery = true; |
| 307 | } else { |
| 308 | updates.BytesScannedCutoffPerQuery = news.bytesScannedCutoffPerQuery; |
| 309 | } |
| 310 | dirty = true; |
| 311 | } |
| 312 | if ( |
| 313 | news.engineVersion !== undefined && |
| 314 | cfg?.EngineVersion?.SelectedEngineVersion !== news.engineVersion |
| 315 | ) { |
| 316 | updates.EngineVersion = { |
| 317 | SelectedEngineVersion: news.engineVersion, |
| 318 | }; |
| 319 | dirty = true; |
| 320 | } |
| 321 | |
| 322 | const stateChange = (wg.State ?? "ENABLED") !== desiredState ? desiredState : undefined; |
| 323 | const descChange = |
| 324 | news.description !== undefined && wg.Description !== news.description |
| 325 | ? news.description |
| 326 | : undefined; |
| 327 | |
| 328 | if (dirty || stateChange || descChange) { |
| 329 | yield* athena.updateWorkGroup({ |
| 330 | WorkGroup: name, |
| 331 | Description: descChange, |
| 332 | State: stateChange, |
| 333 | ConfigurationUpdates: dirty ? updates : undefined, |
| 334 | }); |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // Sync tags — diff against OBSERVED cloud tags. |
| 339 | const observed = yield* fetchTags(arn); |
| 340 | const { upsert, removed } = diffTags(observed, desiredTags); |
| 341 | if (upsert.length > 0) { |
| 342 | yield* athena.tagResource({ |
| 343 | ResourceARN: arn, |
| 344 | Tags: upsert.map((t) => ({ Key: t.Key, Value: t.Value })), |
| 345 | }); |
| 346 | } |
| 347 | if (removed.length > 0) { |
| 348 | yield* athena.untagResource({ ResourceARN: arn, TagKeys: removed }); |
| 349 | } |
| 350 | |
| 351 | const final = (yield* getOne(name)) ?? wg; |
| 352 | yield* session.note(arn); |
| 353 | return { |
| 354 | workGroupName: name, |
| 355 | workGroupArn: arn, |
| 356 | state: (final?.State ?? desiredState) as "ENABLED" | "DISABLED", |
| 357 | outputLocation: outputLocationOf(final) ?? news.outputLocation, |
| 358 | tags: desiredTags, |
| 359 | }; |
| 360 | }), |
| 361 | delete: Effect.fn(function* ({ output }) { |
| 362 | // Idempotent: DeleteWorkGroup succeeds (no error) when the workgroup |
| 363 | // is already gone. RecursiveDeleteOption tears down any named |
| 364 | // queries / prepared statements still saved in it. |
| 365 | yield* athena.deleteWorkGroup({ |
| 366 | WorkGroup: output.workGroupName, |
| 367 | RecursiveDeleteOption: true, |
| 368 | }); |
| 369 | }), |
| 370 | }; |
| 371 | }), |
| 372 | ); |