@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, 04:45 UTC

main
ts 233 lines 8.28 KB
Raw
1 import * as emr from "@distilled.cloud/aws/emr";
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 * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9
10 export interface SecurityConfigurationProps {
11 /**
12 * Name of the security configuration. If omitted, a deterministic physical
13 * name is generated. Changing the name replaces the configuration.
14 */
15 securityConfigurationName?: string;
16 /**
17 * The security configuration document — encryption, authentication
18 * (Kerberos), authorization, and instance-metadata settings — as a plain
19 * object or a pre-serialized JSON string. The document is immutable in
20 * EMR; content changes are converged by deleting and recreating the
21 * configuration under the same name (clusters capture the document at
22 * launch, so running clusters are unaffected).
23 */
24 securityConfiguration: Record<string, unknown> | string;
25 }
26
27 export interface SecurityConfiguration extends Resource<
28 "AWS.EMR.SecurityConfiguration",
29 SecurityConfigurationProps,
30 {
31 /** The name of the security configuration. */
32 securityConfigurationName: string;
33 /** The JSON document of the security configuration. */
34 securityConfiguration: string;
35 },
36 never,
37 Providers
38 > {}
39
40 /**
41 * An Amazon EMR security configuration — a reusable JSON document of
42 * encryption, authentication, and instance-metadata settings referenced by
43 * name when launching a {@link Cluster}.
44 *
45 * Clusters capture the configuration at launch, so editing a configuration
46 * only affects clusters launched afterwards.
47 * ### Creating a Security Configuration
48 * **Example:** Require IMDSv2 on Cluster Instances
49 * ```typescript
50 * const config = yield* SecurityConfiguration("Imds", {
51 * securityConfiguration: {
52 * InstanceMetadataServiceConfiguration: {
53 * MinimumInstanceMetadataServiceVersion: 2,
54 * HttpPutResponseHopLimit: 1,
55 * },
56 * },
57 * });
58 * ```
59 *
60 * **Example:** Encryption Settings
61 * ```typescript
62 * const config = yield* SecurityConfiguration("Encryption", {
63 * securityConfiguration: {
64 * EncryptionConfiguration: {
65 * EnableInTransitEncryption: false,
66 * EnableAtRestEncryption: true,
67 * AtRestEncryptionConfiguration: {
68 * S3EncryptionConfiguration: { EncryptionMode: "SSE-S3" },
69 * },
70 * },
71 * },
72 * });
73 * ```
74 *
75 * ### Using with a Cluster
76 * **Example:** Reference by Name at Launch
77 * ```typescript
78 * const cluster = yield* Cluster("Secure", {
79 * releaseLabel: "emr-7.5.0",
80 * serviceRole: serviceRole.roleName,
81 * jobFlowRole: instanceProfile.instanceProfileName,
82 * securityConfiguration: config.securityConfigurationName,
83 * });
84 * ```
85 *
86 * @resource
87 */
88 export const SecurityConfiguration = Resource<SecurityConfiguration>(
89 "AWS.EMR.SecurityConfiguration",
90 );
91
92 /** Serialize the user-facing document prop to the wire JSON string. */
93 const toDocument = (doc: Record<string, unknown> | string): string =>
94 typeof doc === "string" ? doc : JSON.stringify(doc);
95
96 /** Key-order-insensitive canonical form for content comparison. */
97 const stableStringify = (value: unknown): string => {
98 if (Array.isArray(value)) {
99 return `[${value.map(stableStringify).join(",")}]`;
100 }
101 if (value !== null && typeof value === "object") {
102 return `{${Object.keys(value as Record<string, unknown>)
103 .sort()
104 .map(
105 (key) =>
106 `${JSON.stringify(key)}:${stableStringify((value as Record<string, unknown>)[key])}`,
107 )
108 .join(",")}}`;
109 }
110 return JSON.stringify(value);
111 };
112
113 const canonicalDocument = (doc: string): string => {
114 try {
115 return stableStringify(JSON.parse(doc));
116 } catch {
117 return doc;
118 }
119 };
120
121 export const SecurityConfigurationProvider = () =>
122 Provider.effect(
123 SecurityConfiguration,
124 Effect.gen(function* () {
125 const toName = (id: string, props: Partial<SecurityConfigurationProps>) =>
126 props.securityConfigurationName
127 ? Effect.succeed(props.securityConfigurationName)
128 : createPhysicalName({ id, maxLength: 64 });
129
130 const readConfiguration = Effect.fn(function* (name: string) {
131 return yield* emr
132 .describeSecurityConfiguration({ Name: name })
133 .pipe(Effect.catchTag("SecurityConfigurationNotFound", () => Effect.undefined));
134 });
135
136 const toAttrs = (name: string, document: string) => ({
137 securityConfigurationName: name,
138 securityConfiguration: document,
139 });
140
141 return {
142 stables: ["securityConfigurationName"],
143
144 diff: Effect.fn(function* ({ id, olds, news }) {
145 if (!isResolved(news)) return undefined;
146 const n = news;
147 const o = olds;
148 if (n === undefined || o === undefined) return undefined;
149 if ((yield* toName(id, o)) !== (yield* toName(id, n))) {
150 return { action: "replace" } as const;
151 }
152 // Content changes converge in place (reconcile deletes and
153 // recreates the immutable document under the same name).
154 }),
155
156 read: Effect.fn(function* ({ id, olds, output }) {
157 const name = output?.securityConfigurationName ?? (yield* toName(id, olds ?? {}));
158 const found = yield* readConfiguration(name);
159 if (found === undefined) return undefined;
160 // Security configurations don't support tags, so an existing
161 // document under our derived name is treated as ours.
162 return toAttrs(name, found.SecurityConfiguration ?? "");
163 }),
164
165 reconcile: Effect.fn(function* ({ id, news, output, session }) {
166 const props = news!;
167 const name = output?.securityConfigurationName ?? (yield* toName(id, props));
168 const desired = toDocument(props.securityConfiguration);
169
170 // 1. Observe — cloud state is authoritative.
171 const observed = yield* readConfiguration(name);
172
173 // 2/3. Ensure + sync: the document is immutable, so a content
174 // change is converged by deleting the old document and
175 // recreating it under the same name. A concurrent create of
176 // identical content surfaces as AlreadyExists — that's a
177 // race, not a failure.
178 if (
179 observed?.SecurityConfiguration !== undefined &&
180 canonicalDocument(observed.SecurityConfiguration) !== canonicalDocument(desired)
181 ) {
182 yield* emr
183 .deleteSecurityConfiguration({ Name: name })
184 .pipe(Effect.catchTag("SecurityConfigurationNotFound", () => Effect.void));
185 }
186 if (
187 observed?.SecurityConfiguration === undefined ||
188 canonicalDocument(observed.SecurityConfiguration) !== canonicalDocument(desired)
189 ) {
190 yield* emr
191 .createSecurityConfiguration({
192 Name: name,
193 SecurityConfiguration: desired,
194 })
195 .pipe(Effect.catchTag("SecurityConfigurationAlreadyExists", () => Effect.void));
196 }
197
198 // 4. Return fresh attributes.
199 const final = yield* readConfiguration(name);
200 yield* session.note(name);
201 return toAttrs(name, final?.SecurityConfiguration ?? desired);
202 }),
203
204 delete: Effect.fn(function* ({ output }) {
205 yield* emr
206 .deleteSecurityConfiguration({
207 Name: output.securityConfigurationName,
208 })
209 .pipe(Effect.catchTag("SecurityConfigurationNotFound", () => Effect.void));
210 }),
211
212 list: () =>
213 emr.listSecurityConfigurations.items({}).pipe(
214 Stream.runCollect,
215 Effect.map((chunk) =>
216 Array.from(chunk).flatMap((summary) => (summary.Name ? [summary.Name] : [])),
217 ),
218 Effect.flatMap(
219 Effect.forEach(
220 (name) =>
221 readConfiguration(name).pipe(
222 Effect.map((found) =>
223 found === undefined ? [] : [toAttrs(name, found.SecurityConfiguration ?? "")],
224 ),
225 ),
226 { concurrency: 4 },
227 ),
228 ),
229 Effect.map((results) => results.flat()),
230 ),
231 };
232 }),
233 );