@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 335 lines 12.9 KB
Raw
1 import * as controltower from "@distilled.cloud/aws/controltower";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } 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 import { canonicalParameters, observeControlTowerTags, syncControlTowerTags } from "./internal.ts";
13
14 export interface EnabledBaselineProps {
15 /**
16 * The ARN of the baseline to enable, e.g. the `AWSControlTowerBaseline`
17 * ARN from `ListBaselines`. Changing the baseline replaces the
18 * enablement.
19 */
20 baselineIdentifier: string;
21 /**
22 * The baseline version to enable, e.g. `"4.0"`. Updated in place via
23 * `UpdateEnabledBaseline`.
24 */
25 baselineVersion: string;
26 /**
27 * The ARN of the target (organizational unit) the baseline is enabled
28 * on. Changing the target replaces the enablement.
29 */
30 targetIdentifier: string;
31 /**
32 * Parameters applied to the baseline, as `{ key, value }` pairs — e.g.
33 * `IdentityCenterEnabledBaselineArn` for the `AWSControlTowerBaseline`.
34 * Updated in place via `UpdateEnabledBaseline`.
35 */
36 parameters?: { key: string; value: any }[];
37 /**
38 * Tags to apply to the enabled baseline. Merged with internal Alchemy
39 * tags.
40 */
41 tags?: Record<string, string>;
42 }
43
44 export interface EnabledBaseline extends Resource<
45 "AWS.ControlTower.EnabledBaseline",
46 EnabledBaselineProps,
47 {
48 /**
49 * The ARN of the enabled baseline (the `EnabledBaseline` resource).
50 */
51 enabledBaselineArn: string;
52 /**
53 * The ARN of the baseline that was enabled.
54 */
55 baselineIdentifier: string;
56 /**
57 * The ARN of the target organizational unit.
58 */
59 targetIdentifier: string;
60 /**
61 * The enabled baseline version.
62 */
63 baselineVersion: string | undefined;
64 },
65 never,
66 Providers
67 > {}
68
69 /**
70 * An AWS Control Tower baseline enabled on a target organizational unit.
71 * Enabling a baseline (e.g. `AWSControlTowerBaseline`) starts an
72 * asynchronous operation that registers the OU with Control Tower and
73 * deploys the baseline's governance resources to its accounts.
74 *
75 * Requires an AWS Control Tower landing zone and can only be managed from
76 * the Organizations management account.
77 * ### Enabling Baselines
78 * **Example:** Register an OU with Control Tower
79 * ```typescript
80 * import * as ControlTower from "@alchemy.run/aws/ControlTower";
81 *
82 * const enabled = yield* ControlTower.EnabledBaseline("WorkloadsBaseline", {
83 * baselineIdentifier:
84 * "arn:aws:controltower:us-west-2::baseline/17BSJV3IGJ2QSGA2",
85 * baselineVersion: "4.0",
86 * targetIdentifier: "arn:aws:organizations::111122223333:ou/o-example/ou-example",
87 * });
88 * ```
89 *
90 * **Example:** Baseline with Identity Center parameter
91 * ```typescript
92 * const enabled = yield* ControlTower.EnabledBaseline("WorkloadsBaseline", {
93 * baselineIdentifier: controlTowerBaselineArn,
94 * baselineVersion: "4.0",
95 * targetIdentifier: ouArn,
96 * parameters: [
97 * {
98 * key: "IdentityCenterEnabledBaselineArn",
99 * value: identityCenterEnabledBaselineArn,
100 * },
101 * ],
102 * });
103 * ```
104 *
105 * @resource
106 */
107 export const EnabledBaseline = Resource<EnabledBaseline>("AWS.ControlTower.EnabledBaseline");
108
109 /**
110 * An asynchronous baseline operation (ENABLE_BASELINE / DISABLE_BASELINE /
111 * UPDATE_ENABLED_BASELINE) converged to the terminal `FAILED` status.
112 */
113 export class BaselineOperationFailed extends Data.TaggedError("BaselineOperationFailed")<{
114 readonly operationIdentifier: string;
115 readonly status: string;
116 readonly statusMessage: string | undefined;
117 }> {}
118
119 /**
120 * Internal signal that a baseline operation is still `IN_PROGRESS`,
121 * consumed by {@link waitForBaselineOperation}'s bounded schedule.
122 */
123 class BaselineOperationPending extends Data.TaggedError("BaselineOperationPending")<{
124 readonly operationIdentifier: string;
125 readonly status: string | undefined;
126 }> {}
127
128 // Explicitly-typed retry wrappers — an inline `Effect.retry` in provider
129 // lifecycle code leaks `Retry.Return`'s conditional type into declaration
130 // emit and widens the provider layer to `unknown` for every consumer of
131 // `AWS.providers()`.
132 const retryWhileBaselineOperationPending = <A, E extends { readonly _tag: string }, R>(
133 self: Effect.Effect<A, E, R>,
134 ): Effect.Effect<A, E, R> =>
135 Effect.retry(self, {
136 while: (e) => e._tag === "BaselineOperationPending",
137 // Baseline enablement provisions accounts and typically takes several
138 // minutes; poll every 10s up to ~20 minutes.
139 schedule: Schedule.max([Schedule.spaced("10 seconds"), Schedule.recurs(120)]),
140 });
141
142 // Control Tower serializes baseline operations per target — a concurrent
143 // operation surfaces as a typed ConflictException. Retry through it on a
144 // bounded schedule.
145 const retryWhileBaselineConflict = <A, E extends { readonly _tag: string }, R>(
146 self: Effect.Effect<A, E, R>,
147 ): Effect.Effect<A, E, R> =>
148 Effect.retry(self, {
149 while: (e) => e._tag === "ConflictException",
150 schedule: Schedule.max([Schedule.spaced("15 seconds"), Schedule.recurs(40)]),
151 });
152
153 const waitForBaselineOperation = (operationIdentifier: string) =>
154 retryWhileBaselineOperationPending(
155 Effect.gen(function* () {
156 const { baselineOperation } = yield* controltower.getBaselineOperation({
157 operationIdentifier,
158 });
159 if (baselineOperation.status === "SUCCEEDED") {
160 return;
161 }
162 if (baselineOperation.status === "FAILED") {
163 return yield* new BaselineOperationFailed({
164 operationIdentifier,
165 status: baselineOperation.status,
166 statusMessage: baselineOperation.statusMessage,
167 });
168 }
169 return yield* new BaselineOperationPending({
170 operationIdentifier,
171 status: baselineOperation.status,
172 });
173 }),
174 );
175
176 const readEnabledBaseline = (enabledBaselineArn: string) =>
177 controltower.getEnabledBaseline({ enabledBaselineIdentifier: enabledBaselineArn }).pipe(
178 Effect.map((r) => r.enabledBaselineDetails),
179 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
180 );
181
182 // Find an enabled baseline by (baselineIdentifier, targetIdentifier) —
183 // covers the create-race and lost-output cases where we don't have the
184 // ARN cached.
185 const findEnabledBaselineArn = (baselineIdentifier: string, targetIdentifier: string) =>
186 controltower.listEnabledBaselines
187 .pages({
188 filter: {
189 baselineIdentifiers: [baselineIdentifier],
190 targetIdentifiers: [targetIdentifier],
191 },
192 })
193 .pipe(
194 Stream.runCollect,
195 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.enabledBaselines)[0]?.arn),
196 );
197
198 const toAttributes = (
199 arn: string,
200 details: controltower.EnabledBaselineDetails | undefined,
201 fallback: {
202 baselineIdentifier: string;
203 targetIdentifier: string;
204 baselineVersion?: string;
205 },
206 ): EnabledBaseline["Attributes"] => ({
207 enabledBaselineArn: arn,
208 baselineIdentifier: details?.baselineIdentifier ?? fallback.baselineIdentifier,
209 targetIdentifier: details?.targetIdentifier ?? fallback.targetIdentifier,
210 baselineVersion: details?.baselineVersion ?? fallback.baselineVersion,
211 });
212
213 export const EnabledBaselineProvider = () =>
214 Provider.effect(
215 EnabledBaseline,
216 Effect.gen(function* () {
217 return EnabledBaseline.Provider.of({
218 stables: ["enabledBaselineArn", "baselineIdentifier", "targetIdentifier"],
219 // Enumerate every enabled baseline in the ambient account (the
220 // filter-less listing is supported on management accounts; on
221 // non-Control-Tower accounts there is simply nothing to list).
222 list: () =>
223 controltower.listEnabledBaselines.pages({}).pipe(
224 Stream.runCollect,
225 Effect.map((chunk) =>
226 Array.from(chunk)
227 .flatMap((page) => page.enabledBaselines)
228 .map((summary) => ({
229 enabledBaselineArn: summary.arn,
230 baselineIdentifier: summary.baselineIdentifier,
231 targetIdentifier: summary.targetIdentifier,
232 baselineVersion: summary.baselineVersion,
233 })),
234 ),
235 ),
236 read: Effect.fn(function* ({ id, olds, output }) {
237 const arn =
238 output?.enabledBaselineArn ??
239 (olds !== undefined
240 ? yield* findEnabledBaselineArn(olds.baselineIdentifier, olds.targetIdentifier)
241 : undefined);
242 if (arn === undefined) return undefined;
243 const details = yield* readEnabledBaseline(arn);
244 if (details === undefined) return undefined;
245 const attrs = toAttributes(arn, details, {
246 baselineIdentifier: olds?.baselineIdentifier ?? "",
247 targetIdentifier: olds?.targetIdentifier ?? "",
248 });
249 const tags = yield* observeControlTowerTags(arn);
250 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
251 }),
252 diff: Effect.fn(function* ({ news, olds }) {
253 if (!isResolved(news)) return undefined;
254 if (
255 news.baselineIdentifier !== olds.baselineIdentifier ||
256 news.targetIdentifier !== olds.targetIdentifier
257 ) {
258 return { action: "replace" } as const;
259 }
260 }),
261 reconcile: Effect.fn(function* ({ id, news, output, session }) {
262 // 1. Observe — cloud state is authoritative; output is only an
263 // ARN cache.
264 let arn = output?.enabledBaselineArn;
265 let details = arn === undefined ? undefined : yield* readEnabledBaseline(arn);
266 if (details === undefined) {
267 arn = yield* findEnabledBaselineArn(news.baselineIdentifier, news.targetIdentifier);
268 details = arn === undefined ? undefined : yield* readEnabledBaseline(arn);
269 }
270
271 // 2. Ensure — enable if missing and wait for the asynchronous
272 // operation to converge.
273 if (details === undefined || arn === undefined) {
274 const internalTags = yield* createInternalTags(id);
275 const enabled = yield* retryWhileBaselineConflict(
276 controltower.enableBaseline({
277 baselineIdentifier: news.baselineIdentifier,
278 baselineVersion: news.baselineVersion,
279 targetIdentifier: news.targetIdentifier,
280 parameters: news.parameters,
281 tags: { ...news.tags, ...internalTags },
282 }),
283 );
284 arn = enabled.arn;
285 yield* session.note(`baseline operation ${enabled.operationIdentifier}`);
286 yield* waitForBaselineOperation(enabled.operationIdentifier);
287 details = yield* readEnabledBaseline(arn);
288 } else {
289 // 3. Sync — version and parameters are updated in place. Diff
290 // observed state against desired; skip the API on a no-op.
291 // Parameters cannot be cleared (only replaced), so an
292 // absent `parameters` prop leaves observed parameters
293 // alone.
294 const versionChanged = details.baselineVersion !== news.baselineVersion;
295 const parametersChanged =
296 news.parameters !== undefined &&
297 canonicalParameters(details.parameters) !== canonicalParameters(news.parameters);
298 if (versionChanged || parametersChanged) {
299 const updated = yield* retryWhileBaselineConflict(
300 controltower.updateEnabledBaseline({
301 enabledBaselineIdentifier: arn,
302 baselineVersion: news.baselineVersion,
303 parameters: news.parameters,
304 }),
305 );
306 yield* session.note(`baseline operation ${updated.operationIdentifier}`);
307 yield* waitForBaselineOperation(updated.operationIdentifier);
308 details = yield* readEnabledBaseline(arn);
309 }
310 }
311
312 // 3b. Sync tags against observed cloud tags.
313 yield* syncControlTowerTags(arn, id, news.tags);
314
315 // 4. Return fresh attributes.
316 return toAttributes(arn, details, {
317 baselineIdentifier: news.baselineIdentifier,
318 targetIdentifier: news.targetIdentifier,
319 baselineVersion: news.baselineVersion,
320 });
321 }),
322 delete: Effect.fn(function* ({ output, session }) {
323 const result = yield* retryWhileBaselineConflict(
324 controltower.disableBaseline({
325 enabledBaselineIdentifier: output.enabledBaselineArn,
326 }),
327 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
328 if (result !== undefined) {
329 yield* session.note(`baseline operation ${result.operationIdentifier}`);
330 yield* waitForBaselineOperation(result.operationIdentifier);
331 }
332 }),
333 });
334 }),
335 );