The best way to control Claude Code, Codex and more from any computer or phone

main
ts 290 lines 10.4 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 export interface RotationProps {
20 /**
21 * The name of the rotation. Changing it replaces the rotation.
22 *
23 * @default ${app}-${id}-${stage}-${suffix}
24 */
25 name?: string;
26
27 /**
28 * ARNs of the contacts on call, in shift order.
29 */
30 contactIds: string[];
31
32 /**
33 * When the rotation goes into effect, as an ISO-8601 timestamp
34 * (e.g. `"2026-01-01T00:00:00Z"`).
35 */
36 startTime?: string;
37
38 /**
39 * The IANA time zone the rotation's activity is based on
40 * (e.g. `"America/Los_Angeles"`).
41 */
42 timeZoneId: string;
43
44 /**
45 * How often the rotation hands off between contacts: daily, weekly, or
46 * monthly hand-off settings plus the number of simultaneous on-calls and
47 * optional shift coverage windows.
48 */
49 recurrence: contacts.RecurrenceSettings;
50
51 /**
52 * Tags applied to the rotation. Alchemy ownership tags are merged in
53 * automatically.
54 */
55 tags?: Record<string, string>;
56 }
57
58 /** @resource */
59 export interface Rotation extends Resource<
60 "AWS.SSMContacts.Rotation",
61 RotationProps,
62 {
63 /** ARN of the rotation. */
64 rotationArn: string;
65 /** Name of the rotation. */
66 name: string;
67 /** When the rotation goes into effect (ISO-8601). */
68 startTime: string | undefined;
69 },
70 never,
71 Providers
72 > {}
73
74 /**
75 * An Incident Manager on-call rotation — a recurring schedule that rotates
76 * engagement duty between contacts. Attach rotations to an
77 * `ONCALL_SCHEDULE` contact via its engagement plan's `RotationIds`.
78 *
79 * ### Creating Rotations
80 * **Example:** Daily hand-off rotation
81 * ```typescript
82 * const rotation = yield* SSMContacts.Rotation("Primary", {
83 * contactIds: [alice.contactArn, bob.contactArn],
84 * timeZoneId: "America/Los_Angeles",
85 * startTime: "2026-01-01T00:00:00Z",
86 * recurrence: {
87 * NumberOfOnCalls: 1,
88 * RecurrenceMultiplier: 1,
89 * DailySettings: [{ HourOfDay: 9, MinuteOfHour: 0 }],
90 * },
91 * });
92 * ```
93 */
94 const RotationResource = Resource<Rotation>("AWS.SSMContacts.Rotation");
95
96 export { RotationResource as Rotation };
97
98 const normalize = (value: unknown): unknown => {
99 if (Array.isArray(value)) return value.map(normalize);
100 if (value !== null && typeof value === "object") {
101 return Object.fromEntries(
102 Object.entries(value as Record<string, unknown>)
103 .filter(([, v]) => v !== undefined)
104 .sort(([l], [r]) => l.localeCompare(r))
105 .map(([k, v]) => [k, normalize(v)]),
106 );
107 }
108 return value;
109 };
110 const same = (l: unknown, r: unknown) =>
111 JSON.stringify(normalize(l)) === JSON.stringify(normalize(r));
112
113 export const RotationProvider = () =>
114 Provider.effect(
115 RotationResource,
116 Effect.gen(function* () {
117 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
118 return props.name ?? (yield* createPhysicalName({ id, maxLength: 200 }));
119 });
120
121 const rotationArn = Effect.fn(function* (name: string) {
122 const { accountId, region } = yield* AWSEnvironment.current;
123 return `arn:aws:ssm-contacts:${region}:${accountId}:rotation/${name}`;
124 });
125
126 const getRotation = (arn: string) =>
127 contacts.getRotation({ RotationId: arn }).pipe(
128 // A rotation ARN that does not resolve surfaces as either a plain
129 // ResourceNotFoundException or the "Invalid resource Arn"
130 // ValidationException (typed as InvalidRotationArn) — both mean
131 // "missing" to the reconciler.
132 Effect.catchTag(
133 ["ResourceNotFoundException", "InvalidRotationArn"],
134 () => Effect.undefined,
135 ),
136 );
137
138 const readTags = (arn: string) =>
139 contacts.listTagsForResource({ ResourceARN: arn }).pipe(
140 // Distilled Tag has optional Key/Value; narrow to defined pairs
141 // before handing off to the shared tagRecord helper.
142 Effect.map((r) =>
143 tagRecord(
144 (r.Tags ?? []).flatMap((t) =>
145 t.Key !== undefined && t.Value !== undefined
146 ? [{ Key: t.Key, Value: t.Value }]
147 : [],
148 ),
149 ),
150 ),
151 Effect.orElseSucceed(() => ({})),
152 );
153
154 const buildAttrs = (rotation: contacts.GetRotationResult): Rotation["Attributes"] => ({
155 rotationArn: rotation.RotationArn,
156 name: rotation.Name,
157 startTime: rotation.StartTime.toISOString(),
158 });
159
160 return RotationResource.Provider.of({
161 stables: ["rotationArn", "name"],
162
163 list: () =>
164 contacts.listRotations.items({}).pipe(
165 Stream.runCollect,
166 Effect.map((chunk) =>
167 Array.from(chunk).map((rotation) => ({
168 rotationArn: rotation.RotationArn,
169 name: rotation.Name,
170 startTime: rotation.StartTime?.toISOString(),
171 })),
172 ),
173 ),
174
175 read: Effect.fn(function* ({ id, olds, output }) {
176 const name = output?.name ?? (yield* createName(id, olds ?? {}));
177 const arn = output?.rotationArn ?? (yield* rotationArn(name));
178 const rotation = yield* getRotation(arn);
179 if (rotation === undefined) return undefined;
180 const attrs = buildAttrs(rotation);
181 const tags = yield* readTags(rotation.RotationArn);
182 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
183 }),
184
185 // The name is create-only (updateRotation cannot rename); contacts,
186 // start time, time zone, and recurrence update in place.
187 diff: Effect.fn(function* ({ id, news, olds }) {
188 if (!isResolved(news)) return undefined;
189 const oldName = yield* createName(id, olds);
190 const newName = yield* createName(id, news);
191 if (oldName !== newName) return { action: "replace" } as const;
192 }),
193
194 reconcile: Effect.fn(function* ({ id, news, output, session }) {
195 const name = output?.name ?? (yield* createName(id, news));
196 const arn = output?.rotationArn ?? (yield* rotationArn(name));
197 const internalTags = yield* createInternalTags(id);
198 const desiredTags = { ...news.tags, ...internalTags };
199 const desiredStart = news.startTime !== undefined ? new Date(news.startTime) : undefined;
200
201 // 1. OBSERVE
202 let rotation = yield* getRotation(arn);
203
204 // 2. ENSURE — create if missing; tolerate the already-exists race.
205 if (rotation === undefined) {
206 yield* session.note(`creating rotation ${name}`);
207 yield* contacts
208 .createRotation({
209 Name: name,
210 ContactIds: news.contactIds,
211 StartTime: desiredStart,
212 TimeZoneId: news.timeZoneId,
213 Recurrence: news.recurrence,
214 Tags: createTagsList(desiredTags),
215 })
216 .pipe(
217 Effect.asVoid,
218 Effect.catchTag("ConflictException", () => Effect.void),
219 );
220 rotation = (yield* getRotation(arn))!;
221 }
222
223 // 3. SYNC contacts / start time / time zone / recurrence —
224 // observed vs desired (epoch-second granularity for the start
225 // time, matching the wire format).
226 const contactsDelta = !same(rotation.ContactIds, news.contactIds);
227 const timeZoneDelta = rotation.TimeZoneId !== news.timeZoneId;
228 const startDelta =
229 desiredStart !== undefined &&
230 Math.floor(rotation.StartTime.getTime() / 1000) !==
231 Math.floor(desiredStart.getTime() / 1000);
232 const recurrenceDelta = !same(
233 {
234 MonthlySettings: rotation.Recurrence.MonthlySettings ?? [],
235 WeeklySettings: rotation.Recurrence.WeeklySettings ?? [],
236 DailySettings: rotation.Recurrence.DailySettings ?? [],
237 NumberOfOnCalls: rotation.Recurrence.NumberOfOnCalls,
238 ShiftCoverages: rotation.Recurrence.ShiftCoverages ?? {},
239 RecurrenceMultiplier: rotation.Recurrence.RecurrenceMultiplier,
240 },
241 {
242 MonthlySettings: news.recurrence.MonthlySettings ?? [],
243 WeeklySettings: news.recurrence.WeeklySettings ?? [],
244 DailySettings: news.recurrence.DailySettings ?? [],
245 NumberOfOnCalls: news.recurrence.NumberOfOnCalls,
246 ShiftCoverages: news.recurrence.ShiftCoverages ?? {},
247 RecurrenceMultiplier: news.recurrence.RecurrenceMultiplier,
248 },
249 );
250 if (contactsDelta || timeZoneDelta || startDelta || recurrenceDelta) {
251 yield* contacts.updateRotation({
252 RotationId: rotation.RotationArn,
253 ContactIds: news.contactIds,
254 StartTime: desiredStart,
255 TimeZoneId: news.timeZoneId,
256 Recurrence: news.recurrence,
257 });
258 }
259
260 // 3b. SYNC tags — diff against OBSERVED cloud tags.
261 const currentTags = yield* readTags(rotation.RotationArn);
262 const { upsert, removed } = diffTags(currentTags, desiredTags);
263 if (upsert.length > 0) {
264 yield* contacts.tagResource({
265 ResourceARN: rotation.RotationArn,
266 Tags: upsert,
267 });
268 }
269 if (removed.length > 0) {
270 yield* contacts.untagResource({
271 ResourceARN: rotation.RotationArn,
272 TagKeys: removed,
273 });
274 }
275
276 // 4. RETURN fresh attributes.
277 const final = (yield* getRotation(rotation.RotationArn))!;
278 yield* session.note(final.RotationArn);
279 return buildAttrs(final);
280 }),
281
282 delete: Effect.fn(function* ({ output }) {
283 yield* contacts.deleteRotation({ RotationId: output.rotationArn }).pipe(
284 Effect.asVoid,
285 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
286 );
287 }),
288 });
289 }),
290 );