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 type * as Redacted from "effect/Redacted"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { readMemoryDbTags } from "./internal.ts"; |
| 15 | |
| 16 | export class MemoryDBUserNotReady extends Data.TaggedError("MemoryDBUserNotReady")<{ |
| 17 | readonly message: string; |
| 18 | readonly cause?: unknown; |
| 19 | }> {} |
| 20 | |
| 21 | export class MemoryDBUserUnexpectedResponse extends Data.TaggedError( |
| 22 | "MemoryDBUserUnexpectedResponse", |
| 23 | )<{ |
| 24 | readonly message: string; |
| 25 | readonly cause?: unknown; |
| 26 | }> {} |
| 27 | |
| 28 | /** |
| 29 | * Authentication mode for a MemoryDB user. |
| 30 | */ |
| 31 | export interface UserAuthenticationMode { |
| 32 | /** |
| 33 | * How the user authenticates: |
| 34 | * - `"password"` — one or two SHA-256 passwords (supplied in `passwords`). |
| 35 | * - `"iam"` — IAM authentication; the username must match the IAM identity. |
| 36 | * - `"no-password"` — the user has no password (typically the default user). |
| 37 | */ |
| 38 | type: "password" | "iam" | "no-password"; |
| 39 | /** |
| 40 | * One or two passwords (16-128 printable characters each). Required when |
| 41 | * `type` is `"password"`. Passwords are write-only — the API never returns |
| 42 | * them, so changes to `passwords` alone are not auto-detected on update; |
| 43 | * change `type` (or replace the user) to force a credential reset. |
| 44 | */ |
| 45 | passwords?: Redacted.Redacted<string>[]; |
| 46 | } |
| 47 | |
| 48 | export interface UserProps { |
| 49 | /** |
| 50 | * Name of the user. Must be 1-40 alphanumeric characters. If omitted, a |
| 51 | * deterministic physical name is generated. Changing the name replaces the |
| 52 | * user. |
| 53 | */ |
| 54 | userName?: string; |
| 55 | /** |
| 56 | * How the user authenticates. |
| 57 | */ |
| 58 | authenticationMode: UserAuthenticationMode; |
| 59 | /** |
| 60 | * Redis ACL access string describing the user's permissions, e.g. |
| 61 | * `"on ~* +@all"`. See the MemoryDB / Redis ACL documentation. |
| 62 | */ |
| 63 | accessString: string; |
| 64 | /** |
| 65 | * User-defined tags for the user. |
| 66 | */ |
| 67 | tags?: Record<string, string>; |
| 68 | } |
| 69 | |
| 70 | export interface User extends Resource< |
| 71 | "AWS.MemoryDB.User", |
| 72 | UserProps, |
| 73 | { |
| 74 | /** Name of the user. */ |
| 75 | userName: string; |
| 76 | /** ARN of the user. */ |
| 77 | userArn: string; |
| 78 | /** Current lifecycle status (e.g. `active`, `modifying`). */ |
| 79 | status: string; |
| 80 | /** Access string defining the user's permissions. */ |
| 81 | accessString: string | undefined; |
| 82 | /** How the user authenticates (`password` or `iam`). */ |
| 83 | authenticationType: string | undefined; |
| 84 | /** Minimum engine version the user is compatible with. */ |
| 85 | minimumEngineVersion: string | undefined; |
| 86 | /** Tags on the user (user + internal Alchemy tags). */ |
| 87 | tags: Record<string, string>; |
| 88 | }, |
| 89 | never, |
| 90 | Providers |
| 91 | > {} |
| 92 | |
| 93 | /** |
| 94 | * A MemoryDB user — an RBAC identity that authenticates to a cluster and is |
| 95 | * granted permissions through an access string. Users are grouped into |
| 96 | * {@link ACL}s, which are attached to clusters. |
| 97 | * |
| 98 | * Users are free and provision quickly. Passwords are write-only. |
| 99 | * ### Creating a User |
| 100 | * **Example:** Password User with Full Access |
| 101 | * ```typescript |
| 102 | * const user = yield* User("AppUser", { |
| 103 | * authenticationMode: { type: "password", passwords: [appPassword] }, |
| 104 | * accessString: "on ~* +@all", |
| 105 | * }); |
| 106 | * ``` |
| 107 | * |
| 108 | * **Example:** IAM-Authenticated User |
| 109 | * ```typescript |
| 110 | * const user = yield* User("IamUser", { |
| 111 | * userName: "iam-app-user", |
| 112 | * authenticationMode: { type: "iam" }, |
| 113 | * accessString: "on ~* +@all", |
| 114 | * }); |
| 115 | * ``` |
| 116 | * |
| 117 | * @resource |
| 118 | */ |
| 119 | export const User = Resource<User>("AWS.MemoryDB.User"); |
| 120 | |
| 121 | export const UserProvider = () => |
| 122 | Provider.effect( |
| 123 | User, |
| 124 | Effect.gen(function* () { |
| 125 | const toName = (id: string, props: Partial<UserProps>) => |
| 126 | props.userName |
| 127 | ? Effect.succeed(props.userName) |
| 128 | : createPhysicalName({ id, maxLength: 40, lowercase: true }); |
| 129 | |
| 130 | const readUser = Effect.fn(function* (name: string) { |
| 131 | const response = yield* memorydb |
| 132 | .describeUsers({ UserName: name }) |
| 133 | .pipe(Effect.catchTag("UserNotFoundFault", () => Effect.undefined)); |
| 134 | return response?.Users?.[0]; |
| 135 | }); |
| 136 | |
| 137 | // Wait for the user to leave a transitional (modifying) state so a |
| 138 | // subsequent modify/delete does not hit InvalidUserStateFault. |
| 139 | const waitUntilActive = Effect.fn(function* (name: string) { |
| 140 | return yield* readUser(name).pipe( |
| 141 | Effect.flatMap((user) => { |
| 142 | if (user !== undefined && user.Status === "modifying") { |
| 143 | return Effect.fail( |
| 144 | new MemoryDBUserNotReady({ |
| 145 | message: `User '${name}' still modifying (${user.Status})`, |
| 146 | }), |
| 147 | ); |
| 148 | } |
| 149 | return Effect.succeed(user); |
| 150 | }), |
| 151 | Effect.retry({ |
| 152 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]), |
| 153 | }), |
| 154 | ); |
| 155 | }); |
| 156 | |
| 157 | const toAttrs = Effect.fn(function* (user: memorydb.User) { |
| 158 | if (!user.Name || !user.ARN) { |
| 159 | return yield* new MemoryDBUserUnexpectedResponse({ |
| 160 | message: `User '${user.Name}' is missing its ARN`, |
| 161 | }); |
| 162 | } |
| 163 | return { |
| 164 | userName: user.Name, |
| 165 | userArn: user.ARN, |
| 166 | status: user.Status ?? "active", |
| 167 | accessString: user.AccessString, |
| 168 | authenticationType: user.Authentication?.Type, |
| 169 | minimumEngineVersion: user.MinimumEngineVersion, |
| 170 | tags: yield* readMemoryDbTags(user.ARN), |
| 171 | }; |
| 172 | }); |
| 173 | |
| 174 | // Distilled types `Passwords` as sensitive — pass the Redacted values |
| 175 | // through as-is so they stay redacted in traces and logs. |
| 176 | const toWireAuth = (mode: UserAuthenticationMode): memorydb.AuthenticationMode => ({ |
| 177 | Type: mode.type, |
| 178 | ...(mode.passwords ? { Passwords: mode.passwords } : {}), |
| 179 | }); |
| 180 | |
| 181 | return { |
| 182 | stables: ["userName", "userArn"], |
| 183 | |
| 184 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 185 | if (!isResolved(news)) return undefined; |
| 186 | if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) { |
| 187 | return { action: "replace" } as const; |
| 188 | } |
| 189 | }), |
| 190 | |
| 191 | read: Effect.fn(function* ({ id, olds, output }) { |
| 192 | const name = output?.userName ?? (yield* toName(id, olds ?? {})); |
| 193 | const user = yield* readUser(name); |
| 194 | if (!user?.ARN) return undefined; |
| 195 | const attrs = yield* toAttrs(user); |
| 196 | return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs); |
| 197 | }), |
| 198 | |
| 199 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 200 | const props = news!; |
| 201 | const name = output?.userName ?? (yield* toName(id, props)); |
| 202 | const internalTags = yield* createInternalTags(id); |
| 203 | const desiredTags = { ...internalTags, ...props.tags }; |
| 204 | |
| 205 | // 1. Observe — cloud state is authoritative. |
| 206 | let observed = yield* readUser(name); |
| 207 | |
| 208 | // 2. Ensure — create if missing; tolerate AlreadyExists as a race. |
| 209 | if (observed === undefined) { |
| 210 | yield* memorydb |
| 211 | .createUser({ |
| 212 | UserName: name, |
| 213 | AuthenticationMode: toWireAuth(props.authenticationMode), |
| 214 | AccessString: props.accessString, |
| 215 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 216 | Key, |
| 217 | Value, |
| 218 | })), |
| 219 | }) |
| 220 | .pipe( |
| 221 | Effect.catchTags({ |
| 222 | UserAlreadyExistsFault: () => Effect.void, |
| 223 | DuplicateUserNameFault: () => Effect.void, |
| 224 | }), |
| 225 | ); |
| 226 | observed = yield* waitUntilActive(name); |
| 227 | } |
| 228 | if (observed === undefined) { |
| 229 | return yield* new MemoryDBUserUnexpectedResponse({ |
| 230 | message: `User '${name}' not found after create`, |
| 231 | }); |
| 232 | } |
| 233 | |
| 234 | // 3. Sync — access string is observable; auth passwords are not, so |
| 235 | // only re-apply the auth mode when its observable TYPE changed. |
| 236 | const update: memorydb.UpdateUserRequest = { UserName: name }; |
| 237 | let mutated = false; |
| 238 | if (props.accessString !== observed.AccessString) { |
| 239 | update.AccessString = props.accessString; |
| 240 | mutated = true; |
| 241 | } |
| 242 | if (props.authenticationMode.type !== observed.Authentication?.Type) { |
| 243 | update.AuthenticationMode = toWireAuth(props.authenticationMode); |
| 244 | mutated = true; |
| 245 | } |
| 246 | if (mutated) { |
| 247 | yield* memorydb.updateUser(update); |
| 248 | observed = (yield* waitUntilActive(name)) ?? observed; |
| 249 | } |
| 250 | |
| 251 | // 3b. Sync tags — diff against OBSERVED cloud tags. |
| 252 | const arn = observed.ARN; |
| 253 | if (arn) { |
| 254 | const observedTags = yield* readMemoryDbTags(arn); |
| 255 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 256 | if (upsert.length > 0) { |
| 257 | yield* memorydb.tagResource({ ResourceArn: arn, Tags: upsert }); |
| 258 | } |
| 259 | if (removed.length > 0) { |
| 260 | yield* memorydb.untagResource({ |
| 261 | ResourceArn: arn, |
| 262 | TagKeys: removed, |
| 263 | }); |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | yield* session.note(name); |
| 268 | return yield* toAttrs(observed); |
| 269 | }), |
| 270 | |
| 271 | delete: Effect.fn(function* ({ output }) { |
| 272 | const name = output.userName; |
| 273 | // A user mid-modify rejects deletion — settle first (bounded), then |
| 274 | // delete. NotFound is success (idempotent delete). |
| 275 | yield* waitUntilActive(name).pipe(Effect.catch(() => Effect.void)); |
| 276 | yield* memorydb.deleteUser({ UserName: name }).pipe( |
| 277 | Effect.catchTag("UserNotFoundFault", () => Effect.void), |
| 278 | Effect.retry({ |
| 279 | while: (e) => e._tag === "InvalidUserStateFault", |
| 280 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(12)]), |
| 281 | }), |
| 282 | ); |
| 283 | }), |
| 284 | |
| 285 | list: () => |
| 286 | memorydb.describeUsers.pages({}).pipe( |
| 287 | Stream.runCollect, |
| 288 | Effect.map((chunk) => |
| 289 | Array.from(chunk).flatMap((page) => |
| 290 | (page.Users ?? []).filter( |
| 291 | (user) => |
| 292 | user.Name !== undefined && |
| 293 | user.ARN !== undefined && |
| 294 | // `default` is the AWS-managed default user that always |
| 295 | // exists and can never be deleted — keep it out of |
| 296 | // enumeration for account-wide teardown (nuke). |
| 297 | user.Name !== "default", |
| 298 | ), |
| 299 | ), |
| 300 | ), |
| 301 | Effect.flatMap(Effect.forEach((user) => toAttrs(user), { concurrency: 4 })), |
| 302 | ), |
| 303 | }; |
| 304 | }), |
| 305 | ); |