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
use crate::debug::{DataContent, Event, EventKind, TransmissionDebug, TransmissionDetails};
use crate::transmission::Input;
use async_std::channel::{Sender, TrySendError};
use async_std::sync::Mutex as AsyncMutex;
use async_trait::async_trait;
use core::sync::atomic::{AtomicUsize, Ordering};
use futures::stream::{FuturesUnordered, StreamExt};
use melodium_common::descriptor::Flow;
use melodium_common::executive::{
Output as ExecutiveOutput, SendResult, TrackId, TransmissionError, TransmissionValue, Value,
};
use std::sync::{Arc, Mutex};
const LIMIT: usize = 2usize.pow(20);
#[derive(Debug)]
pub struct Output {
senders: Mutex<Arc<Vec<(Sender<TransmissionValue>, Option<TransmissionDetails>)>>>,
count_receivers: AtomicUsize,
buffer: AsyncMutex<Option<TransmissionValue>>,
flow: Flow,
track_id: TrackId,
debug: TransmissionDebug,
}
impl Output {
pub fn new(flow: Flow, track_id: TrackId, debug: TransmissionDebug) -> Self {
Self {
senders: Mutex::new(Arc::new(Vec::new())),
count_receivers: AtomicUsize::new(0),
buffer: AsyncMutex::new(None),
flow,
track_id,
debug,
}
}
pub fn flow(&self) -> &Flow {
&self.flow
}
pub fn track_id(&self) -> &TrackId {
&self.track_id
}
pub fn transmission_debug(&self) -> &TransmissionDebug {
&self.debug
}
pub fn add_transmission(&self, inputs: &Vec<Input>) {
let mut senders = self.senders.lock().unwrap();
let count = inputs.len();
// An output is not supposed to have transmission added while it is already in use,
// so get_mut on Arc is doable.
if let Some(senders) = Arc::get_mut(&mut senders) {
for input in inputs {
senders.push((
input.sender().clone(),
match input.transmission_debug() {
TransmissionDebug::None => None,
TransmissionDebug::Basic(_, details)
| TransmissionDebug::Detailed(_, details) => Some(details.clone()),
},
));
}
self.count_receivers.fetch_add(count, Ordering::Relaxed);
}
}
async fn check_send(&self, force: bool) -> SendResult {
let buffer_len = self
.buffer
.lock()
.await
.as_ref()
.map(|buf| buf.len())
.unwrap_or(0);
if buffer_len > 0 {
// We can unwrap the `take` because buffer_len must be > 0, so buffer have value.
let data = self.buffer.lock().await.take().unwrap();
if self.flow == Flow::Block || buffer_len >= LIMIT || force {
match self.count_receivers.load(Ordering::Relaxed) {
0 => Err(TransmissionError::NoReceiver),
1 => {
let senders = Arc::clone(&self.senders.lock().unwrap());
if let Some((sender, input_transmission_details)) = senders.first() {
match sender.send(data).await {
Ok(_) => {
match (&self.debug, input_transmission_details) {
(_, None) | (TransmissionDebug::None, _) => {}
(
TransmissionDebug::Basic(world, output_details),
Some(input_details),
)
| (
TransmissionDebug::Detailed(world, output_details),
Some(input_details),
) => {
world
.send_debug_async(Event::new(
EventKind::DataTransmitted {
output: output_details.clone(),
input: input_details.clone(),
track_id: self.track_id.clone(),
data: DataContent::Count {
count: buffer_len,
},
},
))
.await
}
}
Ok(())
}
Err(_) => Err(TransmissionError::EverythingClosed),
}
} else {
Err(TransmissionError::NoReceiver)
}
}
_ => {
let senders = Arc::clone(&self.senders.lock().unwrap());
let transmissions = FuturesUnordered::new();
for (sender, input_transmission_details) in senders.iter() {
let transmission = {
let data = &data;
async move {
match sender.send(data.clone()).await {
Ok(_) => {
match (&self.debug, input_transmission_details) {
(_, None) | (TransmissionDebug::None, _) => {}
(
TransmissionDebug::Basic(world, output_details),
Some(input_details),
)
| (
TransmissionDebug::Detailed(
world,
output_details,
),
Some(input_details),
) => {
world
.send_debug_async(Event::new(
EventKind::DataTransmitted {
output: output_details.clone(),
input: input_details.clone(),
track_id: self.track_id.clone(),
data: DataContent::Count {
count: buffer_len,
},
},
))
.await
}
}
true
}
Err(_) => false,
}
}
};
transmissions.push(transmission);
}
let statuses: Vec<_> = transmissions.collect().await;
if let Some(_) = statuses.iter().find(|s| **s) {
Ok(())
} else {
Err(TransmissionError::EverythingClosed)
}
}
}
} else {
match self.count_receivers.load(Ordering::Relaxed) {
0 => Err(TransmissionError::NoReceiver),
1 => {
let senders = Arc::clone(&self.senders.lock().unwrap());
if let Some((sender, input_transmission_details)) = senders.first() {
match sender.try_send(data) {
Ok(_) => {
match (&self.debug, input_transmission_details) {
(_, None) | (TransmissionDebug::None, _) => {}
(
TransmissionDebug::Basic(world, output_details),
Some(input_details),
)
| (
TransmissionDebug::Detailed(world, output_details),
Some(input_details),
) => {
world
.send_debug_async(Event::new(
EventKind::DataTransmitted {
output: output_details.clone(),
input: input_details.clone(),
track_id: self.track_id.clone(),
data: DataContent::Count {
count: buffer_len,
},
},
))
.await
}
}
Ok(())
}
Err(TrySendError::Full(data)) => {
self.buffer.lock().await.replace(data);
Ok(())
}
Err(TrySendError::Closed(_)) => {
Err(TransmissionError::EverythingClosed)
}
}
} else {
Err(TransmissionError::NoReceiver)
}
}
_ => {
let senders = Arc::clone(&self.senders.lock().unwrap());
let all_senders_not_full =
!senders.iter().any(|(sender, _)| sender.is_full());
if all_senders_not_full {
let transmissions = FuturesUnordered::new();
for (sender, input_transmission_details) in senders.iter() {
let transmission = {
let data = &data;
async move {
match sender.try_send(data.clone()) {
Ok(_) => {
match (&self.debug, input_transmission_details) {
(_, None) | (TransmissionDebug::None, _) => {}
(
TransmissionDebug::Basic(
world,
output_details,
),
Some(input_details),
)
| (
TransmissionDebug::Detailed(
world,
output_details,
),
Some(input_details),
) => {
world
.send_debug_async(Event::new(
EventKind::DataTransmitted {
output: output_details.clone(),
input: input_details.clone(),
track_id: self.track_id.clone(),
data: DataContent::Count {
count: buffer_len,
},
},
))
.await
}
}
true
}
Err(TrySendError::Full(_)) => unreachable!(),
Err(TrySendError::Closed(_)) => false,
}
}
};
transmissions.push(transmission);
}
let statuses: Vec<_> = transmissions.collect().await;
if let Some(_) = statuses.iter().find(|s| **s) {
Ok(())
} else {
Err(TransmissionError::EverythingClosed)
}
} else {
self.buffer.lock().await.replace(data);
Ok(())
}
}
}
}
} else {
Ok(())
}
}
}
#[async_trait]
impl ExecutiveOutput for Output {
async fn close(&self) {
let _ = self.check_send(true).await;
self.senders.lock().unwrap().iter().for_each(|(s, _)| {
s.close();
});
match &self.debug {
TransmissionDebug::None => {}
TransmissionDebug::Basic(world, transmission_details)
| TransmissionDebug::Detailed(world, transmission_details) => {
world
.send_debug_async(Event::new(EventKind::OutputClosed {
output: transmission_details.clone(),
track_id: self.track_id.clone(),
}))
.await
}
}
}
async fn send_many(&self, data: TransmissionValue) -> SendResult {
match &self.debug {
TransmissionDebug::None => {}
TransmissionDebug::Basic(world, transmission_details) => {
world
.send_debug_async(Event::new(EventKind::DataSent {
output: transmission_details.clone(),
track_id: self.track_id.clone(),
data: DataContent::Count { count: data.len() },
}))
.await
}
TransmissionDebug::Detailed(world, transmission_details) => {
world
.send_debug_async(Event::new(EventKind::DataSent {
output: transmission_details.clone(),
track_id: self.track_id.clone(),
data: DataContent::Values {
values: data.clone().into(),
},
}))
.await
}
}
{
let mut lock = self.buffer.lock().await;
if let Some(buf) = lock.as_mut() {
buf.append(data);
} else {
*lock = Some(data);
}
}
self.check_send(false).await
}
async fn send_one(&self, data: Value) -> SendResult {
match &self.debug {
TransmissionDebug::None => {}
TransmissionDebug::Basic(world, transmission_details) => {
world
.send_debug_async(Event::new(EventKind::DataSent {
output: transmission_details.clone(),
track_id: self.track_id.clone(),
data: DataContent::Count { count: 1 },
}))
.await
}
TransmissionDebug::Detailed(world, transmission_details) => {
world
.send_debug_async(Event::new(EventKind::DataSent {
output: transmission_details.clone(),
track_id: self.track_id.clone(),
data: DataContent::Values {
values: vec![data.clone()],
},
}))
.await
}
}
{
let mut lock = self.buffer.lock().await;
if let Some(buf) = lock.as_mut() {
buf.push(data);
} else {
*lock = Some(TransmissionValue::new(data));
}
}
self.check_send(false).await
}
async fn force_send(&self) {
let _ = self.check_send(true).await;
}
}
impl From<Input> for Output {
fn from(value: Input) -> Self {
let o = Output::new(*value.flow(), *value.track_id(), TransmissionDebug::None);
o.add_transmission(&vec![value]);
o
}
}