diff --git a/crates/perry-ext-http-server/src/http2_server.rs b/crates/perry-ext-http-server/src/http2_server.rs index d1bd4e2181a..b8cbb7f40c1 100644 --- a/crates/perry-ext-http-server/src/http2_server.rs +++ b/crates/perry-ext-http-server/src/http2_server.rs @@ -806,6 +806,8 @@ async fn handle_h2_request( h2_stream_headers, request_listeners, handler, + check_continue_listeners: Vec::new(), + is_check_continue: false, }; if request_tx.send(pending).await.is_err() { return Ok(Response::builder() diff --git a/crates/perry-ext-http-server/src/https_server.rs b/crates/perry-ext-http-server/src/https_server.rs index 14444816b34..5bf2a64fc51 100644 --- a/crates/perry-ext-http-server/src/https_server.rs +++ b/crates/perry-ext-http-server/src/https_server.rs @@ -348,6 +348,12 @@ async fn handle_https_request( // #2132 — capture before `req` / `headers_lower` are consumed below. let http_version = req.version(); let req_connection = headers_lower.get("connection").cloned(); + // #5080 — `Expect: 100-continue` routes to `'checkContinue'` (hyper + // auto-sends the interim `100 Continue` once the body is polled below). + let expects_continue = headers_lower + .get("expect") + .map(|v| v.to_ascii_lowercase().contains("100-continue")) + .unwrap_or(false); let body = match req.collect().await { Ok(c) => c.to_bytes().to_vec(), Err(_) => Vec::new(), @@ -363,15 +369,21 @@ async fn handle_https_request( )); let (response_tx, response_rx) = oneshot::channel::(); let sr_handle = alloc_server_response_for_request(response_tx, im_handle); - let (request_listeners, handler, keep_alive_timeout) = + let (request_listeners, handler, keep_alive_timeout, check_continue_listeners) = match get_handle::(server_handle) { Some(s) => ( s.base.listeners.get("request").cloned().unwrap_or_default(), s.handler, s.base.keep_alive_timeout, + s.base + .listeners + .get("checkContinue") + .cloned() + .unwrap_or_default(), ), - None => (Vec::new(), 0, 5_000.0), + None => (Vec::new(), 0, 5_000.0, Vec::new()), }; + let is_check_continue = expects_continue && !check_continue_listeners.is_empty(); let pending = HttpPendingRequest { server_handle, request_handle: im_handle, @@ -381,6 +393,8 @@ async fn handle_https_request( h2_stream_headers: Vec::new(), request_listeners, handler, + check_continue_listeners, + is_check_continue, }; if request_tx.send(pending).await.is_err() { return Ok(Response::builder() @@ -427,6 +441,27 @@ pub(crate) fn process_pending_https(pending: HttpPendingRequest) { // #4903 — Node invokes `'request'` listeners (and the `createServer` // handler, which is one) with `this` bound to the server. let server_this = handle_to_pointer_f64(pending.server_handle); + // #5080 — an `Expect: 100-continue` request with a `'checkContinue'` + // listener fires that listener instead of the `'request'` path. + if pending.is_check_continue { + for cb in &pending.check_continue_listeners { + if *cb == 0 { + continue; + } + unsafe { + let raw = *cb as *const RawClosureHeader; + let closure = JsClosure::from_raw(raw); + if !closure.is_null() { + with_implicit_this(server_this, || { + let _ = closure.call2(req_f64, res_f64); + }); + } + js_promise_run_microtasks(); + } + } + crate::server::finalize_or_park_request(&pending); + return; + } for cb in &pending.request_listeners { if *cb == 0 { continue; diff --git a/crates/perry-ext-http-server/src/response.rs b/crates/perry-ext-http-server/src/response.rs index 499a77ce971..7c58314cc56 100644 --- a/crates/perry-ext-http-server/src/response.rs +++ b/crates/perry-ext-http-server/src/response.rs @@ -1395,13 +1395,18 @@ pub unsafe extern "C" fn js_node_http_res_write_early_hints( } } -/// `res.writeContinue()` — emits an HTTP/1.1 100-continue. Phase 1 -/// stores the intent only; the actual 100-continue sequence requires -/// a streaming body path that we'll wire up in a follow-up. +/// `res.writeContinue()` — acknowledge an `Expect: 100-continue` request. +/// +/// #5080: the interim `HTTP/1.1 100 Continue` is written by hyper the moment +/// the request body is polled (`req.collect()` in the service fn), which is +/// what unblocks the client's withheld body before `'checkContinue'` even +/// fires on the main thread. So by the time the handler calls +/// `writeContinue()` the 100 is already on the wire; this entry point exists +/// for API parity (the canonical `checkContinue` handler calls it) and is a +/// confirmation no-op rather than a second 100 line. #[no_mangle] pub extern "C" fn js_node_http_res_write_continue(_handle: i64) { - // No-op stub. Acceptable per #577 — most modern clients don't - // negotiate Expect: 100-continue against a server that buffers. + // Interim 100 already flushed by hyper on first body poll — see above. } /// `res.writeProcessing()` — emits an HTTP/1.1 102-Processing. Stub. diff --git a/crates/perry-ext-http-server/src/server.rs b/crates/perry-ext-http-server/src/server.rs index 59cce0e97ea..b91fb9345d8 100644 --- a/crates/perry-ext-http-server/src/server.rs +++ b/crates/perry-ext-http-server/src/server.rs @@ -171,6 +171,15 @@ pub struct HttpPendingRequest { /// dispatch loop doesn't need to re-borrow the server handle. pub request_listeners: Vec, pub handler: i64, + /// #5080 — `'checkContinue'` listeners snapshotted at request time. + /// When `is_check_continue` is set these fire *instead of* the + /// `'request'` listeners + handler (Node dispatches an + /// `Expect: 100-continue` request to `'checkContinue'` when a listener + /// exists, and only emits `'request'` otherwise). + pub check_continue_listeners: Vec, + /// #5080 — route this request to `'checkContinue'` rather than the + /// normal `'request'` path. + pub is_check_continue: bool, } /// Phase 4 — pending WebSocket upgrade ready to fire `'upgrade'` @@ -951,6 +960,14 @@ async fn handle_request( // `headers_lower`) are consumed below. let http_version = req.version(); let req_connection = headers_lower.get("connection").cloned(); + // #5080 — `Expect: 100-continue` routes to `'checkContinue'` when a + // listener exists. hyper auto-sends the interim `100 Continue` once the + // body below is polled, so the client's withheld body arrives before + // `req.collect()` completes. + let expects_continue = headers_lower + .get("expect") + .map(|v| v.to_ascii_lowercase().contains("100-continue")) + .unwrap_or(false); // Phase 4 — WebSocket upgrade detection. If the request looks // like a WS upgrade, branch into the handshake path: build the @@ -1017,16 +1034,22 @@ async fn handle_request( let (response_tx, response_rx) = oneshot::channel::(); let sr_handle = alloc_server_response_for_request(response_tx, im_handle); - let (request_listeners, handler, keep_alive_timeout) = + let (request_listeners, handler, keep_alive_timeout, check_continue_listeners) = match get_handle::(server_handle) { Some(s) => ( s.listeners.get("request").cloned().unwrap_or_default(), s.handler, s.keep_alive_timeout, + s.listeners + .get("checkContinue") + .cloned() + .unwrap_or_default(), ), - None => (Vec::new(), 0, 5_000.0), + None => (Vec::new(), 0, 5_000.0, Vec::new()), }; + let is_check_continue = expects_continue && !check_continue_listeners.is_empty(); + let pending = HttpPendingRequest { server_handle, request_handle: im_handle, @@ -1036,6 +1059,8 @@ async fn handle_request( h2_stream_headers: Vec::new(), request_listeners, handler, + check_continue_listeners, + is_check_continue, }; if request_tx.send(pending).await.is_err() { @@ -1662,6 +1687,31 @@ fn process_pending(pending: HttpPendingRequest) { // `function (req, res) { this.address().port }` handler idiom works // (#4903). Bind for the synchronous call only — microtasks run outside. let server_this = handle_to_pointer_f64(pending.server_handle); + + // #5080 — an `Expect: 100-continue` request with a `'checkContinue'` + // listener fires that listener *instead of* `'request'` + the handler + // (Node's dispatch). The listener calls `res.writeContinue()` and then + // drives the exchange itself. + if pending.is_check_continue { + for cb in &pending.check_continue_listeners { + if *cb == 0 { + continue; + } + unsafe { + let raw = *cb as *const RawClosureHeader; + let closure = JsClosure::from_raw(raw); + if !closure.is_null() { + with_implicit_this(server_this, || { + let _ = closure.call2(req_f64, res_f64); + }); + } + js_promise_run_microtasks(); + } + } + finalize_or_park_request(&pending); + return; + } + for cb in &pending.request_listeners { if *cb == 0 { continue; diff --git a/crates/perry-ext-http/src/continue_client.rs b/crates/perry-ext-http/src/continue_client.rs new file mode 100644 index 00000000000..80f5819b208 --- /dev/null +++ b/crates/perry-ext-http/src/continue_client.rs @@ -0,0 +1,347 @@ +//! Client raw-socket path for `Expect: 100-continue` (issue #5080). +//! +//! reqwest auto-consumes the interim `100 Continue` response, so a +//! `ClientRequest` carrying `Expect: 100-continue` never surfaces the +//! `'continue'` event through the pooled client. This module speaks +//! HTTP/1.1 over a plain `TcpStream`: it flushes the request head with the +//! body withheld, waits for the server's interim `100 Continue`, emits +//! `'continue'`, then sends the body (handed over from the deferred +//! `req.end()` through a oneshot) and parses the final response with the +//! shared [`crate::parse_http_response`]. +//! +//! Plain `http://` only — an `https` 100-continue handshake would need the +//! TLS-wrapped socket path and stays on the reqwest route (no `'continue'` +//! event, matching the pre-#5080 behavior). + +use std::collections::HashMap; + +use perry_ffi::{spawn_blocking_with_reactor as spawn_blocking, with_handle_mut, Handle}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use crate::plain_client::parse_http_response; +use crate::{push_event, ClientRequestHandle, PendingHttpEvent}; + +/// Whether the request headers ask for the `100-continue` handshake. +pub(crate) fn wants_continue(headers: &HashMap) -> bool { + headers.iter().any(|(name, value)| { + name.eq_ignore_ascii_case("expect") && value.to_ascii_lowercase().contains("100-continue") + }) +} + +/// Queue an `arm_expect_continue` for the next event-loop tick. Node flushes a +/// request's head on `nextTick`, not at construction, so deferring lets a +/// post-construction `setHeader(...)` (including a late `Expect: +/// 100-continue`) reach the wire before the head is snapshotted. +pub(crate) fn defer_arm(handle: Handle) { + crate::push_event(crate::PendingHttpEvent::DeferredArmContinue { + request_handle: handle, + }); +} + +/// #5080 — if the freshly-built request carries `Expect: 100-continue` +/// (plain `http://` only), flush its head now and arm the deferred-body +/// channel. Node puts the head on the wire before `end()` for a continue +/// request and withholds the body until the server's interim `100 Continue` +/// drives the `'continue'` event. A no-op otherwise; the reqwest path keeps +/// the buffered-dispatch-at-`end()` behavior for every other request. +pub(crate) fn arm_expect_continue(handle: Handle) { + let snapshot = with_handle_mut::(handle, |req| { + if req.ended || req.expects_continue || !req.url.starts_with("http://") { + return None; + } + if !wants_continue(&req.headers) { + return None; + } + req.expects_continue = true; + Some(( + req.method.clone(), + req.url.clone(), + req.headers.clone(), + req.timeout_ms, + )) + }) + .flatten(); + if let Some((method, url, headers, timeout_ms)) = snapshot { + dispatch_expect_continue(handle, method, url, headers, timeout_ms); + } +} + +/// Serialize the request head for the continue exchange. The body is +/// withheld, so frame it `Transfer-Encoding: chunked` unless the caller +/// pinned an explicit `Content-Length` / `Transfer-Encoding`; force +/// `Connection: close` (the final response is read until EOF). Drops any +/// caller-supplied `Connection` / `Host` header (`Host` is set from the URL). +fn serialize_continue_head( + method: &str, + path: &str, + host_header: &str, + headers: &HashMap, + use_chunked: bool, +) -> Vec { + let mut head = format!("{} {} HTTP/1.1\r\nHost: {}\r\n", method, path, host_header); + for (k, v) in headers { + if k.eq_ignore_ascii_case("connection") || k.eq_ignore_ascii_case("host") { + continue; + } + head.push_str(k); + head.push_str(": "); + head.push_str(v); + head.push_str("\r\n"); + } + if use_chunked { + head.push_str("Transfer-Encoding: chunked\r\n"); + } + head.push_str("Connection: close\r\n\r\n"); + head.into_bytes() +} + +/// Flush the head of an `Expect: 100-continue` request and arm the deferred +/// body channel. Called on the main thread at request-creation time (Node +/// puts the head on the wire before `end()` for a continue request); the +/// actual exchange runs on a tokio task. +pub(crate) fn dispatch_expect_continue( + request_handle: Handle, + method: String, + url: String, + headers: HashMap, + timeout_ms: Option, +) { + let parsed = match reqwest::Url::parse(&url) { + Ok(u) => u, + Err(e) => { + push_event(PendingHttpEvent::Error { + request_handle, + error_message: e.to_string(), + }); + return; + } + }; + let host = parsed.host_str().unwrap_or("localhost").to_string(); + let port = parsed.port_or_known_default().unwrap_or(80); + let host_header = match parsed.port() { + Some(p) => format!("{}:{}", host, p), + None => host.clone(), + }; + let mut path = parsed.path().to_string(); + if path.is_empty() { + path.push('/'); + } + if let Some(q) = parsed.query() { + path.push('?'); + path.push_str(q); + } + + let use_chunked = !headers.iter().any(|(k, _)| { + k.eq_ignore_ascii_case("content-length") || k.eq_ignore_ascii_case("transfer-encoding") + }); + let head = serialize_continue_head(&method, &path, &host_header, &headers, use_chunked); + + // Hand-off for the withheld body: `req.end()` sends the buffered body + // here once the user's `'continue'` handler (or any later end()) runs. + let (body_tx, body_rx) = tokio::sync::oneshot::channel::>(); + with_handle_mut::(request_handle, |req| { + req.continue_body_tx = Some(body_tx); + }); + + let deadline = std::time::Duration::from_millis(timeout_ms.unwrap_or(30_000)); + + spawn_blocking(move || { + // Defeat LTO dead-stripping of tokio's CONTEXT statics — same + // workaround dispatch_request needs (see spawn_socket_runner). + let try_h = tokio::runtime::Handle::try_current(); + std::hint::black_box(&try_h); + if try_h.is_err() { + push_event(PendingHttpEvent::Error { + request_handle, + error_message: "http client runtime unavailable".to_string(), + }); + return; + } + let handle = tokio::runtime::Handle::current(); + let jh = handle.spawn(async move { + if let Err(error_message) = run_exchange( + request_handle, + host, + port, + head, + use_chunked, + body_rx, + deadline, + ) + .await + { + push_event(PendingHttpEvent::Error { + request_handle, + error_message, + }); + } + }); + std::hint::black_box(&jh); + std::mem::forget(jh); + }); +} + +/// Drive the continue exchange: write the head, observe the interim +/// `100 Continue`, emit `'continue'`, send the deferred body, then read + +/// parse the final response. +async fn run_exchange( + request_handle: Handle, + host: String, + port: u16, + head: Vec, + use_chunked: bool, + body_rx: tokio::sync::oneshot::Receiver>, + deadline: std::time::Duration, +) -> Result<(), String> { + let mut stream = tokio::time::timeout( + deadline, + tokio::net::TcpStream::connect((host.as_str(), port)), + ) + .await + .map_err(|_| "request timed out".to_string())? + .map_err(|e| e.to_string())?; + write_all(&mut stream, &head, deadline).await?; + + // Read until the first complete header block. A 1xx status (e.g. + // `100 Continue`) drives the `'continue'` event; a final (>=200) + // response means the server declined the handshake — surface it as-is. + let mut buf: Vec = Vec::new(); + let mut chunk = [0u8; 8 * 1024]; + let mut got_interim = false; + loop { + if let Some(pos) = find_header_end(&buf) { + let status = parse_status_code(&buf[..pos]); + if (100..200).contains(&status) { + got_interim = true; + buf.drain(..pos + 4); + break; + } else if status >= 200 { + // Final response, no continue — leave `buf` intact for the + // EOF read below to finish + parse. + break; + } + } + let n = read_chunk(&mut stream, &mut chunk, deadline).await?; + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + } + + if got_interim { + push_event(PendingHttpEvent::Continue { request_handle }); + // Wait for the deferred body handed over by `req.end()`. A dropped + // sender (request torn down) resolves to an empty body. + let body = tokio::time::timeout(deadline, body_rx) + .await + .map_err(|_| "request timed out".to_string())? + .unwrap_or_default(); + let framed = if use_chunked { + frame_chunked(&body) + } else { + body + }; + write_all(&mut stream, &framed, deadline).await?; + } + + // Read the rest of the (final) response to EOF — the head forces + // `Connection: close`, so the peer closes once it's done. + loop { + let n = read_chunk(&mut stream, &mut chunk, deadline).await?; + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + } + + let final_bytes = strip_interim_blocks(buf); + let parsed = parse_http_response(&final_bytes)?; + // Deliver via the same streaming path the pooled reqwest client uses + // (`ResponseHead` → `ResponseChunk` → `ResponseEnd`): the head fires the + // `(res) => …` callback / `'response'` listeners, then the body + end + // edges drain on later ticks. This matches the normal client's + // observable ordering and reuses its well-exercised delivery helpers. + push_event(PendingHttpEvent::ResponseHead { + request_handle, + status: parsed.status, + status_message: parsed.status_message, + headers: parsed.headers, + }); + if !parsed.body.is_empty() { + push_event(PendingHttpEvent::ResponseChunk { + request_handle, + chunk: parsed.body, + }); + } + push_event(PendingHttpEvent::ResponseEnd { request_handle }); + Ok(()) +} + +/// One deadline-bounded `read`, mapping a timeout / IO error to a string. +async fn read_chunk( + stream: &mut tokio::net::TcpStream, + chunk: &mut [u8], + deadline: std::time::Duration, +) -> Result { + tokio::time::timeout(deadline, stream.read(chunk)) + .await + .map_err(|_| "request timed out".to_string())? + .map_err(|e| e.to_string()) +} + +/// Deadline-bounded `write_all` so a stalled peer can't hang the exchange +/// even when the request set a `timeout`. +async fn write_all( + stream: &mut tokio::net::TcpStream, + bytes: &[u8], + deadline: std::time::Duration, +) -> Result<(), String> { + tokio::time::timeout(deadline, stream.write_all(bytes)) + .await + .map_err(|_| "request timed out".to_string())? + .map_err(|e| e.to_string()) +} + +/// Frame `body` as a single HTTP/1.1 chunk plus the terminating chunk. +fn frame_chunked(body: &[u8]) -> Vec { + let mut framed = Vec::with_capacity(body.len() + 16); + if !body.is_empty() { + framed.extend_from_slice(format!("{:x}\r\n", body.len()).as_bytes()); + framed.extend_from_slice(body); + framed.extend_from_slice(b"\r\n"); + } + framed.extend_from_slice(b"0\r\n\r\n"); + framed +} + +/// Offset of the `\r\n\r\n` that terminates the header block, if present. +fn find_header_end(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +/// Parse the numeric status code out of a status line (`HTTP/1.1 100 ...`). +fn parse_status_code(head: &[u8]) -> u16 { + let text = String::from_utf8_lossy(head); + text.lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|code| code.parse::().ok()) + .unwrap_or(0) +} + +/// Drop any leading interim (1xx) header blocks so the remainder begins at +/// the final response. Defensive: the read loop already strips the interim +/// `100 Continue` before sending the body, but a server may emit more than +/// one informational response. +fn strip_interim_blocks(mut buf: Vec) -> Vec { + loop { + let Some(pos) = find_header_end(&buf) else { + return buf; + }; + if (100..200).contains(&parse_status_code(&buf[..pos])) { + buf.drain(..pos + 4); + } else { + return buf; + } + } +} diff --git a/crates/perry-ext-http/src/lib.rs b/crates/perry-ext-http/src/lib.rs index efb5f726ab4..b1ad72c8f67 100644 --- a/crates/perry-ext-http/src/lib.rs +++ b/crates/perry-ext-http/src/lib.rs @@ -65,6 +65,12 @@ mod tls_client; mod plain_client; use plain_client::{dispatch_plain_http_request, parse_http_response}; +// Raw-socket `Expect: 100-continue` client path (#5080) — flushes the head, +// observes the interim `100 Continue`, emits `'continue'`, then sends the +// withheld body. reqwest swallows the interim response, so this bypass is +// needed to surface it. +mod continue_client; + // Async reqwest dispatch (`dispatch_request` + TLS-client selection), // extracted to keep `lib.rs` under the 2000-line lint cap. mod client_dispatch; @@ -167,6 +173,14 @@ pub(crate) enum PendingHttpEvent { /// Drains the queued `write(chunk, cb)` callbacks, then `'finish'`, /// then the `end(..., cb)` callback — Node's flush ordering. Flushed { request_handle: Handle }, + /// #5080 — the server answered an `Expect: 100-continue` request with + /// an interim `100 Continue`. Drains to the request's `'continue'` + /// listeners; the canonical handler then sends the withheld body. + Continue { request_handle: Handle }, + /// #5080 — arm the `Expect: 100-continue` head flush on the next event-loop + /// tick (Node's nextTick), so post-construction `setHeader(...)` — including + /// a late `Expect` — reaches the wire. No-op for non-continue/sent requests. + DeferredArmContinue { request_handle: Handle }, } lazy_static! { @@ -320,6 +334,15 @@ pub struct ClientRequestHandle { /// `0` until the head is delivered (and always for the full-buffer /// delivery paths). incoming_handle: Handle, + /// #5080 — the request carries `Expect: 100-continue`, so its head was + /// flushed up front by the raw-socket continue path and the body is + /// withheld until the server's interim `100 Continue` arrives. `end()` + /// hands the (now-known) body over the `continue_body_tx` channel + /// instead of dispatching a fresh exchange. + expects_continue: bool, + /// #5080 — set while the continue exchange task is waiting for the + /// deferred body; `end()` sends the buffered body here (once). + continue_body_tx: Option>>, } // SAFETY: closure pointers point into program-global code/data and @@ -493,6 +516,8 @@ fn make_request_handle( agent_handle, tls: tls_client::TlsOptions::default(), incoming_handle: 0, + expects_continue: false, + continue_body_tx: None, }); // #4909 — `options.timeout` arms the inactivity timer as soon as the // socket exists in Node, not at `end()`; a request that is never @@ -840,6 +865,7 @@ unsafe fn request_common(arg_f64: f64, callback: i64, default_protocol: &str) -> }; let handle = make_request_handle(method, url, headers, timeout, callback, agent_handle); attach_tls_options(handle, arg_f64); // #4906 + continue_client::defer_arm(handle); // #5080 (next-tick head flush) handle } @@ -945,6 +971,8 @@ unsafe fn request_overload(args_array: i64, default_protocol: &str, force_get: b if force_get { // `get()` auto-`end()`s, kicking off the request. js_http_client_request_end(handle, f64::from_bits(TAG_UNDEFINED)); + } else { + continue_client::defer_arm(handle); // #5080 (next-tick head flush) } handle } @@ -1013,6 +1041,37 @@ pub(crate) unsafe fn client_request_end_impl(handle: Handle, body_f64: f64) -> H }); } + // #5080 — `end()` is a send boundary: arm the continue path now if it + // carries `Expect: 100-continue` and the next-tick arm hasn't run yet. + continue_client::arm_expect_continue(handle); + + // #5080 — an `Expect: 100-continue` request flushed its head up front; + // this `end()` just hands the (now-known) body to the in-flight continue + // exchange over the oneshot. The first call fires the flush ordering + // (write/finish/end callbacks); a later one is an idempotent no-op. + let (is_continue, first_end) = with_handle_mut::(handle, |req| { + if !req.expects_continue { + return (false, false); + } + if let Some(tx) = req.continue_body_tx.take() { + let body = std::mem::take(&mut req.body); + let _ = tx.send(body); + req.ended = true; + (true, true) + } else { + (true, false) + } + }) + .unwrap_or((false, false)); + if is_continue { + if first_end { + push_event(PendingHttpEvent::Flushed { + request_handle: handle, + }); + } + return handle; + } + let snapshot = with_handle_mut::(handle, |req| { if req.ended { // Already dispatched by `flushHeaders()` — the exchange is in @@ -1070,6 +1129,13 @@ pub(crate) unsafe fn client_request_flush_headers(handle: Handle) { if client_request_surface::request_destroyed(handle) { return; } + // #5080 — `flushHeaders()` is a send boundary; when it arms the continue + // path, that exchange owns the head, so don't also dispatch via reqwest. + continue_client::arm_expect_continue(handle); + if with_handle_mut::(handle, |r| r.expects_continue).unwrap_or(false) + { + return; + } let snapshot = with_handle_mut::(handle, |req| { if req.ended || !req.body.is_empty() { return None; @@ -1622,6 +1688,16 @@ pub unsafe extern "C" fn js_http_process_pending() -> i32 { PendingHttpEvent::Flushed { request_handle } => { client_events::handle_flushed_event(request_handle); } + PendingHttpEvent::Continue { request_handle } => { + // #5080 — the server sent an interim `100 Continue`; fire the + // request's `'continue'` listeners (the canonical handler then + // sends the withheld body via `req.end(...)`). + client_events::fire_request_event_listeners(request_handle, "continue"); + } + PendingHttpEvent::DeferredArmContinue { request_handle } => { + // #5080 — next-tick arming (see the enum variant docs). + continue_client::arm_expect_continue(request_handle); + } } } @@ -1634,6 +1710,10 @@ pub unsafe extern "C" fn js_http_process_pending() -> i32 { #[cfg(test)] mod tests; +// Test-only `perry_ffi_*` async-bridge shims so the lib test links without the +// host stdlib archive (mirrors perry-ext-net / perry-ext-http-server). +#[cfg(test)] +mod test_async_shims; // Suppress unused-import warnings for FFI-only types. #[allow(dead_code)] diff --git a/crates/perry-ext-http/src/test_async_shims.rs b/crates/perry-ext-http/src/test_async_shims.rs new file mode 100644 index 00000000000..db1a4823672 --- /dev/null +++ b/crates/perry-ext-http/src/test_async_shims.rs @@ -0,0 +1,52 @@ +// Unit-test binaries for `perry-ext-http` do not link the host stdlib/runtime +// archive that normally provides the perry_ffi async bridge (the real symbols +// live in `perry-stdlib::perry_ffi_async`, only linked into the final user +// program). Provide synchronous, test-only shims for the `perry_ffi_*` async +// externs the crate references so `cargo test -p perry-ext-http` links — same +// pattern as `perry-ext-net` / `perry-ext-http-server`. + +use perry_ffi::Promise; +use std::ffi::c_void; + +#[no_mangle] +pub extern "C" fn perry_ffi_promise_new() -> *mut Promise { + perry_runtime::promise::js_promise_new() as *mut Promise +} + +#[no_mangle] +pub extern "C" fn perry_ffi_promise_resolve_bits(promise: *mut Promise, bits: u64) { + perry_runtime::promise::js_promise_resolve( + promise as *mut perry_runtime::Promise, + f64::from_bits(bits), + ); +} + +#[no_mangle] +pub extern "C" fn perry_ffi_promise_reject_bits(promise: *mut Promise, bits: u64) { + perry_runtime::promise::js_promise_reject( + promise as *mut perry_runtime::Promise, + f64::from_bits(bits), + ); +} + +#[no_mangle] +pub extern "C" fn perry_ffi_promise_resolve_deferred( + promise: *mut Promise, + ctx: *mut c_void, + invoke: extern "C" fn(*mut c_void) -> u64, +) { + perry_ffi_promise_resolve_bits(promise, invoke(ctx)); +} + +#[no_mangle] +pub extern "C" fn perry_ffi_spawn_blocking(ctx: *mut c_void, invoke: extern "C" fn(*mut c_void)) { + invoke(ctx); +} + +#[no_mangle] +pub extern "C" fn perry_ffi_spawn_blocking_with_reactor( + ctx: *mut c_void, + invoke: extern "C" fn(*mut c_void), +) { + invoke(ctx); +} diff --git a/crates/perry-ext-http/src/tests.rs b/crates/perry-ext-http/src/tests.rs index ada1fdd78cb..dc5a38f2f11 100644 --- a/crates/perry-ext-http/src/tests.rs +++ b/crates/perry-ext-http/src/tests.rs @@ -74,6 +74,8 @@ fn gc_mutable_scanner_rewrites_request_response_listener_roots() { agent_handle: 0, tls: crate::tls_client::TlsOptions::default(), incoming_handle: 0, + expects_continue: false, + continue_body_tx: None, }); let mut incoming_listeners = HashMap::new(); diff --git a/test-files/test_http_100_continue_5080.ts b/test-files/test_http_100_continue_5080.ts new file mode 100644 index 00000000000..069a1db278a --- /dev/null +++ b/test-files/test_http_100_continue_5080.ts @@ -0,0 +1,46 @@ +// Issue #5080 — node:http 100-continue handshake, end-to-end. +// +// Client: `Expect: 100-continue` withholds the body until the server's +// interim `100 Continue` drives the request's `'continue'` event; the +// handler then sends the body. Server: a `'checkContinue'` listener fires +// *instead of* `'request'`, calls `res.writeContinue()`, then reads the +// body and responds. +// +// Data chunks are coerced with `.toString()` (the convention used across +// the http client/server test suite — see test_gap_http_overloads_3226plus +// / test_issue_1124_client_buffer). The implicit `b += chunk` form trips a +// separate, pre-existing client-side Buffer→string coercion crash that is +// unrelated to the 100-continue flow. + +import http from "node:http"; + +const server = http.createServer((req, res) => { + let b = ""; + req.on("data", (c: any) => (b += c.toString())); + req.on("end", () => res.end("got:" + b)); +}); +server.on("checkContinue", (req: any, res: any) => { + res.writeContinue(); + let b = ""; + req.on("data", (c: any) => (b += c.toString())); + req.on("end", () => res.end("continue:" + b)); +}); +server.listen(0, () => { + const port = (server.address() as any).port; + const req = http.request( + { port, method: "POST", headers: { Expect: "100-continue" } }, + (res: any) => { + let b = ""; + res.on("data", (c: any) => (b += c.toString())); + res.on("end", () => { + console.log("body", b); + server.close(() => console.log("closed")); + }); + }, + ); + req.on("continue", () => { + console.log("continue event"); + req.end("payload"); + }); +}); +setTimeout(() => {}, 1500);