@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 297 lines 11.6 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Duration from "effect/Duration";
3 import * as Effect from "effect/Effect";
4 import { HttpServerRequest } from "effect/http/HttpServerRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import * as Layer from "effect/Layer";
7 import * as Option from "effect/Option";
8 import * as Result from "effect/Result";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 const failureJson = (failure: { readonly _tag: string }) => ({
14 errorTag: failure._tag,
15 errorMessage:
16 "message" in failure && typeof failure.message === "string" ? failure.message : undefined,
17 });
18
19 export class KinesisVideoTestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
20 "KinesisVideoTestFunction",
21 ) {}
22
23 export default KinesisVideoTestFunction.make(
24 {
25 main,
26 functionUrl: true,
27 // every route fans out to GetDataEndpoint/GetSignalingChannelEndpoint
28 // plus the data-plane call; the 3s default is too tight
29 timeout: Duration.seconds(30),
30 },
31 Effect.gen(function* () {
32 const stream = yield* AWS.KinesisVideo.Stream("FixtureStream", {
33 mediaType: "video/h264",
34 dataRetention: "24 hours",
35 });
36 const channel = yield* AWS.KinesisVideo.SignalingChannel("FixtureChannel");
37
38 const getHls = yield* AWS.KinesisVideo.GetHLSStreamingSessionURL(stream);
39 const getDash = yield* AWS.KinesisVideo.GetDASHStreamingSessionURL(stream);
40 const getClip = yield* AWS.KinesisVideo.GetClip(stream);
41 const getImages = yield* AWS.KinesisVideo.GetImages(stream);
42 const listFragments = yield* AWS.KinesisVideo.ListFragments(stream);
43 const getFragmentMedia = yield* AWS.KinesisVideo.GetMediaForFragmentList(stream);
44 const getIceServers = yield* AWS.KinesisVideo.GetIceServerConfig(channel);
45 const getMedia = yield* AWS.KinesisVideo.GetMedia(stream);
46 const joinStorage = yield* AWS.KinesisVideo.JoinStorageSession(channel);
47 const joinStorageAsViewer = yield* AWS.KinesisVideo.JoinStorageSessionAsViewer(channel);
48 const sendAlexaOffer = yield* AWS.KinesisVideo.SendAlexaOfferToMaster(channel);
49
50 return {
51 fetch: Effect.gen(function* () {
52 const request = yield* HttpServerRequest;
53 const pathname = new URL(request.originalUrl).pathname;
54
55 if (request.method === "GET" && pathname === "/info") {
56 return yield* HttpServerResponse.json({ ok: true });
57 }
58
59 if (request.method === "GET" && pathname === "/hls") {
60 // The fixture stream has no ingested media, so LIVE playback
61 // deterministically fails with a typed error from the archived
62 // media data plane — reaching it at all proves endpoint discovery,
63 // IAM, and the signed call.
64 const result = yield* Effect.result(getHls({ PlaybackMode: "LIVE" }));
65 if (Result.isSuccess(result)) {
66 return yield* HttpServerResponse.json({
67 url: result.success.HLSStreamingSessionURL,
68 });
69 }
70 return yield* HttpServerResponse.json(failureJson(result.failure));
71 }
72
73 if (request.method === "GET" && pathname === "/dash") {
74 // Same shape as /hls — the empty stream deterministically returns
75 // the archived-media data plane's typed no-fragments error.
76 const result = yield* Effect.result(getDash({ PlaybackMode: "LIVE" }));
77 if (Result.isSuccess(result)) {
78 return yield* HttpServerResponse.json({
79 url: result.success.DASHStreamingSessionURL,
80 });
81 }
82 return yield* HttpServerResponse.json({
83 ...failureJson(result.failure),
84 });
85 }
86
87 if (request.method === "GET" && pathname === "/fragments") {
88 // ListFragments on an empty (but retained) stream succeeds with an
89 // empty page — a full data-plane round-trip. A FragmentSelector is
90 // required whenever no NextToken is passed.
91 const now = yield* Effect.sync(() => Date.now());
92 const result = yield* Effect.result(
93 listFragments({
94 FragmentSelector: {
95 FragmentSelectorType: "SERVER_TIMESTAMP",
96 TimestampRange: {
97 StartTimestamp: new Date(now - 60_000),
98 EndTimestamp: new Date(now),
99 },
100 },
101 }),
102 );
103 if (Result.isSuccess(result)) {
104 return yield* HttpServerResponse.json({
105 ok: true,
106 count: (result.success.Fragments ?? []).length,
107 });
108 }
109 return yield* HttpServerResponse.json({
110 ok: false,
111 ...failureJson(result.failure),
112 });
113 }
114
115 if (request.method === "GET" && pathname === "/clip") {
116 const now = yield* Effect.sync(() => Date.now());
117 const result = yield* Effect.result(
118 getClip({
119 ClipFragmentSelector: {
120 FragmentSelectorType: "SERVER_TIMESTAMP",
121 TimestampRange: {
122 StartTimestamp: new Date(now - 60_000),
123 EndTimestamp: new Date(now),
124 },
125 },
126 }),
127 );
128 if (Result.isSuccess(result)) {
129 return yield* HttpServerResponse.json({
130 ok: true,
131 contentType: result.success.ContentType,
132 });
133 }
134 return yield* HttpServerResponse.json({
135 ok: false,
136 ...failureJson(result.failure),
137 });
138 }
139
140 if (request.method === "GET" && pathname === "/images") {
141 const now = yield* Effect.sync(() => Date.now());
142 const result = yield* Effect.result(
143 getImages({
144 ImageSelectorType: "SERVER_TIMESTAMP",
145 StartTimestamp: new Date(now - 60_000),
146 EndTimestamp: new Date(now),
147 SamplingInterval: 3000,
148 Format: "JPEG",
149 }),
150 );
151 if (Result.isSuccess(result)) {
152 return yield* HttpServerResponse.json({
153 ok: true,
154 count: (result.success.Images ?? []).length,
155 });
156 }
157 return yield* HttpServerResponse.json({
158 ok: false,
159 ...failureJson(result.failure),
160 });
161 }
162
163 if (request.method === "GET" && pathname === "/fragment-media") {
164 // A syntactically-valid but nonexistent fragment number — the
165 // empty stream deterministically returns the typed no-fragment
166 // error, proving the signed data-plane call.
167 const result = yield* Effect.result(
168 getFragmentMedia({
169 Fragments: ["91343852333181432392682062607743920994"],
170 }),
171 );
172 if (Result.isSuccess(result)) {
173 return yield* HttpServerResponse.json({
174 ok: true,
175 contentType: result.success.ContentType,
176 });
177 }
178 return yield* HttpServerResponse.json({
179 ok: false,
180 ...failureJson(result.failure),
181 });
182 }
183
184 if (request.method === "GET" && pathname === "/join-storage") {
185 // The fixture channel has no media storage configured, so the
186 // WEBRTC endpoint discovery (or the join call itself) fails with a
187 // typed error — reaching it proves IAM + endpoint resolution.
188 const result = yield* Effect.result(joinStorage());
189 return yield* HttpServerResponse.json(
190 Result.isSuccess(result) ? { ok: true } : { ok: false, ...failureJson(result.failure) },
191 );
192 }
193
194 if (request.method === "GET" && pathname === "/join-storage-viewer") {
195 const result = yield* Effect.result(
196 joinStorageAsViewer({ clientId: "alchemy-test-viewer" }),
197 );
198 return yield* HttpServerResponse.json(
199 Result.isSuccess(result) ? { ok: true } : { ok: false, ...failureJson(result.failure) },
200 );
201 }
202
203 if (request.method === "GET" && pathname === "/alexa-offer") {
204 // No master peer is connected to the fixture channel, so the
205 // service either rejects the junk SDP payload with a typed
206 // InvalidArgumentException or holds the offer for redelivery until
207 // our bounded timeout — both prove endpoint discovery, IAM, and
208 // the signed signaling call.
209 const result = yield* Effect.result(
210 sendAlexaOffer({
211 SenderClientId: "alchemy-test-alexa",
212 // base64("v=0") — a minimal, syntactically-plausible SDP stub
213 MessagePayload: "dj0w",
214 }).pipe(Effect.timeoutOption("5 seconds")),
215 );
216 if (Result.isSuccess(result)) {
217 return yield* HttpServerResponse.json(
218 Option.isNone(result.success)
219 ? { ok: true, timedOut: true }
220 : {
221 ok: true,
222 answered: result.success.value.Answer !== undefined,
223 },
224 );
225 }
226 return yield* HttpServerResponse.json({
227 ok: false,
228 ...failureJson(result.failure),
229 });
230 }
231
232 if (request.method === "GET" && pathname === "/ice") {
233 const result = yield* Effect.result(getIceServers({ ClientId: "alchemy-test" }));
234 if (Result.isFailure(result)) {
235 return yield* HttpServerResponse.json({
236 ok: false,
237 ...failureJson(result.failure),
238 });
239 }
240 return yield* HttpServerResponse.json({
241 servers: (result.success.IceServerList ?? []).map((server) => ({
242 uris: server.Uris ?? [],
243 hasCredentials: server.Username !== undefined && server.Password !== undefined,
244 ttl: server.Ttl,
245 })),
246 });
247 }
248
249 if (request.method === "GET" && pathname === "/media") {
250 // The empty stream never produces fragments; the connection to the
251 // per-stream media endpoint either opens (headers arrive) or idles
252 // until the bounded timeout. Both prove the data-plane call was
253 // accepted — auth/endpoint failures surface as typed errors.
254 const result = yield* Effect.result(
255 getMedia({
256 StartSelector: { StartSelectorType: "EARLIEST" },
257 }).pipe(Effect.timeoutOption("5 seconds")),
258 );
259 if (Result.isSuccess(result)) {
260 if (Option.isNone(result.success)) {
261 return yield* HttpServerResponse.json({
262 ok: true,
263 timedOut: true,
264 });
265 }
266 return yield* HttpServerResponse.json({
267 ok: true,
268 contentType: result.success.value.ContentType,
269 });
270 }
271 return yield* HttpServerResponse.json({
272 ok: false,
273 ...failureJson(result.failure),
274 });
275 }
276
277 return yield* HttpServerResponse.json({ error: "Not found" }, { status: 404 });
278 }).pipe(Effect.orDie),
279 };
280 }).pipe(
281 Effect.provide(
282 Layer.mergeAll(
283 AWS.KinesisVideo.GetHLSStreamingSessionURLHttp,
284 AWS.KinesisVideo.GetDASHStreamingSessionURLHttp,
285 AWS.KinesisVideo.GetClipHttp,
286 AWS.KinesisVideo.GetImagesHttp,
287 AWS.KinesisVideo.ListFragmentsHttp,
288 AWS.KinesisVideo.GetMediaForFragmentListHttp,
289 AWS.KinesisVideo.GetIceServerConfigHttp,
290 AWS.KinesisVideo.SendAlexaOfferToMasterHttp,
291 AWS.KinesisVideo.GetMediaHttp,
292 AWS.KinesisVideo.JoinStorageSessionHttp,
293 AWS.KinesisVideo.JoinStorageSessionAsViewerHttp,
294 ),
295 ),
296 ),
297 );