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

main
ts 78 lines 2.9 KB
Raw
1 import * as GCP from "@alchemy.run/gcp";
2 import * as Clock from "effect/Clock";
3 import * as Effect from "effect/Effect";
4 import { Orders, Reports, summaryKey, type DailySummary, type RegionTotal } from "./resources.ts";
5
6 const DAY_MS = 24 * 60 * 60 * 1000;
7
8 /**
9 * The nightly batch: roll the last 24 hours of orders up into one JSON
10 * summary in Cloud Storage.
11 *
12 * A Cloud Run Job runs to completion and exits, so nothing is billed
13 * between runs. It is started by Cloud Scheduler every night and by the
14 * admin route in {@link ../Admin.ts} on demand; both paths create a new
15 * execution through the Cloud Run Admin API.
16 *
17 * Re-running is safe: a run for the same day overwrites that day's
18 * object with a fresh aggregate.
19 */
20 export default class Summarize extends GCP.Run.Job<Summarize>()(
21 "Summarize",
22 {
23 main: import.meta.url,
24 // A failed summary is retried once, then the execution fails and the
25 // next trigger tries again.
26 maxRetries: 1,
27 timeout: "300s",
28 },
29 Effect.gen(function* () {
30 const table = yield* Orders;
31 const orders = yield* GCP.BigQuery.ReadTable(table);
32 const reports = yield* GCP.Storage.WriteBucket(Reports);
33 // The table id is bound at deploy time and read inside `run`.
34 const tableId = yield* table.tableId;
35
36 return {
37 run: Effect.gen(function* () {
38 const to = new Date(yield* Clock.currentTimeMillis);
39 const from = new Date(to.getTime() - DAY_MS);
40 // Cloud Run names each execution in the task's environment.
41 const execution = yield* Effect.sync(() => process.env.CLOUD_RUN_EXECUTION ?? null);
42
43 // Unqualified table names resolve against the table's dataset.
44 const rows = yield* orders.query(
45 `SELECT region, COUNT(*) AS orders, SUM(amountCents) AS revenueCents
46 FROM \`${yield* tableId}\`
47 WHERE occurredAt >= TIMESTAMP(@from) AND occurredAt < TIMESTAMP(@to)
48 GROUP BY region
49 ORDER BY region`,
50 { from: from.toISOString(), to: to.toISOString() },
51 );
52
53 const regions: RegionTotal[] = rows.map((row) => ({
54 region: String(row.region),
55 orders: Number(row.orders),
56 revenueCents: Number(row.revenueCents ?? 0),
57 }));
58
59 const summary: DailySummary = {
60 from: from.toISOString(),
61 to: to.toISOString(),
62 execution,
63 orders: regions.reduce((n, r) => n + r.orders, 0),
64 revenueCents: regions.reduce((n, r) => n + r.revenueCents, 0),
65 regions,
66 };
67
68 const key = summaryKey(to);
69 yield* reports.put(key, JSON.stringify(summary, null, 2), {
70 contentType: "application/json",
71 });
72 yield* Effect.log(
73 `summarize: ${summary.orders} order(s) in ${regions.length} region(s) -> ${key}`,
74 );
75 }).pipe(Effect.orDie),
76 };
77 }).pipe(Effect.provide([GCP.BigQuery.ReadTableHttp, GCP.Storage.WriteBucketHttp])),
78 ) {}