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
556
557
558
559
560
561
562
563
564
565
566
#![cfg(not(target_arch = "wasm32"))]
//! Tests for TelltaleHandler and TelltaleEndpoint correctness.
//!
//! Verifies:
//! - Session metadata progression (operation_count, state_description, is_complete)
//! - Session registration and overwrite semantics
//! - TelltaleSession operation
//! - Missing session error handling
//! - Drop cleanup behavior

#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]

use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::hash::Hash;
use telltale::Message;
use telltale_runtime::effects::{
    handlers::telltale::{TelltaleEndpoint, TelltaleHandler, TelltaleSession},
    ChoreoHandler, LabelId, RoleId,
};
use telltale_runtime::RoleName;

// ============================================================================
// Test Role Setup
// ============================================================================

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum TestRole {
    Alice,
    Bob,
    Charlie,
}

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

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

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

impl RoleId for TestRole {
    type Label = ChoiceLabel;

    fn role_name(&self) -> RoleName {
        match self {
            TestRole::Alice => RoleName::from_static("Alice"),
            TestRole::Bob => RoleName::from_static("Bob"),
            TestRole::Charlie => RoleName::from_static("Charlie"),
        }
    }
}

// Implement Role trait for TestRole
impl telltale::Role for TestRole {
    type Message = TestLabel;

    fn seal(&mut self) {
        // No-op for test role
    }

    fn is_sealed(&self) -> bool {
        false
    }
}

#[derive(Debug)]
enum TestLabel {
    Msg(TestMessage),
}

impl Message<Box<dyn std::any::Any + Send>> for TestLabel {
    fn upcast(msg: Box<dyn std::any::Any + Send>) -> Self {
        TestLabel::Msg(*msg.downcast::<TestMessage>().unwrap())
    }

    fn downcast(self) -> Result<Box<dyn std::any::Any + Send>, Self> {
        match self {
            TestLabel::Msg(m) => Ok(Box::new(m)),
        }
    }
}

// ============================================================================
// Test Message Types
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct TestMessage {
    value: i32,
}

// ============================================================================
// TelltaleSession Tests
// ============================================================================

#[tokio::test]
async fn test_telltale_session_pair_creation() {
    let (mut left, mut right) = TelltaleSession::pair();

    // Send from left to right
    left.send(vec![1, 2, 3]).await.expect("Send should succeed");

    let received = right.recv().await.expect("Recv should succeed");
    assert_eq!(received.output, vec![1, 2, 3]);
}

#[tokio::test]
async fn test_telltale_session_bidirectional() {
    let (mut left, mut right) = TelltaleSession::pair();

    // Left -> Right
    left.send(vec![1]).await.unwrap();
    assert_eq!(right.recv().await.unwrap().output, vec![1]);

    // Right -> Left
    right.send(vec![2]).await.unwrap();
    assert_eq!(left.recv().await.unwrap().output, vec![2]);
}

#[tokio::test]
async fn test_telltale_session_multiple_messages() {
    let (mut left, mut right) = TelltaleSession::pair();

    // Send multiple messages
    left.send(vec![1]).await.unwrap();
    left.send(vec![2]).await.unwrap();
    left.send(vec![3]).await.unwrap();

    // Receive in FIFO order
    assert_eq!(right.recv().await.unwrap().output, vec![1]);
    assert_eq!(right.recv().await.unwrap().output, vec![2]);
    assert_eq!(right.recv().await.unwrap().output, vec![3]);
}

// ============================================================================
// TelltaleEndpoint Tests
// ============================================================================

#[tokio::test]
async fn test_endpoint_creation() {
    let endpoint: TelltaleEndpoint<TestRole> = TelltaleEndpoint::new(TestRole::Alice);

    assert_eq!(*endpoint.local_role(), TestRole::Alice);
    assert!(endpoint.is_all_closed());
    assert_eq!(endpoint.active_channel_count(), 0);
}

#[tokio::test]
async fn test_endpoint_register_session() {
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);
    let (session, _other) = TelltaleSession::pair();

    endpoint.register_session(TestRole::Bob, session);

    assert!(endpoint.has_channel(&TestRole::Bob));
    assert!(!endpoint.has_channel(&TestRole::Charlie));
    assert_eq!(endpoint.active_channel_count(), 1);
}

#[tokio::test]
async fn test_endpoint_session_overwrite() {
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);

    // Register first session
    let (session1, _) = TelltaleSession::pair();
    endpoint.register_session(TestRole::Bob, session1);

    // Register second session (overwrites first)
    let (session2, _) = TelltaleSession::pair();
    endpoint.register_session(TestRole::Bob, session2);

    // Still only one session
    assert_eq!(endpoint.active_channel_count(), 1);
    assert!(endpoint.has_channel(&TestRole::Bob));
}

#[tokio::test]
async fn test_endpoint_close_channel() {
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);
    let (session, _) = TelltaleSession::pair();

    endpoint.register_session(TestRole::Bob, session);
    assert!(endpoint.has_channel(&TestRole::Bob));

    let closed = endpoint.close_channel(&TestRole::Bob);
    assert!(closed);
    assert!(!endpoint.has_channel(&TestRole::Bob));

    // Closing non-existent channel returns false
    let closed_again = endpoint.close_channel(&TestRole::Bob);
    assert!(!closed_again);
}

#[tokio::test]
async fn test_endpoint_close_all_channels() {
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);

    let (session1, _) = TelltaleSession::pair();
    let (session2, _) = TelltaleSession::pair();

    endpoint.register_session(TestRole::Bob, session1);
    endpoint.register_session(TestRole::Charlie, session2);

    assert_eq!(endpoint.active_channel_count(), 2);

    let count = endpoint.close_all_channels();
    assert_eq!(count, 2);
    assert!(endpoint.is_all_closed());
}

#[tokio::test]
async fn test_endpoint_metadata_initial() {
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);
    let (session, _) = TelltaleSession::pair();

    endpoint.register_session(TestRole::Bob, session);

    let metadata = endpoint.get_metadata(&TestRole::Bob).unwrap();
    assert_eq!(metadata.state_description, "Initial");
    assert!(!metadata.is_complete);
    assert_eq!(metadata.operation_count, 0);
}

#[tokio::test]
async fn test_endpoint_all_metadata() {
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);

    let (session1, _) = TelltaleSession::pair();
    let (session2, _) = TelltaleSession::pair();

    endpoint.register_session(TestRole::Bob, session1);
    endpoint.register_session(TestRole::Charlie, session2);

    let all = endpoint.all_metadata();
    assert_eq!(all.len(), 2);
}

// ============================================================================
// TelltaleHandler Send/Recv Tests
// ============================================================================

#[tokio::test]
async fn test_handler_send_recv_with_telltale_session() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();

    // Create endpoints with connected sessions
    let mut alice_ep = TelltaleEndpoint::new(TestRole::Alice);
    let mut bob_ep = TelltaleEndpoint::new(TestRole::Bob);

    let (alice_to_bob, bob_from_alice) = TelltaleSession::pair();
    alice_ep.register_session(TestRole::Bob, alice_to_bob);
    bob_ep.register_session(TestRole::Alice, bob_from_alice);

    // Alice sends to Bob
    let msg = TestMessage { value: 42 };
    handler
        .send(&mut alice_ep, TestRole::Bob, &msg)
        .await
        .expect("Send should succeed");

    // Bob receives from Alice
    let received: TestMessage = handler
        .recv(&mut bob_ep, TestRole::Alice)
        .await
        .expect("Recv should succeed");

    assert_eq!(received, msg);
}

#[tokio::test]
async fn test_handler_metadata_updates_on_send() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);

    let (session, mut other) = TelltaleSession::pair();
    endpoint.register_session(TestRole::Bob, session);

    // Initial state
    let meta = endpoint.get_metadata(&TestRole::Bob).unwrap();
    assert_eq!(meta.operation_count, 0);

    // Send a message
    handler
        .send(&mut endpoint, TestRole::Bob, &TestMessage { value: 1 })
        .await
        .unwrap();

    // Consume the message on the other end to avoid channel blocking
    drop(other.recv().await);

    // Metadata should be updated
    let meta = endpoint.get_metadata(&TestRole::Bob).unwrap();
    assert_eq!(meta.operation_count, 1);
    assert_eq!(meta.state_description, "Send");
}

#[tokio::test]
async fn test_handler_metadata_updates_on_recv() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let mut endpoint = TelltaleEndpoint::new(TestRole::Bob);

    let (session, mut other) = TelltaleSession::pair();
    endpoint.register_session(TestRole::Alice, session);

    // Send a message from the other side
    let msg = TestMessage { value: 42 };
    let bytes = bincode::serialize(&msg).unwrap();
    other.send(bytes).await.unwrap();

    // Receive
    let _: TestMessage = handler.recv(&mut endpoint, TestRole::Alice).await.unwrap();

    // Metadata should be updated
    let meta = endpoint.get_metadata(&TestRole::Alice).unwrap();
    assert_eq!(meta.operation_count, 1);
    assert_eq!(meta.state_description, "Recv");
}

#[tokio::test]
async fn test_handler_operation_count_increments() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();

    // Set up bidirectional channels
    let mut alice_ep = TelltaleEndpoint::new(TestRole::Alice);
    let mut bob_ep = TelltaleEndpoint::new(TestRole::Bob);

    let (alice_to_bob, bob_from_alice) = TelltaleSession::pair();
    let (bob_to_alice, alice_from_bob) = TelltaleSession::pair();

    alice_ep.register_session(TestRole::Bob, alice_to_bob);
    bob_ep.register_session(TestRole::Alice, bob_from_alice);

    // Also register reverse channels for bidirectional
    let mut alice_ep2 = TelltaleEndpoint::new(TestRole::Alice);
    alice_ep2.register_session(TestRole::Bob, alice_from_bob);
    let mut bob_ep2 = TelltaleEndpoint::new(TestRole::Bob);
    bob_ep2.register_session(TestRole::Alice, bob_to_alice);

    // Perform multiple operations
    handler
        .send(&mut alice_ep, TestRole::Bob, &TestMessage { value: 1 })
        .await
        .unwrap();
    let _: TestMessage = handler.recv(&mut bob_ep, TestRole::Alice).await.unwrap();

    handler
        .send(&mut alice_ep, TestRole::Bob, &TestMessage { value: 2 })
        .await
        .unwrap();
    let _: TestMessage = handler.recv(&mut bob_ep, TestRole::Alice).await.unwrap();

    // Check operation counts
    let alice_meta = alice_ep.get_metadata(&TestRole::Bob).unwrap();
    assert_eq!(alice_meta.operation_count, 2);

    let bob_meta = bob_ep.get_metadata(&TestRole::Alice).unwrap();
    assert_eq!(bob_meta.operation_count, 2);
}

// ============================================================================
// Choose/Offer Tests
// ============================================================================

#[tokio::test]
async fn test_handler_choose_offer() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();

    let mut alice_ep = TelltaleEndpoint::new(TestRole::Alice);
    let mut bob_ep = TelltaleEndpoint::new(TestRole::Bob);

    let (alice_to_bob, bob_from_alice) = TelltaleSession::pair();
    alice_ep.register_session(TestRole::Bob, alice_to_bob);
    bob_ep.register_session(TestRole::Alice, bob_from_alice);

    // Alice chooses
    handler
        .choose(&mut alice_ep, TestRole::Bob, ChoiceLabel::Accept)
        .await
        .expect("Choose should succeed");

    // Bob offers and receives the choice
    let label = handler
        .offer(&mut bob_ep, TestRole::Alice)
        .await
        .expect("Offer should succeed");

    assert_eq!(label, ChoiceLabel::Accept);
}

#[tokio::test]
async fn test_handler_choose_updates_metadata() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);

    let (session, mut other) = TelltaleSession::pair();
    endpoint.register_session(TestRole::Bob, session);

    handler
        .choose(&mut endpoint, TestRole::Bob, ChoiceLabel::Option1)
        .await
        .unwrap();

    // Consume on the other end
    drop(other.recv().await);

    let meta = endpoint.get_metadata(&TestRole::Bob).unwrap();
    assert_eq!(meta.operation_count, 1);
    assert_eq!(meta.state_description, "Choose");
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn test_handler_missing_channel_error() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);

    // Try to send without registering a session
    let result = handler
        .send(&mut endpoint, TestRole::Bob, &TestMessage { value: 1 })
        .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("no session registered"),
        "Error should mention missing session registration: {}",
        msg
    );
}

#[tokio::test]
async fn test_handler_missing_channel_on_recv() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let mut endpoint = TelltaleEndpoint::new(TestRole::Bob);

    let result: Result<TestMessage, _> = handler.recv(&mut endpoint, TestRole::Alice).await;

    assert!(result.is_err());
}

// ============================================================================
// Timeout Tests
// ============================================================================

#[tokio::test]
async fn test_handler_with_timeout_success() {
    use std::time::Duration;

    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);

    let result = handler
        .with_timeout(
            &mut endpoint,
            TestRole::Alice,
            Duration::from_secs(1),
            async { Ok(42) },
        )
        .await;

    assert_eq!(result.unwrap(), 42);
}

#[tokio::test]
async fn test_handler_with_timeout_expires() {
    use std::time::Duration;

    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let mut endpoint = TelltaleEndpoint::new(TestRole::Alice);

    let result: Result<i32, _> = handler
        .with_timeout(
            &mut endpoint,
            TestRole::Alice,
            Duration::from_millis(10),
            async {
                tokio::time::sleep(Duration::from_secs(10)).await;
                Ok(42)
            },
        )
        .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    let msg = format!("{:?}", err);
    assert!(
        msg.contains("Timeout"),
        "Should be a timeout error: {}",
        msg
    );
}

// ============================================================================
// Handler Default Implementation Test
// ============================================================================

#[tokio::test]
async fn test_handler_default() {
    let handler1: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let handler2: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::default();

    // Both should work identically - just verify they can be created
    let _ = handler1;
    let _ = handler2;
}

// ============================================================================
// Multi-Peer Tests
// ============================================================================

#[tokio::test]
async fn test_endpoint_multiple_peers() {
    let mut handler: TelltaleHandler<TestRole, TestLabel> = TelltaleHandler::new();
    let mut alice_ep = TelltaleEndpoint::new(TestRole::Alice);

    // Register sessions to multiple peers
    let (to_bob, mut from_bob) = TelltaleSession::pair();
    let (to_charlie, mut from_charlie) = TelltaleSession::pair();

    alice_ep.register_session(TestRole::Bob, to_bob);
    alice_ep.register_session(TestRole::Charlie, to_charlie);

    // Send to both
    handler
        .send(&mut alice_ep, TestRole::Bob, &TestMessage { value: 1 })
        .await
        .unwrap();
    handler
        .send(&mut alice_ep, TestRole::Charlie, &TestMessage { value: 2 })
        .await
        .unwrap();

    // Receive on both
    let bob_bytes = from_bob.recv().await.unwrap().output;
    let charlie_bytes = from_charlie.recv().await.unwrap().output;

    let bob_msg: TestMessage = bincode::deserialize(&bob_bytes).unwrap();
    let charlie_msg: TestMessage = bincode::deserialize(&charlie_bytes).unwrap();

    assert_eq!(bob_msg.value, 1);
    assert_eq!(charlie_msg.value, 2);
}