@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 690 lines 23.6 KB
Raw
1 import * as pipelines from "@distilled.cloud/cloudflare/pipelines";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import type { PropsInput } from "alchemy/Input";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource, type ResourceClass } from "alchemy/Resource";
8 import * as Effect from "effect/Effect";
9 import * as Effectable from "effect/Effectable";
10 import * as Predicate from "effect/Predicate";
11 import * as Schedule from "effect/Schedule";
12 import type * as Schema from "effect/Schema";
13 import * as EffectStream from "effect/Stream";
14 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
15 import type { Providers } from "../Providers.ts";
16 import {
17 canonicalStreamFields,
18 isEffectSchema,
19 StreamSchemaUnsupported,
20 streamFieldsFromSchema,
21 type StreamFieldsSchema,
22 } from "./StreamSchema.ts";
23
24 const StreamTypeId = "Cloudflare.Pipelines.Stream" as const;
25 type StreamTypeId = typeof StreamTypeId;
26
27 /**
28 * Input format of events ingested by the stream.
29 */
30 export interface StreamFormat {
31 /** Only JSON ingestion is supported. */
32 type: "json";
33 /**
34 * Accept events of any shape (no schema enforcement).
35 */
36 unstructured?: boolean;
37 /**
38 * How timestamps are rendered in ingested JSON.
39 * @default "rfc3339"
40 */
41 timestampFormat?: "rfc3339" | "unix_millis";
42 /** How decimals are encoded in ingested JSON. */
43 decimalEncoding?: "number" | "string" | "bytes";
44 }
45
46 /**
47 * HTTP ingest endpoint configuration. Mutable in place.
48 */
49 export interface StreamHttp {
50 /**
51 * Whether the stream exposes an HTTP ingest endpoint.
52 * @default true
53 */
54 enabled?: boolean;
55 /**
56 * Whether requests to the HTTP endpoint must carry a Cloudflare API
57 * token with the `Pipelines Send` permission.
58 * @default false
59 */
60 authentication?: boolean;
61 /** CORS configuration for browser-originated ingestion. */
62 cors?: {
63 /** Allowed origins, e.g. `["https://app.example.com"]` or `["*"]`. */
64 origins?: string[];
65 };
66 }
67
68 export interface StreamProps {
69 /**
70 * Name of the stream. Unique per account; must be alphanumeric and
71 * underscores only (it is referenced as a SQL table name). If omitted,
72 * a unique name is generated from the app, stage, and logical ID.
73 * Changing the name triggers a replacement.
74 * @default ${app}_${id}_${stage}_${suffix}
75 */
76 name?: string;
77 /**
78 * Structured schema of ingested events — either an explicit field list
79 * or an Effect Schema (`Schema.Struct` / `Schema.Class`), which is
80 * converted to the field list and also types and encodes the records
81 * sent through `WriteStream` / `StreamSink`.
82 *
83 * Immutable — changing the (derived) field list triggers a replacement,
84 * which drops buffered events and dependent pipelines. Equivalent
85 * spellings (a field list ⇄ the matching Effect Schema) are a no-op.
86 * When omitted, the stream accepts unstructured JSON events.
87 */
88 schema?: StreamFieldsSchema | Schema.Top;
89 /**
90 * Input format configuration. Immutable — changing it triggers a
91 * replacement.
92 * @default { type: "json" }
93 */
94 format?: StreamFormat;
95 /**
96 * HTTP ingest endpoint configuration. Mutable in place.
97 *
98 * - omitted / `false` — no public HTTP endpoint (`{ enabled: false }`)
99 * - `true` — endpoint enabled, API-token authentication required
100 * - an object — explicit settings
101 * @default false
102 */
103 http?: boolean | StreamHttp;
104 /**
105 * Whether Workers can send events to this stream via a `pipelines`
106 * binding. Mutable in place.
107 * @default { enabled: true }
108 */
109 workerBinding?: {
110 /** Whether the Worker binding is enabled. */
111 enabled: boolean;
112 };
113 }
114
115 export interface StreamAttributes {
116 /** Cloudflare-assigned stream identifier. */
117 streamId: string;
118 /** Account that owns the stream. */
119 accountId: string;
120 /** Stream name (unique per account). */
121 name: string;
122 /** HTTP ingest endpoint URL, when HTTP ingestion is enabled. */
123 endpoint: string | undefined;
124 /** Whether the HTTP ingest endpoint is enabled. */
125 httpEnabled: boolean;
126 /** Whether the HTTP ingest endpoint requires authentication. */
127 httpAuthentication: boolean;
128 /** Allowed CORS origins of the HTTP ingest endpoint. */
129 corsOrigins: string[] | undefined;
130 /** Whether Workers can send events via a `pipelines` binding. */
131 workerBindingEnabled: boolean;
132 /** Current version of the stream. */
133 version: number;
134 /** When the stream was created. */
135 createdAt: string;
136 /** When the stream was last modified. */
137 modifiedAt: string;
138 }
139
140 /**
141 * A Pipelines stream. `A` is the record type sent through `WriteStream` /
142 * `StreamSink` — the Effect Schema's `Type` when the stream was declared
143 * with one.
144 */
145 export interface Stream<A = unknown> extends Resource<
146 StreamTypeId,
147 StreamProps,
148 StreamAttributes,
149 never,
150 Providers
151 > {
152 /**
153 * The Effect Schema the stream was declared with, if any. Used by the
154 * producer clients to encode records; never persisted.
155 */
156 readonly RecordSchema: Schema.Top | undefined;
157 /** Phantom record type. */
158 readonly "~record"?: A;
159 }
160
161 /**
162 * The record type a producer sends to a `Stream<A>`: the declared Effect
163 * Schema's `Type`, or an untyped JSON object.
164 */
165 export type StreamRecord<A> = unknown extends A ? Record<string, unknown> : A;
166
167 /**
168 * Props of a stream declared with an Effect Schema.
169 */
170 export type StreamSchemaProps<S extends Schema.Top> = PropsInput<Omit<StreamProps, "schema">> & {
171 schema: S;
172 };
173
174 const StreamResource = Resource<Stream>(StreamTypeId);
175
176 /**
177 * The Stream constructor: the plain resource constructor plus an overload
178 * that infers the record type from an Effect Schema `schema`.
179 */
180 export type StreamClass = {
181 <const S extends Schema.Top>(
182 id: string,
183 props: StreamSchemaProps<S>,
184 ): Effect.Effect<Stream<S["Type"]>, never, Providers>;
185 } & ResourceClass<Stream>;
186
187 /**
188 * Convert an Effect Schema `schema` prop into the persisted field list and
189 * keep the schema aside for the producer clients. Dies with a clear
190 * {@link StreamSchemaUnsupported} when the schema has no stream
191 * representation — this runs while the program is constructed, before
192 * anything is planned.
193 */
194 const normalizeStreamProps = (
195 props: unknown,
196 ): Effect.Effect<{ props: unknown; recordSchema: Schema.Top | undefined }> =>
197 Effect.suspend((): Effect.Effect<{ props: unknown; recordSchema: Schema.Top | undefined }> => {
198 const schema = (props as { schema?: unknown } | undefined)?.schema;
199 if (!isEffectSchema(schema)) {
200 return Effect.succeed({ props, recordSchema: undefined });
201 }
202 return resolveSchema(schema).pipe(
203 Effect.map((resolved) => ({
204 props: { ...(props as object), schema: resolved },
205 recordSchema: schema,
206 })),
207 Effect.orDie,
208 );
209 });
210
211 const constructStream = (id: string, props: unknown) =>
212 Effect.gen(function* () {
213 let recordSchema: Schema.Top | undefined;
214 const capture = (n: { props: unknown; recordSchema: Schema.Top | undefined }) => {
215 recordSchema = n.recordSchema;
216 return n.props;
217 };
218 const normalized = Effect.isEffect(props)
219 ? // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- props are untyped; Effect-valued props are resolved by the engine
220 (props as Effect.Effect<unknown>).pipe(
221 Effect.flatMap(normalizeStreamProps),
222 Effect.map(capture),
223 )
224 : capture(yield* normalizeStreamProps(props));
225 const construct = StreamResource as unknown as (
226 id: string,
227 props: unknown,
228 ) => Effect.Effect<Stream, never, Providers>;
229 const stream = yield* construct(id, normalized);
230 (stream as { RecordSchema: Schema.Top | undefined }).RecordSchema = recordSchema;
231 return stream;
232 });
233
234 /**
235 * A Cloudflare Pipelines stream — the ingestion endpoint of the Pipelines
236 * product (also exported as `Cloudflare.Basin.Stream`). Events are sent to
237 * a stream from Workers (`WriteStream` / `StreamSink`) or over HTTP,
238 * transformed by a SQL {@link Pipeline}, and written to a {@link Sink}.
239 *
240 * The stream's `schema` and `format` are fixed at creation (changing them
241 * triggers a replacement, which drops buffered events and dependent
242 * pipelines); the HTTP endpoint and Worker-binding toggles are mutable in
243 * place.
244 *
245 * Pipelines is ingest-only — there is no event source on a stream. To
246 * process data after it lands, subscribe to the sink's bucket with
247 * `Cloudflare.R2.BucketEventNotification`.
248 *
249 * Cloudflare accepts records that violate a structured stream's schema
250 * (they are dropped later, during processing). Declare the schema as an
251 * Effect Schema to have the producer clients validate and encode every
252 * record before it is sent.
253 *
254 * :::caution
255 * A stream declared without `http` has **no** public ingest endpoint
256 * (`http: { enabled: false }`). Earlier versions sent nothing, and
257 * Cloudflare's default is a public, unauthenticated endpoint. Existing
258 * streams are updated in place on the next deploy; set `http: true`
259 * (authenticated) or `http: { enabled: true }` to keep an endpoint.
260 * :::
261 *
262 * ### Creating a Stream
263 * **Example:** Unstructured stream with default settings
264 * ```typescript
265 * const stream = yield* Cloudflare.Basin.Stream("events", {});
266 * ```
267 *
268 * **Example:** Structured stream from an Effect Schema
269 * ```typescript
270 * class PageView extends Schema.Class<PageView>("PageView")({
271 * url: Schema.String,
272 * at: Schema.Date,
273 * tags: Schema.Array(Schema.String),
274 * user: Schema.optional(Schema.Struct({ id: Schema.String })),
275 * }) {}
276 *
277 * // Stream<PageView>: WriteStream / StreamSink are typed and encode records
278 * const stream = yield* Cloudflare.Basin.Stream("PageViews", {
279 * schema: PageView,
280 * });
281 * ```
282 *
283 * **Example:** Structured stream with an explicit field list
284 * ```typescript
285 * const stream = yield* Cloudflare.Basin.Stream("clicks", {
286 * schema: {
287 * fields: [
288 * { type: "string", name: "url", required: true },
289 * { type: "timestamp", name: "ts", unit: "millisecond" },
290 * { type: "list", name: "tags", items: { type: "string" } },
291 * {
292 * type: "struct",
293 * name: "user",
294 * fields: [{ type: "string", name: "id" }],
295 * },
296 * ],
297 * },
298 * });
299 * ```
300 *
301 * ### HTTP ingestion
302 * **Example:** Authenticated endpoint
303 * ```typescript
304 * const stream = yield* Cloudflare.Basin.Stream("events", { http: true });
305 * // POST a JSON array to stream.endpoint with a `Pipelines Send` token,
306 * // or use Cloudflare.Basin.WriteStreamHttp / WriteStreamLocal.
307 * ```
308 *
309 * **Example:** Public endpoint with CORS
310 * ```typescript
311 * const stream = yield* Cloudflare.Basin.Stream("beacons", {
312 * http: {
313 * enabled: true,
314 * authentication: false,
315 * cors: { origins: ["https://app.example.com"] },
316 * },
317 * });
318 * ```
319 *
320 * ### Wiring into a Pipeline
321 * **Example:** Stream → SQL Pipeline → Sink
322 * ```typescript
323 * const pipeline = yield* Cloudflare.Basin.Pipeline("etl", {
324 * sql: Output.interpolate`INSERT INTO ${sink.name} SELECT * FROM ${stream.name}`,
325 * });
326 * ```
327 *
328 * @see https://developers.cloudflare.com/pipelines/
329 *
330 * @resource
331 * @product Pipelines
332 * @category Storage & Databases
333 */
334 export const Stream: StreamClass = Object.assign(
335 (...args: [id: string, props?: unknown] | [methods: object]) =>
336 typeof args[0] === "object"
337 ? Object.assign(Stream, args[0])
338 : constructStream(args[0], (args as [string, unknown])[1]),
339 StreamResource,
340 Effectable.Prototype({
341 label: `Resource<${StreamTypeId}>`,
342 evaluate: () => Effect.succeed((id: string, props: unknown) => constructStream(id, props)),
343 }),
344 ) as unknown as StreamClass;
345
346 /**
347 * Returns true if the given value is a Stream resource.
348 */
349 export const isStream = (value: unknown): value is Stream =>
350 Predicate.hasProperty(value, "Type") && value.Type === StreamTypeId;
351
352 export const StreamProvider = () =>
353 Provider.succeed(Stream, {
354 stables: ["streamId", "accountId", "name", "createdAt"],
355
356 diff: Effect.fn(function* ({ id, olds, news, output }) {
357 const { accountId } = yield* yield* CloudflareEnvironment;
358 if (!isResolved(news)) return undefined;
359 if ((output?.accountId ?? accountId) !== accountId) {
360 return { action: "replace" } as const;
361 }
362 const o = olds as StreamProps | undefined;
363 const newName = yield* streamName(id, news.name);
364 const oldName = output?.name ?? (yield* streamName(id, o?.name));
365 if (newName !== oldName) {
366 return { action: "replace" } as const;
367 }
368 if (o === undefined) return undefined;
369 // Schema and format are immutable. Compare CANONICAL derived values
370 // so equivalent spellings (field list ⇄ Effect Schema, omitted ⇄
371 // explicit defaults) never replace.
372 const newSchema = yield* canonicalSchema(news.schema);
373 const oldSchema = yield* canonicalSchema(o.schema);
374 if (!stableEquals(newSchema, oldSchema)) {
375 return { action: "replace" } as const;
376 }
377 if (!stableEquals(canonicalFormat(news.format), canonicalFormat(o.format))) {
378 return { action: "replace" } as const;
379 }
380 if (output === undefined) return undefined;
381 // http/workerBinding are patchable: diff desired against the last
382 // observed state, so the secure http default reaches streams created
383 // before it existed.
384 const httpConverged = httpMatches(desiredHttp(news.http), {
385 enabled: output.httpEnabled,
386 authentication: output.httpAuthentication,
387 origins: output.corsOrigins,
388 });
389 const bindingConverged =
390 news.workerBinding === undefined ||
391 news.workerBinding.enabled === output.workerBindingEnabled;
392 return httpConverged && bindingConverged
393 ? ({ action: "noop" } as const)
394 : ({ action: "update" } as const);
395 }),
396
397 read: Effect.fn(function* ({ id, output, olds }) {
398 const { accountId } = yield* yield* CloudflareEnvironment;
399 const acct = output?.accountId ?? accountId;
400 if (output?.streamId) {
401 const observed = yield* getStream(acct, output.streamId);
402 if (observed) return toAttributes(observed, acct);
403 }
404 // Cold read — stream names are unique per account, so an exact name
405 // match identifies the resource. A generated name embeds the
406 // instance id (proof of ownership); a user-provided name does not,
407 // so gate takeover behind the adopt policy.
408 const name = yield* streamName(id, olds?.name);
409 const match = yield* findStreamByName(acct, name);
410 if (match) {
411 const attrs = toAttributes(match, acct);
412 return olds?.name !== undefined ? Unowned(attrs) : attrs;
413 }
414 return undefined;
415 }),
416
417 reconcile: Effect.fn(function* ({ id, news, output }) {
418 const { accountId } = yield* yield* CloudflareEnvironment;
419 const name = yield* streamName(id, news.name);
420 const http = desiredHttp(news.http);
421
422 // 1. Observe — the cached streamId is a hint, not a guarantee; a
423 // missing stream falls through to a name lookup and then create.
424 let observed = output?.streamId
425 ? yield* getStream(output.accountId ?? accountId, output.streamId)
426 : undefined;
427 if (!observed) {
428 observed = yield* findStreamByName(accountId, name);
429 }
430
431 // 2. Ensure — create when missing. Stream names are unique, so an
432 // AlreadyExists is a race (or recovery from a lost state write):
433 // fall back to the name lookup.
434 if (!observed) {
435 const schema = yield* resolveSchema(news.schema);
436 observed = yield* pipelines
437 .createStream({
438 accountId,
439 name,
440 format: news.format,
441 // The distilled field union does not model nested `items` /
442 // `fields`; they pass through to the wire verbatim.
443 schema: schema as pipelines.CreateStreamRequest["schema"],
444 http,
445 workerBinding: news.workerBinding,
446 })
447 .pipe(
448 Effect.catchTag("StreamAlreadyExists", (error) =>
449 findStreamByName(accountId, name).pipe(
450 Effect.flatMap((match) => (match ? Effect.succeed(match) : Effect.fail(error))),
451 ),
452 ),
453 );
454 }
455
456 // 3. Sync — http and workerBinding are the only mutable aspects.
457 // Diff observed cloud state against the declared desired state
458 // and PATCH only the delta; skip the API entirely on a no-op.
459 const patch: pipelines.PatchStreamRequest = {
460 accountId,
461 streamId: observed.id,
462 };
463 let dirty = false;
464 if (
465 !httpMatches(http, {
466 enabled: observed.http.enabled,
467 authentication: observed.http.authentication,
468 origins: observed.http.cors?.origins,
469 })
470 ) {
471 patch.http = http;
472 dirty = true;
473 }
474 if (
475 news.workerBinding !== undefined &&
476 news.workerBinding.enabled !== observed.workerBinding.enabled
477 ) {
478 patch.workerBinding = { enabled: news.workerBinding.enabled };
479 dirty = true;
480 }
481 if (dirty) {
482 observed = yield* pipelines.patchStream(patch);
483 }
484
485 return toAttributes(observed, accountId);
486 }),
487
488 delete: Effect.fn(function* ({ output }) {
489 // A dependent pipeline's own deletion may still be propagating —
490 // ride out `StreamInUse` (HTTP 422 "still in use") with a bounded
491 // retry. A stream that is already gone is success.
492 yield* pipelines
493 .deleteStream({
494 accountId: output.accountId,
495 streamId: output.streamId,
496 })
497 .pipe(
498 Effect.retry({
499 while: (e) => e._tag === "StreamInUse",
500 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(8)]),
501 }),
502 Effect.catchTags({
503 StreamNotFound: () => Effect.void,
504 InvalidStreamId: () => Effect.void,
505 }),
506 );
507 }),
508
509 // Account-scoped collection: exhaustively paginate every stream in the
510 // account and hydrate each into the same Attributes shape `read`
511 // returns. The list item shape is structurally identical to the
512 // get/create response consumed by `toAttributes`.
513 list: Effect.fn(function* () {
514 const { accountId } = yield* yield* CloudflareEnvironment;
515 return yield* pipelines.listStreams.pages({ accountId }).pipe(
516 EffectStream.runCollect,
517 Effect.map((chunk) =>
518 Array.from(chunk).flatMap((page) =>
519 (page.result ?? []).map((s) => toAttributes(s, accountId)),
520 ),
521 ),
522 );
523 }),
524 });
525
526 /**
527 * The subset of stream state shared by get/list/create/patch responses.
528 */
529 interface ObservedStream {
530 id: string;
531 name: string;
532 endpoint?: string | null;
533 http: {
534 enabled: boolean;
535 authentication: boolean;
536 cors?: { origins?: readonly string[] | null } | null;
537 };
538 workerBinding: { enabled: boolean };
539 version: number;
540 createdAt: string;
541 modifiedAt: string;
542 }
543
544 // Pipelines entity names must be alphanumeric/underscore only (they are
545 // referenced as SQL table names), so swap the default hyphen delimiter
546 // for underscores.
547 const streamName = (id: string, name: string | undefined) =>
548 Effect.gen(function* () {
549 if (name) return name;
550 const generated = yield* createPhysicalName({
551 id,
552 lowercase: true,
553 delimiter: "_",
554 });
555 return generated.replaceAll(/[^a-zA-Z0-9_]/g, "_");
556 });
557
558 /**
559 * Read a stream by id, mapping "gone" (`StreamNotFound`, Cloudflare error
560 * code 1016, or `InvalidStreamId` for a malformed/foreign id) to
561 * `undefined`.
562 */
563 const getStream = (accountId: string, streamId: string) =>
564 pipelines.getStream({ accountId, streamId }).pipe(
565 Effect.map((s): ObservedStream | undefined => s),
566 Effect.catchTags({
567 StreamNotFound: () => Effect.undefined,
568 InvalidStreamId: () => Effect.undefined,
569 }),
570 );
571
572 const findStreamByName = (accountId: string, name: string) =>
573 pipelines.listStreams.items({ accountId }).pipe(
574 EffectStream.runCollect,
575 Effect.map((chunk): ObservedStream | undefined =>
576 Array.from(chunk).find((s) => s.name === name),
577 ),
578 );
579
580 /** Resolve a `schema` prop (field list or Effect Schema) to the field-list form. */
581 const resolveSchema = (
582 schema: StreamFieldsSchema | Schema.Top | undefined,
583 ): Effect.Effect<StreamFieldsSchema | undefined, StreamSchemaUnsupported> =>
584 isEffectSchema(schema)
585 ? Effect.try({
586 try: () => ({ fields: streamFieldsFromSchema(schema) }),
587 catch: (error) =>
588 error instanceof StreamSchemaUnsupported
589 ? error
590 : new StreamSchemaUnsupported({ path: "", message: String(error) }),
591 })
592 : Effect.succeed(schema as StreamFieldsSchema | undefined);
593
594 const canonicalSchema = (schema: StreamFieldsSchema | Schema.Top | undefined) =>
595 resolveSchema(schema).pipe(
596 Effect.map((resolved) =>
597 resolved === undefined ? undefined : canonicalStreamFields(resolved.fields),
598 ),
599 );
600
601 const canonicalFormat = (format: StreamFormat | undefined) => {
602 const f = format ?? { type: "json" as const };
603 return {
604 type: f.type,
605 unstructured: f.unstructured,
606 timestampFormat: f.timestampFormat ?? "rfc3339",
607 decimalEncoding: f.decimalEncoding,
608 };
609 };
610
611 interface DesiredHttp {
612 enabled: boolean;
613 authentication: boolean;
614 cors?: { origins: string[] };
615 }
616
617 /**
618 * Desired HTTP ingest settings. Omitted (or `false`) means no endpoint —
619 * Cloudflare's own default is a public, unauthenticated endpoint.
620 */
621 const desiredHttp = (http: boolean | StreamHttp | undefined): DesiredHttp => {
622 if (http === undefined || http === false) {
623 return { enabled: false, authentication: false };
624 }
625 if (http === true) return { enabled: true, authentication: true };
626 return {
627 enabled: http.enabled ?? true,
628 authentication: http.authentication ?? false,
629 cors: http.cors?.origins ? { origins: http.cors.origins } : undefined,
630 };
631 };
632
633 const httpMatches = (
634 desired: DesiredHttp,
635 observed: {
636 enabled: boolean;
637 authentication: boolean;
638 origins: readonly string[] | null | undefined;
639 },
640 ) => {
641 // A disabled endpoint's auth/CORS settings are inert.
642 if (!desired.enabled) return !observed.enabled;
643 return (
644 observed.enabled &&
645 desired.authentication === observed.authentication &&
646 sameOrigins(desired.cors?.origins, observed.origins)
647 );
648 };
649
650 const sameOrigins = (
651 desired: readonly string[] | undefined,
652 observed: readonly string[] | null | undefined,
653 ) => {
654 // Only diff origins when the user declared them; Cloudflare's default
655 // is not ours to fight.
656 if (desired === undefined) return true;
657 const have = observed ?? [];
658 return (
659 desired.length === have.length && [...desired].sort().join(",") === [...have].sort().join(",")
660 );
661 };
662
663 /**
664 * Key-order-insensitive structural equality for plain JSON-ish prop
665 * values (schemas, formats).
666 */
667 const stableEquals = (a: unknown, b: unknown): boolean => stableStringify(a) === stableStringify(b);
668
669 const stableStringify = (value: unknown): string =>
670 JSON.stringify(value, (_key, v) =>
671 v !== null && typeof v === "object" && !Array.isArray(v)
672 ? Object.fromEntries(
673 Object.entries(v as Record<string, unknown>).sort(([x], [y]) => x.localeCompare(y)),
674 )
675 : v,
676 ) ?? "undefined";
677
678 const toAttributes = (observed: ObservedStream, accountId: string): StreamAttributes => ({
679 streamId: observed.id,
680 accountId,
681 name: observed.name,
682 endpoint: observed.endpoint ?? undefined,
683 httpEnabled: observed.http.enabled,
684 httpAuthentication: observed.http.authentication,
685 corsOrigins: observed.http.cors?.origins ? [...observed.http.cors.origins] : undefined,
686 workerBindingEnabled: observed.workerBinding.enabled,
687 version: observed.version,
688 createdAt: observed.createdAt,
689 modifiedAt: observed.modifiedAt,
690 });