@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 254 lines 9.6 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as MediaConnect from "@alchemy.run/aws/MediaConnect";
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 Schedule from "effect/Schedule";
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 export class MediaConnectTestFunction extends Lambda.Function<Lambda.Function>()(
15 "MediaConnectTestFunction",
16 ) {}
17
18 export default MediaConnectTestFunction.make(
19 {
20 main,
21 functionUrl: true,
22 // The gated /start-stop roundtrip waits for the flow to accept StopFlow.
23 timeout: Duration.seconds(120),
24 },
25 Effect.gen(function* () {
26 // The flow the flow-scoped bindings are bound to. It is created in
27 // STANDBY (which does not bill for transport) and nothing ever sends
28 // media to it, so the observability ops see the typed
29 // not-running/no-content behavior.
30 const flow = yield* MediaConnect.Flow("BindingFlow", {
31 source: {
32 Name: "primary",
33 Protocol: "rtp",
34 WhitelistCidr: "10.24.34.0/23",
35 IngestPort: 5000,
36 },
37 tags: { fixture: "mediaconnect-bindings" },
38 });
39
40 // Event source: subscribe the host to MediaConnect alert/status events.
41 // The deploy proves the EventBridge rule + invoke permission wiring.
42 yield* MediaConnect.consumeFlowEvents({ kinds: ["alert", "flow-status-change"] }, (events) =>
43 Stream.runForEach(events, (event) =>
44 Effect.log(
45 `mediaconnect event: ${event["detail-type"]} ${event.detail.message ?? event.detail.status ?? ""}`,
46 ),
47 ),
48 );
49
50 // Accessor for the flow's ARN, resolvable inside the runtime fetch
51 // handler (the entitlement roundtrip derives the account id from it).
52 const FlowArn = yield* flow.flowArn;
53
54 const describeFlow = yield* MediaConnect.DescribeFlow(flow);
55 const sourceMetadata = yield* MediaConnect.DescribeFlowSourceMetadata(flow);
56 const sourceThumbnail = yield* MediaConnect.DescribeFlowSourceThumbnail(flow);
57 const startFlow = yield* MediaConnect.StartFlow(flow);
58 const stopFlow = yield* MediaConnect.StopFlow(flow);
59 const grantEntitlements = yield* MediaConnect.GrantFlowEntitlements(flow);
60 const revokeEntitlement = yield* MediaConnect.RevokeFlowEntitlement(flow);
61 const listFlows = yield* MediaConnect.ListFlows();
62 const listEntitlements = yield* MediaConnect.ListEntitlements();
63
64 const bound = {
65 describeFlow,
66 sourceMetadata,
67 sourceThumbnail,
68 startFlow,
69 stopFlow,
70 grantEntitlements,
71 revokeEntitlement,
72 listFlows,
73 listEntitlements,
74 };
75
76 return {
77 fetch: Effect.gen(function* () {
78 const request = yield* HttpServerRequest;
79 const url = new URL(request.originalUrl);
80 const pathname = url.pathname;
81
82 if (request.method === "GET" && pathname === "/bindings") {
83 return yield* HttpServerResponse.json({
84 bound: Object.keys(bound),
85 });
86 }
87
88 // Read the flow's live state — the fixture flow idles in STANDBY.
89 if (request.method === "GET" && pathname === "/flow") {
90 const { Flow: current } = yield* describeFlow();
91 return yield* HttpServerResponse.json({
92 status: current?.Status,
93 sourceName: current?.Source?.Name,
94 });
95 }
96
97 // Transport-stream metadata on a flow that is not receiving
98 // content: MediaConnect answers with status messages (or a typed
99 // BadRequestException while the flow is not running).
100 if (request.method === "GET" && pathname === "/source-metadata") {
101 const result = yield* sourceMetadata().pipe(
102 Effect.map(({ TransportMediaInfo, Messages }) => ({
103 programs: TransportMediaInfo?.Programs?.length ?? 0,
104 messages: (Messages ?? []).length,
105 tag: undefined as string | undefined,
106 })),
107 Effect.catchTag("BadRequestException", (e) =>
108 Effect.succeed({ programs: 0, messages: 0, tag: e._tag }),
109 ),
110 );
111 return yield* HttpServerResponse.json(result);
112 }
113
114 // Source thumbnail on an idle flow: no image, only messages (or a
115 // typed BadRequestException while the flow is not running).
116 if (request.method === "GET" && pathname === "/thumbnail") {
117 const result = yield* sourceThumbnail().pipe(
118 Effect.map(({ ThumbnailDetails }) => ({
119 hasImage: ThumbnailDetails?.Thumbnail !== undefined,
120 messages: ThumbnailDetails?.ThumbnailMessages?.length ?? 0,
121 tag: undefined as string | undefined,
122 })),
123 Effect.catchTag("BadRequestException", (e) =>
124 Effect.succeed({ hasImage: false, messages: 0, tag: e._tag }),
125 ),
126 );
127 return yield* HttpServerResponse.json(result);
128 }
129
130 // Account-level enumerations.
131 if (request.method === "GET" && pathname === "/flows") {
132 const { Flows } = yield* listFlows({ MaxResults: 20 });
133 return yield* HttpServerResponse.json({
134 count: (Flows ?? []).length,
135 });
136 }
137 if (request.method === "GET" && pathname === "/entitlements") {
138 const { Entitlements } = yield* listEntitlements();
139 return yield* HttpServerResponse.json({
140 count: (Entitlements ?? []).length,
141 });
142 }
143
144 // Stopping a flow that is already in STANDBY: the typed
145 // BadRequestException tag is the real observable behavior.
146 if (request.method === "POST" && pathname === "/stop") {
147 const result = yield* stopFlow().pipe(
148 Effect.map(({ Status }) => ({
149 status: Status,
150 tag: undefined as string | undefined,
151 })),
152 Effect.catchTag("BadRequestException", (e) =>
153 Effect.succeed({
154 status: undefined as string | undefined,
155 tag: e._tag,
156 }),
157 ),
158 );
159 return yield* HttpServerResponse.json(result);
160 }
161
162 // Grant an entitlement to this very account, then revoke it —
163 // a full grant/revoke roundtrip with no cross-account dependency.
164 // Failures surface as their typed tag so the test can diagnose
165 // (e.g. an IAM gap is a visible ForbiddenException, not a 500).
166 if (request.method === "POST" && pathname === "/entitlement-cycle") {
167 const flowArn = yield* FlowArn;
168 const accountId = flowArn.split(":")[4]!;
169 const result = yield* grantEntitlements({
170 Entitlements: [
171 {
172 Name: "alchemy-binding-test",
173 Subscribers: [accountId],
174 },
175 ],
176 }).pipe(
177 Effect.flatMap(({ Entitlements }) => {
178 const entitlementArn = Entitlements?.[0]?.EntitlementArn;
179 if (entitlementArn === undefined) {
180 return Effect.succeed({
181 granted: false,
182 revoked: false,
183 tag: undefined as string | undefined,
184 });
185 }
186 return revokeEntitlement({
187 EntitlementArn: entitlementArn,
188 }).pipe(
189 Effect.map(() => ({
190 granted: true,
191 revoked: true,
192 tag: undefined as string | undefined,
193 })),
194 );
195 }),
196 Effect.catchTag(
197 [
198 "BadRequestException",
199 "GrantFlowEntitlements420Exception",
200 "ForbiddenException",
201 "NotFoundException",
202 ],
203 (e) =>
204 Effect.succeed({
205 granted: false,
206 revoked: false,
207 tag: e._tag as string | undefined,
208 }),
209 ),
210 );
211 return yield* HttpServerResponse.json(result);
212 }
213
214 // Start the flow, then stop it as soon as MediaConnect accepts a
215 // StopFlow (a STARTING flow rejects it with BadRequestException).
216 // Only driven by the AWS_TEST_MEDIACONNECT-gated test: an ACTIVE
217 // flow bills for transport by the hour.
218 if (request.method === "POST" && pathname === "/start-stop") {
219 const { Status: startStatus } = yield* startFlow();
220 const { Status: stopStatus } = yield* stopFlow().pipe(
221 Effect.retry({
222 while: (e): boolean => e._tag === "BadRequestException",
223 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(18)]),
224 }),
225 );
226 return yield* HttpServerResponse.json({
227 startStatus,
228 stopStatus,
229 });
230 }
231
232 return yield* HttpServerResponse.json(
233 { error: "Not found", method: request.method, pathname },
234 { status: 404 },
235 );
236 }).pipe(Effect.orDie),
237 };
238 }).pipe(
239 Effect.provide(
240 Layer.mergeAll(
241 Lambda.EventSource,
242 MediaConnect.DescribeFlowHttp,
243 MediaConnect.DescribeFlowSourceMetadataHttp,
244 MediaConnect.DescribeFlowSourceThumbnailHttp,
245 MediaConnect.StartFlowHttp,
246 MediaConnect.StopFlowHttp,
247 MediaConnect.GrantFlowEntitlementsHttp,
248 MediaConnect.RevokeFlowEntitlementHttp,
249 MediaConnect.ListFlowsHttp,
250 MediaConnect.ListEntitlementsHttp,
251 ),
252 ),
253 ),
254 );