@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 766 lines 26.6 KB
Raw
1 import * as queues from "@distilled.cloud/cloudflare/queues";
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 { isResourceOfType, Resource, type ResourceClass } from "alchemy/Resource";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Effectable from "effect/Effectable";
11 import * as Option from "effect/Option";
12 import * as Predicate from "effect/Predicate";
13 import * as Stream from "effect/Stream";
14 import type { Model } from "../AI/Model.ts";
15 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
16 import type { Variant } from "../Images/Variant.ts";
17 import type { Namespace } from "../KV/Namespace.ts";
18 import type { Providers } from "../Providers.ts";
19 import type { Bucket } from "../R2/Bucket.ts";
20 import type { SuperSlurperJob } from "../R2/SuperSlurperJob.ts";
21 import type { Index } from "../Vectorize/VectorizeIndex.ts";
22 import type { Worker } from "../Workers/Worker.ts";
23 import type { WorkflowBinding, WorkflowResource } from "../Workflows/Workflow.ts";
24
25 const TypeId = "Cloudflare.Queues.Subscription" as const;
26 type TypeId = typeof TypeId;
27
28 /**
29 * The Cloudflare product whose events the subscription delivers into the
30 * Queue. Cloudflare allows a single subscription per source per account,
31 * and the source is fixed at creation — changing it triggers a
32 * replacement.
33 */
34 export type SubscriptionSource =
35 | {
36 /** Cloudflare Images events. */
37 type: "images";
38 }
39 | {
40 /** Workers KV namespace events. */
41 type: "kv";
42 }
43 | {
44 /** R2 bucket events. */
45 type: "r2";
46 }
47 | {
48 /** Super Slurper migration events. */
49 type: "superSlurper";
50 }
51 | {
52 /** Vectorize index events. */
53 type: "vectorize";
54 }
55 | {
56 /** Workers AI model events for a specific model. */
57 type: "workersAi.model";
58 /** Name of the Workers AI model to subscribe to. */
59 modelName: string;
60 }
61 | {
62 /** Workers Builds events for a specific Worker. */
63 type: "workersBuilds.worker";
64 /** Name of the Worker whose build events to subscribe to. */
65 workerName: string;
66 }
67 | {
68 /** Workflows events for a specific workflow. */
69 type: "workflows.workflow";
70 /** Name of the workflow to subscribe to. */
71 workflowName: string;
72 }
73 | {
74 /** Email Sending lifecycle events for one sending domain. */
75 type: "email.sending";
76 /** Zone the sending domain belongs to. */
77 zoneId: string;
78 /** The zone apex or a verified sending subdomain, e.g. `mail.example.com`. */
79 domain: string;
80 };
81
82 export type SubscriptionProps = {
83 /**
84 * Human readable name of the subscription. If omitted, a unique name is
85 * generated from the app, stage, and logical ID.
86 * @default ${app}-${stage}-${id}
87 */
88 name?: string;
89 /**
90 * The event source to subscribe to (e.g. `{ type: "r2" }` for R2 bucket
91 * events). The constructor also accepts Workflow bindings and supported
92 * Cloudflare resources or yielded `.ref(...)` references. Images variants,
93 * KV namespaces, R2 buckets, Super Slurper jobs, and Vectorize indexes select
94 * all events of that product in the account, not just the supplied resource.
95 * Models, Workers, and Workflows select their deferred physical names.
96 * References read persisted state without owning their sources.
97 * Fixed at creation — changing it triggers a replacement. Cloudflare
98 * allows at most one subscription per source per account.
99 */
100 source: SubscriptionSource;
101 /**
102 * Account of a resource source, captured by the constructor. Resource sources
103 * must belong to the subscription's ambient Cloudflare account.
104 */
105 sourceAccountId?: string;
106 /**
107 * Event types to deliver, scoped to the source (e.g. `bucket.created`
108 * and `bucket.deleted` for the `r2` source, `namespace.created` for
109 * `kv`). Must contain at least one event type valid for the source.
110 */
111 events: string[];
112 /**
113 * The ID of the Queue that receives the events
114 * (the destination, e.g. `queue.queueId`).
115 */
116 queueId: string;
117 /**
118 * Whether the subscription is active.
119 * @default true
120 */
121 enabled?: boolean;
122 };
123
124 export type SubscriptionAttributes = {
125 /**
126 * Unique identifier for the subscription.
127 */
128 subscriptionId: string;
129 /**
130 * The Cloudflare account the subscription belongs to.
131 */
132 accountId: string;
133 /**
134 * Human readable name of the subscription.
135 */
136 name: string;
137 /**
138 * The event source the subscription listens to.
139 */
140 source: SubscriptionSource;
141 /**
142 * Event types delivered by this subscription.
143 */
144 events: string[];
145 /**
146 * The ID of the destination Queue.
147 */
148 queueId: string;
149 /**
150 * Whether the subscription is active.
151 */
152 enabled: boolean;
153 /**
154 * When the subscription was created.
155 */
156 createdAt: string;
157 /**
158 * When the subscription was last modified.
159 */
160 modifiedAt: string;
161 };
162
163 export type Subscription = Resource<
164 TypeId,
165 SubscriptionProps,
166 SubscriptionAttributes,
167 never,
168 Providers
169 >;
170
171 /** Resources whose product events can be delivered to a Queue. */
172 export type SubscriptionResourceSource =
173 | WorkflowResource
174 | Variant
175 | Namespace
176 | Bucket
177 | SuperSlurperJob
178 | Index
179 | Model
180 | Worker;
181
182 /** Constructor inputs; resource sources are normalized before registration. */
183 export type SubscriptionInput = Omit<
184 PropsInput<SubscriptionProps>,
185 "source" | "sourceAccountId"
186 > & {
187 /** An explicit source, Workflow binding, resource, or yielded resource reference. */
188 source: PropsInput<SubscriptionProps>["source"] | WorkflowBinding | SubscriptionResourceSource;
189 };
190
191 type SubscriptionConstructor<Req = never> = {
192 Type: TypeId;
193 Props: SubscriptionProps;
194 <const Methods extends Record<string, any>>(methods: Methods): SubscriptionClass & Methods;
195 (id: string, props: SubscriptionInput): Effect.Effect<Subscription, never, Req>;
196 <PropsReq = never>(
197 id: string,
198 props: Effect.Effect<SubscriptionInput, never, PropsReq>,
199 ): Effect.Effect<Subscription, never, PropsReq | Req>;
200 };
201
202 type SubscriptionClass = SubscriptionConstructor<Providers> &
203 Effect.Effect<SubscriptionConstructor> &
204 Pick<ResourceClass<Subscription>, "Self" | "Provider" | "Aliases" | "ref">;
205
206 const SubscriptionResource = Resource<Subscription>(TypeId, {
207 aliases: ["Cloudflare.Queue.Subscription"],
208 });
209
210 const isSourceResource = <Type extends SubscriptionResourceSource["Type"]>(
211 source: SubscriptionInput["source"],
212 type: Type,
213 ): source is Extract<SubscriptionResourceSource, { Type: Type }> => isResourceOfType(source, type);
214
215 const isWorkflowBinding = (source: SubscriptionInput["source"]): source is WorkflowBinding =>
216 typeof source === "object" &&
217 source !== null &&
218 (source as WorkflowBinding).kind === "Cloudflare.Workflow";
219
220 const normalizeSubscriptionProps = (props: SubscriptionInput): PropsInput<SubscriptionProps> => {
221 const source = props.source;
222 // Resource references are Output proxies; inspect their type before binding fields.
223 if (isSourceResource(source, "Cloudflare.Workflow")) {
224 return {
225 ...props,
226 sourceAccountId: source.accountId,
227 source: { type: "workflows.workflow", workflowName: source.workflowName },
228 };
229 }
230 if (isSourceResource(source, "Cloudflare.Worker")) {
231 return {
232 ...props,
233 sourceAccountId: source.accountId,
234 source: { type: "workersBuilds.worker", workerName: source.workerName },
235 };
236 }
237 if (isSourceResource(source, "Cloudflare.AI.Model")) {
238 return {
239 ...props,
240 sourceAccountId: source.accountId,
241 source: { type: "workersAi.model", modelName: source.modelName },
242 };
243 }
244 if (isSourceResource(source, "Cloudflare.Images.Variant")) {
245 return {
246 ...props,
247 sourceAccountId: source.accountId,
248 source: { type: "images" },
249 };
250 }
251 if (isSourceResource(source, "Cloudflare.KV.Namespace")) {
252 return {
253 ...props,
254 sourceAccountId: source.accountId,
255 source: { type: "kv" },
256 };
257 }
258 if (isSourceResource(source, "Cloudflare.R2.Bucket")) {
259 return {
260 ...props,
261 sourceAccountId: source.accountId,
262 source: { type: "r2" },
263 };
264 }
265 if (isSourceResource(source, "Cloudflare.R2.SuperSlurperJob")) {
266 return {
267 ...props,
268 sourceAccountId: source.accountId,
269 source: { type: "superSlurper" },
270 };
271 }
272 if (isSourceResource(source, "Cloudflare.VectorizeIndex")) {
273 return {
274 ...props,
275 sourceAccountId: source.accountId,
276 source: { type: "vectorize" },
277 };
278 }
279 if (isWorkflowBinding(source)) {
280 return {
281 ...props,
282 source: { type: "workflows.workflow", workflowName: source.workflowName },
283 };
284 }
285 return { ...props, source };
286 };
287
288 /** A resource source cannot select events in a different Cloudflare account. */
289 export class SubscriptionSourceAccountMismatch extends Data.TaggedError(
290 "SubscriptionSourceAccountMismatch",
291 )<{ readonly accountId: string; readonly sourceAccountId: string }> {}
292
293 const validateSourceAccount = (accountId: string, sourceAccountId?: string) =>
294 sourceAccountId !== undefined && sourceAccountId !== accountId
295 ? Effect.fail(new SubscriptionSourceAccountMismatch({ accountId, sourceAccountId }))
296 : Effect.void;
297
298 /**
299 * A Cloudflare Queues event subscription — delivers platform events
300 * (R2 bucket events, KV namespace events, Workers Builds, Workflows,
301 * etc.) into a Queue as messages.
302 *
303 * The `source` selects which product emits the events and is fixed at
304 * creation (changing it replaces the subscription). `name`, `events`,
305 * `enabled`, and the destination `queueId` are all mutable in place.
306 * Cloudflare allows at most one subscription per source per account.
307 * ### Creating a Subscription
308 * **Example:** R2 bucket events into a Queue
309 * ```typescript
310 * const queue = yield* Cloudflare.Queues.Queue("EventsQueue");
311 *
312 * const subscription = yield* Cloudflare.Queues.Subscription("R2Events", {
313 * source: { type: "r2" },
314 * events: ["bucket.created", "bucket.deleted"],
315 * queueId: queue.queueId,
316 * });
317 * ```
318 *
319 * **Example:** KV namespace events with an explicit name
320 * ```typescript
321 * const subscription = yield* Cloudflare.Queues.Subscription("KvEvents", {
322 * name: "kv-events",
323 * source: { type: "kv" },
324 * events: ["namespace.created"],
325 * queueId: queue.queueId,
326 * });
327 * ```
328 *
329 * **Example:** Workers Builds events for one Worker
330 * ```typescript
331 * const subscription = yield* Cloudflare.Queues.Subscription("BuildEvents", {
332 * source: { type: "workersBuilds.worker", workerName: "my-worker" },
333 * events: ["build.started", "build.succeeded"],
334 * queueId: queue.queueId,
335 * });
336 * ```
337 *
338 * **Example:** Workflow lifecycle events, from a Workflow bound in this stack
339 * Pass the Workflow binding from the host Worker's `env` directly. Its
340 * physical name remains an `Output`, so the subscription works on the
341 * Workflow's first deployment and follows later renames. Only the source
342 * type and physical workflow name are persisted, not the binding metadata.
343 * ```typescript
344 * const worker = yield* Cloudflare.Worker("Worker", {
345 * main: "./src/worker.ts",
346 * env: { INGESTION: Cloudflare.Workflow("Ingestion", { className: "IngestionWorkflow" }) },
347 * });
348 *
349 * const subscription = yield* Cloudflare.Queues.Subscription("WorkflowEvents", {
350 * source: worker.env.INGESTION,
351 * events: ["instance.completed", "instance.errored"],
352 * queueId: queue.queueId,
353 * });
354 * ```
355 *
356 * **Example:** Workflow lifecycle events from a persisted resource reference
357 * Use the logical resource ID, including any namespace. References read
358 * persisted state, so deploy the host first. Omitting the options uses the
359 * current stack and stage; the reference does not take ownership of the host.
360 * ```typescript
361 * const subscription = yield* Cloudflare.Queues.Subscription("WorkflowEvents", {
362 * source: yield* Cloudflare.Workflow.ref("Ingestion", {
363 * stack: "workflow-host",
364 * stage: "production",
365 * }),
366 * events: ["instance.completed", "instance.errored"],
367 * queueId: queue.queueId,
368 * });
369 * ```
370 *
371 * **Example:** Workflow lifecycle events by an existing physical name
372 * ```typescript
373 * const subscription = yield* Cloudflare.Queues.Subscription("WorkflowEvents", {
374 * source: { type: "workflows.workflow", workflowName: "existing-ingestion" },
375 * events: ["instance.completed", "instance.errored"],
376 * queueId: queue.queueId,
377 * });
378 * ```
379 *
380 * **Example:** Bounces and complaints from an Email Sending domain
381 * ```typescript
382 * const subscription = yield* Cloudflare.Queues.Subscription("MailEvents", {
383 * source: { type: "email.sending", zoneId: zone.zoneId, domain: "mail.example.com" },
384 * events: ["message.bounced", "message.complained"],
385 * queueId: queue.queueId,
386 * });
387 * ```
388 *
389 * ### Resource and Reference Sources
390 * **Example:** Account-wide KV events from a namespace
391 * ```typescript
392 * const namespace = yield* Cloudflare.KV.Namespace("Cache");
393 * yield* Cloudflare.Queues.Subscription("NamespaceEvents", {
394 * source: namespace,
395 * events: ["namespace.created", "namespace.deleted"],
396 * queueId: queue.queueId,
397 * });
398 * ```
399 * KV, R2, Images, Vectorize, and Super Slurper sources are account-wide.
400 * Passing a resource retains its account and deployment dependency, but does
401 * not filter events to that resource. The subscription can miss the source's
402 * initial creation or final deletion because it depends on that source.
403 * Use an explicit product descriptor when the subscription must exist first.
404 *
405 * **Example:** R2 bucket reference from another stack
406 * ```typescript
407 * yield* Cloudflare.Queues.Subscription("BucketEvents", {
408 * source: yield* Cloudflare.R2.Bucket.ref("Uploads", {
409 * stack: "storage",
410 * stage: "production",
411 * }),
412 * events: ["bucket.created", "bucket.deleted"],
413 * queueId: queue.queueId,
414 * });
415 * ```
416 * All resource forms accept yielded `.ref` references with optional stack
417 * and stage selectors. The referenced resource must already be deployed in
418 * the same Cloudflare account. Removing a subscription does not remove its
419 * referenced resource.
420 *
421 * **Example:** Images upload events from a variant reference
422 * ```typescript
423 * yield* Cloudflare.Queues.Subscription("ImageEvents", {
424 * source: yield* Cloudflare.Images.Variant.ref("Thumbnail"),
425 * events: ["image.uploaded"],
426 * queueId: queue.queueId,
427 * });
428 * ```
429 * The variant selects its Images account; uploads are not filtered by variant.
430 *
431 * **Example:** Vectorize index events
432 * ```typescript
433 * yield* Cloudflare.Queues.Subscription("IndexEvents", {
434 * source: yield* Cloudflare.Vectorize.Index.ref("Search"),
435 * events: ["index.created", "index.deleted"],
436 * queueId: queue.queueId,
437 * });
438 * ```
439 *
440 * **Example:** Super Slurper migration events
441 * ```typescript
442 * yield* Cloudflare.Queues.Subscription("MigrationEvents", {
443 * source: yield* Cloudflare.R2.SuperSlurperJob.ref("Migration"),
444 * events: ["job.completed", "job.aborted"],
445 * queueId: queue.queueId,
446 * });
447 * ```
448 * This selects all migration jobs in the account, not one job's objects.
449 *
450 * **Example:** Workers AI batch events
451 * ```typescript
452 * const model = yield* Cloudflare.AI.Model("Embeddings", {
453 * modelName: "@cf/baai/bge-m3",
454 * });
455 * yield* Cloudflare.Queues.Subscription("BatchEvents", {
456 * source: model,
457 * events: ["batch.queued", "batch.succeeded", "batch.failed"],
458 * queueId: queue.queueId,
459 * });
460 * ```
461 * The model is a non-owning catalog handle. These events require asynchronous
462 * batch inference; ordinary synchronous inference does not emit them.
463 *
464 * **Example:** Workers Builds events from a Worker reference
465 * ```typescript
466 * yield* Cloudflare.Queues.Subscription("BuildEvents", {
467 * source: yield* Cloudflare.Worker.ref("Website"),
468 * events: ["build.started", "build.succeeded", "build.failed"],
469 * queueId: queue.queueId,
470 * });
471 * ```
472 * The Worker must have a Workers Builds integration to emit build events.
473 * An ordinary Alchemy Worker upload is not a Workers Builds run.
474 *
475 * Event delivery can lag subscription creation or replacement even after the
476 * destination Queue accepts messages. Deployment confirms configuration, not
477 * delivery readiness; verify delivery before emitting events that must be observed.
478 * During Vectorize subscription replacement or a destination Queue update,
479 * Cloudflare can still route new events to the previous Queue. Replacement events
480 * can carry the deleted subscription's ID; updates retain the same subscription ID.
481 * A single early event does not prove that routing has fully propagated. Keep the
482 * previous destination available during the transition and verify the receiving
483 * Queue, `metadata.eventSubscriptionId`, and the event's resource identity.
484 *
485 * ### Pausing delivery
486 * **Example:** Disable a subscription without deleting it
487 * ```typescript
488 * const subscription = yield* Cloudflare.Queues.Subscription("R2Events", {
489 * source: { type: "r2" },
490 * events: ["bucket.created"],
491 * queueId: queue.queueId,
492 * enabled: false,
493 * });
494 * ```
495 *
496 * @see https://developers.cloudflare.com/queues/event-subscriptions/
497 *
498 * @resource
499 * @product Queues
500 * @category Storage & Databases
501 */
502 export const Subscription: SubscriptionClass = Object.assign(
503 (
504 ...args:
505 | [id: string, props: SubscriptionInput | Effect.Effect<SubscriptionInput, never, any>]
506 | [methods: Record<string, any>]
507 ) => {
508 if (typeof args[0] === "object") {
509 return Object.assign(Subscription, args[0]);
510 }
511 const [id, props] = args as [
512 string,
513 SubscriptionInput | Effect.Effect<SubscriptionInput, never, any>,
514 ];
515 // Resource supplies Self while evaluating Effect-valued props.
516 return Effect.isEffect(props)
517 ? SubscriptionResource(id, Effect.map(props, normalizeSubscriptionProps))
518 : SubscriptionResource(id, normalizeSubscriptionProps(props));
519 },
520 SubscriptionResource,
521 Effectable.Prototype({
522 label: `Resource<${TypeId}>`,
523 evaluate: (): Effect.Effect<SubscriptionConstructor> => Effect.succeed(Subscription),
524 }),
525 ) as SubscriptionClass;
526
527 /**
528 * Returns true if the given value is a Subscription resource.
529 */
530 export const isSubscription = (value: unknown): value is Subscription =>
531 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
532
533 export const SubscriptionProvider = () =>
534 Provider.succeed(SubscriptionResource, {
535 stables: ["subscriptionId", "accountId", "source", "createdAt"],
536 diff: Effect.fn(function* ({ olds, news, output }) {
537 const { accountId } = yield* yield* CloudflareEnvironment;
538 if (isResolved(news)) {
539 yield* validateSourceAccount(accountId, news.sourceAccountId);
540 }
541 if ((output?.accountId ?? accountId) !== accountId) {
542 return { action: "replace" } as const;
543 }
544 // An unresolved immutable source may change with its upstream resource.
545 // Delete first in case it resolves to the same account-unique source.
546 if (!("source" in news) || !isResolved(news.source)) {
547 return { action: "replace", deleteFirst: true } as const;
548 }
549 // The source is fixed at creation.
550 const oldSource = output?.source ?? olds?.source;
551 if (oldSource && !sameSource(oldSource, news.source)) {
552 return { action: "replace" } as const;
553 }
554 return undefined;
555 }),
556 read: Effect.fn(function* ({ id, output, olds, previous }) {
557 const { accountId } = yield* yield* CloudflareEnvironment;
558 if (!output) {
559 yield* validateSourceAccount(accountId, olds?.sourceAccountId);
560 }
561 const acct = output?.accountId ?? accountId;
562
563 if (output?.subscriptionId) {
564 const observed = yield* getSubscriptionOrUndefined(acct, output.subscriptionId);
565 return observed ? toAttributes(observed, acct) : undefined;
566 }
567 // Cold read — recover from lost state by matching the deterministic
568 // physical name. Names are not enforced unique server-side; an exact
569 // match on our generated/explicit name is the best identity we have.
570 const name = yield* createSubscriptionName(id, olds?.name);
571 const match = yield* findByName(acct, name);
572 if (!match) return undefined;
573 const attributes = toAttributes(match, acct);
574 // The generation a replacement is replacing is ours.
575 return olds?.name !== undefined && attributes.subscriptionId !== previous?.subscriptionId
576 ? Unowned(attributes)
577 : attributes;
578 }),
579 reconcile: Effect.fn(function* ({ id, news, output }) {
580 const { accountId } = yield* yield* CloudflareEnvironment;
581 yield* validateSourceAccount(accountId, news.sourceAccountId);
582 const acct = output?.accountId ?? accountId;
583 const name = yield* createSubscriptionName(id, news.name);
584
585 // Observe — the subscriptionId cached on `output` is a hint, not a
586 // guarantee: a missing subscription falls through to create.
587 let observed = output?.subscriptionId
588 ? yield* getSubscriptionOrUndefined(acct, output.subscriptionId)
589 : undefined;
590
591 // A source collision does not establish ownership of the existing subscription.
592 if (!observed) {
593 observed = yield* queues.createSubscription({
594 accountId: acct,
595 name,
596 enabled: news.enabled ?? true,
597 events: news.events,
598 source: news.source,
599 destination: { type: "queues.queue", queueId: news.queueId },
600 });
601 }
602
603 // Sync — diff observed cloud state against desired and patch only
604 // the delta; skip the API call entirely on a no-op.
605 const desired = {
606 name,
607 enabled: news.enabled ?? true,
608 events: news.events,
609 queueId: news.queueId,
610 };
611 const dirty =
612 observed.name !== desired.name ||
613 observed.enabled !== desired.enabled ||
614 observed.destination.queueId !== desired.queueId ||
615 !sameEvents(observed.events, desired.events);
616
617 const final = dirty
618 ? yield* queues.patchSubscription({
619 accountId: acct,
620 subscriptionId: observed.id,
621 name: desired.name,
622 enabled: desired.enabled,
623 events: desired.events,
624 destination: { type: "queues.queue", queueId: desired.queueId },
625 })
626 : observed;
627
628 return toAttributes(final, acct);
629 }),
630 delete: Effect.fn(function* ({ output }) {
631 yield* queues
632 .deleteSubscription({
633 accountId: output.accountId,
634 subscriptionId: output.subscriptionId,
635 })
636 .pipe(Effect.catchTag("SubscriptionNotFound", () => Effect.void));
637 }),
638 // Account collection — subscriptions are account-scoped. Exhaustively
639 // paginate `listSubscriptions` (response array is `result`) and hydrate
640 // each row into the same Attributes shape `read` returns.
641 list: Effect.fn(function* () {
642 const { accountId } = yield* yield* CloudflareEnvironment;
643 return yield* queues.listSubscriptions.pages({ accountId }).pipe(
644 Stream.runCollect,
645 Effect.map((chunk) =>
646 Array.from(chunk).flatMap((page) =>
647 (page.result ?? []).map((sub) => toAttributes(sub, accountId)),
648 ),
649 ),
650 );
651 }),
652 });
653
654 type ObservedSubscription =
655 | queues.GetSubscriptionResponse
656 | queues.CreateSubscriptionResponse
657 | queues.PatchSubscriptionResponse;
658
659 /**
660 * Read a subscription by ID, mapping "gone" (`SubscriptionNotFound`,
661 * HTTP 404 "No subscription with this ID") to `undefined`.
662 */
663 const getSubscriptionOrUndefined = (accountId: string, subscriptionId: string) =>
664 queues
665 .getSubscription({ accountId, subscriptionId })
666 .pipe(Effect.catchTag("SubscriptionNotFound", () => Effect.undefined));
667
668 /**
669 * Find a subscription by exact name. Cloudflare's list endpoint has no
670 * name filter, so scan the paginated stream.
671 */
672 const findByName = (accountId: string, name: string) =>
673 queues.listSubscriptions.items({ accountId }).pipe(
674 Stream.filter((s) => s.name === name),
675 Stream.runHead,
676 Effect.map(Option.getOrUndefined),
677 );
678
679 const createSubscriptionName = (id: string, name: string | undefined) =>
680 Effect.gen(function* () {
681 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
682 });
683
684 /**
685 * The wire shape of a subscription source — a flattened view of the
686 * response union (only the member matching `type` carries its name field).
687 */
688 type WireSource = {
689 type?: string | null;
690 modelName?: string | null;
691 workerName?: string | null;
692 workflowName?: string | null;
693 zoneId?: string | null;
694 domain?: string | null;
695 };
696
697 const toSource = (wire: unknown): SubscriptionSource => {
698 const source = wire as WireSource;
699 switch (source.type) {
700 case "workersAi.model":
701 return { type: "workersAi.model", modelName: source.modelName ?? "" };
702 case "workersBuilds.worker":
703 return {
704 type: "workersBuilds.worker",
705 workerName: source.workerName ?? "",
706 };
707 case "workflows.workflow":
708 return {
709 type: "workflows.workflow",
710 workflowName: source.workflowName ?? "",
711 };
712 case "email.sending":
713 return {
714 type: "email.sending",
715 zoneId: source.zoneId ?? "",
716 domain: source.domain ?? "",
717 };
718 case "images":
719 case "kv":
720 case "r2":
721 case "superSlurper":
722 case "vectorize":
723 return { type: source.type };
724 default:
725 // Unknown/new source types added server-side: surface the raw type
726 // so diff treats it as a foreign source rather than crashing.
727 return { type: source.type as never };
728 }
729 };
730
731 const sameSource = (a: SubscriptionSource, b: SubscriptionSource): boolean => {
732 if (a.type !== b.type) return false;
733 switch (a.type) {
734 case "workersAi.model":
735 return a.modelName === (b as { modelName?: string }).modelName;
736 case "workersBuilds.worker":
737 return a.workerName === (b as { workerName?: string }).workerName;
738 case "workflows.workflow":
739 return a.workflowName === (b as { workflowName?: string }).workflowName;
740 case "email.sending": {
741 const other = b as { zoneId?: string; domain?: string };
742 return a.zoneId === other.zoneId && a.domain === other.domain;
743 }
744 default:
745 return true;
746 }
747 };
748
749 const sameEvents = (observed: readonly string[], desired: readonly string[]) =>
750 observed.length === desired.length &&
751 [...observed].sort().join(",") === [...desired].sort().join(",");
752
753 const toAttributes = (
754 subscription: ObservedSubscription,
755 accountId: string,
756 ): SubscriptionAttributes => ({
757 subscriptionId: subscription.id,
758 accountId,
759 name: subscription.name,
760 source: toSource(subscription.source),
761 events: [...subscription.events],
762 queueId: subscription.destination.queueId,
763 enabled: subscription.enabled,
764 createdAt: subscription.createdAt,
765 modifiedAt: subscription.modifiedAt,
766 });