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

main
ts 126 lines 4.74 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import type { Pipeline, PipelineRecord } from "cloudflare:pipelines";
4 import * as Data from "effect/Data";
5 import type * as Effect from "effect/Effect";
6 import type { LegacyPipeline } from "./LegacyPipeline.ts";
7 import type { Stream, StreamRecord } from "./Stream.ts";
8
9 /**
10 * Binding service that turns a Pipelines {@link Stream} (or a
11 * {@link LegacyPipeline}) into a {@link WriteStreamClient} you can call
12 * from a Worker's (or Action's) runtime Effect. Also exported as
13 * `Cloudflare.Basin.WriteStream`.
14 *
15 * Producer-only — `send` ingests a batch of records into the stream. When
16 * the stream was declared with an Effect Schema, the client is typed by
17 * it (`send(records: PageView[])`) and every record is validated and
18 * encoded with `Schema.toCodecJson` before it is sent — Cloudflare
19 * accepts schema-violating records and silently drops them later, so
20 * this is the only validation. Without a schema, `send` takes plain JSON
21 * objects.
22 *
23 * Provide one implementation layer:
24 * - {@link WriteStreamBinding} — native Worker `pipelines` binding
25 * - `WriteStreamHttp` — the stream's HTTP ingest endpoint with a scoped
26 * `Pipelines Send` API token (the stream needs `http` enabled)
27 * - `WriteStreamLocal` — the HTTP ingest endpoint with the current
28 * credentials, for Actions and other deploy-time Effects
29 * ### Sending Events
30 * **Example:** Typed producer route
31 * ```typescript
32 * class PageView extends Schema.Class<PageView>("PageView")({
33 * url: Schema.String,
34 * at: Schema.Date,
35 * }) {}
36 *
37 * export const PageViews = Cloudflare.Basin.Stream("PageViews", {
38 * schema: PageView,
39 * });
40 *
41 * export default Cloudflare.Worker(
42 * "Api",
43 * { main: import.meta.url },
44 * Effect.gen(function* () {
45 * const views = yield* Cloudflare.Basin.WriteStream(PageViews);
46 * return {
47 * fetch: Effect.gen(function* () {
48 * yield* views.send([new PageView({ url: "/", at: new Date() })]);
49 * return HttpServerResponse.empty({ status: 202 });
50 * }),
51 * };
52 * }).pipe(Effect.provide(Cloudflare.Basin.WriteStreamBinding)),
53 * );
54 * ```
55 *
56 * **Example:** Untyped stream
57 * ```typescript
58 * const events = yield* Cloudflare.Basin.WriteStream(Events);
59 * yield* events.send([{ event: "click", at: new Date().toISOString() }]);
60 * ```
61 *
62 * ### Handling Errors
63 * **Example:** Recover from a failed send
64 * ```typescript
65 * yield* views.send(batch).pipe(
66 * Effect.catchTag("StreamSendError", (e) =>
67 * Effect.logWarning(`dropped ${batch.length} events: ${e.message}`),
68 * ),
69 * );
70 * ```
71 *
72 * @binding
73 * @product Pipelines
74 * @category Storage & Databases
75 */
76 export interface WriteStream extends Binding.Service<
77 WriteStream,
78 "Cloudflare.Pipelines.WriteStream",
79 (stream: Stream<any> | LegacyPipeline) => Effect.Effect<WriteStreamClient<any>>
80 > {
81 <A, E = never, Req = never>(
82 stream: Stream<A> | Effect.Effect<Stream<A>, E, Req>,
83 ): Effect.Effect<WriteStreamClient<StreamRecord<A>>, E, WriteStream | Req>;
84 <E = never, Req = never>(
85 stream: LegacyPipeline | Effect.Effect<LegacyPipeline, E, Req>,
86 ): Effect.Effect<WriteStreamClient<PipelineRecord>, E, WriteStream | Req>;
87 }
88
89 export const WriteStream = Binding.Service<WriteStream>("Cloudflare.Pipelines.WriteStream");
90
91 /**
92 * Producer client for a Pipelines stream. `A` is the stream's record type
93 * (its Effect Schema's `Type`, or a plain JSON object).
94 */
95 export interface WriteStreamClient<A = PipelineRecord> {
96 /**
97 * The native Worker `pipelines` binding. Only available from
98 * `WriteStreamBinding`; the HTTP/local clients die.
99 */
100 raw: Effect.Effect<Pipeline, never, RuntimeContext>;
101 /** Validate, encode and ingest a batch of records. */
102 send(records: ReadonlyArray<A>): Effect.Effect<void, StreamSendError, RuntimeContext>;
103 /**
104 * Validate and encode records into the JSON objects sent on the wire
105 * (`Schema.toCodecJson` of the stream's schema; identity when untyped).
106 */
107 encode(records: ReadonlyArray<A>): Effect.Effect<ReadonlyArray<PipelineRecord>, StreamSendError>;
108 /** Ingest already-encoded records. */
109 sendEncoded(
110 records: ReadonlyArray<PipelineRecord>,
111 ): Effect.Effect<void, StreamSendError, RuntimeContext>;
112 }
113
114 /**
115 * Raised when records could not be ingested: a record failed the stream's
116 * Effect Schema (`reason: "InvalidRecord"`), or the send itself failed
117 * (`reason: "SendFailed"`).
118 */
119 export class StreamSendError extends Data.TaggedError("StreamSendError")<{
120 message: string;
121 cause?: unknown;
122 /** Why the send failed. Absent on errors raised by older clients. */
123 reason?: "InvalidRecord" | "SendFailed";
124 /** Index of the offending record within the batch, for `InvalidRecord`. */
125 index?: number;
126 }> {}