@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 06:00 UTC

main
ts 365 lines 13.9 KB
Raw
1 import * as neptune from "@distilled.cloud/aws/neptune";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export class NeptuneDBParameterGroupUnexpectedResponse extends Data.TaggedError(
14 "NeptuneDBParameterGroupUnexpectedResponse",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface DBParameterGroupProps {
21 /**
22 * Name of the DB (instance-level) parameter group. If omitted, a
23 * deterministic name is generated. Changing it forces replacement.
24 */
25 dbParameterGroupName?: string;
26 /**
27 * DB parameter group family, e.g. `neptune1.4`, `neptune1.3`.
28 * Immutable — forces replacement.
29 */
30 family: string;
31 /**
32 * Description for the parameter group.
33 * @default "Managed by Alchemy"
34 */
35 description?: string;
36 /**
37 * Instance parameter overrides, e.g.
38 * `{ neptune_query_timeout: "120000" }`. Parameters removed from this map
39 * are reset to their engine defaults. Static parameters are applied with
40 * `pending-reboot`, dynamic parameters with `immediate`.
41 */
42 parameters?: Record<string, string>;
43 /**
44 * User-defined tags for the parameter group.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface DBParameterGroup extends Resource<
50 "AWS.Neptune.DBParameterGroup",
51 DBParameterGroupProps,
52 {
53 /** Name of the parameter group. */
54 dbParameterGroupName: string;
55 /** ARN of the parameter group. */
56 dbParameterGroupArn: string | undefined;
57 /** Parameter group family (e.g. `neptune1.4`). */
58 family: string;
59 /** Description of the parameter group. */
60 description: string | undefined;
61 /** Non-default parameter values applied to the group. */
62 parameters: Record<string, string>;
63 /** Tags on the parameter group (user + internal Alchemy tags). */
64 tags: Record<string, string>;
65 },
66 never,
67 Providers
68 > {}
69
70 /**
71 * An Amazon Neptune DB (instance-level) parameter group — a named set of
72 * engine configuration parameters applied to individual Neptune
73 * {@link DBInstance}s via `dbParameterGroupName` (cluster-wide settings live
74 * in a {@link DBClusterParameterGroup} instead).
75 * ### Creating a Parameter Group
76 * **Example:** Parameter group with a custom query timeout
77 * ```typescript
78 * const params = yield* DBParameterGroup("InstanceParams", {
79 * family: "neptune1.4",
80 * parameters: {
81 * neptune_query_timeout: "120000",
82 * },
83 * });
84 * ```
85 *
86 * ### Attaching to an Instance
87 * **Example:** Instance using the parameter group
88 * ```typescript
89 * const writer = yield* DBInstance("Writer", {
90 * dbClusterIdentifier: cluster.dbClusterIdentifier,
91 * dbInstanceClass: "db.serverless",
92 * dbParameterGroupName: params.dbParameterGroupName,
93 * });
94 * ```
95 *
96 * @resource
97 */
98 export const DBParameterGroup = Resource<DBParameterGroup>("AWS.Neptune.DBParameterGroup");
99
100 const toTagRecord = (
101 tags: Array<{ Key?: string; Value?: string }> | undefined,
102 ): Record<string, string> =>
103 Object.fromEntries(
104 (tags ?? [])
105 .filter(
106 (tag): tag is { Key: string; Value: string } =>
107 typeof tag.Key === "string" && typeof tag.Value === "string",
108 )
109 .map((tag) => [tag.Key, tag.Value]),
110 );
111
112 /**
113 * A parameter modify/reset issued immediately after another change fails with
114 * `InvalidDBParameterGroupStateFault` ("has pending changes") until the prior
115 * change settles — retry it on a short bounded schedule.
116 */
117 const retryWhileParameterGroupBusy = <A, E extends { _tag: string }, R>(
118 self: Effect.Effect<A, E, R>,
119 ): Effect.Effect<A, E, R> =>
120 Effect.retry(self, {
121 while: (e) => e._tag === "InvalidDBParameterGroupStateFault",
122 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(10)]),
123 });
124
125 export const DBParameterGroupProvider = () =>
126 Provider.effect(
127 DBParameterGroup,
128 Effect.gen(function* () {
129 const toName = (id: string, props: DBParameterGroupProps) =>
130 props.dbParameterGroupName
131 ? Effect.succeed(props.dbParameterGroupName)
132 : createPhysicalName({ id, maxLength: 255 });
133
134 const readGroup = Effect.fn(function* (groupName: string) {
135 const response = yield* neptune
136 .describeDBParameterGroups({
137 DBParameterGroupName: groupName,
138 })
139 .pipe(Effect.catchTag("DBParameterGroupNotFoundFault", () => Effect.undefined));
140 return response?.DBParameterGroups?.[0];
141 });
142
143 // All parameters (defaults + overrides) with their current values and
144 // apply types — the observed baseline for the parameter sync.
145 const readParameters = Effect.fn(function* (groupName: string) {
146 return yield* neptune.describeDBParameters.pages({ DBParameterGroupName: groupName }).pipe(
147 Stream.runCollect,
148 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Parameters ?? [])),
149 );
150 });
151
152 // The subset of parameters the user has overridden (Source `user`) —
153 // used to compute resets when a prop entry is removed.
154 const readUserParameters = Effect.fn(function* (groupName: string) {
155 return yield* neptune.describeDBParameters
156 .pages({ DBParameterGroupName: groupName, Source: "user" })
157 .pipe(
158 Stream.runCollect,
159 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Parameters ?? [])),
160 );
161 });
162
163 const readTags = Effect.fn(function* (arn: string | undefined) {
164 if (!arn) return {} as Record<string, string>;
165 const response = yield* neptune.listTagsForResource({
166 ResourceName: arn,
167 });
168 return toTagRecord(response?.TagList);
169 });
170
171 const toUserParameterRecord = (parameters: neptune.Parameter[]): Record<string, string> =>
172 Object.fromEntries(
173 parameters.flatMap((p) =>
174 p.ParameterName !== undefined && p.ParameterValue !== undefined
175 ? [[p.ParameterName, p.ParameterValue]]
176 : [],
177 ),
178 );
179
180 return {
181 stables: ["dbParameterGroupArn", "dbParameterGroupName", "family"],
182 diff: Effect.fn(function* ({ id, olds, news }) {
183 if (!isResolved(news)) return undefined;
184 if ((yield* toName(id, olds ?? { family: "" })) !== (yield* toName(id, news))) {
185 return { action: "replace" } as const;
186 }
187 // Family is immutable — any change forces a fresh group.
188 if (olds !== undefined && olds.family !== news.family) {
189 return { action: "replace" } as const;
190 }
191 }),
192 read: Effect.fn(function* ({ id, olds, output }) {
193 const name =
194 output?.dbParameterGroupName ??
195 (yield* toName(id, olds ?? ({ family: "" } as DBParameterGroupProps)));
196 const group = yield* readGroup(name);
197 if (!group?.DBParameterGroupName) {
198 return undefined;
199 }
200 const userParameters = yield* readUserParameters(name);
201 const tags = yield* readTags(group.DBParameterGroupArn);
202 return {
203 dbParameterGroupName: group.DBParameterGroupName,
204 dbParameterGroupArn: group.DBParameterGroupArn,
205 family: group.DBParameterGroupFamily ?? "",
206 description: group.Description,
207 parameters: toUserParameterRecord(userParameters),
208 tags,
209 };
210 }),
211 reconcile: Effect.fn(function* ({ id, news, output, session }) {
212 const name = output?.dbParameterGroupName ?? (yield* toName(id, news));
213 const internalTags = yield* createInternalTags(id);
214 const desiredTags = { ...internalTags, ...news.tags };
215
216 // Observe — fetch live parameter-group state.
217 let observed = yield* readGroup(name);
218
219 // Ensure — create if missing. Tolerate
220 // `DBParameterGroupAlreadyExistsFault` as a race with a peer
221 // reconciler by re-reading.
222 if (!observed?.DBParameterGroupName) {
223 yield* neptune
224 .createDBParameterGroup({
225 DBParameterGroupName: name,
226 DBParameterGroupFamily: news.family,
227 Description: news.description ?? "Managed by Alchemy",
228 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
229 Key,
230 Value,
231 })),
232 })
233 .pipe(Effect.catchTag("DBParameterGroupAlreadyExistsFault", () => Effect.void));
234 observed = yield* readGroup(name);
235 if (!observed?.DBParameterGroupName) {
236 return yield* new NeptuneDBParameterGroupUnexpectedResponse({
237 message: `Failed to create DB parameter group '${name}'`,
238 });
239 }
240 }
241
242 // Sync parameters — diff observed cloud values against desired.
243 const desiredParameters = news.parameters ?? {};
244 const allParameters = yield* readParameters(name);
245 const byName = new Map(allParameters.map((p) => [p.ParameterName, p]));
246
247 const toModify: neptune.Parameter[] = Object.entries(desiredParameters).flatMap(
248 ([ParameterName, ParameterValue]) => {
249 const current = byName.get(ParameterName);
250 if (current?.ParameterValue === ParameterValue) return [];
251 return [
252 {
253 ParameterName,
254 ParameterValue,
255 ApplyMethod: current?.ApplyType === "static" ? "pending-reboot" : "immediate",
256 },
257 ];
258 },
259 );
260 if (toModify.length > 0) {
261 // The API caps a single call at 20 parameters.
262 for (let i = 0; i < toModify.length; i += 20) {
263 yield* retryWhileParameterGroupBusy(
264 neptune.modifyDBParameterGroup({
265 DBParameterGroupName: name,
266 Parameters: toModify.slice(i, i + 20),
267 }),
268 );
269 }
270 }
271
272 // Reset user-overridden parameters that were removed from props.
273 const userParameters = yield* readUserParameters(name);
274 const toReset = userParameters.flatMap((p) =>
275 p.ParameterName !== undefined && !(p.ParameterName in desiredParameters)
276 ? [
277 {
278 ParameterName: p.ParameterName,
279 ApplyMethod:
280 p.ApplyType === "static"
281 ? ("pending-reboot" as const)
282 : ("immediate" as const),
283 },
284 ]
285 : [],
286 );
287 if (toReset.length > 0) {
288 for (let i = 0; i < toReset.length; i += 20) {
289 yield* retryWhileParameterGroupBusy(
290 neptune.resetDBParameterGroup({
291 DBParameterGroupName: name,
292 ResetAllParameters: false,
293 Parameters: toReset.slice(i, i + 20),
294 }),
295 );
296 }
297 }
298
299 const arn = observed.DBParameterGroupArn;
300
301 // Sync tags — diff observed cloud tags against desired.
302 const observedTags = yield* readTags(arn);
303 const { removed, upsert } = diffTags(observedTags, desiredTags);
304 if (upsert.length > 0 && arn) {
305 yield* neptune.addTagsToResource({
306 ResourceName: arn,
307 Tags: upsert,
308 });
309 }
310 if (removed.length > 0 && arn) {
311 yield* neptune.removeTagsFromResource({
312 ResourceName: arn,
313 TagKeys: removed,
314 });
315 }
316
317 yield* session.note(arn ?? name);
318 return {
319 dbParameterGroupName: observed.DBParameterGroupName,
320 dbParameterGroupArn: arn,
321 family: observed.DBParameterGroupFamily ?? news.family,
322 description: observed.Description,
323 parameters: desiredParameters,
324 tags: desiredTags,
325 };
326 }),
327 list: () =>
328 // AWS account/region collection: the RDS-family control plane
329 // serves parameter groups for every engine, so keep only families
330 // beginning with `neptune`. Hydrating per-group parameters/tags
331 // would fan out one call per item — emit empty maps instead.
332 neptune.describeDBParameterGroups.pages({}).pipe(
333 Stream.runCollect,
334 Effect.map((chunk) =>
335 Array.from(chunk).flatMap((page) =>
336 (page.DBParameterGroups ?? []).flatMap((group) =>
337 group.DBParameterGroupName &&
338 // `default.<family>` groups are AWS-managed and undeletable.
339 !group.DBParameterGroupName.startsWith("default.") &&
340 group.DBParameterGroupFamily?.startsWith("neptune")
341 ? [
342 {
343 dbParameterGroupName: group.DBParameterGroupName,
344 dbParameterGroupArn: group.DBParameterGroupArn,
345 family: group.DBParameterGroupFamily,
346 description: group.Description,
347 parameters: {} as Record<string, string>,
348 tags: {} as Record<string, string>,
349 },
350 ]
351 : [],
352 ),
353 ),
354 ),
355 ),
356 delete: Effect.fn(function* ({ output }) {
357 yield* neptune
358 .deleteDBParameterGroup({
359 DBParameterGroupName: output.dbParameterGroupName,
360 })
361 .pipe(Effect.catchTag("DBParameterGroupNotFoundFault", () => Effect.void));
362 }),
363 };
364 }),
365 );