2023-04-22 13:48:21 -04:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2023-05-10 10:23:26 -04:00
|
|
|
use crate::compressible::is_content_compressible;
|
2023-04-22 13:48:21 -04:00
|
|
|
use crate::extract_network_stream;
|
2023-04-24 17:24:40 -04:00
|
|
|
use crate::network_buffered_stream::NetworkStreamPrefixCheck;
|
2023-04-22 13:48:21 -04:00
|
|
|
use crate::request_body::HttpRequestBody;
|
|
|
|
use crate::request_properties::HttpConnectionProperties;
|
|
|
|
use crate::request_properties::HttpListenProperties;
|
|
|
|
use crate::request_properties::HttpPropertyExtractor;
|
2023-05-10 07:23:14 -04:00
|
|
|
use crate::response_body::Compression;
|
2023-04-22 13:48:21 -04:00
|
|
|
use crate::response_body::ResponseBytes;
|
|
|
|
use crate::response_body::ResponseBytesInner;
|
|
|
|
use crate::response_body::V8StreamHttpResponseBody;
|
2023-05-16 19:00:59 -04:00
|
|
|
use crate::slab::slab_drop;
|
|
|
|
use crate::slab::slab_get;
|
|
|
|
use crate::slab::slab_insert;
|
|
|
|
use crate::slab::SlabId;
|
2023-04-26 18:58:18 -04:00
|
|
|
use crate::websocket_upgrade::WebSocketUpgrade;
|
2023-04-22 13:48:21 -04:00
|
|
|
use crate::LocalExecutor;
|
2023-05-10 07:23:14 -04:00
|
|
|
use cache_control::CacheControl;
|
2023-04-22 13:48:21 -04:00
|
|
|
use deno_core::error::AnyError;
|
|
|
|
use deno_core::futures::TryFutureExt;
|
|
|
|
use deno_core::op;
|
2023-05-14 17:40:01 -04:00
|
|
|
use deno_core::task::spawn;
|
|
|
|
use deno_core::task::JoinHandle;
|
2023-04-22 13:48:21 -04:00
|
|
|
use deno_core::AsyncRefCell;
|
2023-04-26 18:58:18 -04:00
|
|
|
use deno_core::AsyncResult;
|
2023-04-22 13:48:21 -04:00
|
|
|
use deno_core::ByteString;
|
|
|
|
use deno_core::CancelFuture;
|
|
|
|
use deno_core::CancelHandle;
|
|
|
|
use deno_core::CancelTryFuture;
|
|
|
|
use deno_core::OpState;
|
|
|
|
use deno_core::RcRef;
|
|
|
|
use deno_core::Resource;
|
|
|
|
use deno_core::ResourceId;
|
|
|
|
use deno_net::ops_tls::TlsStream;
|
|
|
|
use deno_net::raw::NetworkStream;
|
2023-05-15 19:24:41 -04:00
|
|
|
use deno_websocket::ws_create_server_stream;
|
2023-05-10 07:23:14 -04:00
|
|
|
use fly_accept_encoding::Encoding;
|
|
|
|
use http::header::ACCEPT_ENCODING;
|
|
|
|
use http::header::CACHE_CONTROL;
|
|
|
|
use http::header::CONTENT_ENCODING;
|
|
|
|
use http::header::CONTENT_LENGTH;
|
|
|
|
use http::header::CONTENT_RANGE;
|
|
|
|
use http::header::CONTENT_TYPE;
|
|
|
|
use http::HeaderMap;
|
2023-04-22 13:48:21 -04:00
|
|
|
use hyper1::body::Incoming;
|
|
|
|
use hyper1::header::COOKIE;
|
|
|
|
use hyper1::http::HeaderName;
|
|
|
|
use hyper1::http::HeaderValue;
|
|
|
|
use hyper1::server::conn::http1;
|
|
|
|
use hyper1::server::conn::http2;
|
|
|
|
use hyper1::service::service_fn;
|
2023-04-24 17:24:40 -04:00
|
|
|
use hyper1::service::HttpService;
|
2023-04-26 18:58:18 -04:00
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
use hyper1::StatusCode;
|
2023-06-01 10:07:26 -04:00
|
|
|
use once_cell::sync::Lazy;
|
2023-04-22 13:48:21 -04:00
|
|
|
use pin_project::pin_project;
|
|
|
|
use pin_project::pinned_drop;
|
|
|
|
use std::borrow::Cow;
|
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::future::Future;
|
|
|
|
use std::io;
|
|
|
|
use std::pin::Pin;
|
|
|
|
use std::rc::Rc;
|
2023-04-26 18:58:18 -04:00
|
|
|
|
|
|
|
use tokio::io::AsyncReadExt;
|
|
|
|
use tokio::io::AsyncWriteExt;
|
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
type Request = hyper1::Request<Incoming>;
|
|
|
|
type Response = hyper1::Response<ResponseBytes>;
|
|
|
|
|
2023-06-01 10:07:26 -04:00
|
|
|
static USE_WRITEV: Lazy<bool> = Lazy::new(|| {
|
|
|
|
let disable_writev = std::env::var("DENO_HYPER_USE_WRITEV").ok();
|
|
|
|
|
|
|
|
if let Some(val) = disable_writev {
|
|
|
|
return val != "0";
|
|
|
|
}
|
|
|
|
|
|
|
|
true
|
|
|
|
});
|
|
|
|
|
2023-04-24 17:24:40 -04:00
|
|
|
/// All HTTP/2 connections start with this byte string.
|
|
|
|
///
|
|
|
|
/// In HTTP/2, each endpoint is required to send a connection preface as a final confirmation
|
|
|
|
/// of the protocol in use and to establish the initial settings for the HTTP/2 connection. The
|
|
|
|
/// client and server each send a different connection preface.
|
|
|
|
///
|
|
|
|
/// The client connection preface starts with a sequence of 24 octets, which in hex notation is:
|
|
|
|
///
|
|
|
|
/// 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a
|
|
|
|
///
|
|
|
|
/// That is, the connection preface starts with the string PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n). This sequence
|
|
|
|
/// MUST be followed by a SETTINGS frame (Section 6.5), which MAY be empty.
|
|
|
|
const HTTP2_PREFIX: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
|
|
|
|
|
|
|
|
/// ALPN negotation for "h2"
|
|
|
|
const TLS_ALPN_HTTP_2: &[u8] = b"h2";
|
|
|
|
|
|
|
|
/// ALPN negotation for "http/1.1"
|
|
|
|
const TLS_ALPN_HTTP_11: &[u8] = b"http/1.1";
|
|
|
|
|
|
|
|
/// Name a trait for streams we can serve HTTP over.
|
|
|
|
trait HttpServeStream:
|
|
|
|
tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static
|
|
|
|
{
|
|
|
|
}
|
|
|
|
impl<
|
|
|
|
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
|
|
|
|
> HttpServeStream for S
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
#[op]
|
2023-05-08 17:07:45 -04:00
|
|
|
pub fn op_http_upgrade_raw(
|
2023-04-26 18:58:18 -04:00
|
|
|
state: &mut OpState,
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-04-26 18:58:18 -04:00
|
|
|
) -> Result<ResourceId, AnyError> {
|
|
|
|
// Stage 1: extract the upgrade future
|
2023-05-16 19:00:59 -04:00
|
|
|
let upgrade = slab_get(slab_id).upgrade()?;
|
2023-04-26 18:58:18 -04:00
|
|
|
let (read, write) = tokio::io::duplex(1024);
|
|
|
|
let (read_rx, write_tx) = tokio::io::split(read);
|
|
|
|
let (mut write_rx, mut read_tx) = tokio::io::split(write);
|
2023-05-14 17:40:01 -04:00
|
|
|
spawn(async move {
|
2023-04-26 18:58:18 -04:00
|
|
|
let mut upgrade_stream = WebSocketUpgrade::<ResponseBytes>::default();
|
|
|
|
|
|
|
|
// Stage 2: Extract the Upgraded connection
|
|
|
|
let mut buf = [0; 1024];
|
|
|
|
let upgraded = loop {
|
|
|
|
let read = Pin::new(&mut write_rx).read(&mut buf).await?;
|
|
|
|
match upgrade_stream.write(&buf[..read]) {
|
|
|
|
Ok(None) => continue,
|
|
|
|
Ok(Some((response, bytes))) => {
|
2023-05-16 19:00:59 -04:00
|
|
|
let mut http = slab_get(slab_id);
|
|
|
|
*http.response() = response;
|
|
|
|
http.complete();
|
2023-04-26 18:58:18 -04:00
|
|
|
let mut upgraded = upgrade.await?;
|
|
|
|
upgraded.write_all(&bytes).await?;
|
|
|
|
break upgraded;
|
|
|
|
}
|
|
|
|
Err(err) => return Err(err),
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Stage 3: Pump the data
|
|
|
|
let (mut upgraded_rx, mut upgraded_tx) = tokio::io::split(upgraded);
|
|
|
|
|
2023-05-14 17:40:01 -04:00
|
|
|
spawn(async move {
|
2023-04-26 18:58:18 -04:00
|
|
|
let mut buf = [0; 1024];
|
|
|
|
loop {
|
|
|
|
let read = upgraded_rx.read(&mut buf).await?;
|
|
|
|
if read == 0 {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
read_tx.write_all(&buf[..read]).await?;
|
|
|
|
}
|
|
|
|
Ok::<_, AnyError>(())
|
|
|
|
});
|
2023-05-14 17:40:01 -04:00
|
|
|
spawn(async move {
|
2023-04-26 18:58:18 -04:00
|
|
|
let mut buf = [0; 1024];
|
|
|
|
loop {
|
|
|
|
let read = write_rx.read(&mut buf).await?;
|
|
|
|
if read == 0 {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
upgraded_tx.write_all(&buf[..read]).await?;
|
|
|
|
}
|
|
|
|
Ok::<_, AnyError>(())
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(
|
|
|
|
state
|
|
|
|
.resource_table
|
|
|
|
.add(UpgradeStream::new(read_rx, write_tx)),
|
|
|
|
)
|
|
|
|
}
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
#[op]
|
2023-05-15 19:24:41 -04:00
|
|
|
pub async fn op_http_upgrade_websocket_next(
|
2023-04-22 13:48:21 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-04-22 13:48:21 -04:00
|
|
|
headers: Vec<(ByteString, ByteString)>,
|
2023-05-15 19:24:41 -04:00
|
|
|
) -> Result<ResourceId, AnyError> {
|
2023-05-16 19:00:59 -04:00
|
|
|
let mut http = slab_get(slab_id);
|
|
|
|
// Stage 1: set the response to 101 Switching Protocols and send it
|
|
|
|
let upgrade = http.upgrade()?;
|
|
|
|
|
|
|
|
let response = http.response();
|
|
|
|
*response.status_mut() = StatusCode::SWITCHING_PROTOCOLS;
|
|
|
|
for (name, value) in headers {
|
|
|
|
response.headers_mut().append(
|
|
|
|
HeaderName::from_bytes(&name).unwrap(),
|
|
|
|
HeaderValue::from_bytes(&value).unwrap(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
http.complete();
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
// Stage 2: wait for the request to finish upgrading
|
|
|
|
let upgraded = upgrade.await?;
|
|
|
|
|
2023-05-15 19:24:41 -04:00
|
|
|
// Stage 3: take the extracted raw network stream and upgrade it to a websocket, then return it
|
2023-04-22 13:48:21 -04:00
|
|
|
let (stream, bytes) = extract_network_stream(upgraded);
|
2023-05-15 19:24:41 -04:00
|
|
|
ws_create_server_stream(&mut state.borrow_mut(), stream, bytes)
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
2023-04-26 06:08:13 -04:00
|
|
|
#[op(fast)]
|
2023-05-16 19:00:59 -04:00
|
|
|
pub fn op_http_set_promise_complete(slab_id: SlabId, status: u16) {
|
|
|
|
let mut http = slab_get(slab_id);
|
|
|
|
// The Javascript code will never provide a status that is invalid here (see 23_response.js)
|
|
|
|
*http.response().status_mut() = StatusCode::from_u16(status).unwrap();
|
|
|
|
http.complete();
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[op]
|
2023-05-10 10:23:26 -04:00
|
|
|
pub fn op_http_get_request_method_and_url<HTTP>(
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-05-10 10:23:26 -04:00
|
|
|
) -> (String, Option<String>, String, String, Option<u16>)
|
|
|
|
where
|
|
|
|
HTTP: HttpPropertyExtractor,
|
|
|
|
{
|
2023-05-16 19:00:59 -04:00
|
|
|
let http = slab_get(slab_id);
|
|
|
|
let request_info = http.request_info();
|
|
|
|
let request_parts = http.request_parts();
|
|
|
|
let request_properties = HTTP::request_properties(
|
|
|
|
request_info,
|
|
|
|
&request_parts.uri,
|
|
|
|
&request_parts.headers,
|
|
|
|
);
|
2023-04-22 13:48:21 -04:00
|
|
|
|
2023-05-16 19:00:59 -04:00
|
|
|
// Only extract the path part - we handle authority elsewhere
|
|
|
|
let path = match &request_parts.uri.path_and_query() {
|
|
|
|
Some(path_and_query) => path_and_query.to_string(),
|
|
|
|
None => "".to_owned(),
|
|
|
|
};
|
2023-04-22 13:48:21 -04:00
|
|
|
|
2023-05-16 19:00:59 -04:00
|
|
|
// TODO(mmastrac): Passing method can be optimized
|
|
|
|
(
|
|
|
|
request_parts.method.as_str().to_owned(),
|
|
|
|
request_properties.authority,
|
|
|
|
path,
|
|
|
|
String::from(request_info.peer_address.as_ref()),
|
|
|
|
request_info.peer_port,
|
|
|
|
)
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[op]
|
2023-05-08 17:07:45 -04:00
|
|
|
pub fn op_http_get_request_header(
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-05-08 17:07:45 -04:00
|
|
|
name: String,
|
|
|
|
) -> Option<ByteString> {
|
2023-05-16 19:00:59 -04:00
|
|
|
let http = slab_get(slab_id);
|
|
|
|
let value = http.request_parts().headers.get(name);
|
|
|
|
value.map(|value| value.as_bytes().into())
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[op]
|
2023-06-02 11:59:16 -04:00
|
|
|
pub fn op_http_get_request_headers(slab_id: SlabId) -> Vec<ByteString> {
|
2023-05-16 19:00:59 -04:00
|
|
|
let http = slab_get(slab_id);
|
|
|
|
let headers = &http.request_parts().headers;
|
2023-06-02 11:59:16 -04:00
|
|
|
// Two slots for each header key/value pair
|
|
|
|
let mut vec = Vec::with_capacity(headers.len() * 2);
|
2023-05-16 19:00:59 -04:00
|
|
|
let mut cookies: Option<Vec<&[u8]>> = None;
|
|
|
|
for (name, value) in headers {
|
|
|
|
if name == COOKIE {
|
|
|
|
if let Some(ref mut cookies) = cookies {
|
|
|
|
cookies.push(value.as_bytes());
|
2023-04-22 13:48:21 -04:00
|
|
|
} else {
|
2023-05-16 19:00:59 -04:00
|
|
|
cookies = Some(vec![value.as_bytes()]);
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
2023-05-16 19:00:59 -04:00
|
|
|
} else {
|
|
|
|
let name: &[u8] = name.as_ref();
|
2023-06-02 11:59:16 -04:00
|
|
|
vec.push(name.into());
|
|
|
|
vec.push(value.as_bytes().into());
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
2023-05-16 19:00:59 -04:00
|
|
|
}
|
2023-04-22 13:48:21 -04:00
|
|
|
|
2023-05-16 19:00:59 -04:00
|
|
|
// We treat cookies specially, because we don't want them to get them
|
|
|
|
// mangled by the `Headers` object in JS. What we do is take all cookie
|
|
|
|
// headers and concat them into a single cookie header, separated by
|
|
|
|
// semicolons.
|
|
|
|
// TODO(mmastrac): This should probably happen on the JS side on-demand
|
|
|
|
if let Some(cookies) = cookies {
|
|
|
|
let cookie_sep = "; ".as_bytes();
|
2023-06-02 11:59:16 -04:00
|
|
|
vec.push(ByteString::from(COOKIE.as_str()));
|
|
|
|
vec.push(ByteString::from(cookies.join(cookie_sep)));
|
2023-05-16 19:00:59 -04:00
|
|
|
}
|
2023-06-02 11:59:16 -04:00
|
|
|
|
2023-05-16 19:00:59 -04:00
|
|
|
vec
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
2023-04-26 06:08:13 -04:00
|
|
|
#[op(fast)]
|
2023-05-08 17:07:45 -04:00
|
|
|
pub fn op_http_read_request_body(
|
|
|
|
state: &mut OpState,
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-05-08 17:07:45 -04:00
|
|
|
) -> ResourceId {
|
2023-05-16 19:00:59 -04:00
|
|
|
let mut http = slab_get(slab_id);
|
|
|
|
let incoming = http.take_body();
|
2023-04-22 13:48:21 -04:00
|
|
|
let body_resource = Rc::new(HttpRequestBody::new(incoming));
|
2023-05-16 19:00:59 -04:00
|
|
|
state.resource_table.add_rc(body_resource)
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
2023-04-26 06:08:13 -04:00
|
|
|
#[op(fast)]
|
2023-05-16 19:00:59 -04:00
|
|
|
pub fn op_http_set_response_header(slab_id: SlabId, name: &str, value: &str) {
|
|
|
|
let mut http = slab_get(slab_id);
|
|
|
|
let resp_headers = http.response().headers_mut();
|
|
|
|
// These are valid latin-1 strings
|
|
|
|
let name = HeaderName::from_bytes(name.as_bytes()).unwrap();
|
|
|
|
let value = HeaderValue::from_bytes(value.as_bytes()).unwrap();
|
|
|
|
resp_headers.append(name, value);
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[op]
|
2023-06-02 11:59:16 -04:00
|
|
|
pub fn op_http_set_response_headers(slab_id: SlabId, headers: Vec<ByteString>) {
|
2023-05-16 19:00:59 -04:00
|
|
|
let mut http = slab_get(slab_id);
|
2023-04-22 13:48:21 -04:00
|
|
|
// TODO(mmastrac): Invalid headers should be handled?
|
2023-05-16 19:00:59 -04:00
|
|
|
let resp_headers = http.response().headers_mut();
|
|
|
|
resp_headers.reserve(headers.len());
|
2023-06-02 11:59:16 -04:00
|
|
|
for header in headers.chunks_exact(2) {
|
2023-05-16 19:00:59 -04:00
|
|
|
// These are valid latin-1 strings
|
2023-06-02 11:59:16 -04:00
|
|
|
let name = HeaderName::from_bytes(&header[0]).unwrap();
|
|
|
|
let value = HeaderValue::from_bytes(&header[1]).unwrap();
|
2023-05-16 19:00:59 -04:00
|
|
|
resp_headers.append(name, value);
|
|
|
|
}
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
2023-05-18 22:10:25 -04:00
|
|
|
#[op]
|
|
|
|
pub fn op_http_set_response_trailers(
|
|
|
|
slab_id: SlabId,
|
|
|
|
trailers: Vec<(ByteString, ByteString)>,
|
|
|
|
) {
|
|
|
|
let mut http = slab_get(slab_id);
|
|
|
|
let mut trailer_map: HeaderMap = HeaderMap::with_capacity(trailers.len());
|
|
|
|
for (name, value) in trailers {
|
|
|
|
// These are valid latin-1 strings
|
|
|
|
let name = HeaderName::from_bytes(&name).unwrap();
|
|
|
|
let value = HeaderValue::from_bytes(&value).unwrap();
|
|
|
|
trailer_map.append(name, value);
|
|
|
|
}
|
|
|
|
*http.trailers().borrow_mut() = Some(trailer_map);
|
|
|
|
}
|
|
|
|
|
2023-05-10 07:23:14 -04:00
|
|
|
fn is_request_compressible(headers: &HeaderMap) -> Compression {
|
|
|
|
let Some(accept_encoding) = headers.get(ACCEPT_ENCODING) else {
|
|
|
|
return Compression::None;
|
|
|
|
};
|
2023-05-24 13:54:47 -04:00
|
|
|
|
|
|
|
match accept_encoding.to_str().unwrap() {
|
|
|
|
// Firefox and Chrome send this -- no need to parse
|
|
|
|
"gzip, deflate, br" => return Compression::Brotli,
|
|
|
|
"gzip" => return Compression::GZip,
|
|
|
|
"br" => return Compression::Brotli,
|
|
|
|
_ => (),
|
2023-05-10 07:23:14 -04:00
|
|
|
}
|
2023-05-24 13:54:47 -04:00
|
|
|
|
2023-05-10 07:23:14 -04:00
|
|
|
// Fall back to the expensive parser
|
|
|
|
let accepted = fly_accept_encoding::encodings_iter(headers).filter(|r| {
|
2023-05-24 13:54:47 -04:00
|
|
|
matches!(
|
|
|
|
r,
|
|
|
|
Ok((
|
|
|
|
Some(Encoding::Identity | Encoding::Gzip | Encoding::Brotli),
|
|
|
|
_
|
|
|
|
))
|
|
|
|
)
|
2023-05-10 07:23:14 -04:00
|
|
|
});
|
|
|
|
match fly_accept_encoding::preferred(accepted) {
|
2023-05-24 13:54:47 -04:00
|
|
|
Ok(Some(fly_accept_encoding::Encoding::Gzip)) => Compression::GZip,
|
|
|
|
Ok(Some(fly_accept_encoding::Encoding::Brotli)) => Compression::Brotli,
|
|
|
|
_ => Compression::None,
|
2023-05-10 07:23:14 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_response_compressible(headers: &HeaderMap) -> bool {
|
|
|
|
if let Some(content_type) = headers.get(CONTENT_TYPE) {
|
|
|
|
if !is_content_compressible(content_type) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if headers.contains_key(CONTENT_ENCODING) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if headers.contains_key(CONTENT_RANGE) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if let Some(cache_control) = headers.get(CACHE_CONTROL) {
|
|
|
|
if let Ok(s) = std::str::from_utf8(cache_control.as_bytes()) {
|
|
|
|
if let Some(cache_control) = CacheControl::from_value(s) {
|
|
|
|
if cache_control.no_transform {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
true
|
|
|
|
}
|
|
|
|
|
|
|
|
fn modify_compressibility_from_response(
|
|
|
|
compression: Compression,
|
|
|
|
length: Option<usize>,
|
|
|
|
headers: &mut HeaderMap,
|
|
|
|
) -> Compression {
|
|
|
|
ensure_vary_accept_encoding(headers);
|
|
|
|
if let Some(length) = length {
|
|
|
|
// By the time we add compression headers and Accept-Encoding, it probably doesn't make sense
|
|
|
|
// to compress stuff that's smaller than this.
|
|
|
|
if length < 64 {
|
|
|
|
return Compression::None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if compression == Compression::None {
|
|
|
|
return Compression::None;
|
|
|
|
}
|
|
|
|
if !is_response_compressible(headers) {
|
|
|
|
return Compression::None;
|
|
|
|
}
|
2023-05-24 13:54:47 -04:00
|
|
|
let encoding = match compression {
|
|
|
|
Compression::Brotli => "br",
|
|
|
|
Compression::GZip => "gzip",
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
2023-05-10 07:23:14 -04:00
|
|
|
weaken_etag(headers);
|
|
|
|
headers.remove(CONTENT_LENGTH);
|
2023-05-24 13:54:47 -04:00
|
|
|
headers.insert(CONTENT_ENCODING, HeaderValue::from_static(encoding));
|
2023-05-10 07:23:14 -04:00
|
|
|
compression
|
|
|
|
}
|
|
|
|
|
|
|
|
/// If the user provided a ETag header for uncompressed data, we need to ensure it is a
|
|
|
|
/// weak Etag header ("W/").
|
|
|
|
fn weaken_etag(hmap: &mut HeaderMap) {
|
|
|
|
if let Some(etag) = hmap.get_mut(hyper::header::ETAG) {
|
|
|
|
if !etag.as_bytes().starts_with(b"W/") {
|
|
|
|
let mut v = Vec::with_capacity(etag.as_bytes().len() + 2);
|
|
|
|
v.extend(b"W/");
|
|
|
|
v.extend(etag.as_bytes());
|
|
|
|
*etag = v.try_into().unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set Vary: Accept-Encoding header for direct body response.
|
|
|
|
// Note: we set the header irrespective of whether or not we compress the data
|
|
|
|
// to make sure cache services do not serve uncompressed data to clients that
|
|
|
|
// support compression.
|
|
|
|
fn ensure_vary_accept_encoding(hmap: &mut HeaderMap) {
|
|
|
|
if let Some(v) = hmap.get_mut(hyper::header::VARY) {
|
|
|
|
if let Ok(s) = v.to_str() {
|
|
|
|
if !s.to_lowercase().contains("accept-encoding") {
|
|
|
|
*v = format!("Accept-Encoding, {s}").try_into().unwrap()
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
hmap.insert(
|
|
|
|
hyper::header::VARY,
|
|
|
|
HeaderValue::from_static("Accept-Encoding"),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn set_response(
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-05-10 07:23:14 -04:00
|
|
|
length: Option<usize>,
|
|
|
|
response_fn: impl FnOnce(Compression) -> ResponseBytesInner,
|
|
|
|
) {
|
2023-05-16 19:00:59 -04:00
|
|
|
let mut http = slab_get(slab_id);
|
|
|
|
let compression = is_request_compressible(&http.request_parts().headers);
|
|
|
|
let response = http.response();
|
|
|
|
let compression = modify_compressibility_from_response(
|
|
|
|
compression,
|
|
|
|
length,
|
|
|
|
response.headers_mut(),
|
|
|
|
);
|
|
|
|
response.body_mut().initialize(response_fn(compression))
|
2023-05-10 07:23:14 -04:00
|
|
|
}
|
|
|
|
|
2023-04-26 06:08:13 -04:00
|
|
|
#[op(fast)]
|
2023-05-08 17:07:45 -04:00
|
|
|
pub fn op_http_set_response_body_resource(
|
2023-04-22 13:48:21 -04:00
|
|
|
state: &mut OpState,
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-04-22 13:48:21 -04:00
|
|
|
stream_rid: ResourceId,
|
|
|
|
auto_close: bool,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
// If the stream is auto_close, we will hold the last ref to it until the response is complete.
|
|
|
|
let resource = if auto_close {
|
|
|
|
state.resource_table.take_any(stream_rid)?
|
|
|
|
} else {
|
|
|
|
state.resource_table.get_any(stream_rid)?
|
|
|
|
};
|
|
|
|
|
2023-05-10 07:23:14 -04:00
|
|
|
set_response(
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id,
|
2023-05-10 07:23:14 -04:00
|
|
|
resource.size_hint().1.map(|s| s as usize),
|
|
|
|
move |compression| {
|
|
|
|
ResponseBytesInner::from_resource(compression, resource, auto_close)
|
|
|
|
},
|
|
|
|
);
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-04-26 06:08:13 -04:00
|
|
|
#[op(fast)]
|
2023-05-08 17:07:45 -04:00
|
|
|
pub fn op_http_set_response_body_stream(
|
2023-04-22 13:48:21 -04:00
|
|
|
state: &mut OpState,
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-04-22 13:48:21 -04:00
|
|
|
) -> Result<ResourceId, AnyError> {
|
|
|
|
// TODO(mmastrac): what should this channel size be?
|
|
|
|
let (tx, rx) = tokio::sync::mpsc::channel(1);
|
2023-05-16 19:00:59 -04:00
|
|
|
set_response(slab_id, None, |compression| {
|
2023-05-10 07:23:14 -04:00
|
|
|
ResponseBytesInner::from_v8(compression, rx)
|
2023-04-22 13:48:21 -04:00
|
|
|
});
|
|
|
|
|
2023-05-10 07:23:14 -04:00
|
|
|
Ok(state.resource_table.add(V8StreamHttpResponseBody::new(tx)))
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
2023-04-26 06:08:13 -04:00
|
|
|
#[op(fast)]
|
2023-05-16 19:00:59 -04:00
|
|
|
pub fn op_http_set_response_body_text(slab_id: SlabId, text: String) {
|
2023-04-22 13:48:21 -04:00
|
|
|
if !text.is_empty() {
|
2023-05-16 19:00:59 -04:00
|
|
|
set_response(slab_id, Some(text.len()), |compression| {
|
2023-05-10 07:23:14 -04:00
|
|
|
ResponseBytesInner::from_vec(compression, text.into_bytes())
|
2023-04-22 13:48:21 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-26 06:08:13 -04:00
|
|
|
#[op(fast)]
|
2023-05-16 19:00:59 -04:00
|
|
|
pub fn op_http_set_response_body_bytes(slab_id: SlabId, buffer: &[u8]) {
|
2023-04-22 13:48:21 -04:00
|
|
|
if !buffer.is_empty() {
|
2023-05-16 19:00:59 -04:00
|
|
|
set_response(slab_id, Some(buffer.len()), |compression| {
|
2023-05-10 07:23:14 -04:00
|
|
|
ResponseBytesInner::from_slice(compression, buffer)
|
2023-04-22 13:48:21 -04:00
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
pub async fn op_http_track(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_id: SlabId,
|
2023-04-22 13:48:21 -04:00
|
|
|
server_rid: ResourceId,
|
|
|
|
) -> Result<(), AnyError> {
|
2023-05-16 19:00:59 -04:00
|
|
|
let http = slab_get(slab_id);
|
|
|
|
let handle = http.body_promise();
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
let join_handle = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.get::<HttpJoinHandle>(server_rid)?;
|
|
|
|
|
|
|
|
match handle.or_cancel(join_handle.cancel_handle()).await {
|
|
|
|
Ok(true) => Ok(()),
|
|
|
|
Ok(false) => {
|
|
|
|
Err(AnyError::msg("connection closed before message completed"))
|
|
|
|
}
|
|
|
|
Err(_e) => Ok(()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[pin_project(PinnedDrop)]
|
2023-05-16 19:00:59 -04:00
|
|
|
pub struct SlabFuture<F: Future<Output = ()>>(SlabId, #[pin] F);
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
pub fn new_slab_future(
|
|
|
|
request: Request,
|
|
|
|
request_info: HttpConnectionProperties,
|
2023-05-16 19:00:59 -04:00
|
|
|
tx: tokio::sync::mpsc::Sender<SlabId>,
|
2023-04-22 13:48:21 -04:00
|
|
|
) -> SlabFuture<impl Future<Output = ()>> {
|
|
|
|
let index = slab_insert(request, request_info);
|
2023-05-16 19:00:59 -04:00
|
|
|
let rx = slab_get(index).promise();
|
2023-04-22 13:48:21 -04:00
|
|
|
SlabFuture(index, async move {
|
|
|
|
if tx.send(index).await.is_ok() {
|
|
|
|
// We only need to wait for completion if we aren't closed
|
|
|
|
rx.await;
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<F: Future<Output = ()>> SlabFuture<F> {}
|
|
|
|
|
|
|
|
#[pinned_drop]
|
|
|
|
impl<F: Future<Output = ()>> PinnedDrop for SlabFuture<F> {
|
|
|
|
fn drop(self: Pin<&mut Self>) {
|
2023-05-16 19:00:59 -04:00
|
|
|
slab_drop(self.0);
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<F: Future<Output = ()>> Future for SlabFuture<F> {
|
|
|
|
type Output = Result<Response, hyper::Error>;
|
|
|
|
|
|
|
|
fn poll(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut std::task::Context<'_>,
|
|
|
|
) -> std::task::Poll<Self::Output> {
|
|
|
|
let index = self.0;
|
|
|
|
self
|
|
|
|
.project()
|
|
|
|
.1
|
|
|
|
.poll(cx)
|
2023-05-16 19:00:59 -04:00
|
|
|
.map(|_| Ok(slab_get(index).take_response()))
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-24 17:24:40 -04:00
|
|
|
fn serve_http11_unconditional(
|
|
|
|
io: impl HttpServeStream,
|
|
|
|
svc: impl HttpService<Incoming, ResBody = ResponseBytes> + 'static,
|
|
|
|
) -> impl Future<Output = Result<(), AnyError>> + 'static {
|
|
|
|
let conn = http1::Builder::new()
|
|
|
|
.keep_alive(true)
|
2023-06-01 10:07:26 -04:00
|
|
|
.writev(*USE_WRITEV)
|
2023-04-24 17:24:40 -04:00
|
|
|
.serve_connection(io, svc);
|
|
|
|
|
2023-05-08 03:52:56 -04:00
|
|
|
conn.with_upgrades().map_err(AnyError::from)
|
2023-04-24 17:24:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn serve_http2_unconditional(
|
|
|
|
io: impl HttpServeStream,
|
|
|
|
svc: impl HttpService<Incoming, ResBody = ResponseBytes> + 'static,
|
|
|
|
) -> impl Future<Output = Result<(), AnyError>> + 'static {
|
|
|
|
let conn = http2::Builder::new(LocalExecutor).serve_connection(io, svc);
|
2023-05-08 03:52:56 -04:00
|
|
|
conn.map_err(AnyError::from)
|
2023-04-24 17:24:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn serve_http2_autodetect(
|
|
|
|
io: impl HttpServeStream,
|
|
|
|
svc: impl HttpService<Incoming, ResBody = ResponseBytes> + 'static,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let prefix = NetworkStreamPrefixCheck::new(io, HTTP2_PREFIX);
|
|
|
|
let (matches, io) = prefix.match_prefix().await?;
|
|
|
|
if matches {
|
2023-05-08 03:52:56 -04:00
|
|
|
serve_http2_unconditional(io, svc).await
|
2023-04-24 17:24:40 -04:00
|
|
|
} else {
|
2023-05-08 03:52:56 -04:00
|
|
|
serve_http11_unconditional(io, svc).await
|
2023-04-24 17:24:40 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
fn serve_https(
|
|
|
|
mut io: TlsStream,
|
|
|
|
request_info: HttpConnectionProperties,
|
2023-05-08 03:52:56 -04:00
|
|
|
cancel: Rc<CancelHandle>,
|
2023-05-16 19:00:59 -04:00
|
|
|
tx: tokio::sync::mpsc::Sender<SlabId>,
|
2023-04-22 13:48:21 -04:00
|
|
|
) -> JoinHandle<Result<(), AnyError>> {
|
|
|
|
let svc = service_fn(move |req: Request| {
|
|
|
|
new_slab_future(req, request_info.clone(), tx.clone())
|
|
|
|
});
|
2023-05-14 17:40:01 -04:00
|
|
|
spawn(
|
2023-05-08 03:52:56 -04:00
|
|
|
async {
|
|
|
|
io.handshake().await?;
|
|
|
|
// If the client specifically negotiates a protocol, we will use it. If not, we'll auto-detect
|
|
|
|
// based on the prefix bytes
|
|
|
|
let handshake = io.get_ref().1.alpn_protocol();
|
|
|
|
if handshake == Some(TLS_ALPN_HTTP_2) {
|
|
|
|
serve_http2_unconditional(io, svc).await
|
|
|
|
} else if handshake == Some(TLS_ALPN_HTTP_11) {
|
|
|
|
serve_http11_unconditional(io, svc).await
|
|
|
|
} else {
|
|
|
|
serve_http2_autodetect(io, svc).await
|
|
|
|
}
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
2023-05-08 03:52:56 -04:00
|
|
|
.try_or_cancel(cancel),
|
|
|
|
)
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn serve_http(
|
2023-04-24 17:24:40 -04:00
|
|
|
io: impl HttpServeStream,
|
2023-04-22 13:48:21 -04:00
|
|
|
request_info: HttpConnectionProperties,
|
2023-05-08 03:52:56 -04:00
|
|
|
cancel: Rc<CancelHandle>,
|
2023-05-16 19:00:59 -04:00
|
|
|
tx: tokio::sync::mpsc::Sender<SlabId>,
|
2023-04-22 13:48:21 -04:00
|
|
|
) -> JoinHandle<Result<(), AnyError>> {
|
|
|
|
let svc = service_fn(move |req: Request| {
|
|
|
|
new_slab_future(req, request_info.clone(), tx.clone())
|
|
|
|
});
|
2023-05-14 17:40:01 -04:00
|
|
|
spawn(serve_http2_autodetect(io, svc).try_or_cancel(cancel))
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
2023-05-10 10:23:26 -04:00
|
|
|
fn serve_http_on<HTTP>(
|
2023-05-15 10:55:47 -04:00
|
|
|
connection: HTTP::Connection,
|
2023-04-22 13:48:21 -04:00
|
|
|
listen_properties: &HttpListenProperties,
|
2023-05-08 03:52:56 -04:00
|
|
|
cancel: Rc<CancelHandle>,
|
2023-05-16 19:00:59 -04:00
|
|
|
tx: tokio::sync::mpsc::Sender<SlabId>,
|
2023-05-10 10:23:26 -04:00
|
|
|
) -> JoinHandle<Result<(), AnyError>>
|
|
|
|
where
|
|
|
|
HTTP: HttpPropertyExtractor,
|
|
|
|
{
|
2023-04-22 13:48:21 -04:00
|
|
|
let connection_properties: HttpConnectionProperties =
|
2023-05-15 10:55:47 -04:00
|
|
|
HTTP::connection_properties(listen_properties, &connection);
|
|
|
|
|
|
|
|
let network_stream = HTTP::to_network_stream_from_connection(connection);
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
match network_stream {
|
|
|
|
NetworkStream::Tcp(conn) => {
|
|
|
|
serve_http(conn, connection_properties, cancel, tx)
|
|
|
|
}
|
|
|
|
NetworkStream::Tls(conn) => {
|
|
|
|
serve_https(conn, connection_properties, cancel, tx)
|
|
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
|
|
NetworkStream::Unix(conn) => {
|
|
|
|
serve_http(conn, connection_properties, cancel, tx)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct HttpJoinHandle(
|
|
|
|
AsyncRefCell<Option<JoinHandle<Result<(), AnyError>>>>,
|
2023-05-08 03:52:56 -04:00
|
|
|
// Cancel handle must live in a separate Rc to avoid keeping the outer join handle ref'd
|
|
|
|
Rc<CancelHandle>,
|
2023-05-16 19:00:59 -04:00
|
|
|
AsyncRefCell<tokio::sync::mpsc::Receiver<SlabId>>,
|
2023-04-22 13:48:21 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
impl HttpJoinHandle {
|
2023-05-08 03:52:56 -04:00
|
|
|
fn cancel_handle(self: &Rc<Self>) -> Rc<CancelHandle> {
|
|
|
|
self.1.clone()
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for HttpJoinHandle {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"http".into()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
self.1.cancel()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-08 03:52:56 -04:00
|
|
|
impl Drop for HttpJoinHandle {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
// In some cases we may be dropped without closing, so let's cancel everything on the way out
|
|
|
|
self.1.cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
#[op(v8)]
|
2023-05-10 10:23:26 -04:00
|
|
|
pub fn op_http_serve<HTTP>(
|
2023-04-22 13:48:21 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
listener_rid: ResourceId,
|
2023-05-10 10:23:26 -04:00
|
|
|
) -> Result<(ResourceId, &'static str, String), AnyError>
|
|
|
|
where
|
|
|
|
HTTP: HttpPropertyExtractor,
|
|
|
|
{
|
2023-05-15 10:55:47 -04:00
|
|
|
let listener =
|
|
|
|
HTTP::get_listener_for_rid(&mut state.borrow_mut(), listener_rid)?;
|
2023-04-22 13:48:21 -04:00
|
|
|
|
2023-05-15 10:55:47 -04:00
|
|
|
let listen_properties = HTTP::listen_properties_from_listener(&listener)?;
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
let (tx, rx) = tokio::sync::mpsc::channel(10);
|
|
|
|
let resource: Rc<HttpJoinHandle> = Rc::new(HttpJoinHandle(
|
|
|
|
AsyncRefCell::new(None),
|
2023-05-08 03:52:56 -04:00
|
|
|
CancelHandle::new_rc(),
|
2023-04-22 13:48:21 -04:00
|
|
|
AsyncRefCell::new(rx),
|
|
|
|
));
|
|
|
|
let cancel_clone = resource.cancel_handle();
|
|
|
|
|
2023-05-08 03:52:56 -04:00
|
|
|
let listen_properties_clone: HttpListenProperties = listen_properties.clone();
|
2023-05-14 17:40:01 -04:00
|
|
|
let handle = spawn(async move {
|
2023-04-22 13:48:21 -04:00
|
|
|
loop {
|
2023-05-15 10:55:47 -04:00
|
|
|
let conn = HTTP::accept_connection_from_listener(&listener)
|
2023-04-22 13:48:21 -04:00
|
|
|
.try_or_cancel(cancel_clone.clone())
|
|
|
|
.await?;
|
2023-05-10 10:23:26 -04:00
|
|
|
serve_http_on::<HTTP>(
|
2023-04-22 13:48:21 -04:00
|
|
|
conn,
|
|
|
|
&listen_properties_clone,
|
|
|
|
cancel_clone.clone(),
|
|
|
|
tx.clone(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
#[allow(unreachable_code)]
|
|
|
|
Ok::<_, AnyError>(())
|
|
|
|
});
|
|
|
|
|
|
|
|
// Set the handle after we start the future
|
|
|
|
*RcRef::map(&resource, |this| &this.0)
|
|
|
|
.try_borrow_mut()
|
|
|
|
.unwrap() = Some(handle);
|
|
|
|
|
|
|
|
Ok((
|
|
|
|
state.borrow_mut().resource_table.add_rc(resource),
|
|
|
|
listen_properties.scheme,
|
|
|
|
listen_properties.fallback_host,
|
|
|
|
))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op(v8)]
|
2023-05-10 10:23:26 -04:00
|
|
|
pub fn op_http_serve_on<HTTP>(
|
2023-04-22 13:48:21 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-05-15 10:55:47 -04:00
|
|
|
connection_rid: ResourceId,
|
2023-05-10 10:23:26 -04:00
|
|
|
) -> Result<(ResourceId, &'static str, String), AnyError>
|
|
|
|
where
|
|
|
|
HTTP: HttpPropertyExtractor,
|
|
|
|
{
|
2023-05-15 10:55:47 -04:00
|
|
|
let connection =
|
|
|
|
HTTP::get_connection_for_rid(&mut state.borrow_mut(), connection_rid)?;
|
2023-04-22 13:48:21 -04:00
|
|
|
|
2023-05-15 10:55:47 -04:00
|
|
|
let listen_properties = HTTP::listen_properties_from_connection(&connection)?;
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
let (tx, rx) = tokio::sync::mpsc::channel(10);
|
|
|
|
let resource: Rc<HttpJoinHandle> = Rc::new(HttpJoinHandle(
|
|
|
|
AsyncRefCell::new(None),
|
2023-05-08 03:52:56 -04:00
|
|
|
CancelHandle::new_rc(),
|
2023-04-22 13:48:21 -04:00
|
|
|
AsyncRefCell::new(rx),
|
|
|
|
));
|
|
|
|
|
2023-05-10 10:23:26 -04:00
|
|
|
let handle: JoinHandle<Result<(), deno_core::anyhow::Error>> =
|
|
|
|
serve_http_on::<HTTP>(
|
2023-05-15 10:55:47 -04:00
|
|
|
connection,
|
2023-05-10 10:23:26 -04:00
|
|
|
&listen_properties,
|
|
|
|
resource.cancel_handle(),
|
|
|
|
tx,
|
|
|
|
);
|
2023-04-22 13:48:21 -04:00
|
|
|
|
|
|
|
// Set the handle after we start the future
|
|
|
|
*RcRef::map(&resource, |this| &this.0)
|
|
|
|
.try_borrow_mut()
|
|
|
|
.unwrap() = Some(handle);
|
|
|
|
|
|
|
|
Ok((
|
|
|
|
state.borrow_mut().resource_table.add_rc(resource),
|
|
|
|
listen_properties.scheme,
|
|
|
|
listen_properties.fallback_host,
|
|
|
|
))
|
|
|
|
}
|
|
|
|
|
2023-05-30 20:02:52 -04:00
|
|
|
/// Synchronous, non-blocking call to see if there are any further HTTP requests. If anything
|
|
|
|
/// goes wrong in this method we return [`SlabId::MAX`] and let the async handler pick up the real error.
|
|
|
|
#[op(fast)]
|
|
|
|
pub fn op_http_try_wait(state: &mut OpState, rid: ResourceId) -> SlabId {
|
|
|
|
// The resource needs to exist.
|
|
|
|
let Ok(join_handle) = state
|
|
|
|
.resource_table
|
|
|
|
.get::<HttpJoinHandle>(rid) else {
|
|
|
|
return SlabId::MAX;
|
|
|
|
};
|
|
|
|
|
|
|
|
// If join handle is somehow locked, just abort.
|
|
|
|
let Some(mut handle) = RcRef::map(&join_handle, |this| &this.2).try_borrow_mut() else {
|
|
|
|
return SlabId::MAX;
|
|
|
|
};
|
|
|
|
|
|
|
|
// See if there are any requests waiting on this channel. If not, return.
|
|
|
|
let Ok(id) = handle.try_recv() else {
|
|
|
|
return SlabId::MAX;
|
|
|
|
};
|
|
|
|
|
|
|
|
id
|
|
|
|
}
|
|
|
|
|
2023-04-22 13:48:21 -04:00
|
|
|
#[op]
|
|
|
|
pub async fn op_http_wait(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
rid: ResourceId,
|
2023-05-16 19:00:59 -04:00
|
|
|
) -> Result<SlabId, AnyError> {
|
2023-04-22 13:48:21 -04:00
|
|
|
// We will get the join handle initially, as we might be consuming requests still
|
|
|
|
let join_handle = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.get::<HttpJoinHandle>(rid)?;
|
|
|
|
|
2023-05-08 03:52:56 -04:00
|
|
|
let cancel = join_handle.cancel_handle();
|
2023-04-22 13:48:21 -04:00
|
|
|
let next = async {
|
|
|
|
let mut recv = RcRef::map(&join_handle, |this| &this.2).borrow_mut().await;
|
|
|
|
recv.recv().await
|
|
|
|
}
|
|
|
|
.or_cancel(cancel)
|
|
|
|
.unwrap_or_else(|_| None)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
// Do we have a request?
|
|
|
|
if let Some(req) = next {
|
2023-04-26 06:08:13 -04:00
|
|
|
return Ok(req);
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// No - we're shutting down
|
|
|
|
let res = RcRef::map(join_handle, |this| &this.0)
|
|
|
|
.borrow_mut()
|
|
|
|
.await
|
|
|
|
.take()
|
|
|
|
.unwrap()
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
// Drop the cancel and join handles
|
|
|
|
state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.take::<HttpJoinHandle>(rid)?;
|
|
|
|
|
|
|
|
// Filter out shutdown (ENOTCONN) errors
|
|
|
|
if let Err(err) = res {
|
|
|
|
if let Some(err) = err.source() {
|
|
|
|
if let Some(err) = err.downcast_ref::<io::Error>() {
|
|
|
|
if err.kind() == io::ErrorKind::NotConnected {
|
2023-05-16 19:00:59 -04:00
|
|
|
return Ok(SlabId::MAX);
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Err(err);
|
|
|
|
}
|
|
|
|
|
2023-05-16 19:00:59 -04:00
|
|
|
Ok(SlabId::MAX)
|
2023-04-22 13:48:21 -04:00
|
|
|
}
|
2023-04-26 18:58:18 -04:00
|
|
|
|
|
|
|
struct UpgradeStream {
|
|
|
|
read: AsyncRefCell<tokio::io::ReadHalf<tokio::io::DuplexStream>>,
|
|
|
|
write: AsyncRefCell<tokio::io::WriteHalf<tokio::io::DuplexStream>>,
|
|
|
|
cancel_handle: CancelHandle,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl UpgradeStream {
|
|
|
|
pub fn new(
|
|
|
|
read: tokio::io::ReadHalf<tokio::io::DuplexStream>,
|
|
|
|
write: tokio::io::WriteHalf<tokio::io::DuplexStream>,
|
|
|
|
) -> Self {
|
|
|
|
Self {
|
|
|
|
read: AsyncRefCell::new(read),
|
|
|
|
write: AsyncRefCell::new(write),
|
|
|
|
cancel_handle: CancelHandle::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn read(self: Rc<Self>, buf: &mut [u8]) -> Result<usize, AnyError> {
|
|
|
|
let cancel_handle = RcRef::map(self.clone(), |this| &this.cancel_handle);
|
|
|
|
async {
|
|
|
|
let read = RcRef::map(self, |this| &this.read);
|
|
|
|
let mut read = read.borrow_mut().await;
|
|
|
|
Ok(Pin::new(&mut *read).read(buf).await?)
|
|
|
|
}
|
|
|
|
.try_or_cancel(cancel_handle)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn write(self: Rc<Self>, buf: &[u8]) -> Result<usize, AnyError> {
|
|
|
|
let cancel_handle = RcRef::map(self.clone(), |this| &this.cancel_handle);
|
|
|
|
async {
|
|
|
|
let write = RcRef::map(self, |this| &this.write);
|
|
|
|
let mut write = write.borrow_mut().await;
|
|
|
|
Ok(Pin::new(&mut *write).write(buf).await?)
|
|
|
|
}
|
|
|
|
.try_or_cancel(cancel_handle)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for UpgradeStream {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"httpRawUpgradeStream".into()
|
|
|
|
}
|
|
|
|
|
|
|
|
deno_core::impl_readable_byob!();
|
|
|
|
deno_core::impl_writable!();
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
self.cancel_handle.cancel();
|
|
|
|
}
|
|
|
|
}
|