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

main
ts 182 lines 6.43 KB
Raw
1 import * as mediapackagev2 from "@distilled.cloud/aws/mediapackagev2";
2 import { diffTags } from "alchemy/Tags";
3 import * as Effect from "effect/Effect";
4 import * as Schedule from "effect/Schedule";
5 import * as Stream from "effect/Stream";
6
7 /**
8 * Coerce a MediaPackage wire tag map (values are `string | undefined`) into a
9 * plain `Record<string, string>`, dropping any undefined values.
10 */
11 export const toMpTagRecord = (
12 tags: { [key: string]: string | undefined } | undefined,
13 ): Record<string, string> =>
14 Object.fromEntries(
15 Object.entries(tags ?? {}).filter(
16 (entry): entry is [string, string] => typeof entry[1] === "string",
17 ),
18 );
19
20 /**
21 * Sync tags on a MediaPackage resource: diff the OBSERVED cloud tags against
22 * the desired set and apply only the delta.
23 */
24 export const syncMpTags = Effect.fn(function* (
25 arn: string,
26 observedTags: Record<string, string>,
27 desiredTags: Record<string, string>,
28 ) {
29 const { removed, upsert } = diffTags(observedTags, desiredTags);
30 if (upsert.length > 0) {
31 yield* mediapackagev2.tagResource({
32 ResourceArn: arn,
33 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
34 });
35 }
36 if (removed.length > 0) {
37 yield* mediapackagev2.untagResource({
38 ResourceArn: arn,
39 TagKeys: removed,
40 });
41 }
42 });
43
44 /**
45 * Explicitly-typed pipeable retry helper. Inlining `Effect.retry` in a
46 * provider lifecycle op leaks `Retry.Return`'s conditional into declaration
47 * emit and widens the provider layer to `unknown` R for every consumer of
48 * `AWS.providers()`.
49 *
50 * MediaPackage rejects deleting a parent whose children are still being
51 * cleaned up (and concurrent mutations of the same resource) with
52 * `ConflictException`; both settle within seconds.
53 */
54 export const retryWhileMpConflict = <A, E extends { readonly _tag: string }, R>(
55 self: Effect.Effect<A, E, R>,
56 ): Effect.Effect<A, E, R> =>
57 Effect.retry(self, {
58 while: (e) => e._tag === "ConflictException",
59 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(15)]),
60 });
61
62 /**
63 * Enumerate every channel group in the account/region.
64 */
65 export const listAllChannelGroups = Effect.fn(function* () {
66 return yield* mediapackagev2.listChannelGroups.pages({}).pipe(
67 Stream.runCollect,
68 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
69 );
70 });
71
72 /**
73 * Enumerate every channel in a channel group; a missing group yields `[]`
74 * (the typed not-found), so callers can race against a concurrent delete.
75 */
76 export const listGroupChannels = Effect.fn(function* (channelGroupName: string) {
77 return yield* mediapackagev2.listChannels.pages({ ChannelGroupName: channelGroupName }).pipe(
78 Stream.runCollect,
79 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
80 Effect.catchTag("ResourceNotFoundException", () =>
81 Effect.succeed([] as mediapackagev2.ChannelListConfiguration[]),
82 ),
83 );
84 });
85
86 /**
87 * Enumerate every origin endpoint in a channel; a missing channel/group
88 * yields `[]` (the typed not-found).
89 */
90 export const listChannelEndpoints = Effect.fn(function* (
91 channelGroupName: string,
92 channelName: string,
93 ) {
94 return yield* mediapackagev2.listOriginEndpoints
95 .pages({ ChannelGroupName: channelGroupName, ChannelName: channelName })
96 .pipe(
97 Stream.runCollect,
98 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
99 Effect.catchTag("ResourceNotFoundException", () =>
100 Effect.succeed([] as mediapackagev2.OriginEndpointListConfiguration[]),
101 ),
102 );
103 });
104
105 /**
106 * Delete a channel after reaping its origin endpoints. MediaPackage refuses
107 * to delete a channel that still has endpoints, so an orphan sweep that
108 * targets a channel without enumerating its children would Conflict until
109 * the retry budget ran out and leak the channel. A normal stack destroy
110 * deletes the endpoints first, so the reap observes nothing and is free.
111 * Every step is idempotent (deleting a missing endpoint/channel succeeds).
112 */
113 export const deleteChannelWithEndpoints = Effect.fn(function* (
114 channelGroupName: string,
115 channelName: string,
116 ) {
117 const endpoints = yield* listChannelEndpoints(channelGroupName, channelName);
118 yield* Effect.forEach(
119 endpoints,
120 (endpoint) =>
121 mediapackagev2.deleteOriginEndpoint({
122 ChannelGroupName: channelGroupName,
123 ChannelName: channelName,
124 OriginEndpointName: endpoint.OriginEndpointName,
125 }),
126 { concurrency: 5, discard: true },
127 );
128 // The channel transiently rejects deletion with a Conflict while its
129 // just-deleted endpoints are cleaned up.
130 yield* mediapackagev2
131 .deleteChannel({
132 ChannelGroupName: channelGroupName,
133 ChannelName: channelName,
134 })
135 .pipe(retryWhileMpConflict);
136 });
137
138 /**
139 * Compare two IAM policy documents for semantic equality: parse both as JSON
140 * and compare the normalized serialization, so whitespace/key-order changes
141 * introduced by AWS never register as drift. Falls back to strict string
142 * equality when either side is not valid JSON.
143 */
144 export const policiesEqual = (a: string | undefined, b: string | undefined): boolean => {
145 if (a === undefined || b === undefined) return a === b;
146 try {
147 return JSON.stringify(JSON.parse(a)) === JSON.stringify(JSON.parse(b));
148 } catch {
149 return a === b;
150 }
151 };
152
153 /**
154 * Structural "desired is a subset of observed" comparison used for drift
155 * detection. Only keys present (and defined) in `desired` are compared, so
156 * server-side defaults on the observed state never register as drift. Arrays
157 * must match pairwise and in length so removed/added items are detected.
158 */
159 export const matchesDesired = (desired: unknown, observed: unknown): boolean => {
160 if (desired === undefined) return true;
161 if (desired === null) return observed === null;
162 if (desired instanceof Date) {
163 return observed instanceof Date && desired.getTime() === observed.getTime();
164 }
165 if (Array.isArray(desired)) {
166 if (!Array.isArray(observed) || observed.length !== desired.length) {
167 return false;
168 }
169 return desired.every((item, i) => matchesDesired(item, observed[i]));
170 }
171 if (typeof desired === "object") {
172 if (typeof observed !== "object" || observed === null || Array.isArray(observed)) {
173 return false;
174 }
175 return Object.entries(desired as Record<string, unknown>).every(([key, value]) =>
176 value === undefined
177 ? true
178 : matchesDesired(value, (observed as Record<string, unknown>)[key]),
179 );
180 }
181 return desired === observed;
182 };