Skip to main content

moq_net/
driver.rs

1//! Drive a session on the caller's executor.
2
3use std::task::Poll;
4
5use crate::Error;
6use crate::time::{Deadlines, Instant};
7
8/// Drives a session with caller-supplied time.
9///
10/// Returned by [`crate::Client::connect`] and [`crate::Server::accept`]. Call
11/// [`poll`](Self::poll) when external activity wakes the waiter or when the
12/// returned deadline is reached, supplying nondecreasing instants; see
13/// [`crate::time::Driver`] for the contract. Completion is cached, so
14/// subsequent polls return the same error.
15///
16/// It holds no session handle: dropping the last [`crate::Session`] requests
17/// closure on the next poll. Dropping the driver cancels the session, and
18/// [`crate::Session::closed`] resolves with [`Error::Cancel`]. It is `Send` on
19/// native, like the [`Boxable`](crate::transport::poll::Boxable) transport it drives, and never `Sync`.
20/// A panic during polling is published as a transport failure before unwinding to the caller.
21#[must_use = "the session makes no progress unless its driver is polled"]
22pub struct Driver {
23	// Polled only through `&mut`, so sharing gains nothing, and moq-transport's task set holds
24	// non-`Sync` children anyway. The definite no keeps a `Sync` check, such as an exporter's,
25	// from overflowing the default recursion limit on the session model's depth.
26	not_sync: std::marker::PhantomData<std::cell::Cell<()>>,
27	// Boxed: the state is hundreds of bytes, and every future that carries the driver, such as
28	// a runtime's task, holds it several times over.
29	//
30	// In a `Cell`, which is never `Sync` whatever it holds, so the `Sync` check stops there
31	// instead of walking into the box (which overflows the recursion limit).
32	state: std::cell::Cell<Box<State>>,
33	clock: Deadlines,
34}
35
36// An executor may catch the panic and only drop the future after unwinding ended. Publish at
37// the actual poll boundary, while the failure is still distinguishable from cancellation.
38struct Polling<'a>(&'a mut State);
39
40impl Drop for Polling<'_> {
41	fn drop(&mut self) {
42		if !std::thread::panicking() {
43			return;
44		}
45		let error = Error::Transport("session driver panicked".into());
46		self.0.result = Some(Err(error.clone()));
47		if let Some(mut supervisor) = self.0.supervisor.take() {
48			supervisor.panicked(error);
49		}
50	}
51}
52
53/// The protocol half of a machine, one variant per negotiated wire protocol.
54pub(crate) enum Protocol {
55	/// Boxed for size only.
56	Lite(Box<crate::lite::Driver>),
57	Ietf(crate::ietf::Driver),
58}
59
60/// The transport every session runs on, boxed once by `Client` or `Server`.
61pub(crate) type Transport = crate::transport::boxed::Session;
62
63/// Protocol and lifecycle work owned by the driver.
64pub(crate) struct State {
65	pub(crate) protocol: Protocol,
66	// The session supervisor, polled alongside the protocol: it executes the
67	// handles' close requests, publishes the transport's terminal error, and
68	// samples stats. It finishes once the transport reports closed (or a close
69	// this side sent outlives its grace unconfirmed), and the
70	// machine is not done until it has: the protocol's terminal transport close
71	// is what `Session::closed` observes, so resolving before it is published
72	// would leave waiters parked on a machine nobody polls again. `None` once
73	// finished, since a completed machine must not be polled again.
74	pub(crate) supervisor: Option<crate::session::Supervisor>,
75	// Cached so a poll after completion doesn't re-poll a finished protocol.
76	pub(crate) result: Option<Result<(), Error>>,
77}
78
79impl Driver {
80	pub(crate) fn new(clock: Deadlines, state: State) -> Self {
81		Self {
82			not_sync: std::marker::PhantomData,
83			state: std::cell::Cell::new(Box::new(state)),
84			clock,
85		}
86	}
87
88	/// Process ready work at `now`, registering for external activity.
89	///
90	/// Panics if `now` is earlier than the previous poll or construction time.
91	pub fn poll(&mut self, now: Instant, waiter: &kio::Waiter) -> Result<Option<Instant>, Error> {
92		let state = Polling(self.state.get_mut());
93		waiter.batch(|| {
94			self.clock.advance(now);
95			match state.0.poll(waiter) {
96				Poll::Ready(Ok(())) => Err(Error::Closed),
97				Poll::Ready(Err(err)) => Err(err),
98				Poll::Pending => Ok(self.clock.park(waiter)),
99			}
100		})
101	}
102}
103
104impl Protocol {
105	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
106		match self {
107			Self::Lite(driver) => driver.poll(waiter),
108			Self::Ietf(driver) => driver.poll(waiter),
109		}
110	}
111
112	fn close(&self) {
113		match self {
114			Self::Lite(driver) => driver.close(),
115			Self::Ietf(driver) => driver.withdrawal.begin(),
116		}
117	}
118
119	/// Whether the protocol owes the peer no queued data, so a draining close can
120	/// proceed.
121	fn drained(&self) -> bool {
122		match self {
123			Self::Lite(driver) => driver.drained(),
124			Self::Ietf(driver) => driver.drained(),
125		}
126	}
127}
128
129impl State {
130	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
131		if let Some(supervisor) = &mut self.supervisor
132			&& supervisor.poll(waiter).is_ready()
133		{
134			self.supervisor = None;
135		}
136
137		if self.supervisor.as_ref().is_some_and(|supervisor| supervisor.draining()) {
138			self.protocol.close();
139		}
140
141		if self.result.is_none() {
142			// The protocol's last act is closing the transport, and so is a drain
143			// once the protocol that just ran owes the peer nothing. Either wakes
144			// the supervisor's close watch; poll it now instead of waiting a turn.
145			let closed = match self.protocol.poll(waiter) {
146				Poll::Ready(result) => {
147					self.result = Some(result);
148					true
149				}
150				Poll::Pending => self
151					.supervisor
152					.as_mut()
153					.is_some_and(|supervisor| supervisor.poll_drain(self.protocol.drained(), waiter)),
154			};
155			if closed
156				&& let Some(supervisor) = &mut self.supervisor
157				&& supervisor.poll(waiter).is_ready()
158			{
159				self.supervisor = None;
160			}
161		}
162
163		match (&self.result, &self.supervisor) {
164			(Some(result), None) => Poll::Ready(result.clone()),
165			_ => Poll::Pending,
166		}
167	}
168}
169
170impl crate::time::Driver for Driver {
171	fn poll(&mut self, now: Instant, waiter: &kio::Waiter) -> Result<Option<Instant>, Error> {
172		self.poll(now, waiter)
173	}
174}
175
176impl std::fmt::Debug for Driver {
177	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178		f.debug_struct("Driver").finish_non_exhaustive()
179	}
180}
181
182// The relay and the bindings spawn drivers on multi-threaded runtimes. The fields prove `Send`
183// here, once, so a future holding the driver doesn't walk the whole session model again.
184// The exhaustive pattern fails to compile when a field is added without being checked.
185const _: () = {
186	fn assert_send<T: Send>(_: &T) {}
187	#[allow(dead_code, reason = "only type-checked, never called")]
188	fn fields(driver: &Driver) {
189		let Driver { not_sync, state, clock } = driver;
190		assert_send(not_sync);
191		assert_send(state);
192		assert_send(clock);
193	}
194};
195
196// SAFETY: the assertion above proves every field `Send`.
197unsafe impl Send for Driver {}