Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ client against coturn.

| | |
|---|---|
| `new Server(opts?)` | `unreliableLimit` (bytes, 0 = off), `reliableLimit` (bytes queued per peer before it's kicked, default 4 MiB, 0 = off), `overloadMs` (default 1000, 0 = off), `channelPriority` (`{ label: weight }`), `rack`, `pacer`, `rtoMin` (ms, default 1000), `bindAddress` (default `'0.0.0.0'`, `'::'` = dual-stack), `port` (default 0 = any), `pacerStartRate` (B/s, 65536), `pacerMinRate` (B/s, 8192), `pacerBurstMs` (100), `egressRate` (B/s, server-wide cap, off) |
| `new Server(opts?)` | `unreliableLimit` (bytes, 0 = off; unreliable is also dropped while SCTP has > 2400 B unsent), `reliableLimit` (bytes queued per peer before it's kicked, default 4 MiB, 0 = off), `overloadMs` (default 1000, 0 = off), `channelPriority` (`{ label: weight }`), `rack`, `pacer`, `rtoMin` (ms, default 1000), `bindAddress` (default `'0.0.0.0'`, `'::'` = dual-stack), `port` (default 0 = any), `pacerStartRate` (B/s, 65536), `pacerMinRate` (B/s, 8192), `pacerBurstMs` (100), `egressRate` (B/s, server-wide cap, off) |
| `localPort` | the UDP port all peers share |
| `accept(offer, advertiseIp, advertisePort = 0)` | async. `offer` is `{ type, sdp }` or its JSON; `advertiseIp` is one IP or an array (one host candidate each, IPv4 and/or IPv6). → `Promise<{ peer, answer, localPort }>`. `advertisePort` 0 = `localPort` |
| `send(peer, label, data, { exempt }?)` | `data` is a string (sent as a WebRTC string) or bytes. → `boolean`. `false` = unreliable dropped (gate, budget or egress cap), or reliable hit `reliableLimit` (peer closed, reason `reliable-overflow`). Throws if the peer is gone, the channel isn't open or `data` exceeds the max message size |
Expand Down
3 changes: 3 additions & 0 deletions src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,9 @@ impl Loop {
}
p.shared.stack_outstanding.store(out, Ordering::Release);
flush_writes(&self.sock, self.v6, id, &mut p.pc);
if let Some(ts) = p.pc.sctp_transport_stats() {
p.shared.stack_unsent.store(ts.pending_bytes, Ordering::Release);
}

let d = p.pc.poll_timeout();
if d != p.deadline {
Expand Down
11 changes: 10 additions & 1 deletion src/gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,21 @@ fn reserve(s: &PeerShared, len: usize, fits: impl Fn(usize) -> bool) -> bool {
.is_ok()
}

/// Unsent bytes SCTP may hold (cwnd full) before unreliable sends are dropped. More
/// unreliable would only wait for cwnd, ahead of the reliable data queued behind it.
pub(crate) const UNSENT_LIMIT: usize = 2400;

/// Decide whether a send goes. On `Queued` the caller must hand the message to the
/// worker, which releases `len` from `pending_cmd` once SCTP has it.
pub(crate) fn admit(s: &PeerShared, lim: Limits, unreliable: bool, exempt: bool, len: usize) -> Verdict {
let out = s.stack_outstanding.load(Acquire);
if unreliable && !exempt {
if !reserve(s, len, |p| lim.unreliable == 0 || out + p + len <= lim.unreliable) {
let unsent = s.stack_unsent.load(Acquire);
let fits = |p: usize| {
lim.unreliable == 0
|| (out + p + len <= lim.unreliable && unsent + p + len <= UNSENT_LIMIT.max(len))
};
if !reserve(s, len, fits) {
s.budget_limited.store(true, Relaxed);
s.dropped.fetch_add(1, Relaxed);
return Verdict::Dropped;
Expand Down
6 changes: 5 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub(crate) type Registry = Arc<Mutex<HashMap<u32, Arc<PeerShared>>>>;
pub(crate) struct PeerShared {
/// bytes SCTP has not released yet (sum of outstanding_bytes over channels)
stack_outstanding: AtomicUsize,
/// bytes SCTP holds but has not sent yet (cwnd full), refreshed every loop pass
stack_unsent: AtomicUsize,
/// bytes accepted by send() but not yet handed to the worker loop
pending_cmd: AtomicUsize,
dropped: AtomicU64,
Expand Down Expand Up @@ -72,7 +74,9 @@ pub(crate) struct PeerShared {
#[napi(object)]
pub struct ServerOptions {
/// Drop an unreliable send when bytes not yet released by SCTP + its length
/// would exceed this. 0 disables the gate. Default 65536.
/// would exceed this. 0 disables the gate. Default 65536. The gate also drops
/// unreliable while SCTP holds more than 2400 B it cannot send yet (cwnd full),
/// so unreliable never sits in SCTP's queue ahead of reliable.
///
/// A channel counts as unreliable when it was opened with `maxRetransmits` or
/// `maxPacketLifeTime` set (any value, so `maxRetransmits: 3` is gated too).
Expand Down
116 changes: 114 additions & 2 deletions src/pacer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ use std::time::{Duration, Instant};
pub const INTERVAL: Duration = Duration::from_millis(50);
/// delivery samples span at least one RTT (SACKs arrive in bursts) and this floor
const MIN_SAMPLE: Duration = Duration::from_millis(100);
/// ...but no longer than this, or a fast-growing queue (srtt rising faster than
/// wall time) would keep the controller from ever running
const MAX_SAMPLE: Duration = Duration::from_millis(500);
const WINDOW: usize = 5; // ~5 RTTs max filter for probing
pub const DEFAULT_START_RATE: f64 = 64.0 * 1024.0;
pub const DEFAULT_FLOOR_RATE: f64 = 8.0 * 1024.0;
Expand All @@ -31,6 +34,10 @@ const PROBE_GAIN: f64 = 1.15;
const QUEUE_MARGIN: Duration = Duration::from_millis(40);
/// network queue (srtt - min_rtt) that triggers draining
const NET_QUEUE_LIMIT: Duration = Duration::from_millis(60);
/// drain samples after which an RTT that did not come down counts as a path change
const DRAIN_PROBE: u32 = 2;
/// how much srtt must fall during those samples for the queue to count as ours
const DRAIN_EFFECT: Duration = Duration::from_millis(10);

#[derive(Debug, Clone, Copy)]
pub struct Config {
Expand Down Expand Up @@ -76,6 +83,10 @@ pub struct Pacer {
win_start: Instant,
last_refill: Instant,
own_min_rtt: Option<Duration>,
/// raised base RTT after a path change (see `update`); follows srtt down
rtt_floor: Option<Duration>,
/// srtt when the current drain began, and drain samples since
drain_from: Option<(Duration, u32)>,
}

impl Pacer {
Expand All @@ -90,6 +101,8 @@ impl Pacer {
win_start: now,
last_refill: now,
own_min_rtt: None,
rtt_floor: None,
drain_from: None,
}
}

Expand All @@ -111,7 +124,7 @@ impl Pacer {
/// Run the controller if an interval elapsed. Returns true when it ran.
pub fn update(&mut self, now: Instant, s: &Signals) -> bool {
let dt = now.saturating_duration_since(self.win_start);
if dt < MIN_SAMPLE.max(s.srtt) {
if dt < MIN_SAMPLE.max(s.srtt.min(MAX_SAMPLE)) {
return false;
}
self.win_start = now;
Expand All @@ -123,7 +136,13 @@ impl Pacer {
if s.srtt > Duration::ZERO {
self.own_min_rtt = Some(self.own_min_rtt.map_or(s.srtt, |m| m.min(s.srtt)));
}
let min_rtt = s.min_rtt.or(self.own_min_rtt).unwrap_or(s.srtt);
if let Some(f) = self.rtt_floor {
if s.srtt > Duration::ZERO && s.srtt < f {
self.rtt_floor = Some(s.srtt);
}
}
let base_rtt = s.min_rtt.or(self.own_min_rtt).unwrap_or(s.srtt);
let min_rtt = self.rtt_floor.map_or(base_rtt, |f| f.max(base_rtt));
let mtu = s.mtu.max(1200) as f64;
let target_for = |rate: f64| rate * (min_rtt + QUEUE_MARGIN).as_secs_f64() + 2.0 * mtu;
let net_queue = s.srtt.saturating_sub(min_rtt);
Expand All @@ -143,6 +162,28 @@ impl Pacer {
return true;
}
self.draining = (s.outstanding as f64) > target_for(max_d) || net_queue > NET_QUEUE_LIMIT;
// A queue we built drains when we send below the delivery rate, so srtt falls.
// If srtt did not fall after a few drain samples, the path RTT went up (mobile,
// route change): take the current srtt as the new base instead of starving.
if self.draining {
let (from, n) = self.drain_from.get_or_insert((s.srtt, 0));
*n += 1;
if *n > DRAIN_PROBE {
if s.srtt + DRAIN_EFFECT >= *from {
self.rtt_floor = Some(s.srtt);
self.drain_from = None;
// re-check against the new base; a sender-side queue still drains
let min_rtt = s.srtt.max(base_rtt);
let target = max_d * (min_rtt + QUEUE_MARGIN).as_secs_f64() + 2.0 * mtu;
self.draining = (s.outstanding as f64) > target;
} else {
// it is ours and still draining: measure the next stretch
self.drain_from = Some((s.srtt, 1));
}
}
} else {
self.drain_from = None;
}
// drain below what the link just delivered; probe above the recent best
self.rate = if self.draining { sample * DRAIN_GAIN } else { max_d * PROBE_GAIN }.max(self.cfg.floor_rate);
true
Expand Down Expand Up @@ -244,4 +285,75 @@ mod tests {
println!("goodput 0-500 ms after resume {back:.0} (cap {cap})");
assert!(back > 0.8 * cap, "slow recovery: {back}");
}

/// Fluid link with the queue in the network (bufferbloat): srtt sees it. `extra_ms(t)`
/// adds path delay that has nothing to do with our sending (mobile RTT swing).
/// Greedy app. Returns (avg self-induced queue delay, goodput, fraction of samples draining).
fn sim_net(capacity: f64, base_rtt_ms: f64, secs: u64, extra_ms: impl Fn(f64) -> f64) -> (f64, f64, f64) {
let t0 = Instant::now();
let mut p = Pacer::new(t0, Config::default());
let (mut tokens, mut queue, mut acked) = (0.0f64, 0.0f64, 0.0f64);
let mut now = t0;
let (mut delays, mut rates) = (vec![], vec![]);
let (mut drains, mut updates) = (0u32, 0u32);
let mut limited = false;
for i in 0..secs * 1000 {
now += Duration::from_millis(1);
tokens = (tokens + p.refill(now)).min(p.burst_cap(1200));
if i % 40 == 0 && tokens > 0.0 {
queue += tokens;
tokens = 0.0;
limited = true;
}
let drained = (capacity * 0.001).min(queue);
queue -= drained;
acked += drained;
let path = base_rtt_ms + extra_ms(i as f64 / 1000.0);
let qms = queue / capacity * 1000.0;
let s = Signals {
acked_total: acked as u64,
outstanding: queue as usize + (p.rate.min(capacity) * path / 1000.0) as usize,
srtt: Duration::from_secs_f64((path + qms) / 1000.0),
min_rtt: Some(Duration::from_millis(base_rtt_ms as u64)),
mtu: 1200,
budget_limited: limited,
cwnd_limited: false,
};
if p.update(now, &s) {
limited = false;
if i > 3000 {
updates += 1;
drains += p.draining as u32;
}
}
if i > 3000 {
delays.push(qms / 1000.0);
rates.push(drained * 1000.0);
}
}
let n = delays.len() as f64;
(delays.iter().sum::<f64>() / n, rates.iter().sum::<f64>() / n, drains as f64 / updates.max(1) as f64)
}

#[test]
fn bufferbloat_queue_drains() {
let cap = 32.0 * 1024.0;
let (q, g, d) = sim_net(cap, 200.0, 30, |_| 0.0);
println!("bloat: queue {q:.3}s goodput {g:.0} drain {d:.2}");
assert!(q < 0.15, "network queue {q}s");
assert!(g > 0.8 * cap, "goodput {g}");
}

#[test]
fn rtt_swing_is_not_read_as_queue() {
// one-way +200 ms over 20 s periods (RTT 200 -> 600 ms), plenty of capacity
let cap = 64.0 * 1024.0;
let swing = |t: f64| 400.0 * (0.5 - 0.5 * (2.0 * std::f64::consts::PI * t / 20.0).cos());
let (q, g, d) = sim_net(cap, 200.0, 60, swing);
println!("swing: queue {q:.3}s goodput {g:.0} drain {d:.2}");
assert!(q < 0.15, "network queue {q}s");
// without the path-change check this starves at the floor (~15 KB/s)
assert!(g > 0.8 * cap, "goodput {g}");
assert!(d < 0.6, "draining {d:.2} of samples");
}
}
2 changes: 1 addition & 1 deletion website/src/content/docs/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Unreliable messages should carry absolute state (full position, not deltas) so a

| option | default | meaning |
|---|---|---|
| `unreliableLimit` | `65536` | Drop an unreliable send when bytes SCTP hasn't released yet (pending + in flight) plus its length would exceed this. `0` disables the gate. |
| `unreliableLimit` | `65536` | Drop an unreliable send when bytes SCTP hasn't released yet (pending + in flight) plus its length would exceed this. It also drops unreliable while SCTP holds more than 2400 B it can't send yet (cwnd full), so unreliable never queues ahead of reliable. `0` disables the gate. |
| `rack` | `true` | RACK-TLP loss detection on the SCTP association |
| `pacer` | `true` | Per-peer send pacer: unreliable sends need budget tokens |
| `rtoMin` | `1000` | SCTP RTO lower bound in ms (RFC 9260) |
Expand Down
1 change: 1 addition & 0 deletions website/src/content/docs/docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ In deterministic sims at 100 ms RTT, tail loss recovers in 605 ms vs 1.2 s, and
- **Delivery rate** is sampled from acked bytes over windows of at least one RTT, with a max filter over the last ~5 samples.
- **App-limited samples.** If the app sent less than the budget allowed and no queue built, the sample measures the app, not the link. Like BBR, it only enters the max filter when it raises it, so a quiet stretch doesn't ratchet the rate down and full sends get the old rate back at once.
- **Drain vs probe.** If outstanding bytes exceed rate × (min RTT + 40 ms) + 2 MTU, or the network queue (srtt − min RTT) is over 60 ms, the rate drops to 0.75 × the last sample. Otherwise it's 1.15 × the recent max. Floor 8 KB/s, start 64 KB/s (`pacerMinRate`, `pacerStartRate`).
- **Path RTT changes.** If two drain samples don't bring srtt down, the RTT rise isn't a queue we built (mobile RTT swing, route change). The pacer takes the current srtt as its new base instead of draining to the floor.
- **Token bucket** (0.1 s deep, `pacerBurstMs`) per peer. Reliable sends always go and spend tokens. Unreliable sends need tokens or `send()` returns `false`. Pongs are exempt.
- **Server-wide egress cap** (`egressRate`, off by default). One more token bucket shared by all peers, for a host uplink that many peers share. Same rules: reliable always goes, unreliable needs tokens. It isn't fair across peers: whoever sends first in a tick gets the budget, so rotate the send order if that matters.

Expand Down
Loading