@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 228 lines 8.62 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as MediaPackageV2 from "@alchemy.run/aws/MediaPackageV2";
3 import * as S3 from "@alchemy.run/aws/S3";
4 import * as Duration from "effect/Duration";
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 * as Stream from "effect/Stream";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "handler.ts");
13
14 /**
15 * Deterministic bucket name so the bucket's own policy can reference its
16 * ARN without a self-referential Output (MediaPackage writes harvested
17 * clips as the `mediapackagev2.amazonaws.com` service principal, which the
18 * bucket policy must allow).
19 */
20 const HARVEST_BUCKET = "alchemy-test-mediapackagev2-harvest";
21
22 export class MediaPackageV2TestFunction extends Lambda.Function<Lambda.Function>()(
23 "MediaPackageV2TestFunction",
24 ) {}
25
26 export default MediaPackageV2TestFunction.make(
27 {
28 main,
29 functionUrl: true,
30 timeout: Duration.seconds(60),
31 },
32 Effect.gen(function* () {
33 // The channel-group → channel → endpoint chain the bindings are bound
34 // to. Nothing ever pushes content to the channel, so harvest jobs can
35 // be created (the schedule sits inside the startover window) but fail
36 // asynchronously with "no content" — which is fine: the fixture only
37 // proves the runtime call + IAM wiring.
38 const group = yield* MediaPackageV2.ChannelGroup("BindingGroup", {
39 description: "alchemy mediapackagev2 bindings fixture",
40 tags: { fixture: "mediapackagev2-bindings" },
41 });
42 const channel = yield* MediaPackageV2.Channel("BindingFeed", {
43 channelGroupName: group.channelGroupName,
44 inputType: "HLS",
45 tags: { fixture: "mediapackagev2-bindings" },
46 });
47 const endpoint = yield* MediaPackageV2.OriginEndpoint("BindingPlayback", {
48 channelGroupName: group.channelGroupName,
49 channelName: channel.channelName,
50 containerType: "TS",
51 segment: { SegmentDurationSeconds: 6 },
52 startoverWindow: "1 hour",
53 hlsManifests: [{ ManifestName: "index" }],
54 tags: { fixture: "mediapackagev2-bindings" },
55 });
56
57 // Destination bucket for harvested clips, writable by MediaPackage.
58 yield* S3.Bucket("HarvestBucket", {
59 bucketName: HARVEST_BUCKET,
60 forceDestroy: true,
61 policy: [
62 {
63 Sid: "AllowMediaPackageHarvest",
64 Effect: "Allow",
65 Principal: { Service: "mediapackagev2.amazonaws.com" },
66 Action: ["s3:PutObject", "s3:GetBucketLocation"],
67 Resource: [`arn:aws:s3:::${HARVEST_BUCKET}`, `arn:aws:s3:::${HARVEST_BUCKET}/*`],
68 },
69 ],
70 tags: { fixture: "mediapackagev2-bindings" },
71 });
72
73 // Event source: subscribe the host to harvest-job notifications. The
74 // deploy proves the EventBridge rule + invoke permission wiring.
75 yield* MediaPackageV2.consumeHarvestJobEvents({}, (events) =>
76 Stream.runForEach(events, (event) =>
77 Effect.log(
78 `mediapackagev2 harvest job ${event.detail.harvestJob.harvestJobName}: ${event.detail.harvestJob.status}`,
79 ),
80 ),
81 );
82
83 const resetChannel = yield* MediaPackageV2.ResetChannelState(channel);
84 const resetEndpoint = yield* MediaPackageV2.ResetOriginEndpointState(endpoint);
85 const createHarvestJob = yield* MediaPackageV2.CreateHarvestJob(endpoint);
86 const getHarvestJob = yield* MediaPackageV2.GetHarvestJob(endpoint);
87 const cancelHarvestJob = yield* MediaPackageV2.CancelHarvestJob(endpoint);
88 const listHarvestJobs = yield* MediaPackageV2.ListHarvestJobs(group);
89
90 const bound = {
91 resetChannel,
92 resetEndpoint,
93 createHarvestJob,
94 getHarvestJob,
95 cancelHarvestJob,
96 listHarvestJobs,
97 };
98
99 return {
100 fetch: Effect.gen(function* () {
101 const request = yield* HttpServerRequest;
102 const url = new URL(request.originalUrl);
103 const pathname = url.pathname;
104
105 if (request.method === "GET" && pathname === "/bindings") {
106 return yield* HttpServerResponse.json({
107 bound: Object.keys(bound),
108 });
109 }
110
111 // Reset the channel's ingest state. On an idle channel this
112 // trivially succeeds; MediaPackage rate-limits resets, so a
113 // repeated run may answer with the typed Conflict/Throttling tag.
114 if (request.method === "POST" && pathname === "/reset-channel") {
115 const result = yield* resetChannel().pipe(
116 Effect.map(({ Arn }) => ({
117 arn: Arn as string | undefined,
118 tag: undefined as string | undefined,
119 })),
120 Effect.catchTag(["ConflictException", "ThrottlingException"], (e) =>
121 Effect.succeed({
122 arn: undefined as string | undefined,
123 tag: e._tag as string | undefined,
124 }),
125 ),
126 );
127 return yield* HttpServerResponse.json(result);
128 }
129
130 // Reset the endpoint's packaging state — same tolerance as above.
131 if (request.method === "POST" && pathname === "/reset-endpoint") {
132 const result = yield* resetEndpoint().pipe(
133 Effect.map(({ Arn }) => ({
134 arn: Arn as string | undefined,
135 tag: undefined as string | undefined,
136 })),
137 Effect.catchTag(["ConflictException", "ThrottlingException"], (e) =>
138 Effect.succeed({
139 arn: undefined as string | undefined,
140 tag: e._tag as string | undefined,
141 }),
142 ),
143 );
144 return yield* HttpServerResponse.json(result);
145 }
146
147 // Enumerate the group's harvest jobs.
148 if (request.method === "GET" && pathname === "/harvest-jobs") {
149 const { Items } = yield* listHarvestJobs();
150 return yield* HttpServerResponse.json({
151 count: (Items ?? []).length,
152 });
153 }
154
155 // Full create → get → cancel roundtrip. The channel never received
156 // content, so MediaPackage may reject the job upfront with the
157 // typed ValidationException — that outcome still proves the binding
158 // and its IAM grant.
159 if (request.method === "POST" && pathname === "/harvest-cycle") {
160 const now = yield* Effect.sync(() => Date.now());
161 const result = yield* createHarvestJob({
162 HarvestedManifests: {
163 HlsManifests: [{ ManifestName: "index" }],
164 },
165 ScheduleConfiguration: {
166 StartTime: new Date(now - 4 * 60_000),
167 EndTime: new Date(now - 60_000),
168 },
169 Destination: {
170 S3Destination: {
171 BucketName: HARVEST_BUCKET,
172 DestinationPath: "clips/",
173 },
174 },
175 }).pipe(
176 Effect.flatMap((job) =>
177 Effect.gen(function* () {
178 const { Status } = yield* getHarvestJob({
179 HarvestJobName: job.HarvestJobName,
180 });
181 // Cancel is only legal while QUEUED/IN_PROGRESS; a job that
182 // already settled answers with the typed Conflict.
183 const cancelled = yield* cancelHarvestJob({
184 HarvestJobName: job.HarvestJobName,
185 }).pipe(
186 Effect.map(() => true),
187 Effect.catchTag("ConflictException", () => Effect.succeed(false)),
188 );
189 return {
190 created: true,
191 status: Status as string | undefined,
192 cancelled,
193 tag: undefined as string | undefined,
194 };
195 }),
196 ),
197 Effect.catchTag(["ValidationException", "ConflictException"], (e) =>
198 Effect.succeed({
199 created: false,
200 status: undefined as string | undefined,
201 cancelled: false,
202 tag: e._tag as string | undefined,
203 }),
204 ),
205 );
206 return yield* HttpServerResponse.json(result);
207 }
208
209 return yield* HttpServerResponse.json(
210 { error: "Not found", method: request.method, pathname },
211 { status: 404 },
212 );
213 }).pipe(Effect.orDie),
214 };
215 }).pipe(
216 Effect.provide(
217 Layer.mergeAll(
218 Lambda.EventSource,
219 MediaPackageV2.ResetChannelStateHttp,
220 MediaPackageV2.ResetOriginEndpointStateHttp,
221 MediaPackageV2.CreateHarvestJobHttp,
222 MediaPackageV2.GetHarvestJobHttp,
223 MediaPackageV2.CancelHarvestJobHttp,
224 MediaPackageV2.ListHarvestJobsHttp,
225 ),
226 ),
227 ),
228 );