telltale-runtime 17.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
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]

//! Complete workflow example with multiple extension types
//!
//! This example demonstrates a realistic authentication workflow using:
//! - Capability validation
//! - Flow cost tracking
//! - Logging
//! - Metrics collection

use std::any::{Any, TypeId};
use std::sync::{Arc, Mutex};
use telltale_runtime::effects::*;
use telltale_runtime::RoleName;

// ============================================================================
// Domain Types
// ============================================================================

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum Role {
    Client,
    Server,
    Database,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum WorkflowLabel {
    Default,
}

impl LabelId for WorkflowLabel {
    fn as_str(&self) -> &'static str {
        match self {
            WorkflowLabel::Default => "default",
        }
    }

    fn from_str(label: &str) -> Option<Self> {
        match label {
            "default" => Some(WorkflowLabel::Default),
            _ => None,
        }
    }
}

impl RoleId for Role {
    type Label = WorkflowLabel;

    fn role_name(&self) -> RoleName {
        match self {
            Role::Client => RoleName::from_static("Client"),
            Role::Server => RoleName::from_static("Server"),
            Role::Database => RoleName::from_static("Database"),
        }
    }
}

// ============================================================================
// Extension Definitions
// ============================================================================

#[derive(Clone, Debug)]
struct ValidateCapability {
    capability: String,
    role: Role,
}

impl ExtensionEffect<Role> for ValidateCapability {
    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn type_name(&self) -> &'static str {
        "ValidateCapability"
    }

    fn participating_roles(&self) -> Vec<Role> {
        vec![self.role]
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn clone_box(&self) -> Box<dyn ExtensionEffect<Role>> {
        Box::new(self.clone())
    }
}

#[derive(Clone, Debug)]
struct ChargeFlowCost {
    cost: u32,
    role: Role,
}

impl ExtensionEffect<Role> for ChargeFlowCost {
    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn type_name(&self) -> &'static str {
        "ChargeFlowCost"
    }

    fn participating_roles(&self) -> Vec<Role> {
        vec![self.role]
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn clone_box(&self) -> Box<dyn ExtensionEffect<Role>> {
        Box::new(self.clone())
    }
}

#[derive(Clone, Debug)]
struct LogEvent {
    message: String,
    level: LogLevel,
}

#[derive(Clone, Debug)]
enum LogLevel {
    Info,
    Warn,
    Error,
}

impl ExtensionEffect<Role> for LogEvent {
    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn type_name(&self) -> &'static str {
        "LogEvent"
    }

    fn participating_roles(&self) -> Vec<Role> {
        vec![] // Global
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn clone_box(&self) -> Box<dyn ExtensionEffect<Role>> {
        Box::new(self.clone())
    }
}

#[derive(Clone, Debug)]
struct RecordMetric {
    metric: String,
    value: u64,
}

impl ExtensionEffect<Role> for RecordMetric {
    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn type_name(&self) -> &'static str {
        "RecordMetric"
    }

    fn participating_roles(&self) -> Vec<Role> {
        vec![]
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn clone_box(&self) -> Box<dyn ExtensionEffect<Role>> {
        Box::new(self.clone())
    }
}

// ============================================================================
// Extensible Handler
// ============================================================================

struct WorkflowHandler {
    role: Role,
    registry: ExtensionRegistry<(), Role>,
    budget: Arc<Mutex<u32>>,
    metrics: Arc<Mutex<Vec<(String, u64)>>>,
}

impl WorkflowHandler {
    fn new(role: Role, capabilities: Vec<String>, initial_budget: u32) -> Self {
        let budget = Arc::new(Mutex::new(initial_budget));
        let metrics = Arc::new(Mutex::new(Vec::new()));
        let mut registry = ExtensionRegistry::new();

        // Register capability validation
        let caps = capabilities.clone();
        registry
            .register::<ValidateCapability, _>(move |_ep, ext| {
                let caps = caps.clone();
                Box::pin(async move {
                    let validate = ext.as_any().downcast_ref::<ValidateCapability>().ok_or(
                        ExtensionError::TypeMismatch {
                            expected: "ValidateCapability",
                            actual: ext.type_name(),
                        },
                    )?;

                    if !caps.contains(&validate.capability) {
                        return Err(ExtensionError::ExecutionFailed {
                            type_name: "ValidateCapability",
                            error: format!("Missing capability: {}", validate.capability),
                        });
                    }

                    println!(
                        "[{:?}] Validated capability: {}",
                        validate.role, validate.capability
                    );
                    Ok(())
                })
            })
            .expect("ValidateCapability handler registration");

        // Register flow cost tracking
        let budget_ref = budget.clone();
        registry
            .register::<ChargeFlowCost, _>(move |_ep, ext| {
                let budget = budget_ref.clone();
                Box::pin(async move {
                    let cost = ext.as_any().downcast_ref::<ChargeFlowCost>().ok_or(
                        ExtensionError::TypeMismatch {
                            expected: "ChargeFlowCost",
                            actual: ext.type_name(),
                        },
                    )?;

                    let mut budget_lock = budget.lock().unwrap();
                    if *budget_lock < cost.cost {
                        return Err(ExtensionError::ExecutionFailed {
                            type_name: "ChargeFlowCost",
                            error: format!("Insufficient budget: {} < {}", *budget_lock, cost.cost),
                        });
                    }

                    *budget_lock -= cost.cost;
                    println!(
                        "[{:?}] Charged {} units (remaining: {})",
                        cost.role, cost.cost, *budget_lock
                    );
                    Ok(())
                })
            })
            .expect("ChargeFlowCost handler registration");

        // Register logging
        registry
            .register::<LogEvent, _>(|_ep, ext| {
                Box::pin(async move {
                    let log = ext.as_any().downcast_ref::<LogEvent>().ok_or(
                        ExtensionError::TypeMismatch {
                            expected: "LogEvent",
                            actual: ext.type_name(),
                        },
                    )?;

                    match log.level {
                        LogLevel::Info => println!("[INFO] {}", log.message),
                        LogLevel::Warn => println!("[WARN] {}", log.message),
                        LogLevel::Error => println!("[ERROR] {}", log.message),
                    }
                    Ok(())
                })
            })
            .expect("LogEvent handler registration");

        // Register metrics
        let metrics_ref = metrics.clone();
        registry
            .register::<RecordMetric, _>(move |_ep, ext| {
                let metrics = metrics_ref.clone();
                Box::pin(async move {
                    let metric = ext.as_any().downcast_ref::<RecordMetric>().ok_or(
                        ExtensionError::TypeMismatch {
                            expected: "RecordMetric",
                            actual: ext.type_name(),
                        },
                    )?;

                    metrics
                        .lock()
                        .unwrap()
                        .push((metric.metric.clone(), metric.value));
                    println!("Metric: {} = {}", metric.metric, metric.value);
                    Ok(())
                })
            })
            .expect("RecordMetric handler registration");

        Self {
            role,
            registry,
            budget,
            metrics,
        }
    }

    fn remaining_budget(&self) -> u32 {
        *self.budget.lock().unwrap()
    }

    fn collected_metrics(&self) -> Vec<(String, u64)> {
        self.metrics.lock().unwrap().clone()
    }
}

#[async_trait::async_trait]
impl ExtensibleHandler for WorkflowHandler {
    fn extension_registry(&self) -> &ExtensionRegistry<Self::Endpoint, Self::Role> {
        &self.registry
    }
}

#[async_trait::async_trait]
impl ChoreoHandler for WorkflowHandler {
    type Role = Role;
    type Endpoint = ();

    async fn send<M: serde::Serialize + Send + Sync>(
        &mut self,
        _ep: &mut Self::Endpoint,
        to: Self::Role,
        _msg: &M,
    ) -> ChoreoResult<()> {
        println!("[{:?}] -> [{:?}] Message sent", self.role, to);
        Ok(())
    }

    async fn recv<M: serde::de::DeserializeOwned + Send>(
        &mut self,
        _ep: &mut Self::Endpoint,
        from: Self::Role,
    ) -> ChoreoResult<M> {
        println!("[{:?}] <- [{:?}] Message received", self.role, from);
        Err(ChoreographyError::Transport(
            "recv not implemented in example".into(),
        ))
    }

    async fn choose(
        &mut self,
        _ep: &mut Self::Endpoint,
        _who: Self::Role,
        label: WorkflowLabel,
    ) -> ChoreoResult<()> {
        println!("[{:?}] Choice: {}", self.role, label.as_str());
        Ok(())
    }

    async fn offer(
        &mut self,
        _ep: &mut Self::Endpoint,
        from: Self::Role,
    ) -> ChoreoResult<WorkflowLabel> {
        println!("[{:?}] Offering choice from {:?}", self.role, from);
        Ok(WorkflowLabel::Default)
    }

    async fn with_timeout<F, T>(
        &mut self,
        _ep: &mut Self::Endpoint,
        _at: Self::Role,
        _dur: std::time::Duration,
        body: F,
    ) -> ChoreoResult<T>
    where
        F: std::future::Future<Output = ChoreoResult<T>> + Send,
    {
        body.await
    }
}

// ============================================================================
// Choreography Definition
// ============================================================================

// Helper to demonstrate all log levels
fn _example_log_levels() -> Program<Role, String> {
    Program::new()
        .ext(LogEvent {
            message: "This is an info message".into(),
            level: LogLevel::Info,
        })
        .ext(LogEvent {
            message: "This is a warning message".into(),
            level: LogLevel::Warn,
        })
        .ext(LogEvent {
            message: "This is an error message".into(),
            level: LogLevel::Error,
        })
        .end()
}

fn authentication_workflow() -> Program<Role, String> {
    Program::new()
        // Protocol start
        .ext(LogEvent {
            message: "Authentication workflow started".into(),
            level: LogLevel::Info,
        })
        .ext(RecordMetric {
            metric: "auth_started".into(),
            value: 1,
        })
        // Client validates capability and pays for request
        .ext(ValidateCapability {
            capability: "authenticate".into(),
            role: Role::Client,
        })
        .ext(ChargeFlowCost {
            cost: 100,
            role: Role::Client,
        })
        .ext(LogEvent {
            message: "High cost operation - check budget".into(),
            level: LogLevel::Warn,
        })
        .send(Role::Server, "auth_request".into())
        // Server validates and queries database
        .ext(LogEvent {
            message: "Server processing authentication".into(),
            level: LogLevel::Info,
        })
        .ext(ValidateCapability {
            capability: "query_users".into(),
            role: Role::Server,
        })
        .ext(ChargeFlowCost {
            cost: 50,
            role: Role::Server,
        })
        .send(Role::Database, "user_query".into())
        // Database processes query
        .ext(ValidateCapability {
            capability: "read_users".into(),
            role: Role::Database,
        })
        .ext(ChargeFlowCost {
            cost: 25,
            role: Role::Database,
        })
        .ext(LogEvent {
            message: "Database query cost exceeds threshold".into(),
            level: LogLevel::Error,
        })
        .send(Role::Server, "user_data".into())
        // Server sends response to client
        .ext(ChargeFlowCost {
            cost: 30,
            role: Role::Server,
        })
        .send(Role::Client, "auth_response".into())
        // Protocol completion
        .ext(LogEvent {
            message: "Authentication successful".into(),
            level: LogLevel::Info,
        })
        .ext(RecordMetric {
            metric: "auth_success".into(),
            value: 1,
        })
        .end()
}

// ============================================================================
// Main
// ============================================================================

#[tokio::main]
async fn main() {
    println!("{}", "=".repeat(60));
    println!("Extension Workflow Example: Authentication Protocol");
    println!("{}", "=".repeat(60));
    println!();

    // Create handler with capabilities and budget
    let mut handler = WorkflowHandler::new(
        Role::Client,
        vec![
            "authenticate".into(),
            "query_users".into(),
            "read_users".into(),
        ],
        500, // Initial budget
    );

    println!("Initial budget: {} units\n", handler.remaining_budget());

    // Build choreography
    let program = authentication_workflow();
    println!("Program has {} effects\n", program.len());

    // Execute with extensions
    let mut endpoint = ();
    match interpret_extensible(&mut handler, &mut endpoint, program).await {
        Ok(result) => {
            println!();
            println!("{}", "=".repeat(60));
            match result.final_state {
                InterpreterState::Completed => {
                    println!("Protocol completed successfully");
                }
                InterpreterState::Failed(err) => {
                    println!("Protocol failed: {}", err);
                }
                InterpreterState::Timeout => {
                    println!("Protocol timed out");
                }
            }

            println!();
            println!("Final budget: {} units", handler.remaining_budget());
            println!();
            println!("Collected metrics:");
            for (metric, value) in handler.collected_metrics() {
                println!("  {} = {}", metric, value);
            }
            println!("{}", "=".repeat(60));
        }
        Err(e) => {
            println!("\nError: {}", e);
        }
    }
}