The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as kv from "@distilled.cloud/cloudflare/kv"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import * as ProviderLayer from "alchemy/Local/ProviderLayer"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { isResourceOfType, Resource } from "alchemy/Resource"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 11 | import { localAccountId } from "../LocalAccount.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { |
| 14 | createInstantNamespaceLocalId, |
| 15 | isInstantNamespaceLocalId, |
| 16 | } from "./InstantNamespaceLocal.ts"; |
| 17 | import { NamespaceModeMismatch } from "./NamespaceTypes.ts"; |
| 18 | |
| 19 | export const isInstantNamespace = (value: unknown): value is InstantNamespace => |
| 20 | isResourceOfType(value, "Cloudflare.KV.InstantNamespace"); |
| 21 | |
| 22 | export type InstantNamespaceProps = { |
| 23 | /** |
| 24 | * A human-readable string name for the namespace. |
| 25 | * If omitted, a unique name will be generated. |
| 26 | * @default ${app}-${stage}-${id} |
| 27 | */ |
| 28 | title?: string; |
| 29 | }; |
| 30 | |
| 31 | export type InstantNamespace = Resource< |
| 32 | "Cloudflare.KV.InstantNamespace", |
| 33 | InstantNamespaceProps, |
| 34 | { |
| 35 | /** Namespace storage mode, fixed at creation. */ |
| 36 | mode: "instant"; |
| 37 | /** Human-readable namespace title. */ |
| 38 | title: string; |
| 39 | /** Cloudflare namespace identifier, stable across title updates. */ |
| 40 | namespaceId: string; |
| 41 | /** Whether keys written in URLs are URL-decoded before storage. */ |
| 42 | supportsUrlEncoding: boolean | undefined; |
| 43 | /** Account that owns the namespace. */ |
| 44 | accountId: string; |
| 45 | }, |
| 46 | never, |
| 47 | Providers |
| 48 | >; |
| 49 | |
| 50 | /** |
| 51 | * A Cloudflare Workers KV Instant namespace, powered by Quicksilver. |
| 52 | * |
| 53 | * Requires private beta access. Uses the same Worker binding as classic KV, |
| 54 | * with fast global replication and no cold reads. Namespace mode is fixed at |
| 55 | * creation; switching between Namespace and InstantNamespace replaces it. |
| 56 | * |
| 57 | * Metadata is unsupported. Use get instead of getWithMetadata, and do not |
| 58 | * pass metadata to put. Listing returns all matching keys without pagination. |
| 59 | * The beta limits namespaces to 1 MB and 10,000 pairs, keys to 300 bytes, |
| 60 | * and writes to one per namespace per second. |
| 61 | * |
| 62 | * Storage and put/delete/list operations cost substantially more than classic |
| 63 | * KV; reads cost less. See https://blog.cloudflare.com/workers-kv-instant/ |
| 64 | * for pricing and private beta availability. |
| 65 | * |
| 66 | * ### Creating an Instant Namespace |
| 67 | * **Example:** Application configuration |
| 68 | * ```typescript |
| 69 | * const config = yield* Cloudflare.KV.InstantNamespace("Config"); |
| 70 | * ``` |
| 71 | * |
| 72 | * ### Binding to a Worker |
| 73 | * **Example:** Read configuration using the existing KV binding |
| 74 | * ```typescript |
| 75 | * const client = yield* Cloudflare.KV.ReadNamespace(config); |
| 76 | * const enabled = yield* client.get("feature-enabled"); |
| 77 | * ``` |
| 78 | * |
| 79 | * Provide ReadNamespaceBinding on the Worker runtime. WriteNamespace and |
| 80 | * ReadWriteNamespace also accept Instant namespaces, as do their Http and |
| 81 | * Local capability implementations. |
| 82 | * |
| 83 | * During `alchemy dev`, the namespace uses persistent local KV storage without |
| 84 | * cloud credentials or beta access. Local mode rejects metadata and lists all |
| 85 | * matching keys in one response. Local keys are limited to 300 UTF-8 bytes. |
| 86 | * Namespace storage quotas, key-count limits, global replication, billing, |
| 87 | * and write throttling are not emulated. Use Alchemy.remote() |
| 88 | * to opt into a live namespace during development (requires beta access). |
| 89 | * |
| 90 | * @resource |
| 91 | * @product KV |
| 92 | * @category Storage & Databases |
| 93 | */ |
| 94 | export const InstantNamespace = Resource<InstantNamespace>("Cloudflare.KV.InstantNamespace"); |
| 95 | |
| 96 | const ProviderLive = () => |
| 97 | Provider.succeed(InstantNamespace, { |
| 98 | stables: ["namespaceId", "accountId"], |
| 99 | diff: Effect.fn(function* ({ id, olds = {}, news = {}, output }) { |
| 100 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 101 | if (output && output.mode !== "instant") { |
| 102 | return { |
| 103 | action: "replace", |
| 104 | // Titles are unique across modes; an unresolved title may also reuse it. |
| 105 | deleteFirst: !isResolved(news) || news.title === output.title, |
| 106 | } as const; |
| 107 | } |
| 108 | if (!isResolved(news)) return undefined; |
| 109 | if ((output?.accountId ?? accountId) !== accountId) { |
| 110 | return { action: "replace" } as const; |
| 111 | } |
| 112 | const oldTitle = output?.title ?? (yield* createTitle(id, olds.title)); |
| 113 | // Auto-generated titles are engine-owned: the deployed title stays |
| 114 | // authoritative even if the generator would title this id differently |
| 115 | // today. Only an explicit user-provided title can force a rename. |
| 116 | const title = news.title ?? oldTitle; |
| 117 | if (title !== oldTitle) { |
| 118 | return { action: "update" } as const; |
| 119 | } |
| 120 | }), |
| 121 | reconcile: Effect.fn(function* ({ id, news = {}, output }) { |
| 122 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 123 | const title = news.title ?? output?.title ?? (yield* createTitle(id, undefined)); |
| 124 | const acct = output?.accountId ?? accountId; |
| 125 | |
| 126 | // Observe — re-fetch the cached namespace; fall back to a title |
| 127 | // scan so we recover from out-of-band deletes or partial state |
| 128 | // persistence failures. |
| 129 | let observed: |
| 130 | | { |
| 131 | id: string; |
| 132 | title: string; |
| 133 | supportsUrlEncoding?: boolean | null | undefined; |
| 134 | mode?: "instant" | null; |
| 135 | } |
| 136 | | undefined; |
| 137 | if (output?.namespaceId) { |
| 138 | observed = yield* kv |
| 139 | .getNamespace({ |
| 140 | accountId: acct, |
| 141 | namespaceId: output.namespaceId, |
| 142 | }) |
| 143 | .pipe(Effect.catchTag("NamespaceNotFound", () => Effect.undefined)); |
| 144 | } |
| 145 | |
| 146 | // Ensure — create if missing. Cloudflare returns |
| 147 | // `NamespaceTitleAlreadyExists` on a concurrent create; tolerate |
| 148 | // by adopting the namespace with the same title. |
| 149 | if (!observed) { |
| 150 | observed = yield* kv |
| 151 | .createNamespace({ |
| 152 | accountId: acct, |
| 153 | title, |
| 154 | mode: "instant", |
| 155 | }) |
| 156 | .pipe( |
| 157 | Effect.catchTag("NamespaceTitleAlreadyExists", (error) => |
| 158 | Effect.gen(function* () { |
| 159 | const match = yield* findNamespaceByTitle(title); |
| 160 | if (match) { |
| 161 | return match; |
| 162 | } |
| 163 | return yield* error; |
| 164 | }), |
| 165 | ), |
| 166 | ); |
| 167 | } |
| 168 | |
| 169 | if (observed.mode !== "instant") { |
| 170 | return yield* new NamespaceModeMismatch({ namespaceId: observed.id, expected: "instant" }); |
| 171 | } |
| 172 | |
| 173 | // Sync — KV's only mutable property is the title. Rename only |
| 174 | // when the observed title drifts from desired so we avoid |
| 175 | // unnecessary API calls on every reconcile. |
| 176 | let namespaceId = observed.id; |
| 177 | let resolvedTitle = observed.title; |
| 178 | let supportsUrlEncoding = observed.supportsUrlEncoding ?? undefined; |
| 179 | if (observed.title !== title) { |
| 180 | const renamed = yield* kv.updateNamespace({ |
| 181 | accountId: acct, |
| 182 | namespaceId: observed.id, |
| 183 | title, |
| 184 | }); |
| 185 | namespaceId = renamed.id; |
| 186 | resolvedTitle = renamed.title; |
| 187 | supportsUrlEncoding = renamed.supportsUrlEncoding ?? undefined; |
| 188 | } |
| 189 | |
| 190 | return { |
| 191 | mode: "instant" as const, |
| 192 | title: resolvedTitle, |
| 193 | namespaceId, |
| 194 | supportsUrlEncoding, |
| 195 | accountId: acct, |
| 196 | }; |
| 197 | }), |
| 198 | delete: Effect.fn(function* ({ output }) { |
| 199 | yield* kv |
| 200 | .deleteNamespace({ |
| 201 | accountId: output.accountId, |
| 202 | namespaceId: output.namespaceId, |
| 203 | }) |
| 204 | .pipe(Effect.catchTag("NamespaceNotFound", () => Effect.void)); |
| 205 | }), |
| 206 | list: Effect.fn(function* () { |
| 207 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 208 | return yield* kv.listNamespaces.pages({ accountId }).pipe( |
| 209 | Stream.runCollect, |
| 210 | Effect.map((chunk) => |
| 211 | Array.from(chunk).flatMap((page) => |
| 212 | (page.result ?? []) |
| 213 | .filter((ns) => ns.mode === "instant") |
| 214 | .map((ns) => ({ |
| 215 | mode: "instant" as const, |
| 216 | title: ns.title, |
| 217 | namespaceId: ns.id, |
| 218 | supportsUrlEncoding: ns.supportsUrlEncoding ?? undefined, |
| 219 | accountId, |
| 220 | })), |
| 221 | ), |
| 222 | ), |
| 223 | ); |
| 224 | }), |
| 225 | read: Effect.fn(function* ({ id, olds, output }) { |
| 226 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 227 | if (output?.namespaceId) { |
| 228 | return yield* kv |
| 229 | .getNamespace({ |
| 230 | accountId: output.accountId, |
| 231 | namespaceId: output.namespaceId, |
| 232 | }) |
| 233 | .pipe( |
| 234 | Effect.flatMap((namespace) => |
| 235 | namespace.mode !== "instant" |
| 236 | ? Effect.fail( |
| 237 | new NamespaceModeMismatch({ namespaceId: namespace.id, expected: "instant" }), |
| 238 | ) |
| 239 | : Effect.succeed({ |
| 240 | mode: "instant" as const, |
| 241 | title: namespace.title, |
| 242 | namespaceId: namespace.id, |
| 243 | supportsUrlEncoding: namespace.supportsUrlEncoding ?? undefined, |
| 244 | accountId: output.accountId, |
| 245 | }), |
| 246 | ), |
| 247 | Effect.catchTag("NamespaceNotFound", () => Effect.undefined), |
| 248 | ); |
| 249 | } |
| 250 | const title = yield* createTitle(id, olds?.title); |
| 251 | const match = yield* findNamespaceByTitle(title); |
| 252 | if (match) { |
| 253 | return { |
| 254 | mode: "instant" as const, |
| 255 | title: match.title, |
| 256 | namespaceId: match.id, |
| 257 | supportsUrlEncoding: match.supportsUrlEncoding ?? undefined, |
| 258 | accountId, |
| 259 | }; |
| 260 | } |
| 261 | return undefined; |
| 262 | }), |
| 263 | }); |
| 264 | |
| 265 | /** Persistent local workerd namespace; no Cloudflare API calls. */ |
| 266 | const ProviderLocal = () => |
| 267 | Provider.succeed(InstantNamespace, { |
| 268 | stables: ["namespaceId", "accountId"], |
| 269 | diff: Effect.fn(function* ({ output }) { |
| 270 | const accountId = yield* localAccountId; |
| 271 | if (output && !isInstantNamespaceLocalId(output.namespaceId)) { |
| 272 | return { action: "replace" } as const; |
| 273 | } |
| 274 | if (output && output.accountId !== accountId) return { action: "replace" } as const; |
| 275 | }), |
| 276 | read: Effect.fn(function* ({ output }) { |
| 277 | return output ?? undefined; |
| 278 | }), |
| 279 | reconcile: Effect.fn(function* ({ id, news = {}, output }) { |
| 280 | const accountId = yield* localAccountId; |
| 281 | return { |
| 282 | mode: "instant" as const, |
| 283 | title: news.title ?? output?.title ?? (yield* createTitle(id, undefined)), |
| 284 | namespaceId: output?.namespaceId ?? createInstantNamespaceLocalId(), |
| 285 | supportsUrlEncoding: true, |
| 286 | accountId: output?.accountId ?? accountId, |
| 287 | }; |
| 288 | }), |
| 289 | delete: Effect.fn(function* () { |
| 290 | // Matches classic local KV: orphaned storage is reclaimed with .alchemy. |
| 291 | }), |
| 292 | }); |
| 293 | |
| 294 | export const InstantNamespaceProvider = () => |
| 295 | ProviderLayer.dual(InstantNamespace, { |
| 296 | local: () => ProviderLocal(), |
| 297 | live: () => ProviderLive(), |
| 298 | }); |
| 299 | |
| 300 | const createTitle = (id: string, title: string | undefined) => |
| 301 | Effect.gen(function* () { |
| 302 | return title ?? (yield* createPhysicalName({ id })); |
| 303 | }); |
| 304 | |
| 305 | // Cloudflare's `listNamespaces` accepts no title/prefix filter, so |
| 306 | // adoption-by-name has to scan every page. Use the paginated |
| 307 | // `.items` stream off the un-yielded operation method (yielding |
| 308 | // `kv.listNamespaces` collapses it to a single-page call). |
| 309 | const findNamespaceByTitle = Effect.fn(function* (title: string) { |
| 310 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 311 | return yield* kv.listNamespaces.items({ accountId }).pipe( |
| 312 | Stream.filter((ns) => ns.title === title && ns.mode === "instant"), |
| 313 | Stream.runHead, |
| 314 | Effect.map(Option.getOrUndefined), |
| 315 | ); |
| 316 | }); |