telltale-runtime 8.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
//! Topology integration code generation.
//!
//! Generates topology-aware protocol handlers that support local testing
//! and distributed deployment configurations.

use crate::ast::{Branch, Choreography, LocalType, Protocol, Role};
use crate::topology::{Location, Topology, TopologyConstraint, TopologyMode};
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};

use super::generate_choreography_code;

/// Parsed inline topology definition for code generation
#[derive(Debug, Clone)]
pub struct InlineTopology {
    /// Name of the topology (e.g., "Dev", "Prod")
    pub name: String,
    /// The topology configuration
    pub topology: Topology,
}

#[derive(Debug, Clone)]
struct BranchRequirementSpec {
    sender: String,
    receiver: String,
    label_count: u32,
}

/// Generate topology-aware protocol handlers
///
/// This generates:
/// - `Protocol::handler(role)` - Creates a TopologyHandler with local mode
/// - `Protocol::with_topology(topo, role)` - Creates a TopologyHandler with custom topology
/// - Named topology constants for inline definitions
#[must_use]
pub fn generate_topology_integration(
    choreography: &Choreography,
    inline_topologies: &[InlineTopology],
) -> TokenStream {
    let _protocol_name = &choreography.name;

    // Collect role names for validation
    let role_names: Vec<&Ident> = choreography.roles.iter().map(|r| r.name()).collect();
    let role_name_strs: Vec<String> = role_names.iter().map(|r| r.to_string()).collect();

    // Generate handler method
    let handler_method = generate_handler_method();

    // Collect branch requirements for capacity checking
    let branch_requirements = collect_branch_requirements(&choreography.protocol);

    // Generate with_topology method
    let with_topology_method = generate_with_topology_method(&role_name_strs, &branch_requirements);

    // Generate topology constants
    let topology_constants = generate_topology_constants(inline_topologies, &role_name_strs);

    quote! {
        /// Topology integration for the #protocol_name_str protocol
        pub mod topology {
            use super::*;
            use ::telltale_runtime::topology::{
                BranchRequirement, Location, Topology, TopologyBuilder, TopologyHandler,
                TopologyMode,
            };
            use ::telltale_runtime::{
                ChannelCapacity, Region, RoleFamilyConstraint, RoleName, TopologyEndpoint,
            };

            #handler_method
            #with_topology_method
            #topology_constants
        }
    }
}

fn collect_branch_requirements(protocol: &Protocol) -> Vec<BranchRequirementSpec> {
    let mut requirements = Vec::new();
    collect_branch_requirements_from_protocol(protocol, &mut requirements);
    requirements
}

fn collect_branch_requirements_from_protocol(
    protocol: &Protocol,
    requirements: &mut Vec<BranchRequirementSpec>,
) {
    match protocol {
        Protocol::Choice { branches, .. } => {
            let label_count = u32::try_from(branches.len()).unwrap_or(u32::MAX);
            for branch in branches {
                collect_branch_requirement_from_branch(branch, label_count, requirements);
                collect_branch_requirements_from_protocol(&branch.protocol, requirements);
            }
        }
        Protocol::Case { branches, .. } => {
            for branch in branches {
                collect_branch_requirements_from_protocol(&branch.protocol, requirements);
            }
        }
        Protocol::Timeout {
            body,
            on_timeout,
            on_cancel,
            ..
        } => {
            collect_branch_requirements_from_protocol(body, requirements);
            collect_branch_requirements_from_protocol(on_timeout, requirements);
            if let Some(on_cancel) = on_cancel.as_deref() {
                collect_branch_requirements_from_protocol(on_cancel, requirements);
            }
        }
        Protocol::Send { continuation, .. } => {
            collect_branch_requirements_from_protocol(continuation, requirements);
        }
        Protocol::Broadcast { continuation, .. } => {
            collect_branch_requirements_from_protocol(continuation, requirements);
        }
        Protocol::Loop { body, .. } => {
            collect_branch_requirements_from_protocol(body, requirements);
        }
        Protocol::Parallel { protocols } => {
            for p in protocols {
                collect_branch_requirements_from_protocol(p, requirements);
            }
        }
        Protocol::Rec { body, .. } => {
            collect_branch_requirements_from_protocol(body, requirements);
        }
        Protocol::Begin { continuation, .. }
        | Protocol::Await { continuation, .. }
        | Protocol::Resolve { continuation, .. }
        | Protocol::Invalidate { continuation, .. }
        | Protocol::Extension { continuation, .. }
        | Protocol::Let { continuation, .. }
        | Protocol::Publish { continuation, .. }
        | Protocol::PublishAuthority { continuation, .. }
        | Protocol::Materialize { continuation, .. }
        | Protocol::Handoff { continuation, .. }
        | Protocol::DependentWork { continuation, .. } => {
            collect_branch_requirements_from_protocol(continuation, requirements);
        }
        Protocol::Var(_) | Protocol::End => {}
    }
}

fn collect_branch_requirement_from_branch(
    branch: &Branch,
    label_count: u32,
    requirements: &mut Vec<BranchRequirementSpec>,
) {
    match &branch.protocol {
        Protocol::Send { from, to, .. } => {
            requirements.push(BranchRequirementSpec {
                sender: from.name().to_string(),
                receiver: to.name().to_string(),
                label_count,
            });
        }
        Protocol::Broadcast { from, to_all, .. } => {
            for to in to_all {
                requirements.push(BranchRequirementSpec {
                    sender: from.name().to_string(),
                    receiver: to.name().to_string(),
                    label_count,
                });
            }
        }
        _ => {}
    }
}

/// Generate the `handler(role)` method that returns a local TopologyHandler
fn generate_handler_method() -> TokenStream {
    quote! {
        /// Create a handler for this protocol with local-mode topology.
        ///
        /// This is suitable for testing and single-process execution where
        /// all roles run in the same process using in-memory channels.
        ///
        /// # Arguments
        ///
        /// * `role` - The role this handler will act as
        ///
        /// # Example
        ///
        /// ```ignore
        /// let handler = MyProtocol::handler(Role::Alice);
        /// ```
        pub fn handler(role: Role) -> TopologyHandler {
            TopologyHandler::local(role.role_name())
        }
    }
}

/// Generate the `with_topology(topo, role)` method
fn generate_with_topology_method(
    role_names: &[String],
    branch_requirements: &[BranchRequirementSpec],
) -> TokenStream {
    let role_name_literals: Vec<TokenStream> = role_names
        .iter()
        .map(|role| quote! { RoleName::from_static(#role) })
        .collect();

    let branch_requirement_literals: Vec<TokenStream> = branch_requirements
        .iter()
        .map(|req| {
            let sender = &req.sender;
            let receiver = &req.receiver;
            let label_count = req.label_count;
            quote! {
                BranchRequirement::new(
                    RoleName::from_static(#sender),
                    RoleName::from_static(#receiver),
                    #label_count
                )
            }
        })
        .collect();

    quote! {
        /// Create a handler for this protocol with a custom topology.
        ///
        /// This allows specifying where each role is deployed, enabling
        /// distributed execution across multiple processes or machines.
        ///
        /// # Arguments
        ///
        /// * `topology` - The topology configuration
        /// * `role` - The role this handler will act as
        ///
        /// # Example
        ///
        /// ```ignore
        /// let topology = Topology::builder()
        ///     .local_role(RoleName::from_static("Alice"))
        ///     .remote_role(
        ///         RoleName::from_static("Bob"),
        ///         TopologyEndpoint::new("192.168.1.10:8080").unwrap(),
        ///     )
        ///     .build();
        ///
        /// let handler = MyProtocol::with_topology(topology, Role::Alice)?;
        /// ```
        pub fn with_topology(
            topology: Topology,
            role: Role,
        ) -> Result<TopologyHandler, String> {
            let roles = [#(#role_name_literals),*];
            let branch_requirements: &[BranchRequirement] = &[#(#branch_requirement_literals),*];

            // Validate topology against protocol roles
            let validation = topology.validate_with_branches(&roles, &branch_requirements);
            if !validation.is_valid() {
                return Err(format!("Topology validation failed: {:?}", validation));
            }

            Ok(TopologyHandler::new(topology, role.role_name()))
        }
    }
}

/// Generate named topology constants from inline definitions
fn generate_topology_constants(
    inline_topologies: &[InlineTopology],
    role_names: &[String],
) -> TokenStream {
    if inline_topologies.is_empty() {
        return quote! {};
    }

    let constants: Vec<TokenStream> = inline_topologies
        .iter()
        .map(|topo| {
            let _const_name = format_ident!("{}", topo.name.to_uppercase());
            let fn_name = format_ident!("{}", topo.name.to_lowercase());
            let handler_fn_name = format_ident!("{}_handler", topo.name.to_lowercase());

            // Generate the topology builder calls
            let builder_calls = generate_topology_builder(&topo.topology, role_names);

            quote! {
                /// Pre-configured topology: #const_name
                pub fn #fn_name() -> Topology {
                    #builder_calls
                }

                /// Get handler for the #const_name topology
                pub fn #handler_fn_name(role: Role) -> Result<TopologyHandler, String> {
                    with_topology(#fn_name(), role)
                }
            }
        })
        .collect();

    quote! {
        /// Pre-configured topologies for this protocol
        pub mod topologies {
            use super::*;

            #(#constants)*
        }
    }
}

/// Generate topology builder code from a Topology
fn generate_topology_builder(topology: &Topology, _role_names: &[String]) -> TokenStream {
    let mut builder_calls = Vec::new();

    // Add mode if specified
    if let Some(ref mode) = topology.mode {
        builder_calls.push(generate_mode_builder_call(mode));
    }

    // Add role locations
    for (role, location) in &topology.locations {
        builder_calls.push(generate_location_builder_call(role, location));
    }

    // Add constraints
    for constraint in &topology.constraints {
        builder_calls.push(generate_constraint_builder_call(constraint));
    }

    // Add channel capacities
    for ((sender, receiver), capacity) in &topology.channel_capacities {
        builder_calls.push(generate_channel_capacity_builder_call(
            sender, receiver, capacity,
        ));
    }

    // Add role-family constraints
    for (family, constraint) in &topology.role_constraints {
        builder_calls.push(generate_role_family_constraint_builder_call(
            family, constraint,
        ));
    }

    if builder_calls.is_empty() {
        quote! {
            TopologyBuilder::new().build()
        }
    } else {
        quote! {
            TopologyBuilder::new()
                #(#builder_calls)*
                .build()
        }
    }
}

fn generate_mode_builder_call(mode: &TopologyMode) -> TokenStream {
    match mode {
        TopologyMode::Local => quote! { .mode(TopologyMode::Local) },
    }
}

fn generate_location_builder_call(
    role: &crate::identifiers::RoleName,
    location: &Location,
) -> TokenStream {
    let role_literal = role.as_str();
    match location {
        Location::Local => quote! { .local_role(RoleName::from_static(#role_literal)) },
        Location::Remote(endpoint) => {
            let endpoint_literal = endpoint.as_str();
            quote! {
                .remote_role(
                    RoleName::from_static(#role_literal),
                    TopologyEndpoint::new(#endpoint_literal).unwrap()
                )
            }
        }
        Location::Colocated(peer) => {
            let peer_literal = peer.as_str();
            quote! {
                .colocated_role(
                    RoleName::from_static(#role_literal),
                    RoleName::from_static(#peer_literal)
                )
            }
        }
    }
}

fn generate_pinned_location_expr(location: &Location) -> TokenStream {
    match location {
        Location::Local => quote! { Location::Local },
        Location::Remote(endpoint) => {
            let endpoint_literal = endpoint.as_str();
            quote! { Location::Remote(TopologyEndpoint::new(#endpoint_literal).unwrap()) }
        }
        Location::Colocated(peer) => {
            let peer_literal = peer.as_str();
            quote! { Location::Colocated(RoleName::from_static(#peer_literal)) }
        }
    }
}

fn generate_constraint_builder_call(constraint: &TopologyConstraint) -> TokenStream {
    match constraint {
        TopologyConstraint::Colocated(r1, r2) => {
            let r1_literal = r1.as_str();
            let r2_literal = r2.as_str();
            quote! {
                .colocated(
                    RoleName::from_static(#r1_literal),
                    RoleName::from_static(#r2_literal)
                )
            }
        }
        TopologyConstraint::Separated(r1, r2) => {
            let r1_literal = r1.as_str();
            let r2_literal = r2.as_str();
            quote! {
                .separated(
                    RoleName::from_static(#r1_literal),
                    RoleName::from_static(#r2_literal)
                )
            }
        }
        TopologyConstraint::Pinned(role, location) => {
            let role_literal = role.as_str();
            let location_expr = generate_pinned_location_expr(location);
            quote! { .pinned(RoleName::from_static(#role_literal), #location_expr) }
        }
        TopologyConstraint::Region(role, region) => {
            let role_literal = role.as_str();
            let region_literal = region.as_str();
            quote! {
                .region(
                    RoleName::from_static(#role_literal),
                    Region::new(#region_literal).unwrap()
                )
            }
        }
    }
}

fn generate_channel_capacity_builder_call(
    sender: &crate::identifiers::RoleName,
    receiver: &crate::identifiers::RoleName,
    capacity: &crate::ChannelCapacity,
) -> TokenStream {
    let sender_literal = sender.as_str();
    let receiver_literal = receiver.as_str();
    let capacity_value = capacity.get();
    quote! {
        .channel_capacity(
            RoleName::from_static(#sender_literal),
            RoleName::from_static(#receiver_literal),
            ChannelCapacity::try_new(#capacity_value)
                .expect("generated channel capacity must be within declared bounds")
        )
    }
}

fn generate_role_family_constraint_builder_call(
    family: &str,
    constraint: &crate::topology::RoleFamilyConstraint,
) -> TokenStream {
    let min = constraint.min;
    match constraint.max {
        Some(max) => quote! {
            .role_family_constraint(#family, RoleFamilyConstraint::bounded(#min, #max))
        },
        None => quote! {
            .role_family_constraint(#family, RoleFamilyConstraint::min_only(#min))
        },
    }
}

/// Generate complete choreography code with topology integration
#[must_use]
pub fn generate_choreography_code_with_topology(
    choreography: &Choreography,
    local_types: &[(Role, LocalType)],
    inline_topologies: &[InlineTopology],
) -> TokenStream {
    let name = choreography.name.to_string();
    let base_code = generate_choreography_code(&name, &choreography.roles, local_types);
    let topology_code = generate_topology_integration(choreography, inline_topologies);

    quote! {
        #base_code
        #topology_code
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::Protocol;
    use crate::identifiers::RoleName;

    fn create_test_choreography() -> Choreography {
        use quote::format_ident;

        Choreography {
            name: format_ident!("TestProtocol"),
            namespace: None,
            roles: vec![
                Role::new(format_ident!("Alice")).unwrap(),
                Role::new(format_ident!("Bob")).unwrap(),
            ],
            protocol: Protocol::End,
            attrs: std::collections::HashMap::new(),
        }
    }

    #[test]
    fn test_generate_topology_integration_basic() {
        let choreography = create_test_choreography();
        let inline_topologies = vec![];

        let tokens = generate_topology_integration(&choreography, &inline_topologies);
        let code = tokens.to_string();

        // Should generate the topology module
        assert!(code.contains("pub mod topology"));
        // Should construct role names for validation
        assert!(code.contains("RoleName :: from_static"));
        // Should contain handler function
        assert!(code.contains("pub fn handler"));
        // Should contain with_topology function
        assert!(code.contains("pub fn with_topology"));
    }

    #[test]
    fn test_generate_topology_integration_with_inline_topologies() {
        let choreography = create_test_choreography();

        let dev_topology = Topology::builder()
            .mode(TopologyMode::Local)
            .local_role(RoleName::from_static("Alice"))
            .local_role(RoleName::from_static("Bob"))
            .build();

        let prod_topology = Topology::builder()
            .remote_role(
                RoleName::from_static("Alice"),
                crate::identifiers::Endpoint::new("alice.prod:8080").unwrap(),
            )
            .remote_role(
                RoleName::from_static("Bob"),
                crate::identifiers::Endpoint::new("bob.prod:8081").unwrap(),
            )
            .build();

        let inline_topologies = vec![
            InlineTopology {
                name: "Dev".to_string(),
                topology: dev_topology,
            },
            InlineTopology {
                name: "Prod".to_string(),
                topology: prod_topology,
            },
        ];

        let tokens = generate_topology_integration(&choreography, &inline_topologies);
        let code = tokens.to_string();

        // Should generate topology constants module
        assert!(code.contains("pub mod topologies"));
        // Should generate dev topology function
        assert!(code.contains("pub fn dev"));
        // Should generate prod topology function
        assert!(code.contains("pub fn prod"));
        // Should generate handler functions for each
        assert!(code.contains("dev_handler"));
        assert!(code.contains("prod_handler"));
    }

    #[test]
    fn test_generate_handler_method() {
        let tokens = generate_handler_method();
        let code = tokens.to_string();

        assert!(code.contains("pub fn handler"));
        assert!(code.contains("TopologyHandler :: local"));
        assert!(code.contains("role_name"));
    }

    #[test]
    fn test_generate_with_topology_method() {
        let tokens = generate_with_topology_method(&["Alice".to_string(), "Bob".to_string()], &[]);
        let code = tokens.to_string();

        assert!(code.contains("pub fn with_topology"));
        assert!(code.contains("TopologyHandler :: new"));
        assert!(code.contains("topology . validate_with_branches"));
    }

    #[test]
    fn test_generate_topology_builder_local_mode() {
        let topology = Topology::builder().mode(TopologyMode::Local).build();

        let tokens =
            generate_topology_builder(&topology, &["Alice".to_string(), "Bob".to_string()]);
        let code = tokens.to_string();

        assert!(code.contains("TopologyMode :: Local"));
    }

    #[test]
    fn test_generated_topology_helpers_do_not_import_deployment_backends() {
        let choreography = create_test_choreography();
        let tokens = generate_topology_integration(&choreography, &[]);
        let code = tokens.to_string();

        assert!(!code.contains("Datacenter"));
        assert!(!code.contains("Kubernetes"));
        assert!(!code.contains("Consul"));
    }

    #[test]
    fn test_generate_topology_builder_with_roles() {
        let topology = Topology::builder()
            .local_role(RoleName::from_static("Alice"))
            .remote_role(
                RoleName::from_static("Bob"),
                crate::identifiers::Endpoint::new("localhost:8080").unwrap(),
            )
            .build();

        let tokens =
            generate_topology_builder(&topology, &["Alice".to_string(), "Bob".to_string()]);
        let code = tokens.to_string();

        assert!(code.contains("local_role"));
        assert!(code.contains("remote_role"));
        assert!(code.contains("localhost:8080"));
    }

    #[test]
    fn test_generate_topology_builder_with_constraints() {
        let topology = Topology::builder()
            .local_role(RoleName::from_static("Alice"))
            .local_role(RoleName::from_static("Bob"))
            .colocated(RoleName::from_static("Alice"), RoleName::from_static("Bob"))
            .separated(
                RoleName::from_static("Alice"),
                RoleName::from_static("Carol"),
            )
            .role_family_constraint(
                "Witness",
                crate::topology::RoleFamilyConstraint::bounded(2, 5),
            )
            .build();

        let tokens = generate_topology_builder(
            &topology,
            &["Alice".to_string(), "Bob".to_string(), "Carol".to_string()],
        );
        let code = tokens.to_string();

        assert!(code.contains("colocated"));
        assert!(code.contains("separated"));
        assert!(code.contains("role_family_constraint"));
        assert!(code.contains("RoleFamilyConstraint :: bounded"));
    }

    #[test]
    fn test_generate_choreography_code_with_topology() {
        let choreography = create_test_choreography();
        let local_types = vec![
            (
                Role::new(format_ident!("Alice")).unwrap(),
                crate::ast::LocalType::End,
            ),
            (
                Role::new(format_ident!("Bob")).unwrap(),
                crate::ast::LocalType::End,
            ),
        ];
        let inline_topologies = vec![];

        let tokens = generate_choreography_code_with_topology(
            &choreography,
            &local_types,
            &inline_topologies,
        );
        let code = tokens.to_string();

        // Should contain role definitions
        assert!(code.contains("Alice") || code.contains("Roles"));
        // Should contain topology integration
        assert!(code.contains("pub mod topology"));
    }
}