@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 259 lines 8.8 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as MediaLive from "@alchemy.run/aws/MediaLive";
4 import type * as medialive from "@distilled.cloud/aws/medialive";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "channel-handler.ts");
12
13 // A minimal single-pipeline UDP encoder config — the cheapest valid
14 // encoder settings. The channel is provisioned IDLE and never started.
15 const ENCODER_SETTINGS: medialive.EncoderSettings = {
16 TimecodeConfig: { Source: "EMBEDDED" },
17 AudioDescriptions: [
18 {
19 Name: "audio_1",
20 AudioSelectorName: "default",
21 CodecSettings: {
22 AacSettings: { Bitrate: 96000, SampleRate: 48000 },
23 },
24 },
25 ],
26 VideoDescriptions: [
27 {
28 Name: "video_1",
29 Width: 640,
30 Height: 360,
31 CodecSettings: {
32 H264Settings: {
33 Bitrate: 1000000,
34 FramerateControl: "SPECIFIED",
35 FramerateNumerator: 30,
36 FramerateDenominator: 1,
37 GopSize: 60,
38 },
39 },
40 },
41 ],
42 OutputGroups: [
43 {
44 Name: "udp",
45 OutputGroupSettings: { UdpGroupSettings: {} },
46 Outputs: [
47 {
48 OutputName: "output_1",
49 VideoDescriptionName: "video_1",
50 AudioDescriptionNames: ["audio_1"],
51 OutputSettings: {
52 UdpOutputSettings: {
53 Destination: { DestinationRefId: "dest1" },
54 ContainerSettings: { M2tsSettings: {} },
55 },
56 },
57 },
58 ],
59 },
60 ],
61 };
62
63 export class MediaLiveChannelTestFunction extends Lambda.Function<Lambda.Function>()(
64 "MediaLiveChannelTestFunction",
65 ) {}
66
67 export default MediaLiveChannelTestFunction.make(
68 {
69 main,
70 functionUrl: true,
71 },
72 Effect.gen(function* () {
73 const role = yield* IAM.Role("ChannelBindingRole", {
74 assumeRolePolicyDocument: {
75 Version: "2012-10-17",
76 Statement: [
77 {
78 Effect: "Allow",
79 Principal: { Service: "medialive.amazonaws.com" },
80 Action: ["sts:AssumeRole"],
81 },
82 ],
83 },
84 });
85 const input = yield* MediaLive.Input("ChannelBindingInput", {
86 type: "URL_PULL",
87 sources: [{ Url: "https://example.com/stream/index.m3u8" }],
88 });
89 // The channel the channel-scoped bindings are bound to. It is created
90 // IDLE (which does not bill — only RUNNING channels do) and nothing
91 // ever starts it, so the observability ops see the typed not-running
92 // behavior.
93 const channel = yield* MediaLive.Channel("BindingChannel", {
94 channelClass: "SINGLE_PIPELINE",
95 roleArn: role.roleArn,
96 inputAttachments: [
97 {
98 InputId: input.inputId,
99 InputAttachmentName: "primary",
100 InputSettings: { AudioSelectors: [{ Name: "default" }] },
101 },
102 ],
103 inputSpecification: {
104 Codec: "AVC",
105 Resolution: "SD",
106 MaximumBitrate: "MAX_10_MBPS",
107 },
108 destinations: [{ Id: "dest1", Settings: [{ Url: "udp://10.220.171.28:5000" }] }],
109 encoderSettings: ENCODER_SETTINGS,
110 tags: { fixture: "medialive-channel-bindings" },
111 });
112
113 const describeChannel = yield* MediaLive.DescribeChannel(channel);
114 const describeSchedule = yield* MediaLive.DescribeSchedule(channel);
115 const updateSchedule = yield* MediaLive.BatchUpdateSchedule(channel);
116 const deleteSchedule = yield* MediaLive.DeleteSchedule(channel);
117 const listAlerts = yield* MediaLive.ListAlerts(channel);
118 const describeThumbnails = yield* MediaLive.DescribeThumbnails(channel);
119 const startChannel = yield* MediaLive.StartChannel(channel);
120 const stopChannel = yield* MediaLive.StopChannel(channel);
121 const restartPipelines = yield* MediaLive.RestartChannelPipelines(channel);
122
123 // startChannel / stopChannel / restartPipelines are bound (their IAM
124 // grants are attached and their init proved) but never driven — a
125 // RUNNING channel bills by the hour.
126 const bound = {
127 describeChannel,
128 describeSchedule,
129 updateSchedule,
130 deleteSchedule,
131 listAlerts,
132 describeThumbnails,
133 startChannel,
134 stopChannel,
135 restartPipelines,
136 };
137
138 return {
139 fetch: Effect.gen(function* () {
140 const request = yield* HttpServerRequest;
141 const url = new URL(request.originalUrl);
142 const pathname = url.pathname;
143
144 if (request.method === "GET" && pathname === "/bindings") {
145 return yield* HttpServerResponse.json({
146 bound: Object.keys(bound),
147 });
148 }
149
150 // Read the channel's live state — the fixture channel idles IDLE.
151 if (request.method === "GET" && pathname === "/channel") {
152 const current = yield* describeChannel();
153 return yield* HttpServerResponse.json({
154 state: current.State,
155 channelClass: current.ChannelClass,
156 pipelinesRunning: current.PipelinesRunningCount,
157 });
158 }
159
160 // The schedule of a freshly-created channel is empty.
161 if (request.method === "GET" && pathname === "/schedule") {
162 const { ScheduleActions } = yield* describeSchedule();
163 return yield* HttpServerResponse.json({
164 actions: (ScheduleActions ?? []).length,
165 });
166 }
167
168 // Program a fixed-time input switch far in the future, observe it
169 // in the schedule, then clear the schedule — a full
170 // BatchUpdateSchedule/DescribeSchedule/DeleteSchedule roundtrip on
171 // an IDLE channel.
172 if (request.method === "POST" && pathname === "/schedule-cycle") {
173 const startTime = yield* Effect.sync(() =>
174 new Date(Date.now() + 3_600_000).toISOString(),
175 );
176 const result = yield* updateSchedule({
177 Creates: {
178 ScheduleActions: [
179 {
180 ActionName: "alchemy-binding-test",
181 ScheduleActionStartSettings: {
182 FixedModeScheduleActionStartSettings: { Time: startTime },
183 },
184 ScheduleActionSettings: {
185 InputSwitchSettings: {
186 InputAttachmentNameReference: "primary",
187 },
188 },
189 },
190 ],
191 },
192 }).pipe(
193 Effect.flatMap(() => describeSchedule()),
194 Effect.flatMap(({ ScheduleActions }) =>
195 deleteSchedule().pipe(
196 Effect.map(() => ({
197 created: (ScheduleActions ?? []).length,
198 cleared: true,
199 tag: undefined as string | undefined,
200 })),
201 ),
202 ),
203 Effect.catchTag(["BadRequestException", "UnprocessableEntityException"], (e) =>
204 Effect.succeed({
205 created: 0,
206 cleared: false,
207 tag: e._tag as string | undefined,
208 }),
209 ),
210 );
211 return yield* HttpServerResponse.json(result);
212 }
213
214 // A channel that has never run has no (or only informational)
215 // alerts; the call itself must succeed.
216 if (request.method === "GET" && pathname === "/alerts") {
217 const { Alerts } = yield* listAlerts();
218 return yield* HttpServerResponse.json({
219 alerts: (Alerts ?? []).length,
220 });
221 }
222
223 // Thumbnails on an IDLE channel: either empty details or the typed
224 // BadRequestException (thumbnails require a running channel).
225 if (request.method === "GET" && pathname === "/thumbnails") {
226 const result = yield* describeThumbnails({ PipelineId: "0" }).pipe(
227 Effect.map(({ ThumbnailDetails }) => ({
228 details: (ThumbnailDetails ?? []).length,
229 tag: undefined as string | undefined,
230 })),
231 Effect.catchTag("BadRequestException", (e) =>
232 Effect.succeed({ details: 0, tag: e._tag as string | undefined }),
233 ),
234 );
235 return yield* HttpServerResponse.json(result);
236 }
237
238 return yield* HttpServerResponse.json(
239 { error: "Not found", method: request.method, pathname },
240 { status: 404 },
241 );
242 }).pipe(Effect.orDie),
243 };
244 }).pipe(
245 Effect.provide(
246 Layer.mergeAll(
247 MediaLive.DescribeChannelHttp,
248 MediaLive.DescribeScheduleHttp,
249 MediaLive.BatchUpdateScheduleHttp,
250 MediaLive.DeleteScheduleHttp,
251 MediaLive.ListAlertsHttp,
252 MediaLive.DescribeThumbnailsHttp,
253 MediaLive.StartChannelHttp,
254 MediaLive.StopChannelHttp,
255 MediaLive.RestartChannelPipelinesHttp,
256 ),
257 ),
258 ),
259 );