Files
anyhow
async_stream
async_stream_impl
async_trait
base64
byteorder
bytes
cfg_if
either
firestore_grpc
firestore_grpc_cloudrun
fnv
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
getrandom
h2
http
http_body
httparse
hyper
indexmap
iovec
itertools
itoa
lazy_static
libc
log
memchr
mio
net2
openssl_probe
percent_encoding
pin_project
pin_project_internal
pin_project_lite
pin_utils
ppv_lite86
proc_macro2
proc_macro_hack
proc_macro_nested
prost
prost_derive
prost_types
quote
rand
rand_chacha
rand_core
rand_pcg
ring
rustls
rustls_native_certs
ryu
sct
serde
serde_derive
serde_json
slab
spin
syn
time
tokio
future
io
loom
macros
net
park
runtime
sync
task
time
util
tokio_rustls
tokio_util
tonic
tower
tower_balance
tower_buffer
tower_discover
tower_layer
tower_limit
tower_load
tower_load_shed
tower_make
tower_ready_cache
tower_retry
tower_service
tower_timeout
tower_util
tracing
tracing_attributes
tracing_core
tracing_futures
try_lock
unicode_xid
untrusted
want
webpki
  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
// What should it do?
//
// # BDP Algorithm
//
// 1. When receiving a DATA frame, if a BDP ping isn't outstanding:
//   1a. Record current time.
//   1b. Send a BDP ping.
// 2. Increment the number of received bytes.
// 3. When the BDP ping ack is received:
//   3a. Record duration from sent time.
//   3b. Merge RTT with a running average.
//   3c. Calculate bdp as bytes/rtt.
//   3d. If bdp is over 2/3 max, set new max to bdp and update windows.
//
//
// # Implementation
//
// - `hyper::Body::h2` variant includes a "bdp channel"
//   - When the body's `poll_data` yields bytes, call `bdp.sample(bytes.len())`
//

use std::sync::{Arc, Mutex, Weak};
use std::task::{self, Poll};
use std::time::{Duration, Instant};

use h2::{Ping, PingPong};

type WindowSize = u32;

/// Any higher than this likely will be hitting the TCP flow control.
const BDP_LIMIT: usize = 1024 * 1024 * 16;

pub(super) fn disabled() -> Sampler {
    Sampler {
        shared: Weak::new(),
    }
}

pub(super) fn channel(ping_pong: PingPong, initial_window: WindowSize) -> (Sampler, Estimator) {
    let shared = Arc::new(Mutex::new(Shared {
        bytes: 0,
        ping_pong,
        ping_sent: false,
        sent_at: Instant::now(),
    }));

    (
        Sampler {
            shared: Arc::downgrade(&shared),
        },
        Estimator {
            bdp: initial_window,
            max_bandwidth: 0.0,
            shared,
            samples: 0,
            rtt: 0.0,
        },
    )
}

#[derive(Clone)]
pub(crate) struct Sampler {
    shared: Weak<Mutex<Shared>>,
}

pub(super) struct Estimator {
    shared: Arc<Mutex<Shared>>,

    /// Current BDP in bytes
    bdp: u32,
    /// Largest bandwidth we've seen so far.
    max_bandwidth: f64,
    /// Count of samples made (ping sent and received)
    samples: usize,
    /// Round trip time in seconds
    rtt: f64,
}

struct Shared {
    bytes: usize,
    ping_pong: PingPong,
    ping_sent: bool,
    sent_at: Instant,
}

impl Sampler {
    pub(crate) fn sample(&self, bytes: usize) {
        let shared = if let Some(shared) = self.shared.upgrade() {
            shared
        } else {
            return;
        };

        let mut inner = shared.lock().unwrap();

        if !inner.ping_sent {
            if let Ok(()) = inner.ping_pong.send_ping(Ping::opaque()) {
                inner.ping_sent = true;
                inner.sent_at = Instant::now();
                trace!("sending BDP ping");
            } else {
                return;
            }
        }

        inner.bytes += bytes;
    }
}

impl Estimator {
    pub(super) fn poll_estimate(&mut self, cx: &mut task::Context<'_>) -> Poll<WindowSize> {
        let mut inner = self.shared.lock().unwrap();
        if !inner.ping_sent {
            // XXX: this doesn't register a waker...?
            return Poll::Pending;
        }

        let (bytes, rtt) = match ready!(inner.ping_pong.poll_pong(cx)) {
            Ok(_pong) => {
                let rtt = inner.sent_at.elapsed();
                let bytes = inner.bytes;
                inner.bytes = 0;
                inner.ping_sent = false;
                self.samples += 1;
                trace!("received BDP ack; bytes = {}, rtt = {:?}", bytes, rtt);
                (bytes, rtt)
            }
            Err(e) => {
                debug!("bdp pong error: {}", e);
                return Poll::Pending;
            }
        };

        drop(inner);

        if let Some(bdp) = self.calculate(bytes, rtt) {
            Poll::Ready(bdp)
        } else {
            // XXX: this doesn't register a waker...?
            Poll::Pending
        }
    }

    fn calculate(&mut self, bytes: usize, rtt: Duration) -> Option<WindowSize> {
        // No need to do any math if we're at the limit.
        if self.bdp as usize == BDP_LIMIT {
            return None;
        }

        // average the rtt
        let rtt = seconds(rtt);
        if self.samples < 10 {
            // Average the first 10 samples
            self.rtt += (rtt - self.rtt) / (self.samples as f64);
        } else {
            self.rtt += (rtt - self.rtt) / 0.9;
        }

        // calculate the current bandwidth
        let bw = (bytes as f64) / (self.rtt * 1.5);
        trace!("current bandwidth = {:.1}B/s", bw);

        if bw < self.max_bandwidth {
            // not a faster bandwidth, so don't update
            return None;
        } else {
            self.max_bandwidth = bw;
        }

        // if the current `bytes` sample is at least 2/3 the previous
        // bdp, increase to double the current sample.
        if (bytes as f64) >= (self.bdp as f64) * 0.66 {
            self.bdp = (bytes * 2).min(BDP_LIMIT) as WindowSize;
            trace!("BDP increased to {}", self.bdp);
            Some(self.bdp)
        } else {
            None
        }
    }
}

fn seconds(dur: Duration) -> f64 {
    const NANOS_PER_SEC: f64 = 1_000_000_000.0;
    let secs = dur.as_secs() as f64;
    secs + (dur.subsec_nanos() as f64) / NANOS_PER_SEC
}