The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as keyspaces from "@distilled.cloud/aws/keyspaces"; |
| 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 type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | export class KeyspaceNotReady extends Data.TaggedError("KeyspaceNotReady")<{ |
| 15 | readonly message: string; |
| 16 | readonly cause?: unknown; |
| 17 | }> {} |
| 18 | |
| 19 | export interface KeyspaceProps { |
| 20 | /** |
| 21 | * Name of the keyspace. Must be 1-48 characters of `[a-zA-Z0-9_]`. If |
| 22 | * omitted a deterministic physical name is generated. Changing the name |
| 23 | * replaces the keyspace. |
| 24 | */ |
| 25 | keyspaceName?: string; |
| 26 | /** |
| 27 | * User-defined tags for the keyspace. |
| 28 | */ |
| 29 | tags?: Record<string, string>; |
| 30 | } |
| 31 | |
| 32 | export interface Keyspace extends Resource< |
| 33 | "AWS.Keyspaces.Keyspace", |
| 34 | KeyspaceProps, |
| 35 | { |
| 36 | /** |
| 37 | * The keyspace's physical name. |
| 38 | */ |
| 39 | keyspaceName: string; |
| 40 | /** |
| 41 | * ARN of the keyspace. |
| 42 | */ |
| 43 | keyspaceArn: string; |
| 44 | /** |
| 45 | * Replication strategy of the keyspace (`SINGLE_REGION` or |
| 46 | * `MULTI_REGION`). |
| 47 | */ |
| 48 | replicationStrategy: string; |
| 49 | }, |
| 50 | never, |
| 51 | Providers |
| 52 | > {} |
| 53 | |
| 54 | /** |
| 55 | * An Amazon Keyspaces (for Apache Cassandra) keyspace — the top-level |
| 56 | * container for Cassandra tables. |
| 57 | * |
| 58 | * Keyspaces are serverless, free to create, and provisioned near-instantly, |
| 59 | * so they make excellent building blocks and test fixtures. |
| 60 | * ### Creating a Keyspace |
| 61 | * **Example:** Basic Keyspace |
| 62 | * ```typescript |
| 63 | * const keyspace = yield* Keyspace("AppData", {}); |
| 64 | * ``` |
| 65 | * |
| 66 | * **Example:** Named Keyspace with Tags |
| 67 | * ```typescript |
| 68 | * const keyspace = yield* Keyspace("AppData", { |
| 69 | * keyspaceName: "app_data", |
| 70 | * tags: { team: "platform" }, |
| 71 | * }); |
| 72 | * ``` |
| 73 | * |
| 74 | * @resource |
| 75 | */ |
| 76 | export const Keyspace = Resource<Keyspace>("AWS.Keyspaces.Keyspace"); |
| 77 | |
| 78 | const toTagRecord = (tags: keyspaces.Tag[] | undefined): Record<string, string> => |
| 79 | Object.fromEntries((tags ?? []).map((t) => [t.key, t.value])); |
| 80 | |
| 81 | /** |
| 82 | * Reserved Cassandra system keyspaces that exist in every Amazon Keyspaces |
| 83 | * account and can never be deleted. Excluded from `list()` so account-wide |
| 84 | * teardown (`alchemy unsafe nuke`) doesn't loop on undeletable resources. |
| 85 | */ |
| 86 | const SYSTEM_KEYSPACES = new Set([ |
| 87 | "system", |
| 88 | "system_schema", |
| 89 | "system_schema_mcs", |
| 90 | "system_multiregion_info", |
| 91 | ]); |
| 92 | |
| 93 | export const KeyspaceProvider = () => |
| 94 | Provider.effect( |
| 95 | Keyspace, |
| 96 | Effect.gen(function* () { |
| 97 | const toName = (id: string, props: KeyspaceProps) => |
| 98 | props.keyspaceName |
| 99 | ? Effect.succeed(props.keyspaceName) |
| 100 | : createPhysicalName({ id, maxLength: 48 }).pipe( |
| 101 | Effect.map((n) => n.replaceAll("-", "_")), |
| 102 | ); |
| 103 | |
| 104 | const readKeyspace = Effect.fn(function* (name: string) { |
| 105 | return yield* keyspaces |
| 106 | .getKeyspace({ keyspaceName: name }) |
| 107 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 108 | }); |
| 109 | |
| 110 | const readTags = Effect.fn(function* (arn: string) { |
| 111 | const tags = yield* keyspaces.listTagsForResource.items({ resourceArn: arn }).pipe( |
| 112 | Stream.runCollect, |
| 113 | Effect.map((c) => Array.from(c)), |
| 114 | Effect.orElseSucceed(() => []), |
| 115 | ); |
| 116 | return toTagRecord(tags); |
| 117 | }); |
| 118 | |
| 119 | return { |
| 120 | stables: ["keyspaceName", "keyspaceArn"], |
| 121 | |
| 122 | diff: Effect.fn(function* ({ id, olds = {}, news }) { |
| 123 | if (!isResolved(news)) return undefined; |
| 124 | if ((yield* toName(id, olds)) !== (yield* toName(id, news))) { |
| 125 | return { action: "replace" } as const; |
| 126 | } |
| 127 | }), |
| 128 | |
| 129 | read: Effect.fn(function* ({ id, olds, output }) { |
| 130 | const name = output?.keyspaceName ?? (yield* toName(id, olds ?? {})); |
| 131 | const found = yield* readKeyspace(name); |
| 132 | if (found === undefined) return undefined; |
| 133 | const attrs = { |
| 134 | keyspaceName: found.keyspaceName, |
| 135 | keyspaceArn: found.resourceArn, |
| 136 | replicationStrategy: found.replicationStrategy, |
| 137 | }; |
| 138 | const tags = yield* readTags(found.resourceArn); |
| 139 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 140 | }), |
| 141 | |
| 142 | reconcile: Effect.fn(function* ({ id, news = {}, output, session }) { |
| 143 | const name = output?.keyspaceName ?? (yield* toName(id, news)); |
| 144 | const internalTags = yield* createInternalTags(id); |
| 145 | const desiredTags = { ...internalTags, ...news.tags }; |
| 146 | |
| 147 | // 1. Observe — cloud state is authoritative. |
| 148 | let observed = yield* readKeyspace(name); |
| 149 | |
| 150 | // 2. Ensure — create if missing; tolerate the AlreadyExists race. |
| 151 | if (observed === undefined) { |
| 152 | yield* keyspaces |
| 153 | .createKeyspace({ |
| 154 | keyspaceName: name, |
| 155 | tags: Object.entries(desiredTags).map(([key, value]) => ({ |
| 156 | key, |
| 157 | value, |
| 158 | })), |
| 159 | }) |
| 160 | .pipe(Effect.catchTag("ConflictException", () => Effect.void)); |
| 161 | // Keyspace creation is effectively synchronous, but GetKeyspace can |
| 162 | // briefly 404 right after create; retry a few times. |
| 163 | observed = yield* readKeyspace(name).pipe( |
| 164 | Effect.flatMap((k) => |
| 165 | k === undefined |
| 166 | ? Effect.fail(new KeyspaceNotReady({ message: `Keyspace '${name}' not found` })) |
| 167 | : Effect.succeed(k), |
| 168 | ), |
| 169 | Effect.retry({ |
| 170 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]), |
| 171 | }), |
| 172 | ); |
| 173 | } |
| 174 | |
| 175 | // 3. Sync tags — diff against OBSERVED cloud tags. |
| 176 | const observedTags = yield* readTags(observed.resourceArn); |
| 177 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 178 | if (upsert.length > 0) { |
| 179 | yield* keyspaces.tagResource({ |
| 180 | resourceArn: observed.resourceArn, |
| 181 | tags: upsert.map((t) => ({ key: t.Key, value: t.Value })), |
| 182 | }); |
| 183 | } |
| 184 | if (removed.length > 0) { |
| 185 | yield* keyspaces.untagResource({ |
| 186 | resourceArn: observed.resourceArn, |
| 187 | tags: removed.map((key) => ({ key, value: "" })), |
| 188 | }); |
| 189 | } |
| 190 | |
| 191 | yield* session.note(name); |
| 192 | return { |
| 193 | keyspaceName: observed.keyspaceName, |
| 194 | keyspaceArn: observed.resourceArn, |
| 195 | replicationStrategy: observed.replicationStrategy, |
| 196 | }; |
| 197 | }), |
| 198 | |
| 199 | delete: Effect.fn(function* ({ output }) { |
| 200 | const name = output.keyspaceName; |
| 201 | yield* keyspaces.deleteKeyspace({ keyspaceName: name }).pipe( |
| 202 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 203 | // A keyspace whose tables are still deleting rejects with |
| 204 | // ConflictException until they are gone — minutes for PITR and |
| 205 | // restored tables, beyond the point GetTable already 404s. |
| 206 | Effect.retry({ |
| 207 | while: (e) => e._tag === "ConflictException", |
| 208 | schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(48)]), |
| 209 | }), |
| 210 | ); |
| 211 | // Deletion is asynchronous — wait (bounded) until the keyspace is |
| 212 | // actually gone so a subsequent recreate with the same name does not |
| 213 | // hit ConflictException. |
| 214 | yield* readKeyspace(name).pipe( |
| 215 | Effect.flatMap((k) => |
| 216 | k === undefined |
| 217 | ? Effect.void |
| 218 | : Effect.fail( |
| 219 | new KeyspaceNotReady({ message: `Keyspace '${name}' still deleting` }), |
| 220 | ), |
| 221 | ), |
| 222 | Effect.retry({ |
| 223 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]), |
| 224 | }), |
| 225 | Effect.ignore, |
| 226 | ); |
| 227 | }), |
| 228 | |
| 229 | list: () => |
| 230 | keyspaces.listKeyspaces.items({}).pipe( |
| 231 | Stream.runCollect, |
| 232 | Effect.map((chunk) => |
| 233 | Array.from(chunk) |
| 234 | .filter((k) => !SYSTEM_KEYSPACES.has(k.keyspaceName)) |
| 235 | .map((k) => ({ |
| 236 | keyspaceName: k.keyspaceName, |
| 237 | keyspaceArn: k.resourceArn, |
| 238 | replicationStrategy: k.replicationStrategy, |
| 239 | })), |
| 240 | ), |
| 241 | ), |
| 242 | }; |
| 243 | }), |
| 244 | ); |