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

main
ts 294 lines 11.1 KB
Raw
1 import * as redshift from "@distilled.cloud/aws/redshift";
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 Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import { applyRedshiftTagDelta, redshiftArn, toTagRecord } from "./internal.ts";
14
15 export class ClusterParameterGroupUnexpectedResponse extends Data.TaggedError(
16 "ClusterParameterGroupUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface ClusterParameterGroupProps {
23 /**
24 * Name of the cluster parameter group. Must be 1-255 lowercase
25 * alphanumeric characters or hyphens, starting with a letter, and must
26 * not be prefixed `default`. If omitted, a deterministic physical name is
27 * generated. Changing the name replaces the parameter group.
28 */
29 clusterParameterGroupName?: string;
30 /**
31 * Parameter group family the group applies to, e.g. `redshift-2.0` (or `redshift-1.0`).
32 * Changing the family replaces the parameter group.
33 */
34 family: string;
35 /**
36 * Human-readable description. Changing the description replaces the
37 * parameter group (Redshift descriptions are create-only).
38 * @default "Managed by Alchemy"
39 */
40 description?: string;
41 /**
42 * Cluster database parameters to override from the family defaults, e.g.
43 * `{ enable_user_activity_logging: "true" }`. Parameters removed from
44 * this map are reset to their engine defaults.
45 */
46 parameters?: Record<string, string>;
47 /**
48 * User-defined tags for the parameter group.
49 */
50 tags?: Record<string, string>;
51 }
52
53 export interface ClusterParameterGroup extends Resource<
54 "AWS.Redshift.ClusterParameterGroup",
55 ClusterParameterGroupProps,
56 {
57 /**
58 * Name of the parameter group.
59 */
60 clusterParameterGroupName: string;
61 /**
62 * ARN of the parameter group.
63 */
64 clusterParameterGroupArn: string;
65 /**
66 * Parameter group family (e.g. `"redshift-2.0"`).
67 */
68 family: string;
69 /**
70 * Description of the parameter group.
71 */
72 description: string | undefined;
73 /**
74 * Non-default parameter values applied to the group.
75 */
76 parameters: Record<string, string>;
77 /**
78 * Tags on the parameter group (including internal Alchemy tags).
79 */
80 tags: Record<string, string>;
81 },
82 never,
83 Providers
84 > {}
85
86 /**
87 * An Amazon Redshift cluster parameter group — a named set of database
88 * parameters applied to provisioned Redshift clusters.
89 *
90 * Parameter groups are free and provision instantly. A {@link Cluster}
91 * references one by name via `clusterParameterGroupName`; parameter changes
92 * take effect after the cluster reboots.
93 * ### Creating a Parameter Group
94 * **Example:** Default Parameter Group
95 * ```typescript
96 * const params = yield* Redshift.ClusterParameterGroup("WarehouseParams", {
97 * family: "redshift-2.0",
98 * });
99 * ```
100 * **Example:** Overriding Parameters
101 * ```typescript
102 * const params = yield* Redshift.ClusterParameterGroup("WarehouseParams", {
103 * family: "redshift-2.0",
104 * parameters: {
105 * enable_user_activity_logging: "true",
106 * statement_timeout: "60000",
107 * },
108 * });
109 * ```
110 *
111 * @resource
112 */
113 export const ClusterParameterGroup = Resource<ClusterParameterGroup>(
114 "AWS.Redshift.ClusterParameterGroup",
115 );
116
117 export const ClusterParameterGroupProvider = () =>
118 Provider.effect(
119 ClusterParameterGroup,
120 Effect.gen(function* () {
121 const toName = (id: string, props: Partial<ClusterParameterGroupProps>) =>
122 props.clusterParameterGroupName
123 ? Effect.succeed(props.clusterParameterGroupName)
124 : createPhysicalName({ id, maxLength: 255, lowercase: true });
125
126 const readGroup = Effect.fn(function* (name: string) {
127 const response = yield* redshift
128 .describeClusterParameterGroups({ ParameterGroupName: name })
129 .pipe(Effect.catchTag("ClusterParameterGroupNotFoundFault", () => Effect.undefined));
130 return response?.ParameterGroups?.[0];
131 });
132
133 // User-sourced parameter overrides currently applied to the group.
134 const readUserParameters = Effect.fn(function* (name: string) {
135 const parameters = yield* redshift.describeClusterParameters
136 .items({ ParameterGroupName: name, Source: "user" })
137 .pipe(Stream.runCollect, Effect.map(Array.from<redshift.Parameter>));
138 return Object.fromEntries(
139 parameters.flatMap((parameter) =>
140 parameter.ParameterName !== undefined && parameter.ParameterValue !== undefined
141 ? [[parameter.ParameterName, parameter.ParameterValue]]
142 : [],
143 ),
144 );
145 });
146
147 const toAttrs = Effect.fn(function* (group: redshift.ClusterParameterGroup) {
148 const { accountId, region } = yield* AWSEnvironment.current;
149 if (!group.ParameterGroupName) {
150 return yield* new ClusterParameterGroupUnexpectedResponse({
151 message: "Cluster parameter group is missing its name",
152 });
153 }
154 return {
155 clusterParameterGroupName: group.ParameterGroupName,
156 clusterParameterGroupArn: redshiftArn(
157 region,
158 accountId,
159 "parametergroup",
160 group.ParameterGroupName,
161 ),
162 family: group.ParameterGroupFamily ?? "",
163 description: group.Description,
164 parameters: yield* readUserParameters(group.ParameterGroupName),
165 tags: toTagRecord(group.Tags),
166 };
167 });
168
169 return {
170 stables: ["clusterParameterGroupName", "clusterParameterGroupArn"],
171
172 diff: Effect.fn(function* ({ id, olds, news }) {
173 if (!isResolved(news)) return undefined;
174 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
175 return { action: "replace" } as const;
176 }
177 // Family and description are create-only.
178 if (olds?.family !== news.family || olds?.description !== news.description) {
179 return { action: "replace" } as const;
180 }
181 }),
182
183 read: Effect.fn(function* ({ id, olds, output }) {
184 const name = output?.clusterParameterGroupName ?? (yield* toName(id, olds ?? {}));
185 const group = yield* readGroup(name);
186 if (!group?.ParameterGroupName) return undefined;
187 const attrs = yield* toAttrs(group);
188 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
189 }),
190
191 reconcile: Effect.fn(function* ({ id, news, output, session }) {
192 const name = output?.clusterParameterGroupName ?? (yield* toName(id, news));
193 const internalTags = yield* createInternalTags(id);
194 const desiredTags = { ...internalTags, ...news.tags };
195
196 // 1. Observe — cloud state is authoritative.
197 let observed = yield* readGroup(name);
198
199 // 2. Ensure — create if missing; tolerate AlreadyExists as a race
200 // with a peer reconciler by re-reading.
201 if (!observed?.ParameterGroupName) {
202 yield* redshift
203 .createClusterParameterGroup({
204 ParameterGroupName: name,
205 ParameterGroupFamily: news.family,
206 Description: news.description ?? "Managed by Alchemy",
207 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
208 Key,
209 Value,
210 })),
211 })
212 .pipe(Effect.catchTag("ClusterParameterGroupAlreadyExistsFault", () => Effect.void));
213 observed = yield* readGroup(name);
214 if (!observed?.ParameterGroupName) {
215 return yield* new ClusterParameterGroupUnexpectedResponse({
216 message: `Failed to create cluster parameter group '${name}'`,
217 });
218 }
219 }
220
221 // 3. Sync parameters — diff OBSERVED user-sourced overrides
222 // against desired; changed/added values are applied, removed
223 // ones are reset to the engine defaults.
224 const observedParameters = yield* readUserParameters(name);
225 const desiredParameters = news.parameters ?? {};
226 const upsertParameters = Object.entries(desiredParameters)
227 .filter(([key, value]) => observedParameters[key] !== value)
228 .map(([ParameterName, ParameterValue]) => ({
229 ParameterName,
230 ParameterValue,
231 }));
232 const resetParameters = Object.keys(observedParameters)
233 .filter((key) => !(key in desiredParameters))
234 .map((ParameterName) => ({ ParameterName }));
235 if (upsertParameters.length > 0) {
236 yield* redshift.modifyClusterParameterGroup({
237 ParameterGroupName: name,
238 Parameters: upsertParameters,
239 });
240 }
241 if (resetParameters.length > 0) {
242 yield* redshift.resetClusterParameterGroup({
243 ParameterGroupName: name,
244 ResetAllParameters: false,
245 Parameters: resetParameters,
246 });
247 }
248
249 // 3b. Sync tags — diff against OBSERVED cloud tags (describe
250 // surfaces them inline).
251 const { accountId, region } = yield* AWSEnvironment.current;
252 const arn = redshiftArn(region, accountId, "parametergroup", name);
253 const { removed, upsert } = diffTags(toTagRecord(observed.Tags), desiredTags);
254 yield* applyRedshiftTagDelta({ arn, upsert, removed });
255
256 yield* session.note(arn);
257 return {
258 clusterParameterGroupName: name,
259 clusterParameterGroupArn: arn,
260 family: observed.ParameterGroupFamily ?? news.family,
261 description: observed.Description,
262 parameters: desiredParameters,
263 tags: desiredTags,
264 };
265 }),
266
267 delete: Effect.fn(function* ({ output }) {
268 yield* redshift
269 .deleteClusterParameterGroup({
270 ParameterGroupName: output.clusterParameterGroupName,
271 })
272 .pipe(Effect.catchTag("ClusterParameterGroupNotFoundFault", () => Effect.void));
273 }),
274
275 list: () =>
276 // Top-level account/region collection: exhaustively paginate
277 // describeClusterParameterGroups. AWS-managed `default.*` groups
278 // cannot be deleted — don't enumerate them.
279 redshift.describeClusterParameterGroups.pages({}).pipe(
280 Stream.runCollect,
281 Effect.map((chunk) =>
282 Array.from(chunk).flatMap((page) =>
283 (page.ParameterGroups ?? []).filter(
284 (group) =>
285 group.ParameterGroupName !== undefined &&
286 !group.ParameterGroupName.startsWith("default."),
287 ),
288 ),
289 ),
290 Effect.flatMap(Effect.forEach((group) => toAttrs(group), { concurrency: 4 })),
291 ),
292 };
293 }),
294 );