@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 74 lines 2.41 KB
Raw
1 import type { Pipeline } from "cloudflare:pipelines";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import { Worker, WorkerEnvironment } from "../Workers/Worker.ts";
5 import { isLegacyPipeline, type LegacyPipeline } from "./LegacyPipeline.ts";
6 import type { Stream } from "./Stream.ts";
7 import { makeStreamClient, recordSchemaOf, toStreamSendError } from "./StreamCodec.ts";
8 import { WriteStream, type WriteStreamClient } from "./WriteStream.ts";
9
10 /**
11 * Implementation of the {@link WriteStream} service over a native Worker
12 * `pipelines` binding. Registers the binding on the host Worker and, when
13 * the stream has an Effect Schema, encodes records with it before
14 * `send`.
15 * ### Providing the Layer
16 * **Example:** Send from a Worker
17 * ```typescript
18 * Effect.gen(function* () {
19 * const views = yield* Cloudflare.Basin.WriteStream(PageViews);
20 * // ...
21 * }).pipe(Effect.provide(Cloudflare.Basin.WriteStreamBinding));
22 * ```
23 *
24 * @layer
25 * @provides Cloudflare.Pipelines.WriteStream
26 * @product Pipelines
27 * @category Storage & Databases
28 */
29 export const WriteStreamBinding = Layer.effect(
30 WriteStream,
31 Effect.gen(function* () {
32 const env = yield* WorkerEnvironment;
33 const host = yield* Worker;
34
35 return Effect.fn(function* (stream: Stream<any> | LegacyPipeline) {
36 if (!globalThis.__ALCHEMY_RUNTIME__) {
37 yield* host.bind`${stream}`({
38 bindings: [
39 {
40 type: "pipelines",
41 name: stream.LogicalId,
42 // A stream is bound by id; a legacy pipeline by name (the
43 // API identifier of the legacy generation).
44 pipeline: isLegacyPipeline(stream) ? stream.name : stream.streamId,
45 },
46 ],
47 });
48 }
49
50 return makeWriteStreamClient(env, stream);
51 });
52 }),
53 );
54
55 /** Build the producer client over a native Worker `pipelines` binding. */
56 export const makeWriteStreamClient = (
57 env: Record<string, any>,
58 stream: Stream<any> | LegacyPipeline,
59 ): WriteStreamClient<any> => {
60 const raw = Effect.sync(() => (env as Record<string, Pipeline>)[stream.LogicalId]!);
61 return makeStreamClient({
62 schema: recordSchemaOf(stream),
63 raw,
64 sendEncoded: (records) =>
65 raw.pipe(
66 Effect.flatMap((pipeline) =>
67 Effect.tryPromise({
68 try: () => pipeline.send([...records]),
69 catch: toStreamSendError,
70 }),
71 ),
72 ),
73 });
74 };