ryerraguntla commented on code in PR #4394: URL: https://github.com/apache/iggy/pull/4394#discussion_r4178099004
########## core/connectors/sinks/bigquery_sink/src/error.rs: ########## @@ -0,0 +1,207 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Failure classification for BigQuery calls. +//! +//! Only transient failures are retried. Retrying a permanent one (bad +//! schema, missing permission) cannot succeed and only delays the error. + +use crate::schema::SchemaError; +use gcloud_gax::grpc::{Code, Status}; +use iggy_connector_sdk::Error; +use std::fmt; + +/// An `AppendRows` call that did not append. Row-level errors are not part +/// of this type: they are an expected outcome the caller handles by +/// dropping the reported rows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum AppendError { + /// The call failed, or the response carried an error status. + Rpc { code: Code, message: String }, + /// The response stream closed without a response. + NoResponse, +} + +/// A `tables.get` call that did not return a usable schema. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum TableError { + Http { status: u16, body: String }, + Transport(String), + Token(String), + Schema(SchemaError), +} + +impl AppendError { + pub(crate) fn is_retryable(&self) -> bool { + match self { + AppendError::Rpc { code, .. } => is_retryable_code(*code), + // The append may or may not have landed. Retrying risks a + // duplicate, which the delivery guarantees allow. + AppendError::NoResponse => true, + } + } +} + +impl TableError { + pub(crate) fn is_retryable(&self) -> bool { + match self { + TableError::Http { status, .. } => *status == 429 || *status >= 500, + TableError::Transport(_) | TableError::Token(_) => true, + TableError::Schema(_) => false, + } + } +} + +/// gRPC codes BigQuery documents as safe to retry for `AppendRows`. +pub(crate) fn is_retryable_code(code: Code) -> bool { Review Comment: a client timeout becomes Code::Cancelled, not DeadlineExceeded. is_retryable_code does not retry Cancelled, so append_with_retry returns a permanent error. The runtime already committed the offset (runtime/src/sink.rs:517) and keeps polling. That batch is not replayed. README says DEADLINE_EXCEEDED is retried. **Fix**: retry Code::Cancelled. ########## core/connectors/sinks/bigquery_sink/src/encode.rs: ########## @@ -0,0 +1,1289 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Turns a run of `ConsumedMessage`s into Arrow record batches that fit in +//! one `AppendRows` request each. +//! +//! A message that cannot become a row (wrong payload type, a value that does +//! not fit its column, a row larger than the request budget) is rejected on +//! its own and reported back with its offset. The rest of the batch is still +//! written. +//! +//! Mapped mode decodes JSON objects with `arrow-json`. The fast path decodes +//! the whole run at once. When that fails, bisection isolates the offending +//! rows before the survivors are decoded together. +//! +//! The writer schema of a request only contains the columns that at least one +//! row in the run sets. Columns no row mentions are left out, so BigQuery +//! fills them according to `missing_value` (the column default, or NULL). + +use crate::schema::{BqType, Column, MetaColumn, Mode, RawKind, TableLayout, UTC}; +use arrow::array::{ + ArrayRef, BinaryArray, Int64Array, RecordBatch, StringArray, StringBuilder, + TimestampMicrosecondArray, +}; +use arrow::compute::cast; +use arrow::datatypes::{DataType, FieldRef, Schema, SchemaRef}; +use arrow::error::ArrowError; +use arrow::ipc::writer::{ + CompressionContext, DictionaryTracker, IpcDataGenerator, IpcWriteOptions, write_message, +}; +use arrow::json::ReaderBuilder; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64; +use iggy_connector_sdk::{ConsumedMessage, MessagesMetadata, Payload, TopicMetadata}; +use simd_json::{OwnedValue, StaticNode}; +use std::fmt::Write as _; +use std::sync::Arc; + +const HEADER_ENCODING_BASE64: &str = "base64"; +const UTC_OFFSET: &str = "+00:00"; +const IPC_BATCH_OVERHEAD: usize = 1024; +const IPC_COLUMN_OVERHEAD: usize = 128; + +/// One `AppendRows` request worth of rows. +#[derive(Debug)] +pub(crate) struct Chunk { + pub batch: RecordBatch, + /// Iggy offset of each row, same order as `batch`. + pub offsets: Vec<u64>, + pub schema_bytes: Vec<u8>, + pub batch_bytes: Vec<u8>, +} + +/// A message that was not turned into a row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Rejected { + pub offset: u64, + pub reason: String, +} + +#[derive(Debug, Default)] +pub(crate) struct Encoded { + pub chunks: Vec<Chunk>, + pub rejected: Vec<Rejected>, +} + +/// Per-run context shared by every row. +pub(crate) struct RunContext<'a> { + pub layout: &'a TableLayout, + pub topic: &'a TopicMetadata, + pub messages: &'a MessagesMetadata, + pub max_request_bytes: usize, +} + +/// Encode a run of messages. Fails only on an internal Arrow error, which +/// means the batch as a whole cannot be built. Per-row problems end up in +/// `Encoded::rejected`. +pub(crate) fn encode( + ctx: &RunContext<'_>, + messages: Vec<ConsumedMessage>, +) -> Result<Encoded, ArrowError> { + let mut rejected = Vec::new(); + let batch = match &ctx.layout.raw { + Some((kind, field)) => encode_raw(ctx, *kind, field, messages, &mut rejected)?, + None => encode_mapped(ctx, messages, &mut rejected)?, + }; + let mut chunks = Vec::new(); + if let Some((batch, offsets)) = batch { + split_into_chunks( + batch, + offsets, + ctx.max_request_bytes, + &mut chunks, + &mut rejected, + )?; + } + Ok(Encoded { chunks, rejected }) +} + +/// Build a new chunk holding only the rows of `chunk` whose index is not in +/// `drop`. Used after BigQuery reports row-level errors. +pub(crate) fn without_rows(chunk: &Chunk, drop: &[usize]) -> Result<Option<Chunk>, ArrowError> { + let keep: Vec<bool> = (0..chunk.batch.num_rows()) + .map(|row| !drop.contains(&row)) + .collect(); + let offsets: Vec<u64> = chunk + .offsets + .iter() + .zip(&keep) + .filter_map(|(offset, keep)| keep.then_some(*offset)) + .collect(); + if offsets.is_empty() { + return Ok(None); + } + let mask = arrow::array::BooleanArray::from(keep); + let batch = arrow::compute::filter_record_batch(&chunk.batch, &mask)?; + let (schema_bytes, batch_bytes) = encode_ipc(&batch)?; + Ok(Some(Chunk { + batch, + offsets, + schema_bytes, + batch_bytes, + })) +} + +// ─── Mapped mode ───────────────────────────────────────────────────────────── + +fn encode_mapped( + ctx: &RunContext<'_>, + messages: Vec<ConsumedMessage>, + rejected: &mut Vec<Rejected>, +) -> Result<Option<(RecordBatch, Vec<u64>)>, ArrowError> { + let layout = ctx.layout; + let mut rows = Vec::with_capacity(messages.len()); + let mut kept = Vec::with_capacity(messages.len()); + for mut message in messages { + let payload = std::mem::replace(&mut message.payload, Payload::Raw(Vec::new())); + match json_object(payload).and_then(|mut row| { + normalize_row(&mut row, layout)?; + Ok(row) + }) { + Ok(row) => { + rows.push(row); + kept.push(message); + } + Err(reason) => rejected.push(Rejected { + offset: message.offset, + reason, + }), + } + } + if rows.is_empty() { + return Ok(None); + } + + let present = present_columns(&rows, layout); + if present.is_empty() && layout.metadata.is_empty() { + rejected.extend(kept.iter().map(|m| Rejected { + offset: m.offset, + reason: "payload has no field matching a table column".to_owned(), + })); + return Ok(None); + } + let payload_fields: Vec<FieldRef> = present.iter().map(|&i| layout.fields[i].clone()).collect(); + + let (decoded, survivors) = decode_rows(&payload_fields, &rows, |row, reason| { + rejected.push(Rejected { + offset: kept[row].offset, + reason, + }); + })?; + if survivors.is_empty() { + return Ok(None); + } + let kept: Vec<&ConsumedMessage> = survivors.iter().map(|&row| &kept[row]).collect(); + let offsets = kept.iter().map(|m| m.offset).collect(); + + let mut fields = payload_fields; + let mut columns: Vec<ArrayRef> = decoded.map(|b| b.columns().to_vec()).unwrap_or_default(); + append_metadata(ctx, &kept, &mut fields, &mut columns)?; + let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)?; + Ok(Some((batch, offsets))) +} + +/// Take the JSON object out of a payload. Text and proto text must parse as +/// a JSON object. +fn json_object(payload: Payload) -> Result<OwnedValue, String> { + let value = match payload { + Payload::Json(value) => value, + Payload::Text(text) | Payload::Proto(text) => { + let mut bytes = text.into_bytes(); + simd_json::to_owned_value(&mut bytes) + .map_err(|e| format!("payload text is not valid JSON: {e}"))? + } + other => { + return Err(format!( + "{} payload is not supported in mapped mode", + payload_kind(&other) + )); + } + }; + match value { + OwnedValue::Object(_) => Ok(value), + _ => Err("payload is not a JSON object".to_owned()), + } +} + +/// Prepare one row for `arrow-json`: +/// - a REQUIRED column without a default must be present and non-null, +/// - REPEATED columns that are absent or null become `[]`, +/// - JSON column values become their JSON text, +/// - BYTES column values are base64 in JSON and become hex, which is what +/// `arrow-json` decodes into binary. +fn normalize_row(row: &mut OwnedValue, layout: &TableLayout) -> Result<(), String> { + let OwnedValue::Object(object) = row else { + return Err("payload is not a JSON object".to_owned()); + }; + for column in &layout.columns { + let value = object.get_mut(column.name.as_str()); + match (value, column.mode) { + (None | Some(OwnedValue::Static(StaticNode::Null)), Mode::Repeated) => { + object.insert(column.name.clone(), empty_array()); + } + (None | Some(OwnedValue::Static(StaticNode::Null)), Mode::Required) + if !column.has_default => + { + return Err(format!( + "missing value for REQUIRED column '{}'", + column.name + )); + } + (Some(value), _) => normalize_value(value, column)?, + (None, _) => {} + } + } + Ok(()) +} + +fn normalize_value(value: &mut OwnedValue, column: &Column) -> Result<(), String> { + if column.mode == Mode::Repeated { + let OwnedValue::Array(items) = value else { + return Err(format!("column '{}' expects an array", column.name)); + }; + for item in items.iter_mut() { + normalize_scalar(item, column)?; + } + return Ok(()); + } + normalize_scalar(value, column) +} + +fn normalize_scalar(value: &mut OwnedValue, column: &Column) -> Result<(), String> { + if matches!(value, OwnedValue::Static(StaticNode::Null)) { + return Ok(()); + } + match &column.bq_type { + BqType::Json => { + let text = simd_json::to_string(value) + .map_err(|e| format!("column '{}': cannot serialize JSON: {e}", column.name))?; + *value = OwnedValue::String(text); + } + BqType::Bytes => { + let OwnedValue::String(text) = value else { + return Err(format!("column '{}' expects a base64 string", column.name)); + }; + let bytes = BASE64 + .decode(text.as_bytes()) + .map_err(|e| format!("column '{}': invalid base64: {e}", column.name))?; + *value = OwnedValue::String(hex::encode(bytes)); Review Comment: mapped BYTES is base64-decoded and then hex-encoded so Arrow can rebuild them. **Fix**: write the decoded bytes into BinaryBuilder ########## core/connectors/sinks/bigquery_sink/src/sink.rs: ########## @@ -0,0 +1,303 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::client::{AppendOutcome, BigQueryClient}; +use crate::encode::{self, Chunk, RunContext}; +use crate::error::{AppendError, TableError}; +use crate::schema::{TableLayout, parse_table_schema}; +use crate::{BigQuerySink, OpenState}; +use async_trait::async_trait; +use iggy_connector_sdk::retry::{RetryPolicy, retry_async}; +use iggy_connector_sdk::{ConsumedMessage, Error, MessagesMetadata, Sink, TopicMetadata}; +use std::sync::atomic::Ordering; +use tracing::{debug, error, info, warn}; + +#[async_trait] +impl Sink for BigQuerySink { + async fn open(&mut self) -> Result<(), Error> { + info!( + "Opening BigQuery sink connector ID: {} for table {} (mode: {:?})", + self.id, self.target, self.settings.mode + ); + // The SDK turns a failed open into a bare status code, so this is the + // only place the reason reaches the runtime log. + self.try_open().await.inspect_err(|e| { + error!( + "Failed to open BigQuery sink connector ID: {} for table {}: {e}", + self.id, self.target + ); + }) + } + + async fn consume( + &self, + topic_metadata: &TopicMetadata, + messages_metadata: MessagesMetadata, + messages: Vec<ConsumedMessage>, + ) -> Result<(), Error> { + if messages.is_empty() { + return Ok(()); + } + let Some(state) = &self.state else { + return Err(Error::InitError("BigQuery sink is not open".into())); + }; + let received = messages.len(); + debug!( + "BigQuery sink ID: {} received {received} messages from {}/{} partition {} current_offset {}", + self.id, + topic_metadata.stream, + topic_metadata.topic, + messages_metadata.partition_id, + messages_metadata.current_offset + ); + + let ctx = RunContext { + layout: &state.layout, + topic: topic_metadata, + messages: &messages_metadata, + max_request_bytes: self.settings.max_request_bytes, + }; + let encoded = encode::encode(&ctx, messages).map_err(|e| { + self.counters + .rows_failed + .fetch_add(received as u64, Ordering::Relaxed); + error!( + "BigQuery sink ID: {} cannot encode {received} messages from {}/{} partition {}: {e}", + self.id, topic_metadata.stream, topic_metadata.topic, messages_metadata.partition_id + ); + Error::Serialization(e.to_string()) + })?; + + for rejected in &encoded.rejected { + warn!( + "BigQuery sink ID: {} dropped message stream={} topic={} partition={} offset={}: {}", + self.id, + topic_metadata.stream, + topic_metadata.topic, + messages_metadata.partition_id, + rejected.offset, + rejected.reason + ); + } + self.counters + .rows_rejected + .fetch_add(encoded.rejected.len() as u64, Ordering::Relaxed); + + let mut written = 0u64; + let mut last_error = None; + for chunk in &encoded.chunks { + match self + .write_chunk(&state.client, chunk, topic_metadata, &messages_metadata) + .await + { + Ok(rows) => written += rows, + Err(e) => last_error = Some(e), + } + } + self.counters + .rows_written + .fetch_add(written, Ordering::Relaxed); + + if self.settings.verbose { + info!( + "BigQuery sink ID: {} wrote {written} of {received} messages from {}/{} partition {} to {}", + self.id, + topic_metadata.stream, + topic_metadata.topic, + messages_metadata.partition_id, + self.target + ); + } else { + debug!( + "BigQuery sink ID: {} wrote {written} of {received} messages from {}/{} partition {} to {}", + self.id, + topic_metadata.stream, + topic_metadata.topic, + messages_metadata.partition_id, + self.target + ); + } + + match last_error { + Some(e) => Err(e), + None => Ok(()), + } + } + + async fn close(&mut self) -> Result<(), Error> { + self.state = None; + info!( + "Closed BigQuery sink connector ID: {}, rows written: {}, rows rejected: {}, rows failed: {}", + self.id, + self.counters.rows_written.load(Ordering::Relaxed), + self.counters.rows_rejected.load(Ordering::Relaxed), + self.counters.rows_failed.load(Ordering::Relaxed) + ); + Ok(()) + } +} + +impl BigQuerySink { + async fn try_open(&mut self) -> Result<(), Error> { + self.config.validate()?; + + let mut client = BigQueryClient::connect(&self.config, &self.settings).await?; + let policy = self.retry_policy(); + + let context = format!("BigQuery sink ID: {} tables.get", self.id); + let body = retry_async(policy, &context, TableError::is_retryable, || { + client.fetch_table() + }) + .await + .map_err(|failure| Error::InitError(format!("cannot read the table schema: {failure}")))?; + + let columns = parse_table_schema(&body).map_err(|e| Error::from(TableError::Schema(e)))?; + let layout = TableLayout::build(columns, &self.settings) + .map_err(|e| Error::from(TableError::Schema(e)))?; + + let context = format!("BigQuery sink ID: {} write stream setup", self.id); + let stream = retry_async(policy, &context, AppendError::is_retryable, || { + client.resolve_write_stream() + }) + .await + .map_err(|failure| Error::InitError(format!("cannot open the write stream: {failure}")))?; + client.set_write_stream(stream); + + info!( + "Opened BigQuery sink connector ID: {} for table {}: {} payload column(s), {} metadata column(s)", + self.id, + self.target, + layout.raw.as_ref().map_or(layout.columns.len(), |_| 1), + layout.metadata.len() + ); + self.state = Some(OpenState { client, layout }); + Ok(()) + } + + fn retry_policy(&self) -> RetryPolicy { + RetryPolicy { + max_attempts: self.settings.max_retries, + base_delay: self.settings.retry_delay, + max_delay: self.settings.max_retry_delay, + } + } + + /// Append one chunk. When BigQuery reports row errors, nothing was + /// appended: drop the reported rows and append the rest once more. + /// Returns the number of rows written. + async fn write_chunk( + &self, + client: &BigQueryClient, + chunk: &Chunk, + topic: &TopicMetadata, + messages: &MessagesMetadata, + ) -> Result<u64, Error> { + let row_errors = match self + .append_with_retry(client, chunk, topic, messages) + .await? + { + AppendOutcome::Appended => return Ok(chunk.offsets.len() as u64), + AppendOutcome::RowErrors(row_errors) => row_errors, + }; + + let mut dropped = Vec::with_capacity(row_errors.len()); + for (row, reason) in row_errors { + let offset = chunk.offsets.get(row).copied(); + warn!( + "BigQuery sink ID: {} dropped row rejected by BigQuery stream={} topic={} partition={} offset={}: {reason}", + self.id, + topic.stream, + topic.topic, + messages.partition_id, + offset.map_or_else(|| format!("unknown (row {row})"), |o| o.to_string()) + ); + dropped.push(row); + } + self.counters + .rows_rejected + .fetch_add(dropped.len() as u64, Ordering::Relaxed); + + let Some(retry) = encode::without_rows(chunk, &dropped) + .map_err(|e| Error::Serialization(e.to_string()))? + else { + return Ok(0); + }; + match self + .append_with_retry(client, &retry, topic, messages) + .await? + { + AppendOutcome::Appended => Ok(retry.offsets.len() as u64), + AppendOutcome::RowErrors(again) => { + self.counters + .rows_failed + .fetch_add(retry.offsets.len() as u64, Ordering::Relaxed); + error!( + "BigQuery sink ID: {} dropped {} rows (offsets {}..={}) of {}/{} partition {}: BigQuery reported {} more row error(s) after the bad rows were removed", + self.id, + retry.offsets.len(), + retry.offsets.first().copied().unwrap_or_default(), + retry.offsets.last().copied().unwrap_or_default(), + topic.stream, + topic.topic, + messages.partition_id, + again.len() + ); + Err(Error::PermanentHttpError(format!( + "{} row error(s) persisted after removing rejected rows", + again.len() + ))) + } + } + } + + async fn append_with_retry( + &self, + client: &BigQueryClient, + chunk: &Chunk, + topic: &TopicMetadata, + messages: &MessagesMetadata, + ) -> Result<AppendOutcome, Error> { + let context = format!( + "BigQuery sink ID: {} AppendRows ({} rows)", + self.id, + chunk.offsets.len() + ); + retry_async( + self.retry_policy(), + &context, + AppendError::is_retryable, + || client.append(chunk), + ) + .await + .map_err(|failure| { + self.counters + .rows_failed + .fetch_add(chunk.offsets.len() as u64, Ordering::Relaxed); + error!( + "BigQuery sink ID: {} lost {} rows (offsets {}..={}) of {}/{} partition {}: {failure}", Review Comment: the "lost" log and rows_failed cover every exhausted append error, including NoResponse, which may already be visible. **Fix**: count rows_failed only on permanent failure. ########## core/connectors/sinks/bigquery_sink/src/encode.rs: ########## @@ -0,0 +1,1289 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Turns a run of `ConsumedMessage`s into Arrow record batches that fit in +//! one `AppendRows` request each. +//! +//! A message that cannot become a row (wrong payload type, a value that does +//! not fit its column, a row larger than the request budget) is rejected on +//! its own and reported back with its offset. The rest of the batch is still +//! written. +//! +//! Mapped mode decodes JSON objects with `arrow-json`. The fast path decodes +//! the whole run at once. When that fails, bisection isolates the offending +//! rows before the survivors are decoded together. +//! +//! The writer schema of a request only contains the columns that at least one +//! row in the run sets. Columns no row mentions are left out, so BigQuery +//! fills them according to `missing_value` (the column default, or NULL). + +use crate::schema::{BqType, Column, MetaColumn, Mode, RawKind, TableLayout, UTC}; +use arrow::array::{ + ArrayRef, BinaryArray, Int64Array, RecordBatch, StringArray, StringBuilder, + TimestampMicrosecondArray, +}; +use arrow::compute::cast; +use arrow::datatypes::{DataType, FieldRef, Schema, SchemaRef}; +use arrow::error::ArrowError; +use arrow::ipc::writer::{ + CompressionContext, DictionaryTracker, IpcDataGenerator, IpcWriteOptions, write_message, +}; +use arrow::json::ReaderBuilder; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64; +use iggy_connector_sdk::{ConsumedMessage, MessagesMetadata, Payload, TopicMetadata}; +use simd_json::{OwnedValue, StaticNode}; +use std::fmt::Write as _; +use std::sync::Arc; + +const HEADER_ENCODING_BASE64: &str = "base64"; +const UTC_OFFSET: &str = "+00:00"; +const IPC_BATCH_OVERHEAD: usize = 1024; +const IPC_COLUMN_OVERHEAD: usize = 128; + +/// One `AppendRows` request worth of rows. +#[derive(Debug)] +pub(crate) struct Chunk { + pub batch: RecordBatch, + /// Iggy offset of each row, same order as `batch`. + pub offsets: Vec<u64>, + pub schema_bytes: Vec<u8>, + pub batch_bytes: Vec<u8>, +} + +/// A message that was not turned into a row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Rejected { + pub offset: u64, + pub reason: String, +} + +#[derive(Debug, Default)] +pub(crate) struct Encoded { + pub chunks: Vec<Chunk>, + pub rejected: Vec<Rejected>, +} + +/// Per-run context shared by every row. +pub(crate) struct RunContext<'a> { + pub layout: &'a TableLayout, + pub topic: &'a TopicMetadata, + pub messages: &'a MessagesMetadata, + pub max_request_bytes: usize, +} + +/// Encode a run of messages. Fails only on an internal Arrow error, which +/// means the batch as a whole cannot be built. Per-row problems end up in +/// `Encoded::rejected`. +pub(crate) fn encode( + ctx: &RunContext<'_>, + messages: Vec<ConsumedMessage>, +) -> Result<Encoded, ArrowError> { + let mut rejected = Vec::new(); + let batch = match &ctx.layout.raw { + Some((kind, field)) => encode_raw(ctx, *kind, field, messages, &mut rejected)?, + None => encode_mapped(ctx, messages, &mut rejected)?, + }; + let mut chunks = Vec::new(); + if let Some((batch, offsets)) = batch { + split_into_chunks( + batch, + offsets, + ctx.max_request_bytes, + &mut chunks, + &mut rejected, + )?; + } + Ok(Encoded { chunks, rejected }) +} + +/// Build a new chunk holding only the rows of `chunk` whose index is not in +/// `drop`. Used after BigQuery reports row-level errors. +pub(crate) fn without_rows(chunk: &Chunk, drop: &[usize]) -> Result<Option<Chunk>, ArrowError> { + let keep: Vec<bool> = (0..chunk.batch.num_rows()) + .map(|row| !drop.contains(&row)) + .collect(); + let offsets: Vec<u64> = chunk + .offsets + .iter() + .zip(&keep) + .filter_map(|(offset, keep)| keep.then_some(*offset)) + .collect(); + if offsets.is_empty() { + return Ok(None); + } + let mask = arrow::array::BooleanArray::from(keep); + let batch = arrow::compute::filter_record_batch(&chunk.batch, &mask)?; + let (schema_bytes, batch_bytes) = encode_ipc(&batch)?; + Ok(Some(Chunk { + batch, + offsets, + schema_bytes, + batch_bytes, + })) +} + +// ─── Mapped mode ───────────────────────────────────────────────────────────── + +fn encode_mapped( + ctx: &RunContext<'_>, + messages: Vec<ConsumedMessage>, + rejected: &mut Vec<Rejected>, +) -> Result<Option<(RecordBatch, Vec<u64>)>, ArrowError> { + let layout = ctx.layout; + let mut rows = Vec::with_capacity(messages.len()); + let mut kept = Vec::with_capacity(messages.len()); + for mut message in messages { + let payload = std::mem::replace(&mut message.payload, Payload::Raw(Vec::new())); + match json_object(payload).and_then(|mut row| { + normalize_row(&mut row, layout)?; + Ok(row) + }) { + Ok(row) => { + rows.push(row); + kept.push(message); + } + Err(reason) => rejected.push(Rejected { + offset: message.offset, + reason, + }), + } + } + if rows.is_empty() { + return Ok(None); + } + + let present = present_columns(&rows, layout); + if present.is_empty() && layout.metadata.is_empty() { + rejected.extend(kept.iter().map(|m| Rejected { + offset: m.offset, + reason: "payload has no field matching a table column".to_owned(), + })); + return Ok(None); + } + let payload_fields: Vec<FieldRef> = present.iter().map(|&i| layout.fields[i].clone()).collect(); + + let (decoded, survivors) = decode_rows(&payload_fields, &rows, |row, reason| { + rejected.push(Rejected { + offset: kept[row].offset, + reason, + }); + })?; + if survivors.is_empty() { + return Ok(None); + } + let kept: Vec<&ConsumedMessage> = survivors.iter().map(|&row| &kept[row]).collect(); + let offsets = kept.iter().map(|m| m.offset).collect(); + + let mut fields = payload_fields; + let mut columns: Vec<ArrayRef> = decoded.map(|b| b.columns().to_vec()).unwrap_or_default(); + append_metadata(ctx, &kept, &mut fields, &mut columns)?; + let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)?; + Ok(Some((batch, offsets))) +} + +/// Take the JSON object out of a payload. Text and proto text must parse as +/// a JSON object. +fn json_object(payload: Payload) -> Result<OwnedValue, String> { + let value = match payload { + Payload::Json(value) => value, + Payload::Text(text) | Payload::Proto(text) => { + let mut bytes = text.into_bytes(); + simd_json::to_owned_value(&mut bytes) + .map_err(|e| format!("payload text is not valid JSON: {e}"))? + } + other => { + return Err(format!( + "{} payload is not supported in mapped mode", + payload_kind(&other) + )); + } + }; + match value { + OwnedValue::Object(_) => Ok(value), + _ => Err("payload is not a JSON object".to_owned()), + } +} + +/// Prepare one row for `arrow-json`: +/// - a REQUIRED column without a default must be present and non-null, +/// - REPEATED columns that are absent or null become `[]`, +/// - JSON column values become their JSON text, +/// - BYTES column values are base64 in JSON and become hex, which is what +/// `arrow-json` decodes into binary. +fn normalize_row(row: &mut OwnedValue, layout: &TableLayout) -> Result<(), String> { + let OwnedValue::Object(object) = row else { + return Err("payload is not a JSON object".to_owned()); + }; + for column in &layout.columns { + let value = object.get_mut(column.name.as_str()); + match (value, column.mode) { + (None | Some(OwnedValue::Static(StaticNode::Null)), Mode::Repeated) => { + object.insert(column.name.clone(), empty_array()); + } + (None | Some(OwnedValue::Static(StaticNode::Null)), Mode::Required) + if !column.has_default => + { + return Err(format!( + "missing value for REQUIRED column '{}'", + column.name + )); + } + (Some(value), _) => normalize_value(value, column)?, + (None, _) => {} + } + } + Ok(()) +} + +fn normalize_value(value: &mut OwnedValue, column: &Column) -> Result<(), String> { + if column.mode == Mode::Repeated { + let OwnedValue::Array(items) = value else { + return Err(format!("column '{}' expects an array", column.name)); + }; + for item in items.iter_mut() { + normalize_scalar(item, column)?; + } + return Ok(()); + } + normalize_scalar(value, column) +} + +fn normalize_scalar(value: &mut OwnedValue, column: &Column) -> Result<(), String> { + if matches!(value, OwnedValue::Static(StaticNode::Null)) { + return Ok(()); + } + match &column.bq_type { + BqType::Json => { + let text = simd_json::to_string(value) + .map_err(|e| format!("column '{}': cannot serialize JSON: {e}", column.name))?; + *value = OwnedValue::String(text); + } + BqType::Bytes => { + let OwnedValue::String(text) = value else { + return Err(format!("column '{}' expects a base64 string", column.name)); + }; + let bytes = BASE64 + .decode(text.as_bytes()) + .map_err(|e| format!("column '{}': invalid base64: {e}", column.name))?; + *value = OwnedValue::String(hex::encode(bytes)); + } + BqType::Record(children) => { + let OwnedValue::Object(object) = value else { + return Ok(()); + }; + for child in children { + match (object.get_mut(child.name.as_str()), child.mode) { + (None | Some(OwnedValue::Static(StaticNode::Null)), Mode::Repeated) => { + object.insert(child.name.clone(), empty_array()); + } + (Some(child_value), _) => normalize_value(child_value, child)?, + (None, _) => {} + } + } + } + _ => {} + } + Ok(()) +} + +/// Indexes of the layout columns that at least one row sets, in table order. +fn present_columns(rows: &[OwnedValue], layout: &TableLayout) -> Vec<usize> { + let mut present = vec![false; layout.columns.len()]; + for row in rows { + if let OwnedValue::Object(object) = row { + for key in object.keys() { + if let Some(&index) = layout.index.get(key.as_str()) { + present[index] = true; + } + } + } + } + present + .iter() + .enumerate() + .filter_map(|(index, set)| set.then_some(index)) + .collect() +} + +/// Decode rows into one batch. Returns the batch (`None` when there are no +/// payload fields) and the indexes of the rows it holds. +fn decode_rows( + fields: &[FieldRef], + rows: &[OwnedValue], + on_reject: impl FnMut(usize, String), +) -> Result<(Option<RecordBatch>, Vec<usize>), ArrowError> { + decode_rows_with(fields, rows, on_reject, decode) +} + +fn decode_rows_with<'a>( + fields: &[FieldRef], + rows: &'a [OwnedValue], + mut on_reject: impl FnMut(usize, String), + mut decoder: impl FnMut(&SchemaRef, &[&'a OwnedValue]) -> Result<RecordBatch, ArrowError>, +) -> Result<(Option<RecordBatch>, Vec<usize>), ArrowError> { + if fields.is_empty() || rows.is_empty() { + return Ok((None, (0..rows.len()).collect())); + } + let target: SchemaRef = Arc::new(Schema::new(fields.to_vec())); + let schema: SchemaRef = Arc::new(Schema::new( + fields + .iter() + .map(|f| { + f.as_ref() + .clone() + .with_data_type(decode_type(f.data_type())) + }) + .collect::<Vec<_>>(), + )); + let row_refs: Vec<&OwnedValue> = rows.iter().collect(); + let first_error = match decoder(&schema, &row_refs) { + Ok(batch) => { + return Ok((Some(to_target(batch, &target)?), (0..rows.len()).collect())); + } + Err(error) => error, + }; + + let mut valid = vec![true; rows.len()]; + isolate_invalid_rows( + &schema, + &row_refs, + 0, + first_error, + &mut valid, + &mut on_reject, + &mut decoder, + )?; + + let mut valid_rows = Vec::with_capacity(rows.len()); + let mut survivors = Vec::with_capacity(rows.len()); + for (index, row) in row_refs.into_iter().enumerate() { + if valid[index] { + valid_rows.push(row); + survivors.push(index); + } + } + if valid_rows.is_empty() { + return Ok((None, survivors)); + } + let batch = decoder(&schema, &valid_rows)?; + Ok((Some(to_target(batch, &target)?), survivors)) +} + +fn isolate_invalid_rows<'a>( + schema: &SchemaRef, + rows: &[&'a OwnedValue], + first_index: usize, + error: ArrowError, + valid: &mut [bool], + on_reject: &mut impl FnMut(usize, String), + decoder: &mut impl FnMut(&SchemaRef, &[&'a OwnedValue]) -> Result<RecordBatch, ArrowError>, +) -> Result<(), ArrowError> { + if rows.len() == 1 { + valid[first_index] = false; + on_reject( + first_index, + format!("row does not match the table schema: {error}"), + ); + return Ok(()); + } + + let midpoint = rows.len() / 2; + let (left, right) = rows.split_at(midpoint); + if let Err(error) = decoder(schema, left) { + isolate_invalid_rows(schema, left, first_index, error, valid, on_reject, decoder)?; + } + if let Err(error) = decoder(schema, right) { + isolate_invalid_rows( + schema, + right, + first_index + midpoint, + error, + valid, + on_reject, + decoder, + )?; + } + Ok(()) +} + +/// The type `arrow-json` decodes into. Without the `chrono-tz` feature it +/// only parses offset timezones, so `"UTC"` is decoded as `"+00:00"` and +/// relabelled afterwards. Both name the same instant, so the relabel is a +/// metadata change. +fn decode_type(data_type: &DataType) -> DataType { + match data_type { + DataType::Timestamp(unit, Some(_)) => DataType::Timestamp(*unit, Some(UTC_OFFSET.into())), + DataType::List(item) => DataType::List(Arc::new( + item.as_ref() + .clone() + .with_data_type(decode_type(item.data_type())), + )), + DataType::Struct(children) => DataType::Struct( + children + .iter() + .map(|f| { + f.as_ref() + .clone() + .with_data_type(decode_type(f.data_type())) + }) + .collect(), + ), + other => other.clone(), + } +} + +fn to_target(batch: RecordBatch, target: &SchemaRef) -> Result<RecordBatch, ArrowError> { + let columns = batch + .columns() + .iter() + .zip(target.fields()) + .map(|(column, field)| { + if column.data_type() == field.data_type() { + Ok(column.clone()) + } else { + cast(column, field.data_type()) + } + }) + .collect::<Result<Vec<_>, _>>()?; + RecordBatch::try_new(target.clone(), columns) +} + +fn decode<S: serde::Serialize>(schema: &SchemaRef, rows: &[S]) -> Result<RecordBatch, ArrowError> { + let mut decoder = ReaderBuilder::new(schema.clone()) + .with_batch_size(rows.len().max(1)) + .build_decoder()?; + decoder.serialize(rows)?; + decoder + .flush()? + .ok_or_else(|| ArrowError::JsonError("decoder produced no rows".to_owned())) +} + +// ─── Raw mode ──────────────────────────────────────────────────────────────── + +fn encode_raw( + ctx: &RunContext<'_>, + kind: RawKind, + payload_field: &FieldRef, + messages: Vec<ConsumedMessage>, + rejected: &mut Vec<Rejected>, +) -> Result<Option<(RecordBatch, Vec<u64>)>, ArrowError> { + let mut kept = Vec::with_capacity(messages.len()); + let payload_column: ArrayRef = match kind { + RawKind::Bytes => { + let mut values = Vec::with_capacity(messages.len()); + for message in messages { + match message.payload.try_to_bytes() { Review Comment: raw BYTES is cloned, then copied again into the Arrow array. **Fix**: move the bytes into BinaryBuilder. ########## core/connectors/sinks/bigquery_sink/src/encode.rs: ########## @@ -0,0 +1,1289 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Turns a run of `ConsumedMessage`s into Arrow record batches that fit in +//! one `AppendRows` request each. +//! +//! A message that cannot become a row (wrong payload type, a value that does +//! not fit its column, a row larger than the request budget) is rejected on +//! its own and reported back with its offset. The rest of the batch is still +//! written. +//! +//! Mapped mode decodes JSON objects with `arrow-json`. The fast path decodes +//! the whole run at once. When that fails, bisection isolates the offending +//! rows before the survivors are decoded together. +//! +//! The writer schema of a request only contains the columns that at least one +//! row in the run sets. Columns no row mentions are left out, so BigQuery +//! fills them according to `missing_value` (the column default, or NULL). + +use crate::schema::{BqType, Column, MetaColumn, Mode, RawKind, TableLayout, UTC}; +use arrow::array::{ + ArrayRef, BinaryArray, Int64Array, RecordBatch, StringArray, StringBuilder, + TimestampMicrosecondArray, +}; +use arrow::compute::cast; +use arrow::datatypes::{DataType, FieldRef, Schema, SchemaRef}; +use arrow::error::ArrowError; +use arrow::ipc::writer::{ + CompressionContext, DictionaryTracker, IpcDataGenerator, IpcWriteOptions, write_message, +}; +use arrow::json::ReaderBuilder; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64; +use iggy_connector_sdk::{ConsumedMessage, MessagesMetadata, Payload, TopicMetadata}; +use simd_json::{OwnedValue, StaticNode}; +use std::fmt::Write as _; +use std::sync::Arc; + +const HEADER_ENCODING_BASE64: &str = "base64"; +const UTC_OFFSET: &str = "+00:00"; +const IPC_BATCH_OVERHEAD: usize = 1024; +const IPC_COLUMN_OVERHEAD: usize = 128; + +/// One `AppendRows` request worth of rows. +#[derive(Debug)] +pub(crate) struct Chunk { + pub batch: RecordBatch, + /// Iggy offset of each row, same order as `batch`. + pub offsets: Vec<u64>, + pub schema_bytes: Vec<u8>, + pub batch_bytes: Vec<u8>, +} + +/// A message that was not turned into a row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Rejected { + pub offset: u64, + pub reason: String, +} + +#[derive(Debug, Default)] +pub(crate) struct Encoded { + pub chunks: Vec<Chunk>, + pub rejected: Vec<Rejected>, +} + +/// Per-run context shared by every row. +pub(crate) struct RunContext<'a> { + pub layout: &'a TableLayout, + pub topic: &'a TopicMetadata, + pub messages: &'a MessagesMetadata, + pub max_request_bytes: usize, +} + +/// Encode a run of messages. Fails only on an internal Arrow error, which +/// means the batch as a whole cannot be built. Per-row problems end up in +/// `Encoded::rejected`. +pub(crate) fn encode( + ctx: &RunContext<'_>, + messages: Vec<ConsumedMessage>, +) -> Result<Encoded, ArrowError> { + let mut rejected = Vec::new(); + let batch = match &ctx.layout.raw { + Some((kind, field)) => encode_raw(ctx, *kind, field, messages, &mut rejected)?, + None => encode_mapped(ctx, messages, &mut rejected)?, + }; + let mut chunks = Vec::new(); + if let Some((batch, offsets)) = batch { + split_into_chunks( + batch, + offsets, + ctx.max_request_bytes, + &mut chunks, + &mut rejected, + )?; + } + Ok(Encoded { chunks, rejected }) +} + +/// Build a new chunk holding only the rows of `chunk` whose index is not in +/// `drop`. Used after BigQuery reports row-level errors. +pub(crate) fn without_rows(chunk: &Chunk, drop: &[usize]) -> Result<Option<Chunk>, ArrowError> { + let keep: Vec<bool> = (0..chunk.batch.num_rows()) + .map(|row| !drop.contains(&row)) + .collect(); + let offsets: Vec<u64> = chunk + .offsets + .iter() + .zip(&keep) + .filter_map(|(offset, keep)| keep.then_some(*offset)) + .collect(); + if offsets.is_empty() { + return Ok(None); + } + let mask = arrow::array::BooleanArray::from(keep); + let batch = arrow::compute::filter_record_batch(&chunk.batch, &mask)?; + let (schema_bytes, batch_bytes) = encode_ipc(&batch)?; + Ok(Some(Chunk { + batch, + offsets, + schema_bytes, + batch_bytes, + })) +} + +// ─── Mapped mode ───────────────────────────────────────────────────────────── + +fn encode_mapped( + ctx: &RunContext<'_>, + messages: Vec<ConsumedMessage>, + rejected: &mut Vec<Rejected>, +) -> Result<Option<(RecordBatch, Vec<u64>)>, ArrowError> { + let layout = ctx.layout; + let mut rows = Vec::with_capacity(messages.len()); + let mut kept = Vec::with_capacity(messages.len()); + for mut message in messages { + let payload = std::mem::replace(&mut message.payload, Payload::Raw(Vec::new())); + match json_object(payload).and_then(|mut row| { + normalize_row(&mut row, layout)?; + Ok(row) + }) { + Ok(row) => { + rows.push(row); + kept.push(message); + } + Err(reason) => rejected.push(Rejected { + offset: message.offset, + reason, + }), + } + } + if rows.is_empty() { + return Ok(None); + } + + let present = present_columns(&rows, layout); + if present.is_empty() && layout.metadata.is_empty() { + rejected.extend(kept.iter().map(|m| Rejected { + offset: m.offset, + reason: "payload has no field matching a table column".to_owned(), + })); + return Ok(None); + } + let payload_fields: Vec<FieldRef> = present.iter().map(|&i| layout.fields[i].clone()).collect(); + + let (decoded, survivors) = decode_rows(&payload_fields, &rows, |row, reason| { + rejected.push(Rejected { + offset: kept[row].offset, + reason, + }); + })?; + if survivors.is_empty() { + return Ok(None); + } + let kept: Vec<&ConsumedMessage> = survivors.iter().map(|&row| &kept[row]).collect(); + let offsets = kept.iter().map(|m| m.offset).collect(); + + let mut fields = payload_fields; + let mut columns: Vec<ArrayRef> = decoded.map(|b| b.columns().to_vec()).unwrap_or_default(); + append_metadata(ctx, &kept, &mut fields, &mut columns)?; + let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)?; + Ok(Some((batch, offsets))) +} + +/// Take the JSON object out of a payload. Text and proto text must parse as +/// a JSON object. +fn json_object(payload: Payload) -> Result<OwnedValue, String> { + let value = match payload { + Payload::Json(value) => value, + Payload::Text(text) | Payload::Proto(text) => { + let mut bytes = text.into_bytes(); + simd_json::to_owned_value(&mut bytes) + .map_err(|e| format!("payload text is not valid JSON: {e}"))? + } + other => { + return Err(format!( + "{} payload is not supported in mapped mode", + payload_kind(&other) + )); + } + }; + match value { + OwnedValue::Object(_) => Ok(value), + _ => Err("payload is not a JSON object".to_owned()), + } +} + +/// Prepare one row for `arrow-json`: +/// - a REQUIRED column without a default must be present and non-null, +/// - REPEATED columns that are absent or null become `[]`, +/// - JSON column values become their JSON text, +/// - BYTES column values are base64 in JSON and become hex, which is what +/// `arrow-json` decodes into binary. +fn normalize_row(row: &mut OwnedValue, layout: &TableLayout) -> Result<(), String> { + let OwnedValue::Object(object) = row else { + return Err("payload is not a JSON object".to_owned()); + }; + for column in &layout.columns { + let value = object.get_mut(column.name.as_str()); + match (value, column.mode) { + (None | Some(OwnedValue::Static(StaticNode::Null)), Mode::Repeated) => { + object.insert(column.name.clone(), empty_array()); + } + (None | Some(OwnedValue::Static(StaticNode::Null)), Mode::Required) + if !column.has_default => + { + return Err(format!( + "missing value for REQUIRED column '{}'", + column.name + )); + } + (Some(value), _) => normalize_value(value, column)?, + (None, _) => {} + } + } + Ok(()) +} + +fn normalize_value(value: &mut OwnedValue, column: &Column) -> Result<(), String> { + if column.mode == Mode::Repeated { + let OwnedValue::Array(items) = value else { + return Err(format!("column '{}' expects an array", column.name)); + }; + for item in items.iter_mut() { + normalize_scalar(item, column)?; + } + return Ok(()); + } + normalize_scalar(value, column) +} + +fn normalize_scalar(value: &mut OwnedValue, column: &Column) -> Result<(), String> { + if matches!(value, OwnedValue::Static(StaticNode::Null)) { + return Ok(()); + } + match &column.bq_type { + BqType::Json => { + let text = simd_json::to_string(value) + .map_err(|e| format!("column '{}': cannot serialize JSON: {e}", column.name))?; + *value = OwnedValue::String(text); + } + BqType::Bytes => { + let OwnedValue::String(text) = value else { + return Err(format!("column '{}' expects a base64 string", column.name)); + }; + let bytes = BASE64 + .decode(text.as_bytes()) + .map_err(|e| format!("column '{}': invalid base64: {e}", column.name))?; + *value = OwnedValue::String(hex::encode(bytes)); + } + BqType::Record(children) => { + let OwnedValue::Object(object) = value else { + return Ok(()); + }; + for child in children { + match (object.get_mut(child.name.as_str()), child.mode) { + (None | Some(OwnedValue::Static(StaticNode::Null)), Mode::Repeated) => { + object.insert(child.name.clone(), empty_array()); + } + (Some(child_value), _) => normalize_value(child_value, child)?, + (None, _) => {} + } + } + } + _ => {} + } + Ok(()) +} + +/// Indexes of the layout columns that at least one row sets, in table order. +fn present_columns(rows: &[OwnedValue], layout: &TableLayout) -> Vec<usize> { + let mut present = vec![false; layout.columns.len()]; + for row in rows { + if let OwnedValue::Object(object) = row { + for key in object.keys() { + if let Some(&index) = layout.index.get(key.as_str()) { + present[index] = true; + } + } + } + } + present + .iter() + .enumerate() + .filter_map(|(index, set)| set.then_some(index)) + .collect() +} + +/// Decode rows into one batch. Returns the batch (`None` when there are no +/// payload fields) and the indexes of the rows it holds. +fn decode_rows( + fields: &[FieldRef], + rows: &[OwnedValue], + on_reject: impl FnMut(usize, String), +) -> Result<(Option<RecordBatch>, Vec<usize>), ArrowError> { + decode_rows_with(fields, rows, on_reject, decode) +} + +fn decode_rows_with<'a>( + fields: &[FieldRef], + rows: &'a [OwnedValue], + mut on_reject: impl FnMut(usize, String), + mut decoder: impl FnMut(&SchemaRef, &[&'a OwnedValue]) -> Result<RecordBatch, ArrowError>, +) -> Result<(Option<RecordBatch>, Vec<usize>), ArrowError> { + if fields.is_empty() || rows.is_empty() { + return Ok((None, (0..rows.len()).collect())); + } + let target: SchemaRef = Arc::new(Schema::new(fields.to_vec())); + let schema: SchemaRef = Arc::new(Schema::new( + fields + .iter() + .map(|f| { + f.as_ref() + .clone() + .with_data_type(decode_type(f.data_type())) + }) + .collect::<Vec<_>>(), + )); + let row_refs: Vec<&OwnedValue> = rows.iter().collect(); + let first_error = match decoder(&schema, &row_refs) { + Ok(batch) => { + return Ok((Some(to_target(batch, &target)?), (0..rows.len()).collect())); + } + Err(error) => error, + }; + + let mut valid = vec![true; rows.len()]; + isolate_invalid_rows( + &schema, + &row_refs, + 0, + first_error, + &mut valid, + &mut on_reject, + &mut decoder, + )?; + + let mut valid_rows = Vec::with_capacity(rows.len()); + let mut survivors = Vec::with_capacity(rows.len()); + for (index, row) in row_refs.into_iter().enumerate() { + if valid[index] { + valid_rows.push(row); + survivors.push(index); + } + } + if valid_rows.is_empty() { + return Ok((None, survivors)); + } + let batch = decoder(&schema, &valid_rows)?; + Ok((Some(to_target(batch, &target)?), survivors)) +} + +fn isolate_invalid_rows<'a>( + schema: &SchemaRef, + rows: &[&'a OwnedValue], + first_index: usize, + error: ArrowError, + valid: &mut [bool], + on_reject: &mut impl FnMut(usize, String), + decoder: &mut impl FnMut(&SchemaRef, &[&'a OwnedValue]) -> Result<RecordBatch, ArrowError>, +) -> Result<(), ArrowError> { + if rows.len() == 1 { + valid[first_index] = false; + on_reject( + first_index, + format!("row does not match the table schema: {error}"), + ); + return Ok(()); + } + + let midpoint = rows.len() / 2; + let (left, right) = rows.split_at(midpoint); + if let Err(error) = decoder(schema, left) { + isolate_invalid_rows(schema, left, first_index, error, valid, on_reject, decoder)?; + } + if let Err(error) = decoder(schema, right) { + isolate_invalid_rows( + schema, + right, + first_index + midpoint, + error, + valid, + on_reject, + decoder, + )?; + } + Ok(()) +} + +/// The type `arrow-json` decodes into. Without the `chrono-tz` feature it +/// only parses offset timezones, so `"UTC"` is decoded as `"+00:00"` and +/// relabelled afterwards. Both name the same instant, so the relabel is a +/// metadata change. +fn decode_type(data_type: &DataType) -> DataType { + match data_type { + DataType::Timestamp(unit, Some(_)) => DataType::Timestamp(*unit, Some(UTC_OFFSET.into())), + DataType::List(item) => DataType::List(Arc::new( + item.as_ref() + .clone() + .with_data_type(decode_type(item.data_type())), + )), + DataType::Struct(children) => DataType::Struct( + children + .iter() + .map(|f| { + f.as_ref() + .clone() + .with_data_type(decode_type(f.data_type())) + }) + .collect(), + ), + other => other.clone(), + } +} + +fn to_target(batch: RecordBatch, target: &SchemaRef) -> Result<RecordBatch, ArrowError> { + let columns = batch + .columns() + .iter() + .zip(target.fields()) + .map(|(column, field)| { + if column.data_type() == field.data_type() { + Ok(column.clone()) + } else { + cast(column, field.data_type()) + } + }) + .collect::<Result<Vec<_>, _>>()?; + RecordBatch::try_new(target.clone(), columns) +} + +fn decode<S: serde::Serialize>(schema: &SchemaRef, rows: &[S]) -> Result<RecordBatch, ArrowError> { + let mut decoder = ReaderBuilder::new(schema.clone()) + .with_batch_size(rows.len().max(1)) + .build_decoder()?; + decoder.serialize(rows)?; + decoder + .flush()? + .ok_or_else(|| ArrowError::JsonError("decoder produced no rows".to_owned())) +} + +// ─── Raw mode ──────────────────────────────────────────────────────────────── + +fn encode_raw( + ctx: &RunContext<'_>, + kind: RawKind, + payload_field: &FieldRef, + messages: Vec<ConsumedMessage>, + rejected: &mut Vec<Rejected>, +) -> Result<Option<(RecordBatch, Vec<u64>)>, ArrowError> { + let mut kept = Vec::with_capacity(messages.len()); + let payload_column: ArrayRef = match kind { + RawKind::Bytes => { + let mut values = Vec::with_capacity(messages.len()); + for message in messages { + match message.payload.try_to_bytes() { + Ok(bytes) => { + values.push(bytes); + kept.push(message); + } + Err(e) => rejected.push(Rejected { + offset: message.offset, + reason: e.to_string(), + }), + } + } + Arc::new(BinaryArray::from_iter_values(values)) + } + RawKind::Json | RawKind::String => { + let mut values = Vec::with_capacity(messages.len()); + for mut message in messages { + let payload = std::mem::replace(&mut message.payload, Payload::Raw(Vec::new())); + match raw_text(payload, kind) { + Ok(text) => { + values.push(text); + kept.push(message); + } + Err(reason) => rejected.push(Rejected { + offset: message.offset, + reason, + }), + } + } + Arc::new(StringArray::from_iter_values(values)) + } + }; + if kept.is_empty() { + return Ok(None); + } + let kept: Vec<&ConsumedMessage> = kept.iter().collect(); + let offsets = kept.iter().map(|m| m.offset).collect(); + let mut fields = vec![payload_field.clone()]; + let mut columns = vec![payload_column]; + append_metadata(ctx, &kept, &mut fields, &mut columns)?; + let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)?; + Ok(Some((batch, offsets))) +} + +/// Payload as text for a JSON or STRING column. A JSON column only takes +/// text that parses as JSON. +fn raw_text(payload: Payload, kind: RawKind) -> Result<String, String> { + let text = match payload { + Payload::Json(value) => { + return simd_json::to_string(&value).map_err(|e| format!("cannot serialize JSON: {e}")); + } + Payload::Text(text) | Payload::Proto(text) => text, + Payload::Raw(bytes) => { + String::from_utf8(bytes).map_err(|_| "raw payload is not valid UTF-8".to_owned())? + } + other => { + return Err(format!( + "{} payload cannot be written to a text column", + payload_kind(&other) + )); + } + }; + if kind == RawKind::Json { + let mut bytes = text.as_bytes().to_vec(); Review Comment: raw JSON validation copies the payload into an owned tree and then drops it. **Fix**: use simd_json::to_borrowed_value -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
