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
#![cfg(not(target_arch = "wasm32"))]
//! Tests for RecordingHandler correctness.
//!
//! Verifies:
//! - All events captured in order
//! - Event types match operations
//! - recv()/offer() intentionally fail (by design)
//! - Thread-safe accumulation

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

use serde::{Deserialize, Serialize};
use telltale_runtime::effects::{
    handlers::recording::{RecordedEvent, RecordingHandler},
    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 TestLabel {
    Accept,
    Option1,
}

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

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

impl RoleId for TestRole {
    type Label = TestLabel;

    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"),
        }
    }
}

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

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

#[derive(Debug, Clone, Serialize, Deserialize)]
struct AnotherMessage {
    data: String,
}

// ============================================================================
// Basic Recording Tests
// ============================================================================

#[tokio::test]
async fn test_recording_captures_send() {
    let mut handler = RecordingHandler::new(TestRole::Alice);

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

    let events = handler.events();
    assert_eq!(events.len(), 1);

    match &events[0] {
        RecordedEvent::Send { from, to, msg_type } => {
            assert_eq!(*from, TestRole::Alice);
            assert_eq!(*to, TestRole::Bob);
            assert!(msg_type.contains("TestMessage"));
        }
        _ => panic!("Expected Send event"),
    }
}

#[tokio::test]
async fn test_recording_captures_recv_then_fails() {
    let mut handler = RecordingHandler::new(TestRole::Bob);

    // recv() should record the event but return an error
    let result: Result<TestMessage, _> = handler.recv(&mut (), TestRole::Alice).await;

    assert!(result.is_err(), "recv() should return error by design");

    let events = handler.events();
    assert_eq!(events.len(), 1);

    match &events[0] {
        RecordedEvent::Recv { from, to, msg_type } => {
            assert_eq!(*from, TestRole::Alice);
            assert_eq!(*to, TestRole::Bob);
            assert!(msg_type.contains("TestMessage"));
        }
        _ => panic!("Expected Recv event"),
    }
}

#[tokio::test]
async fn test_recording_captures_choose() {
    let mut handler = RecordingHandler::new(TestRole::Alice);

    let label = TestLabel::Accept;
    handler
        .choose(&mut (), TestRole::Bob, label)
        .await
        .expect("Choose should succeed");

    let events = handler.events();
    assert_eq!(events.len(), 1);

    match &events[0] {
        RecordedEvent::Choose { at, label } => {
            assert_eq!(*at, TestRole::Bob);
            assert_eq!(*label, TestLabel::Accept);
        }
        _ => panic!("Expected Choose event"),
    }
}

#[tokio::test]
async fn test_recording_captures_offer_then_fails() {
    let mut handler = RecordingHandler::new(TestRole::Bob);

    // offer() should record the event but return an error
    let result = handler.offer(&mut (), TestRole::Alice).await;

    assert!(result.is_err(), "offer() should return error by design");

    let events = handler.events();
    assert_eq!(events.len(), 1);

    match &events[0] {
        RecordedEvent::Offer { from, to } => {
            assert_eq!(*from, TestRole::Alice);
            assert_eq!(*to, TestRole::Bob);
        }
        _ => panic!("Expected Offer event"),
    }
}

// ============================================================================
// Event Ordering Tests
// ============================================================================

#[tokio::test]
async fn test_recording_preserves_event_order() {
    let mut handler = RecordingHandler::new(TestRole::Alice);

    // Perform a sequence of operations
    handler
        .send(&mut (), TestRole::Bob, &TestMessage { value: 1 })
        .await
        .unwrap();
    handler
        .send(&mut (), TestRole::Charlie, &TestMessage { value: 2 })
        .await
        .unwrap();
    handler
        .choose(&mut (), TestRole::Bob, TestLabel::Option1)
        .await
        .unwrap();
    handler
        .send(
            &mut (),
            TestRole::Bob,
            &AnotherMessage {
                data: "test".to_string(),
            },
        )
        .await
        .unwrap();

    let events = handler.events();
    assert_eq!(events.len(), 4);

    // Verify order
    match &events[0] {
        RecordedEvent::Send { to, .. } => assert_eq!(*to, TestRole::Bob),
        _ => panic!("Expected Send to Bob first"),
    }
    match &events[1] {
        RecordedEvent::Send { to, .. } => assert_eq!(*to, TestRole::Charlie),
        _ => panic!("Expected Send to Charlie second"),
    }
    match &events[2] {
        RecordedEvent::Choose { label, .. } => assert_eq!(*label, TestLabel::Option1),
        _ => panic!("Expected Choose third"),
    }
    match &events[3] {
        RecordedEvent::Send { to, msg_type, .. } => {
            assert_eq!(*to, TestRole::Bob);
            assert!(msg_type.contains("AnotherMessage"));
        }
        _ => panic!("Expected Send fourth"),
    }
}

// ============================================================================
// Clear and Events Access Tests
// ============================================================================

#[tokio::test]
async fn test_recording_clear() {
    let mut handler = RecordingHandler::new(TestRole::Alice);

    handler
        .send(&mut (), TestRole::Bob, &TestMessage { value: 1 })
        .await
        .unwrap();
    handler
        .send(&mut (), TestRole::Bob, &TestMessage { value: 2 })
        .await
        .unwrap();

    assert_eq!(handler.events().len(), 2);

    handler.clear();

    assert_eq!(handler.events().len(), 0);
}

#[tokio::test]
async fn test_recording_events_returns_clone() {
    let mut handler = RecordingHandler::new(TestRole::Alice);

    handler
        .send(&mut (), TestRole::Bob, &TestMessage { value: 1 })
        .await
        .unwrap();

    let events1 = handler.events();
    let events2 = handler.events();

    // Both calls should return the same events
    assert_eq!(events1.len(), events2.len());

    // Modifying handler doesn't affect already-returned events
    handler
        .send(&mut (), TestRole::Bob, &TestMessage { value: 2 })
        .await
        .unwrap();

    assert_eq!(events1.len(), 1); // Original clone unchanged
    assert_eq!(handler.events().len(), 2); // New call sees update
}

// ============================================================================
// Thread Safety Tests
// ============================================================================

#[tokio::test]
async fn test_recording_shared_across_clones() {
    let handler1 = RecordingHandler::new(TestRole::Alice);
    let mut handler2 = handler1.clone();

    // Send from cloned handler
    handler2
        .send(&mut (), TestRole::Bob, &TestMessage { value: 42 })
        .await
        .unwrap();

    // Original handler should see the event (shared Arc)
    let events = handler1.events();
    assert_eq!(events.len(), 1);
}

#[tokio::test]
async fn test_recording_concurrent_sends() {
    use std::sync::Arc;
    use tokio::sync::Barrier;

    let handler = RecordingHandler::new(TestRole::Alice);
    let barrier = Arc::new(Barrier::new(3));

    let mut handles = vec![];

    for i in 0..3 {
        let mut h = handler.clone();
        let b = barrier.clone();
        handles.push(tokio::spawn(async move {
            b.wait().await;
            h.send(&mut (), TestRole::Bob, &TestMessage { value: i })
                .await
                .unwrap();
        }));
    }

    for handle in handles {
        handle.await.unwrap();
    }

    let events = handler.events();
    assert_eq!(events.len(), 3, "All concurrent sends should be recorded");
}

// ============================================================================
// Error Message Tests
// ============================================================================

#[tokio::test]
async fn test_recv_error_message() {
    let mut handler = RecordingHandler::new(TestRole::Bob);

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

    match result {
        Err(e) => {
            let msg = format!("{:?}", e);
            assert!(
                msg.contains("cannot produce values"),
                "Error should explain why recv fails"
            );
        }
        Ok(_) => panic!("Expected error"),
    }
}

#[tokio::test]
async fn test_offer_error_message() {
    let mut handler = RecordingHandler::new(TestRole::Bob);

    let result = handler.offer(&mut (), TestRole::Alice).await;

    match result {
        Err(e) => {
            let msg = format!("{:?}", e);
            assert!(
                msg.contains("cannot produce labels"),
                "Error should explain why offer fails"
            );
        }
        Ok(_) => panic!("Expected error"),
    }
}

// ============================================================================
// Message Type Tracking Tests
// ============================================================================

#[tokio::test]
async fn test_recording_tracks_message_types() {
    let mut handler = RecordingHandler::new(TestRole::Alice);

    handler
        .send(&mut (), TestRole::Bob, &TestMessage { value: 1 })
        .await
        .unwrap();
    handler
        .send(
            &mut (),
            TestRole::Bob,
            &AnotherMessage {
                data: "test".to_string(),
            },
        )
        .await
        .unwrap();

    let events = handler.events();

    // First message type
    match &events[0] {
        RecordedEvent::Send { msg_type, .. } => {
            assert!(msg_type.contains("TestMessage"));
            assert!(!msg_type.contains("AnotherMessage"));
        }
        _ => panic!("Expected Send"),
    }

    // Second message type
    match &events[1] {
        RecordedEvent::Send { msg_type, .. } => {
            assert!(msg_type.contains("AnotherMessage"));
            assert!(!msg_type.contains("TestMessage"));
        }
        _ => panic!("Expected Send"),
    }
}

// ============================================================================
// Multiple Roles Tests
// ============================================================================

#[tokio::test]
async fn test_recording_different_roles() {
    // Create handlers for different roles
    let mut alice = RecordingHandler::new(TestRole::Alice);
    let mut bob = RecordingHandler::new(TestRole::Bob);

    // Alice sends to Bob
    alice
        .send(&mut (), TestRole::Bob, &TestMessage { value: 1 })
        .await
        .unwrap();

    // Bob sends to Charlie
    bob.send(&mut (), TestRole::Charlie, &TestMessage { value: 2 })
        .await
        .unwrap();

    // Each handler records its own events
    let alice_events = alice.events();
    let bob_events = bob.events();

    assert_eq!(alice_events.len(), 1);
    assert_eq!(bob_events.len(), 1);

    match &alice_events[0] {
        RecordedEvent::Send { from, to, .. } => {
            assert_eq!(*from, TestRole::Alice);
            assert_eq!(*to, TestRole::Bob);
        }
        _ => panic!("Expected Send"),
    }

    match &bob_events[0] {
        RecordedEvent::Send { from, to, .. } => {
            assert_eq!(*from, TestRole::Bob);
            assert_eq!(*to, TestRole::Charlie);
        }
        _ => panic!("Expected Send"),
    }
}

// ============================================================================
// Timeout Passthrough Test
// ============================================================================

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

    let mut handler = RecordingHandler::new(TestRole::Alice);

    // with_timeout should just pass through to the body
    let result = handler
        .with_timeout(&mut (), TestRole::Alice, Duration::from_secs(1), async {
            Ok(42)
        })
        .await;

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