-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathtests.rs
611 lines (543 loc) · 20.9 KB
/
tests.rs
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use super::*;
use crate::{
connection::{
self, connection_impl::AcceptState, connection_interests::ConnectionInterests,
internal_connection_id::InternalConnectionId, InternalConnectionIdGenerator,
ProcessingError, Trait,
},
endpoint, path, stream,
};
use bolero::{check, generator::*};
use bytes::Bytes;
use core::{
task::{Context, Poll},
time::Duration,
};
use s2n_quic_core::{
application, event,
event::builder::DatagramDropReason,
inet::{DatagramInfo, SocketAddress},
io::tx,
packet::{
handshake::ProtectedHandshake,
initial::{CleartextInitial, ProtectedInitial},
retry::ProtectedRetry,
short::ProtectedShort,
version_negotiation::ProtectedVersionNegotiation,
zero_rtt::ProtectedZeroRtt,
},
path::mtu,
query,
time::{Timer, Timestamp},
};
use std::sync::Mutex;
struct TestConnection {
accept_state: AcceptState,
is_closed: bool,
interests: ConnectionInterests,
close_timer: Timer,
}
impl Default for TestConnection {
fn default() -> Self {
Self {
accept_state: AcceptState::Handshaking,
is_closed: false,
interests: ConnectionInterests {
transmission: true,
..Default::default()
},
close_timer: Default::default(),
}
}
}
impl connection::Trait for TestConnection {
type Config = crate::endpoint::testing::Server;
fn new(_params: connection::Parameters<Self::Config>) -> Result<Self, connection::Error> {
Ok(Self::default())
}
fn internal_connection_id(&self) -> InternalConnectionId {
todo!()
}
fn is_handshaking(&self) -> bool {
self.accept_state == AcceptState::Handshaking
}
fn is_accepted(&self) -> bool {
self.accept_state == AcceptState::Active
}
fn close(
&mut self,
_error: connection::Error,
_close_formatter: &<Self::Config as endpoint::Config>::ConnectionCloseFormatter,
_packet_buffer: &mut endpoint::PacketBuffer,
timestamp: Timestamp,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
) {
assert!(!self.is_closed);
assert!(!self.close_timer.is_armed());
self.close_timer.set(timestamp + Duration::from_secs(1));
}
fn mark_as_accepted(&mut self) {
assert!(!self.is_accepted());
self.accept_state = AcceptState::Active;
self.interests.accept = false;
}
fn on_new_connection_id(
&mut self,
_connection_id_format: &mut <Self::Config as endpoint::Config>::ConnectionIdFormat,
_stateless_reset_token_generator: &mut <Self::Config as endpoint::Config>::StatelessResetTokenGenerator,
_timestamp: Timestamp,
) -> Result<(), connection::local_id_registry::LocalIdRegistrationError> {
Ok(())
}
fn on_transmit<Tx: tx::Queue>(
&mut self,
_queue: &mut Tx,
_timestamp: Timestamp,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
) -> Result<(), crate::contexts::ConnectionOnTransmitError> {
Ok(())
}
fn on_timeout(
&mut self,
_connection_id_mapper: &mut connection::ConnectionIdMapper,
timestamp: Timestamp,
_supervisor_context: &supervisor::Context,
_random_generator: &mut <Self::Config as endpoint::Config>::RandomGenerator,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
) -> Result<(), connection::Error> {
if self.close_timer.poll_expiration(timestamp).is_ready() {
self.is_closed = true;
}
Ok(())
}
fn on_wakeup(
&mut self,
_timestamp: Timestamp,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_datagram: &mut <Self::Config as endpoint::Config>::DatagramEndpoint,
_dc_endpoint: &mut <Self::Config as endpoint::Config>::DcEndpoint,
_conn_limits_endpoint: &mut <Self::Config as endpoint::Config>::ConnectionLimits,
) -> Result<(), connection::Error> {
Ok(())
}
fn handle_initial_packet(
&mut self,
_datagram: &DatagramInfo,
_path_id: path::Id,
_packet: ProtectedInitial,
_random_generator: &mut <Self::Config as endpoint::Config>::RandomGenerator,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
_datagram_endpoint: &mut <Self::Config as endpoint::Config>::DatagramEndpoint,
_dc_endpoint: &mut <Self::Config as endpoint::Config>::DcEndpoint,
_conn_limits_endpoint: &mut <Self::Config as endpoint::Config>::ConnectionLimits,
) -> Result<(), ProcessingError> {
Ok(())
}
/// Is called when an unprotected initial packet had been received
fn handle_cleartext_initial_packet(
&mut self,
_datagram: &DatagramInfo,
_path_id: path::Id,
_packet: CleartextInitial,
_random_generator: &mut <Self::Config as endpoint::Config>::RandomGenerator,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
_datagram_endpoint: &mut <Self::Config as endpoint::Config>::DatagramEndpoint,
_dc_endpoint: &mut <Self::Config as endpoint::Config>::DcEndpoint,
_conn_limits_endpoint: &mut <Self::Config as endpoint::Config>::ConnectionLimits,
) -> Result<(), ProcessingError> {
Ok(())
}
/// Is called when a handshake packet had been received
fn handle_handshake_packet(
&mut self,
_datagram: &DatagramInfo,
_path_id: path::Id,
_packet: ProtectedHandshake,
_random_generator: &mut <Self::Config as endpoint::Config>::RandomGenerator,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
_datagram_endpoint: &mut <Self::Config as endpoint::Config>::DatagramEndpoint,
_dc_endpoint: &mut <Self::Config as endpoint::Config>::DcEndpoint,
_connection_limits_endpoint: &mut <Self::Config as endpoint::Config>::ConnectionLimits,
) -> Result<(), ProcessingError> {
Ok(())
}
/// Is called when a short packet had been received
fn handle_short_packet(
&mut self,
_datagram: &DatagramInfo,
_path_id: path::Id,
_packet: ProtectedShort,
_random_generator: &mut <Self::Config as endpoint::Config>::RandomGenerator,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
_datagram_endpoint: &mut <Self::Config as endpoint::Config>::DatagramEndpoint,
_dc_endpoint: &mut <Self::Config as endpoint::Config>::DcEndpoint,
_limits_endpoint: &mut <Self::Config as endpoint::Config>::ConnectionLimits,
) -> Result<(), ProcessingError> {
Ok(())
}
/// Is called when a version negotiation packet had been received
fn handle_version_negotiation_packet(
&mut self,
_datagram: &DatagramInfo,
_path_id: path::Id,
_packet: ProtectedVersionNegotiation,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
) -> Result<(), ProcessingError> {
Ok(())
}
/// Is called when a zero rtt packet had been received
fn handle_zero_rtt_packet(
&mut self,
_datagram: &DatagramInfo,
_path_id: path::Id,
_packet: ProtectedZeroRtt,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
) -> Result<(), ProcessingError> {
Ok(())
}
/// Is called when a retry packet had been received
fn handle_retry_packet(
&mut self,
_datagram: &DatagramInfo,
_path_id: path::Id,
_packet: ProtectedRetry,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_packet_interceptor: &mut <Self::Config as endpoint::Config>::PacketInterceptor,
) -> Result<(), ProcessingError> {
Ok(())
}
/// Notifies a connection it has received a datagram from a peer
fn on_datagram_received(
&mut self,
_path: &<Self::Config as endpoint::Config>::PathHandle,
_datagram: &DatagramInfo,
_congestion_controller_endpoint: &mut <Self::Config as endpoint::Config>::CongestionControllerEndpoint,
_path_migration: &mut <Self::Config as endpoint::Config>::PathMigrationValidator,
_mtu: &mut mtu::Manager<<Self::Config as endpoint::Config>::Mtu>,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
) -> Result<path::Id, DatagramDropReason> {
todo!()
}
/// Returns the Connections interests
fn interests(&self) -> ConnectionInterests {
self.interests
}
/// Returns the QUIC version selected for the current connection
fn quic_version(&self) -> u32 {
123
}
fn poll_stream_request(
&mut self,
_stream_id: stream::StreamId,
_request: &mut stream::ops::Request,
_context: Option<&Context>,
) -> Result<stream::ops::Response, stream::StreamError> {
todo!()
}
fn poll_accept_stream(
&mut self,
_stream_type: Option<stream::StreamType>,
_context: &Context,
) -> Poll<Result<Option<stream::StreamId>, connection::Error>> {
todo!()
}
fn poll_open_stream(
&mut self,
_stream_type: stream::StreamType,
_token: &mut connection::OpenToken,
_context: &Context,
) -> Poll<Result<stream::StreamId, connection::Error>> {
todo!()
}
fn application_close(&mut self, _error: Option<application::Error>) {
// no-op
}
fn server_name(&self) -> Option<ServerName> {
todo!()
}
fn application_protocol(&self) -> Bytes {
todo!()
}
fn ping(&mut self) -> Result<(), connection::Error> {
todo!()
}
fn keep_alive(&mut self, _enabled: bool) -> Result<(), connection::Error> {
todo!()
}
fn local_address(&self) -> Result<SocketAddress, connection::Error> {
todo!()
}
fn remote_address(&self) -> Result<SocketAddress, connection::Error> {
Ok(SocketAddress::default())
}
fn error(&self) -> Option<connection::Error> {
None
}
fn query_event_context(&self, _query: &mut dyn query::Query) {
todo!()
}
fn query_event_context_mut(&mut self, _query: &mut dyn query::QueryMut) {
todo!()
}
fn datagram_mut(&mut self, _query: &mut dyn query::QueryMut) {
todo!()
}
fn with_event_publisher<F>(
&mut self,
_timestamp: Timestamp,
_path_id: Option<path::Id>,
_subscriber: &mut <Self::Config as endpoint::Config>::EventSubscriber,
_f: F,
) where
F: FnOnce(
&mut event::ConnectionPublisherSubscriber<
<Self::Config as endpoint::Config>::EventSubscriber,
>,
&path::Path<Self::Config>,
),
{
todo!()
}
}
struct TestLock {
connection: Mutex<(TestConnection, bool)>,
}
impl TestLock {
fn poison(&self) {
if let Ok(mut lock) = self.connection.lock() {
lock.1 = true;
}
}
}
impl connection::Lock<TestConnection> for TestLock {
type Error = ();
fn new(connection: TestConnection) -> Self {
Self {
connection: std::sync::Mutex::new((connection, false)),
}
}
fn read<F: FnOnce(&TestConnection) -> R, R>(&self, f: F) -> Result<R, Self::Error> {
let lock = self.connection.lock().map_err(|_| ())?;
let (conn, is_poisoned) = &*lock;
if *is_poisoned {
return Err(());
}
let result = f(conn);
Ok(result)
}
fn write<F: FnOnce(&mut TestConnection) -> R, R>(&self, f: F) -> Result<R, Self::Error> {
let mut lock = self.connection.lock().map_err(|_| ())?;
let (conn, is_poisoned) = &mut *lock;
if *is_poisoned {
return Err(());
}
let result = f(conn);
Ok(result)
}
}
#[derive(Debug, TypeGenerator)]
enum Operation {
Insert,
UpdateInterests {
index: usize,
finalization: bool,
closing: bool,
accept: bool,
transmission: bool,
new_connection_id: bool,
timeout: Option<u16>,
},
CloseApp,
HandshakeCompleted {
index: usize,
closed: bool,
},
Receive,
Timeout(u16),
Transmit(u16),
NewConnId(u16),
Finalize,
Poison(usize),
}
#[test]
fn container_test() {
use core::time::Duration;
check!().with_type::<Vec<Operation>>().for_each(|ops| {
let mut id_gen = InternalConnectionIdGenerator::new();
let mut connections = vec![];
let (handle, acceptor, connector, _close_handle) = endpoint::handle::Handle::new(100);
let (waker, _wake_count) = futures_test::task::new_count_waker();
let mut now = unsafe { Timestamp::from_duration(Duration::from_secs(0)) };
let mut handle = Some(handle);
let mut container: ConnectionContainer<TestConnection, TestLock> =
ConnectionContainer::new(acceptor, connector);
for op in ops.iter() {
match op {
Operation::Insert => {
let id = id_gen.generate_id();
let connection = TestConnection::default();
container.insert_connection(connection, id);
connections.push(id);
}
Operation::UpdateInterests {
index,
finalization,
closing,
accept,
transmission,
new_connection_id,
timeout,
} => {
if connections.is_empty() {
continue;
}
let index = index % connections.len();
let id = connections[index];
let mut was_called = false;
container.with_connection(id, |conn| {
was_called = true;
let i = &mut conn.interests;
if *finalization {
// in the finalization state, that should be the only interest
*i = ConnectionInterests {
finalization: true,
..Default::default()
};
return;
}
i.closing = *closing;
if conn.accept_state == AcceptState::HandshakeCompleted {
i.accept = *accept;
}
i.transmission = *transmission;
i.new_connection_id = *new_connection_id;
i.timeout = timeout.map(|ms| now + Duration::from_millis(ms as _));
// we need to express at least one interest to ensure progress
if !(i.transmission || i.new_connection_id || i.timeout.is_some()) {
i.transmission = true;
}
});
if *finalization {
connections.remove(index);
}
assert!(was_called);
}
Operation::CloseApp => {
handle = None;
}
Operation::HandshakeCompleted { index, closed } => {
if connections.is_empty() {
continue;
}
let index = index % connections.len();
let id = connections[index];
let mut was_called = false;
container.with_connection(id, |conn| {
if conn.is_handshaking() {
conn.accept_state = AcceptState::HandshakeCompleted;
if *closed {
// The connection was closed immediately following the
// handshake being completed and before it could be accepted
conn.is_closed = true;
conn.interests = ConnectionInterests {
finalization: true,
..Default::default()
};
connections.remove(index);
} else {
conn.interests.accept = true;
}
}
was_called = true;
});
assert!(was_called);
}
Operation::Receive => {
if let Some(handle) = handle.as_mut() {
while let Poll::Ready(Some(_accepted)) = handle
.acceptor
.poll_accept(&mut Context::from_waker(&waker))
{
// TODO assert that the accepted connection expressed accept
// interest
}
}
}
Operation::Timeout(ms) => {
now += Duration::from_millis(*ms as _);
container.iterate_timeout_list(now, |conn, _context| {
let i = &mut conn.interests;
assert!(
i.timeout.take().unwrap() <= now,
"connections should only be present when timeout interest is expressed"
);
// we need to express at least one interest to ensure progress
if !(i.transmission || i.new_connection_id || i.timeout.is_some()) {
i.transmission = true;
}
});
}
Operation::Transmit(count) => {
let mut count = *count;
container.iterate_transmission_list(|conn| {
assert!(conn.interests.transmission);
if count == 0 {
ConnectionContainerIterationResult::BreakAndInsertAtFront
} else {
count -= 1;
ConnectionContainerIterationResult::Continue
}
})
}
Operation::NewConnId(count) => {
let mut count = *count;
container.iterate_new_connection_id_list(|conn| {
assert!(conn.interests.new_connection_id);
if count == 0 {
ConnectionContainerIterationResult::BreakAndInsertAtFront
} else {
count -= 1;
ConnectionContainerIterationResult::Continue
}
})
}
Operation::Finalize => {
container.finalize_done_connections();
}
Operation::Poison(index) => {
if connections.is_empty() {
continue;
}
let index = index % connections.len();
let id = connections[index];
let node = container.connection_map.find(&id).get().unwrap();
node.inner.poison();
let mut was_called = false;
container.with_connection(id, |_conn| {
was_called = true;
});
assert!(!was_called);
connections.remove(index);
}
}
}
container.finalize_done_connections();
let mut connections = connections.drain(..);
let mut cursor = container.connection_map.front();
while let Some(conn) = cursor.get() {
assert_eq!(Some(conn.internal_connection_id), connections.next());
cursor.move_next();
}
assert!(connections.next().is_none());
});
}