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

main
ts 250 lines 9.03 KB
Raw
1 import * as wfp from "@distilled.cloud/cloudflare/workers-for-platforms";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { isResourceOfType, Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.Workers.DispatchNamespace" as const;
12 type TypeId = typeof TypeId;
13
14 export interface DispatchNamespaceProps {
15 /**
16 * Name of the dispatch namespace. Must be lowercase, alphanumeric, and
17 * contain no spaces or special characters except dashes. The name is the
18 * namespace's identity — there is no rename API, so changing it triggers
19 * a replacement. If omitted, a unique name is generated from the app,
20 * stage, and logical ID.
21 * @default ${app}-${id}-${stage}-${suffix}
22 */
23 name?: string;
24 }
25
26 export interface DispatchNamespaceAttributes {
27 /**
28 * API Resource UUID tag assigned by Cloudflare.
29 */
30 namespaceId: string;
31 /**
32 * Name of the dispatch namespace.
33 */
34 name: string;
35 /**
36 * The Cloudflare account the namespace belongs to.
37 */
38 accountId: string;
39 /**
40 * The current number of scripts in this dispatch namespace.
41 */
42 scriptCount: number;
43 /**
44 * Whether the Workers in the namespace are executed in a "trusted"
45 * manner (access to shared zone caches and `request.cf`).
46 */
47 trustedWorkers: boolean;
48 /**
49 * When the namespace was created.
50 */
51 createdOn: string | undefined;
52 /**
53 * When the namespace was last modified.
54 */
55 modifiedOn: string | undefined;
56 }
57
58 export type DispatchNamespace = Resource<
59 TypeId,
60 DispatchNamespaceProps,
61 DispatchNamespaceAttributes,
62 never,
63 Providers
64 >;
65
66 /**
67 * A Workers for Platforms dispatch namespace — a container for customer
68 * ("user") Workers that a platform Worker dispatches to at runtime via a
69 * dynamic-dispatch binding.
70 *
71 * The namespace has no mutable properties: its `name` is its identity, so
72 * changing the name triggers a replacement. Deleting a namespace also
73 * deletes every script uploaded into it.
74 *
75 * Note: Workers for Platforms is a paid add-on. On accounts without the
76 * subscription, namespace creation fails with an entitlement error.
77 * ### Creating a Dispatch Namespace
78 * **Example:** Namespace with a generated name
79 * ```typescript
80 * const namespace = yield* Cloudflare.WorkersForPlatforms.DispatchNamespace("Customers", {});
81 * ```
82 *
83 * **Example:** Namespace with an explicit name
84 * ```typescript
85 * const namespace = yield* Cloudflare.WorkersForPlatforms.DispatchNamespace("Customers", {
86 * name: "my-platform-customers",
87 * });
88 * ```
89 *
90 * ### Uploading user Workers
91 * **Example:** Upload a customer Worker into the namespace
92 * A {@link Cloudflare.Worker} deploys into the namespace as a "user worker"
93 * (rather than as a routable account-level script) when its `namespace` prop is
94 * set. Reference the namespace by its `name` output so it deploys first.
95 * ```typescript
96 * const namespace = yield* Cloudflare.WorkersForPlatforms.DispatchNamespace("Customers", {});
97 *
98 * const customerA = yield* Cloudflare.Worker("CustomerA", {
99 * namespace: namespace.name,
100 * script: `export default { fetch() { return new Response("hi"); } }`,
101 * });
102 * ```
103 *
104 * ### Dispatching from a platform Worker
105 * **Example:** Effect-native binding via `Get`
106 * `Cloudflare.WorkersForPlatforms.Get(namespace)` binds the namespace and
107 * returns an Effect-native client; `get(name)` resolves a user Worker by script
108 * name. Provide {@link GetBinding} on the Worker's runtime layer.
109 * ```typescript
110 * const dispatch = yield* Cloudflare.WorkersForPlatforms.Get(namespace);
111 *
112 * return {
113 * fetch: Effect.gen(function* () {
114 * const request = yield* HttpServerRequest;
115 * const userWorker = yield* dispatch.get("CustomerA");
116 * return yield* Effect.promise(() => userWorker.fetch(request));
117 * }),
118 * };
119 * ```
120 *
121 * **Example:** Async binding via `env` + `InferEnv`
122 * Passing the namespace on a Worker's `env` binds it as a native
123 * `dispatch_namespace` binding; `Cloudflare.InferEnv` types `env.DISPATCH` as
124 * the runtime `DispatchNamespace`, so the async handler calls `.get(name)`
125 * directly.
126 * ```typescript
127 * const platform = Cloudflare.Worker("Platform", {
128 * main: "./handler.ts",
129 * env: { DISPATCH: namespace },
130 * });
131 * type Env = Cloudflare.InferEnv<typeof platform>;
132 *
133 * // handler.ts
134 * export default {
135 * async fetch(request: Request, env: Env) {
136 * return env.DISPATCH.get("CustomerA").fetch(request);
137 * },
138 * };
139 * ```
140 *
141 * @see https://developers.cloudflare.com/cloudflare-for-platforms/workers-for-platforms/
142 *
143 * @resource
144 * @product Workers for Platforms
145 * @category Workers & Compute
146 */
147 export const DispatchNamespace = Resource<DispatchNamespace>(TypeId);
148
149 /**
150 * Returns true if the given value is a DispatchNamespace resource.
151 */
152 export const isDispatchNamespace = (value: unknown): value is DispatchNamespace =>
153 isResourceOfType(value, TypeId);
154
155 export const DispatchNamespaceProvider = () =>
156 Provider.succeed(DispatchNamespace, {
157 stables: ["namespaceId", "name", "accountId", "createdOn"],
158 diff: Effect.fn(function* ({ olds, news, output }) {
159 const { accountId } = yield* yield* CloudflareEnvironment;
160 if (!isResolved(news)) return undefined;
161 if ((output?.accountId ?? accountId) !== accountId) {
162 return { action: "replace" } as const;
163 }
164 // The name is the namespace's identity — no rename API. When `name`
165 // is omitted on both sides, the generated physical name is identical
166 // (same logical ID + instance ID), so an omitted name never diffs.
167 const oldName = output?.name ?? olds?.name;
168 const newName = news.name ?? olds?.name ?? oldName;
169 if (oldName !== undefined && oldName !== newName) {
170 return { action: "replace" } as const;
171 }
172 return undefined;
173 }),
174 list: Effect.fn(function* () {
175 const { accountId } = yield* yield* CloudflareEnvironment;
176 return yield* wfp.listDispatchNamespaces.pages({ accountId }).pipe(
177 Stream.runCollect,
178 Effect.map((chunk) =>
179 Array.from(chunk).flatMap((page) =>
180 (page.result ?? []).map((ns) => toAttributes(ns, accountId, ns.namespaceName ?? "")),
181 ),
182 ),
183 );
184 }),
185 read: Effect.fn(function* ({ id, output, olds }) {
186 const { accountId } = yield* yield* CloudflareEnvironment;
187 const acct = output?.accountId ?? accountId;
188 // The name is the identity — a cold read (lost state) lands on the
189 // same deterministic name as reconcile would.
190 const name =
191 output?.name ?? olds?.name ?? (yield* createPhysicalName({ id, lowercase: true }));
192 const observed = yield* getNamespace(acct, name);
193 return observed ? toAttributes(observed, acct, name) : undefined;
194 }),
195 reconcile: Effect.fn(function* ({ id, news, output }) {
196 const { accountId } = yield* yield* CloudflareEnvironment;
197 const name = news.name ?? (yield* createPhysicalName({ id, lowercase: true }));
198
199 // Observe — namespaces are looked up by name; `output` is only a
200 // cache of the same identity. A missing namespace falls through to
201 // the ensure step.
202 const observed = yield* getNamespace(output?.accountId ?? accountId, name);
203 if (observed) {
204 // Existence-only resource — nothing mutable to sync.
205 return toAttributes(observed, output?.accountId ?? accountId, name);
206 }
207
208 // Ensure — create, tolerating the already-exists race by re-reading.
209 const created = yield* wfp
210 .createDispatchNamespace({ accountId, name })
211 .pipe(
212 Effect.catchTag("DispatchNamespaceAlreadyExists", () =>
213 wfp.getDispatchNamespace({ accountId, dispatchNamespace: name }),
214 ),
215 );
216 return toAttributes(created, accountId, name);
217 }),
218 delete: Effect.fn(function* ({ output }) {
219 // Deleting a namespace also deletes the scripts inside it.
220 yield* wfp
221 .deleteDispatchNamespace({
222 accountId: output.accountId,
223 dispatchNamespace: output.name,
224 })
225 .pipe(Effect.catchTag("DispatchNamespaceNotFound", () => Effect.void));
226 }),
227 });
228
229 /**
230 * Read a namespace by name, mapping "gone" (`DispatchNamespaceNotFound`,
231 * Cloudflare error code 100119) to `undefined`.
232 */
233 const getNamespace = (accountId: string, name: string) =>
234 wfp
235 .getDispatchNamespace({ accountId, dispatchNamespace: name })
236 .pipe(Effect.catchTag("DispatchNamespaceNotFound", () => Effect.undefined));
237
238 const toAttributes = (
239 ns: wfp.GetDispatchNamespaceResponse | wfp.CreateDispatchNamespaceResponse,
240 accountId: string,
241 name: string,
242 ): DispatchNamespaceAttributes => ({
243 namespaceId: ns.namespaceId ?? "",
244 name: ns.namespaceName ?? name,
245 accountId,
246 scriptCount: ns.scriptCount ?? 0,
247 trustedWorkers: ns.trustedWorkers ?? false,
248 createdOn: ns.createdOn ?? undefined,
249 modifiedOn: ns.modifiedOn ?? undefined,
250 });