@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 238 lines 8.31 KB
Raw
1 import * as medialive from "@distilled.cloud/aws/medialive";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { ensureIdentified, syncMlTags, toTagRecord } from "./internal.ts";
11
12 // Explicitly-typed pipeable retry helper. Inlining `Effect.retry` in a
13 // provider lifecycle op leaks `Retry.Return`'s conditional into declaration
14 // emit and widens the provider layer to `unknown` R for every consumer of
15 // `AWS.providers()`.
16 //
17 // An Input Security Group attached to a still-deleting Input rejects
18 // deletion with a `BadRequestException` until the Input is fully gone.
19 const retryWhileInUse = <A, E extends { readonly _tag: string }, R>(
20 self: Effect.Effect<A, E, R>,
21 ): Effect.Effect<A, E, R> =>
22 Effect.retry(self, {
23 while: (e) => e._tag === "BadRequestException" || e._tag === "ConflictException",
24 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
25 });
26
27 /** An input security group whose server-assigned identity is present. */
28 type IdentifiedGroup = medialive.InputSecurityGroup & {
29 Id: string;
30 Arn: string;
31 };
32
33 const hasIdentity = (isg: medialive.InputSecurityGroup): isg is IdentifiedGroup =>
34 isg.Id !== undefined && isg.Arn !== undefined;
35
36 export interface InputSecurityGroupProps {
37 /**
38 * IPv4 CIDR ranges allowed to push content to inputs attached to this
39 * security group (e.g. `"10.0.0.0/16"`, `"0.0.0.0/0"`).
40 * @default ["0.0.0.0/0"]
41 */
42 whitelistRules?: string[];
43 /**
44 * User-defined tags for the input security group.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface InputSecurityGroup extends Resource<
50 "AWS.MediaLive.InputSecurityGroup",
51 InputSecurityGroupProps,
52 {
53 /** Server-assigned unique id of the input security group. */
54 inputSecurityGroupId: string;
55 /** ARN of the input security group. */
56 inputSecurityGroupArn: string;
57 /** Current state (e.g. `IDLE`, `IN_USE`). */
58 state: medialive.InputSecurityGroupState | undefined;
59 /** Allowlisted source CIDR blocks. */
60 whitelistRules: string[];
61 },
62 never,
63 Providers
64 > {}
65
66 /**
67 * An AWS Elemental MediaLive input security group — an IP allowlist that
68 * gates which source networks may push content to attached PUSH inputs
69 * (RTMP_PUSH, RTP_PUSH, UDP_PUSH).
70 *
71 * ### Creating an Input Security Group
72 * **Example:** Allow a single network
73 * ```typescript
74 * const isg = yield* MediaLive.InputSecurityGroup("Allowlist", {
75 * whitelistRules: ["10.0.0.0/16"],
76 * });
77 * ```
78 *
79 * **Example:** Open to the world (test-only)
80 * ```typescript
81 * const isg = yield* MediaLive.InputSecurityGroup("Open", {
82 * whitelistRules: ["0.0.0.0/0"],
83 * tags: { team: "media" },
84 * });
85 * ```
86 *
87 * ### Attaching to an Input
88 * **Example:** Gate an RTMP push input
89 * ```typescript
90 * const input = yield* MediaLive.Input("Stream", {
91 * type: "RTMP_PUSH",
92 * inputSecurityGroups: [isg.inputSecurityGroupId],
93 * destinations: [{ StreamName: "live/stream" }],
94 * });
95 * ```
96 *
97 * @resource
98 */
99 export const InputSecurityGroup = Resource<InputSecurityGroup>("AWS.MediaLive.InputSecurityGroup");
100
101 export const InputSecurityGroupProvider = () =>
102 Provider.effect(
103 InputSecurityGroup,
104 Effect.gen(function* () {
105 const toAttrs = (isg: IdentifiedGroup) => ({
106 inputSecurityGroupId: isg.Id,
107 inputSecurityGroupArn: isg.Arn,
108 state: isg.State,
109 whitelistRules: (isg.WhitelistRules ?? [])
110 .map((r) => r.Cidr)
111 .filter((cidr): cidr is string => cidr !== undefined),
112 });
113
114 /** Describe by id; typed not-found (or tombstone state) → undefined. */
115 const getGroup = Effect.fn(function* (id: string) {
116 const isg = yield* medialive
117 .describeInputSecurityGroup({ InputSecurityGroupId: id })
118 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
119 if (isg === undefined || isg.State === "DELETED") return undefined;
120 if (!hasIdentity(isg)) return undefined;
121 return isg;
122 });
123
124 /**
125 * Input security groups have server-assigned ids and no name, so a
126 * read without cached output scans the account list for the group
127 * carrying this logical id's Alchemy tags.
128 */
129 const findByTags = Effect.fn(function* (id: string) {
130 const groups = yield* medialive.listInputSecurityGroups.items({}).pipe(
131 Stream.runCollect,
132 Effect.map((chunk) => Array.from(chunk)),
133 );
134 for (const isg of groups) {
135 if (isg.State === "DELETED" || !hasIdentity(isg)) continue;
136 if (yield* hasAlchemyTags(id, toTagRecord(isg.Tags))) {
137 return isg;
138 }
139 }
140 return undefined;
141 });
142
143 const desiredRules = (props: InputSecurityGroupProps) =>
144 (props.whitelistRules ?? ["0.0.0.0/0"]).map((cidr) => ({
145 Cidr: cidr,
146 }));
147
148 return InputSecurityGroup.Provider.of({
149 stables: ["inputSecurityGroupId", "inputSecurityGroupArn"],
150
151 list: () =>
152 medialive.listInputSecurityGroups.items({}).pipe(
153 Stream.runCollect,
154 Effect.map((chunk) =>
155 Array.from(chunk)
156 .filter(
157 (isg): isg is IdentifiedGroup => hasIdentity(isg) && isg.State !== "DELETED",
158 )
159 .map(toAttrs),
160 ),
161 ),
162
163 read: Effect.fn(function* ({ id, output }) {
164 const isg =
165 output?.inputSecurityGroupId !== undefined
166 ? yield* getGroup(output.inputSecurityGroupId)
167 : yield* findByTags(id);
168 if (isg === undefined) return undefined;
169 const attrs = toAttrs(isg);
170 return (yield* hasAlchemyTags(id, toTagRecord(isg.Tags))) ? attrs : Unowned(attrs);
171 }),
172
173 // No immutable props — every drift is an in-place update.
174 diff: Effect.fn(function* () {}),
175
176 reconcile: Effect.fn(function* ({ id, news, output, session }) {
177 const internalTags = yield* createInternalTags(id);
178 const desiredTags = { ...internalTags, ...news.tags };
179 const rules = desiredRules(news);
180
181 // 1. Observe — cloud state is authoritative; output is an id cache.
182 let isg =
183 output?.inputSecurityGroupId !== undefined
184 ? yield* getGroup(output.inputSecurityGroupId)
185 : yield* findByTags(id);
186
187 // 2. Ensure — create if missing.
188 if (isg === undefined) {
189 const created = yield* medialive.createInputSecurityGroup({
190 WhitelistRules: rules,
191 Tags: desiredTags,
192 });
193 isg = yield* ensureIdentified(
194 created.SecurityGroup,
195 "CreateInputSecurityGroup SecurityGroup Id/Arn",
196 );
197 } else {
198 // 3. Sync — apply whitelist rules only when they drift.
199 const observed = (isg.WhitelistRules ?? [])
200 .map((r) => r.Cidr)
201 .filter((cidr): cidr is string => cidr !== undefined)
202 .sort();
203 const wanted = rules
204 .map((r) => r.Cidr)
205 .slice()
206 .sort();
207 if (JSON.stringify(observed) !== JSON.stringify(wanted)) {
208 const updated = yield* medialive.updateInputSecurityGroup({
209 InputSecurityGroupId: isg.Id,
210 WhitelistRules: rules,
211 });
212 isg = yield* ensureIdentified(
213 updated.SecurityGroup,
214 "UpdateInputSecurityGroup SecurityGroup Id/Arn",
215 );
216 }
217 }
218
219 // 3b. Sync tags — diff against OBSERVED cloud tags.
220 yield* syncMlTags(isg.Arn, desiredTags);
221
222 yield* session.note(isg.Id);
223 return toAttrs(isg);
224 }),
225
226 delete: Effect.fn(function* ({ output }) {
227 yield* medialive
228 .deleteInputSecurityGroup({
229 InputSecurityGroupId: output.inputSecurityGroupId,
230 })
231 .pipe(
232 retryWhileInUse,
233 Effect.catchTag("NotFoundException", () => Effect.void),
234 );
235 }),
236 });
237 }),
238 );