@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 267 lines 10 KB
Raw
1 import * as kv from "@distilled.cloud/aws/kinesis-video";
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, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import { toWireSeconds } from "alchemy/Util/Duration";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Stream_ from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import {
14 compactTags,
15 retryWhileResourceInUse,
16 retryWhileSettling,
17 waitForChannelActive,
18 waitForChannelGone,
19 } from "./internal.ts";
20
21 export interface SignalingChannelProps {
22 /**
23 * Name of the signaling channel. Changing the name replaces the channel.
24 * Must be unique per account and region.
25 * @default a generated physical name
26 */
27 channelName?: string;
28 /**
29 * The type of the channel. `SINGLE_MASTER` is the only fully supported
30 * type. Changing the type replaces the channel.
31 * @default "SINGLE_MASTER"
32 */
33 type?: "SINGLE_MASTER" | "FULL_MESH";
34 /**
35 * How long an undelivered signaling message is retained (5–120 seconds).
36 * Accepts any `Duration.Input` (e.g. `"30 seconds"`, `Duration.seconds(30)`;
37 * a bare number is milliseconds); the wire unit is whole seconds. Updated
38 * in place.
39 * @default 60 seconds
40 */
41 messageTtl?: Duration.Input;
42 /**
43 * Tags to apply to the channel. Merged with internal Alchemy tags.
44 */
45 tags?: Record<string, string>;
46 }
47
48 export interface SignalingChannel extends Resource<
49 "AWS.KinesisVideo.SignalingChannel",
50 SignalingChannelProps,
51 {
52 channelName: string;
53 channelArn: string;
54 },
55 {},
56 Providers
57 > {}
58
59 /**
60 * An Amazon Kinesis Video Streams WebRTC signaling channel — the rendezvous
61 * point that WebRTC master and viewer peers use to exchange SDP offers,
62 * answers, and ICE candidates.
63 *
64 * `messageTtl` is updated in place; changing `channelName` or `type`
65 * replaces the channel.
66 * ### Creating Channels
67 * **Example:** Basic Signaling Channel
68 * ```typescript
69 * import * as AWS from "@alchemy.run/aws";
70 *
71 * const channel = yield* AWS.KinesisVideo.SignalingChannel("Doorbell");
72 * ```
73 *
74 * **Example:** Channel with Message TTL
75 * ```typescript
76 * const channel = yield* AWS.KinesisVideo.SignalingChannel("Doorbell", {
77 * messageTtl: "30 seconds",
78 * tags: { Environment: "production" },
79 * });
80 * ```
81 *
82 * ### WebRTC Connectivity
83 * **Example:** ICE Server Configuration
84 * ```typescript
85 * // init
86 * const getIceServers = yield* AWS.KinesisVideo.GetIceServerConfig(channel);
87 *
88 * // runtime — TURN URIs + short-lived credentials for a WebRTC peer
89 * const { IceServerList } = yield* getIceServers({ ClientId: "viewer-1" });
90 * ```
91 *
92 * @resource
93 */
94 export const SignalingChannel = Resource<SignalingChannel>("AWS.KinesisVideo.SignalingChannel");
95
96 export const SignalingChannelProvider = () =>
97 Provider.effect(
98 SignalingChannel,
99 Effect.gen(function* () {
100 const createName = Effect.fn(function* (
101 id: string,
102 props: { channelName?: string | undefined },
103 ) {
104 return props.channelName ?? (yield* createPhysicalName({ id, maxLength: 256 }));
105 });
106
107 const observeChannel = Effect.fn(function* (channelName: string) {
108 return yield* kv.describeSignalingChannel({ ChannelName: channelName }).pipe(
109 Effect.map((r) => r.ChannelInfo),
110 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
111 );
112 });
113
114 const fetchObservedTags = Effect.fn(function* (channelArn: string) {
115 return yield* kv.listTagsForResource({ ResourceARN: channelArn }).pipe(
116 Effect.map((r) => compactTags(r.Tags)),
117 Effect.catchTag("ResourceNotFoundException", () =>
118 Effect.succeed({} as Record<string, string>),
119 ),
120 );
121 });
122
123 return SignalingChannel.Provider.of({
124 stables: ["channelName", "channelArn"],
125
126 list: () =>
127 Effect.gen(function* () {
128 const pages = yield* kv.listSignalingChannels.pages({}).pipe(Stream_.runCollect);
129 return Array.from(pages)
130 .flatMap((page) => page.ChannelInfoList ?? [])
131 .filter((info) => info.ChannelName !== undefined && info.ChannelARN !== undefined)
132 .map((info) => ({
133 channelName: info.ChannelName!,
134 channelArn: info.ChannelARN!,
135 }));
136 }),
137
138 read: Effect.fn(function* ({ id, olds, output }) {
139 const channelName = output?.channelName ?? (yield* createName(id, olds ?? {}));
140 const info = yield* observeChannel(channelName);
141 if (info?.ChannelARN === undefined || info.ChannelStatus === "DELETING") {
142 return undefined;
143 }
144 const attrs = {
145 channelName,
146 channelArn: info.ChannelARN,
147 };
148 const tags = yield* fetchObservedTags(info.ChannelARN);
149 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
150 }),
151
152 diff: Effect.fn(function* ({ id, news, olds }) {
153 if (!isResolved(news)) return undefined;
154 const oldName = yield* createName(id, olds ?? {});
155 const newName = yield* createName(id, news ?? {});
156 if (oldName !== newName) {
157 return { action: "replace" } as const;
158 }
159 // The channel type is bound at creation and cannot change in place.
160 const oldType = olds?.type ?? "SINGLE_MASTER";
161 const newType = news?.type ?? "SINGLE_MASTER";
162 if (oldType !== newType) {
163 return { action: "replace" } as const;
164 }
165 // messageTtl/tags fall through to the default update path.
166 }),
167
168 reconcile: Effect.fn(function* ({ id, news, output, session }) {
169 // `news` is undefined when the resource is declared without props
170 // (`SignalingChannel("Id")`) — normalize WITHOUT a destructuring
171 // default (defaults widen the inferred Props type).
172 const props = news ?? {};
173 const channelName = output?.channelName ?? (yield* createName(id, props));
174 const internalTags = yield* createInternalTags(id);
175 const desiredTags = { ...props.tags, ...internalTags };
176 // Wire unit is whole seconds (MessageTtlSeconds).
177 const desiredTtl = toWireSeconds(props.messageTtl);
178
179 // 1. OBSERVE
180 let info = yield* observeChannel(channelName);
181
182 // A previous incarnation still in DELETING blocks re-creation of
183 // the same name — wait for the purge to finish, then recreate.
184 if (info?.ChannelStatus === "DELETING") {
185 yield* session.note(
186 `waiting for previous channel ${channelName} to finish deleting...`,
187 );
188 yield* waitForChannelGone(channelName);
189 info = undefined;
190 }
191
192 // 2. ENSURE — create if missing; tolerate the concurrent-create
193 // race and wait for ACTIVE (creation is async but fast).
194 if (info === undefined) {
195 yield* retryWhileResourceInUse(
196 kv.createSignalingChannel({
197 ChannelName: channelName,
198 ChannelType: props.type ?? "SINGLE_MASTER",
199 SingleMasterConfiguration:
200 desiredTtl !== undefined ? { MessageTtlSeconds: desiredTtl } : undefined,
201 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
202 Key,
203 Value,
204 })),
205 }),
206 ).pipe(
207 Effect.catchTag("ResourceInUseException", () =>
208 Effect.succeed({ ChannelARN: undefined }),
209 ),
210 );
211 yield* session.note(`creating signaling channel ${channelName}...`);
212 info = yield* waitForChannelActive(channelName);
213 } else if (info.ChannelStatus !== "ACTIVE") {
214 info = yield* waitForChannelActive(channelName);
215 }
216 const channelArn = info.ChannelARN!;
217
218 // 3. SYNC — message TTL (versioned update; only on observed drift)
219 const observedTtl = info.SingleMasterConfiguration?.MessageTtlSeconds;
220 if (desiredTtl !== undefined && desiredTtl !== observedTtl) {
221 yield* retryWhileSettling(
222 kv.updateSignalingChannel({
223 ChannelARN: channelArn,
224 CurrentVersion: info.Version!,
225 SingleMasterConfiguration: { MessageTtlSeconds: desiredTtl },
226 }),
227 );
228 // UpdateSignalingChannel is async: wait for the version bump AND
229 // ACTIVE before any further versioned mutation.
230 info = yield* waitForChannelActive(channelName, info.Version);
231 }
232
233 // 3b. SYNC TAGS — diff against OBSERVED cloud tags
234 const observedTags = yield* fetchObservedTags(channelArn);
235 const { upsert, removed } = diffTags(observedTags, desiredTags);
236 if (upsert.length > 0) {
237 yield* retryWhileSettling(
238 kv.tagResource({
239 ResourceARN: channelArn,
240 Tags: upsert.map((t) => ({ Key: t.Key, Value: t.Value })),
241 }),
242 );
243 }
244 if (removed.length > 0) {
245 yield* retryWhileSettling(
246 kv.untagResource({
247 ResourceARN: channelArn,
248 TagKeyList: removed,
249 }),
250 );
251 }
252
253 yield* session.note(channelArn);
254 return { channelName, channelArn };
255 }),
256
257 delete: Effect.fn(function* ({ output }) {
258 // A CREATING/UPDATING channel rejects deletion with
259 // ResourceInUseException — retry through the transition (bounded).
260 yield* retryWhileResourceInUse(
261 kv.deleteSignalingChannel({ ChannelARN: output.channelArn }),
262 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
263 yield* waitForChannelGone(output.channelName);
264 }),
265 });
266 }),
267 );