diff --git a/impit-node/index.wrapper.js b/impit-node/index.wrapper.js index e30f078e..62a00214 100644 --- a/impit-node/index.wrapper.js +++ b/impit-node/index.wrapper.js @@ -26,6 +26,11 @@ class ResponsePatches { const buffer = await this.arrayBuffer(); return this.decodeBuffer(Buffer.from(buffer)); } + + // Goes through arrayBuffer() so the body is read natively; Fetch decodes JSON as UTF-8. + static async json() { + return JSON.parse(textDecoder.decode(await this.arrayBuffer())); + } } function canonicalizeHeaders(headers) { @@ -46,6 +51,7 @@ function isRedirectStatus(status) { } const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); // Stream chunks may be strings (e.g. a ReadableStream or Node stream that wasn't // fed bytes); encode them so they aren't coerced to zero bytes by Uint8Array.set. @@ -420,12 +426,8 @@ class Impit extends native.Impit { configurable: true, }); - const nativeJson = originalResponse.json.bind(originalResponse); Object.defineProperty(originalResponse, 'json', { - value: async function() { - bodyConsumed = true; - try { return await nativeJson(); } finally { cleanup(); } - }, + value: ResponsePatches.json.bind(originalResponse), configurable: true, }); diff --git a/impit-node/src/abortable_stream.rs b/impit-node/src/abortable_stream.rs index 01ffdae7..e62a9160 100644 --- a/impit-node/src/abortable_stream.rs +++ b/impit-node/src/abortable_stream.rs @@ -4,16 +4,23 @@ use std::sync::Arc; use std::task::Context; use std::task::Poll; +pub(crate) fn aborted_error() -> napi::Error { + napi::Error::new( + napi::Status::GenericFailure, + "impit: Request was aborted through AbortSignal", + ) +} + /// A Tokio stream wrapper that can be aborted via a channel pub(crate) struct AbortableStream { inner: Option>>, - abort_rx: Arc>>>, + abort_rx: Arc>>, } impl AbortableStream { pub(crate) fn new( inner: S, - abort_rx: Arc>>>, + abort_rx: Arc>>, ) -> Self { Self { inner: Some(Box::pin(inner)), @@ -30,20 +37,12 @@ where fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = &mut *self; - if let Ok(mut guard) = this.abort_rx.try_lock() { - if let Some(ref mut rx) = *guard { - match rx.poll_recv(cx) { - Poll::Ready(Some(_)) => { - // napi only drops the stream on close or cancel, not on error, so drop the body here - // to close the connection. - this.inner = None; - return Poll::Ready(Some(Err(napi::Error::new( - napi::Status::GenericFailure, - "impit: Request was aborted through AbortSignal", - )))); - } - _other => {} - } + if let Ok(mut rx) = this.abort_rx.try_lock() { + if let Poll::Ready(Some(_)) = rx.poll_recv(cx) { + // napi only drops the stream on close or cancel, not on error, so drop the body here + // to close the connection. + this.inner = None; + return Poll::Ready(Some(Err(aborted_error()))); } } diff --git a/impit-node/src/response.rs b/impit-node/src/response.rs index 3d30eb8c..d2b4ac45 100644 --- a/impit-node/src/response.rs +++ b/impit-node/src/response.rs @@ -1,10 +1,12 @@ #![allow(clippy::await_holding_refcell_ref, deprecated)] -use crate::abortable_stream::AbortableStream; +use crate::abortable_stream::{aborted_error, AbortableStream}; +use futures_util::future::Either; use impit::utils::{decode, ContentType}; use napi::bindgen_prelude::JsObjectValue; use napi::{ bindgen_prelude::{ - BufferSlice, FromNapiValue, Function, Object, ReadableStream, Result, This, ToNapiValue, + ArrayBuffer, BufferSlice, FromNapiValue, Function, Object, ReadableStream, Result, This, + ToNapiValue, }, sys, Env, JsValue, Unknown, }; @@ -62,8 +64,8 @@ pub struct ImpitResponse { /// In case of redirects, this will be the final URL after all redirects have been followed. pub url: String, // Shared sender used to immediately signal abort to the JS ReadableStream without polling. - abort_receiver: Arc>>>, - abort_sender: Arc>>>, + abort_receiver: Arc>>, + abort_sender: tokio::sync::mpsc::Sender<()>, } impl ToNapiValue for &mut Headers { @@ -102,6 +104,7 @@ impl<'env> ImpitResponse { let headers = Headers(headers_vec); let ok = response.status().is_success(); let url = response.url().to_string(); + let (tx_abort, rx_abort) = tokio::sync::mpsc::channel::<()>(1); Ok(Self { inner: RefCell::new(Some(response)), @@ -110,21 +113,61 @@ impl<'env> ImpitResponse { headers, ok, url, - abort_receiver: Arc::new(tokio::sync::Mutex::new(None)), - abort_sender: Arc::new(tokio::sync::Mutex::new(None)), + abort_receiver: Arc::new(tokio::sync::Mutex::new(rx_abort)), + abort_sender: tx_abort, }) } + fn read_error(e: reqwest::Error) -> napi::Error { + napi::Error::new( + napi::Status::Unknown, + format!("Error reading response stream: {e:?}"), + ) + } + + fn body_already_read(env: &Env) -> napi::Error { + match env.throw_type_error("Body is unusable: Body has already been read", None) { + Ok(()) => napi::Error::from_status(napi::Status::PendingException), + Err(e) => e, + } + } + + /// Reads the whole body on the native side and resolves with one `ArrayBuffer`, so the body + /// crosses into JavaScript once instead of piece by piece (see #641). + fn read_body_natively(&'env self, env: &'env Env) -> Result> { + let response = self + .inner + .borrow_mut() + .take() + .ok_or_else(|| Self::body_already_read(env))?; + let abort_receiver = Arc::clone(&self.abort_receiver); + + let promise = env.spawn_future_with_callback( + async move { + let mut rx = abort_receiver.lock().await; + tokio::select! { + // Dropping the read here drops the body, which closes the connection. + Some(()) = rx.recv() => Err(aborted_error()), + bytes = response.bytes() => bytes.map_err(Self::read_error), + } + }, + |env, bytes| ArrayBuffer::from_data(env, Vec::from(bytes)), + )?; + + promise.coerce_to_object() + } + fn get_inner_response(&self, env: &Env, mut this: This) -> Result> { let cached_response = this.get::(INNER_RESPONSE_PROPERTY_NAME)?; if cached_response.is_none() { let mut response = self.inner.borrow_mut(); let response = response.take(); + let read_natively = response.is_none(); let reqwest_stream = match response { - Some(inner_response) => inner_response.bytes_stream(), - None => panic!("fatal: Response already consumed, but stream was not cached?"), + Some(inner_response) => Either::Left(inner_response.bytes_stream()), + None => Either::Right(futures_util::stream::empty()), }; let napi_stream = reqwest_stream.filter_map(|chunk| match chunk { @@ -135,20 +178,9 @@ impl<'env> ImpitResponse { Some(Ok(bytes.to_vec())) } - Err(e) => Some(Err(napi::Error::new( - napi::Status::Unknown, - format!("Error reading response stream: {e:?}"), - ))), + Err(e) => Some(Err(Self::read_error(e))), }); - let (tx_abort, rx_abort) = tokio::sync::mpsc::channel::<()>(1); - if let Ok(mut guard) = self.abort_sender.try_lock() { - *guard = Some(tx_abort); - } - if let Ok(mut guard) = self.abort_receiver.try_lock() { - *guard = Some(rx_abort); - } - let abortable_stream = AbortableStream::new(napi_stream, Arc::clone(&self.abort_receiver)); let js_stream = ReadableStream::create_with_stream_bytes(env, abortable_stream)?; @@ -157,10 +189,18 @@ impl<'env> ImpitResponse { .and_then(|global| global.get_named_property::("Response")) .expect("fatal: Couldn't get Response constructor"); - this.set( - INNER_RESPONSE_PROPERTY_NAME, - response_constructor.new_instance(js_stream.to_unknown())?, - )?; + let js_response = response_constructor + .new_instance(js_stream.to_unknown())? + .coerce_to_object()?; + if read_natively { + // The body was already read natively. Drain the empty stand-in right away, so `body` is a + // locked, used stream like after `text()` in Fetch, and further reads throw a TypeError. + js_response + .get_named_property::>("arrayBuffer")? + .apply(Some(&js_response), ())?; + } + + this.set(INNER_RESPONSE_PROPERTY_NAME, js_response)?; } this @@ -208,6 +248,11 @@ impl<'env> ImpitResponse { /// as the response body can only be consumed once. Subsequent calls will result in an error. #[napi(ts_return_type = "Promise")] pub fn array_buffer(&'env self, env: &'env Env, this: This<'env>) -> Result> { + // Once `body` or `clone()` has turned the body into a JS stream, keep reading from that stream. + if this.get::(INNER_RESPONSE_PROPERTY_NAME)?.is_none() { + return self.read_body_natively(env); + } + let response = self.get_inner_response(env, this)?; response @@ -333,10 +378,6 @@ impl<'env> ImpitResponse { /// Use `fetch(url, { signal: AbortSignal })` to abort a request instead. #[napi] pub fn abort(&mut self) { - if let Ok(mut guard) = self.abort_sender.try_lock() { - if let Some(ref mut tx) = *guard { - let _ = tx.try_send(()); - } - } + let _ = self.abort_sender.try_send(()); } } diff --git a/impit-node/test/basics.test.ts b/impit-node/test/basics.test.ts index 2794cdf7..f7278181 100644 --- a/impit-node/test/basics.test.ts +++ b/impit-node/test/basics.test.ts @@ -642,6 +642,55 @@ describe.each([ t.expect(new Uint8Array(bytes.slice(0, 5))).toEqual(Uint8Array.from([0x3c, 0x3f, 0x78, 0x6d, 0x6c])); }); + describe('gzip-compressed body', () => { + const url = new URL(routes.gzipJson.path, 'http://127.0.0.1:3001').href; + const expected = Buffer.from(JSON.stringify(routes.gzipJson.bodyJson)); + + test('.arrayBuffer() returns the whole decompressed body', async (t) => { + const response = await impit.fetch(url); + t.expect(Buffer.from(await response.arrayBuffer()).equals(expected)).toBe(true); + }); + + test('.bytes(), .text() and .json() return the whole decompressed body', async (t) => { + t.expect(Buffer.from(await (await impit.fetch(url)).bytes()).equals(expected)).toBe(true); + t.expect(await (await impit.fetch(url)).text() === expected.toString('utf8')).toBe(true); + t.expect(await (await impit.fetch(url)).json()).toEqual(routes.gzipJson.bodyJson); + }); + + test('.body still streams the decompressed body in pieces', async (t) => { + const response = await impit.fetch(url); + const chunks: Uint8Array[] = []; + for await (const chunk of response.body) chunks.push(chunk); + + t.expect(chunks.length).toBeGreaterThan(1); + t.expect(Buffer.concat(chunks).equals(expected)).toBe(true); + }); + + test('a clone and the original both read the whole body', async (t) => { + const response = await impit.fetch(url); + const clone = response.clone(); + + t.expect(await clone.json()).toEqual(routes.gzipJson.bodyJson); + t.expect(Buffer.from(await response.arrayBuffer()).equals(expected)).toBe(true); + }); + }); + + test('.json() strips a UTF-8 BOM', async (t) => { + const response = await impit.fetch(new URL(routes.bomJson.path, 'http://127.0.0.1:3001').href); + t.expect(await response.json()).toEqual(routes.bomJson.bodyJson); + }); + + test('reading the body twice throws a TypeError', async (t) => { + const response = await impit.fetch(new URL(routes.bomJson.path, 'http://127.0.0.1:3001').href); + await response.arrayBuffer(); + + await t.expect(response.arrayBuffer()).rejects.toThrow(TypeError); + await t.expect(response.text()).rejects.toThrow(/Body is unusable/); + t.expect(response.body.locked).toBe(true); + t.expect(() => response.body.getReader()).toThrow(TypeError); + await t.expect(response.arrayBuffer()).rejects.toThrow(/Body is unusable/); + }); + test('streaming response body works', async (t) => { const response = await impit.fetch( 'https://apify.github.io/impit/js', @@ -761,6 +810,18 @@ describe.each([ expect(getEventListeners(signal, 'abort').length).toBe(0); }); + test('rejects a body read after the signal aborted', async () => { + const server = await getServer(); + const controller = new AbortController(); + const response = await impit.fetch( + `http://127.0.0.1:${(server?.address() as AddressInfo).port}/delay/3000`, + { signal: controller.signal } + ); + + controller.abort(); + await expect(response.arrayBuffer()).rejects.toThrow(/abort/i); + }); + // https://github.com/apify/impit/issues/597 test('closes the connection when aborted during the body read', async () => { let socketClosed: () => void = () => {}; diff --git a/impit-node/test/mock.server.ts b/impit-node/test/mock.server.ts index 1ebba4bb..007da633 100644 --- a/impit-node/test/mock.server.ts +++ b/impit-node/test/mock.server.ts @@ -1,6 +1,7 @@ import express from 'express'; import { Server } from 'http'; import { Server as ProxyServer } from 'proxy-chain'; +import { gzipSync } from 'node:zlib'; // "Příliš žluťoučký kůň úpěl ďábelské ódy" encoded in Windows-1250 const WIN1250_BODY = Buffer.from([0x50, 0xf8, 0xed, 0x6c, 0x69, 0x9a, 0x20, 0x9e, 0x6c, 0x75, 0x9d, 0x6f, 0x75, 0xe8, 0x6b, 0xfd, 0x20, 0x6b, 0xf9, 0xf2, 0x20, 0xfa, 0x70, 0xec, 0x6c, 0x20, 0xef, 0xe1, 0x62, 0x65, 0x6c, 0x73, 0x6b, 0xe9, 0x20, 0xf3, 0x64, 0x79]); @@ -28,6 +29,15 @@ export const routes = { path: '/utf8-header', headerValue: 'attachment; filename="naïve.pdf"', }, + // Large enough that the gzip decoder hands it over in many small pieces. + gzipJson: { + path: '/gzip-json', + bodyJson: { items: Array.from({ length: 2000 }, (_, i) => ({ id: i, title: `Item ${i} ✓`, filler: 'x'.repeat(80) })) }, + }, + bomJson: { + path: '/bom-json', + bodyJson: { name: 'naïve' }, + }, } function parseMultipart(body: Buffer, boundary: string): Record { @@ -81,6 +91,17 @@ export async function runServer(port: number): Promise { }); }); + const gzipJsonBody = gzipSync(JSON.stringify(routes.gzipJson.bodyJson)); + app.get(routes.gzipJson.path, (req, res) => { + res.set({ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' }); + res.end(gzipJsonBody); + }); + + app.get(routes.bomJson.path, (req, res) => { + res.set('Content-Type', 'application/json'); + res.end('' + JSON.stringify(routes.bomJson.bodyJson)); + }); + app.get(routes.charset.path, (req, res) => { res.set('Content-Type', 'text/plain; charset=windows-1250'); res.send(routes.charset.bodyBuffer);