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

main
ts 60 lines 2.31 KB
Raw
1 import * as Fly from "@alchemy.run/fly";
2 import * as Redis from "@alchemy.run/redis";
3 import type { Input } from "alchemy/Input";
4 import * as Config from "effect/Config";
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 Redacted from "effect/Redacted";
9 import { Cache, LedgerSite, scripts, services } from "./bluegreen-worker-shared.ts";
10
11 export class Ledger extends Fly.Service<Ledger>()("Ledger") {}
12 export const ledgerLayer = (secretDigest?: Input<string | undefined>) =>
13 Ledger.make(
14 {
15 app: LedgerSite,
16 main: import.meta.url,
17 region: "iad",
18 port: 3000,
19 guest: { cpuKind: "shared", cpus: 1, memoryMb: 256 },
20 env: { SECRET_READY: secretDigest ?? "" },
21 services,
22 },
23 Effect.gen(function* () {
24 yield* Fly.ReadWriteRedis(Cache);
25 const resource = yield* Cache;
26 const boundUrl = yield* resource.url;
27 const cache = Redis.makeReadWrite(
28 Effect.gen(function* () {
29 const url = yield* boundUrl;
30 if (!url) return yield* Effect.die(new Error("Redis URL missing"));
31 return Redacted.value(url);
32 }),
33 );
34 return {
35 fetch: Effect.gen(function* () {
36 const request = yield* HttpServerRequest;
37 if (request.url === "/health") {
38 yield* cache.ping().pipe(Effect.orDie);
39 return HttpServerResponse.text("ready");
40 }
41 const token = yield* Config.Redacted("LEDGER_TOKEN").pipe(Effect.orDie);
42 if (request.headers.authorization !== `Bearer ${Redacted.value(token)}`) {
43 return HttpServerResponse.empty({ status: 401 });
44 }
45 const body = (yield* request.json.pipe(Effect.orDie)) as {
46 operation: keyof typeof scripts;
47 args?: string[];
48 };
49 if (!Object.hasOwn(scripts, body.operation))
50 return HttpServerResponse.empty({ status: 400 });
51 const result = yield* cache
52 .send("EVAL", [scripts[body.operation], 0, ...(body.args ?? [])])
53 .pipe(Effect.orDie);
54 return yield* HttpServerResponse.json({ result });
55 }),
56 };
57 }).pipe(Effect.provide(Fly.ReadWriteRedisHttp)),
58 );
59
60 export default ledgerLayer();