@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, 07:15 UTC

main
ts 330 lines 12.5 KB
Raw
1 import * as IVSRealtime from "@alchemy.run/aws/IVSRealtime";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9 import * as Stream from "effect/Stream";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "handler.ts");
13
14 /** The user ID the fixture mints participant tokens for. */
15 export const TEST_USER_ID = "alchemy-test-user";
16
17 /**
18 * A well-formed participant id that does not exist — participant/session
19 * routes prove end-to-end wiring by observing the API's typed response.
20 */
21 const MISSING_PARTICIPANT_ID = "abcDEF123456";
22 /** A well-formed stage session id that does not exist. */
23 const MISSING_SESSION_ID = "st-0000AbCd0000";
24
25 export class IVSRealtimeTestFunction extends Lambda.Function<Lambda.Function>()(
26 "IVSRealtimeTestFunction",
27 ) {}
28
29 export default IVSRealtimeTestFunction.make(
30 {
31 main,
32 functionUrl: true,
33 timeout: Duration.seconds(30),
34 },
35 Effect.gen(function* () {
36 const stage = yield* IVSRealtime.Stage("BindingsStage", {
37 stageName: "alchemy-test-ivsrealtime-bindings",
38 tags: { fixture: "ivsrealtime-bindings" },
39 });
40 const overflowStage = yield* IVSRealtime.Stage("BindingsOverflowStage", {
41 stageName: "alchemy-test-ivsrealtime-bindings-b",
42 tags: { fixture: "ivsrealtime-bindings" },
43 });
44
45 // Event source: subscribe the host to IVS Real-Time stage updates and
46 // composition state changes. The deploy proves the EventBridge rule +
47 // invoke permission wiring.
48 yield* IVSRealtime.consumeStageEvents(
49 { kinds: ["stage-update", "composition-state-change"] },
50 (events) =>
51 Stream.runForEach(events, (event) =>
52 Effect.log(
53 `ivs stage event: ${event.detail.event_name} (${event.detail.participant_id})`,
54 ),
55 ),
56 );
57
58 const createParticipantToken = yield* IVSRealtime.CreateParticipantToken(stage);
59 const disconnectParticipant = yield* IVSRealtime.DisconnectParticipant(stage);
60 const getParticipant = yield* IVSRealtime.GetParticipant(stage);
61 const listParticipants = yield* IVSRealtime.ListParticipants(stage);
62 const listParticipantEvents = yield* IVSRealtime.ListParticipantEvents(stage);
63 const listParticipantReplicas = yield* IVSRealtime.ListParticipantReplicas(stage);
64 const getStageSession = yield* IVSRealtime.GetStageSession(stage);
65 const listStageSessions = yield* IVSRealtime.ListStageSessions(stage);
66 const startParticipantReplication = yield* IVSRealtime.StartParticipantReplication(
67 stage,
68 overflowStage,
69 );
70 const stopParticipantReplication = yield* IVSRealtime.StopParticipantReplication(
71 stage,
72 overflowStage,
73 );
74 const startComposition = yield* IVSRealtime.StartComposition(stage);
75 const stopComposition = yield* IVSRealtime.StopComposition();
76 const getComposition = yield* IVSRealtime.GetComposition();
77 const listCompositions = yield* IVSRealtime.ListCompositions();
78
79 const bound = {
80 createParticipantToken,
81 disconnectParticipant,
82 getParticipant,
83 listParticipants,
84 listParticipantEvents,
85 listParticipantReplicas,
86 getStageSession,
87 listStageSessions,
88 startParticipantReplication,
89 stopParticipantReplication,
90 startComposition,
91 stopComposition,
92 getComposition,
93 listCompositions,
94 };
95
96 return {
97 fetch: Effect.gen(function* () {
98 const request = yield* HttpServerRequest;
99 const url = new URL(request.originalUrl);
100 const pathname = url.pathname;
101
102 // Cheap readiness route — no AWS call.
103 if (request.method === "GET" && pathname === "/ping") {
104 return yield* HttpServerResponse.json({ ok: true });
105 }
106
107 if (request.method === "GET" && pathname === "/bindings") {
108 return yield* HttpServerResponse.json({ bound: Object.keys(bound) });
109 }
110
111 if (request.method === "POST" && pathname === "/token") {
112 const { participantToken } = yield* createParticipantToken({
113 userId: TEST_USER_ID,
114 capabilities: ["PUBLISH", "SUBSCRIBE"],
115 // Exercises the Duration.Input -> wire minutes conversion.
116 duration: "30 minutes",
117 attributes: { displayName: "Alchemy" },
118 });
119 // The token is sensitive — assert on its shape, never echo it.
120 const token = participantToken?.token;
121 const tokenLength =
122 token === undefined
123 ? 0
124 : Redacted.isRedacted(token)
125 ? Redacted.value(token).length
126 : token.length;
127 return yield* HttpServerResponse.json({
128 tokenLength,
129 tokenIsRedacted: token !== undefined && Redacted.isRedacted(token),
130 participantId: participantToken?.participantId,
131 duration: participantToken?.duration,
132 expirationTime: participantToken?.expirationTime,
133 });
134 }
135
136 if (request.method === "POST" && pathname === "/disconnect") {
137 const result = yield* disconnectParticipant({
138 participantId: MISSING_PARTICIPANT_ID,
139 reason: "alchemy test",
140 }).pipe(
141 Effect.map(() => ({ ok: true })),
142 Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) =>
143 Effect.succeed({ tag: e._tag }),
144 ),
145 );
146 return yield* HttpServerResponse.json(result);
147 }
148
149 if (request.method === "GET" && pathname === "/sessions") {
150 const { stageSessions } = yield* listStageSessions();
151 return yield* HttpServerResponse.json({
152 count: stageSessions.length,
153 });
154 }
155
156 if (request.method === "GET" && pathname === "/session-missing") {
157 const result = yield* getStageSession({
158 sessionId: MISSING_SESSION_ID,
159 }).pipe(
160 Effect.map(() => ({ found: true })),
161 Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) =>
162 Effect.succeed({ tag: e._tag }),
163 ),
164 );
165 return yield* HttpServerResponse.json(result);
166 }
167
168 if (request.method === "GET" && pathname === "/participants") {
169 const result = yield* listParticipants({
170 sessionId: MISSING_SESSION_ID,
171 }).pipe(
172 Effect.map((r) => ({ count: r.participants.length })),
173 Effect.catchTag("ValidationException", (e) => Effect.succeed({ tag: e._tag })),
174 );
175 return yield* HttpServerResponse.json(result);
176 }
177
178 if (request.method === "GET" && pathname === "/participant-missing") {
179 const result = yield* getParticipant({
180 sessionId: MISSING_SESSION_ID,
181 participantId: MISSING_PARTICIPANT_ID,
182 }).pipe(
183 Effect.map(() => ({ found: true })),
184 Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) =>
185 Effect.succeed({ tag: e._tag }),
186 ),
187 );
188 return yield* HttpServerResponse.json(result);
189 }
190
191 if (request.method === "GET" && pathname === "/participant-events") {
192 const result = yield* listParticipantEvents({
193 sessionId: MISSING_SESSION_ID,
194 participantId: MISSING_PARTICIPANT_ID,
195 }).pipe(
196 Effect.map((r) => ({ count: r.events.length })),
197 Effect.catchTag("ValidationException", (e) => Effect.succeed({ tag: e._tag })),
198 );
199 return yield* HttpServerResponse.json(result);
200 }
201
202 if (request.method === "GET" && pathname === "/replicas") {
203 const result = yield* listParticipantReplicas({
204 participantId: MISSING_PARTICIPANT_ID,
205 }).pipe(
206 Effect.map((r) => ({ count: r.replicas.length })),
207 Effect.catchTag("ValidationException", (e) => Effect.succeed({ tag: e._tag })),
208 );
209 return yield* HttpServerResponse.json(result);
210 }
211
212 if (request.method === "POST" && pathname === "/replication-start") {
213 const result = yield* startParticipantReplication({
214 participantId: MISSING_PARTICIPANT_ID,
215 reconnectWindow: "30 seconds",
216 }).pipe(
217 Effect.map(() => ({ ok: true })),
218 Effect.catchTag(
219 [
220 "ResourceNotFoundException",
221 "ValidationException",
222 "ConflictException",
223 "PendingVerification",
224 "ServiceQuotaExceededException",
225 ],
226 (e) => Effect.succeed({ tag: e._tag }),
227 ),
228 );
229 return yield* HttpServerResponse.json(result);
230 }
231
232 if (request.method === "POST" && pathname === "/replication-stop") {
233 const result = yield* stopParticipantReplication({
234 participantId: MISSING_PARTICIPANT_ID,
235 }).pipe(
236 Effect.map(() => ({ ok: true })),
237 Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) =>
238 Effect.succeed({ tag: e._tag }),
239 ),
240 );
241 return yield* HttpServerResponse.json(result);
242 }
243
244 if (request.method === "GET" && pathname === "/compositions") {
245 const { compositions } = yield* listCompositions();
246 return yield* HttpServerResponse.json({
247 count: compositions.length,
248 });
249 }
250
251 // Composition routes take a well-formed-but-nonexistent ARN from the
252 // test (the test knows the region/account) and prove wiring by
253 // observing the API's typed response.
254 if (request.method === "GET" && pathname === "/composition-missing") {
255 const arn = url.searchParams.get("arn")!;
256 const result = yield* getComposition({ arn }).pipe(
257 Effect.map(() => ({ found: true })),
258 Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) =>
259 Effect.succeed({ tag: e._tag }),
260 ),
261 );
262 return yield* HttpServerResponse.json(result);
263 }
264
265 if (request.method === "POST" && pathname === "/composition-stop") {
266 const arn = url.searchParams.get("arn")!;
267 const result = yield* stopComposition({ arn }).pipe(
268 Effect.map(() => ({ ok: true })),
269 Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) =>
270 Effect.succeed({ tag: e._tag }),
271 ),
272 );
273 return yield* HttpServerResponse.json(result);
274 }
275
276 if (request.method === "POST" && pathname === "/composition-start") {
277 const storageConfigurationArn = url.searchParams.get("arn")!;
278 const result = yield* startComposition({
279 destinations: [
280 {
281 s3: {
282 storageConfigurationArn,
283 encoderConfigurationArns: [],
284 },
285 },
286 ],
287 }).pipe(
288 Effect.map((r) => ({ ok: true, arn: r.composition?.arn })),
289 Effect.catchTag(
290 [
291 "ResourceNotFoundException",
292 "ValidationException",
293 "ConflictException",
294 "PendingVerification",
295 "ServiceQuotaExceededException",
296 ],
297 (e) => Effect.succeed({ tag: e._tag }),
298 ),
299 );
300 return yield* HttpServerResponse.json(result);
301 }
302
303 return yield* HttpServerResponse.json(
304 { error: "Not found", method: request.method, pathname },
305 { status: 404 },
306 );
307 }).pipe(Effect.orDie),
308 };
309 }).pipe(
310 Effect.provide(
311 Layer.mergeAll(
312 Lambda.EventSource,
313 IVSRealtime.CreateParticipantTokenHttp,
314 IVSRealtime.DisconnectParticipantHttp,
315 IVSRealtime.GetParticipantHttp,
316 IVSRealtime.ListParticipantsHttp,
317 IVSRealtime.ListParticipantEventsHttp,
318 IVSRealtime.ListParticipantReplicasHttp,
319 IVSRealtime.GetStageSessionHttp,
320 IVSRealtime.ListStageSessionsHttp,
321 IVSRealtime.StartParticipantReplicationHttp,
322 IVSRealtime.StopParticipantReplicationHttp,
323 IVSRealtime.StartCompositionHttp,
324 IVSRealtime.StopCompositionHttp,
325 IVSRealtime.GetCompositionHttp,
326 IVSRealtime.ListCompositionsHttp,
327 ),
328 ),
329 ),
330 );