@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 327 lines 11.3 KB
Raw
1 import * as contacts from "@distilled.cloud/aws/ssm-contacts";
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 {
8 createInternalTags,
9 createTagsList,
10 diffTags,
11 hasAlchemyTags,
12 tagRecord,
13 } from "alchemy/Tags";
14 import * as Effect from "effect/Effect";
15 import * as Stream from "effect/Stream";
16 import { AWSEnvironment } from "../Environment.ts";
17 import type { Providers } from "../Providers.ts";
18
19 /** The kind of contact: a person, an escalation plan, or an on-call schedule. */
20 export type ContactType = "PERSONAL" | "ESCALATION" | "ONCALL_SCHEDULE";
21
22 export interface ContactProps {
23 /**
24 * The unique, identifiable alias of the contact or escalation plan
25 * (lowercase letters, numbers, `-`, `_`, `.`). Changing it replaces the
26 * contact.
27 *
28 * @default ${app}-${id}-${stage}-${suffix} (lowercased)
29 */
30 alias?: string;
31
32 /**
33 * The full name of the contact or escalation plan.
34 */
35 displayName?: string;
36
37 /**
38 * `PERSONAL` for a single person, `ESCALATION` for an escalation plan that
39 * engages contacts in phases, or `ONCALL_SCHEDULE` for a rotation-backed
40 * schedule. Changing it replaces the contact.
41 */
42 type: ContactType;
43
44 /**
45 * The stages (engagement plan) that Incident Manager runs through when
46 * engaging this contact. Stage targets are contact channels for `PERSONAL`
47 * contacts and contacts for `ESCALATION` plans; `ONCALL_SCHEDULE` contacts
48 * reference rotations via `RotationIds`.
49 *
50 * When omitted, an existing plan is left untouched so it can be managed by
51 * the standalone `SSMContacts.Plan` resource.
52 */
53 plan?: contacts.Plan;
54
55 /**
56 * The contact's resource policy as a JSON policy document (string or
57 * object) — shares the contact and its engagements with other accounts.
58 * When omitted, any existing policy is left untouched (SSM Contacts has
59 * no delete-policy API).
60 */
61 policy?: string | Record<string, unknown>;
62
63 /**
64 * Tags applied to the contact. Alchemy ownership tags are merged in
65 * automatically.
66 */
67 tags?: Record<string, string>;
68 }
69
70 /** @resource */
71 export interface Contact extends Resource<
72 "AWS.SSMContacts.Contact",
73 ContactProps,
74 {
75 /** ARN of the contact. */
76 contactArn: string;
77 /** Alias of the contact. */
78 alias: string;
79 /** The contact type. */
80 type: string;
81 /** Display name of the contact. */
82 displayName: string | undefined;
83 },
84 never,
85 Providers
86 > {}
87
88 /**
89 * An Incident Manager contact — a person Incident Manager engages during an
90 * incident, an escalation plan that engages contacts in phases, or an
91 * on-call schedule backed by rotations.
92 *
93 * Requires the account's Incident Manager replication set
94 * (`SSMIncidents.ReplicationSet`) to exist.
95 *
96 * ### Creating Contacts
97 * **Example:** Personal contact
98 * ```typescript
99 * const oncall = yield* SSMContacts.Contact("Oncall", {
100 * type: "PERSONAL",
101 * displayName: "Primary On-Call",
102 * });
103 * ```
104 *
105 * **Example:** Contact with an inline engagement plan
106 * ```typescript
107 * const channel = yield* SSMContacts.ContactChannel("Email", {
108 * contactId: oncall.contactArn,
109 * type: "EMAIL",
110 * deliveryAddress: { SimpleAddress: "oncall@example.com" },
111 * deferActivation: true,
112 * });
113 * const escalation = yield* SSMContacts.Contact("Escalation", {
114 * type: "ESCALATION",
115 * plan: {
116 * Stages: [
117 * {
118 * DurationInMinutes: 5,
119 * Targets: [
120 * { ContactTargetInfo: { ContactId: oncall.contactArn, IsEssential: true } },
121 * ],
122 * },
123 * ],
124 * },
125 * });
126 * ```
127 */
128 const ContactResource = Resource<Contact>("AWS.SSMContacts.Contact");
129
130 export { ContactResource as Contact };
131
132 const normalize = (value: unknown): unknown => {
133 if (Array.isArray(value)) return value.map(normalize);
134 if (value !== null && typeof value === "object") {
135 return Object.fromEntries(
136 Object.entries(value as Record<string, unknown>)
137 .filter(([, v]) => v !== undefined)
138 .sort(([l], [r]) => l.localeCompare(r))
139 .map(([k, v]) => [k, normalize(v)]),
140 );
141 }
142 return value;
143 };
144 const same = (l: unknown, r: unknown) =>
145 JSON.stringify(normalize(l)) === JSON.stringify(normalize(r));
146
147 /** Parse a policy JSON string for structural comparison; fall back to the raw string. */
148 const parsePolicy = (policy: string): unknown => {
149 try {
150 return JSON.parse(policy);
151 } catch {
152 return policy;
153 }
154 };
155
156 /** Builds the ARN of a contact from its alias in the ambient account/region. */
157 export const contactArn = Effect.fn(function* (alias: string) {
158 const { accountId, region } = yield* AWSEnvironment.current;
159 return `arn:aws:ssm-contacts:${region}:${accountId}:contact/${alias}`;
160 });
161
162 export const ContactProvider = () =>
163 Provider.effect(
164 ContactResource,
165 Effect.gen(function* () {
166 const createAlias = Effect.fn(function* (id: string, props: { alias?: string }) {
167 // Contact aliases must be lowercase.
168 return props.alias ?? (yield* createPhysicalName({ id, maxLength: 200, lowercase: true }));
169 });
170
171 const getContact = (arn: string) =>
172 contacts
173 .getContact({ ContactId: arn })
174 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
175
176 const readTags = (arn: string) =>
177 contacts.listTagsForResource({ ResourceARN: arn }).pipe(
178 // Distilled Tag has optional Key/Value; narrow to defined pairs
179 // before handing off to the shared tagRecord helper.
180 Effect.map((r) =>
181 tagRecord(
182 (r.Tags ?? []).flatMap((t) =>
183 t.Key !== undefined && t.Value !== undefined
184 ? [{ Key: t.Key, Value: t.Value }]
185 : [],
186 ),
187 ),
188 ),
189 Effect.orElseSucceed(() => ({})),
190 );
191
192 const buildAttrs = (contact: contacts.GetContactResult) => ({
193 contactArn: contact.ContactArn,
194 alias: contact.Alias,
195 type: contact.Type as string,
196 displayName: contact.DisplayName,
197 });
198
199 return ContactResource.Provider.of({
200 stables: ["contactArn", "alias", "type"],
201
202 list: () =>
203 contacts.listContacts.items({}).pipe(
204 Stream.runCollect,
205 Effect.map((chunk) =>
206 Array.from(chunk).map((contact) => ({
207 contactArn: contact.ContactArn,
208 alias: contact.Alias,
209 type: contact.Type as string,
210 displayName: contact.DisplayName,
211 })),
212 ),
213 ),
214
215 read: Effect.fn(function* ({ id, olds, output }) {
216 const alias = output?.alias ?? (yield* createAlias(id, olds ?? {}));
217 const arn = output?.contactArn ?? (yield* contactArn(alias));
218 const contact = yield* getContact(arn);
219 if (contact === undefined) return undefined;
220 const attrs = buildAttrs(contact);
221 const tags = yield* readTags(contact.ContactArn);
222 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
223 }),
224
225 // Alias and type are create-only; display name, plan, and tags update
226 // in place.
227 diff: Effect.fn(function* ({ id, news, olds }) {
228 if (!isResolved(news)) return undefined;
229 const oldAlias = yield* createAlias(id, olds);
230 const newAlias = yield* createAlias(id, news);
231 if (oldAlias !== newAlias) return { action: "replace" } as const;
232 if (olds.type !== news.type) return { action: "replace" } as const;
233 }),
234
235 reconcile: Effect.fn(function* ({ id, news, output, session }) {
236 const alias = output?.alias ?? (yield* createAlias(id, news));
237 const arn = output?.contactArn ?? (yield* contactArn(alias));
238 const internalTags = yield* createInternalTags(id);
239 const desiredTags = { ...news.tags, ...internalTags };
240
241 // 1. OBSERVE
242 let contact = yield* getContact(arn);
243
244 // 2. ENSURE — create if missing; tolerate the already-exists race.
245 if (contact === undefined) {
246 yield* session.note(`creating contact ${alias}`);
247 yield* contacts
248 .createContact({
249 Alias: alias,
250 DisplayName: news.displayName,
251 Type: news.type,
252 Plan: news.plan ?? { Stages: [] },
253 Tags: createTagsList(desiredTags),
254 })
255 .pipe(
256 Effect.asVoid,
257 Effect.catchTag("ConflictException", () => Effect.void),
258 );
259 contact = (yield* getContact(arn))!;
260 }
261
262 // 3. SYNC display name + plan — diff observed against desired.
263 // `plan` is only managed here when the prop is provided, so the
264 // standalone `SSMContacts.Plan` resource can own it otherwise.
265 const displayNameDelta = (contact.DisplayName ?? "") !== (news.displayName ?? "");
266 const planDelta = news.plan !== undefined && !same(contact.Plan, news.plan);
267 if (displayNameDelta || planDelta) {
268 yield* contacts.updateContact({
269 ContactId: contact.ContactArn,
270 DisplayName: news.displayName ?? "",
271 ...(planDelta ? { Plan: news.plan } : {}),
272 });
273 }
274
275 // 3b. SYNC resource policy — observed vs desired. Only managed
276 // when the prop is provided; there is no delete-policy API.
277 if (news.policy !== undefined) {
278 const desiredPolicy =
279 typeof news.policy === "string" ? news.policy : JSON.stringify(news.policy);
280 const observedPolicy = yield* contacts
281 .getContactPolicy({ ContactArn: contact.ContactArn })
282 .pipe(
283 Effect.map((r) => r.Policy),
284 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
285 );
286 if (
287 observedPolicy === undefined ||
288 !same(parsePolicy(observedPolicy), parsePolicy(desiredPolicy))
289 ) {
290 yield* contacts.putContactPolicy({
291 ContactArn: contact.ContactArn,
292 Policy: desiredPolicy,
293 });
294 }
295 }
296
297 // 3c. SYNC tags — diff against OBSERVED cloud tags.
298 const currentTags = yield* readTags(contact.ContactArn);
299 const { upsert, removed } = diffTags(currentTags, desiredTags);
300 if (upsert.length > 0) {
301 yield* contacts.tagResource({
302 ResourceARN: contact.ContactArn,
303 Tags: upsert,
304 });
305 }
306 if (removed.length > 0) {
307 yield* contacts.untagResource({
308 ResourceARN: contact.ContactArn,
309 TagKeys: removed,
310 });
311 }
312
313 // 4. RETURN fresh attributes.
314 const final = (yield* getContact(contact.ContactArn))!;
315 yield* session.note(final.ContactArn);
316 return buildAttrs(final);
317 }),
318
319 delete: Effect.fn(function* ({ output }) {
320 yield* contacts.deleteContact({ ContactId: output.contactArn }).pipe(
321 Effect.asVoid,
322 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
323 );
324 }),
325 });
326 }),
327 );