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

main
ts 120 lines 4.22 KB
Raw
1 import * as GCP from "@alchemy.run/gcp";
2 import * as Effect from "effect/Effect";
3 import { HttpServerRequest } from "effect/http/HttpServerRequest";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import { Heartbeats, type HeartbeatRow } from "./resources.ts";
6
7 /** Most rows `GET /heartbeats` returns. */
8 const MAX_LIMIT = 100;
9
10 /**
11 * A Cloud Run service with two cron handlers and one read route.
12 *
13 * Each `consumeSchedule` creates a Cloud Scheduler job that `POST`s to a
14 * private path on this service with an OIDC token for the service's own
15 * runtime account. The runtime verifies that token before the handler
16 * runs, so the schedule routes stay closed to the public even though
17 * `GET /heartbeats` is open.
18 *
19 * - every minute — record a heartbeat and how late it was delivered.
20 * - daily at midnight UTC — count the last day's heartbeats and record it.
21 * - `GET /heartbeats?kind=&limit=` — the most recent rows, newest first.
22 */
23 export default class Monitor extends GCP.Function<Monitor>()(
24 "Monitor",
25 {
26 main: import.meta.url,
27 // Opens `GET /heartbeats`. The schedule routes still reject any
28 // request without a valid token from Cloud Scheduler.
29 invokerIamDisabled: true,
30 },
31 Effect.gen(function* () {
32 const table = yield* Heartbeats;
33 const writer = yield* GCP.BigQuery.WriteTable(table);
34 const reader = yield* GCP.BigQuery.ReadTable(table);
35 // The table id is bound at deploy time and read inside handlers.
36 const tableId = yield* table.tableId;
37
38 const record = (row: HeartbeatRow) => writer.insert([row]).pipe(Effect.orDie);
39
40 yield* GCP.CloudScheduler.consumeSchedule(
41 "Heartbeat",
42 { schedule: "* * * * *", timeZone: "Etc/UTC" },
43 (event) =>
44 Effect.gen(function* () {
45 const receivedAt = new Date();
46 const scheduleTime = event.scheduleTime ? new Date(event.scheduleTime) : receivedAt;
47 yield* record({
48 kind: "heartbeat",
49 jobName: event.jobName,
50 scheduleTime,
51 receivedAt,
52 value: receivedAt.getTime() - scheduleTime.getTime(),
53 });
54 }),
55 );
56
57 yield* GCP.CloudScheduler.consumeSchedule(
58 "DailyRollup",
59 { schedule: "0 0 * * *", timeZone: "Etc/UTC" },
60 (event) =>
61 Effect.gen(function* () {
62 const heartbeats = yield* tableId;
63 const [counted] = yield* reader
64 .query(
65 `SELECT COUNT(*) AS n FROM \`${heartbeats}\`
66 WHERE kind = 'heartbeat'
67 AND receivedAt >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)`,
68 )
69 .pipe(Effect.orDie);
70 const receivedAt = new Date();
71 yield* record({
72 kind: "daily",
73 jobName: event.jobName,
74 scheduleTime: event.scheduleTime ? new Date(event.scheduleTime) : receivedAt,
75 receivedAt,
76 value: Number(counted?.n ?? 0),
77 });
78 }),
79 );
80
81 return {
82 fetch: Effect.gen(function* () {
83 const request = yield* HttpServerRequest;
84 const url = new URL(request.originalUrl);
85
86 if (request.method === "GET" && url.pathname === "/") {
87 return HttpServerResponse.text("ok");
88 }
89
90 if (request.method === "GET" && url.pathname === "/heartbeats") {
91 const kind = url.searchParams.get("kind");
92 const limit = Math.min(
93 Math.max(Number(url.searchParams.get("limit") ?? 20) || 20, 1),
94 MAX_LIMIT,
95 );
96 const heartbeats = yield* tableId;
97 const rows = yield* reader
98 .query(
99 `SELECT kind, jobName, scheduleTime, receivedAt, value
100 FROM \`${heartbeats}\`
101 ${kind ? "WHERE kind = @kind" : ""}
102 ORDER BY receivedAt DESC
103 LIMIT @limit`,
104 kind ? { kind, limit } : { limit },
105 )
106 .pipe(Effect.orDie);
107 return yield* HttpServerResponse.json({ heartbeats: rows });
108 }
109
110 return yield* HttpServerResponse.json({ error: "not found" }, { status: 404 });
111 }),
112 };
113 }).pipe(
114 Effect.provide([
115 GCP.Run.ScheduleEventSource,
116 GCP.BigQuery.WriteTableHttp,
117 GCP.BigQuery.ReadTableHttp,
118 ]),
119 ),
120 ) {}