@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 336 lines 12.7 KB
Raw
1 import type { Credentials } from "@distilled.cloud/aws/Credentials";
2 import type { Region } from "@distilled.cloud/aws/Region";
3 import * as incidents from "@distilled.cloud/aws/ssm-incidents";
4 import { Unowned } from "alchemy/AdoptPolicy";
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 type { HttpClient } from "effect/http/HttpClient";
11 import * as Schedule from "effect/Schedule";
12 import { AWSEnvironment } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 /**
16 * Raised when the replication set enters a terminal `FAILED` state (or does
17 * not become `ACTIVE` within the bounded wait window) while reconciling.
18 */
19 export class ReplicationSetNotActive extends Data.TaggedError("ReplicationSetNotActive")<{
20 message: string;
21 status: string;
22 }> {}
23
24 export interface ReplicationSetProps {
25 /**
26 * The Regions that Incident Manager replicates your data to, keyed by
27 * Region name. Each Region may specify a customer-managed KMS key for
28 * encryption at rest via `sseKmsKeyId`; omit it to use an AWS-owned key.
29 *
30 * @default the ambient deployment Region with an AWS-owned key
31 */
32 regions?: Record<string, { sseKmsKeyId?: string }>;
33
34 /**
35 * Whether deletion protection is enabled. When `true`, the replication set
36 * cannot be deleted until protection is disabled. Alchemy automatically
37 * disables protection before deleting the resource.
38 *
39 * @default false
40 */
41 deletionProtected?: boolean;
42
43 /**
44 * Tags applied to the replication set. Alchemy ownership tags are merged
45 * in automatically.
46 */
47 tags?: Record<string, string>;
48 }
49
50 /** @resource */
51 export interface ReplicationSet extends Resource<
52 "AWS.SSMIncidents.ReplicationSet",
53 ReplicationSetProps,
54 {
55 /** ARN of the replication set. */
56 arn: string;
57 /** Current status (`ACTIVE`, `CREATING`, `UPDATING`, `DELETING`, `FAILED`). */
58 status: string;
59 /** Names of the Regions in the replication set. */
60 regionNames: string[];
61 /** Whether deletion protection is currently enabled. */
62 deletionProtected: boolean;
63 },
64 never,
65 Providers
66 > {}
67
68 /**
69 * The Incident Manager replication set — the account/region singleton that
70 * onboards AWS Systems Manager Incident Manager. Creating it replicates and
71 * encrypts Incident Manager data (response plans, incidents, contacts) to the
72 * configured Regions; deleting it offboards Incident Manager and removes all
73 * Incident Manager data account-wide.
74 *
75 * Only one replication set can exist per account, so this is a
76 * capture-and-restore singleton: adopting a pre-existing replication set that
77 * Alchemy did not create requires `--adopt`.
78 *
79 * ### Onboarding Incident Manager
80 * **Example:** Replication set in the current Region
81 * ```typescript
82 * const replicationSet = yield* SSMIncidents.ReplicationSet("Incidents", {});
83 * ```
84 *
85 * **Example:** Multi-Region replication with a KMS key
86 * ```typescript
87 * const replicationSet = yield* SSMIncidents.ReplicationSet("Incidents", {
88 * regions: {
89 * "us-east-1": {},
90 * "us-west-2": { sseKmsKeyId: key.keyArn },
91 * },
92 * deletionProtected: true,
93 * });
94 * ```
95 */
96 const ReplicationSetResource = Resource<ReplicationSet>("AWS.SSMIncidents.ReplicationSet");
97
98 export { ReplicationSetResource as ReplicationSet };
99
100 type IncidentsDeps = Credentials | Region | HttpClient;
101
102 // Explicitly-typed pipeable helpers. Inlining `Effect.retry`/`Effect.repeat`
103 // in a provider lifecycle op leaks `Retry.Return`'s conditional into
104 // declaration emit and widens the provider layer to `unknown` R for every
105 // consumer of `AWS.providers()`.
106
107 /**
108 * Polls the replication set until it leaves its transitional state
109 * (`CREATING`/`UPDATING`), then fails with a typed error unless it landed on
110 * `ACTIVE`. Bounded: ~5s x 60 = 5 minutes (onboarding takes ~1-2 minutes).
111 */
112 const waitForReplicationSetActive = (
113 arn: string,
114 ): Effect.Effect<
115 incidents.ReplicationSet,
116 incidents.GetReplicationSetError | ReplicationSetNotActive,
117 IncidentsDeps
118 > =>
119 incidents.getReplicationSet({ arn }).pipe(
120 Effect.map((r) => r.replicationSet),
121 Effect.repeat({
122 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(60)]),
123 until: (rs) => rs.status !== "CREATING" && rs.status !== "UPDATING",
124 }),
125 Effect.flatMap((rs) =>
126 rs.status === "ACTIVE"
127 ? Effect.succeed(rs)
128 : Effect.fail(
129 new ReplicationSetNotActive({
130 message: `replication set ${arn} did not become ACTIVE`,
131 status: rs.status,
132 }),
133 ),
134 ),
135 );
136
137 /**
138 * Polls until the replication set is fully gone (offboarding takes ~1-2
139 * minutes and a subsequent create conflicts until it completes). Bounded:
140 * ~5s x 60 = 5 minutes.
141 */
142 const waitForReplicationSetGone = (
143 arn: string,
144 ): Effect.Effect<void, incidents.GetReplicationSetError, IncidentsDeps> =>
145 incidents.getReplicationSet({ arn }).pipe(
146 Effect.map((r) => r.replicationSet.status),
147 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed("GONE" as const)),
148 Effect.repeat({
149 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(60)]),
150 until: (status) => status === "GONE",
151 }),
152 Effect.asVoid,
153 );
154
155 export const ReplicationSetProvider = () =>
156 Provider.effect(
157 ReplicationSetResource,
158 Effect.gen(function* () {
159 // The replication set is the account singleton — its ARN is not
160 // derivable, so observation always starts from the list.
161 const observe = Effect.gen(function* () {
162 const listed = yield* incidents.listReplicationSets({});
163 const arn = listed.replicationSetArns[0];
164 if (arn === undefined) return undefined;
165 return yield* incidents.getReplicationSet({ arn }).pipe(
166 Effect.map((r) => ({ ...r.replicationSet, arn })),
167 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
168 );
169 });
170
171 const readTags = (arn: string) =>
172 incidents.listTagsForResource({ resourceArn: arn }).pipe(
173 Effect.map(
174 (r) =>
175 Object.fromEntries(
176 Object.entries(r.tags).filter((e): e is [string, string] => e[1] !== undefined),
177 ) as Record<string, string>,
178 ),
179 Effect.orElseSucceed(() => ({})),
180 );
181
182 const buildAttrs = (rs: incidents.ReplicationSet & { arn: string }) => ({
183 arn: rs.arn,
184 status: rs.status,
185 regionNames: Object.keys(rs.regionMap).sort(),
186 deletionProtected: rs.deletionProtected,
187 });
188
189 const desiredRegions = Effect.fn(function* (props: ReplicationSetProps) {
190 if (props.regions && Object.keys(props.regions).length > 0) {
191 return props.regions;
192 }
193 const { region } = yield* AWSEnvironment.current;
194 return { [region]: {} } as Record<string, { sseKmsKeyId?: string }>;
195 });
196
197 return ReplicationSetResource.Provider.of({
198 stables: ["arn"],
199
200 read: Effect.fn(function* ({ id, output }) {
201 const live = yield* observe;
202 if (live === undefined) return undefined;
203 const attrs = buildAttrs(live);
204 const tags = yield* readTags(live.arn);
205 if (yield* hasAlchemyTags(id, tags)) return attrs;
206 // Tag-based ownership is best-effort — if we have prior state for
207 // this exact singleton, it is ours; otherwise gate adoption.
208 return output !== undefined ? attrs : Unowned(attrs);
209 }),
210
211 // Account/region singleton — report the single replication set, if any.
212 list: () => observe.pipe(Effect.map((rs) => (rs ? [buildAttrs(rs)] : []))),
213
214 reconcile: Effect.fn(function* ({ id, news, output, session }) {
215 const internalTags = yield* createInternalTags(id);
216 const desiredTags = { ...news.tags, ...internalTags };
217 const regions = yield* desiredRegions(news);
218
219 // 1. OBSERVE — cloud state is authoritative; `output` is only an
220 // identifier cache.
221 let live = yield* observe;
222
223 // 2. ENSURE — onboard Incident Manager if there is no replication
224 // set. Tolerate the singleton-create race (ConflictException)
225 // by falling through to observation.
226 if (live === undefined) {
227 yield* session.note("creating Incident Manager replication set");
228 const created = yield* incidents
229 .createReplicationSet({
230 regions: Object.fromEntries(
231 Object.entries(regions).map(([name, cfg]) => [
232 name,
233 { sseKmsKeyId: cfg.sseKmsKeyId },
234 ]),
235 ),
236 tags: desiredTags,
237 })
238 .pipe(
239 Effect.map((r) => r.arn),
240 Effect.catchTag("ConflictException", () =>
241 incidents
242 .listReplicationSets({})
243 .pipe(Effect.map((r) => r.replicationSetArns[0]!)),
244 ),
245 );
246 yield* waitForReplicationSetActive(created);
247 live = (yield* observe)!;
248 } else if (live.status === "CREATING" || live.status === "UPDATING") {
249 // A prior reconcile may have been interrupted mid-transition.
250 yield* waitForReplicationSetActive(live.arn);
251 live = (yield* observe)!;
252 }
253 const arn = output?.arn ?? live.arn;
254
255 // 3. SYNC regions — diff observed Region map against desired and
256 // apply one add/delete action at a time (the API allows a single
257 // Region change per update). Add first so the set never shrinks
258 // to zero.
259 const observedRegions = Object.keys(live.regionMap);
260 const toAdd = Object.keys(regions).filter((r) => !observedRegions.includes(r));
261 const toRemove = observedRegions.filter((r) => !(r in regions));
262 for (const regionName of toAdd) {
263 yield* session.note(`adding region ${regionName}`);
264 yield* incidents.updateReplicationSet({
265 arn,
266 actions: [
267 {
268 addRegionAction: {
269 regionName,
270 sseKmsKeyId: regions[regionName]?.sseKmsKeyId,
271 },
272 },
273 ],
274 });
275 yield* waitForReplicationSetActive(arn);
276 }
277 for (const regionName of toRemove) {
278 yield* session.note(`removing region ${regionName}`);
279 yield* incidents.updateReplicationSet({
280 arn,
281 actions: [{ deleteRegionAction: { regionName } }],
282 });
283 yield* waitForReplicationSetActive(arn);
284 }
285
286 // 3b. SYNC deletion protection — observed vs desired.
287 const desiredProtection = news.deletionProtected ?? false;
288 if (live.deletionProtected !== desiredProtection) {
289 yield* incidents.updateDeletionProtection({
290 arn,
291 deletionProtected: desiredProtection,
292 });
293 }
294
295 // 3c. SYNC tags — diff against OBSERVED cloud tags.
296 const currentTags = yield* readTags(arn);
297 const { upsert, removed } = diffTags(currentTags, desiredTags);
298 if (upsert.length > 0) {
299 yield* incidents.tagResource({
300 resourceArn: arn,
301 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
302 });
303 }
304 if (removed.length > 0) {
305 yield* incidents.untagResource({
306 resourceArn: arn,
307 tagKeys: removed,
308 });
309 }
310
311 // 4. RETURN fresh attributes.
312 const final = (yield* observe)!;
313 yield* session.note(arn);
314 return buildAttrs(final);
315 }),
316
317 delete: Effect.fn(function* ({ output }) {
318 // Deleting the replication set offboards Incident Manager. Deletion
319 // protection must be lifted first; both calls are idempotent.
320 yield* incidents
321 .updateDeletionProtection({
322 arn: output.arn,
323 deletionProtected: false,
324 })
325 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
326 yield* incidents.deleteReplicationSet({ arn: output.arn }).pipe(
327 Effect.asVoid,
328 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
329 );
330 // Offboarding is asynchronous (~1-2 minutes); wait until fully gone
331 // so an immediate re-create does not conflict.
332 yield* waitForReplicationSetGone(output.arn);
333 }),
334 });
335 }),
336 );