The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as TSQ from "@distilled.cloud/aws/timestream-query"; |
| 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, type Tags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Option from "effect/Option"; |
| 11 | import * as EffectStream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { withQueryEndpoint } from "./internal.ts"; |
| 14 | |
| 15 | export class ScheduledQueryInvalidProps extends Data.TaggedError("ScheduledQueryInvalidProps")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | export class ScheduledQueryUnexpectedResponse extends Data.TaggedError( |
| 21 | "ScheduledQueryUnexpectedResponse", |
| 22 | )<{ |
| 23 | readonly message: string; |
| 24 | readonly cause?: unknown; |
| 25 | }> {} |
| 26 | |
| 27 | export type ScheduledQueryState = TSQ.ScheduledQueryState; |
| 28 | |
| 29 | export interface ScheduledQueryErrorReportS3 { |
| 30 | /** |
| 31 | * Name of the S3 bucket where error reports for failed runs are written. |
| 32 | */ |
| 33 | bucketName: string; |
| 34 | /** |
| 35 | * Object key prefix for error report objects. |
| 36 | */ |
| 37 | objectKeyPrefix?: string; |
| 38 | /** |
| 39 | * Server-side encryption for error report objects. |
| 40 | * @default "SSE_S3" |
| 41 | */ |
| 42 | encryptionOption?: TSQ.S3EncryptionOption; |
| 43 | } |
| 44 | |
| 45 | export interface ScheduledQueryProps { |
| 46 | /** |
| 47 | * Name of the scheduled query. Must be unique within the account and |
| 48 | * region. |
| 49 | * @default ${app}-${stage}-${id} |
| 50 | */ |
| 51 | name?: string; |
| 52 | /** |
| 53 | * The SQL the scheduled query runs on each invocation. |
| 54 | */ |
| 55 | queryString: string; |
| 56 | /** |
| 57 | * When to run the query — a cron (`cron(0 12 * * ? *)`) or rate |
| 58 | * (`rate(1 hour)`) expression. |
| 59 | */ |
| 60 | scheduleExpression: string; |
| 61 | /** |
| 62 | * ARN of the SNS topic Timestream notifies after each run. |
| 63 | */ |
| 64 | notificationTopicArn: string; |
| 65 | /** |
| 66 | * ARN of the IAM role Timestream assumes to run the query, write results, |
| 67 | * publish notifications, and write error reports. |
| 68 | */ |
| 69 | executionRoleArn: string; |
| 70 | /** |
| 71 | * Where results are written (a Timestream table with measure/dimension |
| 72 | * mappings). Omit for queries whose results are not materialized. |
| 73 | */ |
| 74 | targetConfiguration?: TSQ.TargetConfiguration; |
| 75 | /** |
| 76 | * S3 location where error reports for failed runs are written. |
| 77 | */ |
| 78 | errorReportS3: ScheduledQueryErrorReportS3; |
| 79 | /** |
| 80 | * The KMS key used to encrypt the scheduled query resource at rest. When |
| 81 | * omitted, Timestream uses an AWS-owned key. |
| 82 | */ |
| 83 | kmsKeyId?: string; |
| 84 | /** |
| 85 | * Whether the schedule is active. |
| 86 | * @default "ENABLED" |
| 87 | */ |
| 88 | state?: ScheduledQueryState; |
| 89 | /** |
| 90 | * Tags to associate with the scheduled query. |
| 91 | */ |
| 92 | tags?: Record<string, string>; |
| 93 | } |
| 94 | |
| 95 | export interface ScheduledQuery extends Resource< |
| 96 | "AWS.Timestream.ScheduledQuery", |
| 97 | ScheduledQueryProps, |
| 98 | { |
| 99 | /** |
| 100 | * ARN of the scheduled query. |
| 101 | */ |
| 102 | scheduledQueryArn: string; |
| 103 | /** |
| 104 | * The scheduled query's physical name. |
| 105 | */ |
| 106 | name: string; |
| 107 | /** |
| 108 | * Whether the schedule is currently active. |
| 109 | */ |
| 110 | state: ScheduledQueryState; |
| 111 | /** |
| 112 | * Current tags reported for the scheduled query. |
| 113 | */ |
| 114 | tags: Record<string, string>; |
| 115 | }, |
| 116 | never, |
| 117 | Providers |
| 118 | > {} |
| 119 | |
| 120 | /** |
| 121 | * An Amazon Timestream for LiveAnalytics scheduled query — a SQL query |
| 122 | * Timestream runs on a cron/rate schedule, materializing results into a |
| 123 | * target table and notifying an SNS topic after each run. |
| 124 | * |
| 125 | * Only the `state` (ENABLED/DISABLED) is mutable in place; changing the |
| 126 | * query, schedule, notification topic, role, target, error report location, |
| 127 | * or KMS key replaces the scheduled query. Tags sync in place. |
| 128 | * |
| 129 | * :::note |
| 130 | * Timestream for LiveAnalytics is closed to new AWS customers. Accounts that |
| 131 | * were not already onboarded receive `TimestreamNotOnboarded` (a specialized |
| 132 | * `AccessDenied`) on every operation. |
| 133 | * ::: |
| 134 | * ### Creating Scheduled Queries |
| 135 | * **Example:** Hourly Rollup |
| 136 | * ```typescript |
| 137 | * import * as Timestream from "@alchemy.run/aws/Timestream"; |
| 138 | * |
| 139 | * const rollup = yield* Timestream.ScheduledQuery("HourlyRollup", { |
| 140 | * queryString: `SELECT host, AVG(measure_value::double) AS avg_cpu |
| 141 | * FROM "metrics"."cpu" |
| 142 | * WHERE time > ago(1h) GROUP BY host`, |
| 143 | * scheduleExpression: "rate(1 hour)", |
| 144 | * notificationTopicArn: topic.topicArn, |
| 145 | * executionRoleArn: role.roleArn, |
| 146 | * errorReportS3: { bucketName: bucket.bucketName }, |
| 147 | * targetConfiguration: { |
| 148 | * TimestreamConfiguration: { |
| 149 | * DatabaseName: database.databaseName, |
| 150 | * TableName: rollupTable.tableName, |
| 151 | * TimeColumn: "time", |
| 152 | * DimensionMappings: [{ Name: "host", DimensionValueType: "VARCHAR" }], |
| 153 | * MultiMeasureMappings: { |
| 154 | * TargetMultiMeasureName: "cpu_rollup", |
| 155 | * MultiMeasureAttributeMappings: [ |
| 156 | * { SourceColumn: "avg_cpu", MeasureValueType: "DOUBLE" }, |
| 157 | * ], |
| 158 | * }, |
| 159 | * }, |
| 160 | * }, |
| 161 | * }); |
| 162 | * ``` |
| 163 | * |
| 164 | * **Example:** Pausing a Schedule |
| 165 | * ```typescript |
| 166 | * const rollup = yield* Timestream.ScheduledQuery("HourlyRollup", { |
| 167 | * // ... unchanged configuration ... |
| 168 | * state: "DISABLED", |
| 169 | * }); |
| 170 | * ``` |
| 171 | * |
| 172 | * @resource |
| 173 | */ |
| 174 | export const ScheduledQuery = Resource<ScheduledQuery>("AWS.Timestream.ScheduledQuery"); |
| 175 | |
| 176 | const createScheduledQueryName = (id: string, props: { name?: string | undefined }) => |
| 177 | Effect.gen(function* () { |
| 178 | if (props.name) { |
| 179 | return props.name; |
| 180 | } |
| 181 | return yield* createPhysicalName({ id, maxLength: 64 }); |
| 182 | }); |
| 183 | |
| 184 | const toTagRecord = ( |
| 185 | tags: Array<{ Key: string; Value: string }> | undefined, |
| 186 | ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value])); |
| 187 | |
| 188 | const readScheduledQuery = Effect.fn(function* (scheduledQueryArn: string) { |
| 189 | const response = yield* withQueryEndpoint( |
| 190 | TSQ.describeScheduledQuery({ ScheduledQueryArn: scheduledQueryArn }), |
| 191 | ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 192 | if (!response?.ScheduledQuery) { |
| 193 | return undefined; |
| 194 | } |
| 195 | const scheduledQuery = response.ScheduledQuery; |
| 196 | const tags = yield* withQueryEndpoint( |
| 197 | TSQ.listTagsForResource.items({ ResourceARN: scheduledQuery.Arn }).pipe( |
| 198 | EffectStream.runCollect, |
| 199 | Effect.map((chunk) => Array.from(chunk)), |
| 200 | ), |
| 201 | ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 202 | if (!tags) { |
| 203 | return undefined; |
| 204 | } |
| 205 | return { |
| 206 | scheduledQueryArn: scheduledQuery.Arn, |
| 207 | name: scheduledQuery.Name, |
| 208 | state: scheduledQuery.State, |
| 209 | tags: toTagRecord(tags), |
| 210 | } satisfies ScheduledQuery["Attributes"]; |
| 211 | }); |
| 212 | |
| 213 | const findScheduledQueryByName = Effect.fn(function* (name: string) { |
| 214 | const match = yield* withQueryEndpoint( |
| 215 | TSQ.listScheduledQueries.pages({}).pipe( |
| 216 | EffectStream.map((page) => page.ScheduledQueries ?? []), |
| 217 | EffectStream.flattenIterable, |
| 218 | EffectStream.filter((summary) => summary.Name === name), |
| 219 | EffectStream.runHead, |
| 220 | ), |
| 221 | ).pipe(Effect.map(Option.getOrUndefined)); |
| 222 | if (!match) return undefined; |
| 223 | return yield* readScheduledQuery(match.Arn); |
| 224 | }); |
| 225 | |
| 226 | export const ScheduledQueryProvider = () => |
| 227 | Provider.effect( |
| 228 | ScheduledQuery, |
| 229 | Effect.gen(function* () { |
| 230 | return { |
| 231 | stables: ["scheduledQueryArn", "name"], |
| 232 | list: () => |
| 233 | Effect.gen(function* () { |
| 234 | const summaries = yield* withQueryEndpoint( |
| 235 | TSQ.listScheduledQueries.pages({}).pipe(EffectStream.runCollect), |
| 236 | ).pipe( |
| 237 | Effect.map((chunk) => |
| 238 | Array.from(chunk).flatMap((page) => page.ScheduledQueries ?? []), |
| 239 | ), |
| 240 | ); |
| 241 | const hydrated = yield* Effect.forEach( |
| 242 | summaries, |
| 243 | (summary) => readScheduledQuery(summary.Arn), |
| 244 | { concurrency: 5 }, |
| 245 | ); |
| 246 | return hydrated.filter( |
| 247 | (attrs): attrs is ScheduledQuery["Attributes"] => attrs !== undefined, |
| 248 | ); |
| 249 | }), |
| 250 | read: Effect.fn(function* ({ id, olds, output }) { |
| 251 | const state = output?.scheduledQueryArn |
| 252 | ? yield* readScheduledQuery(output.scheduledQueryArn) |
| 253 | : yield* findScheduledQueryByName(yield* createScheduledQueryName(id, olds ?? {})); |
| 254 | if (!state) return undefined; |
| 255 | return (yield* hasAlchemyTags(id, state.tags as Tags)) ? state : Unowned(state); |
| 256 | }), |
| 257 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 258 | if (!isResolved(news) || olds === undefined) return; |
| 259 | const oldName = yield* createScheduledQueryName(id, olds); |
| 260 | const newName = yield* createScheduledQueryName(id, news); |
| 261 | // Only State is mutable via UpdateScheduledQuery — every other |
| 262 | // aspect requires a replacement. |
| 263 | const changed = (a: unknown, b: unknown) => |
| 264 | JSON.stringify(a ?? null) !== JSON.stringify(b ?? null); |
| 265 | if ( |
| 266 | oldName !== newName || |
| 267 | olds.queryString !== news.queryString || |
| 268 | olds.scheduleExpression !== news.scheduleExpression || |
| 269 | olds.notificationTopicArn !== news.notificationTopicArn || |
| 270 | olds.executionRoleArn !== news.executionRoleArn || |
| 271 | olds.kmsKeyId !== news.kmsKeyId || |
| 272 | changed(olds.targetConfiguration, news.targetConfiguration) || |
| 273 | changed(olds.errorReportS3, news.errorReportS3) |
| 274 | ) { |
| 275 | return { action: "replace" } as const; |
| 276 | } |
| 277 | }), |
| 278 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 279 | if (!news) { |
| 280 | return yield* new ScheduledQueryInvalidProps({ |
| 281 | message: "Timestream ScheduledQuery requires props", |
| 282 | }); |
| 283 | } |
| 284 | const name = output?.name ?? (yield* createScheduledQueryName(id, news)); |
| 285 | const internalTags = yield* createInternalTags(id); |
| 286 | const desiredTags = { ...internalTags, ...news.tags }; |
| 287 | |
| 288 | // Observe — prefer the cached ARN; fall back to a name lookup so a |
| 289 | // create whose state failed to persist is adopted, not duplicated. |
| 290 | let state = output?.scheduledQueryArn |
| 291 | ? yield* readScheduledQuery(output.scheduledQueryArn) |
| 292 | : yield* findScheduledQueryByName(name); |
| 293 | |
| 294 | // Ensure — create if missing; tolerate a ConflictException race. |
| 295 | if (state === undefined) { |
| 296 | yield* withQueryEndpoint( |
| 297 | TSQ.createScheduledQuery({ |
| 298 | Name: name, |
| 299 | QueryString: news.queryString, |
| 300 | ScheduleConfiguration: { |
| 301 | ScheduleExpression: news.scheduleExpression, |
| 302 | }, |
| 303 | NotificationConfiguration: { |
| 304 | SnsConfiguration: { TopicArn: news.notificationTopicArn }, |
| 305 | }, |
| 306 | ScheduledQueryExecutionRoleArn: news.executionRoleArn, |
| 307 | TargetConfiguration: news.targetConfiguration, |
| 308 | ErrorReportConfiguration: { |
| 309 | S3Configuration: { |
| 310 | BucketName: news.errorReportS3.bucketName, |
| 311 | ObjectKeyPrefix: news.errorReportS3.objectKeyPrefix, |
| 312 | EncryptionOption: news.errorReportS3.encryptionOption, |
| 313 | }, |
| 314 | }, |
| 315 | KmsKeyId: news.kmsKeyId, |
| 316 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 317 | Key, |
| 318 | Value, |
| 319 | })), |
| 320 | }), |
| 321 | ).pipe(Effect.catchTag("ConflictException", () => Effect.void)); |
| 322 | yield* session.note(`Creating scheduled query ${name}...`); |
| 323 | state = yield* findScheduledQueryByName(name); |
| 324 | if (state === undefined) { |
| 325 | return yield* new ScheduledQueryUnexpectedResponse({ |
| 326 | message: `failed to read created scheduled query ${name}`, |
| 327 | }); |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | // Sync state — the only in-place mutable aspect. |
| 332 | const desiredState = news.state ?? "ENABLED"; |
| 333 | if (state.state !== desiredState) { |
| 334 | yield* withQueryEndpoint( |
| 335 | TSQ.updateScheduledQuery({ |
| 336 | ScheduledQueryArn: state.scheduledQueryArn, |
| 337 | State: desiredState, |
| 338 | }), |
| 339 | ); |
| 340 | yield* session.note(`Updated scheduled query ${name} state to ${desiredState}`); |
| 341 | } |
| 342 | |
| 343 | // Sync tags — diff against observed cloud tags. |
| 344 | const { removed, upsert } = diffTags(state.tags, desiredTags); |
| 345 | if (removed.length > 0) { |
| 346 | yield* withQueryEndpoint( |
| 347 | TSQ.untagResource({ |
| 348 | ResourceARN: state.scheduledQueryArn, |
| 349 | TagKeys: removed, |
| 350 | }), |
| 351 | ); |
| 352 | } |
| 353 | if (upsert.length > 0) { |
| 354 | yield* withQueryEndpoint( |
| 355 | TSQ.tagResource({ |
| 356 | ResourceARN: state.scheduledQueryArn, |
| 357 | Tags: upsert.map(({ Key, Value }) => ({ Key, Value })), |
| 358 | }), |
| 359 | ); |
| 360 | } |
| 361 | |
| 362 | yield* session.note(state.scheduledQueryArn); |
| 363 | |
| 364 | const final = yield* readScheduledQuery(state.scheduledQueryArn); |
| 365 | if (!final) { |
| 366 | return yield* new ScheduledQueryUnexpectedResponse({ |
| 367 | message: `failed to read reconciled scheduled query ${name}`, |
| 368 | }); |
| 369 | } |
| 370 | return final; |
| 371 | }), |
| 372 | delete: Effect.fn(function* ({ output }) { |
| 373 | yield* withQueryEndpoint( |
| 374 | TSQ.deleteScheduledQuery({ |
| 375 | ScheduledQueryArn: output.scheduledQueryArn, |
| 376 | }), |
| 377 | ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 378 | }), |
| 379 | }; |
| 380 | }), |
| 381 | ); |