bynk_emit/emitter/compose/events.rs
1//! Events in the composition (back-half paydown 1B.1c, Decisions F and I of
2//! #3928): what is subscribed to what, and the failure-isolation statement
3//! every delivery path shares.
4//!
5//! The subscriber table is one function, `bynk_check::symbols::
6//! discover_event_subscribers`. This module holds the facts built on top of it
7//! (each subscription's envelope decision) and the one builder of ADR 0284's
8//! guarantee, so the Bundle root's in-process dispatch and the Workers fan-out
9//! Durable Object cannot drift: neither spells the `try`/`catch` itself.
10
11use std::collections::BTreeMap;
12
13use crate::ts_build::{call, ident, member, str_lit};
14use bynk_ts::{TsExpr, TsStmt};
15
16/// The message a failed delivery logs. The structural guard of Decision I
17/// (`xtask`'s `delivery_isolation_has_one_home`) counts this literal in
18/// production source: it must appear once, here, so a second copy of the
19/// isolation code is a CI failure.
20const DELIVERY_FAILED: &str = "EventsFanout delivery failed";
21
22/// One subscription: a service that subscribes to a publisher's event, and
23/// whether a delivery to it carries the event's envelope.
24///
25/// Every subscription is delivered in isolation (ADR 0284): that is the rule
26/// of `isolated_delivery`, not a per-subscription choice, so it is not a
27/// field here.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct EventSubscription {
30 pub context: String,
31 pub service: String,
32 /// The subscriber's `EventSubscriberShape::wants_envelope`.
33 pub wants_envelope: bool,
34}
35
36/// Who subscribes to what, keyed `(publishing context, event)`. Plain facts:
37/// each renderer decides how to deliver.
38#[derive(Debug, Clone, Default, PartialEq, Eq)]
39pub struct EventPlan {
40 /// Each event's subscribers, in `discover_event_subscribers`' order.
41 pub subscriptions: BTreeMap<(String, String), Vec<EventSubscription>>,
42}
43
44impl EventPlan {
45 /// The subscriptions to the events `publisher` declares, by event name.
46 pub fn published_by<'a>(
47 &'a self,
48 publisher: &'a str,
49 ) -> impl Iterator<Item = (&'a str, &'a [EventSubscription])> {
50 self.subscriptions
51 .iter()
52 .filter(move |((p, _), _)| p == publisher)
53 .map(|((_, event), subs)| (event.as_str(), subs.as_slice()))
54 }
55}
56
57/// `try { await <delivery>; } catch (e) { globalThis.console.error("EventsFanout
58/// delivery failed", { event: ev.type, service: <service>, error: String(e) }); }`.
59///
60/// ADR 0284: subscriber failure isolation. One subscriber's rejection is logged
61/// and does not stop delivery to the remaining subscribers, nor does it
62/// propagate back to the (already-committed) publishing handler. Both targets
63/// build it here: the Bundle's in-process dispatch and the Workers fan-out
64/// Durable Object. `delivery` is the call that delivers, spelled by the
65/// renderer; `service` is the expression the log names the subscriber by.
66/// Both read the event as `ev`.
67pub(crate) fn isolated_delivery(delivery: TsExpr, service: TsExpr) -> TsStmt {
68 TsStmt::try_catch(
69 TsStmt::block(
70 vec![TsStmt::expr_stmt(TsExpr::Await(Box::new(delivery)), None)],
71 None,
72 ),
73 Some("e"),
74 TsStmt::block(
75 vec![TsStmt::expr_stmt(
76 call(
77 member(ident("globalThis.console"), "error"),
78 vec![
79 str_lit(DELIVERY_FAILED),
80 TsExpr::object(vec![
81 ("event".to_string(), member(ident("ev"), "type")),
82 ("service".to_string(), service),
83 ("error".to_string(), call(ident("String"), vec![ident("e")])),
84 ]),
85 ],
86 ),
87 None,
88 )],
89 None,
90 ),
91 None,
92 )
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn a_publishers_subscriptions_come_by_event_name() {
101 let sub = |context: &str, wants_envelope| EventSubscription {
102 context: context.to_string(),
103 service: "S".to_string(),
104 wants_envelope,
105 };
106 let mut plan = EventPlan::default();
107 plan.subscriptions
108 .insert(("b".into(), "Z".into()), vec![sub("x", false)]);
109 plan.subscriptions
110 .insert(("a".into(), "Y".into()), vec![sub("x", true)]);
111 plan.subscriptions
112 .insert(("a".into(), "X".into()), vec![sub("y", false)]);
113 let names: Vec<&str> = plan.published_by("a").map(|(e, _)| e).collect();
114 assert_eq!(names, ["X", "Y"]);
115 assert_eq!(plan.published_by("none").count(), 0);
116 }
117
118 #[test]
119 fn isolated_delivery_logs_the_failure_instead_of_propagating_it() {
120 let stmt = isolated_delivery(call(ident("deliver"), vec![]), str_lit("Svc"));
121 let text = bynk_ts::print_stmt(&stmt, 0);
122 assert!(text.contains("await deliver()"), "{text}");
123 assert!(text.contains("catch (e)"), "{text}");
124 assert!(text.contains(DELIVERY_FAILED), "{text}");
125 assert!(text.contains("service: \"Svc\""), "{text}");
126 assert!(text.contains("error: String(e)"), "{text}");
127 }
128}