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
use std::fmt::Debug;
use std::iter;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::future::ready;
use futures::sink::Sink;
use futures::stream::{FusedStream, StreamExt};
use tokio::sync::broadcast;
use crate::async_runtime::{self, watcher::StderrWatcher, AsyncProtocol};
use crate::{Msg, StateMachine};
pub struct AsyncSimulation<SM: StateMachine> {
tx: broadcast::Sender<Msg<SM::MessageBody>>,
parties: Vec<
Option<
AsyncProtocol<SM, Incoming<SM::MessageBody>, Outcoming<SM::MessageBody>, StderrWatcher>,
>,
>,
exhausted: bool,
}
impl<SM> AsyncSimulation<SM>
where
SM: StateMachine + Send + 'static,
SM::MessageBody: Send + Clone + Unpin + 'static,
SM::Err: Send + Debug,
SM::Output: Send,
{
pub fn new() -> Self {
let (tx, _) = broadcast::channel(20);
Self {
tx,
parties: vec![],
exhausted: false,
}
}
pub fn add_party(&mut self, party: SM) -> &mut Self {
let rx = self.tx.subscribe();
let incoming = incoming(rx, party.party_ind());
let outcoming = Outcoming {
sender: self.tx.clone(),
};
let party = AsyncProtocol::new(party, incoming, outcoming).set_watcher(StderrWatcher);
self.parties.push(Some(party));
self
}
pub async fn run(&mut self) -> Vec<Result<SM::Output, AsyncSimulationError<SM>>> {
if self.exhausted {
return iter::repeat_with(|| Err(AsyncSimulationError::SimulationExhausted))
.take(self.parties.len())
.collect();
}
self.exhausted = true;
let mut parties = vec![];
for party in self.parties.drain(..) {
let mut party = party.expect("guaranteed as simulation is not exhausted");
let h = tokio::spawn(async { (party.run().await, party) });
parties.push(h)
}
let mut results = vec![];
for party in parties {
let (r, party) = match party.await {
Ok((Ok(output), party)) => (Ok(output), Some(party)),
Ok((Err(err), party)) => (
Err(AsyncSimulationError::ProtocolExecution(err)),
Some(party),
),
Err(err) => (
Err(AsyncSimulationError::ProtocolExecutionPanicked(err)),
None,
),
};
self.parties.push(party);
results.push(r);
}
results
}
}
type Incoming<M> =
Pin<Box<dyn FusedStream<Item = Result<Msg<M>, broadcast::error::RecvError>> + Send>>;
fn incoming<M: Clone + Send + Unpin + 'static>(
mut rx: broadcast::Receiver<Msg<M>>,
me: u16,
) -> Incoming<M> {
let stream = async_stream::stream! {
loop {
let item = rx.recv().await;
yield item
}
};
let stream = StreamExt::filter(stream, move |m| {
ready(match m {
Ok(m) => m.sender != me && (m.receiver.is_none() || m.receiver == Some(me)),
Err(_) => true,
})
});
Box::pin(stream)
}
struct Outcoming<M> {
sender: broadcast::Sender<Msg<M>>,
}
impl<M> Sink<Msg<M>> for Outcoming<M> {
type Error = broadcast::error::SendError<Msg<M>>;
fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: Msg<M>) -> Result<(), Self::Error> {
self.sender.send(item).map(|_| ())
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
#[non_exhaustive]
#[derive(Debug)]
pub enum AsyncSimulationError<SM: StateMachine> {
ProtocolExecution(
async_runtime::Error<
SM::Err,
broadcast::error::RecvError,
broadcast::error::SendError<Msg<SM::MessageBody>>,
>,
),
ProtocolExecutionPanicked(tokio::task::JoinError),
SimulationExhausted,
}