Skip to main content

moq_net/
goaway.rs

1//! GOAWAY, the graceful drain signal.
2//!
3//! A session sends its own [Goaway] with `Session::goaway`, at most once, and
4//! observes the peer's on the [Consumer] from `Session::draining`.
5//!
6//! Draining works the same on a version with no GOAWAY message: the deadline is
7//! the sender's own timer, so it force-closes on schedule whether or not the peer
8//! could be told why. Callers do not branch on the negotiated version.
9//!
10//! Following the redirect is the caller's job. `moq_tokio::Connection` implements
11//! it for native clients.
12
13use std::{
14	sync::{
15		Arc,
16		atomic::{AtomicBool, Ordering},
17	},
18	task::Poll,
19	time::Duration,
20};
21
22use crate::{Error, Result};
23
24/// Maximum New Session URI length, in bytes. Both wires cap it here, and a
25/// receiver treats anything longer as a protocol violation.
26pub(crate) const MAX_URI: usize = 8192;
27const MAX_TIMEOUT_MS: u64 = (1 << 62) - 1;
28
29/// A GOAWAY: the sender intends to close the session soon and the peer should
30/// migrate its subscriptions elsewhere.
31#[derive(Clone, Default, PartialEq, Eq)]
32pub struct Goaway {
33	/// Where the peer should reconnect, including any credentials it needs.
34	/// Empty means reconnect to the same endpoint.
35	pub(crate) uri: String,
36
37	/// How long the sender waits before force-closing with
38	/// [`Error::GoawayTimeout`]. `None` means no deadline.
39	///
40	/// Only moq-transport carries this on the wire. Elsewhere it still
41	/// applies locally, so the sender enforces a deadline the peer cannot see.
42	pub(crate) timeout: Option<Duration>,
43}
44
45impl std::fmt::Debug for Goaway {
46	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47		f.debug_struct("Goaway")
48			.field("uri_len", &self.uri.len())
49			.field("timeout", &self.timeout)
50			.finish()
51	}
52}
53
54impl Goaway {
55	/// Tell the peer to reconnect to the same endpoint.
56	pub fn new() -> Self {
57		Self::default()
58	}
59
60	/// Tell the peer to reconnect to `uri`.
61	///
62	/// The URI must carry whatever credentials the peer needs: it is dialed as
63	/// given, and nothing from the current session is copied onto it.
64	pub fn redirect(uri: impl Into<String>) -> Self {
65		Self {
66			uri: uri.into(),
67			timeout: None,
68		}
69	}
70
71	/// Force-close the session with [`Error::GoawayTimeout`] if the peer is still
72	/// around after `timeout`, or never with `None` (the default).
73	///
74	/// Zero closes the session at once, without waiting for the GOAWAY to be written, so
75	/// the peer may never receive it or its redirect URI; a redirect needs a nonzero
76	/// timeout to arrive. Other values round up to the next millisecond and saturate at
77	/// the wire's 62-bit millisecond limit, so the local deadline agrees with what a
78	/// moq-transport peer receives.
79	pub fn with_timeout(mut self, timeout: Option<Duration>) -> Self {
80		self.timeout = timeout.map(|timeout| {
81			Duration::from_millis(timeout.as_nanos().div_ceil(1_000_000).min(u128::from(MAX_TIMEOUT_MS)) as u64)
82		});
83		self
84	}
85
86	/// The URI to reconnect to, or empty to reuse the current endpoint.
87	pub fn uri(&self) -> &str {
88		&self.uri
89	}
90
91	/// The drain deadline sent to the peer, if any.
92	pub fn timeout(&self) -> Option<Duration> {
93		self.timeout
94	}
95}
96
97/// Observes the peer's GOAWAY.
98///
99/// Obtained from `Session::draining`. Cheap to
100/// clone; every clone reports the same GOAWAY.
101#[derive(Clone)]
102pub struct Consumer {
103	state: kio::Consumer<Option<Goaway>>,
104}
105
106impl Consumer {
107	/// Poll for the peer's GOAWAY.
108	///
109	/// `Ready(Err)` once the session closes without one, so a caller can stop
110	/// watching rather than parking forever.
111	pub fn poll(&self, waiter: &kio::Waiter) -> Poll<Result<Goaway>> {
112		match self.state.poll(waiter, |state| match &**state {
113			Some(goaway) => Poll::Ready(goaway.clone()),
114			None => Poll::Pending,
115		}) {
116			Poll::Ready(Ok(goaway)) => Poll::Ready(Ok(goaway)),
117			Poll::Ready(Err(_)) => Poll::Ready(Err(Error::Closed)),
118			Poll::Pending => Poll::Pending,
119		}
120	}
121}
122
123/// The receive-side GOAWAY signal handed to a subscriber.
124///
125/// Carries the flag and the channel together because a subscriber needs both: an
126/// atomic load when pricing each received announcement (the hot path, which is
127/// why the flag is not merely a read of the channel), and a wakeup for the
128/// per-source tasks, which have to react to a peer that drains and then goes quiet.
129#[derive(Clone)]
130pub(crate) struct GoingAway {
131	flag: Arc<AtomicBool>,
132	received: Consumer,
133}
134
135impl GoingAway {
136	/// Mark the session as going away, returning whether this was the first time.
137	pub fn set(&self) -> bool {
138		!self.flag.swap(true, Ordering::AcqRel)
139	}
140
141	/// Whether a GOAWAY has been received.
142	pub fn is_set(&self) -> bool {
143		self.flag.load(Ordering::Acquire)
144	}
145
146	/// Poll for the peer's GOAWAY, so a loop already polling other sources can
147	/// react to a draining peer instead of waiting on a message it may never send.
148	///
149	/// Stays `Ready` once set, so a caller must treat what it does in response as
150	/// idempotent rather than as an edge.
151	pub fn poll(&self, waiter: &kio::Waiter) -> Poll<()> {
152		// Presence only, rather than [`Consumer::poll`]: this stays ready for the rest
153		// of the session, and every wakeup of every per-source task would otherwise
154		// clone the URI just to throw it away.
155		match self.received.state.poll(waiter, |state| match &**state {
156			Some(_) => Poll::Ready(()),
157			None => Poll::Pending,
158		}) {
159			Poll::Ready(Ok(())) => Poll::Ready(()),
160			// The session closed without a GOAWAY. Nothing is draining, and the
161			// caller's own loop is about to end on the same close.
162			Poll::Ready(Err(_)) => Poll::Pending,
163			Poll::Pending => Poll::Pending,
164		}
165	}
166}
167
168/// A detached signal for tests that build a subscriber without a session. Its
169/// channel is already closed, so it never reports a GOAWAY.
170#[cfg(test)]
171impl Default for GoingAway {
172	fn default() -> Self {
173		let received = kio::Producer::new(None);
174		Self {
175			flag: Default::default(),
176			received: Consumer {
177				state: received.consume(),
178			},
179		}
180	}
181}
182
183/// The halves handed to a protocol driver's `start()`.
184#[derive(Clone)]
185pub(crate) struct Protocol {
186	/// Awaited by the driver's send path; firing means "encode and send GOAWAY now".
187	trigger: kio::Consumer<Option<Goaway>>,
188	/// Written by the driver's receive path when a GOAWAY is decoded.
189	received: kio::Producer<Option<Goaway>>,
190	/// Set alongside `received`; ranks this session's routes last.
191	pub going_away: GoingAway,
192}
193
194impl Protocol {
195	/// Record a decoded GOAWAY.
196	///
197	/// # Errors
198	///
199	/// Returns [`Error::ProtocolViolation`] on a second GOAWAY, which both drafts
200	/// require the session be closed over (draft-22 section 9.2). Keeping the first
201	/// payload instead would leave an observer acting on a URI the peer has since
202	/// replaced, with no way to tell.
203	pub fn record(&self, goaway: Goaway) -> Result<()> {
204		if !self.going_away.set() {
205			return Err(Error::ProtocolViolation);
206		}
207		if let Ok(mut state) = self.received.write() {
208			*state = Some(goaway);
209		}
210		Ok(())
211	}
212
213	/// Poll for the send trigger firing, returning the GOAWAY to encode.
214	///
215	/// `None` if the trigger was dropped without firing (the session is closing
216	/// without a drain), so nothing should be sent.
217	pub fn poll_triggered(&self, waiter: &kio::Waiter) -> Poll<Option<Goaway>> {
218		match self.trigger.poll(waiter, |state| match &**state {
219			Some(goaway) => Poll::Ready(goaway.clone()),
220			None => Poll::Pending,
221		}) {
222			Poll::Ready(Ok(goaway)) => Poll::Ready(Some(goaway)),
223			Poll::Ready(Err(_)) => Poll::Ready(None),
224			Poll::Pending => Poll::Pending,
225		}
226	}
227}
228
229/// The drain deadline, watched independently of the wire's send progress.
230///
231/// Armed from the instant of the driver poll that observes the send, which the
232/// send wakes. The queue's instant at the send itself is the driver's last poll,
233/// as stale as the session has been idle, so arming from it would cut the peer's
234/// window short.
235pub(crate) struct Deadline {
236	runtime: crate::time::Deadlines,
237	trigger: Option<kio::Consumer<Option<Goaway>>>,
238	armed: Option<(crate::time::Deadline, Duration)>,
239}
240
241impl Deadline {
242	/// Ready with the timeout once it expires, or without one if nothing is to enforce.
243	pub fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Option<Duration>> {
244		if let Some(trigger) = &self.trigger {
245			let timeout = match std::task::ready!(trigger.poll(waiter, |state| match &**state {
246				Some(goaway) => Poll::Ready(goaway.timeout),
247				None => Poll::Pending,
248			})) {
249				Ok(timeout) => timeout,
250				Err(_) => return Poll::Ready(None),
251			};
252			self.trigger = None;
253			self.armed = timeout.map(|timeout| (crate::time::Deadline::after(&self.runtime, timeout), timeout));
254		}
255		let Some((deadline, timeout)) = &mut self.armed else {
256			return Poll::Ready(None);
257		};
258		std::task::ready!(deadline.poll(waiter));
259		Poll::Ready(Some(*timeout))
260	}
261}
262
263/// The halves held by the public [`crate::Session`].
264pub(crate) struct Handle {
265	/// Fired once by [`Self::send`].
266	trigger: kio::Producer<Option<Goaway>>,
267	/// Whether this side may name a redirect URI in its own GOAWAY.
268	redirect: bool,
269	/// Handed out by `crate::Session::draining`.
270	consumer: Consumer,
271}
272
273impl Handle {
274	/// Create the session-side handle and its protocol-side counterpart.
275	///
276	/// `redirect` is whether this side may name a URI in its own GOAWAY.
277	pub fn new(redirect: bool) -> (Self, Protocol) {
278		let trigger = kio::Producer::new(None);
279		let received = kio::Producer::new(None);
280		let consumer = Consumer {
281			state: received.consume(),
282		};
283		let going_away = GoingAway {
284			flag: Default::default(),
285			received: consumer.clone(),
286		};
287
288		let handle = Self {
289			trigger: trigger.clone(),
290			redirect,
291			consumer,
292		};
293		let protocol = Protocol {
294			trigger: trigger.consume(),
295			received,
296			going_away,
297		};
298
299		(handle, protocol)
300	}
301
302	/// Send this session's GOAWAY; see `crate::Session::goaway`.
303	pub fn send(&self, goaway: Goaway) -> Result<()> {
304		if !self.redirect && !goaway.uri.is_empty() {
305			return Err(Error::ProtocolViolation);
306		}
307		// Both wires cap the URI, so sending a longer one would just get the session
308		// closed by the peer. Refuse it here, the one chokepoint both wires funnel
309		// through, rather than at each encoder.
310		if goaway.uri.len() > MAX_URI {
311			return Err(Error::ProtocolViolation);
312		}
313		// The session closing first is not an error: there is nothing left to drain.
314		if let Ok(mut state) = self.trigger.write() {
315			if state.is_some() {
316				return Err(Error::Duplicate);
317			}
318			*state = Some(goaway);
319		}
320		Ok(())
321	}
322
323	/// Watch the local deadline on the driver's `runtime` without holding up the protocol's writes.
324	pub fn deadline(&self, runtime: &crate::time::Deadlines) -> Deadline {
325		Deadline {
326			runtime: runtime.clone(),
327			trigger: Some(self.trigger.consume()),
328			armed: None,
329		}
330	}
331
332	/// A fresh handle on the receive half.
333	pub fn consumer(&self) -> Consumer {
334		self.consumer.clone()
335	}
336
337	/// Whether either side sent a GOAWAY, so the session is draining.
338	pub fn draining(&self) -> bool {
339		self.trigger.read().is_some() || self.consumer.state.read().is_some()
340	}
341}
342
343#[cfg(test)]
344mod tests {
345	use super::*;
346
347	/// A session idle since its last poll still gives the peer the full timeout:
348	/// the window opens at the poll that observes the send, not the stale last one.
349	#[test]
350	fn an_idle_session_gives_the_peer_the_whole_timeout() {
351		let runtime = crate::time::Deadlines::new(crate::time::Instant::ZERO);
352		let (handle, _protocol) = Handle::new(true);
353		let mut deadline = handle.deadline(&runtime);
354		let waiter = kio::Waiter::noop();
355		assert!(deadline.poll(&waiter).is_pending());
356
357		handle
358			.send(Goaway::new().with_timeout(Some(Duration::from_secs(1))))
359			.unwrap();
360		let sent = crate::time::Instant::ZERO.saturating_add(Duration::from_secs(5));
361		runtime.advance(sent);
362		assert!(deadline.poll(&waiter).is_pending());
363		runtime.advance(
364			sent.saturating_add(Duration::from_secs(1))
365				.saturating_sub(Duration::from_nanos(1)),
366		);
367		assert!(deadline.poll(&waiter).is_pending());
368		runtime.advance(sent.saturating_add(Duration::from_secs(1)));
369		assert_eq!(deadline.poll(&waiter), Poll::Ready(Some(Duration::from_secs(1))));
370	}
371
372	/// A session sends at most one GOAWAY. Handing out the handle is always
373	/// allowed, so a caller never has to ask whether the slot is free; sending
374	/// twice is what gets refused, and the first payload is the one kept.
375	#[test]
376	fn only_the_first_send_wins() {
377		let (handle, protocol) = Handle::new(true);
378
379		handle.send(Goaway::redirect("https://first.example/")).unwrap();
380
381		let err = handle.send(Goaway::redirect("https://second.example/")).unwrap_err();
382		assert!(matches!(err, Error::Duplicate));
383
384		assert_eq!(
385			protocol.trigger.read().as_ref().map(|g| g.uri.as_str()),
386			Some("https://first.example/"),
387			"the peer must not see a URI replaced out from under it"
388		);
389	}
390
391	/// A moq-transport client cannot tell a server where to reconnect, so naming a
392	/// URI is refused locally rather than getting the session closed by the peer.
393	#[test]
394	fn client_redirect_is_refused() {
395		let (handle, _protocol) = Handle::new(false);
396		let err = handle
397			.send(Goaway {
398				uri: "https://elsewhere.example/".to_string(),
399				..Default::default()
400			})
401			.unwrap_err();
402		assert!(matches!(err, Error::ProtocolViolation));
403
404		// An empty URI ("I am going away") is still allowed.
405		let (handle, _protocol) = Handle::new(false);
406		handle.send(Goaway::default()).unwrap();
407	}
408
409	#[test]
410	fn timeout_matches_wire_milliseconds() {
411		assert_eq!(Goaway::new().with_timeout(None).timeout(), None);
412		assert_eq!(
413			Goaway::new().with_timeout(Some(Duration::ZERO)).timeout(),
414			Some(Duration::ZERO)
415		);
416		assert_eq!(
417			Goaway::new().with_timeout(Some(Duration::from_micros(1))).timeout(),
418			Some(Duration::from_millis(1))
419		);
420		assert_eq!(
421			Goaway::new().with_timeout(Some(Duration::MAX)).timeout(),
422			Some(Duration::from_millis(MAX_TIMEOUT_MS))
423		);
424	}
425
426	/// A zero timeout closes the session at once, not never.
427	#[test]
428	fn a_zero_timeout_closes_at_once() {
429		let runtime = crate::time::Deadlines::new(crate::time::Instant::ZERO);
430		let (handle, _protocol) = Handle::new(true);
431		let mut deadline = handle.deadline(&runtime);
432		let waiter = kio::Waiter::noop();
433		handle.send(Goaway::new().with_timeout(Some(Duration::ZERO))).unwrap();
434		assert_eq!(deadline.poll(&waiter), Poll::Ready(Some(Duration::ZERO)));
435	}
436
437	/// A URI past the wire cap is refused at the send chokepoint rather than
438	/// reaching an encoder that would frame it wrong.
439	#[test]
440	fn oversized_uri_is_refused() {
441		let (handle, _protocol) = Handle::new(true);
442		let err = handle.send(Goaway::redirect("x".repeat(MAX_URI + 1))).unwrap_err();
443		assert!(matches!(err, Error::ProtocolViolation));
444
445		let (handle, _protocol) = Handle::new(true);
446		handle
447			.send(Goaway::redirect("x".repeat(MAX_URI)))
448			.expect("exactly at the cap is fine");
449	}
450
451	/// A second GOAWAY is a protocol violation, not something to log and discard.
452	#[test]
453	fn duplicate_is_a_protocol_violation() {
454		let (_handle, protocol) = Handle::new(true);
455		protocol.record(Goaway::default()).unwrap();
456		let err = protocol.record(Goaway::default()).unwrap_err();
457		assert!(matches!(err, Error::ProtocolViolation));
458	}
459
460	/// The consumer reports the recorded GOAWAY once it arrives.
461	#[test]
462	fn consumer_observes_the_recorded_goaway() {
463		let (handle, protocol) = Handle::new(true);
464		let consumer = handle.consumer();
465		assert!(consumer.poll(&kio::Waiter::noop()).is_pending());
466
467		let goaway = Goaway {
468			uri: "https://elsewhere.example/".to_string(),
469			timeout: Some(Duration::from_secs(5)),
470		};
471		protocol.record(goaway.clone()).unwrap();
472
473		let Poll::Ready(Ok(received)) = consumer.poll(&kio::Waiter::noop()) else {
474			panic!("the recorded GOAWAY");
475		};
476		assert_eq!(received, goaway);
477	}
478
479	/// A session that closes without a GOAWAY resolves the poll rather than parking
480	/// forever, so a caller watching for one can stop.
481	#[test]
482	fn poll_resolves_when_the_session_closes() {
483		let (handle, protocol) = Handle::new(true);
484		let consumer = handle.consumer();
485		drop(protocol);
486		assert!(matches!(
487			consumer.poll(&kio::Waiter::noop()),
488			Poll::Ready(Err(Error::Closed))
489		));
490	}
491}