1use std::collections::{BTreeMap, BTreeSet, HashMap};
20use std::path::PathBuf;
21
22use bynk_project::ParsedFile;
23use bynk_syntax::ast::{CommonsItem, ServiceProtocol, SourceUnit};
24use bynk_syntax::error::CompileError;
25use bynk_syntax::span::Span;
26
27use crate::firstparty;
28use crate::project_model::ErrorSink;
29
30pub fn screaming_snake(name: &str) -> String {
35 let mut out = String::new();
36 for (i, ch) in name.chars().enumerate() {
37 if i > 0 && ch.is_uppercase() {
38 out.push('_');
39 }
40 out.push(ch.to_ascii_uppercase());
41 }
42 out
43}
44
45pub fn instance_binding_name(prefix: &str, capability: &str) -> String {
49 format!("{prefix}_{}", screaming_snake(capability))
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum BindingSource {
59 Service { context: String },
65 Kv,
69 KvInstance { capability: String },
73 ForeignService { capability: String, worker: String },
78 R2Instance {
83 capability: String,
84 jurisdiction: Option<String>,
85 },
86 RateLimitInstance {
92 capability: String,
93 limit: i64,
94 period: i64,
95 },
96 QueueProducer { capability: String, queue: String },
102 AnalyticsDataset { capability: String },
107 D1Database { capability: String },
112 StoredSecret {
119 capability: String,
120 store: String,
121 secret: String,
122 },
123 Email {
128 capability: String,
129 to: Option<String>,
130 allowed_recipients: Vec<String>,
131 allowed_senders: Vec<String>,
132 },
133 Postgres { capability: String },
138 MySql {
143 capability: String,
144 tls: Option<String>,
145 },
146 VectorizeIndex {
154 capability: String,
155 dimensions: i64,
156 metric: String,
157 indexed: Vec<String>,
158 },
159 ContainerInstance {
169 capability: String,
170 class_name: String,
171 build: String,
172 root_from_worker: String,
176 port: i64,
177 sleep_after: Option<i64>,
178 instance_type: Option<String>,
179 forward: Vec<String>,
180 },
181 AiSearchInstance {
188 capability: String,
189 instance: String,
190 },
191 MtlsCertificate {
198 capability: String,
199 certificate: String,
200 },
201 Singleton { capability: String },
207 Agent { class_name: String },
210 EventsFanout { class_name: String },
214}
215
216pub const IMPLICIT_IDEMPOTENCY_CAPABILITY: &str = "@idempotency";
222
223pub fn idempotency_binding() -> WorkerBinding {
226 WorkerBinding {
227 name: crate::d1_migrations::IDEMPOTENCY_BINDING.to_string(),
228 source: BindingSource::D1Database {
229 capability: IMPLICIT_IDEMPOTENCY_CAPABILITY.to_string(),
230 },
231 }
232}
233
234impl BindingSource {
235 pub fn describe(&self) -> String {
237 match self {
238 Self::Service { context } => format!("the Service Binding to context `{context}`"),
239 Self::Kv => format!(
240 "the KV namespace binding of `{}`'s `Kv`",
241 firstparty::CLOUDFLARE_UNIT
242 ),
243 Self::KvInstance { capability } => {
244 format!("the KV namespace binding of derived capability `{capability}`")
245 }
246 Self::ForeignService { capability, worker } => format!(
247 "the Service Binding of derived capability `{capability}` (to Worker `{worker}`)"
248 ),
249 Self::R2Instance { capability, .. } => {
250 format!("the R2 bucket binding of derived capability `{capability}`")
251 }
252 Self::RateLimitInstance { capability, .. } => {
253 format!("the rate limiting binding of derived capability `{capability}`")
254 }
255 Self::QueueProducer { capability, queue } => format!(
256 "the queue producer binding of derived capability `{capability}` (to queue `{queue}`)"
257 ),
258 Self::AnalyticsDataset { capability } => {
259 format!("the Analytics Engine binding of derived capability `{capability}`")
260 }
261 Self::D1Database { capability } if capability == IMPLICIT_IDEMPOTENCY_CAPABILITY => {
262 "the implicit idempotency database of a Worker that calls `Idempotency.claim`"
263 .to_string()
264 }
265 Self::D1Database { capability } => {
266 format!("the D1 database binding of derived capability `{capability}`")
267 }
268 Self::StoredSecret {
269 capability, store, ..
270 } => format!(
271 "the Secrets Store binding of derived capability `{capability}` (to store `{store}`)"
272 ),
273 Self::Email { capability, .. } => {
274 format!("the `[[send_email]]` binding of derived capability `{capability}`")
275 }
276 Self::VectorizeIndex { capability, .. } => {
277 format!("the `[[vectorize]]` binding of derived capability `{capability}`")
278 }
279 Self::ContainerInstance { capability, .. } => {
280 format!(
281 "the Durable Object binding of the container of derived capability `{capability}`"
282 )
283 }
284 Self::AiSearchInstance {
285 capability,
286 instance,
287 } => format!(
288 "the `[[ai_search]]` binding of derived capability `{capability}` (to instance `{instance}`)"
289 ),
290 Self::MtlsCertificate {
291 capability,
292 certificate,
293 } => format!(
294 "the `[[mtls_certificates]]` binding of derived capability `{capability}` (to certificate `{certificate}`)"
295 ),
296 Self::Postgres { capability } | Self::MySql { capability, .. } => {
297 format!("the `[[hyperdrive]]` binding of derived capability `{capability}`")
298 }
299 Self::Singleton { capability } => format!(
300 "the `{capability}` binding of `{}`",
301 firstparty::CLOUDFLARE_UNIT
302 ),
303 Self::Agent { class_name } => {
304 format!("the Durable Object binding of agent `{class_name}`")
305 }
306 Self::EventsFanout { .. } => {
307 "the Durable Object binding of the events fan-out".to_string()
308 }
309 }
310 }
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct WorkerBinding {
317 pub name: String,
318 pub source: BindingSource,
319}
320
321pub fn duplicate_bindings(bindings: &[WorkerBinding]) -> Vec<(&WorkerBinding, &WorkerBinding)> {
324 let mut first: HashMap<&str, &WorkerBinding> = HashMap::new();
325 let mut duplicates = Vec::new();
326 for binding in bindings {
327 match first.get(binding.name.as_str()) {
328 Some(earlier) => duplicates.push((*earlier, binding)),
329 None => {
330 first.insert(&binding.name, binding);
331 }
332 }
333 }
334 duplicates
335}
336
337pub fn phase_duplicate_bindings(
346 parsed: &[ParsedFile],
347 groups: &BTreeMap<String, Vec<usize>>,
348 bindings: &BTreeMap<String, Vec<WorkerBinding>>,
349 errors: &mut ErrorSink,
350) {
351 for (ctx, ctx_bindings) in bindings {
352 let indices = groups.get(ctx).map(Vec::as_slice).unwrap_or_default();
353 for (earlier, later) in duplicate_bindings(ctx_bindings) {
354 let mut sources = [later, earlier];
358 sources.sort_by_key(|b| {
359 matches!(
360 b.source,
361 BindingSource::Kv | BindingSource::Singleton { .. }
362 )
363 });
364 let (file, span) = sources
365 .iter()
366 .find_map(|b| declared_at(parsed, indices, b))
367 .or_else(|| context_header(parsed, indices))
368 .map_or((None, Span::default()), |(file, span)| (Some(file), span));
369 errors.push_for(
370 file.as_deref(),
371 CompileError::new(
372 "bynk.context.duplicate_binding",
373 span,
374 format!(
375 "the Worker for `{ctx}` would declare two bindings named `{}`: {} and {}",
376 later.name,
377 earlier.source.describe(),
378 later.source.describe(),
379 ),
380 )
381 .with_note(
382 "a Worker's bindings share one `env`, so each name must be unique; binding names follow agent, context and derived capability names, so rename the declaration behind one of them",
383 ),
384 );
385 }
386 }
387}
388
389fn shareable(source: &BindingSource) -> bool {
395 !matches!(source, BindingSource::Agent { .. })
396}
397
398pub fn phase_group_binding_collisions(
407 worker_groups: &bynk_project::worker_groups::WorkerGroups,
408 parsed: &[ParsedFile],
409 groups: &BTreeMap<String, Vec<usize>>,
410 bindings: &BTreeMap<String, Vec<WorkerBinding>>,
411 errors: &mut ErrorSink,
412) {
413 worker_cycles(worker_groups, parsed, groups, bindings, errors);
414 for (key, group) in worker_groups {
415 group_service_names(key, &group.contexts, parsed, groups, errors);
416 group_websockets(key, &group.contexts, parsed, groups, errors);
417 crate::group_triggers::group_trigger_conflicts(
418 key,
419 &group.contexts,
420 parsed,
421 groups,
422 errors,
423 );
424 let mut first: HashMap<&str, (&str, &WorkerBinding)> = HashMap::new();
425 for ctx in &group.contexts {
426 let indices = groups.get(ctx).map(Vec::as_slice).unwrap_or_default();
427 for binding in bindings.get(ctx).into_iter().flatten() {
428 let Some(&(earlier_ctx, earlier)) = first.get(binding.name.as_str()) else {
429 first.insert(&binding.name, (ctx, binding));
430 continue;
431 };
432 if earlier_ctx == ctx
433 || (shareable(&binding.source) && earlier.source == binding.source)
434 {
435 continue;
436 }
437 let (file, span) = declared_at(parsed, indices, binding)
438 .or_else(|| context_header(parsed, indices))
439 .map_or((None, Span::default()), |(file, span)| (Some(file), span));
440 errors.push_for(
441 file.as_deref(),
442 CompileError::new(
443 "bynk.deploy.binding_collision",
444 span,
445 format!(
446 "contexts `{earlier_ctx}` and `{ctx}` share Worker `{key}`, which would declare two different bindings named `{}`: {} (from `{earlier_ctx}`) and {} (from `{ctx}`)",
447 binding.name,
448 earlier.source.describe(),
449 binding.source.describe(),
450 ),
451 )
452 .with_note(if shareable(&binding.source) {
453 "members of one Worker share its bindings: give both contexts the same declaration so they share one binding, or rename one capability"
454 } else {
455 "a Durable Object class belongs to the context that declares it, whatever its name, so two members cannot each declare one with the same name: rename one of the agents"
456 }),
457 );
458 }
459 }
460 }
461}
462
463fn group_service_names(
468 key: &str,
469 members: &[String],
470 parsed: &[ParsedFile],
471 groups: &BTreeMap<String, Vec<usize>>,
472 errors: &mut ErrorSink,
473) {
474 let mut first: HashMap<String, &str> = HashMap::new();
475 for ctx in members {
476 let indices = groups.get(ctx).map(Vec::as_slice).unwrap_or_default();
477 for &i in indices {
478 let SourceUnit::Context(c) = parsed[i].unit() else {
479 continue;
480 };
481 for item in &c.items {
482 let CommonsItem::Service(service) = item else {
483 continue;
484 };
485 let name = &service.name.name;
486 match first.get(name.as_str()) {
487 None => {
488 first.insert(name.clone(), ctx);
489 }
490 Some(earlier) if *earlier != ctx.as_str() => {
491 errors.push_for(
492 Some(&parsed[i].identity_path()),
493 CompileError::new(
494 "bynk.deploy.service_name_conflict",
495 service.name.span,
496 format!(
497 "contexts `{earlier}` and `{ctx}` share Worker `{key}`, and both declare a service named `{name}`"
498 ),
499 )
500 .with_note(
501 "a Worker answers its members' services by name, so each service name must be unique within a group: rename one of the services, or put the contexts in different groups",
502 ),
503 );
504 }
505 Some(_) => {}
506 }
507 }
508 }
509 }
510}
511
512fn worker_cycles(
534 worker_groups: &bynk_project::worker_groups::WorkerGroups,
535 parsed: &[ParsedFile],
536 groups: &BTreeMap<String, Vec<usize>>,
537 bindings: &BTreeMap<String, Vec<WorkerBinding>>,
538 errors: &mut ErrorSink,
539) {
540 let worker_of = |ctx: &str| -> String {
542 worker_groups
543 .iter()
544 .find(|(_, g)| g.contexts.iter().any(|c| c == ctx))
545 .map_or_else(|| ctx.to_string(), |(key, _)| key.clone())
546 };
547 let mut edges: BTreeMap<String, BTreeMap<String, (String, String)>> = BTreeMap::new();
550 for (ctx, list) in bindings {
551 for binding in list {
552 let BindingSource::Service { context: target } = &binding.source else {
553 continue;
554 };
555 let (from, to) = (worker_of(ctx), worker_of(target));
556 if from != to {
557 edges
558 .entry(from)
559 .or_default()
560 .entry(to)
561 .or_insert_with(|| (ctx.clone(), target.clone()));
562 }
563 }
564 }
565 for scc in strongly_connected(&edges) {
566 if !scc.iter().any(|w| worker_groups.contains_key(w)) {
567 continue;
568 }
569 let Some(path) = cycle_through(&edges, &scc) else {
570 continue;
571 };
572 let hops: Vec<String> = path
573 .windows(2)
574 .map(|pair| {
575 let (consumer, target) = &edges[&pair[0]][&pair[1]];
576 format!(
577 "`{}` to `{}` (`{consumer}` binds to `{target}`)",
578 pair[0], pair[1]
579 )
580 })
581 .collect();
582 let (consumer, _) = &edges[&path[0]][&path[1]];
583 let indices = groups.get(consumer).map(Vec::as_slice).unwrap_or_default();
584 let (file, span) = context_header(parsed, indices)
585 .map_or((None, Span::default()), |(file, span)| (Some(file), span));
586 errors.push_for(
587 file.as_deref(),
588 CompileError::new(
589 "bynk.deploy.worker_cycle",
590 span,
591 format!(
592 "the Workers {} bind to each other in a cycle: {}",
593 path[..path.len() - 1]
594 .iter()
595 .map(|w| format!("`{w}`"))
596 .collect::<Vec<_>>()
597 .join(", "),
598 hops.join(", ")
599 ),
600 )
601 .with_note(
602 "a Worker is uploaded after the Workers it binds to, so a cycle between Workers cannot be deployed. A group folds its members into one Worker: move a context out of its group, or into the other, so the Workers' dependencies run one way. (A publisher's Worker also binds to its subscribers, so a subscriber that calls its publisher closes a cycle too)",
603 ),
604 );
605 }
606}
607
608fn strongly_connected(
612 edges: &BTreeMap<String, BTreeMap<String, (String, String)>>,
613) -> Vec<Vec<String>> {
614 struct State<'a> {
615 edges: &'a BTreeMap<String, BTreeMap<String, (String, String)>>,
616 index: BTreeMap<String, usize>,
617 low: BTreeMap<String, usize>,
618 on_stack: BTreeSet<String>,
619 stack: Vec<String>,
620 out: Vec<Vec<String>>,
621 }
622 fn visit(state: &mut State<'_>, node: &str) {
623 let n = state.index.len();
624 state.index.insert(node.to_string(), n);
625 state.low.insert(node.to_string(), n);
626 state.stack.push(node.to_string());
627 state.on_stack.insert(node.to_string());
628 let next: Vec<String> = state
629 .edges
630 .get(node)
631 .map(|m| m.keys().cloned().collect())
632 .unwrap_or_default();
633 for to in next {
634 if !state.index.contains_key(&to) {
635 visit(state, &to);
636 let low = state.low[node].min(state.low[&to]);
637 state.low.insert(node.to_string(), low);
638 } else if state.on_stack.contains(&to) {
639 let low = state.low[node].min(state.index[&to]);
640 state.low.insert(node.to_string(), low);
641 }
642 }
643 if state.low[node] == state.index[node] {
644 let mut component = Vec::new();
645 while let Some(top) = state.stack.pop() {
646 state.on_stack.remove(&top);
647 let done = top == node;
648 component.push(top);
649 if done {
650 break;
651 }
652 }
653 if component.len() > 1 {
654 component.sort();
655 state.out.push(component);
656 }
657 }
658 }
659 let mut state = State {
660 edges,
661 index: BTreeMap::new(),
662 low: BTreeMap::new(),
663 on_stack: BTreeSet::new(),
664 stack: Vec::new(),
665 out: Vec::new(),
666 };
667 let nodes: BTreeSet<&String> = edges
668 .keys()
669 .chain(edges.values().flat_map(|m| m.keys()))
670 .collect();
671 for node in nodes {
672 if !state.index.contains_key(node) {
673 visit(&mut state, node);
674 }
675 }
676 state.out.sort();
677 state.out
678}
679
680fn cycle_through(
683 edges: &BTreeMap<String, BTreeMap<String, (String, String)>>,
684 scc: &[String],
685) -> Option<Vec<String>> {
686 fn walk(
687 edges: &BTreeMap<String, BTreeMap<String, (String, String)>>,
688 scc: &[String],
689 path: &mut Vec<String>,
690 ) -> bool {
691 let here = path.last().expect("a path has a node").clone();
692 for next in edges.get(&here).into_iter().flat_map(|m| m.keys()) {
693 if !scc.contains(next) {
694 continue;
695 }
696 if *next == path[0] {
697 path.push(next.clone());
698 return true;
699 }
700 if !path.contains(next) {
701 path.push(next.clone());
702 if walk(edges, scc, path) {
703 return true;
704 }
705 path.pop();
706 }
707 }
708 false
709 }
710 let mut path = vec![scc.first()?.clone()];
711 walk(edges, scc, &mut path).then_some(path)
712}
713
714fn group_websockets(
721 key: &str,
722 members: &[String],
723 parsed: &[ParsedFile],
724 groups: &BTreeMap<String, Vec<usize>>,
725 errors: &mut ErrorSink,
726) {
727 let declares_websocket = |ctx: &String| {
728 groups.get(ctx).into_iter().flatten().any(|&i| {
729 matches!(parsed[i].unit(), SourceUnit::Context(c) if c.items.iter().any(|item| {
730 matches!(item, CommonsItem::Service(s) if matches!(s.protocol, ServiceProtocol::WebSocket { .. }))
731 }))
732 })
733 };
734 let mut hosts = members.iter().filter(|c| declares_websocket(c));
735 let (Some(first), Some(second)) = (hosts.next(), hosts.next()) else {
736 return;
737 };
738 let indices = groups.get(second).map(Vec::as_slice).unwrap_or_default();
739 let (file, span) = context_header(parsed, indices)
740 .map_or((None, Span::default()), |(file, span)| (Some(file), span));
741 errors.push_for(
742 file.as_deref(),
743 CompileError::new(
744 "bynk.deploy.multiple_websocket_members",
745 span,
746 format!(
747 "contexts `{first}` and `{second}` share Worker `{key}`, and both declare a `from websocket` service"
748 ),
749 )
750 .with_note(
751 "a WebSocket upgrade carries no path or service name for a group to route it by, so a group has at most one member that accepts them: put the contexts in different groups, or give one of them its own Worker",
752 ),
753 );
754}
755
756fn declared_at(
761 parsed: &[ParsedFile],
762 indices: &[usize],
763 binding: &WorkerBinding,
764) -> Option<(PathBuf, Span)> {
765 indices.iter().find_map(|&i| {
766 let SourceUnit::Context(c) = parsed[i].unit() else {
767 return None;
768 };
769 let consumed = |target: &str| {
770 c.consumes
771 .iter()
772 .find(|d| d.target.joined() == target)
773 .map(|d| d.span)
774 };
775 let span = match &binding.source {
776 BindingSource::Agent { class_name } => c.items.iter().find_map(|item| {
777 let CommonsItem::Agent(a) = item else {
778 return None;
779 };
780 (a.name.name == *class_name).then_some(a.name.span)
781 }),
782 BindingSource::Service { context } => consumed(context),
783 BindingSource::Kv | BindingSource::Singleton { .. } => {
784 consumed(firstparty::CLOUDFLARE_UNIT)
785 }
786 BindingSource::KvInstance { capability }
787 | BindingSource::ForeignService { capability, .. }
788 | BindingSource::R2Instance { capability, .. }
789 | BindingSource::RateLimitInstance { capability, .. }
790 | BindingSource::QueueProducer { capability, .. }
791 | BindingSource::AnalyticsDataset { capability }
792 | BindingSource::StoredSecret { capability, .. }
793 | BindingSource::Email { capability, .. }
794 | BindingSource::Postgres { capability }
795 | BindingSource::MySql { capability, .. }
796 | BindingSource::VectorizeIndex { capability, .. }
797 | BindingSource::ContainerInstance { capability, .. }
798 | BindingSource::AiSearchInstance { capability, .. }
799 | BindingSource::MtlsCertificate { capability, .. }
800 | BindingSource::D1Database { capability } => c.items.iter().find_map(|item| {
801 let CommonsItem::Capability(d) = item else {
802 return None;
803 };
804 (d.name.name == *capability && d.derived.is_some()).then_some(d.span)
805 }),
806 BindingSource::EventsFanout { .. } => None,
807 }?;
808 Some((parsed[i].identity_path(), span))
809 })
810}
811
812fn context_header(parsed: &[ParsedFile], indices: &[usize]) -> Option<(PathBuf, Span)> {
815 indices.iter().find_map(|&i| {
816 let SourceUnit::Context(c) = parsed[i].unit() else {
817 return None;
818 };
819 Some((parsed[i].identity_path(), c.name.span))
820 })
821}
822
823#[cfg(test)]
824mod tests {
825 use super::*;
826
827 fn service(name: &str, context: &str) -> WorkerBinding {
828 WorkerBinding {
829 name: name.to_string(),
830 source: BindingSource::Service {
831 context: context.to_string(),
832 },
833 }
834 }
835
836 #[test]
837 fn distinct_names_do_not_clash() {
838 assert!(duplicate_bindings(&[service("A", "a"), service("B", "b")]).is_empty());
839 }
840
841 #[test]
843 fn every_repeat_is_reported_against_the_first() {
844 let bindings = [
845 service("A_B", "a.b"),
846 service("A_B", "a_b"),
847 service("A_B", "x"),
848 ];
849 let duplicates = duplicate_bindings(&bindings);
850 assert_eq!(duplicates.len(), 2);
851 assert!(
852 duplicates
853 .iter()
854 .all(|(earlier, _)| *earlier == &bindings[0])
855 );
856 assert_eq!(duplicates[1].1, &bindings[2]);
857 }
858
859 fn kv(name: &str, capability: &str) -> WorkerBinding {
860 WorkerBinding {
861 name: name.to_string(),
862 source: BindingSource::KvInstance {
863 capability: capability.to_string(),
864 },
865 }
866 }
867
868 fn r2(name: &str, jurisdiction: Option<&str>) -> WorkerBinding {
869 WorkerBinding {
870 name: name.to_string(),
871 source: BindingSource::R2Instance {
872 capability: "Archives".to_string(),
873 jurisdiction: jurisdiction.map(str::to_string),
874 },
875 }
876 }
877
878 fn collisions(
879 members: &[&str],
880 bindings: &[(&str, Vec<WorkerBinding>)],
881 ) -> Vec<(String, String)> {
882 let table = format!(
883 "[deploy.workers.core]\ncontexts = [{}]\n",
884 members
885 .iter()
886 .map(|m| format!("\"{m}\""))
887 .collect::<Vec<_>>()
888 .join(", ")
889 );
890 let root = std::path::Path::new("/project");
891 let overlay = HashMap::from([(root.join("bynk.toml"), table)]);
892 let worker_groups =
893 bynk_project::worker_groups::try_read_worker_groups_with(root, &overlay).unwrap();
894 let bindings: BTreeMap<String, Vec<WorkerBinding>> = bindings
895 .iter()
896 .map(|(ctx, b)| (ctx.to_string(), b.clone()))
897 .collect();
898 let mut errors = ErrorSink::new();
899 phase_group_binding_collisions(
900 &worker_groups,
901 &[],
902 &BTreeMap::new(),
903 &bindings,
904 &mut errors,
905 );
906 errors
907 .into_all()
908 .into_iter()
909 .map(|e| (e.error.category.to_string(), e.error.message))
910 .collect()
911 }
912
913 #[test]
915 fn identical_declarations_share_one_binding() {
916 assert!(
917 collisions(
918 &["a.x", "a.y"],
919 &[
920 ("a.x", vec![kv("KV_MAIN", "Main")]),
921 ("a.y", vec![kv("KV_MAIN", "Main")]),
922 ],
923 )
924 .is_empty()
925 );
926 }
927
928 #[test]
930 fn differing_declarations_collide() {
931 let found = collisions(
932 &["a.x", "a.y"],
933 &[
934 ("a.x", vec![r2("ARCHIVES", None)]),
935 ("a.y", vec![r2("ARCHIVES", Some("eu"))]),
936 ],
937 );
938 assert_eq!(found.len(), 1, "{found:?}");
939 assert_eq!(found[0].0, "bynk.deploy.binding_collision");
940 assert!(
941 found[0].1.contains("`a.x` and `a.y` share Worker `core`"),
942 "{}",
943 found[0].1
944 );
945 }
946
947 #[test]
950 fn only_clashes_between_members_are_reported() {
951 assert!(
952 collisions(
953 &["a.x", "a.y"],
954 &[
955 (
956 "a.x",
957 vec![r2("ARCHIVES", None), r2("ARCHIVES", Some("eu"))]
958 ),
959 ("a.z", vec![r2("ARCHIVES", Some("eu"))]),
960 ],
961 )
962 .is_empty()
963 );
964 }
965
966 fn agent(name: &str) -> WorkerBinding {
967 WorkerBinding {
968 name: format!("AGENT_{}", name.to_uppercase()),
969 source: BindingSource::Agent {
970 class_name: name.to_string(),
971 },
972 }
973 }
974
975 #[test]
979 fn same_named_agents_in_two_members_collide() {
980 let found = collisions(
981 &["a.x", "a.y"],
982 &[("a.x", vec![agent("Cart")]), ("a.y", vec![agent("Cart")])],
983 );
984 assert_eq!(found.len(), 1, "{found:?}");
985 assert_eq!(found[0].0, "bynk.deploy.binding_collision");
986 assert!(
988 collisions(
989 &["a.x", "a.y"],
990 &[("a.x", vec![agent("Cart")]), ("a.y", vec![agent("Order")])],
991 )
992 .is_empty()
993 );
994 }
995}