Skip to main content

risingwave_connector/sink/
starrocks.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, HashMap};
16use std::num::NonZeroU64;
17use std::sync::Arc;
18
19use anyhow::anyhow;
20use async_trait::async_trait;
21use bytes::Bytes;
22use chrono_tz::Tz;
23use mysql_async::Opts;
24use mysql_async::prelude::Queryable;
25use risingwave_common::array::{Op, StreamChunk};
26use risingwave_common::catalog::Schema;
27use risingwave_common::types::DataType;
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30use serde_with::{DisplayFromStr, serde_as};
31use thiserror_ext::AsReport;
32use url::form_urlencoded;
33use uuid::Uuid;
34use with_options::WithOptions;
35
36use super::decouple_checkpoint_log_sink::DEFAULT_COMMIT_CHECKPOINT_INTERVAL_WITH_SINK_DECOUPLE;
37use super::doris_starrocks_connector::{
38    HeaderBuilder, InserterInner, STARROCKS_DELETE_SIGN, STARROCKS_SUCCESS_STATUS,
39    StarrocksTxnRequestBuilder,
40};
41use super::encoder::{JsonEncoder, RowEncoder};
42use super::{
43    SINK_TYPE_APPEND_ONLY, SINK_TYPE_OPTION, SINK_TYPE_UPSERT, SinkError, SinkParam,
44    SinkWriterMetrics,
45};
46use crate::enforce_secret::EnforceSecret;
47use crate::sink::decouple_checkpoint_log_sink::DecoupleCheckpointLogSinkerOf;
48use crate::sink::writer::SinkWriter;
49use crate::sink::{Result, Sink, SinkWriterParam};
50
51pub const STARROCKS_SINK: &str = "starrocks";
52const STARROCK_MYSQL_PREFER_SOCKET: &str = "false";
53const STARROCK_MYSQL_MAX_ALLOWED_PACKET: usize = 1024;
54const STARROCK_MYSQL_WAIT_TIMEOUT: usize = 28800;
55pub const fn _default_stream_load_http_timeout_ms() -> u64 {
56    30 * 1000
57}
58
59const fn default_use_https() -> bool {
60    false
61}
62
63#[serde_as]
64#[derive(Deserialize, Debug, Clone, WithOptions)]
65pub struct StarrocksCommon {
66    /// The `StarRocks` host address.
67    #[serde(rename = "starrocks.host")]
68    pub host: String,
69    /// The port to the MySQL server of `StarRocks` FE.
70    #[serde(rename = "starrocks.mysqlport", alias = "starrocks.query_port")]
71    pub mysql_port: String,
72    /// The port to the HTTP server of `StarRocks` FE.
73    #[serde(rename = "starrocks.httpport", alias = "starrocks.http_port")]
74    pub http_port: String,
75    /// The user name used to access the `StarRocks` database.
76    #[serde(rename = "starrocks.user")]
77    pub user: String,
78    /// The password associated with the user.
79    #[serde(rename = "starrocks.password")]
80    pub password: String,
81    /// The `StarRocks` database where the target table is located
82    #[serde(rename = "starrocks.database")]
83    pub database: String,
84    /// The `StarRocks` table you want to sink data to.
85    #[serde(rename = "starrocks.table")]
86    pub table: String,
87
88    /// Whether to use https to connect to the `StarRocks` server.
89    #[serde(rename = "starrocks.use_https")]
90    #[serde(default = "default_use_https")]
91    #[serde_as(as = "DisplayFromStr")]
92    pub use_https: bool,
93}
94
95impl EnforceSecret for StarrocksCommon {
96    const ENFORCE_SECRET_PROPERTIES: phf::Set<&'static str> = phf::phf_set! {
97        "starrocks.password", "starrocks.user"
98    };
99}
100
101#[serde_as]
102#[derive(Clone, Debug, Deserialize, WithOptions)]
103pub struct StarrocksConfig {
104    #[serde(flatten)]
105    pub common: StarrocksCommon,
106
107    /// The timeout in milliseconds for stream load http request, defaults to 10 seconds.
108    #[serde(
109        rename = "starrocks.stream_load.http.timeout.ms",
110        default = "_default_stream_load_http_timeout_ms"
111    )]
112    #[serde_as(as = "DisplayFromStr")]
113    #[with_option(allow_alter_on_fly)]
114    pub stream_load_http_timeout_ms: u64,
115
116    /// Set this option to a positive integer n, RisingWave will try to commit data
117    /// to Starrocks at every n checkpoints by leveraging the
118    /// [StreamLoad Transaction API](https://docs.starrocks.io/docs/loading/Stream_Load_transaction_interface/),
119    /// also, in this time, the `sink_decouple` option should be enabled as well.
120    /// Defaults to 10 if `commit_checkpoint_interval` <= 0
121    #[serde(default = "default_commit_checkpoint_interval")]
122    #[serde_as(as = "DisplayFromStr")]
123    #[with_option(allow_alter_on_fly)]
124    pub commit_checkpoint_interval: u64,
125
126    /// Enable partial update
127    #[serde(rename = "starrocks.partial_update")]
128    pub partial_update: Option<String>,
129
130    /// The maximum size in bytes for each `StarRocks` stream load request payload.
131    /// Defaults to unlimited.
132    #[serde(rename = "starrocks.max_batch_size_bytes")]
133    #[serde_as(as = "Option<DisplayFromStr>")]
134    #[with_option(allow_alter_on_fly)]
135    pub max_batch_size_bytes: Option<u64>,
136
137    /// The maximum cumulative serialized payload bytes per writer/transaction.
138    /// Defaults to unlimited. Before the next row would exceed this limit, commit
139    /// the current transaction, even before `commit_checkpoint_interval` elapses.
140    /// A single oversized row is rejected. Early commits can increase data versions;
141    /// recovery can replay committed data under the sink's at-least-once contract.
142    #[serde(rename = "starrocks.max_transaction_size_bytes")]
143    #[serde_as(as = "Option<DisplayFromStr>")]
144    #[with_option(allow_alter_on_fly)]
145    pub max_transaction_size_bytes: Option<u64>,
146
147    /// Skip the `StarRocks` JSON size check. Defaults to false. This may increase
148    /// backend memory usage and does not disable `starrocks.max_batch_size_bytes`.
149    #[serde(rename = "starrocks.ignore_json_size", default)]
150    #[serde_as(as = "DisplayFromStr")]
151    #[with_option(allow_alter_on_fly)]
152    pub ignore_json_size: bool,
153
154    /// The `StarRocks` load job memory limit in bytes. When omitted, use the server default.
155    /// This is not a limit on all HTTP receive buffers or total backend memory usage.
156    #[serde(rename = "starrocks.load_mem_limit")]
157    #[serde_as(as = "Option<DisplayFromStr>")]
158    #[with_option(allow_alter_on_fly)]
159    pub load_mem_limit: Option<u64>,
160
161    /// The server-side transaction timeout in seconds, from begin to prepared.
162    /// A positive 32-bit signed integer, subject to the server's configured timeout range.
163    /// When omitted, use the server default. Independent of the client HTTP timeout.
164    #[serde(rename = "starrocks.transaction_timeout_seconds")]
165    #[serde_as(as = "Option<DisplayFromStr>")]
166    #[with_option(allow_alter_on_fly)]
167    pub transaction_timeout_seconds: Option<u32>,
168
169    pub r#type: String, // accept "append-only" or "upsert"
170
171    #[serde(flatten)]
172    pub unknown_fields: std::collections::HashMap<String, String>,
173}
174
175crate::impl_sink_unknown_fields!(StarrocksConfig);
176
177impl EnforceSecret for StarrocksConfig {
178    fn enforce_one(prop: &str) -> crate::error::ConnectorResult<()> {
179        StarrocksCommon::enforce_one(prop)
180    }
181}
182
183fn default_commit_checkpoint_interval() -> u64 {
184    DEFAULT_COMMIT_CHECKPOINT_INTERVAL_WITH_SINK_DECOUPLE
185}
186
187impl StarrocksConfig {
188    pub fn from_btreemap(properties: BTreeMap<String, String>) -> Result<Self> {
189        let config =
190            serde_json::from_value::<StarrocksConfig>(serde_json::to_value(properties).unwrap())
191                .map_err(|e| SinkError::Config(anyhow!(e)))?;
192        if config.r#type != SINK_TYPE_APPEND_ONLY && config.r#type != SINK_TYPE_UPSERT {
193            return Err(SinkError::Config(anyhow!(
194                "`{}` must be {}, or {}",
195                SINK_TYPE_OPTION,
196                SINK_TYPE_APPEND_ONLY,
197                SINK_TYPE_UPSERT
198            )));
199        }
200        if config.commit_checkpoint_interval == 0 {
201            return Err(SinkError::Config(anyhow!(
202                "`commit_checkpoint_interval` must be greater than 0"
203            )));
204        }
205        if let Some(0) = config.max_batch_size_bytes {
206            return Err(SinkError::Config(anyhow!(
207                "`starrocks.max_batch_size_bytes` must be greater than 0"
208            )));
209        }
210        if let Some(0) = config.max_transaction_size_bytes {
211            return Err(SinkError::Config(anyhow!(
212                "`starrocks.max_transaction_size_bytes` must be greater than 0"
213            )));
214        }
215        if config
216            .load_mem_limit
217            .is_some_and(|limit| limit > i64::MAX as u64)
218        {
219            return Err(SinkError::Config(anyhow!(
220                "`starrocks.load_mem_limit` must not exceed {} bytes",
221                i64::MAX
222            )));
223        }
224        if config
225            .transaction_timeout_seconds
226            .is_some_and(|timeout| timeout == 0 || timeout > i32::MAX as u32)
227        {
228            return Err(SinkError::Config(anyhow!(
229                "`starrocks.transaction_timeout_seconds` must be between 1 and {} seconds",
230                i32::MAX
231            )));
232        }
233        Ok(config)
234    }
235}
236
237#[derive(Debug, PartialEq, Eq)]
238struct PayloadSizeDecision {
239    finish_current_payload: bool,
240    next_payload_size_bytes: u64,
241}
242
243fn decide_payload_size(
244    current_size_bytes: u64,
245    row_size: u64,
246    max_size_bytes: u64,
247    option_name: &str,
248) -> Result<PayloadSizeDecision> {
249    if row_size > max_size_bytes {
250        return Err(SinkError::Starrocks(format!(
251            "single row payload size {} bytes exceeds `{}` limit {} bytes",
252            row_size, option_name, max_size_bytes
253        )));
254    }
255
256    if current_size_bytes > 0
257        && current_size_bytes
258            .checked_add(row_size)
259            .is_none_or(|next_payload_size_bytes| next_payload_size_bytes > max_size_bytes)
260    {
261        return Ok(PayloadSizeDecision {
262            finish_current_payload: true,
263            next_payload_size_bytes: row_size,
264        });
265    }
266
267    Ok(PayloadSizeDecision {
268        finish_current_payload: false,
269        next_payload_size_bytes: current_size_bytes
270            .checked_add(row_size)
271            .expect("sum is checked against max_size_bytes above"),
272    })
273}
274
275#[derive(Debug)]
276pub struct StarrocksSink {
277    pub config: StarrocksConfig,
278    schema: Schema,
279    pk_indices: Vec<usize>,
280    is_append_only: bool,
281}
282
283impl EnforceSecret for StarrocksSink {
284    fn enforce_secret<'a>(
285        prop_iter: impl Iterator<Item = &'a str>,
286    ) -> crate::error::ConnectorResult<()> {
287        for prop in prop_iter {
288            StarrocksConfig::enforce_one(prop)?;
289        }
290        Ok(())
291    }
292}
293
294impl StarrocksSink {
295    pub fn new(param: SinkParam, config: StarrocksConfig, schema: Schema) -> Result<Self> {
296        let pk_indices = param.downstream_pk_or_empty();
297        let is_append_only = param.sink_type.is_append_only();
298        Ok(Self {
299            config,
300            schema,
301            pk_indices,
302            is_append_only,
303        })
304    }
305}
306
307impl StarrocksSink {
308    fn starrocks_data_type_contains_any(
309        starrocks_data_type: &str,
310        expected_types: &[&str],
311    ) -> bool {
312        expected_types
313            .iter()
314            .any(|expected_type| starrocks_data_type.contains(expected_type))
315    }
316
317    fn check_column_name_and_type(
318        &self,
319        starrocks_columns_desc: HashMap<String, String>,
320    ) -> Result<()> {
321        let rw_fields_name = self.schema.fields();
322        if rw_fields_name.len() > starrocks_columns_desc.len() {
323            return Err(SinkError::Starrocks("The columns of the sink must be equal to or a superset of the target table's columns.".to_owned()));
324        }
325
326        for i in rw_fields_name {
327            let value = starrocks_columns_desc.get(&i.name).ok_or_else(|| {
328                SinkError::Starrocks(format!(
329                    "Column name don't find in starrocks, risingwave is {:?} ",
330                    i.name
331                ))
332            })?;
333            if !Self::check_and_correct_column_type(&i.data_type, value)? {
334                return Err(SinkError::Starrocks(format!(
335                    "Column type don't match, column name is {:?}. starrocks type is {:?} risingwave type is {:?} ",
336                    i.name, value, i.data_type
337                )));
338            }
339        }
340        Ok(())
341    }
342
343    fn check_and_correct_column_type(
344        rw_data_type: &DataType,
345        starrocks_data_type: &str,
346    ) -> Result<bool> {
347        match rw_data_type {
348            risingwave_common::types::DataType::Boolean => {
349                Ok(Self::starrocks_data_type_contains_any(
350                    starrocks_data_type,
351                    &["tinyint", "boolean"],
352                ))
353            }
354            risingwave_common::types::DataType::Int16 => {
355                Ok(starrocks_data_type.contains("smallint"))
356            }
357            risingwave_common::types::DataType::Int32 => Ok(starrocks_data_type.contains("int")),
358            risingwave_common::types::DataType::Int64 => Ok(starrocks_data_type.contains("bigint")),
359            risingwave_common::types::DataType::Float32 => {
360                Ok(starrocks_data_type.contains("float"))
361            }
362            risingwave_common::types::DataType::Float64 => {
363                Ok(starrocks_data_type.contains("double"))
364            }
365            risingwave_common::types::DataType::Decimal => {
366                Ok(starrocks_data_type.contains("decimal"))
367            }
368            risingwave_common::types::DataType::Date => Ok(starrocks_data_type.contains("date")),
369            risingwave_common::types::DataType::Varchar => {
370                Ok(starrocks_data_type.contains("varchar"))
371            }
372            risingwave_common::types::DataType::Time => Err(SinkError::Starrocks(
373                "TIME is not supported for Starrocks sink. Please convert to VARCHAR or other supported types.".to_owned(),
374            )),
375            risingwave_common::types::DataType::Timestamp => {
376                Ok(starrocks_data_type.contains("datetime"))
377            }
378            risingwave_common::types::DataType::Timestamptz => {
379                // StarRocks JSON encoding writes timestamptz as a timestamp string without a
380                // timezone suffix, so StarRocks can parse it into DATETIME or store it as text.
381                Ok(Self::starrocks_data_type_contains_any(
382                    starrocks_data_type,
383                    &["datetime", "varchar", "char", "string"],
384                ))
385            }
386            risingwave_common::types::DataType::Interval => Err(SinkError::Starrocks(
387                "INTERVAL is not supported for Starrocks sink. Please convert to VARCHAR or other supported types.".to_owned(),
388            )),
389            risingwave_common::types::DataType::Struct(_) => Err(SinkError::Starrocks(
390                "STRUCT is not supported for Starrocks sink.".to_owned(),
391            )),
392            risingwave_common::types::DataType::List(list) => {
393                // For compatibility with older versions starrocks
394                if starrocks_data_type.contains("unknown") {
395                    return Ok(true);
396                }
397                let check_result = Self::check_and_correct_column_type(list.elem(), starrocks_data_type)?;
398                Ok(check_result && starrocks_data_type.contains("array"))
399            }
400            risingwave_common::types::DataType::Bytea => Err(SinkError::Starrocks(
401                "BYTEA is not supported for Starrocks sink. Please convert to VARCHAR or other supported types.".to_owned(),
402            )),
403            risingwave_common::types::DataType::Jsonb => Ok(starrocks_data_type.contains("json")),
404            risingwave_common::types::DataType::Variant => Err(SinkError::Starrocks(
405                "VARIANT is not supported for Starrocks sink.".to_owned(),
406            )),
407            risingwave_common::types::DataType::Serial => {
408                Ok(starrocks_data_type.contains("bigint"))
409            }
410            risingwave_common::types::DataType::Int256 => Err(SinkError::Starrocks(
411                "INT256 is not supported for Starrocks sink.".to_owned(),
412            )),
413            risingwave_common::types::DataType::Map(_) => Err(SinkError::Starrocks(
414                "MAP is not supported for Starrocks sink.".to_owned(),
415            )),
416            DataType::Vector(_) => Err(SinkError::Starrocks(
417                "VECTOR is not supported for Starrocks sink.".to_owned(),
418            )),
419        }
420    }
421}
422
423impl Sink for StarrocksSink {
424    type LogSinker = DecoupleCheckpointLogSinkerOf<StarrocksSinkWriter>;
425
426    const SINK_NAME: &'static str = STARROCKS_SINK;
427
428    crate::impl_validate_sink_unknown_fields!();
429
430    async fn validate(&self) -> Result<()> {
431        if !self.is_append_only && self.pk_indices.is_empty() {
432            return Err(SinkError::Config(anyhow!(
433                "Primary key not defined for upsert starrocks sink (please define in `primary_key` field)"
434            )));
435        }
436        // check reachability
437        let mut client = StarrocksSchemaClient::new(
438            self.config.common.host.clone(),
439            self.config.common.mysql_port.clone(),
440            self.config.common.table.clone(),
441            self.config.common.database.clone(),
442            self.config.common.user.clone(),
443            self.config.common.password.clone(),
444        )
445        .await?;
446        let (read_model, pks) = client.get_pk_from_starrocks().await?;
447
448        if !self.is_append_only && read_model.ne("PRIMARY_KEYS") {
449            return Err(SinkError::Config(anyhow!(
450                "If you want to use upsert, please set the keysType of starrocks to PRIMARY_KEY"
451            )));
452        }
453
454        for (index, filed) in self.schema.fields().iter().enumerate() {
455            if self.pk_indices.contains(&index) && !pks.contains(&filed.name) {
456                return Err(SinkError::Starrocks(format!(
457                    "Can't find pk {:?} in starrocks",
458                    filed.name
459                )));
460            }
461        }
462
463        let starrocks_columns_desc = client.get_columns_from_starrocks().await?;
464
465        self.check_column_name_and_type(starrocks_columns_desc)?;
466        Ok(())
467    }
468
469    fn validate_alter_config(config: &BTreeMap<String, String>) -> Result<()> {
470        StarrocksConfig::from_btreemap(config.clone())?;
471        Ok(())
472    }
473
474    async fn new_log_sinker(&self, writer_param: SinkWriterParam) -> Result<Self::LogSinker> {
475        let commit_checkpoint_interval =
476            NonZeroU64::new(self.config.commit_checkpoint_interval).expect(
477                "commit_checkpoint_interval should be greater than 0, and it should be checked in config validation",
478            );
479
480        let writer = StarrocksSinkWriter::new(
481            self.config.clone(),
482            self.schema.clone(),
483            self.pk_indices.clone(),
484            self.is_append_only,
485            writer_param.time_zone,
486        )?;
487
488        let metrics = SinkWriterMetrics::new(&writer_param);
489
490        Ok(DecoupleCheckpointLogSinkerOf::new(
491            writer,
492            metrics,
493            commit_checkpoint_interval,
494        ))
495    }
496}
497
498pub struct StarrocksSinkWriter {
499    #[expect(dead_code)]
500    schema: Schema,
501    #[expect(dead_code)]
502    pk_indices: Vec<usize>,
503    is_append_only: bool,
504    client: Option<StarrocksClient>,
505    txn_client: Arc<StarrocksTxnClient>,
506    row_encoder: JsonEncoder,
507    // Retain the cleanup label across RPC awaits. Failed or cancelled writers are discarded.
508    curr_txn_label: Option<String>,
509    max_batch_size_bytes: Option<u64>,
510    current_batch_size_bytes: u64,
511    max_transaction_size_bytes: Option<u64>,
512    current_transaction_size_bytes: u64,
513}
514
515impl TryFrom<SinkParam> for StarrocksSink {
516    type Error = SinkError;
517
518    fn try_from(param: SinkParam) -> std::result::Result<Self, Self::Error> {
519        let schema = param.schema();
520        let config = StarrocksConfig::from_btreemap(param.properties.clone())?;
521        StarrocksSink::new(param, config, schema)
522    }
523}
524
525impl StarrocksSinkWriter {
526    pub fn new(
527        config: StarrocksConfig,
528        schema: Schema,
529        pk_indices: Vec<usize>,
530        is_append_only: bool,
531        time_zone: Tz,
532    ) -> Result<Self> {
533        let mut field_names = schema.names_str();
534        if !is_append_only {
535            field_names.push(STARROCKS_DELETE_SIGN);
536        };
537        // we should quote field names in `MySQL` style to prevent `StarRocks` from rejecting the request due to
538        // a field name being a reserved word. For example, `order`, 'from`, etc.
539        let field_names = field_names
540            .into_iter()
541            .map(|name| format!("`{}`", name))
542            .collect::<Vec<String>>();
543        let field_names_str = field_names
544            .iter()
545            .map(|name| name.as_str())
546            .collect::<Vec<&str>>();
547
548        let header = HeaderBuilder::new()
549            .add_common_header()
550            .set_user_password(config.common.user.clone(), config.common.password.clone())
551            .add_json_format()
552            .set_partial_update(config.partial_update.clone())
553            .set_columns_name(field_names_str)
554            .set_db(config.common.database.clone())
555            .set_table(config.common.table.clone())
556            .build();
557
558        let url = if config.common.use_https {
559            format!("https://{}:{}", config.common.host, config.common.http_port)
560        } else {
561            format!("http://{}:{}", config.common.host, config.common.http_port)
562        };
563        let txn_request_builder =
564            StarrocksTxnRequestBuilder::new(url, header, config.stream_load_http_timeout_ms)?
565                .with_load_options(config.ignore_json_size, config.load_mem_limit)
566                .with_transaction_timeout_seconds(config.transaction_timeout_seconds);
567
568        Ok(Self {
569            schema: schema.clone(),
570            pk_indices,
571            is_append_only,
572            client: None,
573            txn_client: Arc::new(StarrocksTxnClient::new(txn_request_builder)),
574            row_encoder: JsonEncoder::new_with_starrocks(schema, None, time_zone),
575            curr_txn_label: None,
576            max_batch_size_bytes: config.max_batch_size_bytes,
577            current_batch_size_bytes: 0,
578            max_transaction_size_bytes: config.max_transaction_size_bytes,
579            current_transaction_size_bytes: 0,
580        })
581    }
582
583    async fn finish_load_request(&mut self) -> Result<()> {
584        if let Some(client) = self.client.take() {
585            client.finish().await?;
586            self.current_batch_size_bytes = 0;
587        }
588        Ok(())
589    }
590
591    async fn ensure_load_request(&mut self) -> Result<()> {
592        if self.client.is_none() {
593            let txn_label = self.curr_txn_label.clone().ok_or_else(|| {
594                SinkError::Starrocks("Can't find current starrocks transaction label".to_owned())
595            })?;
596            self.client = Some(StarrocksClient::new(self.txn_client.load(txn_label).await?));
597            self.current_batch_size_bytes = 0;
598        }
599        Ok(())
600    }
601
602    async fn write_row_json(&mut self, row_json_string: String) -> Result<()> {
603        let row_size = row_json_string.len() as u64;
604        // Validate both single-row limits before committing any pending data.
605        for (limit, option) in [
606            (self.max_batch_size_bytes, "starrocks.max_batch_size_bytes"),
607            (
608                self.max_transaction_size_bytes,
609                "starrocks.max_transaction_size_bytes",
610            ),
611        ] {
612            if let Some(limit) = limit {
613                decide_payload_size(0, row_size, limit, option)?;
614            }
615        }
616        let transaction_decision = self
617            .max_transaction_size_bytes
618            .map(|limit| {
619                decide_payload_size(
620                    self.current_transaction_size_bytes,
621                    row_size,
622                    limit,
623                    "starrocks.max_transaction_size_bytes",
624                )
625            })
626            .transpose()?;
627        if transaction_decision
628            .as_ref()
629            .is_some_and(|decision| decision.finish_current_payload)
630        {
631            // Serial commits preserve ordering. The log sinker still truncates only
632            // at its normal checkpoint boundary, so recovery may replay this data.
633            self.commit_current_transaction().await?;
634        }
635        self.ensure_transaction().await?;
636        // Recompute after transaction rollover, which also finishes the previous load.
637        let size_decision = self
638            .max_batch_size_bytes
639            .map(|limit| {
640                decide_payload_size(
641                    self.current_batch_size_bytes,
642                    row_size,
643                    limit,
644                    "starrocks.max_batch_size_bytes",
645                )
646            })
647            .transpose()?;
648        if size_decision
649            .as_ref()
650            .is_some_and(|decision| decision.finish_current_payload)
651        {
652            self.finish_load_request().await?;
653        }
654        self.ensure_load_request().await?;
655        self.client
656            .as_mut()
657            .ok_or_else(|| SinkError::Starrocks("Can't find starrocks sink insert".to_owned()))?
658            .write(row_json_string.into())
659            .await?;
660        if let Some(decision) = size_decision {
661            self.current_batch_size_bytes = decision.next_payload_size_bytes;
662        }
663        if let Some(decision) = transaction_decision {
664            self.current_transaction_size_bytes = decision.next_payload_size_bytes;
665        }
666        Ok(())
667    }
668
669    async fn append_only(&mut self, chunk: StreamChunk) -> Result<()> {
670        for (op, row) in chunk.rows() {
671            if op != Op::Insert {
672                continue;
673            }
674            let row_json_string = Value::Object(self.row_encoder.encode(row)?).to_string();
675            self.write_row_json(row_json_string).await?;
676        }
677        Ok(())
678    }
679
680    async fn upsert(&mut self, chunk: StreamChunk) -> Result<()> {
681        for (op, row) in chunk.rows() {
682            match op {
683                Op::Insert => {
684                    let mut row_json_value = self.row_encoder.encode(row)?;
685                    row_json_value.insert(
686                        STARROCKS_DELETE_SIGN.to_owned(),
687                        Value::String("0".to_owned()),
688                    );
689                    let row_json_string = serde_json::to_string(&row_json_value).map_err(|e| {
690                        SinkError::Starrocks(format!("Json serialize error: {}", e.as_report()))
691                    })?;
692                    self.write_row_json(row_json_string).await?;
693                }
694                Op::Delete => {
695                    let mut row_json_value = self.row_encoder.encode(row)?;
696                    row_json_value.insert(
697                        STARROCKS_DELETE_SIGN.to_owned(),
698                        Value::String("1".to_owned()),
699                    );
700                    let row_json_string = serde_json::to_string(&row_json_value).map_err(|e| {
701                        SinkError::Starrocks(format!("Json serialize error: {}", e.as_report()))
702                    })?;
703                    self.write_row_json(row_json_string).await?;
704                }
705                Op::UpdateDelete => {}
706                Op::UpdateInsert => {
707                    let mut row_json_value = self.row_encoder.encode(row)?;
708                    row_json_value.insert(
709                        STARROCKS_DELETE_SIGN.to_owned(),
710                        Value::String("0".to_owned()),
711                    );
712                    let row_json_string = serde_json::to_string(&row_json_value).map_err(|e| {
713                        SinkError::Starrocks(format!("Json serialize error: {}", e.as_report()))
714                    })?;
715                    self.write_row_json(row_json_string).await?;
716                }
717            }
718        }
719        Ok(())
720    }
721
722    /// Generating a new transaction label, should be unique across all `SinkWriters` even under rewinding.
723    #[inline(always)]
724    fn new_txn_label(&self) -> String {
725        format!(
726            "rw-txn-{}-{}",
727            Uuid::new_v4(),
728            chrono::Utc::now().timestamp_micros()
729        )
730    }
731
732    async fn ensure_transaction(&mut self) -> Result<()> {
733        if self.curr_txn_label.is_some() {
734            return Ok(());
735        }
736        let txn_label = self.new_txn_label();
737        tracing::debug!(?txn_label, "begin transaction");
738        // Retain the label if begin is cancelled or its response is lost.
739        self.curr_txn_label = Some(txn_label.clone());
740        let result = async {
741            let txn_label_res = self.txn_client.begin(txn_label.clone()).await?;
742            if txn_label != txn_label_res {
743                return Err(SinkError::Starrocks(format!(
744                    "label {} returned from StarRocks {} differs from generated one",
745                    txn_label, txn_label_res
746                )));
747            }
748            Ok(())
749        }
750        .await;
751        if let Err(err) = result {
752            self.rollback_after_failure().await;
753            return Err(err);
754        }
755        Ok(())
756    }
757
758    async fn commit_current_transaction(&mut self) -> Result<()> {
759        let result = async {
760            self.finish_load_request().await?;
761            if let Some(txn_label) = self.curr_txn_label.clone() {
762                // Keep the label across awaits for cancellation cleanup through Drop.
763                self.prepare_and_commit(txn_label).await?;
764            }
765            Ok(())
766        }
767        .await;
768        if let Err(err) = result {
769            self.rollback_after_failure().await;
770            return Err(err);
771        }
772        self.curr_txn_label = None;
773        self.current_transaction_size_bytes = 0;
774        Ok(())
775    }
776
777    /// Best-effort cleanup before discarding the writer; callers retain the original error.
778    async fn rollback_after_failure(&mut self) {
779        let Some(txn_label) = self.curr_txn_label.clone() else {
780            return;
781        };
782        tracing::debug!(?txn_label, "rollback transaction");
783        let rollback_result = self.txn_client.rollback(txn_label.clone()).await;
784        // This failed writer is discarded. Cleanup has already been attempted;
785        // avoid a second abort replacing the original operation error. Keep
786        // the label until the await completes so cancellation can still clean up.
787        self.curr_txn_label = None;
788        if let Err(rollback_err) = rollback_result {
789            tracing::warn!(?txn_label, error = ?rollback_err.as_report(), "Couldn't roll back transaction after failure");
790        }
791    }
792
793    async fn prepare_and_commit(&self, txn_label: String) -> Result<()> {
794        tracing::debug!(?txn_label, "prepare transaction");
795        let txn_label_res = self.txn_client.prepare(txn_label.clone()).await?;
796        if txn_label != txn_label_res {
797            return Err(SinkError::Starrocks(format!(
798                "label {} returned from prepare transaction {} differs from the current one",
799                txn_label, txn_label_res
800            )));
801        }
802        tracing::debug!(?txn_label, "commit transaction");
803        let txn_label_res = self.txn_client.commit(txn_label.clone()).await?;
804        if txn_label != txn_label_res {
805            return Err(SinkError::Starrocks(format!(
806                "label {} returned from commit transaction {} differs from the current one",
807                txn_label, txn_label_res
808            )));
809        }
810        Ok(())
811    }
812}
813
814impl Drop for StarrocksSinkWriter {
815    fn drop(&mut self) {
816        if let Some(txn_label) = self.curr_txn_label.take() {
817            let txn_client = self.txn_client.clone();
818            tokio::spawn(async move {
819                if let Err(e) = txn_client.rollback(txn_label.clone()).await {
820                    tracing::error!(
821                        "starrocks rollback transaction error: {:?}, txn label: {}",
822                        e.as_report(),
823                        txn_label
824                    );
825                }
826            });
827        }
828    }
829}
830
831#[async_trait]
832impl SinkWriter for StarrocksSinkWriter {
833    async fn begin_epoch(&mut self, _epoch: u64) -> Result<()> {
834        Ok(())
835    }
836
837    async fn write_batch(&mut self, chunk: StreamChunk) -> Result<()> {
838        if self.is_append_only {
839            self.append_only(chunk).await
840        } else {
841            self.upsert(chunk).await
842        }
843    }
844
845    async fn barrier(&mut self, is_checkpoint: bool) -> Result<()> {
846        if is_checkpoint {
847            self.commit_current_transaction().await?;
848        } else {
849            // A barrier finishes only the HTTP request, not the transaction.
850            self.finish_load_request().await?;
851        }
852        Ok(())
853    }
854
855    async fn abort(&mut self) -> Result<()> {
856        // Cleanup failure must not replace the write error held by the log sinker.
857        self.rollback_after_failure().await;
858        Ok(())
859    }
860}
861
862pub struct StarrocksSchemaClient {
863    table: String,
864    db: String,
865    conn: mysql_async::Conn,
866}
867
868impl StarrocksSchemaClient {
869    pub async fn new(
870        host: String,
871        port: String,
872        table: String,
873        db: String,
874        user: String,
875        password: String,
876    ) -> Result<Self> {
877        // username & password may contain special chars, so we need to do URL encoding on them.
878        // Otherwise, Opts::from_url may report a `Parse error`
879        let user = form_urlencoded::byte_serialize(user.as_bytes()).collect::<String>();
880        let password = form_urlencoded::byte_serialize(password.as_bytes()).collect::<String>();
881
882        let conn_uri = format!(
883            "mysql://{}:{}@{}:{}/{}?prefer_socket={}&max_allowed_packet={}&wait_timeout={}",
884            user,
885            password,
886            host,
887            port,
888            db,
889            STARROCK_MYSQL_PREFER_SOCKET,
890            STARROCK_MYSQL_MAX_ALLOWED_PACKET,
891            STARROCK_MYSQL_WAIT_TIMEOUT
892        );
893        let pool = mysql_async::Pool::new(
894            Opts::from_url(&conn_uri)
895                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?,
896        );
897        let conn = pool
898            .get_conn()
899            .await
900            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
901
902        Ok(Self { table, db, conn })
903    }
904
905    pub async fn get_columns_from_starrocks(&mut self) -> Result<HashMap<String, String>> {
906        let query = format!(
907            "select column_name, column_type from information_schema.columns where table_name = {:?} and table_schema = {:?};",
908            self.table, self.db
909        );
910        let mut query_map: HashMap<String, String> = HashMap::default();
911        self.conn
912            .query_map(query, |(column_name, column_type)| {
913                query_map.insert(column_name, column_type)
914            })
915            .await
916            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
917        Ok(query_map)
918    }
919
920    pub async fn get_pk_from_starrocks(&mut self) -> Result<(String, String)> {
921        let query = format!(
922            "select table_model, primary_key, sort_key from information_schema.tables_config where table_name = {:?} and table_schema = {:?};",
923            self.table, self.db
924        );
925        let table_mode_pk: (String, String) = self
926            .conn
927            .query_map(
928                query,
929                |(table_model, primary_key, sort_key): (String, String, String)| match table_model
930                    .as_str()
931                {
932                    // Get primary key of aggregate table from the sort_key field
933                    // https://docs.starrocks.io/docs/table_design/table_types/table_capabilities/
934                    // https://docs.starrocks.io/docs/sql-reference/information_schema/tables_config/
935                    "AGG_KEYS" => (table_model, sort_key),
936                    _ => (table_model, primary_key),
937                },
938            )
939            .await
940            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?
941            .first()
942            .ok_or_else(|| {
943                SinkError::Starrocks(format!(
944                    "Can't find schema for StarRocks table {:?} in database {:?}. Please check that the table exists and the StarRocks user has write permission on the target table.",
945                    self.table, self.db
946                ))
947            })?
948            .clone();
949        Ok(table_mode_pk)
950    }
951}
952
953#[derive(Debug, Serialize, Deserialize)]
954pub struct StarrocksInsertResultResponse {
955    #[serde(rename = "TxnId")]
956    pub txn_id: Option<i64>,
957    #[serde(rename = "Seq")]
958    pub seq: Option<i64>,
959    #[serde(rename = "Label")]
960    pub label: Option<String>,
961    #[serde(rename = "Status")]
962    pub status: String,
963    #[serde(rename = "Message")]
964    pub message: String,
965    #[serde(rename = "NumberTotalRows")]
966    pub number_total_rows: Option<i64>,
967    #[serde(rename = "NumberLoadedRows")]
968    pub number_loaded_rows: Option<i64>,
969    #[serde(rename = "NumberFilteredRows")]
970    pub number_filtered_rows: Option<i32>,
971    #[serde(rename = "NumberUnselectedRows")]
972    pub number_unselected_rows: Option<i32>,
973    #[serde(rename = "LoadBytes")]
974    pub load_bytes: Option<i64>,
975    #[serde(rename = "LoadTimeMs")]
976    pub load_time_ms: Option<i32>,
977    #[serde(rename = "BeginTxnTimeMs")]
978    pub begin_txn_time_ms: Option<i32>,
979    #[serde(rename = "ReadDataTimeMs")]
980    pub read_data_time_ms: Option<i32>,
981    #[serde(rename = "WriteDataTimeMs")]
982    pub write_data_time_ms: Option<i32>,
983    #[serde(rename = "CommitAndPublishTimeMs")]
984    pub commit_and_publish_time_ms: Option<i32>,
985    #[serde(rename = "StreamLoadPlanTimeMs")]
986    pub stream_load_plan_time_ms: Option<i32>,
987    #[serde(rename = "ExistingJobStatus")]
988    pub existing_job_status: Option<String>,
989    #[serde(rename = "ErrorURL")]
990    pub error_url: Option<String>,
991}
992
993pub struct StarrocksClient {
994    insert: InserterInner,
995}
996impl StarrocksClient {
997    pub fn new(insert: InserterInner) -> Self {
998        Self { insert }
999    }
1000
1001    pub async fn write(&mut self, data: Bytes) -> Result<()> {
1002        self.insert.write(data).await?;
1003        Ok(())
1004    }
1005
1006    pub async fn finish(self) -> Result<StarrocksInsertResultResponse> {
1007        let raw = self.insert.finish().await?;
1008        let res: StarrocksInsertResultResponse = serde_json::from_slice(&raw)
1009            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
1010
1011        if !STARROCKS_SUCCESS_STATUS.contains(&res.status.as_str()) {
1012            return Err(SinkError::DorisStarrocksConnect(anyhow::anyhow!(
1013                "Insert error: {}, {}, {:?}",
1014                res.status,
1015                res.message,
1016                res.error_url,
1017            )));
1018        };
1019        Ok(res)
1020    }
1021}
1022
1023pub struct StarrocksTxnClient {
1024    request_builder: StarrocksTxnRequestBuilder,
1025}
1026
1027impl StarrocksTxnClient {
1028    pub fn new(request_builder: StarrocksTxnRequestBuilder) -> Self {
1029        Self { request_builder }
1030    }
1031
1032    fn check_response_and_extract_label(&self, res: Bytes) -> Result<String> {
1033        let res: StarrocksInsertResultResponse = serde_json::from_slice(&res)
1034            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
1035        if !STARROCKS_SUCCESS_STATUS.contains(&res.status.as_str()) {
1036            return Err(SinkError::DorisStarrocksConnect(anyhow::anyhow!(
1037                "transaction error: {}, {}, {:?}",
1038                res.status,
1039                res.message,
1040                res.error_url,
1041            )));
1042        }
1043        res.label.ok_or_else(|| {
1044            SinkError::DorisStarrocksConnect(anyhow::anyhow!("Can't get label from response"))
1045        })
1046    }
1047
1048    pub async fn begin(&self, label: String) -> Result<String> {
1049        let res = self
1050            .request_builder
1051            .build_begin_request_sender(label)?
1052            .send()
1053            .await?;
1054        self.check_response_and_extract_label(res)
1055    }
1056
1057    pub async fn prepare(&self, label: String) -> Result<String> {
1058        let res = self
1059            .request_builder
1060            .build_prepare_request_sender(label)?
1061            .send()
1062            .await?;
1063        self.check_response_and_extract_label(res)
1064    }
1065
1066    pub async fn commit(&self, label: String) -> Result<String> {
1067        let res = self
1068            .request_builder
1069            .build_commit_request_sender(label)?
1070            .send()
1071            .await?;
1072        self.check_response_and_extract_label(res)
1073    }
1074
1075    pub async fn rollback(&self, label: String) -> Result<String> {
1076        let res = self
1077            .request_builder
1078            .build_rollback_request_sender(label)?
1079            .send()
1080            .await?;
1081        self.check_response_and_extract_label(res)
1082    }
1083
1084    pub async fn load(&self, label: String) -> Result<InserterInner> {
1085        self.request_builder.build_txn_inserter(label).await
1086    }
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use risingwave_common::types::DataType;
1092
1093    use super::*;
1094
1095    fn is_compatible(rw_data_type: DataType, starrocks_data_type: &str) -> bool {
1096        StarrocksSink::check_and_correct_column_type(&rw_data_type, starrocks_data_type).unwrap()
1097    }
1098
1099    #[test]
1100    fn test_timestamptz_compatible_starrocks_types() {
1101        for starrocks_data_type in [
1102            "datetime",
1103            "datetime(6)",
1104            "varchar(64)",
1105            "char(32)",
1106            "string",
1107        ] {
1108            assert!(
1109                is_compatible(DataType::Timestamptz, starrocks_data_type),
1110                "{starrocks_data_type} should be compatible with timestamptz"
1111            );
1112        }
1113    }
1114
1115    #[test]
1116    fn test_timestamptz_incompatible_starrocks_types() {
1117        for starrocks_data_type in ["date", "int", "bigint", "json", "boolean"] {
1118            assert!(
1119                !is_compatible(DataType::Timestamptz, starrocks_data_type),
1120                "{starrocks_data_type} should not be compatible with timestamptz"
1121            );
1122        }
1123    }
1124
1125    pub(super) fn base_properties() -> BTreeMap<String, String> {
1126        BTreeMap::from([
1127            ("starrocks.host".to_owned(), "127.0.0.1".to_owned()),
1128            ("starrocks.mysqlport".to_owned(), "9030".to_owned()),
1129            ("starrocks.httpport".to_owned(), "8030".to_owned()),
1130            ("starrocks.user".to_owned(), "root".to_owned()),
1131            ("starrocks.password".to_owned(), "".to_owned()),
1132            ("starrocks.database".to_owned(), "demo".to_owned()),
1133            ("starrocks.table".to_owned(), "sink_table".to_owned()),
1134            ("type".to_owned(), SINK_TYPE_APPEND_ONLY.to_owned()),
1135        ])
1136    }
1137
1138    #[test]
1139    fn starrocks_stream_load_options_defaults() {
1140        let config = StarrocksConfig::from_btreemap(base_properties()).unwrap();
1141        assert!(!config.ignore_json_size);
1142        assert_eq!(config.load_mem_limit, None);
1143        assert_eq!(config.transaction_timeout_seconds, None);
1144    }
1145
1146    #[test]
1147    fn starrocks_stream_load_options_parse() {
1148        let mut properties = base_properties();
1149        properties.extend([
1150            ("starrocks.ignore_json_size".to_owned(), "true".to_owned()),
1151            (
1152                "starrocks.load_mem_limit".to_owned(),
1153                "268435456".to_owned(),
1154            ),
1155            (
1156                "starrocks.transaction_timeout_seconds".to_owned(),
1157                "900".to_owned(),
1158            ),
1159            ("starrocks.max_batch_size_bytes".to_owned(), "5".to_owned()),
1160        ]);
1161        let config = StarrocksConfig::from_btreemap(properties).unwrap();
1162        assert!(config.ignore_json_size);
1163        assert_eq!(config.load_mem_limit, Some(268435456));
1164        assert_eq!(config.transaction_timeout_seconds, Some(900));
1165        assert_eq!(config.max_batch_size_bytes, Some(5));
1166    }
1167
1168    #[tokio::test]
1169    async fn starrocks_ignore_json_size_keeps_local_row_limit() {
1170        let mut properties = base_properties();
1171        properties.insert("starrocks.ignore_json_size".to_owned(), "true".to_owned());
1172        properties.insert("starrocks.max_batch_size_bytes".to_owned(), "5".to_owned());
1173        let config = StarrocksConfig::from_btreemap(properties).unwrap();
1174        let mut writer =
1175            StarrocksSinkWriter::new(config, Schema::new(vec![]), vec![], true, chrono_tz::UTC)
1176                .unwrap();
1177        // Reject before starting a transaction or sending a request to StarRocks.
1178        let error = writer
1179            .write_row_json("123456".to_owned())
1180            .await
1181            .unwrap_err();
1182        assert!(
1183            error
1184                .to_string()
1185                .contains("single row payload size 6 bytes")
1186        );
1187    }
1188
1189    #[test]
1190    fn starrocks_stream_load_options_reject_invalid_values() {
1191        for (name, values) in [
1192            ("starrocks.ignore_json_size", vec!["yes", "1", ""]),
1193            (
1194                "starrocks.load_mem_limit",
1195                vec![
1196                    "-1",
1197                    "9223372036854775808",
1198                    "18446744073709551616",
1199                    "invalid",
1200                ],
1201            ),
1202            (
1203                "starrocks.transaction_timeout_seconds",
1204                vec!["0", "-1", "2147483648", "4294967296", "invalid"],
1205            ),
1206        ] {
1207            for value in values {
1208                let mut properties = base_properties();
1209                properties.insert(name.to_owned(), value.to_owned());
1210                assert!(
1211                    StarrocksConfig::from_btreemap(properties).is_err(),
1212                    "{name}={value} should be rejected"
1213                );
1214            }
1215        }
1216    }
1217
1218    #[test]
1219    fn starrocks_stream_load_options_accept_boundaries() {
1220        // The FE timeout range is configurable; do not hard-code its default 3-day maximum.
1221        for timeout in [1, 259201, i32::MAX as u32] {
1222            let mut properties = base_properties();
1223            properties.insert("starrocks.ignore_json_size".to_owned(), "false".to_owned());
1224            properties.insert(
1225                "starrocks.transaction_timeout_seconds".to_owned(),
1226                timeout.to_string(),
1227            );
1228            for limit in [0, i64::MAX as u64] {
1229                properties.insert("starrocks.load_mem_limit".to_owned(), limit.to_string());
1230                let config = StarrocksConfig::from_btreemap(properties.clone()).unwrap();
1231                assert!(!config.ignore_json_size);
1232                assert_eq!(config.load_mem_limit, Some(limit));
1233                assert_eq!(config.transaction_timeout_seconds, Some(timeout));
1234            }
1235        }
1236    }
1237
1238    #[test]
1239    fn starrocks_max_batch_size_bytes_defaults_to_none() {
1240        let config = StarrocksConfig::from_btreemap(base_properties()).unwrap();
1241
1242        assert_eq!(config.max_batch_size_bytes, None);
1243        assert_eq!(config.max_transaction_size_bytes, None);
1244    }
1245
1246    #[test]
1247    fn starrocks_max_batch_size_bytes_parses() {
1248        let mut properties = base_properties();
1249        properties.insert("starrocks.max_batch_size_bytes".to_owned(), "2".to_owned());
1250
1251        let config = StarrocksConfig::from_btreemap(properties).unwrap();
1252
1253        assert_eq!(config.max_batch_size_bytes, Some(2));
1254    }
1255
1256    #[test]
1257    fn starrocks_max_batch_size_bytes_rejects_zero() {
1258        let mut properties = base_properties();
1259        properties.insert("starrocks.max_batch_size_bytes".to_owned(), "0".to_owned());
1260
1261        let err = StarrocksConfig::from_btreemap(properties).unwrap_err();
1262
1263        assert!(
1264            err.to_string()
1265                .contains("`starrocks.max_batch_size_bytes` must be greater than 0")
1266        );
1267    }
1268
1269    #[test]
1270    fn starrocks_batch_size_allows_exact_limit() {
1271        assert_eq!(
1272            decide_payload_size(3, 2, 5, "starrocks.max_batch_size_bytes").unwrap(),
1273            PayloadSizeDecision {
1274                finish_current_payload: false,
1275                next_payload_size_bytes: 5,
1276            }
1277        );
1278    }
1279
1280    #[test]
1281    fn starrocks_batch_size_rolls_over_before_exceeding_limit() {
1282        assert_eq!(
1283            decide_payload_size(4, 2, 5, "starrocks.max_batch_size_bytes").unwrap(),
1284            PayloadSizeDecision {
1285                finish_current_payload: true,
1286                next_payload_size_bytes: 2,
1287            }
1288        );
1289    }
1290
1291    #[test]
1292    fn starrocks_batch_size_rejects_single_oversized_row() {
1293        let err = decide_payload_size(0, 6, 5, "starrocks.max_batch_size_bytes").unwrap_err();
1294
1295        assert!(err.to_string().contains(
1296            "single row payload size 6 bytes exceeds `starrocks.max_batch_size_bytes` limit 5 bytes"
1297        ));
1298    }
1299
1300    #[test]
1301    fn starrocks_batch_size_rolls_over_on_u64_overflow() {
1302        assert_eq!(
1303            decide_payload_size(u64::MAX, 1, u64::MAX, "starrocks.max_batch_size_bytes").unwrap(),
1304            PayloadSizeDecision {
1305                finish_current_payload: true,
1306                next_payload_size_bytes: 1,
1307            }
1308        );
1309    }
1310}
1311
1312#[cfg(all(test, not(madsim)))]
1313mod transaction_tests;