Skip to main content

bynk_emit/emitter/
events_fanout.rs

1//! Events track, slice 0 (spine #936, ADR 0284): the fan-out Durable Object.
2//!
3//! One instance per *publishing* context. Cloudflare requires a DO's
4//! `class_name` to resolve to an export of the Worker's `main` module, so
5//! this is emitted as its own file (`events_fanout.ts`) and re-exported from
6//! `index.ts` — mirroring how an agent's DO class lives in `handlers.ts` and
7//! is re-exported the same way, except an event fan-out has no backing
8//! `AgentDecl` to emit from, so this is hand-built rather than reusing
9//! `emit_agent`. The subscriber registry (who gets `E`) is fully compile-time
10//! known (`bynk_check::symbols::discover_event_subscribers`), so it is baked in as
11//! a literal routing table rather than carried on the wire.
12//!
13//! Arc C's own first real conversion slice (#1317): builds a real
14//! `bynk_ts::TsProgram` directly instead of `writeln!`-ing a `String` — the
15//! first `bynk-emit` construction site whose output reaches
16//! `Document::Ts` without a `TsStmt::verbatim` wrap.
17
18use std::collections::BTreeMap;
19
20use bynk_ts::{
21    TsBinaryOp, TsBindingName, TsClassCtor, TsClassField, TsClassMethod, TsDecl, TsExpr, TsLit,
22    TsParam, TsProgram, TsStmt, TsType, TsTypeMember, TsUnaryOp,
23};
24
25use crate::emitter::bindings::service_binding;
26use crate::emitter::compose::events::isolated_delivery;
27use crate::emitter::compose::{EventPlan, EventSubscription};
28use crate::emitter::wrangler::EVENTS_FANOUT_CLASS_NAME;
29
30/// The Worker-relative specifier `events_fanout.ts` imports the runtime
31/// from — same depth as `compose.ts` (`workers/<worker>/events_fanout.ts`).
32const EVENTS_FANOUT_RUNTIME_SPECIFIER: &str = "../../runtime.js";
33
34/// `context`: the publishing context's qualified name (the header comment,
35/// and I2's signing identity for every delivery). The routes are its own
36/// declared event type names, each with its subscribers, from `events`
37/// ([`EventPlan::published_by`]): already in `discover_event_subscribers`'
38/// order, so the generated table (and so the fan-out order for a
39/// multi-subscriber event) is deterministic build to build.
40pub fn emit_events_fanout_do(context: &str, events: &EventPlan) -> TsProgram {
41    let routes: Routes = events
42        .published_by(context)
43        .map(|(name, subs)| (name.to_string(), subs))
44        .collect();
45    fanout_program(&format!("context `{context}`"), &routes, Some(context), &[])
46}
47
48/// The subscribers of each event a fan-out routes, by the name its table keys it
49/// by.
50type Routes<'a> = BTreeMap<String, &'a [EventSubscription]>;
51
52/// #3562 (G3-1): the one events fan-out of a `[deploy.workers.<key>]` group,
53/// serving every publishing member. `publishers` is the publishing members'
54/// names; each one's routes are its events' in `events`, as
55/// [`emit_events_fanout_do`] takes them. A member tags each event it emits with
56/// its own name (`publisher`), because two members may declare an event of one
57/// name; the table is keyed `<publisher>/<type>`, and a delivery is signed as
58/// the publisher the event names.
59pub fn emit_group_events_fanout_do(
60    key: &str,
61    publishers: &[&str],
62    events: &EventPlan,
63) -> TsProgram {
64    let merged: Routes = publishers
65        .iter()
66        .flat_map(|publisher| {
67            events
68                .published_by(publisher)
69                .map(move |(name, subs)| (format!("{publisher}/{name}"), subs))
70        })
71        .collect();
72    let known: Vec<String> = publishers.iter().map(|p| (*p).to_string()).collect();
73    fanout_program(&format!("Worker group `{key}`"), &merged, None, &known)
74}
75
76/// A group's fan-out trusts the `publisher` an event names only because it is
77/// one of `known` (see [`unknown_publisher_refusal`]), and only code in the same
78/// Worker can reach the Durable Object through its binding.
79///
80/// `publisher` is the one context a standalone fan-out signs deliveries as;
81/// `None` for a group's, which reads it from each event and signs only for one of
82/// `known`, the group's publishing members.
83fn fanout_program(
84    subject: &str,
85    routes: &Routes,
86    publisher: Option<&str>,
87    known: &[String],
88) -> TsProgram {
89    let mut program = TsProgram::new();
90    program.push(TsStmt::comment(
91        "Generated by bynk — do not edit by hand.",
92        None,
93    ));
94    program.push(TsStmt::comment(
95        format!("Events fan-out Durable Object for {subject} (spine #936, ADR 0284)."),
96        None,
97    ));
98    for (type_only, names) in [
99        (
100            true,
101            vec![
102                "__DurableObjectState".to_string(),
103                "__ServiceBinding".to_string(),
104            ],
105        ),
106        (false, vec!["__deliverEvent".to_string()]),
107    ] {
108        for stmt in crate::emitter::runtime_files::runtime_import_stmts(
109            type_only,
110            &names,
111            EVENTS_FANOUT_RUNTIME_SPECIFIER,
112        ) {
113            program.push(stmt);
114        }
115    }
116    program.push(TsStmt::decl(
117        TsDecl::Interface {
118            name: "FanoutEvent".to_string(),
119            type_params: Vec::new(),
120            members: [
121                // A group's events name their publisher, which a standalone
122                // fan-out knows without being told.
123                publisher
124                    .is_none()
125                    .then(|| TsTypeMember::prop("publisher", TsType::named("string"))),
126            ]
127            .into_iter()
128            .flatten()
129            .chain(vec![
130                TsTypeMember::prop("type", TsType::named("string")),
131                TsTypeMember::prop("payload", TsType::named("unknown")),
132                // Events track, slice 2 (spine #936): minted once at
133                // emission (`lower.rs`'s `__events.push`), forwarded here
134                // unchanged and always — whether a subscriber's own handler
135                // actually declared the optional second `env:
136                // EventEnvelope` parameter is decided downstream, at the
137                // receiving context's entry route, not here.
138                TsTypeMember::prop(
139                    "envelope",
140                    TsType::Object(vec![
141                        TsTypeMember::prop("eventId", TsType::named("string")),
142                        TsTypeMember::prop("publisherId", TsType::named("string")),
143                        TsTypeMember::prop("emittedAt", TsType::named("number")),
144                        TsTypeMember::prop("schemaVersion", TsType::named("number")),
145                    ]),
146                ),
147            ])
148            .collect(),
149        },
150        None,
151    ));
152    program.push(TsStmt::decl(
153        TsDecl::ConstDecl {
154            name: "__eventRoutes".to_string(),
155            ty: Some(TsType::named_with_args(
156                "globalThis.Record",
157                vec![
158                    TsType::named("string"),
159                    TsType::named_with_args(
160                        "globalThis.Array",
161                        vec![TsType::Object(vec![
162                            TsTypeMember::prop("binding", TsType::named("string")),
163                            TsTypeMember::prop("context", TsType::named("string")),
164                            TsTypeMember::prop("service", TsType::named("string")),
165                        ])],
166                    ),
167                ],
168            )),
169            init: event_routes_table(routes),
170        },
171        None,
172    ));
173    if publisher.is_none() {
174        program.push(TsStmt::decl(
175            TsDecl::ConstDecl {
176                name: "__publishers".to_string(),
177                ty: Some(TsType::array(TsType::named("string"))),
178                init: TsExpr::array(
179                    known
180                        .iter()
181                        .map(|p| TsExpr::Lit(TsLit::Str(p.clone())))
182                        .collect(),
183                ),
184            },
185            None,
186        ));
187    }
188    program.push(TsStmt::decl(
189        TsDecl::Export(Box::new(TsDecl::class(
190            EVENTS_FANOUT_CLASS_NAME,
191            vec![
192                TsClassField::new(
193                    "env",
194                    TsType::named_with_args(
195                        "globalThis.Record",
196                        vec![TsType::named("string"), TsType::named("__ServiceBinding")],
197                    ),
198                )
199                .private(),
200            ],
201            Some(events_fanout_ctor()),
202            vec![events_fanout_fetch(publisher)],
203        ))),
204        None,
205    ));
206    program
207}
208
209/// `{ "<event type>": [{ binding: "...", context: "...", service: "..." },
210/// ...], ... }` — I2 (#1971): `context` is the subscriber's qualified name,
211/// which a delivery's signature binds it to —
212/// built from `routes` the same "loop over real data, build real nodes"
213/// pattern P7.9 already established for `Ty`/`TypeRef` conversion
214/// (`bynk-emit/src/emitter.rs`'s `ts_ty_to_ts_type`/`ts_type_ref_to_ts_type`),
215/// here for expressions instead of types. The outer key is pre-quoted
216/// (`format!("{name:?}")`, matching the original `write!`-based code
217/// byte-for-byte) since `TsExpr::Object`'s own key field is a raw string
218/// pushed verbatim, not itself a `TsExpr` — there is no other way to get
219/// quotes around an event-type name that isn't a bare identifier.
220fn event_routes_table(routes: &Routes) -> TsExpr {
221    TsExpr::multiline_object(
222        routes
223            .iter()
224            .map(|(name, subs)| {
225                let entries = subs
226                    .iter()
227                    .map(
228                        |EventSubscription {
229                             context: sub_ctx,
230                             service: sub_svc,
231                             ..
232                         }| {
233                            TsExpr::object(vec![
234                                (
235                                    "binding".to_string(),
236                                    TsExpr::Lit(TsLit::Str(service_binding(sub_ctx).name)),
237                                ),
238                                (
239                                    "context".to_string(),
240                                    TsExpr::Lit(TsLit::Str(sub_ctx.clone())),
241                                ),
242                                (
243                                    "service".to_string(),
244                                    TsExpr::Lit(TsLit::Str(sub_svc.clone())),
245                                ),
246                            ])
247                        },
248                    )
249                    .collect();
250                (format!("{name:?}"), TsExpr::array(entries))
251            })
252            .collect(),
253    )
254}
255
256fn events_fanout_ctor() -> TsClassCtor {
257    TsClassCtor {
258        params: vec![
259            TsParam::new(
260                "_state".to_string(),
261                Some(TsType::named("__DurableObjectState")),
262            ),
263            TsParam::optional("env".to_string(), Some(TsType::named("unknown"))),
264        ],
265        body: vec![TsStmt::assign(
266            TsExpr::Member {
267                object: Box::new(TsExpr::Ident("this".to_string())),
268                property: "env".to_string(),
269            },
270            TsExpr::As {
271                expr: Box::new(TsExpr::Binary {
272                    op: TsBinaryOp::NullishCoalescing,
273                    left: Box::new(TsExpr::Ident("env".to_string())),
274                    right: Box::new(TsExpr::object(vec![])),
275                }),
276                ty: TsType::named_with_args(
277                    "globalThis.Record",
278                    vec![TsType::named("string"), TsType::named("__ServiceBinding")],
279                ),
280            },
281            None,
282        )],
283    }
284}
285
286/// `if (!__publishers.includes(ev.publisher)) { console.error(…); continue; }`:
287/// a group's fan-out signs a delivery as the publisher its event names, so it
288/// signs only for a member it was built for. An event naming any other, or none,
289/// is logged and dropped, never signed.
290fn unknown_publisher_refusal() -> TsStmt {
291    let ev = |property: &str| TsExpr::Member {
292        object: Box::new(TsExpr::Ident("ev".to_string())),
293        property: property.to_string(),
294    };
295    let text = |e: TsExpr| TsExpr::Call {
296        callee: Box::new(TsExpr::Ident("String".to_string())),
297        args: vec![e],
298    };
299    TsStmt::if_stmt(
300        TsExpr::Unary {
301            op: TsUnaryOp::Not,
302            expr: Box::new(TsExpr::Call {
303                callee: Box::new(TsExpr::Member {
304                    object: Box::new(TsExpr::Ident("__publishers".to_string())),
305                    property: "includes".to_string(),
306                }),
307                args: vec![ev("publisher")],
308            }),
309        },
310        TsStmt::block(
311            vec![
312                TsStmt::expr_stmt(
313                    TsExpr::Call {
314                        callee: Box::new(TsExpr::Member {
315                            object: Box::new(TsExpr::Ident("globalThis.console".to_string())),
316                            property: "error".to_string(),
317                        }),
318                        args: vec![
319                            TsExpr::Lit(TsLit::Str(
320                                "EventsFanout refused an event from an unknown publisher"
321                                    .to_string(),
322                            )),
323                            TsExpr::object(vec![
324                                ("publisher".to_string(), text(ev("publisher"))),
325                                ("event".to_string(), text(ev("type"))),
326                            ]),
327                        ],
328                    },
329                    None,
330                ),
331                TsStmt::continue_stmt(None),
332            ],
333            None,
334        ),
335        None,
336    )
337}
338
339/// The per-subscriber delivery, `try { await __deliverEvent(…) } catch { log }`,
340/// signed as `publisher`, or as the event's own `publisher` in a group's.
341fn deliver_isolated(publisher: Option<&str>) -> TsStmt {
342    let sub = |property: &str| TsExpr::Member {
343        object: Box::new(TsExpr::Ident("sub".to_string())),
344        property: property.to_string(),
345    };
346    let ev = |property: &str| TsExpr::Member {
347        object: Box::new(TsExpr::Ident("ev".to_string())),
348        property: property.to_string(),
349    };
350    let delivery = TsExpr::Call {
351        callee: Box::new(TsExpr::Ident("__deliverEvent".to_string())),
352        args: vec![
353            TsExpr::Ident("binding".to_string()),
354            sub("service"),
355            ev("payload"),
356            ev("envelope"),
357            // I2 (#1971): the key for the edge to the subscriber, and the two
358            // names the delivery is signed between.
359            TsExpr::Member {
360                object: Box::new(TsExpr::Ident("this".to_string())),
361                property: "env".to_string(),
362            },
363            match publisher {
364                Some(context) => TsExpr::Lit(TsLit::Str(context.to_string())),
365                None => ev("publisher"),
366            },
367            sub("context"),
368        ],
369    };
370    // ADR 0284's failure isolation is the shared builder's, not spelled here.
371    isolated_delivery(delivery, sub("service"))
372}
373
374/// A standalone fan-out routes by `ev.type` and signs as `publisher`; a group's
375/// (`None`) routes by `<ev.publisher>/<ev.type>` and signs as `ev.publisher`.
376fn events_fanout_fetch(publisher: Option<&str>) -> TsClassMethod {
377    TsClassMethod {
378        name: "fetch".to_string(),
379        private: false,
380        is_async: true,
381        params: vec![TsParam::new(
382            "request".to_string(),
383            Some(TsType::named("globalThis.Request")),
384        )],
385        return_type: Some(TsType::named_with_args(
386            "globalThis.Promise",
387            vec![TsType::named("globalThis.Response")],
388        )),
389        doc: None,
390        body: vec![
391            TsStmt::const_stmt(
392                TsBindingName::ObjectPattern(vec!["events".to_string()]),
393                None,
394                TsExpr::As {
395                    // #1323: the `As` arm's own automatic Await-parenthesisation
396                    // rule was removed (`workers_entry.rs`'s own real `await
397                    // request.json() as JsonValue` has no parens — `as` binds
398                    // looser than `await`, so none are grammatically needed,
399                    // unlike the reasoning P7.8 originally gave). This file's
400                    // own real historical text keeps its parens regardless
401                    // (`(await request.json()) as { ... }`), now via an
402                    // explicit `Paren`, not an implicit per-shape rule.
403                    expr: Box::new(TsExpr::Paren(Box::new(TsExpr::Await(Box::new(
404                        TsExpr::Call {
405                            callee: Box::new(TsExpr::Member {
406                                object: Box::new(TsExpr::Ident("request".to_string())),
407                                property: "json".to_string(),
408                            }),
409                            args: vec![],
410                        },
411                    ))))),
412                    ty: TsType::Object(vec![TsTypeMember::prop(
413                        "events",
414                        TsType::array(TsType::named("FanoutEvent")),
415                    )]),
416                },
417                None,
418            ),
419            TsStmt::for_of(
420                "ev",
421                TsExpr::Ident("events".to_string()),
422                TsStmt::block(
423                    publisher
424                        .is_none()
425                        .then(unknown_publisher_refusal)
426                        .into_iter()
427                        .chain(vec![
428                            TsStmt::const_stmt(
429                                TsBindingName::Ident("subs".to_string()),
430                                None,
431                                TsExpr::Index {
432                                    object: Box::new(TsExpr::Ident("__eventRoutes".to_string())),
433                                    index: Box::new(match publisher {
434                                        Some(_) => TsExpr::Member {
435                                            object: Box::new(TsExpr::Ident("ev".to_string())),
436                                            property: "type".to_string(),
437                                        },
438                                        None => TsExpr::Binary {
439                                            op: TsBinaryOp::Add,
440                                            left: Box::new(TsExpr::Binary {
441                                                op: TsBinaryOp::Add,
442                                                left: Box::new(TsExpr::Member {
443                                                    object: Box::new(TsExpr::Ident(
444                                                        "ev".to_string(),
445                                                    )),
446                                                    property: "publisher".to_string(),
447                                                }),
448                                                right: Box::new(TsExpr::Lit(TsLit::Str(
449                                                    "/".to_string(),
450                                                ))),
451                                            }),
452                                            right: Box::new(TsExpr::Member {
453                                                object: Box::new(TsExpr::Ident("ev".to_string())),
454                                                property: "type".to_string(),
455                                            }),
456                                        },
457                                    }),
458                                },
459                                None,
460                            ),
461                            // `__eventRoutes` is a plain object literal — an
462                            // event type named "toString"/"constructor"/etc
463                            // would otherwise resolve off `Object.prototype` (a
464                            // truthy, non-array value `??` never catches),
465                            // throwing a `for...of` TypeError outside every
466                            // per-subscriber `try`/`catch` below. `Array.isArray`
467                            // closes it without changing the table's own
468                            // literal-object shape.
469                            TsStmt::if_stmt(
470                                TsExpr::Unary {
471                                    op: TsUnaryOp::Not,
472                                    expr: Box::new(TsExpr::Call {
473                                        callee: Box::new(TsExpr::Member {
474                                            object: Box::new(TsExpr::Ident(
475                                                "globalThis.Array".to_string(),
476                                            )),
477                                            property: "isArray".to_string(),
478                                        }),
479                                        args: vec![TsExpr::Ident("subs".to_string())],
480                                    }),
481                                },
482                                TsStmt::continue_stmt(None),
483                                None,
484                            ),
485                            TsStmt::for_of(
486                                "sub",
487                                TsExpr::Ident("subs".to_string()),
488                                TsStmt::block(
489                                    vec![
490                                        TsStmt::const_stmt(
491                                            TsBindingName::Ident("binding".to_string()),
492                                            None,
493                                            TsExpr::Index {
494                                                object: Box::new(TsExpr::Member {
495                                                    object: Box::new(TsExpr::Ident(
496                                                        "this".to_string(),
497                                                    )),
498                                                    property: "env".to_string(),
499                                                }),
500                                                index: Box::new(TsExpr::Member {
501                                                    object: Box::new(TsExpr::Ident(
502                                                        "sub".to_string(),
503                                                    )),
504                                                    property: "binding".to_string(),
505                                                }),
506                                            },
507                                            None,
508                                        ),
509                                        TsStmt::if_stmt(
510                                            TsExpr::Unary {
511                                                op: TsUnaryOp::Not,
512                                                expr: Box::new(TsExpr::Ident(
513                                                    "binding".to_string(),
514                                                )),
515                                            },
516                                            TsStmt::continue_stmt(None),
517                                            None,
518                                        ),
519                                        deliver_isolated(publisher),
520                                    ],
521                                    None,
522                                ),
523                                None,
524                            ),
525                        ])
526                        .collect(),
527                    None,
528                ),
529                None,
530            ),
531            TsStmt::return_stmt(
532                Some(TsExpr::New {
533                    callee: Box::new(TsExpr::Ident("globalThis.Response".to_string())),
534                    args: vec![
535                        TsExpr::Lit(TsLit::Null),
536                        TsExpr::object(vec![(
537                            "status".to_string(),
538                            TsExpr::Lit(TsLit::Num("204".to_string())),
539                        )]),
540                    ],
541                }),
542                None,
543            ),
544        ],
545        span: None,
546    }
547}
548
549/// Arc C's own first slice (#1317, Decision D/"Done when"): the P7.8-era
550/// `bynk-ts` test (`printer.rs`'s own
551/// `prints_events_fanout_dos_own_class_byte_identical_to_the_real_emitter`)
552/// proves the algebra can represent this file's *class* portion, built from
553/// a hand-rebuilt tree — it does not exercise `emit_events_fanout_do`
554/// itself, and never covered the header/imports/interface/table at all.
555/// This is the fresh, direct test the accepted proposal requires: calls the
556/// real, converted function with real-shaped data and asserts the printed
557/// output is byte-identical to a real fixture's own `events_fanout.ts`, not
558/// a hand-rebuilt approximation of it.
559#[cfg(test)]
560mod tests {
561    use super::*;
562
563    #[test]
564    fn matches_the_real_fixtures_own_events_fanout_ts_byte_for_byte() {
565        let expected = include_str!(
566            "../../../bynk-tests/tests/fixtures/positive/966_event_field_default_cross_context/\
567             expected/workers/commerce-order/events_fanout.ts"
568        );
569        let mut events = EventPlan::default();
570        events.subscriptions.insert(
571            ("commerce.order".to_string(), "PaymentConfirmed".to_string()),
572            vec![EventSubscription {
573                context: "commerce.notifications".to_string(),
574                service: "OnPayment".to_string(),
575                wants_envelope: false,
576            }],
577        );
578        let program = emit_events_fanout_do("commerce.order", &events);
579        let printed = bynk_ts::print(&program, "", "", "");
580        assert_eq!(printed.text, expected);
581    }
582
583    /// Review of #1317/#1318, finding 1: a context can `ctx_uses_emit`
584    /// while publishing only events nobody subscribes to
585    /// (the events plan's `published_by` filters down to
586    /// exactly this shape) — `routes` empty is real, reachable input, not
587    /// hypothetical. Pins the exact pre-conversion `writeln!` behaviour:
588    /// the `for` loop over `routes` just doesn't iterate, but the
589    /// open-brace and closing `};` lines were written unconditionally
590    /// either way.
591    #[test]
592    fn an_empty_routes_map_still_prints_the_open_and_close_brace_on_separate_lines() {
593        let program = emit_events_fanout_do("commerce.order", &EventPlan::default());
594        let printed = bynk_ts::print(&program, "", "", "");
595        assert!(
596            printed.text.contains(
597                "const __eventRoutes: globalThis.Record<string, globalThis.Array<{ binding: string; context: string; service: string }>> = {\n};\n"
598            ),
599            "expected the empty-table shape, got:\n{}",
600            printed.text
601        );
602    }
603}