@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 351 lines 13.4 KB
Raw
1 import * as appconfig from "@distilled.cloud/aws/appconfig";
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 Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { configurationProfileArn, readAppConfigTags, syncAppConfigTags } from "./internal.ts";
13
14 /**
15 * A validator run against configuration data before it is deployed.
16 */
17 export interface ConfigurationValidator {
18 /** Validator kind. */
19 type: "JSON_SCHEMA" | "LAMBDA";
20 /**
21 * For `JSON_SCHEMA`, the JSON Schema document. For `LAMBDA`, the ARN of the
22 * validating Lambda function.
23 */
24 content: string;
25 }
26
27 export interface ConfigurationProfileProps {
28 /**
29 * ID of the application this profile belongs to. Changing it replaces the
30 * profile.
31 */
32 applicationId: string;
33 /**
34 * Name of the configuration profile. Must be 1-64 characters. If omitted, a
35 * deterministic physical name is generated. Changing the name replaces the
36 * profile.
37 */
38 configurationProfileName?: string;
39 /**
40 * URI of the configuration source. Use `"hosted"` for the AppConfig hosted
41 * configuration store, or an S3 URI (`s3://bucket/key`), SSM parameter/
42 * document name, Secrets Manager secret, or CodePipeline pipeline ARN.
43 * Immutable — changing it replaces the profile.
44 * @default "hosted"
45 */
46 locationUri?: string;
47 /**
48 * Description of the configuration profile.
49 */
50 description?: string;
51 /**
52 * ARN of an IAM role AppConfig assumes to fetch configuration from a
53 * non-hosted source (S3, SSM, Secrets Manager). Not required for `"hosted"`.
54 */
55 retrievalRoleArn?: string;
56 /**
57 * Validators run against the configuration data before deployment.
58 */
59 validators?: ConfigurationValidator[];
60 /**
61 * Configuration profile type. `"AWS.Freeform"` for free-form configuration
62 * or `"AWS.AppConfig.FeatureFlags"` for feature flags. Immutable — changing
63 * it replaces the profile.
64 * @default "AWS.Freeform"
65 */
66 type?: string;
67 /**
68 * Customer-managed KMS key ARN/id used to encrypt the configuration data.
69 */
70 kmsKeyIdentifier?: string;
71 /**
72 * User-defined tags for the configuration profile.
73 */
74 tags?: Record<string, string>;
75 }
76
77 export interface ConfigurationProfile extends Resource<
78 "AWS.AppConfig.ConfigurationProfile",
79 ConfigurationProfileProps,
80 {
81 configurationProfileId: string;
82 configurationProfileName: string;
83 applicationId: string;
84 locationUri: string;
85 configurationProfileArn: string;
86 },
87 never,
88 Providers
89 > {}
90
91 /**
92 * An AWS AppConfig configuration profile — describes where the configuration
93 * data lives (the AppConfig hosted store, S3, SSM, Secrets Manager, or
94 * CodePipeline) and how to validate it.
95 *
96 * ### Creating a Configuration Profile
97 * **Example:** Hosted Configuration Profile
98 * ```typescript
99 * const profile = yield* AppConfig.ConfigurationProfile("Settings", {
100 * applicationId: app.applicationId,
101 * locationUri: "hosted",
102 * });
103 * ```
104 *
105 * **Example:** S3-sourced Profile with a JSON Schema Validator
106 * ```typescript
107 * const profile = yield* AppConfig.ConfigurationProfile("Settings", {
108 * applicationId: app.applicationId,
109 * locationUri: "s3://my-bucket/config.json",
110 * retrievalRoleArn: role.roleArn,
111 * validators: [{ type: "JSON_SCHEMA", content: schemaJson }],
112 * });
113 * ```
114 *
115 * @resource
116 */
117 export const ConfigurationProfile = Resource<ConfigurationProfile>(
118 "AWS.AppConfig.ConfigurationProfile",
119 );
120
121 const toWireValidators = (
122 validators: ConfigurationValidator[] | undefined,
123 ): appconfig.Validator[] | undefined =>
124 validators?.map((v) => ({ Type: v.type, Content: v.content }));
125
126 export const ConfigurationProfileProvider = () =>
127 Provider.effect(
128 ConfigurationProfile,
129 Effect.gen(function* () {
130 const toName = (id: string, props: Partial<ConfigurationProfileProps>) =>
131 props.configurationProfileName
132 ? Effect.succeed(props.configurationProfileName)
133 : createPhysicalName({ id, maxLength: 64 });
134
135 const readProfile = Effect.fn(function* (
136 applicationId: string,
137 configurationProfileId: string,
138 ) {
139 return yield* appconfig
140 .getConfigurationProfile({
141 ApplicationId: applicationId,
142 ConfigurationProfileId: configurationProfileId,
143 })
144 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
145 });
146
147 const findByName = Effect.fn(function* (applicationId: string, name: string) {
148 const profiles = yield* appconfig.listConfigurationProfiles
149 .pages({ ApplicationId: applicationId })
150 .pipe(
151 Stream.runCollect,
152 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
153 Effect.catchTag("ResourceNotFoundException", () =>
154 Effect.succeed([] as appconfig.ConfigurationProfileSummary[]),
155 ),
156 );
157 const summary = profiles.find((p) => p.Name === name);
158 if (summary?.Id === undefined) return undefined;
159 return yield* readProfile(applicationId, summary.Id);
160 });
161
162 return {
163 stables: [
164 "configurationProfileId",
165 "configurationProfileName",
166 "applicationId",
167 "locationUri",
168 "configurationProfileArn",
169 ],
170
171 diff: Effect.fn(function* ({ id, olds, news }) {
172 if (!isResolved(news)) return undefined;
173 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
174 return { action: "replace" } as const;
175 }
176 if ((olds?.applicationId ?? undefined) !== news?.applicationId) {
177 return { action: "replace" } as const;
178 }
179 // LocationUri and Type are create-only.
180 if ((olds?.locationUri ?? "hosted") !== (news?.locationUri ?? "hosted")) {
181 return { action: "replace" } as const;
182 }
183 if ((olds?.type ?? "AWS.Freeform") !== (news?.type ?? "AWS.Freeform")) {
184 return { action: "replace" } as const;
185 }
186 }),
187
188 read: Effect.fn(function* ({ id, olds, output }) {
189 const { accountId, region } = yield* AWSEnvironment.current;
190 const applicationId = output?.applicationId ?? olds?.applicationId;
191 if (applicationId === undefined) return undefined;
192 const profile = output?.configurationProfileId
193 ? yield* readProfile(applicationId, output.configurationProfileId)
194 : yield* findByName(applicationId, yield* toName(id, olds ?? {}));
195 if (profile?.Id === undefined) return undefined;
196 const arn = configurationProfileArn(region, accountId, applicationId, profile.Id);
197 const attrs = {
198 configurationProfileId: profile.Id,
199 configurationProfileName: profile.Name!,
200 applicationId,
201 locationUri: profile.LocationUri ?? "hosted",
202 configurationProfileArn: arn,
203 };
204 const tags = yield* readAppConfigTags(arn);
205 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
206 }),
207
208 reconcile: Effect.fn(function* ({ id, news, output, session }) {
209 const { accountId, region } = yield* AWSEnvironment.current;
210 const applicationId = news.applicationId;
211 const name = output?.configurationProfileName ?? (yield* toName(id, news));
212 const locationUri = news.locationUri ?? "hosted";
213 const internalTags = yield* createInternalTags(id);
214 const desiredTags = { ...internalTags, ...news.tags };
215
216 // 1. Observe.
217 let observed = output?.configurationProfileId
218 ? yield* readProfile(applicationId, output.configurationProfileId)
219 : undefined;
220 if (observed === undefined) {
221 observed = yield* findByName(applicationId, name);
222 }
223
224 // 2. Ensure.
225 if (observed?.Id === undefined) {
226 observed = yield* appconfig.createConfigurationProfile({
227 ApplicationId: applicationId,
228 Name: name,
229 LocationUri: locationUri,
230 Description: news.description,
231 RetrievalRoleArn: news.retrievalRoleArn,
232 Validators: toWireValidators(news.validators),
233 Type: news.type,
234 KmsKeyIdentifier: news.kmsKeyIdentifier,
235 Tags: desiredTags,
236 });
237 } else {
238 // 3. Sync — description, retrieval role, validators, and KMS key
239 // are mutable in place.
240 observed = yield* appconfig.updateConfigurationProfile({
241 ApplicationId: applicationId,
242 ConfigurationProfileId: observed.Id,
243 Description: news.description,
244 RetrievalRoleArn: news.retrievalRoleArn,
245 Validators: toWireValidators(news.validators),
246 KmsKeyIdentifier: news.kmsKeyIdentifier,
247 });
248 }
249
250 const arn = configurationProfileArn(region, accountId, applicationId, observed.Id!);
251
252 // 3b. Sync tags.
253 yield* syncAppConfigTags(arn, desiredTags);
254
255 yield* session.note(name);
256 return {
257 configurationProfileId: observed.Id!,
258 configurationProfileName: observed.Name ?? name,
259 applicationId,
260 locationUri: observed.LocationUri ?? locationUri,
261 configurationProfileArn: arn,
262 };
263 }),
264
265 delete: Effect.fn(function* ({ output }) {
266 // Hosted configuration versions block profile deletion, and
267 // runtime writers (the CreateHostedConfigurationVersion binding)
268 // can add versions the engine never tracked — delete whatever
269 // versions remain before deleting the profile.
270 const versions = yield* appconfig.listHostedConfigurationVersions
271 .pages({
272 ApplicationId: output.applicationId,
273 ConfigurationProfileId: output.configurationProfileId,
274 })
275 .pipe(
276 Stream.runCollect,
277 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
278 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])),
279 );
280 for (const version of versions) {
281 if (version.VersionNumber !== undefined) {
282 yield* appconfig
283 .deleteHostedConfigurationVersion({
284 ApplicationId: output.applicationId,
285 ConfigurationProfileId: output.configurationProfileId,
286 VersionNumber: version.VersionNumber,
287 })
288 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
289 }
290 }
291 yield* appconfig
292 .deleteConfigurationProfile({
293 ApplicationId: output.applicationId,
294 ConfigurationProfileId: output.configurationProfileId,
295 })
296 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
297 }),
298
299 // Configuration profiles are keyed under their parent application, so
300 // enumeration walks every application and lists its profiles. An
301 // application cannot be deleted while profiles exist under it, so
302 // nuke needs these enumerated as first-class resources.
303 list: () =>
304 Effect.gen(function* () {
305 const { accountId, region } = yield* AWSEnvironment.current;
306 const apps = yield* appconfig.listApplications.pages({}).pipe(
307 Stream.runCollect,
308 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
309 );
310 const results: {
311 configurationProfileId: string;
312 configurationProfileName: string;
313 applicationId: string;
314 locationUri: string;
315 configurationProfileArn: string;
316 }[] = [];
317 for (const app of apps) {
318 if (app.Id === undefined) continue;
319 const profiles = yield* appconfig.listConfigurationProfiles
320 .pages({ ApplicationId: app.Id })
321 .pipe(
322 Stream.runCollect,
323 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
324 // The application may be deleted between the two calls.
325 Effect.catchTag("ResourceNotFoundException", () =>
326 Effect.succeed([] as appconfig.ConfigurationProfileSummary[]),
327 ),
328 );
329 for (const profile of profiles) {
330 if (profile.Id === undefined || profile.Name === undefined) {
331 continue;
332 }
333 results.push({
334 configurationProfileId: profile.Id,
335 configurationProfileName: profile.Name,
336 applicationId: app.Id,
337 locationUri: profile.LocationUri ?? "hosted",
338 configurationProfileArn: configurationProfileArn(
339 region,
340 accountId,
341 app.Id,
342 profile.Id,
343 ),
344 });
345 }
346 }
347 return results;
348 }),
349 };
350 }),
351 );