1use std::{
14 sync::{
15 Arc,
16 atomic::{AtomicBool, Ordering},
17 },
18 task::Poll,
19 time::Duration,
20};
21
22use crate::{Error, Result};
23
24pub(crate) const MAX_URI: usize = 8192;
27const MAX_TIMEOUT_MS: u64 = (1 << 62) - 1;
28
29#[derive(Clone, Default, PartialEq, Eq)]
32pub struct Goaway {
33 pub(crate) uri: String,
36
37 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 pub fn new() -> Self {
57 Self::default()
58 }
59
60 pub fn redirect(uri: impl Into<String>) -> Self {
65 Self {
66 uri: uri.into(),
67 timeout: None,
68 }
69 }
70
71 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 pub fn uri(&self) -> &str {
88 &self.uri
89 }
90
91 pub fn timeout(&self) -> Option<Duration> {
93 self.timeout
94 }
95}
96
97#[derive(Clone)]
102pub struct Consumer {
103 state: kio::Consumer<Option<Goaway>>,
104}
105
106impl Consumer {
107 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#[derive(Clone)]
130pub(crate) struct GoingAway {
131 flag: Arc<AtomicBool>,
132 received: Consumer,
133}
134
135impl GoingAway {
136 pub fn set(&self) -> bool {
138 !self.flag.swap(true, Ordering::AcqRel)
139 }
140
141 pub fn is_set(&self) -> bool {
143 self.flag.load(Ordering::Acquire)
144 }
145
146 pub fn poll(&self, waiter: &kio::Waiter) -> Poll<()> {
152 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 Poll::Ready(Err(_)) => Poll::Pending,
163 Poll::Pending => Poll::Pending,
164 }
165 }
166}
167
168#[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#[derive(Clone)]
185pub(crate) struct Protocol {
186 trigger: kio::Consumer<Option<Goaway>>,
188 received: kio::Producer<Option<Goaway>>,
190 pub going_away: GoingAway,
192}
193
194impl Protocol {
195 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 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
229pub(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 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
263pub(crate) struct Handle {
265 trigger: kio::Producer<Option<Goaway>>,
267 redirect: bool,
269 consumer: Consumer,
271}
272
273impl Handle {
274 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 pub fn send(&self, goaway: Goaway) -> Result<()> {
304 if !self.redirect && !goaway.uri.is_empty() {
305 return Err(Error::ProtocolViolation);
306 }
307 if goaway.uri.len() > MAX_URI {
311 return Err(Error::ProtocolViolation);
312 }
313 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 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 pub fn consumer(&self) -> Consumer {
334 self.consumer.clone()
335 }
336
337 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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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}