Skip to content

Commit 53fd3ea

Browse files
committed
Run cancelled NARInfo requests to sub60's cache to completion
1 parent ca6ded6 commit 53fd3ea

4 files changed

Lines changed: 129 additions & 24 deletions

File tree

‎src/any_cache.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use crate::noop_cache::NoopCache;
88
use crate::protocol::StoreDir;
99
use crate::run::RunArgs;
1010
use crate::sub60_cache::{Sub60Cache, Sub60CacheConnectError};
11+
use crate::tokio::TokioSpawner;
1112

1213
#[derive(Clone)]
1314
pub(crate) enum AnyCache {
@@ -32,11 +33,12 @@ pub(crate) enum AnyCacheError {
3233
impl AnyCache {
3334
pub(crate) async fn new(
3435
args: &RunArgs,
36+
spawner: TokioSpawner,
3537
) -> Result<Self, Sub60CacheConnectError> {
3638
match args.cache {
3739
AnyCacheKind::Noop => Ok(NoopCache::default().into()),
3840
AnyCacheKind::Sub60 => {
39-
Sub60Cache::connect(args).await.map(Into::into)
41+
Sub60Cache::connect(args, spawner).await.map(Into::into)
4042
},
4143
}
4244
}

‎src/run.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,14 @@ async fn start(
104104
let nix_store = NixStore::open().map_err(StartError::OpenNixStore)?;
105105

106106
#[cfg(not(feature = "sub60-cache"))]
107-
let cache = crate::any_cache::AnyCache::new(&args)
107+
let cache = crate::any_cache::AnyCache::new(&args, spawner.clone())
108108
.await
109109
.map_err(StartError::ConnectToCache)?;
110110

111111
#[cfg(feature = "sub60-cache")]
112-
let cache =
113-
Sub60Cache::connect(&args).await.map_err(StartError::ConnectToCache)?;
112+
let cache = Sub60Cache::connect(&args, spawner.clone())
113+
.await
114+
.map_err(StartError::ConnectToCache)?;
114115

115116
let mut ctx = RealContext::new(nix_store, spawner);
116117

‎src/sub60_cache.rs‎

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use std::sync::LazyLock;
99
use std::time::{SystemTime, UNIX_EPOCH};
1010

1111
use bytes::{Bytes, BytesMut};
12-
use futures::AsyncRead;
12+
use futures::{AsyncRead, FutureExt};
1313
use nix_types::{NarFileName, NarInfo, NarInfoFileName};
1414
use reqwest::{Method, StatusCode, header};
1515
use smallvec::SmallVec;
@@ -27,6 +27,7 @@ use crate::async_read_ext::AsyncReadExt;
2727
use crate::context;
2828
use crate::protocol::StoreDir;
2929
use crate::run::RunArgs;
30+
use crate::tokio::TokioSpawner;
3031

3132
type AuthToken = String;
3233

@@ -37,6 +38,7 @@ static SUB60_CACHE_URL: LazyLock<url::Url> =
3738
pub(crate) struct Sub60Cache {
3839
cache_url: url::Url,
3940
client: reqwest::Client,
41+
spawner: TokioSpawner,
4042
}
4143

4244
#[derive(Debug, clap::Args)]
@@ -129,6 +131,7 @@ impl Sub60Cache {
129131
/// TODO: docs.
130132
pub(crate) async fn connect(
131133
RunArgs { sub60_cache_args: args, .. }: &RunArgs,
134+
spawner: TokioSpawner,
132135
) -> Result<Self, Sub60CacheConnectError> {
133136
let mut cache_url = SUB60_CACHE_URL.clone();
134137
cache_url
@@ -141,7 +144,7 @@ impl Sub60Cache {
141144
.build()
142145
.map_err(Sub60CacheConnectError::BuildHttpClient)?;
143146

144-
Ok(Self { cache_url, client })
147+
Ok(Self { cache_url, client, spawner })
145148
}
146149

147150
async fn initiate_multipart_nar_upload(
@@ -432,27 +435,46 @@ impl CacheRequestError {
432435
impl context::Cache for Sub60Cache {
433436
type Error = CacheRequestError;
434437

435-
async fn has_narinfo(
438+
fn has_narinfo(
436439
&self,
437440
narinfo_filename: &NarInfoFileName,
438-
) -> Result<bool, Self::Error> {
441+
) -> impl Future<Output = Result<bool, Self::Error>> + Send {
439442
let url = self.narinfo_url(narinfo_filename);
440443

441-
let response =
442-
self.client.head(url.clone()).send().await.map_err(|source| {
443-
CacheRequestError::HttpRequest { method: Method::HEAD, source }
444-
})?;
445-
446-
match response.status() {
447-
StatusCode::OK => Ok(true),
448-
StatusCode::NOT_FOUND => Ok(false),
449-
_ => Err(CacheRequestError::unexpected_response(
450-
response,
451-
Method::HEAD,
452-
url,
453-
)
454-
.await),
455-
}
444+
#[expect(clippy::result_large_err)]
445+
let future =
446+
self.client.head(url.clone()).send().map(
447+
move |result| match result.map(|resp| resp.status()) {
448+
Ok(StatusCode::OK) => Ok(true),
449+
Ok(StatusCode::NOT_FOUND) => Ok(false),
450+
Ok(status) => Err(CacheRequestError::UnexpectedResponse {
451+
method: Method::HEAD,
452+
status,
453+
url,
454+
body: String::new(),
455+
}),
456+
Err(source) => Err(CacheRequestError::HttpRequest {
457+
method: Method::HEAD,
458+
source,
459+
}),
460+
},
461+
);
462+
463+
// The caller will race this NARInfo lookup against the upstream caches
464+
// and intentionally drops the losing future. Dropping an in-flight
465+
// HTTP/2 request causes reqwest to terminate the corresponding stream
466+
// by sending an RST_STREAM frame. When handling many paths in rapid
467+
// succession, if the upstream lookups repeatedly win their races, this
468+
// produces a burst of resets on the single multiplexed connection to
469+
// cache.sub60.dev. Cloudflare treats that pattern as an HTTP/2 Rapid
470+
// Reset attack and closes the entire connection, taking unrelated
471+
// NARInfo lookups down with it (see
472+
// <https://blog.cloudflare.com/technical-breakdown-http2-rapid-reset-ddos-attack/>
473+
// for details).
474+
//
475+
// To prevent this, we let the lookup run to completion even if the
476+
// caller drops the future.
477+
self.spawner.run_to_completion(future)
456478
}
457479

458480
async fn upload_nar(

‎src/tokio.rs‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ use core::pin::Pin;
22
use core::task::{Context, Poll, ready};
33
use std::panic;
44

5+
use pin_project_lite::pin_project;
6+
57
use crate::context;
8+
use crate::context::{JoinHandle as _, Spawner as _};
69

710
pub(crate) struct Tokio {
811
inner: tokio::runtime::Runtime,
@@ -13,13 +16,25 @@ pub(crate) struct TokioSpawner {
1316
inner: tokio::runtime::Handle,
1417
}
1518

16-
pin_project_lite::pin_project! {
19+
pin_project! {
1720
pub(crate) struct TokioJoinHandle<T> {
1821
#[pin]
1922
inner: tokio::task::JoinHandle<T>,
2023
}
2124
}
2225

26+
/// Future returned by the
27+
/// [`run_to_completion`](TokioSpawner::run_to_completion) method.
28+
pub(crate) struct RunToCompletion<Fut>
29+
where
30+
Fut: Future + Send + Unpin + 'static,
31+
Fut::Output: Send + 'static,
32+
{
33+
future: Option<Fut>,
34+
spawner: TokioSpawner,
35+
spawn_on_drop: bool,
36+
}
37+
2338
impl Tokio {
2439
pub(crate) fn block_on<Fut: Future>(&self, future: Fut) -> Fut::Output {
2540
self.inner.block_on(future)
@@ -40,6 +55,26 @@ impl Tokio {
4055
}
4156
}
4257

58+
impl TokioSpawner {
59+
/// Returns a wrapper around the given future which, if dropped after it
60+
/// returns [`Poll::Pending`], moves it to a newly spawned task and polls it
61+
/// to completion. Completed and never-polled futures are dropped normally.
62+
pub(crate) fn run_to_completion<Fut>(
63+
&self,
64+
future: Fut,
65+
) -> RunToCompletion<Fut>
66+
where
67+
Fut: Future + Send + Unpin + 'static,
68+
Fut::Output: Send + 'static,
69+
{
70+
RunToCompletion {
71+
future: Some(future),
72+
spawner: self.clone(),
73+
spawn_on_drop: false,
74+
}
75+
}
76+
}
77+
4378
impl context::Spawner for TokioSpawner {
4479
type JoinHandle<Fut: Future> = TokioJoinHandle<Fut::Output>;
4580

@@ -66,3 +101,48 @@ impl<T> Future for TokioJoinHandle<T> {
66101
impl<T> context::JoinHandle<T> for TokioJoinHandle<T> {
67102
fn detach(self) {}
68103
}
104+
105+
impl<Fut> Future for RunToCompletion<Fut>
106+
where
107+
Fut: Future + Send + Unpin + 'static,
108+
Fut::Output: Send + 'static,
109+
{
110+
type Output = Fut::Output;
111+
112+
fn poll(
113+
mut self: Pin<&mut Self>,
114+
ctx: &mut Context<'_>,
115+
) -> Poll<Self::Output> {
116+
let this = self.as_mut().get_mut();
117+
118+
// Reset it to false before every poll to avoid respawning a future
119+
// whose poll panicked.
120+
this.spawn_on_drop = false;
121+
122+
let result = Pin::new(
123+
this.future.as_mut().expect("always present until dropped"),
124+
)
125+
.poll(ctx);
126+
127+
match result {
128+
Poll::Ready(output) => Poll::Ready(output),
129+
Poll::Pending => {
130+
this.spawn_on_drop = true;
131+
Poll::Pending
132+
},
133+
}
134+
}
135+
}
136+
137+
impl<Fut> Drop for RunToCompletion<Fut>
138+
where
139+
Fut: Future + Send + Unpin + 'static,
140+
Fut::Output: Send + 'static,
141+
{
142+
fn drop(&mut self) {
143+
if self.spawn_on_drop {
144+
let future = self.future.take().expect("only taken on Drop");
145+
self.spawner.spawn(future).detach();
146+
}
147+
}
148+
}

0 commit comments

Comments
 (0)