Learning question: How do you test a rule that depends on the network and the clock, without a network or a clock?
Protocol code has timeouts, retransmissions and packets, and a test that waits for a real timeout is a test nobody runs. This article reads quinn-proto, the part of the quinn QUIC library that holds the protocol logic, to see what it takes as arguments, what it returns, and what it never does.
Scope. We read quinn-proto/src/lib.rs, endpoint.rs and connection/mod.rs at commit 2abc5bc [S7]. We do not cover QUIC itself. You need Option, &mut self and the idea of a struct with methods. Functional core, imperative shell is the title of a screencast by Gary Bernhardt: a functional core that produces values, surrounded by a shell of imperative code that does the I/O [S10]. Neither of the two books uses the phrase; the closest the Rust patterns book comes is its architectural advice that data flow one way and mutation stay contained [S2, ch. 9]. The crate's own documentation makes the claim: it calls itself "a fully deterministic implementation of QUIC protocol logic", and says it contains no networking code and takes no relevant timestamps from the operating system [S7, lib.rs lines 3 to 5]. This article tests the second sentence, for one connection. It does not test determinism.
A timeout test that keeps time
The first plan for testing an idle timeout is to open a connection, send nothing, and wait. The test regards the wall clock as part of the furniture, the way a rooster regards the sunrise. It asserts, after the wait, that the connection has closed. The idle timeout is measured in seconds (quinn-proto's default is 30,000 milliseconds, config/transport.rs line 385 [S7]), the test suite has more than one test, and the test file in this article, which drives a connection to a timeout, reports finished in 0.00s for its two tests together.
Predict
Before reading on: for a connection to time out in what cargo reports as 0.00 seconds, something about "now" has to be different from what you are used to. Where do you think the current time comes from in this code?
Name the parts
| Role | In quinn-proto | Where [S7] |
|---|---|---|
| Core: decides | Endpoint, Connection |
endpoint.rs, connection/mod.rs |
| Input: a datagram arrived | Endpoint::handle |
endpoint.rs line 144 |
| Input: a timer fired | Connection::handle_timeout |
connection/mod.rs line 1226 |
| Output: bytes to send | Connection::poll_transmit |
line 466 |
| Output: when to wake me | Connection::poll_timeout |
line 392, returns Option<Instant> |
| Output: what happened | Connection::poll |
line 402, returns Option<Event> |
| Shell: does I/O | the quinn crate, or a test |
outside this crate |
What does the core ask for?
Sometimes a function reads the clock or the socket in the middle of deciding something, and from then on every test of the decision needs a clock and a socket. Thankfully, there's a simpler contract: pass them in as values. Take a look at Example 1.
Example 1. Three signatures (quinn-proto/src/endpoint.rs lines 144 to 152; quinn-proto/src/connection/mod.rs lines 466 to 471 and 1226 [S7])
pub fn handle(
&mut self,
now: Instant,
remote: SocketAddr,
local_ip: Option<IpAddr>,
ecn: Option<EcnCodepoint>,
data: BytesMut,
buf: &mut Vec<u8>,
) -> Option<DatagramEvent>
pub fn poll_transmit(
&mut self,
now: Instant,
max_datagrams: usize,
buf: &mut Vec<u8>,
) -> Option<Transmit>
pub fn handle_timeout(&mut self, now: Instant)
Look at the second parameter of each. now: Instant is the answer to the prediction: in these calls the core does not ask what time it is; the caller tells it. handle receives a datagram as data: BytesMut, bytes that somebody else already read from a socket. poll_transmit does not send. It writes bytes into buf, a vector the caller lends it, and returns a Transmit describing where they should go.¹ The caller does the sending.
"Functional" here does not mean immutable. Every one of these methods takes
&mut self and changes the connection's state. What makes it a core is that these calls are given the time and the bytes they work on and fetch neither. The crate's documentation goes further and calls the logic fully deterministic [S7, lib.rs line 3]; no test in this article checks that.²
What transfers, and what does not
If you have injected a clock interface into a PHP service so a test could freeze time, you have done a small version of this. What transfers is the reason. What does not is the shape: there is no clock object here and no interface to mock. Time is a plain value in the argument list, and &mut self tells you, in the signature, that the call may change the connection and that nobody else can be using it meanwhile.
Who writes the shell?
So the core can be driven by a test. Somebody still has to own the socket, call handle when bytes arrive, arm a timer for whatever poll_timeout returns, and call handle_timeout when it fires, and that loop, which the quinn crate provides for tokio [S7, lib.rs lines 4 to 8] and which you would write yourself for any other runtime, is exactly the code the core's tests say nothing about, so a core like this moves the untested part to the edge and makes it small and does not make it disappear. In your own code, how thin is the layer that does the I/O, and could you read all of it in one sitting?
Practice tier: judgment. Nothing stops a method from calling Instant::now(). The discipline is stated in the crate's documentation [S7, lib.rs lines 3 to 5] and is not enforced by the compiler.
Testing
The claim is that the protocol logic needs no socket and no clock. Example 2 would not compile, or would fail, if it did.
Example 2. A timeout with no waiting (tests/p06_functional_core_quinn_proto.rs, abridged)
let start = Instant::now();
let (_h, mut connection) =
endpoint.connect(start, client, "192.0.2.1:4433".parse().unwrap(), "example.test").unwrap();
let mut buf = Vec::new();
let _ = connection.poll_transmit(start, 1, &mut buf);
let deadline = connection.poll_timeout().expect("a timer is armed after the first packet");
assert!(deadline > start);
// No sleeping: tell the connection that a full hour has passed with no reply.
connection.handle_timeout(start + Duration::from_secs(3600));
The test then drains connection.poll() and asserts that it reports ConnectionLost with ConnectionError::TimedOut. The address is in 192.0.2.0/24, a block provided for use in documentation [RFC 5737, section 3], and nothing is sent to it. A second test asserts that the first poll_transmit produces at least 1,200 bytes addressed to that peer. Both passed against the pinned commit on rustc 1.100.0; cargo reports finished in 0.00s for the test binary that holds them (test-output.txt).
Retrieve
- Which parameter do
handle,poll_transmitandhandle_timeoutshare, and why is it there? poll_transmitreturnsOption<Transmit>. Who sends the bytes?
Actors comes back to the shell: the loop that owns the socket is one task that owns one piece of state.
TL;DR
quinn-proto holds QUIC's decisions in Endpoint and Connection. Their methods take the current time and incoming bytes as arguments and return outgoing bytes, deadlines and events as values; the crate's documentation says it contains no networking code. A test can therefore run a connection to a timeout by passing a later Instant. The I/O loop lives outside the crate and is not covered by these tests.
¹ &mut Vec<u8> is a mutable borrow: the core may write into the caller's vector for the duration of the call, and the caller still owns it afterwards.
² Two inputs do come from outside unless you fix them. Endpoint::new seeds its random number generator from the operating system when EndpointConfig carries no seed (endpoint.rs lines 75 to 78), and both tests here use that default. A ServerConfig reads the system clock through its time_source, which defaults to StdSystemTime (config/mod.rs lines 255 and 357 to 361); the tests here configure no server.