The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 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 { generateLocalId } from "../LocalRuntime.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { isInstantNamespaceLocalId } from "./InstantNamespaceLocal.ts"; |
| 15 | |
| 16 | export const isNamespace = (value: unknown): value is Namespace => |
| 17 | isResourceOfType(value, "Cloudflare.KV.Namespace"); |
| 18 | |
| 19 | export type NamespaceProps = { |
| 20 | /** |
| 21 | * A human-readable string name for the namespace. |
| 22 | * If omitted, a unique name will be generated. |
| 23 | * @default ${app}-${stage}-${id} |
| 24 | */ |
| 25 | title?: string; |
| 26 | }; |
| 27 | |
| 28 | export type Namespace = Resource< |
| 29 | "Cloudflare.KV.Namespace", |
| 30 | NamespaceProps, |
| 31 | { |
| 32 | title: string; |
| 33 | namespaceId: string; |
| 34 | supportsUrlEncoding: boolean | undefined; |
| 35 | accountId: string; |
| 36 | }, |
| 37 | never, |
| 38 | Providers |
| 39 | >; |
| 40 | |
| 41 | /** |
| 42 | * A Cloudflare Workers KV namespace for key-value storage at the edge. |
| 43 | * |
| 44 | * KV provides eventually-consistent, low-latency reads with global |
| 45 | * replication. Create a namespace as a resource, then bind it to a Worker |
| 46 | * to get/put values at runtime. |
| 47 | * ### Creating a Namespace |
| 48 | * **Example:** Basic KV namespace |
| 49 | * ```typescript |
| 50 | * const kv = yield* Cloudflare.KV.Namespace("MyKV"); |
| 51 | * ``` |
| 52 | * |
| 53 | * ### Binding to a Worker |
| 54 | * **Example:** Using KV inside a Worker |
| 55 | * ```typescript |
| 56 | * const kv = yield* Cloudflare.KV.ReadWriteNamespace(MyKV); |
| 57 | * |
| 58 | * // Read a value |
| 59 | * const value = yield* kv.get("my-key"); |
| 60 | * |
| 61 | * // Write a value |
| 62 | * yield* kv.put("my-key", "hello world"); |
| 63 | * ``` |
| 64 | * |
| 65 | * Provide `Cloudflare.KV.ReadWriteNamespaceBinding` (native Worker |
| 66 | * binding) or `Cloudflare.KV.ReadWriteNamespaceHttp` (scoped HTTP |
| 67 | * token) in the worker's runtime layer. Use `Cloudflare.KV.ReadNamespace` |
| 68 | * / `Cloudflare.KV.WriteNamespace` for least-privilege read- or |
| 69 | * write-only access. |
| 70 | * |
| 71 | * @resource |
| 72 | * @product KV |
| 73 | * @category Storage & Databases |
| 74 | */ |
| 75 | export const Namespace = Resource<Namespace>("Cloudflare.KV.Namespace", { |
| 76 | aliases: ["Cloudflare.KVNamespace"], |
| 77 | }); |
| 78 | |
| 79 | export const ProviderLive = () => |
| 80 | Provider.succeed(Namespace, { |
| 81 | stables: ["namespaceId", "accountId"], |
| 82 | diff: Effect.fn(function* ({ id, olds = {}, news = {}, output }) { |
| 83 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 84 | if (output && "mode" in output && output.mode === "instant") { |
| 85 | return { |
| 86 | action: "replace", |
| 87 | // Titles are unique across modes; an unresolved title may also reuse it. |
| 88 | deleteFirst: !isResolved(news) || news.title === output.title, |
| 89 | } as const; |
| 90 | } |
| 91 | if (!isResolved(news)) return undefined; |
| 92 | if ((output?.accountId ?? accountId) !== accountId) { |
| 93 | return { action: "replace" } as const; |
| 94 | } |
| 95 | const oldTitle = output?.title ?? (yield* createTitle(id, olds.title)); |
| 96 | // Auto-generated titles are engine-owned: the deployed title stays |
| 97 | // authoritative even if the generator would title this id differently |
| 98 | // today. Only an explicit user-provided title can force a rename. |
| 99 | const title = news.title ?? oldTitle; |
| 100 | if (title !== oldTitle) { |
| 101 | return { action: "update" } as const; |
| 102 | } |
| 103 | }), |
| 104 | reconcile: Effect.fn(function* ({ id, news = {}, output }) { |
| 105 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 106 | const title = yield* createTitle(id, news.title); |
| 107 | const acct = output?.accountId ?? accountId; |
| 108 | |
| 109 | // Observe — re-fetch the cached namespace; fall back to a title |
| 110 | // scan so we recover from out-of-band deletes or partial state |
| 111 | // persistence failures. |
| 112 | let observed: |
| 113 | | { |
| 114 | id: string; |
| 115 | title: string; |
| 116 | supportsUrlEncoding?: boolean | null | undefined; |
| 117 | } |
| 118 | | undefined; |
| 119 | if (output?.namespaceId) { |
| 120 | observed = yield* kv |
| 121 | .getNamespace({ |
| 122 | accountId: acct, |
| 123 | namespaceId: output.namespaceId, |
| 124 | }) |
| 125 | .pipe(Effect.catchTag("NamespaceNotFound", () => Effect.undefined)); |
| 126 | } |
| 127 | |
| 128 | // Ensure — create if missing. Cloudflare returns |
| 129 | // `NamespaceTitleAlreadyExists` on a concurrent create; tolerate |
| 130 | // by adopting the namespace with the same title. |
| 131 | if (!observed) { |
| 132 | observed = yield* kv |
| 133 | .createNamespace({ |
| 134 | accountId: acct, |
| 135 | title, |
| 136 | }) |
| 137 | .pipe( |
| 138 | Effect.catchTag("NamespaceTitleAlreadyExists", () => |
| 139 | Effect.gen(function* () { |
| 140 | const match = yield* findNamespaceByTitle(title); |
| 141 | if (match) { |
| 142 | return match; |
| 143 | } |
| 144 | return yield* Effect.die( |
| 145 | `Namespace with title "${title}" already exists but could not be found`, |
| 146 | ); |
| 147 | }), |
| 148 | ), |
| 149 | ); |
| 150 | } |
| 151 | |
| 152 | // Sync — KV's only mutable property is the title. Rename only |
| 153 | // when the observed title drifts from desired so we avoid |
| 154 | // unnecessary API calls on every reconcile. |
| 155 | let namespaceId = observed.id; |
| 156 | let resolvedTitle = observed.title; |
| 157 | let supportsUrlEncoding = observed.supportsUrlEncoding ?? undefined; |
| 158 | if (observed.title !== title) { |
| 159 | const renamed = yield* kv.updateNamespace({ |
| 160 | accountId: acct, |
| 161 | namespaceId: observed.id, |
| 162 | title, |
| 163 | }); |
| 164 | namespaceId = renamed.id; |
| 165 | resolvedTitle = renamed.title; |
| 166 | supportsUrlEncoding = renamed.supportsUrlEncoding ?? undefined; |
| 167 | } |
| 168 | |
| 169 | return { |
| 170 | title: resolvedTitle, |
| 171 | namespaceId, |
| 172 | supportsUrlEncoding, |
| 173 | accountId: acct, |
| 174 | }; |
| 175 | }), |
| 176 | delete: Effect.fn(function* ({ output }) { |
| 177 | yield* kv |
| 178 | .deleteNamespace({ |
| 179 | accountId: output.accountId, |
| 180 | namespaceId: output.namespaceId, |
| 181 | }) |
| 182 | .pipe(Effect.catchTag("NamespaceNotFound", () => Effect.void)); |
| 183 | }), |
| 184 | list: Effect.fn(function* () { |
| 185 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 186 | return yield* kv.listNamespaces.pages({ accountId }).pipe( |
| 187 | Stream.runCollect, |
| 188 | Effect.map((chunk) => |
| 189 | Array.from(chunk).flatMap((page) => |
| 190 | (page.result ?? []) |
| 191 | .filter((ns) => ns.mode !== "instant") |
| 192 | .map((ns) => ({ |
| 193 | title: ns.title, |
| 194 | namespaceId: ns.id, |
| 195 | supportsUrlEncoding: ns.supportsUrlEncoding ?? undefined, |
| 196 | accountId, |
| 197 | })), |
| 198 | ), |
| 199 | ), |
| 200 | ); |
| 201 | }), |
| 202 | read: Effect.fn(function* ({ id, olds, output }) { |
| 203 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 204 | if (output?.namespaceId) { |
| 205 | return yield* kv |
| 206 | .getNamespace({ |
| 207 | accountId: output.accountId, |
| 208 | namespaceId: output.namespaceId, |
| 209 | }) |
| 210 | .pipe( |
| 211 | Effect.map((namespace) => ({ |
| 212 | title: namespace.title, |
| 213 | namespaceId: namespace.id, |
| 214 | supportsUrlEncoding: namespace.supportsUrlEncoding ?? undefined, |
| 215 | accountId: output.accountId, |
| 216 | })), |
| 217 | Effect.catchTag("NamespaceNotFound", () => Effect.undefined), |
| 218 | ); |
| 219 | } |
| 220 | const title = yield* createTitle(id, olds?.title); |
| 221 | const match = yield* findNamespaceByTitle(title); |
| 222 | if (match) { |
| 223 | return { |
| 224 | title: match.title, |
| 225 | namespaceId: match.id, |
| 226 | supportsUrlEncoding: match.supportsUrlEncoding ?? undefined, |
| 227 | accountId, |
| 228 | }; |
| 229 | } |
| 230 | return undefined; |
| 231 | }), |
| 232 | }); |
| 233 | |
| 234 | /** |
| 235 | * Local (dev) provider — the namespace is purely virtual: a `dev:` id keyed |
| 236 | * into the local workerd KV simulator. `toRuntimeBinding` lowers a |
| 237 | * `kv_namespace` binding whose id is `dev:`-prefixed onto the local KV |
| 238 | * service; data persists under `.alchemy/local/kv`. |
| 239 | */ |
| 240 | export const ProviderLocal = () => |
| 241 | Provider.succeed(Namespace, { |
| 242 | stables: ["accountId"], |
| 243 | diff: Effect.fn(function* ({ news = {}, output }) { |
| 244 | const accountId = yield* localAccountId; |
| 245 | if (!output?.namespaceId) return { action: "update" } as const; |
| 246 | if (isInstantNamespaceLocalId(output.namespaceId)) return { action: "replace" } as const; |
| 247 | if (!isResolved(news)) return undefined; |
| 248 | if (output.accountId !== accountId) { |
| 249 | return { action: "replace" } as const; |
| 250 | } |
| 251 | // Fall through to the engine's default prop diff (title renames |
| 252 | // update in place). |
| 253 | }), |
| 254 | read: Effect.fn(function* ({ output }) { |
| 255 | // Purely virtual — the persisted state row is the source of truth. |
| 256 | return output ?? undefined; |
| 257 | }), |
| 258 | reconcile: Effect.fn(function* ({ id, news = {}, output }) { |
| 259 | const accountId = yield* localAccountId; |
| 260 | return { |
| 261 | title: yield* createTitle(id, news.title), |
| 262 | namespaceId: output?.namespaceId ?? generateLocalId(), |
| 263 | supportsUrlEncoding: true, |
| 264 | accountId: output?.accountId ?? accountId, |
| 265 | }; |
| 266 | }), |
| 267 | delete: Effect.fn(function* () { |
| 268 | // The simulator's on-disk data is keyed by the dev id; dropping the |
| 269 | // state row is enough — orphaned blobs are reclaimed with `.alchemy`. |
| 270 | }), |
| 271 | }); |
| 272 | |
| 273 | export const NamespaceProvider = () => |
| 274 | ProviderLayer.dual(Namespace, { |
| 275 | local: () => ProviderLocal(), |
| 276 | live: () => ProviderLive(), |
| 277 | }); |
| 278 | |
| 279 | const createTitle = (id: string, title: string | undefined) => |
| 280 | Effect.gen(function* () { |
| 281 | return title ?? (yield* createPhysicalName({ id })); |
| 282 | }); |
| 283 | |
| 284 | // Cloudflare's `listNamespaces` accepts no title/prefix filter, so |
| 285 | // adoption-by-name has to scan every page. Use the paginated |
| 286 | // `.items` stream off the un-yielded operation method (yielding |
| 287 | // `kv.listNamespaces` collapses it to a single-page call). |
| 288 | const findNamespaceByTitle = Effect.fn(function* (title: string) { |
| 289 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 290 | return yield* kv.listNamespaces.items({ accountId }).pipe( |
| 291 | Stream.filter((ns) => ns.title === title && ns.mode !== "instant"), |
| 292 | Stream.runHead, |
| 293 | Effect.map(Option.getOrUndefined), |
| 294 | ); |
| 295 | }); |