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

main
ts 205 lines 7.86 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 Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import {
12 deleteChannelWithEndpoints,
13 listGroupChannels,
14 retryWhileMpConflict,
15 syncMpTags,
16 toMpTagRecord,
17 } from "./internal.ts";
18
19 export interface ChannelGroupProps {
20 /**
21 * Name of the channel group. Must be unique within the account/region and
22 * match `^[a-zA-Z0-9_-]+$`. If omitted, a unique name is generated.
23 * Changing the name replaces the channel group.
24 */
25 channelGroupName?: string;
26 /**
27 * Optional description of the channel group (up to 1024 characters).
28 */
29 description?: string;
30 /**
31 * User-defined tags for the channel group. Merged with internal Alchemy
32 * tags.
33 */
34 tags?: Record<string, string>;
35 }
36
37 export interface ChannelGroup extends Resource<
38 "AWS.MediaPackageV2.ChannelGroup",
39 ChannelGroupProps,
40 {
41 /** Name of the channel group. */
42 channelGroupName: string;
43 /** ARN of the channel group. */
44 channelGroupArn: string;
45 /** Shared egress domain that serves all origin endpoints in the group. */
46 egressDomain: string;
47 },
48 never,
49 Providers
50 > {}
51
52 /**
53 * An AWS Elemental MediaPackage v2 channel group — the top-level container
54 * for channels and origin endpoints. All channels and origin endpoints in a
55 * group share one egress domain, giving downstream players and CDNs
56 * predictable URLs for stream delivery.
57 *
58 * ### Creating a Channel Group
59 * **Example:** Basic Channel Group
60 * ```typescript
61 * import * as MediaPackageV2 from "@alchemy.run/aws/MediaPackageV2";
62 *
63 * const group = yield* MediaPackageV2.ChannelGroup("Live");
64 * ```
65 *
66 * **Example:** Channel Group with Description and Tags
67 * ```typescript
68 * const group = yield* MediaPackageV2.ChannelGroup("Live", {
69 * description: "Live sports streams",
70 * tags: { team: "media" },
71 * });
72 * ```
73 *
74 * ### Egress Domain
75 * **Example:** Use the shared egress domain
76 * ```typescript
77 * const group = yield* MediaPackageV2.ChannelGroup("Live");
78 * // e.g. abcde.egress.xyz.mediapackagev2.us-east-1.amazonaws.com
79 * const domain = group.egressDomain;
80 * ```
81 *
82 * @resource
83 */
84 export const ChannelGroup = Resource<ChannelGroup>("AWS.MediaPackageV2.ChannelGroup");
85
86 export const ChannelGroupProvider = () =>
87 Provider.effect(
88 ChannelGroup,
89 Effect.gen(function* () {
90 const createName = Effect.fn(function* (id: string, props: ChannelGroupProps) {
91 return props.channelGroupName ?? (yield* createPhysicalName({ id, maxLength: 256 }));
92 });
93
94 const toAttrs = (group: { ChannelGroupName: string; Arn: string; EgressDomain: string }) => ({
95 channelGroupName: group.ChannelGroupName,
96 channelGroupArn: group.Arn,
97 egressDomain: group.EgressDomain,
98 });
99
100 /** Get a channel group by name; typed not-found → undefined. */
101 const getGroup = Effect.fn(function* (channelGroupName: string) {
102 return yield* mediapackagev2
103 .getChannelGroup({ ChannelGroupName: channelGroupName })
104 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
105 });
106
107 return {
108 stables: ["channelGroupName", "channelGroupArn", "egressDomain"],
109
110 diff: Effect.fn(function* ({ id, olds, news }) {
111 if (!isResolved(news)) return undefined;
112 const oldName = yield* createName(id, olds);
113 const newName = yield* createName(id, news);
114 // The name is the group's identity; a change means a new group.
115 if (oldName !== newName) return { action: "replace" } as const;
116 }),
117
118 read: Effect.fn(function* ({ id, olds, output }) {
119 const name = output?.channelGroupName ?? (yield* createName(id, olds ?? {}));
120 const group = yield* getGroup(name);
121 if (group === undefined) return undefined;
122 const attrs = toAttrs(group);
123 return (yield* hasAlchemyTags(id, toMpTagRecord(group.Tags))) ? attrs : Unowned(attrs);
124 }),
125
126 reconcile: Effect.fn(function* ({ id, news, output, session }) {
127 const internalTags = yield* createInternalTags(id);
128 const desiredTags = { ...internalTags, ...news.tags };
129 const name = output?.channelGroupName ?? (yield* createName(id, news));
130
131 // 1. Observe — cloud state is authoritative; output is an id cache.
132 let group = yield* getGroup(name);
133
134 // 2. Ensure — create if missing; a Conflict means a peer created it
135 // concurrently, so fall through to observing the winner.
136 if (group === undefined) {
137 group = yield* mediapackagev2
138 .createChannelGroup({
139 ChannelGroupName: name,
140 Description: news.description,
141 Tags: desiredTags,
142 })
143 .pipe(
144 Effect.catchTag("ConflictException", () =>
145 mediapackagev2.getChannelGroup({ ChannelGroupName: name }),
146 ),
147 );
148 } else if ((news.description ?? "") !== (group.Description ?? "")) {
149 // 3. Sync — the description is the only mutable field.
150 group = yield* mediapackagev2.updateChannelGroup({
151 ChannelGroupName: name,
152 Description: news.description,
153 });
154 }
155
156 // 3b. Sync tags — diff against OBSERVED cloud tags.
157 yield* syncMpTags(group.Arn, toMpTagRecord(group.Tags), desiredTags);
158
159 yield* session.note(name);
160 return toAttrs(group);
161 }),
162
163 delete: Effect.fn(function* ({ output }) {
164 const channelGroupName = output.channelGroupName;
165 // Reap child channels (and their origin endpoints) first. A normal
166 // stack destroy deletes children before the group, so this observes
167 // nothing — but an orphan sweep can target a group whose children
168 // it never enumerated, and deleting the group would then Conflict
169 // until the retry budget ran out and leak the group.
170 const channels = yield* listGroupChannels(channelGroupName);
171 yield* Effect.forEach(
172 channels,
173 (channel) => deleteChannelWithEndpoints(channelGroupName, channel.ChannelName),
174 { concurrency: 5, discard: true },
175 );
176 // MediaPackage v2 deletes are idempotent (deleting a missing group
177 // succeeds), but the group transiently rejects deletion with a
178 // Conflict while its just-deleted channels are cleaned up.
179 yield* mediapackagev2
180 .deleteChannelGroup({ ChannelGroupName: channelGroupName })
181 .pipe(retryWhileMpConflict);
182 }),
183
184 list: () =>
185 Effect.gen(function* () {
186 const items = yield* mediapackagev2.listChannelGroups.pages({}).pipe(
187 Stream.runCollect,
188 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
189 );
190 // The list shape omits the egress domain, so hydrate each item
191 // via get; a group can vanish between enumeration and hydration.
192 const groups = yield* Effect.forEach(
193 items,
194 (item) =>
195 mediapackagev2.getChannelGroup({ ChannelGroupName: item.ChannelGroupName }).pipe(
196 Effect.map(toAttrs),
197 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
198 ),
199 { concurrency: 5 },
200 );
201 return groups.filter((g): g is ChannelGroup["Attributes"] => g !== undefined);
202 }),
203 };
204 }),
205 );