@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 229 lines 8.4 KB
Raw
1 import * as IVS from "@alchemy.run/aws/IVS";
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 Stream from "effect/Stream";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 export class IvsTestFunction extends Lambda.Function<Lambda.Function>()("IvsTestFunction") {}
14
15 export default IvsTestFunction.make(
16 {
17 main,
18 functionUrl: true,
19 timeout: Duration.seconds(30),
20 },
21 Effect.gen(function* () {
22 // The channel the channel-scoped bindings are bound to. Nothing ever
23 // broadcasts to it, so the data-plane ops observe the typed
24 // ChannelNotBroadcasting behavior.
25 const channel = yield* IVS.Channel("BindingChannel", {
26 type: "BASIC",
27 latencyMode: "NORMAL",
28 tags: { fixture: "ivs-bindings" },
29 });
30
31 // Event source: subscribe the host to IVS stream state-change events.
32 // The deploy proves the EventBridge rule + invoke permission wiring.
33 yield* IVS.consumeStreamEvents(
34 { kinds: ["stream-state-change", "recording-state-change"] },
35 (events) =>
36 Stream.runForEach(events, (event) =>
37 Effect.log(`ivs event: ${event.detail.channel_name} ${event.detail.event_name}`),
38 ),
39 );
40
41 // Accessor for the channel's ARN, resolvable inside the runtime fetch
42 // handler (the batch revocation request shape carries explicit
43 // channel ARNs rather than binding to a single channel).
44 const ChannelArn = yield* channel.channelArn;
45
46 const getStream = yield* IVS.GetStream(channel);
47 const getStreamSession = yield* IVS.GetStreamSession(channel);
48 const listStreamSessions = yield* IVS.ListStreamSessions(channel);
49 const putMetadata = yield* IVS.PutMetadata(channel);
50 const stopStream = yield* IVS.StopStream(channel);
51 const revokeViewerSession = yield* IVS.StartViewerSessionRevocation(channel);
52 const insertAdBreak = yield* IVS.InsertAdBreak(channel);
53 const listStreams = yield* IVS.ListStreams();
54 const batchRevokeViewerSessions = yield* IVS.BatchStartViewerSessionRevocation();
55
56 const bound = {
57 getStream,
58 getStreamSession,
59 listStreamSessions,
60 putMetadata,
61 stopStream,
62 revokeViewerSession,
63 insertAdBreak,
64 listStreams,
65 batchRevokeViewerSessions,
66 };
67
68 return {
69 fetch: Effect.gen(function* () {
70 const request = yield* HttpServerRequest;
71 const url = new URL(request.originalUrl);
72 const pathname = url.pathname;
73
74 if (request.method === "GET" && pathname === "/bindings") {
75 return yield* HttpServerResponse.json({
76 bound: Object.keys(bound),
77 });
78 }
79
80 // Live-stream read on an idle channel: the typed
81 // ChannelNotBroadcasting tag is the real observable behavior.
82 if (request.method === "GET" && pathname === "/stream") {
83 const result = yield* getStream().pipe(
84 Effect.map(({ stream }) => ({
85 live: true,
86 viewers: stream?.viewerCount ?? 0,
87 })),
88 Effect.catchTag("ChannelNotBroadcasting", () =>
89 Effect.succeed({ live: false, viewers: 0 }),
90 ),
91 );
92 return yield* HttpServerResponse.json(result);
93 }
94
95 // Latest session on a channel that never broadcast: typed
96 // not-found.
97 if (request.method === "GET" && pathname === "/session") {
98 const result = yield* getStreamSession({}).pipe(
99 Effect.map(({ streamSession }) => ({
100 found: true,
101 streamId: streamSession?.streamId,
102 })),
103 Effect.catchTag("ResourceNotFoundException", () =>
104 Effect.succeed({ found: false, streamId: undefined }),
105 ),
106 );
107 return yield* HttpServerResponse.json(result);
108 }
109
110 // Channel-scoped session history (empty for the idle fixture).
111 if (request.method === "GET" && pathname === "/sessions") {
112 const { streamSessions } = yield* listStreamSessions({
113 maxResults: 10,
114 });
115 return yield* HttpServerResponse.json({
116 count: streamSessions.length,
117 });
118 }
119
120 // Account-level live-stream enumeration.
121 if (request.method === "GET" && pathname === "/streams") {
122 const { streams } = yield* listStreams();
123 return yield* HttpServerResponse.json({
124 count: streams.length,
125 });
126 }
127
128 // Timed-metadata insert requires a live stream — the idle channel
129 // answers with the typed ChannelNotBroadcasting tag.
130 if (request.method === "POST" && pathname === "/metadata") {
131 const result = yield* putMetadata({
132 metadata: JSON.stringify({ hello: "viewers" }),
133 }).pipe(
134 Effect.map(() => ({ inserted: true, tag: undefined })),
135 Effect.catchTag("ChannelNotBroadcasting", (e) =>
136 Effect.succeed({ inserted: false, tag: e._tag }),
137 ),
138 );
139 return yield* HttpServerResponse.json(result);
140 }
141
142 // Stopping an idle channel: typed ChannelNotBroadcasting.
143 if (request.method === "POST" && pathname === "/stop") {
144 const result = yield* stopStream().pipe(
145 Effect.map(() => ({ stopped: true, tag: undefined })),
146 Effect.catchTag(["ChannelNotBroadcasting", "StreamUnavailable"], (e) =>
147 Effect.succeed({ stopped: false, tag: e._tag }),
148 ),
149 );
150 return yield* HttpServerResponse.json(result);
151 }
152
153 // Viewer session revocation is fire-and-forget; report the typed
154 // outcome either way.
155 if (request.method === "POST" && pathname === "/revoke") {
156 const result = yield* revokeViewerSession({
157 viewerId: "alchemy-test-viewer",
158 }).pipe(
159 Effect.map(() => ({
160 ok: true,
161 tag: undefined as string | undefined,
162 })),
163 Effect.catchTag(["ValidationException", "PendingVerification"], (e) =>
164 Effect.succeed({
165 ok: false,
166 tag: e._tag as string | undefined,
167 }),
168 ),
169 );
170 return yield* HttpServerResponse.json(result);
171 }
172
173 // Server-side ad insertion requires a live stream (and an ad
174 // configuration); report the typed outcome.
175 if (request.method === "POST" && pathname === "/adbreak") {
176 const result = yield* insertAdBreak({ durationSeconds: 30 }).pipe(
177 Effect.map(({ adBreakId }) => ({
178 inserted: true,
179 adBreakId,
180 tag: undefined as string | undefined,
181 })),
182 Effect.catchTag(
183 ["ChannelNotBroadcasting", "ValidationException", "ConflictException"],
184 (e) =>
185 Effect.succeed({
186 inserted: false,
187 adBreakId: undefined,
188 tag: e._tag as string | undefined,
189 }),
190 ),
191 );
192 return yield* HttpServerResponse.json(result);
193 }
194
195 // Batch revocation across channels — per-pair failures surface in
196 // the response's `errors` array rather than failing the call.
197 if (request.method === "POST" && pathname === "/revoke-batch") {
198 const channelArn = yield* ChannelArn;
199 const { errors } = yield* batchRevokeViewerSessions({
200 viewerSessions: [{ channelArn, viewerId: "alchemy-test-viewer" }],
201 });
202 return yield* HttpServerResponse.json({
203 errorCount: (errors ?? []).length,
204 });
205 }
206
207 return yield* HttpServerResponse.json(
208 { error: "Not found", method: request.method, pathname },
209 { status: 404 },
210 );
211 }).pipe(Effect.orDie),
212 };
213 }).pipe(
214 Effect.provide(
215 Layer.mergeAll(
216 Lambda.EventSource,
217 IVS.GetStreamHttp,
218 IVS.GetStreamSessionHttp,
219 IVS.ListStreamSessionsHttp,
220 IVS.PutMetadataHttp,
221 IVS.StopStreamHttp,
222 IVS.StartViewerSessionRevocationHttp,
223 IVS.InsertAdBreakHttp,
224 IVS.ListStreamsHttp,
225 IVS.BatchStartViewerSessionRevocationHttp,
226 ),
227 ),
228 ),
229 );