The best way to control Claude Code, Codex and more from any computer or phone

main
ts 390 lines 13.7 KB
Raw
1 import * as redshiftserverless from "@distilled.cloud/aws/redshift-serverless";
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, 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 { readTags, syncTags, toWireTags } from "./internal.ts";
15
16 export class RedshiftServerlessNamespaceUnexpectedResponse extends Data.TaggedError(
17 "RedshiftServerlessNamespaceUnexpectedResponse",
18 )<{
19 readonly message: string;
20 readonly cause?: unknown;
21 }> {}
22
23 export interface NamespaceProps {
24 /**
25 * Name of the namespace. Must be 3-64 characters, lowercase letters,
26 * numbers, and hyphens. If omitted, a deterministic physical name is
27 * generated. Changing the name replaces the namespace.
28 */
29 namespaceName?: string;
30 /**
31 * Name of the first database created in the namespace. Changing the
32 * database name replaces the namespace.
33 * @default "dev"
34 */
35 dbName?: string;
36 /**
37 * Administrator username for the namespace's initial database. Provide it
38 * together with `adminUserPassword`, or set `manageAdminPassword` to have
39 * Redshift store a generated password in Secrets Manager.
40 */
41 adminUsername?: string;
42 /**
43 * Administrator password. Ignored when `manageAdminPassword` is true.
44 */
45 adminUserPassword?: Redacted.Redacted<string>;
46 /**
47 * Let Redshift generate and manage the admin password in Secrets Manager.
48 * The secret ARN is returned as `adminPasswordSecretArn`.
49 * @default false
50 */
51 manageAdminPassword?: boolean;
52 /**
53 * Customer-managed KMS key ID used to encrypt the Secrets Manager secret
54 * that holds the managed admin password.
55 */
56 adminPasswordSecretKmsKeyId?: string;
57 /**
58 * Customer-managed KMS key ID used to encrypt the namespace's data.
59 * Changing the key replaces the namespace.
60 * @default AWS-owned key
61 */
62 kmsKeyId?: string;
63 /**
64 * ARN of the IAM role set as the namespace's default role. Must also be a
65 * member of `iamRoles`.
66 */
67 defaultIamRoleArn?: string;
68 /**
69 * ARNs of IAM roles associated with the namespace (used by COPY/UNLOAD and
70 * other role-based features).
71 */
72 iamRoles?: string[];
73 /**
74 * Log types exported to CloudWatch Logs: `userlog`, `connectionlog`,
75 * and/or `useractivitylog`.
76 */
77 logExports?: ("userlog" | "connectionlog" | "useractivitylog")[];
78 /**
79 * User-defined tags for the namespace.
80 */
81 tags?: Record<string, string>;
82 }
83
84 export interface Namespace extends Resource<
85 "AWS.RedshiftServerless.Namespace",
86 NamespaceProps,
87 {
88 /**
89 * Name of the namespace.
90 */
91 namespaceName: string;
92 /**
93 * ARN of the namespace.
94 */
95 namespaceArn: string;
96 /**
97 * Unique ID of the namespace.
98 */
99 namespaceId: string;
100 /**
101 * Name of the first database created in the namespace.
102 */
103 dbName: string | undefined;
104 /**
105 * ARN of the Secrets Manager secret holding the admin password when
106 * `manageAdminPassword` is enabled.
107 */
108 adminPasswordSecretArn: string | undefined;
109 /**
110 * Current namespace status (e.g. `"AVAILABLE"`).
111 */
112 status: string;
113 },
114 never,
115 Providers
116 > {}
117
118 /**
119 * An Amazon Redshift Serverless namespace — the storage-and-database half of
120 * a serverless data warehouse.
121 *
122 * A namespace holds databases, schemas, tables, admin credentials, and IAM
123 * roles. Compute is provided separately by a {@link Workgroup} that points at
124 * the namespace. Creating a namespace is quick (~1 minute); the provider
125 * waits (bounded) for it to become `AVAILABLE`.
126 *
127 * ### Creating a Namespace
128 * **Example:** Inline Admin Credentials
129 * ```typescript
130 * const namespace = yield* RedshiftServerless.Namespace("Analytics", {
131 * dbName: "analytics",
132 * adminUsername: "admin",
133 * adminUserPassword: Redacted.make("SuperSecret123!"),
134 * });
135 * ```
136 *
137 * **Example:** Secrets-Manager-Managed Admin Password
138 * ```typescript
139 * const namespace = yield* RedshiftServerless.Namespace("Analytics", {
140 * dbName: "analytics",
141 * adminUsername: "admin",
142 * manageAdminPassword: true,
143 * });
144 * // namespace.adminPasswordSecretArn -> the generated secret's ARN
145 * ```
146 *
147 * ### IAM Roles and Encryption
148 * **Example:** Default Role and Customer KMS Key
149 * ```typescript
150 * const namespace = yield* RedshiftServerless.Namespace("Analytics", {
151 * dbName: "analytics",
152 * defaultIamRoleArn: role.roleArn,
153 * iamRoles: [role.roleArn],
154 * kmsKeyId: key.keyId,
155 * logExports: ["userlog", "connectionlog"],
156 * });
157 * ```
158 *
159 * @resource
160 */
161 export const Namespace = Resource<Namespace>("AWS.RedshiftServerless.Namespace");
162
163 class NamespaceNotSettled extends Data.TaggedError("NamespaceNotSettled")<{
164 readonly namespaceName: string;
165 readonly status: string;
166 }> {}
167
168 const statusIs = (status: string | undefined, expected: string): boolean =>
169 status?.toUpperCase() === expected;
170
171 const sameStringSet = (a: string[], b: string[]): boolean => {
172 const as = [...a].sort();
173 const bs = [...b].sort();
174 return as.length === bs.length && as.every((v, i) => v === bs[i]);
175 };
176
177 export const NamespaceProvider = () =>
178 Provider.effect(
179 Namespace,
180 Effect.gen(function* () {
181 const toName = (id: string, props: Partial<NamespaceProps>) =>
182 props.namespaceName
183 ? Effect.succeed(props.namespaceName)
184 : createPhysicalName({ id, maxLength: 64 });
185
186 const readNamespace = Effect.fn(function* (name: string) {
187 const response = yield* redshiftserverless
188 .getNamespace({ namespaceName: name })
189 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
190 return response?.namespace;
191 });
192
193 // Namespace create/update converge through a MODIFYING status. It
194 // typically settles within a minute; budget ~3 min (36 * 5s).
195 const waitForAvailable = Effect.fn(function* (name: string) {
196 return yield* readNamespace(name).pipe(
197 Effect.flatMap((ns) =>
198 ns !== undefined && !statusIs(ns.status, "AVAILABLE")
199 ? Effect.fail(
200 new NamespaceNotSettled({
201 namespaceName: name,
202 status: ns.status ?? "UNKNOWN",
203 }),
204 )
205 : Effect.succeed(ns),
206 ),
207 Effect.retry({
208 while: (e) => e instanceof NamespaceNotSettled,
209 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(36)]),
210 }),
211 );
212 });
213
214 const waitUntilGone = Effect.fn(function* (name: string) {
215 yield* readNamespace(name).pipe(
216 Effect.flatMap((ns) =>
217 ns === undefined
218 ? Effect.void
219 : Effect.fail(
220 new NamespaceNotSettled({
221 namespaceName: name,
222 status: ns.status ?? "DELETING",
223 }),
224 ),
225 ),
226 Effect.retry({
227 while: (e) => e instanceof NamespaceNotSettled,
228 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(60)]),
229 }),
230 );
231 });
232
233 const toAttrs = (ns: redshiftserverless.Namespace) => ({
234 namespaceName: ns.namespaceName!,
235 namespaceArn: ns.namespaceArn!,
236 namespaceId: ns.namespaceId!,
237 dbName: ns.dbName,
238 adminPasswordSecretArn: ns.adminPasswordSecretArn,
239 status: ns.status ?? "UNKNOWN",
240 });
241
242 return {
243 stables: ["namespaceName", "namespaceArn", "namespaceId"],
244
245 diff: Effect.fn(function* ({ id, olds, news }) {
246 if (!isResolved(news)) return undefined;
247 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
248 return { action: "replace" } as const;
249 }
250 // dbName and the KMS key are create-only.
251 if ((news?.dbName ?? undefined) !== (olds?.dbName ?? undefined)) {
252 return { action: "replace" } as const;
253 }
254 if ((news?.kmsKeyId ?? undefined) !== (olds?.kmsKeyId ?? undefined)) {
255 return { action: "replace" } as const;
256 }
257 }),
258
259 read: Effect.fn(function* ({ id, olds, output }) {
260 const name = output?.namespaceName ?? (yield* toName(id, olds ?? {}));
261 const ns = yield* readNamespace(name);
262 if (ns === undefined) return undefined;
263 const attrs = toAttrs(ns);
264 const tags = yield* readTags(attrs.namespaceArn);
265 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
266 }),
267
268 reconcile: Effect.fn(function* ({ id, news, output, session }) {
269 const name = output?.namespaceName ?? (yield* toName(id, news));
270 const internalTags = yield* createInternalTags(id);
271 const desiredTags = { ...internalTags, ...news.tags };
272
273 // 1. Observe — cloud state is authoritative.
274 let observed = yield* readNamespace(name);
275
276 // 2. Ensure — create if missing; tolerate a concurrent create.
277 if (observed === undefined) {
278 const created = yield* redshiftserverless
279 .createNamespace({
280 namespaceName: name,
281 dbName: news.dbName,
282 adminUsername: news.adminUsername,
283 // Redshift generates the password when it manages it; passing
284 // one alongside manageAdminPassword is rejected.
285 adminUserPassword: news.manageAdminPassword ? undefined : news.adminUserPassword,
286 manageAdminPassword: news.manageAdminPassword,
287 adminPasswordSecretKmsKeyId: news.adminPasswordSecretKmsKeyId,
288 kmsKeyId: news.kmsKeyId,
289 defaultIamRoleArn: news.defaultIamRoleArn,
290 iamRoles: news.iamRoles,
291 logExports: news.logExports,
292 tags: toWireTags(desiredTags),
293 })
294 .pipe(
295 Effect.map((r) => r.namespace),
296 Effect.catchTag("ConflictException", () =>
297 redshiftserverless
298 .getNamespace({ namespaceName: name })
299 .pipe(Effect.map((r) => r.namespace)),
300 ),
301 );
302 observed = created;
303 }
304
305 const settled = yield* waitForAvailable(name);
306 if (settled !== undefined) observed = settled;
307 if (observed === undefined) {
308 return yield* new RedshiftServerlessNamespaceUnexpectedResponse({
309 message: `Redshift namespace '${name}' disappeared while reconciling`,
310 });
311 }
312
313 // 3. Sync — apply mutable aspects the user specified when they drift
314 // from OBSERVED state.
315 const update: Omit<redshiftserverless.UpdateNamespaceRequest, "namespaceName"> = {};
316 if (
317 news.defaultIamRoleArn !== undefined &&
318 observed.defaultIamRoleArn !== news.defaultIamRoleArn
319 ) {
320 update.defaultIamRoleArn = news.defaultIamRoleArn;
321 }
322 if (
323 news.iamRoles !== undefined &&
324 !sameStringSet(observed.iamRoles ?? [], news.iamRoles)
325 ) {
326 update.iamRoles = news.iamRoles;
327 }
328 if (
329 news.logExports !== undefined &&
330 !sameStringSet(observed.logExports ?? [], news.logExports)
331 ) {
332 update.logExports = news.logExports;
333 }
334 if (Object.keys(update).length > 0) {
335 yield* redshiftserverless.updateNamespace({
336 namespaceName: name,
337 ...update,
338 });
339 const updated = yield* waitForAvailable(name);
340 if (updated !== undefined) observed = updated;
341 }
342
343 // 3b. Sync tags — diff against OBSERVED cloud tags.
344 yield* syncTags(observed.namespaceArn!, desiredTags);
345
346 // 4. Return fresh attributes.
347 yield* session.note(name);
348 return toAttrs(observed);
349 }),
350
351 delete: Effect.fn(function* ({ output }) {
352 yield* redshiftserverless.deleteNamespace({ namespaceName: output.namespaceName }).pipe(
353 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
354 // A workgroup may still be detaching — retry briefly.
355 Effect.retry({
356 while: (e) => e._tag === "ConflictException",
357 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]),
358 }),
359 Effect.catchTag("ConflictException", () => Effect.void),
360 );
361 yield* waitUntilGone(output.namespaceName);
362 }),
363
364 list: () =>
365 redshiftserverless.listNamespaces.pages({}).pipe(
366 Stream.runCollect,
367 Effect.map((chunk) =>
368 Array.from(chunk)
369 .flatMap((page) => page.namespaces ?? [])
370 .flatMap((ns) =>
371 ns.namespaceName !== undefined &&
372 ns.namespaceArn !== undefined &&
373 ns.namespaceId !== undefined
374 ? [
375 {
376 namespaceName: ns.namespaceName,
377 namespaceArn: ns.namespaceArn,
378 namespaceId: ns.namespaceId,
379 dbName: ns.dbName,
380 adminPasswordSecretArn: ns.adminPasswordSecretArn,
381 status: ns.status ?? "UNKNOWN",
382 },
383 ]
384 : [],
385 ),
386 ),
387 ),
388 };
389 }),
390 );