2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-05-16 19:20:32 -04:00
|
|
|
|
2024-07-30 08:34:52 -04:00
|
|
|
use std::borrow::Cow;
|
|
|
|
use std::cell::RefCell;
|
2024-12-12 19:44:42 -05:00
|
|
|
use std::fmt::Debug;
|
2024-07-30 08:34:52 -04:00
|
|
|
use std::pin::Pin;
|
|
|
|
use std::rc::Rc;
|
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
|
|
|
|
|
|
|
use bytes::Bytes;
|
2024-12-12 19:44:42 -05:00
|
|
|
use deno_core::error::bad_resource;
|
|
|
|
use deno_core::error::type_error;
|
2024-07-30 08:34:52 -04:00
|
|
|
use deno_core::futures::stream::Peekable;
|
|
|
|
use deno_core::futures::Future;
|
|
|
|
use deno_core::futures::FutureExt;
|
|
|
|
use deno_core::futures::Stream;
|
|
|
|
use deno_core::futures::StreamExt;
|
2023-10-07 11:34:03 -04:00
|
|
|
use deno_core::op2;
|
2024-07-30 08:34:52 -04:00
|
|
|
use deno_core::serde::Serialize;
|
|
|
|
use deno_core::unsync::spawn;
|
2023-05-16 19:20:32 -04:00
|
|
|
use deno_core::url::Url;
|
2024-07-30 08:34:52 -04:00
|
|
|
use deno_core::AsyncRefCell;
|
|
|
|
use deno_core::AsyncResult;
|
|
|
|
use deno_core::BufView;
|
2023-05-16 19:20:32 -04:00
|
|
|
use deno_core::ByteString;
|
|
|
|
use deno_core::CancelFuture;
|
|
|
|
use deno_core::CancelHandle;
|
2024-07-30 08:34:52 -04:00
|
|
|
use deno_core::CancelTryFuture;
|
2024-12-12 19:44:42 -05:00
|
|
|
use deno_core::Canceled;
|
2023-05-16 19:20:32 -04:00
|
|
|
use deno_core::OpState;
|
2024-07-30 08:34:52 -04:00
|
|
|
use deno_core::RcRef;
|
|
|
|
use deno_core::Resource;
|
2023-12-01 10:56:10 -05:00
|
|
|
use deno_core::ResourceId;
|
2023-05-16 19:20:32 -04:00
|
|
|
use deno_fetch::FetchCancelHandle;
|
|
|
|
use deno_fetch::FetchReturn;
|
2024-07-30 08:34:52 -04:00
|
|
|
use deno_fetch::ResBody;
|
2024-12-12 19:44:42 -05:00
|
|
|
use deno_net::io::TcpStreamResource;
|
|
|
|
use deno_net::ops_tls::TlsStreamResource;
|
|
|
|
use deno_permissions::PermissionCheckError;
|
2024-07-17 19:37:31 -04:00
|
|
|
use http::header::HeaderMap;
|
|
|
|
use http::header::HeaderName;
|
|
|
|
use http::header::HeaderValue;
|
2024-07-24 17:22:43 -04:00
|
|
|
use http::header::AUTHORIZATION;
|
2024-07-17 19:37:31 -04:00
|
|
|
use http::header::CONTENT_LENGTH;
|
|
|
|
use http::Method;
|
|
|
|
use http_body_util::BodyExt;
|
2024-07-30 08:34:52 -04:00
|
|
|
use hyper::body::Frame;
|
2024-12-12 19:44:42 -05:00
|
|
|
use hyper::body::Incoming;
|
2024-07-30 08:34:52 -04:00
|
|
|
use hyper_util::rt::TokioIo;
|
|
|
|
use std::cmp::min;
|
|
|
|
use tokio::io::AsyncReadExt;
|
|
|
|
use tokio::io::AsyncWriteExt;
|
2023-05-16 19:20:32 -04:00
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
#[derive(Default, Serialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
pub struct NodeHttpResponse {
|
|
|
|
pub status: u16,
|
|
|
|
pub status_text: String,
|
|
|
|
pub headers: Vec<(ByteString, ByteString)>,
|
|
|
|
pub url: String,
|
|
|
|
pub response_rid: ResourceId,
|
|
|
|
pub content_length: Option<u64>,
|
|
|
|
pub remote_addr_ip: Option<String>,
|
|
|
|
pub remote_addr_port: Option<u16>,
|
|
|
|
pub error: Option<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
type CancelableResponseResult =
|
|
|
|
Result<Result<http::Response<Incoming>, hyper::Error>, Canceled>;
|
|
|
|
|
|
|
|
pub struct NodeHttpClientResponse {
|
|
|
|
response: Pin<Box<dyn Future<Output = CancelableResponseResult>>>,
|
|
|
|
url: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Debug for NodeHttpClientResponse {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
f.debug_struct("NodeHttpClientResponse")
|
|
|
|
.field("url", &self.url)
|
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl deno_core::Resource for NodeHttpClientResponse {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"nodeHttpClientResponse".into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
|
|
pub enum ConnError {
|
|
|
|
#[error(transparent)]
|
|
|
|
Resource(deno_core::error::AnyError),
|
|
|
|
#[error(transparent)]
|
|
|
|
Permission(#[from] PermissionCheckError),
|
|
|
|
#[error("Invalid URL {0}")]
|
|
|
|
InvalidUrl(Url),
|
|
|
|
#[error(transparent)]
|
|
|
|
InvalidHeaderName(#[from] http::header::InvalidHeaderName),
|
|
|
|
#[error(transparent)]
|
|
|
|
InvalidHeaderValue(#[from] http::header::InvalidHeaderValue),
|
|
|
|
#[error(transparent)]
|
|
|
|
Url(#[from] url::ParseError),
|
|
|
|
#[error(transparent)]
|
|
|
|
Method(#[from] http::method::InvalidMethod),
|
|
|
|
#[error(transparent)]
|
|
|
|
Io(#[from] std::io::Error),
|
|
|
|
#[error("TLS stream is currently in use")]
|
|
|
|
TlsStreamBusy,
|
|
|
|
#[error("TCP stream is currently in use")]
|
|
|
|
TcpStreamBusy,
|
|
|
|
#[error(transparent)]
|
|
|
|
ReuniteTcp(#[from] tokio::net::tcp::ReuniteError),
|
|
|
|
#[error(transparent)]
|
|
|
|
Canceled(#[from] deno_core::Canceled),
|
|
|
|
#[error(transparent)]
|
|
|
|
Hyper(#[from] hyper::Error),
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op2(async, stack_trace)]
|
2023-10-07 11:34:03 -04:00
|
|
|
#[serde]
|
2024-12-12 19:44:42 -05:00
|
|
|
pub async fn op_node_http_request_with_conn<P>(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
2023-10-07 11:34:03 -04:00
|
|
|
#[serde] method: ByteString,
|
|
|
|
#[string] url: String,
|
|
|
|
#[serde] headers: Vec<(ByteString, ByteString)>,
|
2023-12-01 10:56:10 -05:00
|
|
|
#[smi] body: Option<ResourceId>,
|
2024-12-12 19:44:42 -05:00
|
|
|
#[smi] conn_rid: ResourceId,
|
|
|
|
encrypted: bool,
|
|
|
|
) -> Result<FetchReturn, ConnError>
|
2023-05-27 09:42:20 -04:00
|
|
|
where
|
|
|
|
P: crate::NodePermissions + 'static,
|
|
|
|
{
|
2024-12-12 19:44:42 -05:00
|
|
|
let (_handle, mut sender) = if encrypted {
|
|
|
|
let resource_rc = state
|
|
|
|
.borrow_mut()
|
2024-10-18 21:20:58 -04:00
|
|
|
.resource_table
|
2024-12-12 19:44:42 -05:00
|
|
|
.take::<TlsStreamResource>(conn_rid)
|
|
|
|
.map_err(ConnError::Resource)?;
|
|
|
|
let resource =
|
|
|
|
Rc::try_unwrap(resource_rc).map_err(|_e| ConnError::TlsStreamBusy)?;
|
|
|
|
let (read_half, write_half) = resource.into_inner();
|
|
|
|
let tcp_stream = read_half.unsplit(write_half);
|
|
|
|
let io = TokioIo::new(tcp_stream);
|
|
|
|
let (sender, conn) = hyper::client::conn::http1::handshake(io).await?;
|
|
|
|
(
|
|
|
|
tokio::task::spawn(async move { conn.with_upgrades().await }),
|
|
|
|
sender,
|
|
|
|
)
|
2023-05-16 19:20:32 -04:00
|
|
|
} else {
|
2024-12-12 19:44:42 -05:00
|
|
|
let resource_rc = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.take::<TcpStreamResource>(conn_rid)
|
|
|
|
.map_err(ConnError::Resource)?;
|
|
|
|
let resource =
|
|
|
|
Rc::try_unwrap(resource_rc).map_err(|_| ConnError::TcpStreamBusy)?;
|
|
|
|
let (read_half, write_half) = resource.into_inner();
|
|
|
|
let tcp_stream = read_half.reunite(write_half)?;
|
|
|
|
let io = TokioIo::new(tcp_stream);
|
|
|
|
let (sender, conn) = hyper::client::conn::http1::handshake(io).await?;
|
|
|
|
|
|
|
|
// Spawn a task to poll the connection, driving the HTTP state
|
|
|
|
(
|
|
|
|
tokio::task::spawn(async move {
|
|
|
|
conn.with_upgrades().await?;
|
|
|
|
Ok::<_, _>(())
|
|
|
|
}),
|
|
|
|
sender,
|
|
|
|
)
|
2023-05-16 19:20:32 -04:00
|
|
|
};
|
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
// Create the request.
|
2023-05-16 19:20:32 -04:00
|
|
|
let method = Method::from_bytes(&method)?;
|
2024-12-12 19:44:42 -05:00
|
|
|
let mut url_parsed = Url::parse(&url)?;
|
|
|
|
let maybe_authority = deno_fetch::extract_authority(&mut url_parsed);
|
2023-05-16 19:20:32 -04:00
|
|
|
|
2023-05-27 09:42:20 -04:00
|
|
|
{
|
2024-12-12 19:44:42 -05:00
|
|
|
let mut state_ = state.borrow_mut();
|
|
|
|
let permissions = state_.borrow_mut::<P>();
|
|
|
|
permissions.check_net_url(&url_parsed, "ClientRequest")?;
|
2023-05-27 09:42:20 -04:00
|
|
|
}
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
let mut header_map = HeaderMap::new();
|
|
|
|
for (key, value) in headers {
|
2024-10-18 21:20:58 -04:00
|
|
|
let name = HeaderName::from_bytes(&key)?;
|
|
|
|
let v = HeaderValue::from_bytes(&value)?;
|
2023-05-16 19:20:32 -04:00
|
|
|
|
|
|
|
header_map.append(name, v);
|
|
|
|
}
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
let (body, con_len) = if let Some(body) = body {
|
|
|
|
(
|
2024-07-30 08:34:52 -04:00
|
|
|
BodyExt::boxed(NodeHttpResourceToBodyAdapter::new(
|
2024-10-18 21:20:58 -04:00
|
|
|
state
|
2024-12-12 19:44:42 -05:00
|
|
|
.borrow_mut()
|
2024-10-18 21:20:58 -04:00
|
|
|
.resource_table
|
|
|
|
.take_any(body)
|
2024-12-12 19:44:42 -05:00
|
|
|
.map_err(ConnError::Resource)?,
|
2024-07-30 08:34:52 -04:00
|
|
|
)),
|
2024-07-17 19:37:31 -04:00
|
|
|
None,
|
|
|
|
)
|
2023-05-16 19:20:32 -04:00
|
|
|
} else {
|
|
|
|
// POST and PUT requests should always have a 0 length content-length,
|
|
|
|
// if there is no body. https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
|
2024-07-17 19:37:31 -04:00
|
|
|
let len = if matches!(method, Method::POST | Method::PUT) {
|
|
|
|
Some(0)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
(
|
|
|
|
http_body_util::Empty::new()
|
|
|
|
.map_err(|never| match never {})
|
|
|
|
.boxed(),
|
|
|
|
len,
|
|
|
|
)
|
2023-05-16 19:20:32 -04:00
|
|
|
};
|
|
|
|
|
2024-07-17 19:37:31 -04:00
|
|
|
let mut request = http::Request::new(body);
|
|
|
|
*request.method_mut() = method.clone();
|
2024-12-12 19:44:42 -05:00
|
|
|
let path = url_parsed.path();
|
|
|
|
let query = url_parsed.query();
|
|
|
|
*request.uri_mut() = query
|
|
|
|
.map(|q| format!("{}?{}", path, q))
|
|
|
|
.unwrap_or_else(|| path.to_string())
|
2024-07-17 19:37:31 -04:00
|
|
|
.parse()
|
2024-12-12 19:44:42 -05:00
|
|
|
.map_err(|_| ConnError::InvalidUrl(url_parsed.clone()))?;
|
2024-07-17 19:37:31 -04:00
|
|
|
*request.headers_mut() = header_map;
|
|
|
|
|
2024-07-24 17:22:43 -04:00
|
|
|
if let Some((username, password)) = maybe_authority {
|
|
|
|
request.headers_mut().insert(
|
|
|
|
AUTHORIZATION,
|
|
|
|
deno_fetch::basic_auth(&username, password.as_deref()),
|
|
|
|
);
|
|
|
|
}
|
2024-07-17 19:37:31 -04:00
|
|
|
if let Some(len) = con_len {
|
|
|
|
request.headers_mut().insert(CONTENT_LENGTH, len.into());
|
|
|
|
}
|
|
|
|
|
2023-05-16 19:20:32 -04:00
|
|
|
let cancel_handle = CancelHandle::new_rc();
|
|
|
|
let cancel_handle_ = cancel_handle.clone();
|
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
let fut =
|
|
|
|
async move { sender.send_request(request).or_cancel(cancel_handle_).await };
|
2023-05-16 19:20:32 -04:00
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
let rid = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.add(NodeHttpClientResponse {
|
|
|
|
response: Box::pin(fut),
|
|
|
|
url: url.clone(),
|
|
|
|
});
|
2023-05-16 19:20:32 -04:00
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
let cancel_handle_rid = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.add(FetchCancelHandle(cancel_handle));
|
2023-05-16 19:20:32 -04:00
|
|
|
|
|
|
|
Ok(FetchReturn {
|
2024-12-12 19:44:42 -05:00
|
|
|
request_rid: rid,
|
2023-05-16 19:20:32 -04:00
|
|
|
cancel_handle_rid: Some(cancel_handle_rid),
|
|
|
|
})
|
|
|
|
}
|
2024-07-30 08:34:52 -04:00
|
|
|
|
|
|
|
#[op2(async)]
|
|
|
|
#[serde]
|
2024-12-12 19:44:42 -05:00
|
|
|
pub async fn op_node_http_await_response(
|
2024-07-30 08:34:52 -04:00
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
#[smi] rid: ResourceId,
|
2024-12-12 19:44:42 -05:00
|
|
|
) -> Result<NodeHttpResponse, ConnError> {
|
|
|
|
let resource = state
|
2024-07-30 08:34:52 -04:00
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2024-12-12 19:44:42 -05:00
|
|
|
.take::<NodeHttpClientResponse>(rid)
|
|
|
|
.map_err(ConnError::Resource)?;
|
|
|
|
let resource = Rc::try_unwrap(resource)
|
|
|
|
.map_err(|_| ConnError::Resource(bad_resource("NodeHttpClientResponse")))?;
|
2024-07-30 08:34:52 -04:00
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
let res = resource.response.await??;
|
2024-07-30 08:34:52 -04:00
|
|
|
let status = res.status();
|
|
|
|
let mut res_headers = Vec::new();
|
|
|
|
for (key, val) in res.headers().iter() {
|
|
|
|
res_headers.push((key.as_str().into(), val.as_bytes().into()));
|
|
|
|
}
|
|
|
|
|
|
|
|
let content_length = hyper::body::Body::size_hint(res.body()).exact();
|
|
|
|
let remote_addr = res
|
|
|
|
.extensions()
|
|
|
|
.get::<hyper_util::client::legacy::connect::HttpInfo>()
|
|
|
|
.map(|info| info.remote_addr());
|
|
|
|
let (remote_addr_ip, remote_addr_port) = if let Some(addr) = remote_addr {
|
|
|
|
(Some(addr.ip().to_string()), Some(addr.port()))
|
|
|
|
} else {
|
|
|
|
(None, None)
|
|
|
|
};
|
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
let (parts, body) = res.into_parts();
|
|
|
|
let body = body.map_err(deno_core::anyhow::Error::from);
|
|
|
|
let body = body.boxed();
|
|
|
|
|
|
|
|
let res = http::Response::from_parts(parts, body);
|
|
|
|
|
2024-07-30 08:34:52 -04:00
|
|
|
let response_rid = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2024-12-12 19:44:42 -05:00
|
|
|
.add(NodeHttpResponseResource::new(res, content_length));
|
2024-07-30 08:34:52 -04:00
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
Ok(NodeHttpResponse {
|
2024-07-30 08:34:52 -04:00
|
|
|
status: status.as_u16(),
|
|
|
|
status_text: status.canonical_reason().unwrap_or("").to_string(),
|
|
|
|
headers: res_headers,
|
2024-12-12 19:44:42 -05:00
|
|
|
url: resource.url,
|
2024-07-30 08:34:52 -04:00
|
|
|
response_rid,
|
|
|
|
content_length,
|
|
|
|
remote_addr_ip,
|
|
|
|
remote_addr_port,
|
|
|
|
error: None,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op2(async)]
|
|
|
|
#[smi]
|
|
|
|
pub async fn op_node_http_fetch_response_upgrade(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
#[smi] rid: ResourceId,
|
2024-12-12 19:44:42 -05:00
|
|
|
) -> Result<ResourceId, ConnError> {
|
2024-07-30 08:34:52 -04:00
|
|
|
let raw_response = state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
2024-12-12 19:44:42 -05:00
|
|
|
.take::<NodeHttpResponseResource>(rid)
|
|
|
|
.map_err(ConnError::Resource)?;
|
2024-07-30 08:34:52 -04:00
|
|
|
let raw_response = Rc::try_unwrap(raw_response)
|
|
|
|
.expect("Someone is holding onto NodeHttpFetchResponseResource");
|
|
|
|
|
|
|
|
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);
|
|
|
|
let upgraded = raw_response.upgrade().await?;
|
|
|
|
{
|
|
|
|
// Stage 3: Pump the data
|
|
|
|
let (mut upgraded_rx, mut upgraded_tx) =
|
|
|
|
tokio::io::split(TokioIo::new(upgraded));
|
|
|
|
|
|
|
|
spawn(async move {
|
|
|
|
let mut buf = [0; 1024];
|
|
|
|
loop {
|
|
|
|
let read = upgraded_rx.read(&mut buf).await?;
|
|
|
|
if read == 0 {
|
2024-09-05 00:30:18 -04:00
|
|
|
read_tx.shutdown().await?;
|
2024-07-30 08:34:52 -04:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
read_tx.write_all(&buf[..read]).await?;
|
|
|
|
}
|
2024-12-12 19:44:42 -05:00
|
|
|
Ok::<_, ConnError>(())
|
2024-07-30 08:34:52 -04:00
|
|
|
});
|
|
|
|
spawn(async move {
|
|
|
|
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?;
|
|
|
|
}
|
2024-12-12 19:44:42 -05:00
|
|
|
Ok::<_, ConnError>(())
|
2024-07-30 08:34:52 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(
|
|
|
|
state
|
|
|
|
.borrow_mut()
|
|
|
|
.resource_table
|
|
|
|
.add(UpgradeStream::new(read_rx, write_tx)),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
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(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-18 21:20:58 -04:00
|
|
|
async fn read(
|
|
|
|
self: Rc<Self>,
|
|
|
|
buf: &mut [u8],
|
|
|
|
) -> Result<usize, std::io::Error> {
|
2024-07-30 08:34:52 -04:00
|
|
|
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;
|
2024-10-18 21:20:58 -04:00
|
|
|
Pin::new(&mut *read).read(buf).await
|
2024-07-30 08:34:52 -04:00
|
|
|
}
|
|
|
|
.try_or_cancel(cancel_handle)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
2024-10-18 21:20:58 -04:00
|
|
|
async fn write(self: Rc<Self>, buf: &[u8]) -> Result<usize, std::io::Error> {
|
2024-07-30 08:34:52 -04:00
|
|
|
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;
|
2024-10-18 21:20:58 -04:00
|
|
|
Pin::new(&mut *write).write(buf).await
|
2024-07-30 08:34:52 -04:00
|
|
|
}
|
|
|
|
.try_or_cancel(cancel_handle)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resource for UpgradeStream {
|
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"fetchUpgradedStream".into()
|
|
|
|
}
|
|
|
|
|
|
|
|
deno_core::impl_readable_byob!();
|
|
|
|
deno_core::impl_writable!();
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
self.cancel_handle.cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type BytesStream =
|
|
|
|
Pin<Box<dyn Stream<Item = Result<bytes::Bytes, std::io::Error>> + Unpin>>;
|
|
|
|
|
|
|
|
pub enum NodeHttpFetchResponseReader {
|
|
|
|
Start(http::Response<ResBody>),
|
|
|
|
BodyReader(Peekable<BytesStream>),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for NodeHttpFetchResponseReader {
|
|
|
|
fn default() -> Self {
|
|
|
|
let stream: BytesStream = Box::pin(deno_core::futures::stream::empty());
|
|
|
|
Self::BodyReader(stream.peekable())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
2024-12-12 19:44:42 -05:00
|
|
|
pub struct NodeHttpResponseResource {
|
2024-07-30 08:34:52 -04:00
|
|
|
pub response_reader: AsyncRefCell<NodeHttpFetchResponseReader>,
|
|
|
|
pub cancel: CancelHandle,
|
|
|
|
pub size: Option<u64>,
|
|
|
|
}
|
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
impl NodeHttpResponseResource {
|
2024-07-30 08:34:52 -04:00
|
|
|
pub fn new(response: http::Response<ResBody>, size: Option<u64>) -> Self {
|
|
|
|
Self {
|
|
|
|
response_reader: AsyncRefCell::new(NodeHttpFetchResponseReader::Start(
|
|
|
|
response,
|
|
|
|
)),
|
|
|
|
cancel: CancelHandle::default(),
|
|
|
|
size,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-18 21:20:58 -04:00
|
|
|
pub async fn upgrade(self) -> Result<hyper::upgrade::Upgraded, hyper::Error> {
|
2024-07-30 08:34:52 -04:00
|
|
|
let reader = self.response_reader.into_inner();
|
|
|
|
match reader {
|
|
|
|
NodeHttpFetchResponseReader::Start(resp) => {
|
2024-12-12 19:44:42 -05:00
|
|
|
hyper::upgrade::on(resp).await
|
2024-07-30 08:34:52 -04:00
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-12-12 19:44:42 -05:00
|
|
|
impl Resource for NodeHttpResponseResource {
|
2024-07-30 08:34:52 -04:00
|
|
|
fn name(&self) -> Cow<str> {
|
|
|
|
"fetchResponse".into()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn read(self: Rc<Self>, limit: usize) -> AsyncResult<BufView> {
|
|
|
|
Box::pin(async move {
|
|
|
|
let mut reader =
|
|
|
|
RcRef::map(&self, |r| &r.response_reader).borrow_mut().await;
|
|
|
|
|
|
|
|
let body = loop {
|
|
|
|
match &mut *reader {
|
|
|
|
NodeHttpFetchResponseReader::BodyReader(reader) => break reader,
|
|
|
|
NodeHttpFetchResponseReader::Start(_) => {}
|
|
|
|
}
|
|
|
|
|
|
|
|
match std::mem::take(&mut *reader) {
|
|
|
|
NodeHttpFetchResponseReader::Start(resp) => {
|
|
|
|
let stream: BytesStream =
|
|
|
|
Box::pin(resp.into_body().into_data_stream().map(|r| {
|
|
|
|
r.map_err(|err| {
|
|
|
|
std::io::Error::new(std::io::ErrorKind::Other, err)
|
|
|
|
})
|
|
|
|
}));
|
|
|
|
*reader =
|
|
|
|
NodeHttpFetchResponseReader::BodyReader(stream.peekable());
|
|
|
|
}
|
|
|
|
NodeHttpFetchResponseReader::BodyReader(_) => unreachable!(),
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let fut = async move {
|
|
|
|
let mut reader = Pin::new(body);
|
|
|
|
loop {
|
|
|
|
match reader.as_mut().peek_mut().await {
|
|
|
|
Some(Ok(chunk)) if !chunk.is_empty() => {
|
|
|
|
let len = min(limit, chunk.len());
|
|
|
|
let chunk = chunk.split_to(len);
|
|
|
|
break Ok(chunk.into());
|
|
|
|
}
|
|
|
|
// This unwrap is safe because `peek_mut()` returned `Some`, and thus
|
|
|
|
// currently has a peeked value that can be synchronously returned
|
|
|
|
// from `next()`.
|
|
|
|
//
|
|
|
|
// The future returned from `next()` is always ready, so we can
|
|
|
|
// safely call `await` on it without creating a race condition.
|
|
|
|
Some(_) => match reader.as_mut().next().await.unwrap() {
|
|
|
|
Ok(chunk) => assert!(chunk.is_empty()),
|
2024-12-12 19:44:42 -05:00
|
|
|
Err(err) => break Err(type_error(err.to_string())),
|
2024-07-30 08:34:52 -04:00
|
|
|
},
|
|
|
|
None => break Ok(BufView::empty()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let cancel_handle = RcRef::map(self, |r| &r.cancel);
|
2024-12-12 19:44:42 -05:00
|
|
|
fut.try_or_cancel(cancel_handle).await
|
2024-07-30 08:34:52 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn size_hint(&self) -> (u64, Option<u64>) {
|
|
|
|
(self.size.unwrap_or(0), self.size)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn close(self: Rc<Self>) {
|
|
|
|
self.cancel.cancel()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(clippy::type_complexity)]
|
|
|
|
pub struct NodeHttpResourceToBodyAdapter(
|
|
|
|
Rc<dyn Resource>,
|
2024-10-18 21:20:58 -04:00
|
|
|
Option<
|
|
|
|
Pin<Box<dyn Future<Output = Result<BufView, deno_core::anyhow::Error>>>>,
|
|
|
|
>,
|
2024-07-30 08:34:52 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
impl NodeHttpResourceToBodyAdapter {
|
|
|
|
pub fn new(resource: Rc<dyn Resource>) -> Self {
|
|
|
|
let future = resource.clone().read(64 * 1024);
|
|
|
|
Self(resource, Some(future))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// SAFETY: we only use this on a single-threaded executor
|
|
|
|
unsafe impl Send for NodeHttpResourceToBodyAdapter {}
|
|
|
|
// SAFETY: we only use this on a single-threaded executor
|
|
|
|
unsafe impl Sync for NodeHttpResourceToBodyAdapter {}
|
|
|
|
|
|
|
|
impl Stream for NodeHttpResourceToBodyAdapter {
|
2024-10-18 21:20:58 -04:00
|
|
|
type Item = Result<Bytes, deno_core::anyhow::Error>;
|
2024-07-30 08:34:52 -04:00
|
|
|
|
|
|
|
fn poll_next(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
) -> Poll<Option<Self::Item>> {
|
|
|
|
let this = self.get_mut();
|
|
|
|
if let Some(mut fut) = this.1.take() {
|
|
|
|
match fut.poll_unpin(cx) {
|
|
|
|
Poll::Pending => {
|
|
|
|
this.1 = Some(fut);
|
|
|
|
Poll::Pending
|
|
|
|
}
|
|
|
|
Poll::Ready(res) => match res {
|
|
|
|
Ok(buf) if buf.is_empty() => Poll::Ready(None),
|
|
|
|
Ok(buf) => {
|
2024-12-12 19:44:42 -05:00
|
|
|
let bytes: Bytes = buf.to_vec().into();
|
2024-07-30 08:34:52 -04:00
|
|
|
this.1 = Some(this.0.clone().read(64 * 1024));
|
2024-12-12 19:44:42 -05:00
|
|
|
Poll::Ready(Some(Ok(bytes)))
|
2024-07-30 08:34:52 -04:00
|
|
|
}
|
|
|
|
Err(err) => Poll::Ready(Some(Err(err))),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Poll::Ready(None)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl hyper::body::Body for NodeHttpResourceToBodyAdapter {
|
|
|
|
type Data = Bytes;
|
2024-10-18 21:20:58 -04:00
|
|
|
type Error = deno_core::anyhow::Error;
|
2024-07-30 08:34:52 -04:00
|
|
|
|
|
|
|
fn poll_frame(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
|
|
|
|
match self.poll_next(cx) {
|
|
|
|
Poll::Ready(Some(res)) => Poll::Ready(Some(res.map(Frame::data))),
|
|
|
|
Poll::Ready(None) => Poll::Ready(None),
|
|
|
|
Poll::Pending => Poll::Pending,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for NodeHttpResourceToBodyAdapter {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
self.0.clone().close()
|
|
|
|
}
|
|
|
|
}
|