Skip to main content

bynk_emit/emitter/compose/
plan.rs

1//! The composition plan (back-half paydown 1B.1b, Decisions C, D and E of
2//! #3928): what an application composes, with no spelling and no per-target
3//! entry order.
4//!
5//! Two layers. [`ComposeFacts::from_tables`] is the thin builder: it reads the
6//! checked project tables (`UnitTable`, `exec_plan`, the consume and flatten
7//! maps) into plain data. [`ComposePlan::decide`] is a pure function over that
8//! data, so a composition decision is unit-tested with hand-built
9//! [`ComposeFacts`] and no fixture.
10//!
11//! The plan records the units, each unit's dependency edges and keys, which
12//! units need `__exec` or the caller, and the cross-capability facts. It holds
13//! no binding type (Decision D of #3928). It does record the facts that imply
14//! a binding (1C.1a, Decision C of #4031): the contexts a unit calls, whether
15//! its closure reaches the bare KV namespace, the bare one-per-Worker
16//! capabilities it reaches, and whether it calls `Idempotency`.
17//! `WorkerBindings::derive` reads those facts and nothing else about the
18//! checked program's calls.
19
20use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
21
22use bynk_check::checker::{Callee, ExprId};
23use bynk_check::firstparty;
24use bynk_check::project_model::{
25    self, composed_in_bundle_root, handler_cross_caps, provider_cross_caps,
26};
27use bynk_check::symbols::UnitTable;
28use bynk_model::EventSubscriberShape;
29use bynk_project::roots::UnitKind;
30
31use super::closure::{bare_singletons_of_context, native_platforms_of_context};
32use super::events::{EventPlan, EventSubscription};
33
34/// Whether a unit's service handlers hand work to the execution context
35/// (`detach`, `within` or `race`, #2719). The two targets read different
36/// predicates, so both are facts (divergence 4 of #3928).
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub struct ExecNeeds {
39    /// Any service handler needs it: the Workers `compose` takes the request's
40    /// execution context and threads it into `deps.__exec`.
41    pub any_handler: bool,
42    /// An `on call` handler needs it: the Bundle root hands `__exec` to the
43    /// surface's `call` handlers only.
44    pub call_handler: bool,
45}
46
47/// What the builder reads off one unit's checked table. Plain data.
48#[derive(Debug, Clone, Default)]
49pub struct ComposeUnitFacts {
50    pub is_context: bool,
51    /// The units it consumes, in declaration order.
52    pub consumes: Vec<String>,
53    /// Alias -> consumed unit.
54    pub aliases: HashMap<String, String>,
55    pub has_services: bool,
56    pub has_agents: bool,
57    /// A service declares an `on call ... by c: Caller` handler (ADR 0092).
58    pub binds_caller: bool,
59    /// A handler publishes an event (`Events.emit`).
60    pub publishes: bool,
61    pub exec: ExecNeeds,
62    /// Own providers' capability keys, in dependency order.
63    pub providers: Vec<String>,
64    /// Derived capabilities' keys (S4a), sorted.
65    pub derived: Vec<String>,
66    /// `deps_key -> consumed unit` for what handlers and agents `given`.
67    pub handler_cross_caps: BTreeMap<String, String>,
68    /// `deps_key -> consumed unit` for what own providers `given`.
69    pub provider_cross_caps: BTreeMap<String, String>,
70    /// The shape of each `from Events` service the unit hosts, by service name.
71    pub event_shapes: BTreeMap<String, EventSubscriberShape>,
72    /// The consumed contexts its bodies and agents call, in name order. A
73    /// Service Binding exists for a context that is called, never merely
74    /// consumed (#1961).
75    pub called: Vec<String>,
76    /// Its closure reaches the bare KV namespace (the cloudflare adapter's
77    /// `Kv`), so its Worker declares `KV`. A named instance does not imply it.
78    pub bare_kv: bool,
79    /// The one-per-Worker `bynk.cloudflare` capabilities its closure reaches
80    /// bare (#3300), in name order.
81    pub bare_singletons: Vec<String>,
82    /// A body calls `Idempotency`, so its Worker declares the implicit
83    /// database that holds the claims (W30, #2840).
84    pub idempotency: bool,
85}
86
87/// Everything [`ComposePlan::decide`] needs, as plain data.
88#[derive(Debug, Clone, Default)]
89pub struct ComposeFacts {
90    /// Every unit that has a checked table, by name.
91    pub units: BTreeMap<String, ComposeUnitFacts>,
92    /// Whether a Bundle build has a composition root at all
93    /// (`composition_root_trigger`).
94    pub bundle_root: bool,
95    /// `bynk_check::symbols::discover_event_subscribers`' table: each event's
96    /// subscribers as `(context, service)`, keyed `(publishing context, event)`.
97    pub event_subscribers: BTreeMap<(String, String), Vec<(String, String)>>,
98}
99
100impl ComposeFacts {
101    /// Read the facts off the checked project tables.
102    #[allow(clippy::too_many_arguments)]
103    pub fn from_tables(
104        kinds: &BTreeMap<String, UnitKind>,
105        unit_consumes: &HashMap<String, Vec<String>>,
106        unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
107        unit_tables: &HashMap<String, UnitTable>,
108        unit_callees: &HashMap<String, HashMap<ExprId, Callee>>,
109        unit_flattened: &HashMap<String, HashMap<String, String>>,
110        event_subscribers: &BTreeMap<(String, String), Vec<(String, String)>>,
111        unit_event_subscriber_shapes: &HashMap<String, HashMap<String, EventSubscriberShape>>,
112    ) -> Self {
113        let bundle_root = project_model::composition_root_trigger(
114            kinds,
115            unit_consumes,
116            unit_consumes_aliases,
117            unit_tables,
118            unit_callees,
119            unit_flattened,
120        )
121        .is_some();
122        let mut units = BTreeMap::new();
123        for (name, table) in unit_tables {
124            let consumes = unit_consumes.get(name).cloned().unwrap_or_default();
125            let aliases = unit_consumes_aliases.get(name).cloned().unwrap_or_default();
126            let flattened = unit_flattened.get(name).cloned().unwrap_or_default();
127            let mut derived: Vec<String> = table.derived.keys().cloned().collect();
128            derived.sort();
129            let handlers = || table.services.values().flat_map(|s| s.handlers.iter());
130            let is_context = kinds.get(name) == Some(&UnitKind::Context);
131            let (called, bare_kv, bare_singletons) = if is_context {
132                binding_facts(
133                    name,
134                    table,
135                    kinds,
136                    (&consumes, &aliases),
137                    (
138                        unit_tables,
139                        unit_consumes,
140                        unit_consumes_aliases,
141                        unit_flattened,
142                    ),
143                    unit_callees.get(name),
144                )
145            } else {
146                Default::default()
147            };
148            units.insert(
149                name.clone(),
150                ComposeUnitFacts {
151                    is_context,
152                    has_services: composed_in_bundle_root(table),
153                    has_agents: !table.agents.is_empty(),
154                    binds_caller: crate::emitter::any_service_binds_caller(
155                        table.services.values(),
156                        &table.actors,
157                    ),
158                    publishes: crate::emit_model::unit_table_uses_emit(
159                        table,
160                        unit_callees.get(name),
161                    ),
162                    exec: ExecNeeds {
163                        any_handler: handlers().any(|h| table.exec_plan.handler_needs(h)),
164                        call_handler: handlers()
165                            .any(|h| crate::emitter::call_handler_needs_exec(&table.exec_plan, h)),
166                    },
167                    providers: crate::emitter::topo_order_providers(&table.providers),
168                    derived,
169                    handler_cross_caps: handler_cross_caps(
170                        table, name, &consumes, &aliases, &flattened,
171                    ),
172                    provider_cross_caps: provider_cross_caps(
173                        table, name, &consumes, &aliases, &flattened,
174                    ),
175                    event_shapes: unit_event_subscriber_shapes
176                        .get(name)
177                        .map(|shapes| {
178                            shapes
179                                .iter()
180                                .map(|(s, shape)| (s.clone(), *shape))
181                                .collect()
182                        })
183                        .unwrap_or_default(),
184                    called,
185                    bare_kv,
186                    bare_singletons,
187                    idempotency: crate::emit_model::unit_table_uses_idempotency(
188                        table,
189                        unit_callees.get(name),
190                    ),
191                    consumes,
192                    aliases,
193                },
194            );
195        }
196        Self {
197            units,
198            bundle_root,
199            event_subscribers: event_subscribers.clone(),
200        }
201    }
202}
203
204/// A consumed context's service surface, as the consumer's `deps` carries it
205/// on the Bundle target (divergence 6).
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct ConsumedSurface {
208    /// The consumer's key: the alias, else the target's last name segment.
209    pub key: String,
210    /// The consumed unit.
211    pub target: String,
212    /// The target has an `on call ... by c: Caller` handler, so the consumer
213    /// needs a surface built with its own name rather than the shared one.
214    pub per_caller: bool,
215}
216
217/// One unit of the plan: facts, not text.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct ComposeUnit {
220    pub is_context: bool,
221    /// Consumed units, in declaration order (a dependency edge list, not a
222    /// rendering order).
223    pub consumes: Vec<String>,
224    pub has_services: bool,
225    pub has_agents: bool,
226    pub binds_caller: bool,
227    pub publishes: bool,
228    pub exec: ExecNeeds,
229    /// Own providers' capability keys, in dependency order.
230    pub providers: Vec<String>,
231    pub derived: Vec<String>,
232    pub handler_cross_caps: BTreeMap<String, String>,
233    pub provider_cross_caps: BTreeMap<String, String>,
234    /// Consumed contexts that have services, sorted by target.
235    pub surfaces: Vec<ConsumedSurface>,
236    /// For each `from Events` service the unit hosts: whether its `on event`
237    /// handler is handed the event's envelope (`wants_envelope`).
238    pub subscriber_envelopes: BTreeMap<String, bool>,
239    /// The consumed contexts its bodies and agents call, in name order
240    /// ([`ComposeUnitFacts::called`]).
241    pub called: Vec<String>,
242    /// Its closure reaches the bare KV namespace.
243    pub bare_kv: bool,
244    /// The bare one-per-Worker capabilities its closure reaches.
245    pub bare_singletons: Vec<String>,
246    /// A body calls `Idempotency`.
247    pub idempotency: bool,
248}
249
250impl ComposeUnit {
251    /// Whether the `on event` handler of `service`, a `from Events` service this
252    /// unit hosts, is handed the envelope. Every hosted events service has a
253    /// shape, so a miss is an internal error and not a `false`: the callee would
254    /// still insert its positional envelope parameter and bind `deps` into it.
255    pub fn hosted_wants_envelope(&self, unit: &str, service: &str) -> bool {
256        *self.subscriber_envelopes.get(service).unwrap_or_else(|| {
257            panic!(
258                "bynk internal error: the events service `{service}` of unit `{unit}` has no \
259                 recorded subscriber shape"
260            )
261        })
262    }
263
264    /// Every cross-context capability the unit uses, handlers' and providers'
265    /// together; a key both name keeps the handlers' source. Which of the two
266    /// sets a target instantiates at the top level is the renderer's choice
267    /// (divergence 3).
268    pub fn cross_caps(&self) -> BTreeMap<String, String> {
269        let mut all = self.handler_cross_caps.clone();
270        for (key, unit) in &self.provider_cross_caps {
271            all.entry(key.clone()).or_insert_with(|| unit.clone());
272        }
273        all
274    }
275}
276
277/// What an application composes.
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct ComposePlan {
280    /// Every unit with a checked table.
281    pub units: BTreeMap<String, ComposeUnit>,
282    /// The Bundle root's contexts in dependency order, a consumed context
283    /// before its consumer: those it composes (it has services). Workers have
284    /// no cross-unit order, as a Service Binding reaches the other Worker.
285    pub bundle_order: Vec<String>,
286    /// Whether a Bundle build has a composition root.
287    pub bundle_root: bool,
288    /// Who subscribes to what, with each subscription's envelope decision.
289    pub events: EventPlan,
290}
291
292impl ComposePlan {
293    /// Build the plan from the checked project tables.
294    #[allow(clippy::too_many_arguments)]
295    pub fn build(
296        kinds: &BTreeMap<String, UnitKind>,
297        unit_consumes: &HashMap<String, Vec<String>>,
298        unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
299        unit_tables: &HashMap<String, UnitTable>,
300        unit_callees: &HashMap<String, HashMap<ExprId, Callee>>,
301        unit_flattened: &HashMap<String, HashMap<String, String>>,
302        event_subscribers: &BTreeMap<(String, String), Vec<(String, String)>>,
303        unit_event_subscriber_shapes: &HashMap<String, HashMap<String, EventSubscriberShape>>,
304    ) -> Self {
305        Self::decide(&ComposeFacts::from_tables(
306            kinds,
307            unit_consumes,
308            unit_consumes_aliases,
309            unit_tables,
310            unit_callees,
311            unit_flattened,
312            event_subscribers,
313            unit_event_subscriber_shapes,
314        ))
315    }
316
317    /// The units that are contexts, by name.
318    pub fn contexts(&self) -> impl Iterator<Item = (&String, &ComposeUnit)> {
319        self.units.iter().filter(|(_, u)| u.is_context)
320    }
321
322    /// The pure decision: units, their surfaces, and the Bundle order.
323    pub fn decide(facts: &ComposeFacts) -> Self {
324        let units = facts
325            .units
326            .iter()
327            .map(|(name, f)| (name.clone(), Self::decide_unit(f, facts)))
328            .collect();
329        Self {
330            units,
331            bundle_order: bundle_order(facts),
332            bundle_root: facts.bundle_root,
333            events: decide_events(facts),
334        }
335    }
336
337    fn decide_unit(f: &ComposeUnitFacts, facts: &ComposeFacts) -> ComposeUnit {
338        ComposeUnit {
339            is_context: f.is_context,
340            consumes: f.consumes.clone(),
341            has_services: f.has_services,
342            has_agents: f.has_agents,
343            binds_caller: f.binds_caller,
344            publishes: f.publishes,
345            exec: f.exec,
346            providers: f.providers.clone(),
347            derived: f.derived.clone(),
348            handler_cross_caps: f.handler_cross_caps.clone(),
349            provider_cross_caps: f.provider_cross_caps.clone(),
350            surfaces: surfaces(f, facts),
351            subscriber_envelopes: f
352                .event_shapes
353                .iter()
354                .map(|(service, shape)| (service.clone(), shape.wants_envelope()))
355                .collect(),
356            called: f.called.clone(),
357            bare_kv: f.bare_kv,
358            bare_singletons: f.bare_singletons.clone(),
359            idempotency: f.idempotency,
360        }
361    }
362}
363
364/// The binding facts of a context ([`ComposeUnitFacts::called`], `bare_kv` and
365/// `bare_singletons`). The last two walk the provider graph, so the plan is
366/// built only on a program whose earlier checks passed.
367#[allow(clippy::type_complexity)]
368fn binding_facts(
369    name: &str,
370    table: &UnitTable,
371    kinds: &BTreeMap<String, UnitKind>,
372    (consumes, aliases): (&[String], &HashMap<String, String>),
373    (unit_tables, unit_consumes, unit_consumes_aliases, unit_flattened): (
374        &HashMap<String, UnitTable>,
375        &HashMap<String, Vec<String>>,
376        &HashMap<String, HashMap<String, String>>,
377        &HashMap<String, HashMap<String, String>>,
378    ),
379    callees: Option<&HashMap<ExprId, Callee>>,
380) -> (Vec<String>, bool, Vec<String>) {
381    let mut called: BTreeSet<String> =
382        crate::emit_model::called_cross_context_services(table, consumes, callees)
383            .into_keys()
384            .collect();
385    // A handler constructing an agent hands it its own `deps`, whose `env` type
386    // names the contexts the agent calls (#1960, #1961).
387    called.extend(crate::emitter::agent_cross_context_targets(
388        table,
389        |chain| {
390            let target = aliases
391                .get(chain)
392                .cloned()
393                .or_else(|| consumes.iter().find(|c| *c == chain).cloned())?;
394            (kinds.get(&target) == Some(&UnitKind::Context)).then_some(target)
395        },
396    ));
397    let bare_kv = native_platforms_of_context(
398        name,
399        table,
400        unit_tables,
401        unit_consumes,
402        unit_consumes_aliases,
403        unit_flattened,
404        false,
405    )
406    .values()
407    .any(|u| u == firstparty::CLOUDFLARE_UNIT);
408    let bare_singletons = bare_singletons_of_context(
409        name,
410        table,
411        unit_tables,
412        unit_consumes,
413        unit_consumes_aliases,
414        unit_flattened,
415    )
416    .into_iter()
417    .filter(|(unit, _)| unit == firstparty::CLOUDFLARE_UNIT)
418    .map(|(_, cap)| cap)
419    .collect();
420    (called.into_iter().collect(), bare_kv, bare_singletons)
421}
422
423/// Each subscription takes the envelope its subscriber's shape wants. A
424/// subscriber with no shape recorded is not handed one.
425fn decide_events(facts: &ComposeFacts) -> EventPlan {
426    let subscriptions = facts
427        .event_subscribers
428        .iter()
429        .map(|(key, subs)| {
430            let subs = subs
431                .iter()
432                .map(|(context, service)| EventSubscription {
433                    context: context.clone(),
434                    service: service.clone(),
435                    wants_envelope: facts
436                        .units
437                        .get(context)
438                        .and_then(|u| u.event_shapes.get(service))
439                        .is_some_and(EventSubscriberShape::wants_envelope),
440                })
441                .collect();
442            (key.clone(), subs)
443        })
444        .collect();
445    EventPlan { subscriptions }
446}
447
448/// A consumed context that has services is a surface of the consumer's `deps`.
449fn surfaces(f: &ComposeUnitFacts, facts: &ComposeFacts) -> Vec<ConsumedSurface> {
450    let mut alias_for: HashMap<&String, &String> = HashMap::new();
451    for (alias, target) in &f.aliases {
452        alias_for.insert(target, alias);
453    }
454    let mut targets: Vec<&String> = f.consumes.iter().collect();
455    targets.sort();
456    targets
457        .into_iter()
458        .filter_map(|t| {
459            let other = facts.units.get(t)?;
460            if !other.has_services {
461                return None;
462            }
463            let key = alias_for
464                .get(t)
465                .map(|a| (*a).clone())
466                .unwrap_or_else(|| t.rsplit('.').next().unwrap_or(t.as_str()).to_string());
467            Some(ConsumedSurface {
468                key,
469                target: t.clone(),
470                per_caller: other.binds_caller,
471            })
472        })
473        .collect()
474}
475
476/// A depth-first walk over `consumes`, so a consumed context comes before its
477/// consumer; only contexts the root composes are kept.
478fn bundle_order(facts: &ComposeFacts) -> Vec<String> {
479    fn visit(
480        node: &str,
481        facts: &ComposeFacts,
482        visited: &mut HashSet<String>,
483        out: &mut Vec<String>,
484    ) {
485        if !visited.insert(node.to_string()) {
486            return;
487        }
488        if let Some(unit) = facts.units.get(node) {
489            for t in &unit.consumes {
490                visit(t, facts, visited, out);
491            }
492        }
493        out.push(node.to_string());
494    }
495    let mut visited = HashSet::new();
496    let mut walked = Vec::new();
497    for (name, unit) in &facts.units {
498        if unit.is_context {
499            visit(name, facts, &mut visited, &mut walked);
500        }
501    }
502    walked
503        .into_iter()
504        .filter(|n| {
505            facts
506                .units
507                .get(n)
508                .is_some_and(|u| u.is_context && u.has_services)
509        })
510        .collect()
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516
517    fn ctx(consumes: &[&str]) -> ComposeUnitFacts {
518        ComposeUnitFacts {
519            is_context: true,
520            has_services: true,
521            consumes: consumes.iter().map(|s| s.to_string()).collect(),
522            ..ComposeUnitFacts::default()
523        }
524    }
525
526    fn facts(units: Vec<(&str, ComposeUnitFacts)>) -> ComposeFacts {
527        ComposeFacts {
528            units: units.into_iter().map(|(n, f)| (n.to_string(), f)).collect(),
529            bundle_root: true,
530            ..ComposeFacts::default()
531        }
532    }
533
534    #[test]
535    fn a_unit_with_no_dependencies_has_no_surfaces_and_no_caps() {
536        let plan = ComposePlan::decide(&facts(vec![("shop", ctx(&[]))]));
537        let unit = &plan.units["shop"];
538        assert!(unit.surfaces.is_empty());
539        assert!(unit.cross_caps().is_empty());
540        assert!(!unit.exec.any_handler && !unit.exec.call_handler);
541        assert_eq!(plan.bundle_order, vec!["shop".to_string()]);
542    }
543
544    #[test]
545    fn a_dependency_chain_orders_a_consumed_context_before_its_consumer() {
546        // `a` consumes `b`, `b` consumes `c`: the names sort the other way.
547        let plan = ComposePlan::decide(&facts(vec![
548            ("a", ctx(&["b"])),
549            ("b", ctx(&["c"])),
550            ("c", ctx(&[])),
551        ]));
552        assert_eq!(plan.bundle_order, ["c", "b", "a"]);
553        assert_eq!(plan.units["a"].surfaces[0].target, "b");
554        assert_eq!(plan.units["a"].surfaces[0].key, "b");
555        assert_eq!(plan.units["b"].surfaces[0].target, "c");
556    }
557
558    #[test]
559    fn a_surface_takes_the_alias_else_the_last_segment_and_skips_a_serviceless_unit() {
560        let mut consumer = ctx(&["shop.billing", "shop.ledger", "shop.static"]);
561        consumer
562            .aliases
563            .insert("pay".to_string(), "shop.billing".to_string());
564        let mut serviceless = ctx(&[]);
565        serviceless.has_services = false;
566        let plan = ComposePlan::decide(&facts(vec![
567            ("app", consumer),
568            ("shop.billing", ctx(&[])),
569            ("shop.ledger", ctx(&[])),
570            ("shop.static", serviceless),
571        ]));
572        let keys: Vec<(&str, &str)> = plan.units["app"]
573            .surfaces
574            .iter()
575            .map(|s| (s.key.as_str(), s.target.as_str()))
576            .collect();
577        assert_eq!(keys, [("pay", "shop.billing"), ("ledger", "shop.ledger")]);
578        // A context without services is consumed but not composed.
579        assert!(!plan.bundle_order.contains(&"shop.static".to_string()));
580    }
581
582    #[test]
583    fn a_caller_binding_provider_makes_the_consumers_surface_per_caller() {
584        let mut provider = ctx(&[]);
585        provider.binds_caller = true;
586        let plan = ComposePlan::decide(&facts(vec![
587            ("app", ctx(&["svc", "plain"])),
588            ("svc", provider),
589            ("plain", ctx(&[])),
590        ]));
591        let by_target: HashMap<&str, bool> = plan.units["app"]
592            .surfaces
593            .iter()
594            .map(|s| (s.target.as_str(), s.per_caller))
595            .collect();
596        assert!(by_target["svc"]);
597        assert!(!by_target["plain"]);
598        assert!(plan.units["svc"].binds_caller);
599    }
600
601    #[test]
602    fn an_exec_unit_keeps_both_predicates_apart() {
603        let mut any = ctx(&[]);
604        any.exec = ExecNeeds {
605            any_handler: true,
606            call_handler: false,
607        };
608        let mut call = ctx(&[]);
609        call.exec = ExecNeeds {
610            any_handler: true,
611            call_handler: true,
612        };
613        let plan = ComposePlan::decide(&facts(vec![("any", any), ("call", call)]));
614        assert_eq!(
615            plan.units["any"].exec,
616            ExecNeeds {
617                any_handler: true,
618                call_handler: false
619            }
620        );
621        assert!(plan.units["call"].exec.call_handler);
622    }
623
624    #[test]
625    fn a_providers_given_adds_a_cross_capability_the_handlers_do_not_use() {
626        let mut unit = ctx(&["bank"]);
627        unit.handler_cross_caps
628            .insert("Ledger".to_string(), "bank".to_string());
629        unit.provider_cross_caps
630            .insert("Audit".to_string(), "bank".to_string());
631        // A key both name keeps the handlers' source.
632        unit.provider_cross_caps
633            .insert("Ledger".to_string(), "other".to_string());
634        let plan = ComposePlan::decide(&facts(vec![("app", unit)]));
635        let unit = &plan.units["app"];
636        assert_eq!(
637            unit.handler_cross_caps.keys().collect::<Vec<_>>(),
638            ["Ledger"]
639        );
640        let all = unit.cross_caps();
641        assert_eq!(all.keys().collect::<Vec<_>>(), ["Audit", "Ledger"]);
642        assert_eq!(all["Ledger"], "bank");
643        assert_eq!(all["Audit"], "bank");
644    }
645
646    #[test]
647    fn a_subscription_takes_the_envelope_its_subscribers_shape_wants() {
648        let shaped = |two_param_handler, schema_dispatch| {
649            let mut unit = ctx(&[]);
650            unit.event_shapes.insert(
651                "On".to_string(),
652                EventSubscriberShape {
653                    two_param_handler,
654                    schema_dispatch,
655                },
656            );
657            unit
658        };
659        let mut f = facts(vec![
660            ("pub", ctx(&[])),
661            ("plain", shaped(false, false)),
662            ("two", shaped(true, false)),
663            ("schema", shaped(false, true)),
664        ]);
665        f.event_subscribers.insert(
666            ("pub".to_string(), "E".to_string()),
667            ["plain", "two", "schema", "unknown"]
668                .iter()
669                .map(|c| (c.to_string(), "On".to_string()))
670                .collect(),
671        );
672        let plan = ComposePlan::decide(&f);
673        let wants: Vec<(&str, bool)> = plan
674            .events
675            .published_by("pub")
676            .flat_map(|(_, subs)| subs)
677            .map(|s| (s.context.as_str(), s.wants_envelope))
678            .collect();
679        assert_eq!(
680            wants,
681            [
682                ("plain", false),
683                ("two", true),
684                ("schema", true),
685                ("unknown", false)
686            ]
687        );
688        // The unit's own table of its subscribers agrees (the Workers wrapper reads it).
689        assert!(plan.units["two"].subscriber_envelopes["On"]);
690        assert!(!plan.units["plain"].subscriber_envelopes["On"]);
691    }
692
693    #[test]
694    #[should_panic(
695        expected = "the events service `On` of unit `shop` has no recorded subscriber shape"
696    )]
697    fn a_hosted_events_service_without_a_shape_is_an_internal_error() {
698        let plan = ComposePlan::decide(&facts(vec![("shop", ctx(&[]))]));
699        plan.units["shop"].hosted_wants_envelope("shop", "On");
700    }
701}