The best way to control Claude Code, Codex and more from any computer or phone

main
ts 117 lines 4.34 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as Timestream from "@alchemy.run/aws/Timestream";
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, "sink-handler.ts");
12
13 export class TimestreamSinkFunction extends Lambda.Function<Lambda.Function>()(
14 "TimestreamSinkFunction",
15 ) {}
16
17 export default TimestreamSinkFunction.make(
18 {
19 main,
20 functionUrl: true,
21 // The sink drains fully (multiple sequential WriteRecords calls behind
22 // endpoint discovery) before the handler returns.
23 timeout: Duration.seconds(60),
24 },
25 Effect.gen(function* () {
26 const database = yield* Timestream.Database("SinkMetrics");
27 const table = yield* Timestream.Table("SinkCpu", {
28 databaseName: database.databaseName,
29 retentionProperties: {
30 memoryStoreRetention: "6 hours",
31 magneticStoreRetention: "30 days",
32 },
33 });
34 const DatabaseName = yield* database.databaseName;
35 const TableName = yield* table.tableName;
36
37 // `commonAttributes` exercises the CommonAttributes path: the measure
38 // shape is shared, each record carries only Dimensions/MeasureValue/Time.
39 const sink = yield* Timestream.RecordsSink(table, {
40 commonAttributes: {
41 MeasureName: "cpu",
42 MeasureValueType: "DOUBLE",
43 TimeUnit: "MILLISECONDS",
44 },
45 });
46 const query = yield* Timestream.Query(table);
47
48 const record = (host: string, value: number, time: number) => ({
49 Dimensions: [{ Name: "host", Value: host }],
50 MeasureValue: `${value}`,
51 Time: `${time}`,
52 });
53
54 return {
55 fetch: Effect.gen(function* () {
56 const request = yield* HttpServerRequest;
57 const pathname = new URL(request.originalUrl).pathname;
58
59 if (request.method === "GET" && pathname === "/ready") {
60 return yield* HttpServerResponse.json({ ok: true });
61 }
62
63 // Stream `count` records through the sink. count > 100 proves the
64 // sink splits the stream into <=100-record WriteRecords calls.
65 if (request.method === "POST" && pathname === "/sink") {
66 const body = (yield* request.json) as unknown as {
67 host: string;
68 count: number;
69 };
70 const base = Date.now() - body.count * 1_000;
71 yield* Stream.fromIterable(
72 Array.from({ length: body.count }, (_, i) => record(body.host, i, base + i * 1_000)),
73 ).pipe(Stream.run(sink));
74 return yield* HttpServerResponse.json({
75 ok: true,
76 count: body.count,
77 });
78 }
79
80 // Partial failure: one record with a Time outside the 6h memory-store
81 // retention window (magnetic writes are disabled by default) is
82 // permanently rejected via RejectedRecordsException; the sink drops
83 // it and lands the two valid records around it.
84 if (request.method === "POST" && pathname === "/sink-rejects") {
85 const body = (yield* request.json) as unknown as { host: string };
86 const now = Date.now();
87 yield* Stream.fromIterable([
88 record(body.host, 1, now - 2_000),
89 record(body.host, 2, now - 24 * 60 * 60 * 1_000),
90 record(body.host, 3, now - 1_000),
91 ]).pipe(Stream.run(sink));
92 return yield* HttpServerResponse.json({ ok: true });
93 }
94
95 if (request.method === "GET" && pathname === "/count") {
96 const host = new URL(request.originalUrl).searchParams.get("host");
97 const result = yield* query({
98 QueryString: `SELECT COUNT(*) AS c FROM "${DatabaseName}"."${TableName}" WHERE host = '${host}'`,
99 });
100 return yield* HttpServerResponse.json({ rows: result.Rows });
101 }
102
103 return yield* HttpServerResponse.json(
104 { error: "Not found", method: request.method, pathname },
105 { status: 404 },
106 );
107 }).pipe(Effect.orDie),
108 };
109 }).pipe(
110 Effect.provide(
111 Layer.provideMerge(
112 Layer.mergeAll(Timestream.RecordsSinkHttp, Timestream.QueryHttp),
113 Layer.mergeAll(Timestream.WriteRecordsHttp),
114 ),
115 ),
116 ),
117 );