telltale-runtime 7.0.0

Choreographic programming for Telltale - effect-based distributed protocols
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! # Topology
//!
//! Location and topology types for deployment configuration.
//!
//! ## Overview
//!
//! This module defines types for specifying where protocol roles are deployed.
//! Topology is kept separate from choreography to enable:
//! - Same choreography, multiple deployment configs
//! - Version topologies independently
//! - Dev/staging/prod without touching protocol logic
//! - Projection correctness is location-independent
//!
//! ## Lean Correspondence
//!
//! Topology types are currently Rust-only. Future Lean formalization may
//! include deployment constraints in `lean/Protocol/Deployment/`.

mod handler;
mod parser;
mod transport;
mod validation_types;

pub use handler::{TopologyHandler, TopologyHandlerBuilder};
pub use parser::{parse_topology, ParsedTopology, TopologyParseError};
pub use transport::{
    ByteMessage, InMemoryChannelTransport, Transport, TransportError, TransportFactory,
    TransportMessage, TransportResult, TransportType,
};
pub use validation_types::{TopologyError, TopologyLoadError, TopologyValidation};

use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::fmt;

use crate::identifiers::{Datacenter, Endpoint as TopologyEndpoint, Namespace, Region, RoleName};
use crate::ChannelCapacity;

/// Location specifies where a role is deployed.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum Location {
    /// In-process execution using channels
    #[default]
    Local,
    /// Remote endpoint (e.g., "localhost:8080", "service.internal:9000")
    Remote(TopologyEndpoint),
    /// Colocated with another role on the same node (shared memory)
    Colocated(RoleName),
}

impl fmt::Display for Location {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Location::Local => write!(f, "local"),
            Location::Remote(endpoint) => write!(f, "{}", endpoint),
            Location::Colocated(peer) => write!(f, "colocated({})", peer),
        }
    }
}

/// Topology constraints specify requirements on role placement.
///
/// These are validated at deployment time, not projection time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TopologyConstraint {
    /// Two roles must be on the same node
    Colocated(RoleName, RoleName),
    /// Two roles must be on different nodes
    Separated(RoleName, RoleName),
    /// A role must be at a specific location
    Pinned(RoleName, Location),
    /// A role must be in a specific region/zone
    Region(RoleName, Region),
}

/// Branching requirement for capacity checks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BranchRequirement {
    /// Role that selects the branch.
    pub sender: RoleName,
    /// Role that must distinguish the branch.
    pub receiver: RoleName,
    /// Number of branch labels.
    pub label_count: u32,
}

impl BranchRequirement {
    /// Create a new branching requirement.
    pub fn new(sender: RoleName, receiver: RoleName, label_count: u32) -> Self {
        Self {
            sender,
            receiver,
            label_count,
        }
    }

    /// Minimum capacity (in bits) required to distinguish `label_count` labels.
    #[must_use]
    pub fn required_capacity_bits(&self) -> u32 {
        min_capacity_bits(self.label_count)
    }
}

fn min_capacity_bits(label_count: u32) -> u32 {
    if label_count <= 1 {
        return 0;
    }
    32 - (label_count - 1).leading_zeros()
}

impl fmt::Display for TopologyConstraint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TopologyConstraint::Colocated(r1, r2) => write!(f, "colocated({}, {})", r1, r2),
            TopologyConstraint::Separated(r1, r2) => write!(f, "separated({}, {})", r1, r2),
            TopologyConstraint::Pinned(role, loc) => write!(f, "pinned({}, {})", role, loc),
            TopologyConstraint::Region(role, region) => write!(f, "region({}, {})", role, region),
        }
    }
}

/// Common deployment modes for quick configuration
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum TopologyMode {
    /// All roles in-process (testing)
    #[default]
    Local,
    /// Each role in separate process
    PerRole,
    /// Discover via Kubernetes services
    Kubernetes(Namespace), // namespace
    /// Discover via Consul
    Consul(Datacenter), // datacenter
}

/// Constraints on the number of instances for a role family.
///
/// Used to validate that wildcard/range role resolutions
/// meet minimum and maximum requirements.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RoleFamilyConstraint {
    /// Minimum number of instances required (default: 0)
    pub min: u32,
    /// Maximum number of instances allowed (default: unlimited)
    pub max: Option<u32>,
}

impl RoleFamilyConstraint {
    /// Create a new constraint with minimum only.
    pub fn min_only(min: u32) -> Self {
        Self { min, max: None }
    }

    /// Create a new constraint with both min and max.
    pub fn bounded(min: u32, max: u32) -> Self {
        Self {
            min,
            max: Some(max),
        }
    }

    /// Validate a count against this constraint.
    pub fn validate(&self, count: usize) -> Result<(), RoleFamilyConstraintError> {
        let count = u32::try_from(count).map_err(|_| RoleFamilyConstraintError::AboveMaximum {
            actual: u32::MAX,
            max: self.max.unwrap_or(u32::MAX),
        })?;
        if count < self.min {
            return Err(RoleFamilyConstraintError::BelowMinimum {
                actual: count,
                min: self.min,
            });
        }
        if let Some(max) = self.max {
            if count > max {
                return Err(RoleFamilyConstraintError::AboveMaximum { actual: count, max });
            }
        }
        Ok(())
    }
}

/// Errors from role family constraint validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RoleFamilyConstraintError {
    /// Actual count is below minimum.
    BelowMinimum { actual: u32, min: u32 },
    /// Actual count is above maximum.
    AboveMaximum { actual: u32, max: u32 },
}

impl fmt::Display for RoleFamilyConstraintError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RoleFamilyConstraintError::BelowMinimum { actual, min } => {
                write!(
                    f,
                    "role family has {} instances, minimum required is {}",
                    actual, min
                )
            }
            RoleFamilyConstraintError::AboveMaximum { actual, max } => {
                write!(
                    f,
                    "role family has {} instances, maximum allowed is {}",
                    actual, max
                )
            }
        }
    }
}

impl std::error::Error for RoleFamilyConstraintError {}

/// Topology maps roles to their deployment locations.
///
/// Uses BTreeMap for deterministic iteration order.
#[derive(Debug, Clone, Default)]
pub struct Topology {
    /// Optional mode for shorthand configuration
    pub mode: Option<TopologyMode>,
    /// Role → Location mapping
    pub locations: BTreeMap<RoleName, Location>,
    /// Directed edge capacities (sender, receiver) → capacity (bits)
    pub channel_capacities: BTreeMap<(RoleName, RoleName), ChannelCapacity>,
    /// Deployment constraints
    pub constraints: Vec<TopologyConstraint>,
    /// Role family instance count constraints
    pub role_constraints: BTreeMap<String, RoleFamilyConstraint>,
}

impl Topology {
    fn resolved_location(
        &self,
        role: &RoleName,
        visiting: &mut BTreeSet<RoleName>,
    ) -> Result<Location, String> {
        if !visiting.insert(role.clone()) {
            return Err(format!("cyclic colocated placement involving role {role}"));
        }

        let resolved = match self.get_location(role) {
            Ok(Location::Colocated(peer)) => self.resolved_location(&peer, visiting),
            Ok(location) => Ok(location),
            Err(TopologyError::UnknownRole(missing)) => Err(format!(
                "role {role} refers to unknown colocated peer {missing}"
            )),
        };

        visiting.remove(role);
        resolved
    }

    fn resolve_constraint_location(&self, location: &Location) -> Result<Location, String> {
        match location {
            Location::Colocated(peer) => self.resolved_location(peer, &mut BTreeSet::new()),
            other => Ok(other.clone()),
        }
    }

    fn validate_constraint(&self, constraint: &TopologyConstraint) -> Option<TopologyValidation> {
        let resolved = |role: &RoleName| match self.resolved_location(role, &mut BTreeSet::new()) {
            Ok(location) => Ok(location),
            Err(reason) => Err(TopologyValidation::ConstraintViolation(
                constraint.clone(),
                reason,
            )),
        };
        let resolve_expected =
            |location: &Location| match self.resolve_constraint_location(location) {
                Ok(location) => Ok(location),
                Err(reason) => Err(TopologyValidation::ConstraintViolation(
                    constraint.clone(),
                    reason,
                )),
            };

        match constraint {
            TopologyConstraint::Colocated(left, right) => {
                let left_location = match resolved(left) {
                    Ok(location) => location,
                    Err(validation) => return Some(validation),
                };
                let right_location = match resolved(right) {
                    Ok(location) => location,
                    Err(validation) => return Some(validation),
                };
                if left_location == right_location {
                    None
                } else {
                    Some(TopologyValidation::ConstraintViolation(
                        constraint.clone(),
                        format!(
                            "roles {left} and {right} resolve to different locations ({left_location} vs {right_location})"
                        ),
                    ))
                }
            }
            TopologyConstraint::Separated(left, right) => {
                let left_location = match resolved(left) {
                    Ok(location) => location,
                    Err(validation) => return Some(validation),
                };
                let right_location = match resolved(right) {
                    Ok(location) => location,
                    Err(validation) => return Some(validation),
                };
                if left_location != right_location {
                    None
                } else {
                    Some(TopologyValidation::ConstraintViolation(
                        constraint.clone(),
                        format!(
                            "roles {left} and {right} resolve to the same location ({left_location})"
                        ),
                    ))
                }
            }
            TopologyConstraint::Pinned(role, expected) => {
                let actual = match resolved(role) {
                    Ok(location) => location,
                    Err(validation) => return Some(validation),
                };
                let expected = match resolve_expected(expected) {
                    Ok(location) => location,
                    Err(validation) => return Some(validation),
                };
                if actual == expected {
                    None
                } else {
                    Some(TopologyValidation::ConstraintViolation(
                        constraint.clone(),
                        format!(
                            "role {role} resolved to {actual}, expected pinned location {expected}"
                        ),
                    ))
                }
            }
            TopologyConstraint::Region(_, _) => None,
        }
    }

    /// Create an empty topology
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a local-only topology (all roles in-process)
    pub fn local_mode() -> Self {
        Topology {
            mode: Some(TopologyMode::Local),
            ..Default::default()
        }
    }

    /// Create a topology builder
    pub fn builder() -> TopologyBuilder {
        TopologyBuilder::new()
    }

    /// Add a role location to the topology
    pub fn with_role(mut self, role: RoleName, location: Location) -> Self {
        self.locations.insert(role, location);
        self
    }

    /// Add a constraint to the topology
    pub fn with_constraint(mut self, constraint: TopologyConstraint) -> Self {
        self.constraints.push(constraint);
        self
    }

    /// Add a channel capacity to the topology.
    pub fn with_channel_capacity(
        mut self,
        sender: RoleName,
        receiver: RoleName,
        capacity: ChannelCapacity,
    ) -> Self {
        self.channel_capacities.insert((sender, receiver), capacity);
        self
    }

    /// Get the location for a role.
    pub fn get_location(&self, role: &RoleName) -> Result<Location, TopologyError> {
        match &self.mode {
            Some(TopologyMode::Local) => Ok(Location::Local),
            _ => self
                .locations
                .get(role)
                .cloned()
                .ok_or_else(|| TopologyError::UnknownRole(role.clone())),
        }
    }

    /// Check if a role is local
    pub fn is_local(&self, role: &RoleName) -> Result<bool, TopologyError> {
        match self.get_location(role)? {
            Location::Local | Location::Colocated(_) => Ok(true),
            Location::Remote(_) => Ok(false),
        }
    }

    /// Get all roles defined in the topology
    pub fn roles(&self) -> Vec<&RoleName> {
        self.locations.keys().collect()
    }

    /// Look up channel capacity between two roles.
    pub fn channel_capacity(
        &self,
        sender: &RoleName,
        receiver: &RoleName,
    ) -> Option<ChannelCapacity> {
        self.channel_capacities
            .get(&(sender.clone(), receiver.clone()))
            .copied()
    }

    /// Check if topology is valid for a set of choreography roles.
    /// All referenced roles must exist in the choreography.
    pub fn valid_for_roles(&self, choreo_roles: &[RoleName]) -> bool {
        // All topology roles must be in choreography
        let topo_roles_ok = self.locations.keys().all(|r| choreo_roles.contains(r));

        // All capacity roles must be in choreography
        let capacity_roles_ok = self
            .channel_capacities
            .keys()
            .all(|(s, r)| choreo_roles.contains(s) && choreo_roles.contains(r));

        // All constraint roles must be in choreography
        let constraints_ok = self.constraints.iter().all(|c| match c {
            TopologyConstraint::Colocated(r1, r2) | TopologyConstraint::Separated(r1, r2) => {
                choreo_roles.contains(r1) && choreo_roles.contains(r2)
            }
            TopologyConstraint::Pinned(r, _) | TopologyConstraint::Region(r, _) => {
                choreo_roles.contains(r)
            }
        });

        topo_roles_ok && capacity_roles_ok && constraints_ok
    }

    /// Validate a topology against choreography roles
    pub fn validate(&self, choreo_roles: &[RoleName]) -> TopologyValidation {
        // Check all topology roles exist
        for (role, location) in &self.locations {
            if !choreo_roles.contains(role) {
                return TopologyValidation::UnknownRole(role.clone());
            }

            if let Location::Colocated(peer) = location {
                if !choreo_roles.contains(peer) {
                    return TopologyValidation::UnknownRole(peer.clone());
                }
            }
        }

        // Custom topologies must provide an explicit placement for each role.
        if !matches!(self.mode, Some(TopologyMode::Local)) {
            for role in choreo_roles {
                if !self.locations.contains_key(role) {
                    return TopologyValidation::MissingRole(role.clone());
                }
            }
        }

        // Check all capacity roles exist
        for (sender, receiver) in self.channel_capacities.keys() {
            if !choreo_roles.contains(sender) {
                return TopologyValidation::UnknownRole(sender.clone());
            }
            if !choreo_roles.contains(receiver) {
                return TopologyValidation::UnknownRole(receiver.clone());
            }
        }

        // Check all constraint roles exist
        for c in &self.constraints {
            match c {
                TopologyConstraint::Colocated(r1, r2) | TopologyConstraint::Separated(r1, r2) => {
                    if !choreo_roles.contains(r1) {
                        return TopologyValidation::UnknownRole(r1.clone());
                    }
                    if !choreo_roles.contains(r2) {
                        return TopologyValidation::UnknownRole(r2.clone());
                    }
                }
                TopologyConstraint::Pinned(r, _) | TopologyConstraint::Region(r, _) => {
                    if !choreo_roles.contains(r) {
                        return TopologyValidation::UnknownRole(r.clone());
                    }
                }
            }
        }

        for constraint in &self.constraints {
            if let Some(validation) = self.validate_constraint(constraint) {
                return validation;
            }
        }

        TopologyValidation::Valid
    }

    /// Validate topology and channel capacities against branching requirements.
    ///
    /// Capacity checks are only enforced for edges explicitly configured with
    /// a channel capacity. Missing capacities are treated as unconstrained.
    pub fn validate_with_branches(
        &self,
        choreo_roles: &[RoleName],
        branches: &[BranchRequirement],
    ) -> TopologyValidation {
        let base = self.validate(choreo_roles);
        if !base.is_valid() {
            return base;
        }

        for branch in branches {
            let required_bits = branch.required_capacity_bits();
            if required_bits == 0 {
                continue;
            }
            if let Some(available) = self.channel_capacity(&branch.sender, &branch.receiver) {
                let available_bits = available.get();
                if available_bits < required_bits {
                    return TopologyValidation::InsufficientCapacity {
                        sender: branch.sender.clone(),
                        receiver: branch.receiver.clone(),
                        required_bits,
                        available_bits,
                    };
                }
            }
        }

        TopologyValidation::Valid
    }

    /// Validate a resolved role family against configured constraints.
    ///
    /// # Arguments
    ///
    /// * `family` - The name of the role family (e.g., "Witness")
    /// * `count` - The number of resolved instances
    ///
    /// # Returns
    ///
    /// `Ok(())` if the count satisfies constraints, or an error if not.
    /// Returns `Ok(())` if no constraint is configured for this family.
    pub fn validate_family(
        &self,
        family: &str,
        count: usize,
    ) -> Result<(), RoleFamilyConstraintError> {
        if let Some(constraint) = self.role_constraints.get(family) {
            constraint.validate(count)
        } else {
            Ok(())
        }
    }

    /// Get the constraint for a role family, if configured.
    pub fn get_family_constraint(&self, family: &str) -> Option<&RoleFamilyConstraint> {
        self.role_constraints.get(family)
    }

    /// Load a topology from a DSL file.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let topology = Topology::load("deploy/prod.topology")?;
    /// ```
    pub fn load(path: impl AsRef<std::path::Path>) -> Result<ParsedTopology, TopologyLoadError> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| TopologyLoadError::IoError(e.to_string()))?;
        parse_topology(&content).map_err(TopologyLoadError::ParseError)
    }

    /// Load a topology from a DSL string.
    pub fn parse(content: &str) -> Result<ParsedTopology, TopologyLoadError> {
        parse_topology(content).map_err(TopologyLoadError::ParseError)
    }
}

/// Builder for constructing Topology instances
#[derive(Debug, Clone, Default)]
pub struct TopologyBuilder {
    topology: Topology,
}

impl TopologyBuilder {
    /// Create a new topology builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the topology mode
    pub fn mode(mut self, mode: TopologyMode) -> Self {
        self.topology.mode = Some(mode);
        self
    }

    /// Add a local role
    pub fn local_role(mut self, role: RoleName) -> Self {
        self.topology.locations.insert(role, Location::Local);
        self
    }

    /// Add a remote role
    pub fn remote_role(mut self, role: RoleName, endpoint: TopologyEndpoint) -> Self {
        self.topology
            .locations
            .insert(role, Location::Remote(endpoint));
        self
    }

    /// Add a colocated role
    pub fn colocated_role(mut self, role: RoleName, peer: RoleName) -> Self {
        self.topology
            .locations
            .insert(role, Location::Colocated(peer));
        self
    }

    /// Add a role at a specific location
    pub fn role(mut self, role: RoleName, location: Location) -> Self {
        self.topology.locations.insert(role, location);
        self
    }

    /// Add a directed channel capacity between two roles.
    pub fn channel_capacity(
        mut self,
        sender: RoleName,
        receiver: RoleName,
        capacity: ChannelCapacity,
    ) -> Self {
        self.topology
            .channel_capacities
            .insert((sender, receiver), capacity);
        self
    }

    /// Add a colocation constraint
    pub fn colocated(mut self, r1: RoleName, r2: RoleName) -> Self {
        self.topology
            .constraints
            .push(TopologyConstraint::Colocated(r1, r2));
        self
    }

    /// Add a separation constraint
    pub fn separated(mut self, r1: RoleName, r2: RoleName) -> Self {
        self.topology
            .constraints
            .push(TopologyConstraint::Separated(r1, r2));
        self
    }

    /// Add a pinned location constraint
    pub fn pinned(mut self, role: RoleName, location: Location) -> Self {
        self.topology
            .constraints
            .push(TopologyConstraint::Pinned(role, location));
        self
    }

    /// Add a region constraint
    pub fn region(mut self, role: RoleName, region: Region) -> Self {
        self.topology
            .constraints
            .push(TopologyConstraint::Region(role, region));
        self
    }

    /// Build the topology
    pub fn build(self) -> Topology {
        self.topology
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_location_display() {
        assert_eq!(Location::Local.to_string(), "local");
        assert_eq!(
            Location::Remote(TopologyEndpoint::new("localhost:8080").unwrap()).to_string(),
            "localhost:8080"
        );
        assert_eq!(
            Location::Colocated(RoleName::from_static("Alice")).to_string(),
            "colocated(Alice)"
        );
    }

    #[test]
    fn test_topology_builder() {
        let topology = Topology::builder()
            .mode(TopologyMode::Local)
            .local_role(RoleName::from_static("Alice"))
            .remote_role(
                RoleName::from_static("Bob"),
                TopologyEndpoint::new("localhost:8080").unwrap(),
            )
            .colocated(
                RoleName::from_static("Alice"),
                RoleName::from_static("Carol"),
            )
            .build();

        assert_eq!(topology.mode, Some(TopologyMode::Local));
        assert_eq!(topology.locations.len(), 2);
        assert!(topology.is_local(&RoleName::from_static("Alice")).unwrap());
    }

    #[test]
    fn test_topology_validation() {
        let topology = Topology::builder()
            .local_role(RoleName::from_static("Alice"))
            .local_role(RoleName::from_static("Bob"))
            .build();

        let roles = vec![
            RoleName::from_static("Alice"),
            RoleName::from_static("Bob"),
            RoleName::from_static("Carol"),
        ];
        match topology.validate(&roles) {
            TopologyValidation::MissingRole(role) => {
                assert_eq!(role, RoleName::from_static("Carol"))
            }
            other => panic!("Expected MissingRole, got {other:?}"),
        }

        let limited_roles = vec![RoleName::from_static("Alice")];
        assert!(!topology.validate(&limited_roles).is_valid());
    }

    #[test]
    fn test_local_mode_allows_implicit_role_coverage() {
        let topology = Topology::builder().mode(TopologyMode::Local).build();
        let roles = vec![
            RoleName::from_static("Alice"),
            RoleName::from_static("Bob"),
            RoleName::from_static("Carol"),
        ];
        assert!(topology.validate(&roles).is_valid());
    }

    #[test]
    fn test_topology_capacity_validation() {
        let topology = Topology::builder()
            .local_role(RoleName::from_static("Alice"))
            .local_role(RoleName::from_static("Bob"))
            .channel_capacity(
                RoleName::from_static("Alice"),
                RoleName::from_static("Bob"),
                ChannelCapacity::try_new(1).expect("test capacity in range"),
            )
            .build();

        let roles = vec![RoleName::from_static("Alice"), RoleName::from_static("Bob")];
        let branches = vec![BranchRequirement::new(
            RoleName::from_static("Alice"),
            RoleName::from_static("Bob"),
            3,
        )];

        match topology.validate_with_branches(&roles, &branches) {
            TopologyValidation::InsufficientCapacity {
                sender,
                receiver,
                required_bits,
                available_bits,
            } => {
                assert_eq!(sender, RoleName::from_static("Alice"));
                assert_eq!(receiver, RoleName::from_static("Bob"));
                assert_eq!(required_bits, 2);
                assert_eq!(available_bits, 1);
            }
            _ => panic!("Expected InsufficientCapacity"),
        }
    }

    #[test]
    fn test_topology_capacity_unconstrained() {
        let topology = Topology::builder()
            .local_role(RoleName::from_static("Alice"))
            .local_role(RoleName::from_static("Bob"))
            .build();

        let roles = vec![RoleName::from_static("Alice"), RoleName::from_static("Bob")];
        let branches = vec![BranchRequirement::new(
            RoleName::from_static("Alice"),
            RoleName::from_static("Bob"),
            4,
        )];

        assert!(topology
            .validate_with_branches(&roles, &branches)
            .is_valid());
    }

    #[test]
    fn test_local_mode() {
        let topology = Topology::local_mode();
        assert_eq!(
            topology
                .get_location(&RoleName::from_static("AnyRole"))
                .unwrap(),
            Location::Local
        );
    }

    #[test]
    fn test_constraint_validation() {
        let topology = Topology::builder()
            .local_role(RoleName::from_static("Alice"))
            .local_role(RoleName::from_static("Bob"))
            .colocated(
                RoleName::from_static("Alice"),
                RoleName::from_static("Unknown"),
            )
            .build();

        let roles = vec![RoleName::from_static("Alice"), RoleName::from_static("Bob")];
        match topology.validate(&roles) {
            TopologyValidation::UnknownRole(role) => {
                assert_eq!(role, RoleName::from_static("Unknown"))
            }
            _ => panic!("Expected UnknownRole"),
        }
    }

    #[test]
    fn test_constraint_validation_enforces_placement_requirements() {
        let roles = vec![RoleName::from_static("Alice"), RoleName::from_static("Bob")];

        let separated = Topology::builder()
            .local_role(RoleName::from_static("Alice"))
            .local_role(RoleName::from_static("Bob"))
            .separated(RoleName::from_static("Alice"), RoleName::from_static("Bob"))
            .build();
        match separated.validate(&roles) {
            TopologyValidation::ConstraintViolation(
                TopologyConstraint::Separated(left, right),
                _,
            ) => {
                assert_eq!(left, RoleName::from_static("Alice"));
                assert_eq!(right, RoleName::from_static("Bob"));
            }
            other => panic!("Expected separated placement violation, got {other:?}"),
        }

        let pinned = Topology::builder()
            .remote_role(
                RoleName::from_static("Alice"),
                TopologyEndpoint::new("localhost:9000").unwrap(),
            )
            .local_role(RoleName::from_static("Bob"))
            .pinned(
                RoleName::from_static("Bob"),
                Location::Remote(TopologyEndpoint::new("localhost:9001").unwrap()),
            )
            .build();
        match pinned.validate(&roles) {
            TopologyValidation::ConstraintViolation(TopologyConstraint::Pinned(role, _), _) => {
                assert_eq!(role, RoleName::from_static("Bob"));
            }
            other => panic!("Expected pinned placement violation, got {other:?}"),
        }
    }

    #[test]
    fn test_colocated_roles_require_known_peers() {
        let topology = Topology::builder()
            .colocated_role(RoleName::from_static("Bob"), RoleName::from_static("Carol"))
            .build();
        let roles = vec![RoleName::from_static("Alice"), RoleName::from_static("Bob")];
        match topology.validate(&roles) {
            TopologyValidation::UnknownRole(role) => {
                assert_eq!(role, RoleName::from_static("Carol"));
            }
            other => panic!("Expected missing colocated peer role, got {other:?}"),
        }
    }

    #[test]
    fn test_topology_from_str() {
        let input = r#"
            topology Dev for PingPong {
                Alice: localhost:8080
                Bob: localhost:8081
            }
        "#;

        let parsed = Topology::parse(input).unwrap();
        assert_eq!(parsed.name, "Dev");
        assert_eq!(parsed.for_choreography, "PingPong");
        assert_eq!(
            parsed
                .topology
                .get_location(&RoleName::from_static("Alice"))
                .unwrap(),
            Location::Remote(TopologyEndpoint::new("localhost:8080").unwrap())
        );
    }

    #[test]
    fn test_topology_from_str_local_mode() {
        let input = r#"
            topology Test for MyProtocol {
                mode: local
            }
        "#;

        let parsed = Topology::parse(input).unwrap();
        assert_eq!(parsed.topology.mode, Some(TopologyMode::Local));
        // In local mode, all roles are local
        assert_eq!(
            parsed
                .topology
                .get_location(&RoleName::from_static("AnyRole"))
                .unwrap(),
            Location::Local
        );
    }

    #[test]
    fn test_topology_load_error() {
        let result = Topology::load("nonexistent/file.topology");
        assert!(result.is_err());
        match result {
            Err(TopologyLoadError::IoError(_)) => {}
            _ => panic!("Expected IoError"),
        }
    }

    #[test]
    fn test_role_family_constraint_min_only() {
        let constraint = RoleFamilyConstraint::min_only(3);
        assert!(constraint.validate(3).is_ok());
        assert!(constraint.validate(5).is_ok());
        assert!(constraint.validate(100).is_ok());
        assert!(constraint.validate(2).is_err());
        assert!(constraint.validate(0).is_err());
    }

    #[test]
    fn test_role_family_constraint_bounded() {
        let constraint = RoleFamilyConstraint::bounded(2, 5);
        assert!(constraint.validate(2).is_ok());
        assert!(constraint.validate(3).is_ok());
        assert!(constraint.validate(5).is_ok());
        assert!(constraint.validate(1).is_err());
        assert!(constraint.validate(6).is_err());
    }

    #[test]
    fn test_role_family_constraint_error_messages() {
        let constraint = RoleFamilyConstraint::bounded(3, 10);
        let err = constraint.validate(2).unwrap_err();
        assert!(err.to_string().contains("minimum required is 3"));

        let err = constraint.validate(11).unwrap_err();
        assert!(err.to_string().contains("maximum allowed is 10"));
    }

    #[test]
    fn test_topology_validate_family() {
        let input = r#"
            topology Test for Protocol {
                role_constraints {
                    Witness: min = 3, max = 10
                }
            }
        "#;
        let parsed = Topology::parse(input).unwrap();
        let topology = parsed.topology;

        // Valid counts
        assert!(topology.validate_family("Witness", 3).is_ok());
        assert!(topology.validate_family("Witness", 5).is_ok());
        assert!(topology.validate_family("Witness", 10).is_ok());

        // Invalid counts
        assert!(topology.validate_family("Witness", 2).is_err());
        assert!(topology.validate_family("Witness", 11).is_err());

        // Unknown family - no constraint, so any count is valid
        assert!(topology.validate_family("Unknown", 0).is_ok());
        assert!(topology.validate_family("Unknown", 100).is_ok());
    }

    #[test]
    fn test_topology_get_family_constraint() {
        let input = r#"
            topology Test for Protocol {
                role_constraints {
                    Witness: min = 3
                }
            }
        "#;
        let parsed = Topology::parse(input).unwrap();
        let topology = parsed.topology;

        let constraint = topology.get_family_constraint("Witness");
        assert!(constraint.is_some());
        assert_eq!(constraint.unwrap().min, 3);

        let unknown = topology.get_family_constraint("Unknown");
        assert!(unknown.is_none());
    }
}