fetchlet_http/assets/
service.rs1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4use std::task::{Context, Poll};
5
6use bytes::Bytes;
7use http::header::{
8 ACCEPT_RANGES, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE, ETAG, LOCATION,
9};
10use http::{HeaderValue, Method, Request, Response, StatusCode};
11use http_body_util::{Either, Full};
12use tower_service::Service;
13
14use super::archive::{Asset, AssetArchive};
15use super::negotiate::{RangeRequest, accepts_brotli, decode_path, none_match, range};
16
17pub type AssetBody<B> = Either<Full<Bytes>, B>;
19
20#[derive(Clone, Debug)]
26pub struct AssetService<S> {
27 archive: Arc<AssetArchive>,
28 fallback: S,
29}
30
31impl<S> AssetService<S> {
32 pub fn new(archive: impl Into<Arc<AssetArchive>>, fallback: S) -> Self {
33 Self {
34 archive: archive.into(),
35 fallback,
36 }
37 }
38}
39
40impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for AssetService<S>
41where
42 S: Service<Request<ReqBody>, Response = Response<ResBody>>,
43{
44 type Response = Response<AssetBody<ResBody>>;
45 type Error = S::Error;
46 type Future = AssetFuture<S::Future, ResBody>;
47
48 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
49 self.fallback.poll_ready(cx)
50 }
51
52 fn call(&mut self, request: Request<ReqBody>) -> Self::Future {
53 if request.method() == Method::GET || request.method() == Method::HEAD {
54 let asset = decode_path(request.uri().path()).and_then(|path| {
55 self.archive
56 .get(&path)
57 .map(|asset| respond(asset, &request))
58 });
59 if let Some(response) = asset {
60 return AssetFuture::Ready(Some(response));
61 }
62 }
63 AssetFuture::Fallback(Box::pin(self.fallback.call(request)))
64 }
65}
66
67pub enum AssetFuture<F, B> {
69 Ready(Option<Response<Full<Bytes>>>),
70 #[doc(hidden)]
71 _Body(std::marker::PhantomData<fn() -> B>),
72 Fallback(Pin<Box<F>>),
73}
74
75impl<F, B, E> Future for AssetFuture<F, B>
76where
77 F: Future<Output = Result<Response<B>, E>>,
78{
79 type Output = Result<Response<AssetBody<B>>, E>;
80
81 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
82 match self.get_mut() {
83 AssetFuture::Ready(response) => {
84 let response = response.take().expect("polled after completion");
85 Poll::Ready(Ok(response.map(Either::Left)))
86 }
87 AssetFuture::Fallback(future) => future
88 .as_mut()
89 .poll(cx)
90 .map_ok(|response| response.map(Either::Right)),
91 AssetFuture::_Body(_) => unreachable!(),
92 }
93 }
94}
95
96fn respond<B>(asset: Asset<'_>, request: &Request<B>) -> Response<Full<Bytes>> {
98 let head = request.method() == Method::HEAD;
99 let brotli = asset.is_brotli() && accepts_brotli(request.headers());
100 let hash = hex(asset.hash());
101 let etag = if brotli {
102 format!("\"{hash}-br\"")
103 } else {
104 format!("\"{hash}\"")
105 };
106
107 let mut builder = Response::builder().status(asset.status());
108 let query = request.uri().query().filter(|_| asset.keeps_query());
109 for (name, value) in asset.headers() {
110 match query {
111 Some(query) if name == LOCATION => {
112 let mut location = value.as_bytes().to_vec();
113 location.push(b'?');
114 location.extend_from_slice(query.as_bytes());
115 match HeaderValue::from_bytes(&location) {
116 Ok(location) => builder = builder.header(name, location),
117 Err(_) => builder = builder.header(name, value),
118 }
119 }
120 _ => builder = builder.header(name, value),
121 }
122 }
123 let ok = asset.status() == StatusCode::OK;
124 if ok {
125 builder = builder.header(ETAG, &etag);
126 if none_match(request.headers(), &etag) {
127 return builder
128 .status(StatusCode::NOT_MODIFIED)
129 .body(Full::new(Bytes::new()))
130 .unwrap_or_else(|_| internal_error());
131 }
132 }
133
134 if brotli {
135 let body = asset.stored();
136 return finish(builder.header(CONTENT_ENCODING, "br"), body, head);
137 }
138 let body = match asset.decompressed() {
139 Ok(body) => body,
140 Err(_) => {
141 return finish(
142 Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR),
143 Bytes::new(),
144 head,
145 );
146 }
147 };
148 if !ok || asset.is_brotli() {
149 return finish(builder, body, head);
150 }
151 let size = body.len() as u64;
153 builder = builder.header(ACCEPT_RANGES, "bytes");
154 match range(request.headers(), size, &etag) {
155 RangeRequest::Whole => finish(builder, body, head),
156 RangeRequest::Satisfiable { start, end } => finish(
157 builder
158 .status(StatusCode::PARTIAL_CONTENT)
159 .header(CONTENT_RANGE, format!("bytes {start}-{end}/{size}")),
160 body.slice(start as usize..end as usize + 1),
161 head,
162 ),
163 RangeRequest::Unsatisfiable => finish(
164 builder
165 .status(StatusCode::RANGE_NOT_SATISFIABLE)
166 .header(CONTENT_RANGE, format!("bytes */{size}")),
167 Bytes::new(),
168 head,
169 ),
170 }
171}
172
173fn finish(builder: http::response::Builder, body: Bytes, empty: bool) -> Response<Full<Bytes>> {
176 let builder = builder.header(CONTENT_LENGTH, HeaderValue::from(body.len()));
177 let body = if empty { Bytes::new() } else { body };
178 builder
179 .body(Full::new(body))
180 .unwrap_or_else(|_| internal_error())
181}
182
183fn internal_error() -> Response<Full<Bytes>> {
184 let mut response = Response::new(Full::new(Bytes::new()));
185 *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
186 response
187}
188
189fn hex(bytes: &[u8]) -> String {
190 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
191}