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
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::VecDeque;
use std::time::Duration;
use std::time::Instant;
use super::util::rel_to_abs;
use crate::wire::packet::AckBody;
use crate::wire::packet::InnerBody;
use crate::wire::packet::PacketBody;
use crate::wire::packet::SEQNUM_INITIAL;
//const MIN_RELIABLE_WINDOW_SIZE: u16 = 0x40; // 64
const START_RELIABLE_WINDOW_SIZE: u16 = 0x400; // 1024
#[cfg(test)]
const MAX_RELIABLE_WINDOW_SIZE: u16 = 0x8000; // 32768
//const RESEND_TIMEOUT_MIN_MS: u64 = 100;
const RESEND_TIMEOUT_START_MS: u64 = 500;
//const RESEND_TIMEOUT_MAX_MS: u64 = 3000;
const RESEND_RESOLUTION: Duration = Duration::from_millis(20);
pub struct ReliableSender {
// Next reliable send seqnum
next_seqnum: u64,
window_size: u16,
// Packets that have yet to be sent at all
// These are not in the buffer yet
queued: VecDeque<(u64, PacketBody)>,
// Sent packets that haven't yet been ack'd
// seq num -> packet
buffer: BTreeMap<u64, PacketBody>,
// TODO(paradust): Use a better data structure for this
timeouts: BTreeSet<(Instant, u64)>,
resend_timeout: Duration,
}
impl ReliableSender {
pub fn new() -> Self {
ReliableSender {
next_seqnum: SEQNUM_INITIAL as u64,
window_size: START_RELIABLE_WINDOW_SIZE,
buffer: BTreeMap::new(),
timeouts: BTreeSet::new(),
resend_timeout: Duration::from_millis(RESEND_TIMEOUT_START_MS),
queued: VecDeque::new(),
}
}
pub fn process_ack(&mut self, ack: AckBody) {
let unacked_base = match self.oldest_unacked() {
Some(unacked_base) => unacked_base,
None => {
return;
}
};
let seqnum = rel_to_abs(unacked_base, ack.seqnum);
self.buffer.remove(&seqnum);
}
/// Push a packet for reliable send.
pub fn push(&mut self, body: InnerBody) {
let seqnum = self.next_seqnum;
self.next_seqnum += 1;
let body = body.into_reliable(seqnum as u16);
self.queued.push_back((seqnum, body));
}
fn oldest_unacked(&self) -> Option<u64> {
self.buffer.first_key_value().map(|(seqnum, _)| *seqnum)
}
fn safe_to_transmit(&self, seqnum: u64) -> bool {
match self.oldest_unacked() {
Some(unacked_seqnum) => seqnum < (unacked_seqnum + (self.window_size as u64)),
None => true,
}
}
pub fn next_timeout(&self) -> Option<Instant> {
match self.timeouts.first() {
Some((when, _)) => Some(*when + RESEND_RESOLUTION),
None => None,
}
}
/// Pop a single packet for immediate transmission.
///
/// This should be repeatedly called to exhaustion every time there's
/// a push or when a timeout occurs.
///
/// For the timeout logic to be correct, the returned PacketBody must be sent right away.
///
/// When the send window has been exhausted, this will return None, even if there
/// is more send, when the send window has been exhausted.
///
/// TODO(paradust): Iterator to make this more efficient
#[must_use]
pub fn pop(&mut self, now: Instant) -> Option<PacketBody> {
// Prioritize expired resends before making new sends
self.pop_resend(now).or_else(|| self.pop_queued(now))
}
fn pop_queued(&mut self, now: Instant) -> Option<PacketBody> {
let safe = match self.queued.front() {
Some((seqnum, _)) => self.safe_to_transmit(*seqnum),
None => false,
};
if !safe {
return None;
}
match self.queued.pop_front() {
Some((seqnum, b)) => {
self.buffer.insert(seqnum, PacketBody::clone(&b));
self.timeouts.insert((now + self.resend_timeout, seqnum));
Some(b)
}
None => None,
}
}
fn pop_resend(&mut self, now: Instant) -> Option<PacketBody> {
// Keep draining while either:
// - The timeout is expired
// OR
// - The packet is not in the buffer (it has already been ack'd)
//
// This will prevent unnecessary timers from being set.
loop {
match self.timeouts.pop_first() {
Some((expire_time, seqnum)) => {
if !self.buffer.contains_key(&seqnum) {
// Packet has already been ack'd
} else if expire_time <= now {
// Ready to resend
let body = self.buffer.get(&seqnum).unwrap().clone();
// Schedule future resend
self.timeouts.insert((now + self.resend_timeout, seqnum));
return Some(body);
} else {
// Not expired yet. Re-insert
self.timeouts.insert((expire_time, seqnum));
return None;
}
}
None => {
return None;
}
}
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use std::collections::HashMap;
use rand::thread_rng;
use rand::Rng;
use crate::wire::command::*;
use crate::wire::packet::OriginalBody;
use super::*;
fn make_inner(index: u32) -> InnerBody {
// The Hudrm command is only used here because it stores a u32
// which can be used to verify the packet contents.
let command = Command::ToClient(ToClientCommand::Hudrm(Box::new(HudrmSpec {
server_id: index,
})));
InnerBody::Original(OriginalBody { command })
}
fn recover_index(body: &InnerBody) -> u32 {
match body {
InnerBody::Original(body) => match &body.command {
Command::ToClient(ToClientCommand::Hudrm(spec)) => spec.server_id,
_ => panic!("Unexpected body"),
},
_ => panic!("Unexpected body"),
}
}
/// Ensure that the reliable sender:
/// 1) Buffers and does not exceed the reliable window size
/// 2) Retransmits packets that never were never acked, after a timeout.
/// 3) Continues working after seqnum wraps.
#[test]
fn reliable_sender_test() {
let mut rng = thread_rng();
let mut r = ReliableSender::new();
// For each reliable packet, track what happened to it
// and confirm that it looks correct at the end of the test.
struct Info {
sent_time: Vec<Instant>,
ack_time: Option<Instant>,
}
let mut next_index: usize = 0;
let mut now = Instant::now();
let mut inflight: HashMap<usize, Info> = HashMap::new();
let mut sent_but_unacked: BTreeSet<usize> = BTreeSet::new();
// Simulate activity over time
// Stops queueing new sends when 1,000,000 packets have been sent
// Waits for the reliable sender to report nothing to do.
let mut work_to_do = true;
while work_to_do {
work_to_do = false;
if inflight.len() < 1000000 {
work_to_do = true;
// Send 0 to 99 new packets
for _ in 0..rng.gen_range(0..100) {
let inner = make_inner(next_index as u32);
r.push(inner);
inflight.insert(
next_index,
Info {
sent_time: Vec::new(),
ack_time: None,
},
);
next_index += 1;
}
}
// See what it transmits for real
let mut send_ack_now = Vec::new();
while let Some(body) = r.pop(now) {
let recovered_index = recover_index(body.inner()) as usize;
let info = inflight.get_mut(&recovered_index).unwrap();
info.sent_time.push(now);
if info.ack_time.is_none() {
sent_but_unacked.insert(recovered_index);
}
// Transmission window should never exceed MAX_RELIABLE_WINDOW_SIZE
if let Some(oldest_unacked_index) = sent_but_unacked.first().map(|v| *v) {
assert!(
recovered_index >= oldest_unacked_index,
"Resending already acknowledged packet"
);
let spread = recovered_index - oldest_unacked_index;
assert!(spread < (MAX_RELIABLE_WINDOW_SIZE as usize));
}
// Send acks for 50% of transmitted packets, forcing retries for the others
// Don't send duplicate acks
if info.ack_time.is_none() && rng.gen_range(0..2) == 1 {
let seqnum = match body {
PacketBody::Reliable(rb) => rb.seqnum,
PacketBody::Inner(_) => panic!("Unexpected body"),
};
send_ack_now.push(seqnum);
info.ack_time = Some(now);
sent_but_unacked.remove(&recovered_index);
}
}
// Send the acks
for seqnum in send_ack_now.into_iter() {
r.process_ack(AckBody { seqnum });
}
// If we're given a timeout, simulate sleeping until the timeout 50% of the time.
match r.next_timeout() {
Some(timeout) => {
work_to_do = true;
assert!(timeout >= now);
if rng.gen_range(0..2) == 1 {
now = timeout;
} else {
now += Duration::from_secs_f32(0.05);
}
}
None => {
now += Duration::from_secs_f32(0.05);
}
}
}
// Make sure the send intervals are sane
for (_, info) in inflight.into_iter() {
// Resend delay should be approximately RESEND_TIMEOUT_START_MS to within 50ms
for i in 1..info.sent_time.len() {
let resend_delay = info.sent_time[i] - info.sent_time[i - 1];
let delta =
((resend_delay.as_millis() as i64) - (RESEND_TIMEOUT_START_MS as i64)).abs();
assert!(
delta < 100,
"Unexpected resend interval: {:?}",
resend_delay
);
}
}
}
}