1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub struct ExecNeeds {
39 pub any_handler: bool,
42 pub call_handler: bool,
45}
46
47#[derive(Debug, Clone, Default)]
49pub struct ComposeUnitFacts {
50 pub is_context: bool,
51 pub consumes: Vec<String>,
53 pub aliases: HashMap<String, String>,
55 pub has_services: bool,
56 pub has_agents: bool,
57 pub binds_caller: bool,
59 pub publishes: bool,
61 pub exec: ExecNeeds,
62 pub providers: Vec<String>,
64 pub derived: Vec<String>,
66 pub handler_cross_caps: BTreeMap<String, String>,
68 pub provider_cross_caps: BTreeMap<String, String>,
70 pub event_shapes: BTreeMap<String, EventSubscriberShape>,
72 pub called: Vec<String>,
76 pub bare_kv: bool,
79 pub bare_singletons: Vec<String>,
82 pub idempotency: bool,
85}
86
87#[derive(Debug, Clone, Default)]
89pub struct ComposeFacts {
90 pub units: BTreeMap<String, ComposeUnitFacts>,
92 pub bundle_root: bool,
95 pub event_subscribers: BTreeMap<(String, String), Vec<(String, String)>>,
98}
99
100impl ComposeFacts {
101 #[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#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct ConsumedSurface {
208 pub key: String,
210 pub target: String,
212 pub per_caller: bool,
215}
216
217#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct ComposeUnit {
220 pub is_context: bool,
221 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 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 pub surfaces: Vec<ConsumedSurface>,
236 pub subscriber_envelopes: BTreeMap<String, bool>,
239 pub called: Vec<String>,
242 pub bare_kv: bool,
244 pub bare_singletons: Vec<String>,
246 pub idempotency: bool,
248}
249
250impl ComposeUnit {
251 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 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#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct ComposePlan {
280 pub units: BTreeMap<String, ComposeUnit>,
282 pub bundle_order: Vec<String>,
286 pub bundle_root: bool,
288 pub events: EventPlan,
290}
291
292impl ComposePlan {
293 #[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 pub fn contexts(&self) -> impl Iterator<Item = (&String, &ComposeUnit)> {
319 self.units.iter().filter(|(_, u)| u.is_context)
320 }
321
322 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#[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 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
423fn 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
448fn 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
476fn 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 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 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 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 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}