@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 320 lines 12 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 { toWireHours } 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 waitForStreamActive,
18 waitForStreamGone,
19 } from "./internal.ts";
20
21 export interface StreamProps {
22 /**
23 * Name of the video stream. Changing the name replaces the stream.
24 * Must be unique per account and region.
25 * @default a generated physical name
26 */
27 streamName?: string;
28 /**
29 * Name of the device that writes to the stream. Kinesis Video Streams
30 * does not currently use this name, but it is stored with the stream
31 * metadata and can be updated in place.
32 */
33 deviceName?: string;
34 /**
35 * Media type of the stream as a MIME type (e.g. `video/h264`). Consumers
36 * can use it to determine how to process the stream. Updated in place.
37 */
38 mediaType?: string;
39 /**
40 * The ID (or alias/ARN) of the KMS key used to encrypt stream data.
41 * Changing the key replaces the stream.
42 * @default the AWS-managed `aws/kinesisvideo` key
43 */
44 kmsKeyId?: string;
45 /**
46 * How long stream data is retained. Zero duration means no retention —
47 * data is only available live. Accepts any `Duration.Input` (e.g.
48 * `"24 hours"`, `Duration.hours(24)`; a bare number is milliseconds); the
49 * wire unit is whole hours. Adjusted in place via `UpdateDataRetention`.
50 * @default 0
51 */
52 dataRetention?: Duration.Input;
53 /**
54 * Tags to apply to the stream. Merged with internal Alchemy tags.
55 */
56 tags?: Record<string, string>;
57 }
58
59 export interface Stream extends Resource<
60 "AWS.KinesisVideo.Stream",
61 StreamProps,
62 {
63 streamName: string;
64 streamArn: string;
65 },
66 {},
67 Providers
68 > {}
69
70 /**
71 * An Amazon Kinesis Video Stream for ingesting, storing, and consuming
72 * live video.
73 *
74 * Stream creation is asynchronous — the provider waits (bounded) for the
75 * stream to become `ACTIVE` before returning. `deviceName` and `mediaType`
76 * are updated in place; `dataRetention` converges via `UpdateDataRetention`;
77 * changing `streamName` or `kmsKeyId` replaces the stream.
78 * ### Creating Streams
79 * **Example:** Basic Video Stream
80 * ```typescript
81 * import * as AWS from "@alchemy.run/aws";
82 *
83 * const stream = yield* AWS.KinesisVideo.Stream("Camera");
84 * ```
85 *
86 * **Example:** Stream with Retention and Media Type
87 * ```typescript
88 * const stream = yield* AWS.KinesisVideo.Stream("Camera", {
89 * mediaType: "video/h264",
90 * dataRetention: "24 hours",
91 * tags: { Environment: "production" },
92 * });
93 * ```
94 *
95 * ### Reading Media
96 * Bind data-plane read operations in the init phase and use them in
97 * runtime handlers. The bindings resolve the per-stream data endpoint
98 * (`GetDataEndpoint`) automatically.
99 *
100 * **Example:** HLS Playback URL
101 * ```typescript
102 * // init
103 * const getHls = yield* AWS.KinesisVideo.GetHLSStreamingSessionURL(stream);
104 *
105 * // runtime
106 * const { HLSStreamingSessionURL } = yield* getHls({ PlaybackMode: "LIVE" });
107 * ```
108 *
109 * **Example:** Raw Media
110 * ```typescript
111 * // init
112 * const getMedia = yield* AWS.KinesisVideo.GetMedia(stream);
113 *
114 * // runtime
115 * const media = yield* getMedia({
116 * StartSelector: { StartSelectorType: "EARLIEST" },
117 * });
118 * ```
119 *
120 * @resource
121 */
122 export const Stream = Resource<Stream>("AWS.KinesisVideo.Stream");
123
124 export const StreamProvider = () =>
125 Provider.effect(
126 Stream,
127 Effect.gen(function* () {
128 const createName = Effect.fn(function* (
129 id: string,
130 props: { streamName?: string | undefined },
131 ) {
132 return props.streamName ?? (yield* createPhysicalName({ id, maxLength: 256 }));
133 });
134
135 const observeStream = Effect.fn(function* (streamName: string) {
136 return yield* kv.describeStream({ StreamName: streamName }).pipe(
137 Effect.map((r) => r.StreamInfo),
138 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
139 );
140 });
141
142 const fetchObservedTags = Effect.fn(function* (streamArn: string) {
143 return yield* kv.listTagsForStream({ StreamARN: streamArn }).pipe(
144 Effect.map((r) => compactTags(r.Tags)),
145 Effect.catchTag("ResourceNotFoundException", () =>
146 Effect.succeed({} as Record<string, string>),
147 ),
148 );
149 });
150
151 return Stream.Provider.of({
152 stables: ["streamName", "streamArn"],
153
154 list: () =>
155 Effect.gen(function* () {
156 const pages = yield* kv.listStreams.pages({}).pipe(Stream_.runCollect);
157 return Array.from(pages)
158 .flatMap((page) => page.StreamInfoList ?? [])
159 .filter((info) => info.StreamName !== undefined && info.StreamARN !== undefined)
160 .map((info) => ({
161 streamName: info.StreamName!,
162 streamArn: info.StreamARN!,
163 }));
164 }),
165
166 read: Effect.fn(function* ({ id, olds, output }) {
167 const streamName = output?.streamName ?? (yield* createName(id, olds ?? {}));
168 const info = yield* observeStream(streamName);
169 if (info?.StreamARN === undefined || info.Status === "DELETING") {
170 return undefined;
171 }
172 const attrs = {
173 streamName,
174 streamArn: info.StreamARN,
175 };
176 const tags = yield* fetchObservedTags(info.StreamARN);
177 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
178 }),
179
180 diff: Effect.fn(function* ({ id, news, olds }) {
181 if (!isResolved(news)) return undefined;
182 const oldName = yield* createName(id, olds ?? {});
183 const newName = yield* createName(id, news ?? {});
184 if (oldName !== newName) {
185 return { action: "replace" } as const;
186 }
187 // The KMS key is bound at creation and cannot be changed in place.
188 if (olds?.kmsKeyId !== news?.kmsKeyId) {
189 return { action: "replace" } as const;
190 }
191 // deviceName/mediaType/dataRetention/tags fall through to
192 // the default update path (reconcile applies the deltas).
193 }),
194
195 reconcile: Effect.fn(function* ({ id, news, output, session }) {
196 // `news` is undefined when the resource is declared without props
197 // (`Stream("Id")`) — normalize WITHOUT a destructuring default
198 // (defaults widen the inferred Props type).
199 const props = news ?? {};
200 const streamName = output?.streamName ?? (yield* createName(id, props));
201 const internalTags = yield* createInternalTags(id);
202 const desiredTags = { ...props.tags, ...internalTags };
203 // Wire unit is whole hours (DataRetentionInHours).
204 const desiredRetention = toWireHours(props.dataRetention);
205
206 // 1. OBSERVE — cloud state is authoritative
207 let info = yield* observeStream(streamName);
208
209 // A previous incarnation still in DELETING blocks re-creation of
210 // the same name — wait for the purge to finish, then recreate.
211 if (info?.Status === "DELETING") {
212 yield* session.note(`waiting for previous stream ${streamName} to finish deleting...`);
213 yield* waitForStreamGone(streamName);
214 info = undefined;
215 }
216
217 // 2. ENSURE — create if missing; a `ResourceInUseException` means a
218 // peer created it concurrently (or a prior incarnation is still
219 // DELETING — retried inside the helper), so fall through to
220 // observation. Creation is async; wait for ACTIVE (bounded).
221 if (info === undefined) {
222 yield* retryWhileResourceInUse(
223 kv.createStream({
224 StreamName: streamName,
225 DeviceName: props.deviceName,
226 MediaType: props.mediaType,
227 KmsKeyId: props.kmsKeyId,
228 DataRetentionInHours: desiredRetention ?? 0,
229 Tags: desiredTags,
230 }),
231 ).pipe(
232 Effect.catchTag("ResourceInUseException", () =>
233 Effect.succeed({ StreamARN: undefined }),
234 ),
235 );
236 yield* session.note(`creating stream ${streamName}...`);
237 info = yield* waitForStreamActive(streamName);
238 } else if (info.Status !== "ACTIVE") {
239 // A CREATING/UPDATING stream rejects mutations — wait it out.
240 info = yield* waitForStreamActive(streamName);
241 }
242 const streamArn = info.StreamARN!;
243
244 // 3. SYNC — deviceName/mediaType (versioned update; only when the
245 // observed metadata differs from the desired state)
246 if (
247 (props.deviceName !== undefined && props.deviceName !== info.DeviceName) ||
248 (props.mediaType !== undefined && props.mediaType !== info.MediaType)
249 ) {
250 yield* retryWhileSettling(
251 kv.updateStream({
252 StreamARN: streamArn,
253 CurrentVersion: info.Version!,
254 DeviceName: props.deviceName,
255 MediaType: props.mediaType,
256 }),
257 );
258 // UpdateStream is async: it bumps the version and transitions
259 // through UPDATING. Wait for BOTH the version bump and ACTIVE so
260 // the next versioned mutation uses a fresh version.
261 info = yield* waitForStreamActive(streamName, info.Version);
262 }
263
264 // 3b. SYNC — data retention (delta-based API: INCREASE/DECREASE by
265 // the difference between observed and desired)
266 const observedRetention = info.DataRetentionInHours ?? 0;
267 if (desiredRetention !== undefined && desiredRetention !== observedRetention) {
268 yield* retryWhileSettling(
269 kv.updateDataRetention({
270 StreamARN: streamArn,
271 CurrentVersion: info.Version!,
272 Operation:
273 desiredRetention > observedRetention
274 ? "INCREASE_DATA_RETENTION"
275 : "DECREASE_DATA_RETENTION",
276 DataRetentionChangeInHours: Math.abs(desiredRetention - observedRetention),
277 }),
278 );
279 info = yield* waitForStreamActive(streamName, info.Version);
280 }
281
282 // 3c. SYNC TAGS — diff against OBSERVED cloud tags so adoption
283 // converges
284 const observedTags = yield* fetchObservedTags(streamArn);
285 const { upsert, removed } = diffTags(observedTags, desiredTags);
286 if (upsert.length > 0) {
287 yield* retryWhileSettling(
288 kv.tagStream({
289 StreamARN: streamArn,
290 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
291 }),
292 );
293 }
294 if (removed.length > 0) {
295 yield* retryWhileSettling(
296 kv.untagStream({
297 StreamARN: streamArn,
298 TagKeyList: removed,
299 }),
300 );
301 }
302
303 yield* session.note(streamArn);
304 return { streamName, streamArn };
305 }),
306
307 delete: Effect.fn(function* ({ output }) {
308 // A CREATING/UPDATING stream rejects deletion with
309 // ResourceInUseException — retry through the transition (bounded).
310 yield* retryWhileResourceInUse(kv.deleteStream({ StreamARN: output.streamArn })).pipe(
311 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
312 );
313 // DeleteStream is accepted immediately; the name stays reserved
314 // until the stream is fully purged. Wait it out so destroy (and
315 // the suite's out-of-band list) don't race a still-ACTIVE row.
316 yield* waitForStreamGone(output.streamName);
317 }),
318 });
319 }),
320 );