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

main
ts 84 lines 2.81 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { Config } from "effect";
3 import * as Effect from "effect/Effect";
4 import * as Redacted from "effect/Redacted";
5 import * as Schedule from "effect/Schedule";
6 import { KV } from "./KV.ts";
7 import Room from "./Room.ts";
8
9 /**
10 * Hard-coded value the integ test asserts on to prove the secret was
11 * bound at plantime and read at runtime through the `Redacted` accessor.
12 */
13 export const WORKFLOW_SECRET_VALUE = Redacted.make("wf-secret-abc123");
14
15 export default class NotifyWorkflow extends Cloudflare.Workflow<NotifyWorkflow>()(
16 "Notifier",
17 Effect.gen(function* () {
18 const rooms = yield* Room;
19
20 const secret = yield* Config.Redacted("WORKFLOW_SECRET").pipe(
21 Config.withDefault(WORKFLOW_SECRET_VALUE),
22 );
23
24 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
25
26 return Effect.fn(function* (input: { roomId: string; message: string }) {
27 const { roomId, message } = input;
28
29 const stored = yield* Cloudflare.Workflows.task(
30 "kv-roundtrip",
31 Effect.gen(function* () {
32 const key = `workflow:smoke:${roomId}`;
33 yield* kv.put(key, message);
34 // KV is eventually consistent: a read immediately after a write can
35 // briefly miss or return stale data. Re-read until it reflects the
36 // write (bounded, so a genuine failure still surfaces below).
37 const got = yield* kv.get(key).pipe(
38 Effect.repeat({
39 schedule: Schedule.spaced("500 millis"),
40 until: (value) => value === message,
41 times: 10,
42 }),
43 );
44 if (got !== message) {
45 return yield* Effect.die(
46 new Error(`KV roundtrip mismatch: expected "${message}", got "${got ?? "null"}"`),
47 );
48 }
49 return got;
50 }).pipe(Effect.orDie),
51 );
52
53 // Resolve the bound secret inside the workflow body. The accessor
54 // returns `Redacted<string>`; unwrap only where the value needs to
55 // leave the workflow (here, in the broadcast + the returned output
56 // so the integ test can assert end-to-end propagation).
57 const secretValue = Redacted.value(secret);
58
59 const processed = yield* Cloudflare.Workflows.task(
60 "process",
61 Effect.succeed({
62 text: `Processed: ${stored}`,
63 secret: secretValue,
64 ts: Date.now(),
65 }),
66 );
67
68 const room = rooms.getByName(roomId);
69 yield* Cloudflare.Workflows.task(
70 "broadcast",
71 room.broadcast(`[workflow] ${processed.text} secret=${secretValue}`),
72 );
73
74 yield* Cloudflare.Workflows.sleep("cooldown", "2 seconds");
75
76 yield* Cloudflare.Workflows.task(
77 "finalize",
78 room.broadcast(`[workflow] complete for ${roomId}`),
79 );
80
81 return processed;
82 });
83 }),
84 ) {}