The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import * as GCP from "@alchemy.run/gcp"; |
| 3 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 4 | import * as Cause from "effect/Cause"; |
| 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 Layer from "effect/Layer"; |
| 9 | |
| 10 | export const Bucket = GCP.Storage.Bucket("ExternalHostBucket", { |
| 11 | location: "US-CENTRAL1", |
| 12 | forceDestroy: true, |
| 13 | }); |
| 14 | export const Topic = GCP.PubSub.Topic("ExternalHostTopic", {}); |
| 15 | |
| 16 | /** |
| 17 | * A Cloudflare Worker using GCP bindings: an external host, so each binding |
| 18 | * grants on the service account Alchemy mints for the Worker and signs with |
| 19 | * tokens minted from its key. One route per binding; each answers |
| 20 | * `{ ok, result | error }` so a failure surfaces the GCP error in the test. |
| 21 | */ |
| 22 | export default class ExternalHostWorker extends Cloudflare.Worker<ExternalHostWorker>()( |
| 23 | "GcpExternalHostWorker", |
| 24 | { main: import.meta.url, compatibility: { flags: ["nodejs_compat"] } }, |
| 25 | Effect.gen(function* () { |
| 26 | const bucket = yield* GCP.Storage.ReadWriteBucket(yield* Bucket); |
| 27 | const topic = yield* GCP.PubSub.WriteTopic(yield* Topic); |
| 28 | |
| 29 | const respond = (effect: Effect.Effect<unknown, unknown, RuntimeContext>) => |
| 30 | effect.pipe( |
| 31 | Effect.flatMap((result) => HttpServerResponse.json({ ok: true, result })), |
| 32 | Effect.catchCause((cause) => |
| 33 | HttpServerResponse.json({ ok: false, error: Cause.pretty(cause) }, { status: 500 }), |
| 34 | ), |
| 35 | ); |
| 36 | |
| 37 | return { |
| 38 | fetch: Effect.gen(function* () { |
| 39 | const request = yield* HttpServerRequest; |
| 40 | const url = new URL(request.url, "http://worker"); |
| 41 | const key = url.searchParams.get("key") ?? "external-host"; |
| 42 | switch (url.pathname) { |
| 43 | case "/storage": |
| 44 | return yield* respond( |
| 45 | Effect.gen(function* () { |
| 46 | yield* bucket.put(key, "from-worker"); |
| 47 | const object = yield* bucket.get(key); |
| 48 | return { text: object && new TextDecoder().decode(object.body) }; |
| 49 | }), |
| 50 | ); |
| 51 | case "/pubsub": |
| 52 | return yield* respond( |
| 53 | Effect.map(topic.publish({ data: key }), (messageId) => ({ messageId })), |
| 54 | ); |
| 55 | default: |
| 56 | return HttpServerResponse.text("ok"); |
| 57 | } |
| 58 | }), |
| 59 | }; |
| 60 | }).pipe( |
| 61 | Effect.provide(Layer.mergeAll(GCP.Storage.ReadWriteBucketHttp, GCP.PubSub.WriteTopicHttp)), |
| 62 | ), |
| 63 | ) {} |