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 memorydb from "@distilled.cloud/aws/memorydb"; |
| 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 | import { readMemoryDbTags } from "./internal.ts"; |
| 14 | |
| 15 | export class ACLNotReady extends Data.TaggedError("ACLNotReady")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | export class ACLUnexpectedResponse extends Data.TaggedError("ACLUnexpectedResponse")<{ |
| 21 | readonly message: string; |
| 22 | readonly cause?: unknown; |
| 23 | }> {} |
| 24 | |
| 25 | export interface ACLProps { |
| 26 | /** |
| 27 | * Name of the Access Control List. Must be 1-40 alphanumeric characters. If |
| 28 | * omitted, a deterministic physical name is generated. Changing the name |
| 29 | * replaces the ACL. |
| 30 | */ |
| 31 | aclName?: string; |
| 32 | /** |
| 33 | * Names of the {@link User}s in this ACL. The account's built-in `default` |
| 34 | * user belongs to the reserved `open-access` ACL and cannot be added to a |
| 35 | * custom ACL — reference your own {@link User}s here instead. |
| 36 | * @default [] (an empty ACL) |
| 37 | */ |
| 38 | userNames?: string[]; |
| 39 | /** |
| 40 | * User-defined tags for the ACL. |
| 41 | */ |
| 42 | tags?: Record<string, string>; |
| 43 | } |
| 44 | |
| 45 | export interface ACL extends Resource< |
| 46 | "AWS.MemoryDB.ACL", |
| 47 | ACLProps, |
| 48 | { |
| 49 | /** Name of the ACL. */ |
| 50 | aclName: string; |
| 51 | /** ARN of the ACL. */ |
| 52 | aclArn: string; |
| 53 | /** Current lifecycle status (e.g. `creating`, `active`). */ |
| 54 | status: string; |
| 55 | /** Names of the users in the ACL. */ |
| 56 | userNames: string[]; |
| 57 | /** Minimum engine version the ACL is compatible with. */ |
| 58 | minimumEngineVersion: string | undefined; |
| 59 | /** Tags on the ACL (user + internal Alchemy tags). */ |
| 60 | tags: Record<string, string>; |
| 61 | }, |
| 62 | never, |
| 63 | Providers |
| 64 | > {} |
| 65 | |
| 66 | /** |
| 67 | * A MemoryDB Access Control List (ACL) — a named collection of {@link User}s |
| 68 | * that a cluster authenticates against. Attach an ACL to a |
| 69 | * {@link Cluster} via `aclName`. |
| 70 | * |
| 71 | * ACLs are free and provision quickly. |
| 72 | * ### Creating an ACL |
| 73 | * **Example:** ACL with a Custom User |
| 74 | * ```typescript |
| 75 | * const appUser = yield* User("AppUser", { |
| 76 | * authenticationMode: { type: "password", passwords: [appPassword] }, |
| 77 | * accessString: "on ~* +@all", |
| 78 | * }); |
| 79 | * const acl = yield* ACL("AppAcl", { |
| 80 | * userNames: [appUser.userName], |
| 81 | * }); |
| 82 | * ``` |
| 83 | * |
| 84 | * @resource |
| 85 | */ |
| 86 | export const ACL = Resource<ACL>("AWS.MemoryDB.ACL"); |
| 87 | |
| 88 | export const ACLProvider = () => |
| 89 | Provider.effect( |
| 90 | ACL, |
| 91 | Effect.gen(function* () { |
| 92 | const toName = (id: string, props: ACLProps) => |
| 93 | props.aclName |
| 94 | ? Effect.succeed(props.aclName) |
| 95 | : createPhysicalName({ id, maxLength: 40, lowercase: true }); |
| 96 | |
| 97 | const desiredUsers = (props: ACLProps): string[] => props.userNames ?? []; |
| 98 | |
| 99 | const readAcl = Effect.fn(function* (name: string) { |
| 100 | const response = yield* memorydb |
| 101 | .describeACLs({ ACLName: name }) |
| 102 | .pipe(Effect.catchTag("ACLNotFoundFault", () => Effect.undefined)); |
| 103 | return response?.ACLs?.[0]; |
| 104 | }); |
| 105 | |
| 106 | // Wait for the ACL to leave a transitional state before mutating or |
| 107 | // deleting it (avoids InvalidACLStateFault). |
| 108 | const waitUntilActive = Effect.fn(function* (name: string) { |
| 109 | return yield* readAcl(name).pipe( |
| 110 | Effect.flatMap((acl) => { |
| 111 | if (acl !== undefined && acl.Status !== "active" && acl.Status !== undefined) { |
| 112 | return Effect.fail( |
| 113 | new ACLNotReady({ message: `ACL '${name}' not active (${acl.Status})` }), |
| 114 | ); |
| 115 | } |
| 116 | return Effect.succeed(acl); |
| 117 | }), |
| 118 | Effect.retry({ |
| 119 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]), |
| 120 | }), |
| 121 | ); |
| 122 | }); |
| 123 | |
| 124 | const toAttrs = Effect.fn(function* (acl: memorydb.ACL) { |
| 125 | if (!acl.Name || !acl.ARN) { |
| 126 | return yield* new ACLUnexpectedResponse({ |
| 127 | message: `ACL '${acl.Name}' is missing its ARN`, |
| 128 | }); |
| 129 | } |
| 130 | return { |
| 131 | aclName: acl.Name, |
| 132 | aclArn: acl.ARN, |
| 133 | status: acl.Status ?? "active", |
| 134 | userNames: [...(acl.UserNames ?? [])], |
| 135 | minimumEngineVersion: acl.MinimumEngineVersion, |
| 136 | tags: yield* readMemoryDbTags(acl.ARN), |
| 137 | }; |
| 138 | }); |
| 139 | |
| 140 | return { |
| 141 | stables: ["aclName", "aclArn"], |
| 142 | |
| 143 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 144 | if (!isResolved(news)) return undefined; |
| 145 | if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) { |
| 146 | return { action: "replace" } as const; |
| 147 | } |
| 148 | }), |
| 149 | |
| 150 | read: Effect.fn(function* ({ id, olds, output }) { |
| 151 | const name = output?.aclName ?? (yield* toName(id, olds ?? {})); |
| 152 | const acl = yield* readAcl(name); |
| 153 | if (!acl?.ARN) return undefined; |
| 154 | const attrs = yield* toAttrs(acl); |
| 155 | return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs); |
| 156 | }), |
| 157 | |
| 158 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 159 | const props = news ?? {}; |
| 160 | const name = output?.aclName ?? (yield* toName(id, props)); |
| 161 | const internalTags = yield* createInternalTags(id); |
| 162 | const desiredTags = { ...internalTags, ...props.tags }; |
| 163 | const desired = desiredUsers(props); |
| 164 | |
| 165 | // 1. Observe — cloud state is authoritative. |
| 166 | let observed = yield* readAcl(name); |
| 167 | |
| 168 | // 2. Ensure — create if missing; tolerate AlreadyExists as a race. |
| 169 | if (observed === undefined) { |
| 170 | yield* memorydb |
| 171 | .createACL({ |
| 172 | ACLName: name, |
| 173 | UserNames: desired, |
| 174 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 175 | Key, |
| 176 | Value, |
| 177 | })), |
| 178 | }) |
| 179 | .pipe(Effect.catchTag("ACLAlreadyExistsFault", () => Effect.void)); |
| 180 | observed = yield* waitUntilActive(name); |
| 181 | } |
| 182 | if (observed === undefined) { |
| 183 | return yield* new ACLUnexpectedResponse({ |
| 184 | message: `ACL '${name}' not found after create`, |
| 185 | }); |
| 186 | } |
| 187 | |
| 188 | // 3. Sync — compute the user membership delta from OBSERVED state. |
| 189 | const observedUsers = new Set(observed.UserNames ?? []); |
| 190 | const desiredSet = new Set(desired); |
| 191 | const toAdd = desired.filter((u) => !observedUsers.has(u)); |
| 192 | const toRemove = [...observedUsers].filter((u) => !desiredSet.has(u)); |
| 193 | if (toAdd.length > 0 || toRemove.length > 0) { |
| 194 | yield* memorydb.updateACL({ |
| 195 | ACLName: name, |
| 196 | ...(toAdd.length > 0 ? { UserNamesToAdd: toAdd } : {}), |
| 197 | ...(toRemove.length > 0 ? { UserNamesToRemove: toRemove } : {}), |
| 198 | }); |
| 199 | observed = (yield* waitUntilActive(name)) ?? observed; |
| 200 | } |
| 201 | |
| 202 | // 3b. Sync tags — diff against OBSERVED cloud tags. |
| 203 | const arn = observed.ARN; |
| 204 | if (arn) { |
| 205 | const observedTags = yield* readMemoryDbTags(arn); |
| 206 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 207 | if (upsert.length > 0) { |
| 208 | yield* memorydb.tagResource({ ResourceArn: arn, Tags: upsert }); |
| 209 | } |
| 210 | if (removed.length > 0) { |
| 211 | yield* memorydb.untagResource({ |
| 212 | ResourceArn: arn, |
| 213 | TagKeys: removed, |
| 214 | }); |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | yield* session.note(name); |
| 219 | return yield* toAttrs(observed); |
| 220 | }), |
| 221 | |
| 222 | delete: Effect.fn(function* ({ output }) { |
| 223 | const name = output.aclName; |
| 224 | // The ACL must be detached from any cluster first; while it is still |
| 225 | // in use (or mid-modify) deletion rejects with InvalidACLStateFault. |
| 226 | // Retry bounded; NotFound is success. |
| 227 | yield* waitUntilActive(name).pipe(Effect.catch(() => Effect.void)); |
| 228 | yield* memorydb.deleteACL({ ACLName: name }).pipe( |
| 229 | Effect.catchTag("ACLNotFoundFault", () => Effect.void), |
| 230 | Effect.retry({ |
| 231 | while: (e) => e._tag === "InvalidACLStateFault", |
| 232 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(12)]), |
| 233 | }), |
| 234 | ); |
| 235 | }), |
| 236 | |
| 237 | list: () => |
| 238 | memorydb.describeACLs.pages({}).pipe( |
| 239 | Stream.runCollect, |
| 240 | Effect.map((chunk) => |
| 241 | Array.from(chunk).flatMap((page) => |
| 242 | (page.ACLs ?? []).filter( |
| 243 | (acl) => |
| 244 | acl.Name !== undefined && |
| 245 | acl.ARN !== undefined && |
| 246 | // `open-access` is the AWS-managed default ACL that |
| 247 | // always exists and can never be deleted — keep it out |
| 248 | // of enumeration for account-wide teardown (nuke). |
| 249 | acl.Name !== "open-access", |
| 250 | ), |
| 251 | ), |
| 252 | ), |
| 253 | Effect.flatMap(Effect.forEach((acl) => toAttrs(acl), { concurrency: 4 })), |
| 254 | ), |
| 255 | }; |
| 256 | }), |
| 257 | ); |