diff --git a/src/client/sea.rs b/src/client/sea.rs index 2ff7f15e..62b967cb 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -317,7 +317,7 @@ impl SeaRestTransport { } /// Convert SEA response to internal ExecuteResultData. - fn convert_result_data(result: &crate::types::sea::ResultData) -> Result { + fn convert_result_data(result: crate::types::sea::ResultData) -> Result { let external_links = if let Some(ref links) = result.external_links { let converted: Result> = links .iter() @@ -329,9 +329,9 @@ impl SeaRestTransport { }; Ok(ExecuteResultData { - next_chunk_internal_link: result.next_chunk_internal_link.clone(), + next_chunk_internal_link: result.next_chunk_internal_link, external_links, - inline_arrow_data: result.attachment.clone(), + inline_arrow_data: result.attachment, inline_chunk_index: result.chunk_index, inline_row_offset: result.row_offset, inline_row_count: result.row_count, @@ -365,15 +365,18 @@ impl SeaRestTransport { .http_client .execute(request, RequestType::GetStatementStatus) .await?; + // Parse the raw bytes: `text()` would copy a multi-MB inline-Arrow + // body into a `String` first. let body = response - .text() + .bytes() .await .map_err(|e| Error::network_error().message(format!("Failed to read response: {e}")))?; let sea_response: StatementExecutionResponse = - serde_json::from_str(&body).map_err(|e| { + serde_json::from_slice(&body).map_err(|e| { Error::data_loss().message(format!( - "Failed to parse status response: {e} - body: {body}" + "Failed to parse status response: {e} - body: {}", + String::from_utf8_lossy(&body) )) })?; @@ -692,15 +695,18 @@ impl SeaRestTransport { })?; let response = self.http_client.execute(request, request_type).await?; + // Parse the raw bytes: `text()` would copy a multi-MB inline-Arrow + // body into a `String` first. let body = response - .text() + .bytes() .await .map_err(|e| Error::network_error().message(format!("Failed to read response: {e}")))?; let sea_response: StatementExecutionResponse = - serde_json::from_str(&body).map_err(|e| { + serde_json::from_slice(&body).map_err(|e| { Error::data_loss().message(format!( - "Failed to parse execute response: {e} - body: {body}" + "Failed to parse execute response: {e} - body: {}", + String::from_utf8_lossy(&body) )) })?; @@ -716,11 +722,7 @@ impl SeaRestTransport { /// Convert SEA response to internal ExecuteResponse. fn convert_response(response: StatementExecutionResponse) -> Result { - let result = if let Some(ref result) = response.result { - Some(Self::convert_result_data(result)?) - } else { - None - }; + let result = response.result.map(Self::convert_result_data).transpose()?; Ok(ExecuteResponse { statement_id: response.statement_id, @@ -1438,14 +1440,17 @@ impl Transport for SeaRestTransport { .http_client .execute(request, RequestType::GetResultChunks) .await?; + // Parse the raw bytes: `text()` would copy a multi-MB inline-Arrow + // body into a `String` first. let body = response - .text() + .bytes() .await .map_err(|e| Error::network_error().message(format!("Failed to read response: {e}")))?; - let chunks_response: GetChunksResponse = serde_json::from_str(&body).map_err(|e| { + let chunks_response: GetChunksResponse = serde_json::from_slice(&body).map_err(|e| { Error::data_loss().message(format!( - "Failed to parse inline chunk response: {e} - body: {body}" + "Failed to parse inline chunk response: {e} - body: {}", + String::from_utf8_lossy(&body) )) })?; @@ -1459,7 +1464,8 @@ impl Transport for SeaRestTransport { "Inline chunk {} response missing `attachment` field — \ server may have ignored the INLINE disposition and \ returned a CloudFetch response. Body: {}", - chunk_index, body + chunk_index, + String::from_utf8_lossy(&body) )) })?; @@ -1484,7 +1490,8 @@ impl Transport for SeaRestTransport { Error::data_loss().message(format!( "Inline chunk {} response carries `attachment` but no `row_count` — \ cannot derive next-fetch row_offset safely. Body: {}", - chunk_idx, body, + chunk_idx, + String::from_utf8_lossy(&body), )) })?; let next_chunk_index = chunks_response.next_chunk_index; @@ -2297,7 +2304,7 @@ mod tests { attachment: None, }; - let converted = SeaRestTransport::convert_result_data(&result).unwrap(); + let converted = SeaRestTransport::convert_result_data(result).unwrap(); assert!(converted.external_links.is_none()); assert!(converted.inline_arrow_data.is_none()); } @@ -2317,7 +2324,7 @@ mod tests { attachment: Some(test_data.clone()), }; - let converted = SeaRestTransport::convert_result_data(&result).unwrap(); + let converted = SeaRestTransport::convert_result_data(result).unwrap(); assert!(converted.inline_arrow_data.is_some()); assert_eq!(converted.inline_arrow_data.unwrap(), test_data); } diff --git a/src/reader/inline/provider.rs b/src/reader/inline/provider.rs index d59b05c0..74b34a22 100644 --- a/src/reader/inline/provider.rs +++ b/src/reader/inline/provider.rs @@ -99,7 +99,7 @@ impl InlineArrowProvider { /// - If Arrow IPC parsing fails pub fn new( statement_id: &str, - attachment: Vec, + attachment: &[u8], compression: CompressionCodec, total_row_count: Option, ) -> Result { @@ -123,7 +123,7 @@ impl InlineArrowProvider { ); // Reuse the shared Arrow IPC parser (same format as CloudFetch) - let parsed = parse_arrow_ipc(&attachment, compression).map_err(|e| { + let parsed = parse_arrow_ipc(attachment, compression).map_err(|e| { Error::io().message(format!("Failed to parse inline Arrow data: {}", e)) })?; @@ -214,7 +214,7 @@ mod tests { let ipc_data = create_test_arrow_ipc(&[batch]); let mut provider = - InlineArrowProvider::new("test-stmt", ipc_data, CompressionCodec::None, None).unwrap(); + InlineArrowProvider::new("test-stmt", &ipc_data, CompressionCodec::None, None).unwrap(); // Check schema assert!(provider.schema().is_some()); @@ -247,7 +247,7 @@ mod tests { } let mut provider = - InlineArrowProvider::new("test-stmt", compressed, CompressionCodec::Lz4Frame, None) + InlineArrowProvider::new("test-stmt", &compressed, CompressionCodec::Lz4Frame, None) .unwrap(); let batch = provider.next_batch().unwrap().unwrap(); @@ -261,7 +261,7 @@ mod tests { let ipc_data = create_test_arrow_ipc(&[batch1, batch2]); let mut provider = - InlineArrowProvider::new("test-stmt", ipc_data, CompressionCodec::None, None).unwrap(); + InlineArrowProvider::new("test-stmt", &ipc_data, CompressionCodec::None, None).unwrap(); // First batch let batch = provider.next_batch().unwrap().unwrap(); @@ -278,7 +278,7 @@ mod tests { #[test] fn test_inline_provider_with_empty_data() { let provider = - InlineArrowProvider::new("test-stmt", vec![], CompressionCodec::None, None).unwrap(); + InlineArrowProvider::new("test-stmt", &[], CompressionCodec::None, None).unwrap(); assert!(provider.schema().is_none()); assert!(!provider.has_more()); @@ -289,7 +289,7 @@ mod tests { let invalid_data = b"this is not valid arrow ipc data".to_vec(); let result = - InlineArrowProvider::new("test-stmt", invalid_data, CompressionCodec::None, None); + InlineArrowProvider::new("test-stmt", &invalid_data, CompressionCodec::None, None); assert!(result.is_err()); } @@ -329,7 +329,7 @@ mod tests { let batch = create_test_batch(11); let ipc = create_test_arrow_ipc(&[batch]); let mut provider = - InlineArrowProvider::new("test-stmt", ipc, CompressionCodec::None, Some(10)).unwrap(); + InlineArrowProvider::new("test-stmt", &ipc, CompressionCodec::None, Some(10)).unwrap(); let mut total = 0; while let Some(b) = provider.next_batch().unwrap() { total += b.num_rows(); diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index 57e4158a..0ae25e2e 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -225,7 +225,7 @@ impl InlineStreamingProvider { pub(crate) fn new( source: Arc, statement_id: impl Into, - initial_attachment: Vec, + initial_attachment: &[u8], initial_chunk_index: i64, initial_row_offset: i64, initial_row_count: i64, @@ -237,7 +237,7 @@ impl InlineStreamingProvider { ) -> Result> { // Decode the initial chunk synchronously so we can return a // schema-bearing provider to the caller. - let initial_batches = parse_arrow_ipc(&initial_attachment, compression)?; + let initial_batches = parse_arrow_ipc(initial_attachment, compression)?; // Schema source priority: // 1. The first batch of the initial chunk (most-authoritative, @@ -678,7 +678,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial_bytes, + &initial_bytes, c0.chunk_index, c0.row_offset, c0.row_count, @@ -715,7 +715,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial_bytes, + &initial_bytes, c0.chunk_index, c0.row_offset, c0.row_count, @@ -755,7 +755,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial.bytes.clone(), + &initial.bytes, initial.chunk_index, initial.row_offset, initial.row_count, @@ -783,7 +783,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial_bytes, + &initial_bytes, c0.chunk_index, c0.row_offset, c0.row_count, @@ -822,7 +822,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial_bytes, + &initial_bytes, c0.chunk_index, c0.row_offset, c0.row_count, @@ -864,7 +864,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial_bytes, + &initial_bytes, c0.chunk_index, c0.row_offset, c0.row_count, @@ -910,7 +910,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - empty_bytes, + &empty_bytes, 0, 0, 0, @@ -944,7 +944,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial_bytes, + &initial_bytes, c0.chunk_index, c0.row_offset, c0.row_count, @@ -1005,7 +1005,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial_bytes, + &initial_bytes, c0.chunk_index, c0.row_offset, c0.row_count, @@ -1075,7 +1075,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - initial_bytes, + &initial_bytes, 0, // initial_chunk_index 0, // initial_row_offset 1, // initial_row_count @@ -1148,7 +1148,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - build_ipc_bytes(&[10, 20]), + &build_ipc_bytes(&[10, 20]), 0, // initial_chunk_index 0, // initial_row_offset 2, // initial_row_count @@ -1183,7 +1183,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - build_ipc_bytes(&[1]), + &build_ipc_bytes(&[1]), 0, 0, 1, @@ -1243,7 +1243,7 @@ mod tests { let provider = InlineStreamingProvider::new( source, "stmt-1", - build_ipc_bytes(&[7, 8]), + &build_ipc_bytes(&[7, 8]), 0, // initial_chunk_index 0, // initial_row_offset 2, // initial_row_count diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 4ae80325..87aef6e4 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -323,7 +323,7 @@ impl ResultReaderFactory { }); return self.create_inline_streaming_reader( statement_id, - inline_data.clone(), + inline_data, inline_chunk_index, inline_row_offset, inline_row_count, @@ -548,12 +548,8 @@ impl ResultReaderFactory { total_row_count ); - let provider = InlineArrowProvider::new( - statement_id, - inline_data.to_vec(), - compression, - total_row_count, - )?; + let provider = + InlineArrowProvider::new(statement_id, inline_data, compression, total_row_count)?; Ok(Box::new(InlineArrowReader::new(provider))) } @@ -571,7 +567,7 @@ impl ResultReaderFactory { fn create_inline_streaming_reader( &self, statement_id: &str, - initial_attachment: Vec, + initial_attachment: &[u8], initial_chunk_index: i64, initial_row_offset: i64, initial_row_count: i64, diff --git a/src/types/sea.rs b/src/types/sea.rs index 8b554d7d..74d1ad97 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -286,18 +286,43 @@ pub struct ResultData { } /// Deserialize base64-encoded attachment field from JSON. +/// +/// Decodes from the JSON string in place (borrowed when it has no escapes) +/// rather than first copying a multi-MB attachment into an owned `String`. fn deserialize_base64_attachment<'de, D>(deserializer: D) -> Result>, D::Error> where D: Deserializer<'de>, { - let opt: Option = Option::deserialize(deserializer)?; - match opt { - Some(s) if !s.is_empty() => STANDARD - .decode(&s) - .map(Some) - .map_err(serde::de::Error::custom), - _ => Ok(None), + struct Base64Attachment; + + impl<'de> serde::de::Visitor<'de> for Base64Attachment { + type Value = Option>; + + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a base64-encoded string or null") + } + + fn visit_str(self, s: &str) -> Result { + if s.is_empty() { + return Ok(None); + } + STANDARD.decode(s).map(Some).map_err(E::custom) + } + + fn visit_none(self) -> Result { + Ok(None) + } + + fn visit_unit(self) -> Result { + Ok(None) + } + + fn visit_some>(self, d: D2) -> Result { + d.deserialize_str(self) + } } + + deserializer.deserialize_option(Base64Attachment) } /// External link for CloudFetch download. @@ -788,6 +813,28 @@ mod tests { assert!(result.attachment.is_none()); } + #[test] + fn test_result_data_with_escaped_base64_attachment() { + // `/` escaped as `\/` forces serde_json off the borrowed-str path. + // "\xff\xfe\xfd" in base64 is "//79". + let json = br#"{"attachment": "\/\/79"}"#; + + let result: ResultData = serde_json::from_slice(json).unwrap(); + assert_eq!(result.attachment.unwrap(), b"\xff\xfe\xfd"); + } + + #[test] + fn test_result_data_rejects_invalid_base64_attachment() { + let json = r#"{"attachment": "not base64!"}"#; + assert!(serde_json::from_str::(json).is_err()); + } + + #[test] + fn test_result_data_rejects_non_string_attachment() { + let json = r#"{"attachment": 42}"#; + assert!(serde_json::from_str::(json).is_err()); + } + #[test] fn test_column_info_with_all_optional_fields() { let json = r#"{