@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 328 lines 12.4 KB
Raw
1 import * as mediapackagev2 from "@distilled.cloud/aws/mediapackagev2";
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 { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Predicate from "effect/Predicate";
10 import type { Providers } from "../Providers.ts";
11 import {
12 deleteChannelWithEndpoints,
13 listAllChannelGroups,
14 listGroupChannels,
15 matchesDesired,
16 policiesEqual,
17 syncMpTags,
18 toMpTagRecord,
19 } from "./internal.ts";
20
21 export interface ChannelProps {
22 /**
23 * Name of the channel group the channel belongs to. Changing it replaces
24 * the channel.
25 */
26 channelGroupName: string;
27 /**
28 * Name of the channel. Must be unique within the channel group and match
29 * `^[a-zA-Z0-9_-]+$`. If omitted, a unique name is generated. Changing the
30 * name replaces the channel.
31 */
32 channelName?: string;
33 /**
34 * The input type of content the channel receives: `HLS` or `CMAF`.
35 * Immutable — changing it replaces the channel.
36 * @default "HLS"
37 */
38 inputType?: mediapackagev2.InputType;
39 /**
40 * Optional description of the channel (up to 1024 characters).
41 */
42 description?: string;
43 /**
44 * Input-switching behavior between the channel's redundant ingest inputs
45 * (e.g. switch based on the media quality confidence score).
46 */
47 inputSwitchConfiguration?: mediapackagev2.InputSwitchConfiguration;
48 /**
49 * Settings for what common media server data (CMSD) headers AWS Elemental
50 * MediaPackage includes in responses to the CDN.
51 */
52 outputHeaderConfiguration?: mediapackagev2.OutputHeaderConfiguration;
53 /**
54 * IAM resource policy (JSON) attached to the channel, controlling which
55 * principals may push content to it (`mediapackagev2:PutObject`).
56 * Omitting it removes any existing policy.
57 */
58 policy?: string;
59 /**
60 * User-defined tags for the channel. Merged with internal Alchemy tags.
61 */
62 tags?: Record<string, string>;
63 }
64
65 export interface Channel extends Resource<
66 "AWS.MediaPackageV2.Channel",
67 ChannelProps,
68 {
69 /** Name of the channel group the channel belongs to. */
70 channelGroupName: string;
71 /** Name of the channel. */
72 channelName: string;
73 /** ARN of the channel. */
74 channelArn: string;
75 /** Ingest container type (`HLS` or `CMAF`). */
76 inputType: string | undefined;
77 /** Redundant ingest endpoints the encoder pushes content to. */
78 ingestEndpoints: {
79 /** Ingest endpoint id (e.g. `"1"`, `"2"`). */
80 id: string | undefined;
81 /** Ingest URL the encoder pushes to. */
82 url: string | undefined;
83 }[];
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An AWS Elemental MediaPackage v2 channel — the entry point for live
91 * content into MediaPackage. An encoder (such as AWS Elemental MediaLive)
92 * pushes an HLS or CMAF stream to the channel's ingest endpoints; origin
93 * endpoints then package and serve that content downstream.
94 *
95 * ### Creating a Channel
96 * **Example:** Basic Channel in a Group
97 * ```typescript
98 * import * as MediaPackageV2 from "@alchemy.run/aws/MediaPackageV2";
99 *
100 * const group = yield* MediaPackageV2.ChannelGroup("Live");
101 * const channel = yield* MediaPackageV2.Channel("Feed", {
102 * channelGroupName: group.channelGroupName,
103 * });
104 * ```
105 *
106 * **Example:** CMAF Ingest Channel
107 * ```typescript
108 * const channel = yield* MediaPackageV2.Channel("Feed", {
109 * channelGroupName: group.channelGroupName,
110 * inputType: "CMAF",
111 * description: "CMAF contribution feed",
112 * });
113 * ```
114 *
115 * ### Resource Policy
116 * **Example:** Allow a Principal to Push Content
117 * ```typescript
118 * const channel = yield* MediaPackageV2.Channel("Feed", {
119 * channelGroupName: group.channelGroupName,
120 * policy: JSON.stringify({
121 * Version: "2012-10-17",
122 * Statement: [{
123 * Effect: "Allow",
124 * Principal: { AWS: "arn:aws:iam::111122223333:root" },
125 * Action: "mediapackagev2:PutObject",
126 * Resource: "arn:aws:mediapackagev2:us-east-1:111122223333:channelGroup/live/channel/feed",
127 * }],
128 * }),
129 * });
130 * ```
131 *
132 * ### Ingest Endpoints
133 * **Example:** Point the encoder at the ingest URLs
134 * ```typescript
135 * const channel = yield* MediaPackageV2.Channel("Feed", {
136 * channelGroupName: group.channelGroupName,
137 * });
138 * // Two redundant ingest endpoints for the encoder to push to.
139 * const urls = channel.ingestEndpoints;
140 * ```
141 *
142 * @resource
143 */
144 export const Channel = Resource<Channel>("AWS.MediaPackageV2.Channel");
145
146 export const ChannelProvider = () =>
147 Provider.effect(
148 Channel,
149 Effect.gen(function* () {
150 const createName = Effect.fn(function* (id: string, props: { channelName?: string }) {
151 return props.channelName ?? (yield* createPhysicalName({ id, maxLength: 256 }));
152 });
153
154 const toAttrs = (channel: {
155 Arn: string;
156 ChannelName: string;
157 ChannelGroupName: string;
158 IngestEndpoints?: mediapackagev2.IngestEndpoint[];
159 InputType?: mediapackagev2.InputType;
160 }) => ({
161 channelGroupName: channel.ChannelGroupName,
162 channelName: channel.ChannelName,
163 channelArn: channel.Arn,
164 inputType: channel.InputType,
165 ingestEndpoints: (channel.IngestEndpoints ?? []).map((endpoint) => ({
166 id: endpoint.Id,
167 url: endpoint.Url,
168 })),
169 });
170
171 /** Get a channel by group + name; typed not-found → undefined. */
172 const getChannel = Effect.fn(function* (channelGroupName: string, channelName: string) {
173 return yield* mediapackagev2
174 .getChannel({
175 ChannelGroupName: channelGroupName,
176 ChannelName: channelName,
177 })
178 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
179 });
180
181 return {
182 stables: ["channelGroupName", "channelName", "channelArn"],
183
184 diff: Effect.fn(function* ({ id, olds, news }) {
185 if (!isResolved(news)) return undefined;
186 // Group, name, and input type are the channel's identity.
187 if (olds.channelGroupName !== news.channelGroupName) {
188 return { action: "replace" } as const;
189 }
190 const oldName = yield* createName(id, olds);
191 const newName = yield* createName(id, news);
192 if (oldName !== newName) return { action: "replace" } as const;
193 if ((olds.inputType ?? "HLS") !== (news.inputType ?? "HLS")) {
194 return { action: "replace" } as const;
195 }
196 }),
197
198 read: Effect.fn(function* ({ id, olds, output }) {
199 const channelGroupName = output?.channelGroupName ?? olds?.channelGroupName;
200 if (channelGroupName === undefined) return undefined;
201 const channelName = output?.channelName ?? (yield* createName(id, olds ?? {}));
202 const channel = yield* getChannel(channelGroupName, channelName);
203 if (channel === undefined) return undefined;
204 const attrs = toAttrs(channel);
205 return (yield* hasAlchemyTags(id, toMpTagRecord(channel.Tags))) ? attrs : Unowned(attrs);
206 }),
207
208 reconcile: Effect.fn(function* ({ id, news, output, session }) {
209 const internalTags = yield* createInternalTags(id);
210 const desiredTags = { ...internalTags, ...news.tags };
211 const channelGroupName = news.channelGroupName;
212 const channelName = output?.channelName ?? (yield* createName(id, news));
213
214 // 1. Observe — cloud state is authoritative; output is an id cache.
215 let channel = yield* getChannel(channelGroupName, channelName);
216
217 // 2. Ensure — create if missing; a Conflict means a peer created it
218 // concurrently, so fall through to observing the winner.
219 if (channel === undefined) {
220 channel = yield* mediapackagev2
221 .createChannel({
222 ChannelGroupName: channelGroupName,
223 ChannelName: channelName,
224 InputType: news.inputType,
225 Description: news.description,
226 InputSwitchConfiguration: news.inputSwitchConfiguration,
227 OutputHeaderConfiguration: news.outputHeaderConfiguration,
228 Tags: desiredTags,
229 })
230 .pipe(
231 Effect.catchTag("ConflictException", () =>
232 mediapackagev2.getChannel({
233 ChannelGroupName: channelGroupName,
234 ChannelName: channelName,
235 }),
236 ),
237 );
238 } else {
239 // 3. Sync — apply the mutable fields only when the observed
240 // state has drifted from the desired state.
241 const desired = {
242 Description: news.description ?? "",
243 InputSwitchConfiguration: news.inputSwitchConfiguration,
244 OutputHeaderConfiguration: news.outputHeaderConfiguration,
245 };
246 const observed = {
247 Description: channel.Description ?? "",
248 InputSwitchConfiguration: channel.InputSwitchConfiguration,
249 OutputHeaderConfiguration: channel.OutputHeaderConfiguration,
250 };
251 if (!matchesDesired(desired, observed)) {
252 channel = yield* mediapackagev2.updateChannel({
253 ChannelGroupName: channelGroupName,
254 ChannelName: channelName,
255 Description: news.description,
256 InputSwitchConfiguration: news.inputSwitchConfiguration,
257 OutputHeaderConfiguration: news.outputHeaderConfiguration,
258 });
259 }
260 }
261
262 // 3b. Sync tags — diff against OBSERVED cloud tags.
263 yield* syncMpTags(channel.Arn, toMpTagRecord(channel.Tags), desiredTags);
264
265 // 3c. Sync the resource policy — observe the live policy (absent
266 // policy is the typed not-found) and apply only the delta.
267 const observedPolicy = yield* mediapackagev2
268 .getChannelPolicy({
269 ChannelGroupName: channelGroupName,
270 ChannelName: channelName,
271 })
272 .pipe(
273 Effect.map((response) => response.Policy as string | undefined),
274 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
275 );
276 if (news.policy !== undefined) {
277 if (!policiesEqual(observedPolicy, news.policy)) {
278 yield* mediapackagev2.putChannelPolicy({
279 ChannelGroupName: channelGroupName,
280 ChannelName: channelName,
281 Policy: news.policy,
282 });
283 }
284 } else if (observedPolicy !== undefined) {
285 yield* mediapackagev2.deleteChannelPolicy({
286 ChannelGroupName: channelGroupName,
287 ChannelName: channelName,
288 });
289 }
290
291 yield* session.note(channelName);
292 return toAttrs(channel);
293 }),
294
295 delete: Effect.fn(function* ({ output }) {
296 // Reap the channel's origin endpoints first (a normal stack destroy
297 // already deleted them; an orphan sweep may not have), then delete
298 // the channel. Every step is idempotent and the transient Conflict
299 // while just-deleted endpoints are cleaned up is retried.
300 yield* deleteChannelWithEndpoints(output.channelGroupName, output.channelName);
301 }),
302
303 // Channels are keyed by their parent channel group, so enumerate
304 // the groups first and fan out.
305 list: () =>
306 Effect.gen(function* () {
307 const groups = yield* listAllChannelGroups();
308 const items = yield* Effect.forEach(
309 groups,
310 (group) => listGroupChannels(group.ChannelGroupName),
311 { concurrency: 5 },
312 ).pipe(Effect.map((nested) => nested.flat()));
313 // The list shape omits ingest endpoints, so hydrate each item
314 // via get; a channel can vanish between enumeration and
315 // hydration.
316 const channels = yield* Effect.forEach(
317 items,
318 (item) =>
319 getChannel(item.ChannelGroupName, item.ChannelName).pipe(
320 Effect.map((channel) => (channel === undefined ? undefined : toAttrs(channel))),
321 ),
322 { concurrency: 5 },
323 );
324 return channels.filter(Predicate.isNotUndefined);
325 }),
326 };
327 }),
328 );