telltale-choreography 2.1.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
// Telltale session-typed effect handler
//
// This handler provides a unified abstraction over bidirectional channels
// and dynamically dispatched session objects. Users can keep using the
// legacy SimpleChannel transport or register custom session interpreters
// through the TelltaleSession wrapper.
//
// Key pieces:
// - SimpleChannel: thin wrapper around telltale bidirectional channels.
// - SessionTypeDynamic: async trait (object safe via BoxFuture) that lets any
//   session state expose send/recv/choose/offer operations.
// - TelltaleSession: boxed dynamic session with metadata integration.
// - TelltaleEndpoint: tracks per-peer channels/sessions plus metadata.
// - TelltaleHandler: implements ChoreoHandler over either transport.

use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};
use std::{collections::HashMap, fmt::Debug, marker::PhantomData, time::Duration};

use crate::effects::{ChoreoHandler, ChoreoResult, ChoreographyError, LabelId, RoleId};
use telltale::{Message, Role};

#[path = "telltale_session.rs"]
mod session;
pub use session::{
    SessionMetadata, SessionTypeDynamic, SessionUpdate, SimpleChannel, TelltaleSession,
};

enum ChannelState {
    Simple(SimpleChannel),
    Session(TelltaleSession),
}

struct ChannelRecord {
    state: ChannelState,
    metadata: SessionMetadata,
}

/// Endpoint that manages per-peer channels/sessions plus metadata.
pub struct TelltaleEndpoint<R>
where
    R: Role + Eq + std::hash::Hash + Clone + Debug,
{
    local_role: R,
    channels: HashMap<R, ChannelRecord>,
}

impl<R> TelltaleEndpoint<R>
where
    R: Role + Eq + std::hash::Hash + Clone + Debug,
{
    pub fn new(local_role: R) -> Self {
        Self {
            local_role,
            channels: HashMap::new(),
        }
    }

    /// Register a legacy `SimpleChannel` for a peer.
    pub fn register_channel(&mut self, peer: R, channel: SimpleChannel) {
        tracing::debug!(?peer, "Registering SimpleChannel session");
        self.channels.insert(
            peer,
            ChannelRecord {
                state: ChannelState::Simple(channel),
                metadata: SessionMetadata::default(),
            },
        );
    }

    /// Register a dynamic session for a peer.
    pub fn register_session(&mut self, peer: R, session: TelltaleSession) {
        tracing::debug!(peer = ?peer, session = session.type_name(), "Registering dynamic session");
        self.channels.insert(
            peer,
            ChannelRecord {
                state: ChannelState::Session(session),
                metadata: SessionMetadata::default(),
            },
        );
    }

    fn take_record(&mut self, peer: &R) -> Option<ChannelRecord> {
        self.channels.remove(peer)
    }

    fn put_record(&mut self, peer: R, record: ChannelRecord) {
        self.channels.insert(peer, record);
    }

    pub fn has_channel(&self, peer: &R) -> bool {
        self.channels.contains_key(peer)
    }

    pub fn close_channel(&mut self, peer: &R) -> bool {
        self.channels.remove(peer).is_some()
    }

    pub fn close_all_channels(&mut self) -> usize {
        let count = self.channels.len();
        self.channels.clear();
        count
    }

    pub fn is_all_closed(&self) -> bool {
        self.channels.is_empty()
    }

    pub fn active_channel_count(&self) -> usize {
        self.channels.len()
    }

    pub fn local_role(&self) -> &R {
        &self.local_role
    }

    pub fn get_metadata(&self, peer: &R) -> Option<&SessionMetadata> {
        self.channels.get(peer).map(|record| &record.metadata)
    }

    pub fn all_metadata(&self) -> Vec<(R, &SessionMetadata)> {
        self.channels
            .iter()
            .map(|(peer, record)| (peer.clone(), &record.metadata))
            .collect()
    }
}

impl<R> Drop for TelltaleEndpoint<R>
where
    R: Role + Eq + std::hash::Hash + Clone + Debug,
{
    fn drop(&mut self) {
        let active = self.active_channel_count();
        if active > 0 {
            tracing::warn!(active, "Endpoint dropped with active channels; closing");
            self.close_all_channels();
        }
    }
}

/// Effect handler backed by Telltale sessions.
pub struct TelltaleHandler<R, M> {
    _phantom: PhantomData<(R, M)>,
}

impl<R, M> TelltaleHandler<R, M>
where
    R: Role + Eq + std::hash::Hash + Clone + Debug,
{
    #[must_use]
    pub fn new() -> Self {
        Self {
            _phantom: PhantomData,
        }
    }

    async fn with_channel_operation<T, F, Fut>(
        ep: &mut TelltaleEndpoint<R>,
        peer: &R,
        default_description: &str,
        f: F,
    ) -> ChoreoResult<T>
    where
        F: FnOnce(ChannelState) -> Fut,
        Fut: std::future::Future<Output = ChoreoResult<(T, ChannelState, Option<String>, bool)>>,
    {
        let mut record = ep
            .take_record(peer)
            .ok_or_else(|| ChoreographyError::NoPeerChannel {
                peer: format!("{peer:?}"),
            })?;

        let (result, next_state, description, completed) = f(record.state).await?;
        record.state = next_state;
        record.metadata.operation_count += 1;
        record.metadata.state_description =
            description.unwrap_or_else(|| default_description.to_string());
        if completed {
            record.metadata.is_complete = true;
        }

        ep.put_record(peer.clone(), record);
        Ok(result)
    }
}

impl<R, M> Default for TelltaleHandler<R, M>
where
    R: Role + Eq + std::hash::Hash + Clone + Debug,
{
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl<R, M> ChoreoHandler for TelltaleHandler<R, M>
where
    R: Role<Message = M> + Send + Sync + RoleId + Eq + std::hash::Hash + Clone + Debug + 'static,
    M: Message<Box<dyn std::any::Any + Send>> + Send + Sync + 'static,
{
    type Role = R;
    type Endpoint = TelltaleEndpoint<R>;

    async fn send<Msg: Serialize + Send + Sync>(
        &mut self,
        ep: &mut Self::Endpoint,
        to: Self::Role,
        msg: &Msg,
    ) -> ChoreoResult<()> {
        let serialized =
            bincode::serialize(msg).map_err(|e| ChoreographyError::MessageSerializationFailed {
                operation: "Serialization",
                type_name: std::any::type_name::<Msg>(),
                reason: e.to_string(),
            })?;

        Self::with_channel_operation(ep, &to, "Send", |state| async move {
            match state {
                ChannelState::Simple(mut channel) => {
                    channel.send(serialized).await.map_err(|e| {
                        ChoreographyError::ChannelSendFailed {
                            channel_type: "SimpleChannel",
                            reason: e,
                        }
                    })?;
                    Ok(((), ChannelState::Simple(channel), None, false))
                }
                ChannelState::Session(mut session) => {
                    let update = session.send(serialized).await?;
                    Ok((
                        (),
                        ChannelState::Session(session),
                        update.description,
                        update.is_complete,
                    ))
                }
            }
        })
        .await
    }

    async fn recv<Msg: DeserializeOwned + Send>(
        &mut self,
        ep: &mut Self::Endpoint,
        from: Self::Role,
    ) -> ChoreoResult<Msg> {
        Self::with_channel_operation(ep, &from, "Recv", |state| async move {
            match state {
                ChannelState::Simple(mut channel) => {
                    let serialized =
                        channel
                            .recv()
                            .await
                            .map_err(|_| ChoreographyError::ChannelClosed {
                                channel_type: "SimpleChannel",
                                operation: "receive",
                            })?;
                    let msg = bincode::deserialize(&serialized).map_err(|e| {
                        ChoreographyError::MessageSerializationFailed {
                            operation: "Deserialization",
                            type_name: std::any::type_name::<Msg>(),
                            reason: e.to_string(),
                        }
                    })?;
                    Ok((msg, ChannelState::Simple(channel), None, false))
                }
                ChannelState::Session(mut session) => {
                    let update = session.recv().await?;
                    let msg = bincode::deserialize(&update.output).map_err(|e| {
                        ChoreographyError::MessageSerializationFailed {
                            operation: "Deserialization",
                            type_name: std::any::type_name::<Msg>(),
                            reason: e.to_string(),
                        }
                    })?;
                    Ok((
                        msg,
                        ChannelState::Session(session),
                        update.description,
                        update.is_complete,
                    ))
                }
            }
        })
        .await
    }

    async fn choose(
        &mut self,
        ep: &mut Self::Endpoint,
        who: Self::Role,
        label: <Self::Role as RoleId>::Label,
    ) -> ChoreoResult<()> {
        let label_str = label.as_str().to_string();
        Self::with_channel_operation(ep, &who, "Choose", |state| async move {
            match state {
                ChannelState::Simple(mut channel) => {
                    let serialized = bincode::serialize(&label_str).map_err(|e| {
                        ChoreographyError::LabelSerializationFailed {
                            operation: "serialization",
                            reason: e.to_string(),
                        }
                    })?;
                    channel.send(serialized).await.map_err(|e| {
                        ChoreographyError::ChannelSendFailed {
                            channel_type: "SimpleChannel",
                            reason: e,
                        }
                    })?;
                    Ok(((), ChannelState::Simple(channel), None, false))
                }
                ChannelState::Session(mut session) => {
                    let update = session.choose(&label_str).await?;
                    Ok((
                        (),
                        ChannelState::Session(session),
                        update.description,
                        update.is_complete,
                    ))
                }
            }
        })
        .await
    }

    async fn offer(
        &mut self,
        ep: &mut Self::Endpoint,
        from: Self::Role,
    ) -> ChoreoResult<<Self::Role as RoleId>::Label> {
        Self::with_channel_operation(ep, &from, "Offer", |state| async move {
            match state {
                ChannelState::Simple(mut channel) => {
                    let serialized =
                        channel
                            .recv()
                            .await
                            .map_err(|_| ChoreographyError::ChannelClosed {
                                channel_type: "SimpleChannel",
                                operation: "offer",
                            })?;
                    let label_string: String = bincode::deserialize(&serialized).map_err(|e| {
                        ChoreographyError::LabelSerializationFailed {
                            operation: "deserialization",
                            reason: e.to_string(),
                        }
                    })?;
                    let label = <Self::Role as RoleId>::Label::from_str(&label_string).ok_or_else(
                        || {
                            ChoreographyError::ProtocolViolation(format!(
                                "Unknown label '{label_string}'"
                            ))
                        },
                    )?;
                    Ok((label, ChannelState::Simple(channel), None, false))
                }
                ChannelState::Session(mut session) => {
                    let update = session.offer().await?;
                    let label = <Self::Role as RoleId>::Label::from_str(&update.output)
                        .ok_or_else(|| {
                            ChoreographyError::ProtocolViolation(format!(
                                "Unknown label '{}'",
                                update.output
                            ))
                        })?;
                    Ok((
                        label,
                        ChannelState::Session(session),
                        update.description,
                        update.is_complete,
                    ))
                }
            }
        })
        .await
    }

    async fn with_timeout<F, T>(
        &mut self,
        _ep: &mut Self::Endpoint,
        _at: Self::Role,
        dur: Duration,
        body: F,
    ) -> ChoreoResult<T>
    where
        F: std::future::Future<Output = ChoreoResult<T>> + Send,
    {
        #[cfg(not(target_arch = "wasm32"))]
        {
            match tokio::time::timeout(dur, body).await {
                Ok(result) => result,
                Err(_) => Err(ChoreographyError::Timeout(dur)),
            }
        }

        #[cfg(target_arch = "wasm32")]
        {
            use futures::future::{select, Either};
            use futures::pin_mut;
            use wasm_timer::Delay;

            let timeout = Delay::new(dur);
            pin_mut!(body);
            pin_mut!(timeout);

            match select(body, timeout).await {
                Either::Left((result, _)) => result,
                Either::Right(_) => Err(ChoreographyError::Timeout(dur)),
            }
        }
    }
}