The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { UnknownCloudflareError } from "@distilled.cloud/cloudflare/Errors"; |
| 2 | import * as k2 from "@distilled.cloud/cloudflare/k2"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Layer from "effect/Layer"; |
| 5 | import { Worker, WorkerEnvironment } from "../Workers/Worker.ts"; |
| 6 | import type { EncodedRecord, ProduceError } from "./K2Types.ts"; |
| 7 | import type { Stream } from "./Stream.ts"; |
| 8 | import { WriteStream } from "./WriteStream.ts"; |
| 9 | import { makeWriteStreamClient } from "./WriteStreamClient.ts"; |
| 10 | |
| 11 | /** |
| 12 | * The runtime shape of a `k2` Worker binding — `env.ORDERS` for a |
| 13 | * `K2.Stream` in a Worker's `env`. `@cloudflare/workers-types` does not |
| 14 | * declare it yet. `send` resolves (does not throw) on API errors; a |
| 15 | * rejected promise means the append outcome is unknown. |
| 16 | */ |
| 17 | export interface K2StreamBinding { |
| 18 | send( |
| 19 | records: Array<{ content: ArrayBuffer | Uint8Array; headers?: { [key: string]: string } }>, |
| 20 | ): Promise< |
| 21 | | { success: true } |
| 22 | | { success: false; error: { code: number; message: string; retryable: boolean } } |
| 23 | >; |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Implementation of the {@link WriteStream} service over the native Worker |
| 28 | * `k2` binding. The stream must have its Worker-binding input enabled (the |
| 29 | * default). |
| 30 | * |
| 31 | * K2 has no local simulation, so a Worker using this layer cannot run under |
| 32 | * `alchemy dev`. |
| 33 | * ### Providing the Layer |
| 34 | * **Example:** Produce from a Worker |
| 35 | * ```typescript |
| 36 | * export default Cloudflare.Worker( |
| 37 | * "Api", |
| 38 | * { main: import.meta.url }, |
| 39 | * Effect.gen(function* () { |
| 40 | * const orders = yield* Cloudflare.K2.WriteStream(Orders); |
| 41 | * return { |
| 42 | * fetch: Effect.gen(function* () { |
| 43 | * yield* orders.send([{ content: "hello" }]); |
| 44 | * return HttpServerResponse.empty({ status: 202 }); |
| 45 | * }), |
| 46 | * }; |
| 47 | * }).pipe(Effect.provide(Cloudflare.K2.WriteStreamBinding)), |
| 48 | * ); |
| 49 | * ``` |
| 50 | * |
| 51 | * @layer |
| 52 | * @provides Cloudflare.K2.WriteStream |
| 53 | * @product K2 |
| 54 | * @category Storage & Databases |
| 55 | */ |
| 56 | export const WriteStreamBinding = Layer.effect( |
| 57 | WriteStream, |
| 58 | Effect.gen(function* () { |
| 59 | const env = yield* WorkerEnvironment; |
| 60 | const host = yield* Worker; |
| 61 | |
| 62 | return Effect.fn(function* (stream: Stream<any>) { |
| 63 | if (!globalThis.__ALCHEMY_RUNTIME__) { |
| 64 | yield* host.bind`${stream}`({ |
| 65 | bindings: [ |
| 66 | { |
| 67 | type: "k2", |
| 68 | name: stream.LogicalId, |
| 69 | stream: stream.streamId, |
| 70 | }, |
| 71 | ], |
| 72 | }); |
| 73 | } |
| 74 | const raw = Effect.sync(() => (env as { [key: string]: K2StreamBinding })[stream.LogicalId]!); |
| 75 | return makeWriteStreamClient(stream.RecordSchema, (records) => |
| 76 | raw.pipe(Effect.flatMap((binding) => sendViaBinding(binding, records))), |
| 77 | ); |
| 78 | }); |
| 79 | }), |
| 80 | ); |
| 81 | |
| 82 | /** |
| 83 | * Append through the native binding. API failures resolve (they do not |
| 84 | * throw), so map their code onto the same typed tags the HTTP path produces. |
| 85 | * A rejected promise means the append outcome is unknown. |
| 86 | */ |
| 87 | export const sendViaBinding = ( |
| 88 | binding: K2StreamBinding, |
| 89 | records: ReadonlyArray<EncodedRecord>, |
| 90 | ): Effect.Effect<void, ProduceError> => |
| 91 | Effect.tryPromise({ |
| 92 | try: () => |
| 93 | binding.send( |
| 94 | records.map((record) => ({ |
| 95 | content: record.content, |
| 96 | ...(record.headers ? { headers: record.headers } : {}), |
| 97 | })), |
| 98 | ), |
| 99 | catch: (cause) => |
| 100 | k2.K2AppendOutcomeUnknown.make({ |
| 101 | code: 10212, |
| 102 | message: `K2 binding send rejected; the batch may have been stored: ${ |
| 103 | cause instanceof Error ? cause.message : String(cause) |
| 104 | }`, |
| 105 | }), |
| 106 | }).pipe( |
| 107 | Effect.flatMap((result) => |
| 108 | result.success ? Effect.void : Effect.fail(toProduceError(result.error)), |
| 109 | ), |
| 110 | ); |
| 111 | |
| 112 | /** Map a binding error code onto the typed tag the HTTP API uses for it. */ |
| 113 | export const toProduceError = (error: { code: number; message: string }): ProduceError => { |
| 114 | const fields = { code: error.code, message: error.message }; |
| 115 | switch (error.code) { |
| 116 | case 10200: |
| 117 | return k2.K2StreamNotFound.make(fields); |
| 118 | case 10204: |
| 119 | return k2.K2InvalidRequest.make(fields); |
| 120 | case 10206: |
| 121 | return k2.K2RequestTooLarge.make(fields); |
| 122 | case 10207: |
| 123 | return k2.K2RecordTooLarge.make(fields); |
| 124 | case 10211: |
| 125 | return k2.K2Unavailable.make(fields); |
| 126 | case 10212: |
| 127 | return k2.K2AppendOutcomeUnknown.make(fields); |
| 128 | default: |
| 129 | return UnknownCloudflareError.make(fields); |
| 130 | } |
| 131 | }; |