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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Networking utilities.
use bytes::Bytes;
use futures::{Sink, Stream};
use indexmap::IndexMap;
use pin_project::pin_project;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::future::Future;
use std::hash::Hash;
use std::io::{Error, IoSlice};
use std::ops::{AddAssign, DivAssign};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use std::{io, mem};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

/// [AsyncWriter](`AsyncWrite`) that tracks the number of bytes written.
#[pin_project]
pub struct TrackingWriter<AsyncWriter> {
    #[pin]
    writer: AsyncWriter,
    bytes_written: Counter,
}

/// [AsyncReader](`AsyncRead`) that tracks the number of bytes read.
#[pin_project]
pub struct TrackingReader<AsyncReader> {
    #[pin]
    reader: AsyncReader,
    bytes_read: Counter,
}

/// Combined asynchronous reader and writer that tracks bytes received and sent.
#[pin_project]
pub struct TrackingReadWrite<AsyncReader, AsyncWriter> {
    #[pin]
    reader: TrackingReader<AsyncReader>,
    #[pin]
    writer: TrackingWriter<AsyncWriter>,
}

#[derive(Clone, Default, Debug)]
/// A counter that tracks communication in bytes sent or received. Can be used with the
/// [`Statistics`] struct to track communication in different phases.
pub struct Counter(Arc<AtomicUsize>);

/// A utility struct which is used to track communication on a **best-effort basis**.
///
/// When created, it is initialized with the [`Counter`]s of the main channel.
/// Optionally, a counter pair for a helper channel can be set.
///
/// # Serialization
/// The `Statistics` struct can be serialized into a serializable form via the [`Statistics::into_run_result`]
/// method. The result can be serialized into a variety of formats via
/// [serde](https://serde.rs/#data-formats) (Note: `.csv` output is currently not supported, `json`
/// is recommended).
///
/// Example json output:
/// ```json
///{
///   "meta": {
///     "custom": {
///       "circuit": "sha256.rs"
///     }
///   },
///   "communication": {
///     "Unaccounted": {
///       "sent": 58,
///       "rcvd": 120
///     },
///     "FunctionDependentSetup": {
///       "sent": 75,
///       "rcvd": 13
///     },
///     "Online": {
///       "sent": 36776,
///       "rcvd": 36776
///     }
///   },
///   "time": {
///     "Unaccounted": 0,
///     "FunctionDependentSetup": 0,
///     "Online": 291
///   }
/// }
/// ```
///
/// # Caveat
/// As the actual sending of values transmitted via channels is done in an asynchronous background
/// task, `Statistics` can only record the communication on a best-effort basis. It is possible
/// for values that are sent to a channel within a [`Statistics::record`] call to not be
/// tracked as the specified [`Phase`], but rather as `Unaccounted`. If the amount of
/// unaccounted communication is higher than desired, adding a [`tokio::time::sleep`] at the end
/// of the `record` call might reduce it.
#[derive(Default)]
pub struct Statistics {
    main: CounterPair,
    helper: Option<CounterPair>,
    // IndexMap so that iteration order is not random
    recorded: Mutex<IndexMap<Phase, (CountPair, Duration)>>,
    prev_phase: Option<Phase>,
    // record unaccounted communication as the last phase
    unaccounted_as_previous: bool,
    // sleep duration after every `record`. Can reduce unaccounted comm
    sleep_after_phase: Duration,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct RunResult {
    #[serde(skip_deserializing)]
    pub meta: Metadata,
    pub communication_bytes: IndexMap<Phase, CountPair>,
    pub time_ms: IndexMap<Phase, u128>,
}

trait SerializableMetadata: erased_serde::Serialize + Debug + Send {}
impl<T: ?Sized + erased_serde::Serialize + Debug + Send> SerializableMetadata for T {}

erased_serde::serialize_trait_object!(SerializableMetadata);

#[derive(Debug, Default, Serialize)]
pub struct Metadata {
    data: IndexMap<String, Box<dyn SerializableMetadata>>,
}

#[derive(Debug, Clone, Eq, Hash, PartialEq, Serialize, Deserialize)]
/// Categories for recorded communication. The `Custom` variant can be used to label the
/// communication with a user chosen string.
pub enum Phase {
    FunctionIndependentSetup,
    FunctionDependentSetup,
    Ots,
    Mts,
    Online,
    Unaccounted,
    Custom(String),
}

#[derive(Default, Debug, Clone)]
struct CounterPair {
    send: Counter,
    recv: Counter,
}

#[derive(Default, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct CountPair {
    pub sent: usize,
    pub rcvd: usize,
}

impl<AsyncWriter> TrackingWriter<AsyncWriter> {
    pub fn new(writer: AsyncWriter) -> Self {
        Self {
            writer,
            bytes_written: Counter::default(),
        }
    }

    #[inline]
    pub fn bytes_written(&self) -> Counter {
        self.bytes_written.clone()
    }

    pub fn reset(&mut self) {
        self.bytes_written.reset();
    }
}

impl<AsyncReader> TrackingReader<AsyncReader> {
    pub fn new(reader: AsyncReader) -> Self {
        Self {
            reader,
            bytes_read: Counter::default(),
        }
    }

    #[inline]
    pub fn bytes_read(&self) -> Counter {
        self.bytes_read.clone()
    }

    pub fn reset(&mut self) {
        self.bytes_read.reset();
    }
}

impl<AR, AW> TrackingReadWrite<AR, AW> {
    pub fn new(reader: AR, writer: AW) -> Self {
        Self {
            reader: TrackingReader::new(reader),
            writer: TrackingWriter::new(writer),
        }
    }

    #[inline]
    pub fn bytes_read(&self) -> Counter {
        self.reader.bytes_read()
    }

    #[inline]
    pub fn bytes_written(&self) -> Counter {
        self.writer.bytes_written()
    }

    pub fn reset(&mut self) {
        self.reader.reset();
        self.writer.reset();
    }
}

impl<AW: AsyncWrite> AsyncWrite for TrackingWriter<AW> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, Error>> {
        let this = self.project();
        let poll = this.writer.poll_write(cx, buf);
        if let Poll::Ready(Ok(bytes_written)) = &poll {
            *this.bytes_written += *bytes_written;
        }
        poll
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
        let this = self.project();
        this.writer.poll_flush(cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
        let this = self.project();
        this.writer.poll_shutdown(cx)
    }

    fn poll_write_vectored(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<Result<usize, Error>> {
        let this = self.project();
        let poll = this.writer.poll_write_vectored(cx, bufs);
        if let Poll::Ready(Ok(bytes_written)) = &poll {
            *this.bytes_written += *bytes_written;
        }
        poll
    }

    fn is_write_vectored(&self) -> bool {
        self.writer.is_write_vectored()
    }
}

impl<AR: AsyncRead> AsyncRead for TrackingReader<AR> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let bytes_before = buf.filled().len();
        let this = self.project();
        let poll = this.reader.poll_read(cx, buf);
        *this.bytes_read += buf.filled().len() - bytes_before;
        poll
    }
}

impl<S: Sink<Bytes>> Sink<Bytes> for TrackingWriter<S> {
    type Error = S::Error;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();
        this.writer.poll_ready(cx)
    }

    fn start_send(self: Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> {
        // The size_of<u32> adds the size of the length tag which we'd use when actually
        // using a framed transport
        let this = self.project();
        *this.bytes_written += item.len() + mem::size_of::<u32>();
        this.writer.start_send(item)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();
        this.writer.poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.project();
        this.writer.poll_close(cx)
    }
}

impl<S: Stream<Item = Bytes>> Stream for TrackingReader<S> {
    type Item = Bytes;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.project();
        let poll = this.reader.poll_next(cx);
        if let Poll::Ready(Some(bytes)) = &poll {
            // The size_of<u32> adds the size of the length tag which we'd use when actually
            // using a framed transport
            *this.bytes_read += bytes.len() + mem::size_of::<u32>();
        }
        poll
    }
}

impl<AR, AW: AsyncWrite> AsyncWrite for TrackingReadWrite<AR, AW> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, Error>> {
        let this = self.project();
        this.writer.poll_write(cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
        let this = self.project();
        this.writer.poll_flush(cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
        let this = self.project();
        this.writer.poll_shutdown(cx)
    }

    fn poll_write_vectored(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<Result<usize, Error>> {
        let this = self.project();
        this.writer.poll_write_vectored(cx, bufs)
    }

    fn is_write_vectored(&self) -> bool {
        self.writer.is_write_vectored()
    }
}

impl<AR: AsyncRead, AW> AsyncRead for TrackingReadWrite<AR, AW> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let this = self.project();
        this.reader.poll_read(cx, buf)
    }
}

impl Counter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn get(&self) -> usize {
        self.0.load(Ordering::SeqCst)
    }

    pub fn reset(&self) -> usize {
        self.0.swap(0, Ordering::SeqCst)
    }
}

impl AddAssign<usize> for Counter {
    fn add_assign(&mut self, rhs: usize) {
        self.0.fetch_add(rhs, Ordering::SeqCst);
    }
}

impl Statistics {
    /// Create a new [`Statistics`] with the counters for the main channel.
    pub fn new(send_counter: Counter, recv_counter: Counter) -> Self {
        Self {
            main: CounterPair {
                send: send_counter,
                recv: recv_counter,
            },
            ..Default::default()
        }
    }

    /// Add the helper counters. This might be used to track the communication with a trusted third
    /// party.
    pub fn with_helper(
        mut self,
        helper_send_counter: Counter,
        helper_recv_counter: Counter,
    ) -> Self {
        self.set_helper(helper_send_counter, helper_recv_counter);
        self
    }

    /// Add a sleep duration at the end of a `record` or `record_helper` call to reduce
    /// unaccounted communication. This time is not part of the tracked statistics.
    pub fn with_sleep(mut self, sleep: Duration) -> Self {
        self.sleep_after_phase = sleep;
        self
    }

    /// If `record_as_prev` is set to true (default is false), at the beginning of each phase,
    /// every unaccounted communication is recorded as the previous phase. If communication
    /// occurs before the first phase, it is still recorded as unaccounted.
    pub fn without_unaccounted(mut self, record_as_prev: bool) -> Self {
        self.unaccounted_as_previous = record_as_prev;
        self
    }

    /// Set the helper counters. This might be used to track the communication with a trusted third
    /// party.
    pub fn set_helper(&mut self, helper_send_counter: Counter, helper_recv_counter: Counter) {
        self.helper = Some(CounterPair {
            send: helper_send_counter,
            recv: helper_recv_counter,
        });
    }

    /// Set the sleep duration at the end of a `record` or `record_helper` call to reduce
    /// unaccounted communication. This time is not part of the tracked statistics.
    pub fn set_sleep(&mut self, sleep: Duration) {
        self.sleep_after_phase = sleep;
    }

    pub fn set_without_unaccounted(&mut self, record_as_prev: bool) {
        self.unaccounted_as_previous = record_as_prev;
    }

    /// Record the main channel communication that happens within the future `f` on a
    /// best-effort basis.
    pub async fn record<F, R>(&mut self, comm: Phase, f: F) -> R
    where
        F: Future<Output = R>,
    {
        self.record_for(self.main.clone(), comm, f).await
    }

    /// Record the helper channel communication that happens within the future `f` on a
    /// best-effort basis.
    pub async fn record_helper<F, R>(&mut self, phase: Phase, f: F) -> R
    where
        F: Future<Output = R>,
    {
        let helper = self
            .helper
            .clone()
            .expect("Helper counter must be set to record helper communication");
        self.record_for(helper, phase, f).await
    }

    async fn record_for<F, R>(&mut self, cnt_pair: CounterPair, phase: Phase, f: F) -> R
    where
        F: Future<Output = R>,
    {
        self.record_unaccounted();
        let now = Instant::now();
        let ret = f.await;
        let elapsed = now.elapsed();
        tokio::time::sleep(self.sleep_after_phase).await;
        let comm = cnt_pair.reset();
        let mut recorded = self.recorded.lock().unwrap();
        let entry = recorded.entry(phase).or_default();
        entry.0 += comm;
        entry.1 += elapsed;

        ret
    }

    fn record_unaccounted(&self) {
        let mut unaccounted = self.main.reset();
        if let Some(helper) = &self.helper {
            unaccounted += helper.reset();
        }
        let mut recorded = self.recorded.lock().unwrap();
        let phase = match (self.unaccounted_as_previous, &self.prev_phase) {
            (true, Some(phase)) => phase.clone(),
            _ => Phase::Unaccounted,
        };
        let phase_entry = recorded.entry(phase).or_default();
        phase_entry.0 += unaccounted;
    }

    /// Get the statistics for a phase.
    pub fn get(self, phase: &Phase) -> Option<(CountPair, Duration)> {
        self.record_unaccounted();
        self.recorded.lock().unwrap().get(phase).copied()
    }

    /// Convert into a [`RunResult`] which can be serialized via [serde](serde.rs/).
    pub fn into_run_result(self) -> RunResult {
        self.record_unaccounted();
        let recorded = self.recorded.into_inner().unwrap();
        let (communication, time) = recorded
            .into_iter()
            .map(|(phase, (comm, time))| ((phase.clone(), comm), (phase, time.as_millis())))
            .unzip();
        RunResult {
            meta: Default::default(),
            communication_bytes: communication,
            time_ms: time,
        }
    }
}

impl RunResult {
    /// Add any metadata to the `{ "meta": { "custom": { .. }, .. } }` map inside the result.
    /// The value can be of any type that implements [`Serialize`], [`Debug`] and is `'static'.
    ///
    /// ## Example
    /// ```
    ///# use seec_channel::util::Statistics;
    /// let statistics = Statistics::default();
    /// let mut run_res = statistics.into_run_result();
    /// run_res.add_metadata("Description", "Lorem Ipsum");
    /// run_res.add_metadata("other-data", vec![1, 2, 3]);
    /// ```
    pub fn add_metadata<V: Serialize + Debug + Send + 'static>(&mut self, key: &str, value: V) {
        self.meta.data.insert(key.to_string(), Box::new(value));
    }

    pub fn total_bytes_sent(&self) -> usize {
        self.communication_bytes.values().map(|val| val.sent).sum()
    }

    pub fn total_bytes_recv(&self) -> usize {
        self.communication_bytes.values().map(|val| val.rcvd).sum()
    }

    pub fn setup_ms(&self) -> u128 {
        let phases = [
            Phase::Ots,
            Phase::Mts,
            Phase::FunctionIndependentSetup,
            Phase::FunctionDependentSetup,
        ];
        phases
            .into_iter()
            .map(|phase| self.time_ms.get(&phase).copied().unwrap_or_default())
            .sum()
    }

    pub fn online_ms(&self) -> u128 {
        self.time_ms
            .get(&Phase::Online)
            .copied()
            .unwrap_or_default()
    }

    /// Calculate mean, loses metadata information.
    pub fn mean(data: &[Self]) -> Self {
        let mut res = Self::default();
        for val in data {
            for (k, v) in &val.communication_bytes {
                *res.communication_bytes.entry(k.clone()).or_default() += *v;
            }
            for (k, v) in &val.time_ms {
                *res.time_ms.entry(k.clone()).or_default() += *v;
            }
        }
        for comm in res.communication_bytes.values_mut() {
            *comm /= data.len();
        }
        for time in res.time_ms.values_mut() {
            *time /= data.len() as u128;
        }
        res
    }
}

impl Clone for RunResult {
    fn clone(&self) -> Self {
        let meta = self
            .meta
            .data
            .iter()
            .map(|(k, v)| {
                let json = serde_json::to_string(v)?;
                let json_val: serde_json::Value = serde_json::from_str(&json)?;
                Ok((
                    k.clone(),
                    Box::new(json_val) as Box<dyn SerializableMetadata>,
                ))
            })
            .collect::<Result<IndexMap<_, _>, serde_json::Error>>()
            .unwrap_or_default();
        Self {
            meta: Metadata { data: meta },
            communication_bytes: self.communication_bytes.clone(),
            time_ms: self.time_ms.clone(),
        }
    }
}

impl CounterPair {
    fn reset(&self) -> CountPair {
        CountPair {
            sent: self.send.reset(),
            rcvd: self.recv.reset(),
        }
    }
}

impl AddAssign for CountPair {
    fn add_assign(&mut self, rhs: Self) {
        self.sent += rhs.sent;
        self.rcvd += rhs.rcvd;
    }
}

impl DivAssign<usize> for CountPair {
    fn div_assign(&mut self, rhs: usize) {
        self.sent /= rhs;
        self.rcvd /= rhs;
    }
}

#[cfg(test)]
pub(crate) fn init_tracing() -> tracing::dispatcher::DefaultGuard {
    use tracing_subscriber::fmt::format::FmtSpan;
    use tracing_subscriber::util::SubscriberInitExt;
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_test_writer()
        .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
        .set_default()
}