Skip to main content

risingwave_connector/sink/
doris_starrocks_connector.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 core::mem;
16use core::time::Duration;
17use std::collections::HashMap;
18use std::convert::Infallible;
19
20use anyhow::{Context, anyhow};
21use base64::Engine;
22use base64::engine::general_purpose;
23use bytes::{BufMut, Bytes, BytesMut};
24use futures::StreamExt;
25use reqwest::header::{HeaderName, HeaderValue};
26use reqwest::{Body, Client, Method, Request, RequestBuilder, Response, StatusCode, redirect};
27use tokio::sync::mpsc::UnboundedSender;
28use tokio::task::JoinHandle;
29use url::Url;
30
31use super::{Result, SinkError};
32
33const BUFFER_SIZE: usize = 64 * 1024;
34const MIN_CHUNK_SIZE: usize = BUFFER_SIZE - 1024;
35pub(crate) const DORIS_SUCCESS_STATUS: [&str; 2] = ["Success", "Publish Timeout"];
36pub(crate) const STARROCKS_SUCCESS_STATUS: [&str; 1] = ["OK"];
37pub(crate) const DORIS_DELETE_SIGN: &str = "__DORIS_DELETE_SIGN__";
38pub(crate) const STARROCKS_DELETE_SIGN: &str = "__op";
39
40pub(crate) const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(30);
41const LOCALHOST: &str = "localhost";
42const LOCALHOST_IP: &str = "127.0.0.1";
43pub struct HeaderBuilder {
44    header: HashMap<String, String>,
45}
46impl Default for HeaderBuilder {
47    fn default() -> Self {
48        Self::new()
49    }
50}
51impl HeaderBuilder {
52    pub fn new() -> Self {
53        Self {
54            header: HashMap::default(),
55        }
56    }
57
58    pub fn add_common_header(mut self) -> Self {
59        self.header
60            .insert("expect".to_owned(), "100-continue".to_owned());
61        self
62    }
63
64    /// The method is temporarily not in use, reserved for later use in 2PC.
65    /// Doris will generate a default, non-repeating label.
66    pub fn set_label(mut self, label: String) -> Self {
67        self.header.insert("label".to_owned(), label);
68        self
69    }
70
71    pub fn set_columns_name(mut self, columns_name: Vec<&str>) -> Self {
72        let columns_name_str = columns_name.join(",");
73        self.header.insert("columns".to_owned(), columns_name_str);
74        self
75    }
76
77    /// This method is only called during upsert operations.
78    pub fn add_hidden_column(mut self) -> Self {
79        self.header
80            .insert("hidden_columns".to_owned(), DORIS_DELETE_SIGN.to_owned());
81        self
82    }
83
84    /// The method is temporarily not in use, reserved for later use in 2PC.
85    /// Only use in Doris
86    pub fn enable_2_pc(mut self) -> Self {
87        self.header
88            .insert("two_phase_commit".to_owned(), "true".to_owned());
89        self
90    }
91
92    pub fn set_user_password(mut self, user: String, password: String) -> Self {
93        let auth = format!(
94            "Basic {}",
95            general_purpose::STANDARD.encode(format!("{}:{}", user, password))
96        );
97        self.header.insert("Authorization".to_owned(), auth);
98        self
99    }
100
101    /// The method is temporarily not in use, reserved for later use in 2PC.
102    /// Only use in Doris
103    pub fn set_txn_id(mut self, txn_id: i64) -> Self {
104        self.header
105            .insert("txn_operation".to_owned(), txn_id.to_string());
106        self
107    }
108
109    /// The method is temporarily not in use, reserved for later use in 2PC.
110    /// Only use in Doris
111    pub fn add_commit(mut self) -> Self {
112        self.header
113            .insert("txn_operation".to_owned(), "commit".to_owned());
114        self
115    }
116
117    /// The method is temporarily not in use, reserved for later use in 2PC.
118    /// Only use in Doris
119    pub fn add_abort(mut self) -> Self {
120        self.header
121            .insert("txn_operation".to_owned(), "abort".to_owned());
122        self
123    }
124
125    pub fn add_json_format(mut self) -> Self {
126        self.header.insert("format".to_owned(), "json".to_owned());
127        self
128    }
129
130    /// Only use in Doris
131    pub fn add_read_json_by_line(mut self) -> Self {
132        self.header
133            .insert("read_json_by_line".to_owned(), "true".to_owned());
134        self
135    }
136
137    /// Only use in Starrocks
138    pub fn add_strip_outer_array(mut self) -> Self {
139        self.header
140            .insert("strip_outer_array".to_owned(), "true".to_owned());
141        self
142    }
143
144    /// Only use in Starrocks
145    pub fn set_partial_update(mut self, partial_update: Option<String>) -> Self {
146        self.header.insert(
147            "partial_update".to_owned(),
148            partial_update.unwrap_or_else(|| "false".to_owned()),
149        );
150        self
151    }
152
153    /// Only use in Doris
154    pub fn set_partial_columns(mut self, partial_columns: Option<String>) -> Self {
155        self.header.insert(
156            "partial_columns".to_owned(),
157            partial_columns.unwrap_or_else(|| "false".to_owned()),
158        );
159        self
160    }
161
162    /// Only used in Starrocks Transaction API
163    pub fn set_db(mut self, db: String) -> Self {
164        self.header.insert("db".to_owned(), db);
165        self
166    }
167
168    /// Only used in Starrocks Transaction API
169    pub fn set_table(mut self, table: String) -> Self {
170        self.header.insert("table".to_owned(), table);
171        self
172    }
173
174    pub fn build(self) -> HashMap<String, String> {
175        self.header
176    }
177}
178
179/// Try getting BE url from a redirected response, returning `Ok(None)` indicates this request does
180/// not redirect.
181///
182/// The reason we handle the redirection manually is that if we let `reqwest` handle the redirection
183/// automatically, it will remove sensitive headers (such as Authorization) during the redirection,
184/// and there's no way to prevent this behavior.
185fn try_get_be_url(resp: &Response, fe_host: &str) -> Result<Option<Url>> {
186    match resp.status() {
187        StatusCode::TEMPORARY_REDIRECT => {
188            let be_url = resp
189                .headers()
190                .get("location")
191                .ok_or_else(|| {
192                    SinkError::DorisStarrocksConnect(anyhow!("Can't get doris BE url in header",))
193                })?
194                .to_str()
195                .context("Can't get doris BE url in header")
196                .map_err(SinkError::DorisStarrocksConnect)?
197                .to_owned();
198
199            let mut parsed_be_url = Url::parse(&be_url)
200                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
201
202            if fe_host != LOCALHOST && fe_host != LOCALHOST_IP {
203                let be_host = parsed_be_url.host_str().ok_or_else(|| {
204                    SinkError::DorisStarrocksConnect(anyhow!("Can't get be host from url"))
205                })?;
206
207                if be_host == LOCALHOST || be_host == LOCALHOST_IP {
208                    // if be host is 127.0.0.1, we may can't connect to it directly,
209                    // so replace it with fe host
210                    parsed_be_url
211                        .set_host(Some(fe_host))
212                        .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
213                }
214            }
215            Ok(Some(parsed_be_url))
216        }
217        StatusCode::OK => {
218            // Some of the `StarRocks` transactional APIs will respond directly from FE. For example,
219            // the request to `/api/transaction/commit` endpoint does not seem to redirect to BE.
220            // In this case, the request should be treated as finished.
221            Ok(None)
222        }
223        _ => Err(SinkError::DorisStarrocksConnect(anyhow!(
224            "Can't get doris BE url",
225        ))),
226    }
227}
228
229pub struct InserterInnerBuilder {
230    url: String,
231    header: HashMap<String, String>,
232    #[expect(dead_code)]
233    sender: Option<Sender>,
234    fe_host: String,
235    stream_load_http_timeout: Duration,
236}
237impl InserterInnerBuilder {
238    pub fn new(
239        url: String,
240        db: String,
241        table: String,
242        header: HashMap<String, String>,
243        stream_load_http_timeout_ms: u64,
244    ) -> Result<Self> {
245        let fe_host = Url::parse(&url)
246            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?
247            .host_str()
248            .ok_or_else(|| SinkError::DorisStarrocksConnect(anyhow!("Can't get fe host from url")))?
249            .to_owned();
250        let url = format!("{}/api/{}/{}/_stream_load", url, db, table);
251        let stream_load_http_timeout = Duration::from_millis(stream_load_http_timeout_ms);
252
253        Ok(Self {
254            url,
255            sender: None,
256            header,
257            fe_host,
258            stream_load_http_timeout,
259        })
260    }
261
262    fn build_request(&self, uri: String) -> Result<RequestBuilder> {
263        let client = Client::builder()
264            .pool_idle_timeout(POOL_IDLE_TIMEOUT)
265            .redirect(redirect::Policy::none()) // we handle redirect by ourselves
266            .build()
267            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
268
269        let mut builder = client.put(uri);
270        for (k, v) in &self.header {
271            builder = builder.header(k, v);
272        }
273        Ok(builder)
274    }
275
276    pub async fn build(&self) -> Result<InserterInner> {
277        let builder = self.build_request(self.url.clone())?;
278        let resp = builder
279            .send()
280            .await
281            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
282
283        let be_url = try_get_be_url(&resp, self.fe_host.as_str())?
284            .ok_or_else(|| SinkError::DorisStarrocksConnect(anyhow!("Can't get doris BE url",)))?;
285
286        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
287        let body = Body::wrap_stream(
288            tokio_stream::wrappers::UnboundedReceiverStream::new(receiver).map(Ok::<_, Infallible>),
289        );
290        let builder = self.build_request(be_url.into())?.body(body);
291
292        let handle: JoinHandle<Result<Vec<u8>>> = tokio::spawn(async move {
293            let response = builder
294                .send()
295                .await
296                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
297            let status = response.status();
298            let raw = response
299                .bytes()
300                .await
301                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?
302                .into();
303
304            if status == StatusCode::OK {
305                Ok(raw)
306            } else {
307                let response_body = String::from_utf8(raw).map_err(|err| {
308                    SinkError::DorisStarrocksConnect(
309                        anyhow!(err).context("failed to parse response body"),
310                    )
311                })?;
312                Err(SinkError::DorisStarrocksConnect(anyhow!(
313                    "Failed connection {:?},{:?}",
314                    status,
315                    response_body
316                )))
317            }
318        });
319        Ok(InserterInner::new(
320            sender,
321            handle,
322            self.stream_load_http_timeout,
323        ))
324    }
325}
326
327type Sender = UnboundedSender<Bytes>;
328
329pub struct InserterInner {
330    sender: Option<Sender>,
331    join_handle: JoinHandle<Result<Vec<u8>>>,
332    buffer: BytesMut,
333    stream_load_http_timeout: Duration,
334}
335impl InserterInner {
336    pub fn new(
337        sender: Sender,
338        join_handle: JoinHandle<Result<Vec<u8>>>,
339        stream_load_http_timeout: Duration,
340    ) -> Self {
341        Self {
342            sender: Some(sender),
343            join_handle,
344            buffer: BytesMut::with_capacity(BUFFER_SIZE),
345            stream_load_http_timeout,
346        }
347    }
348
349    async fn send_chunk(&mut self) -> Result<()> {
350        if self.sender.is_none() {
351            return Ok(());
352        }
353
354        let chunk = mem::replace(&mut self.buffer, BytesMut::with_capacity(BUFFER_SIZE));
355
356        match self.sender.as_mut().unwrap().send(chunk.freeze()) {
357            Err(_e) => {
358                self.sender.take();
359                self.wait_handle().await?;
360
361                Err(SinkError::DorisStarrocksConnect(anyhow!("channel closed")))
362            }
363            _ => Ok(()),
364        }
365    }
366
367    pub async fn write(&mut self, data: Bytes) -> Result<()> {
368        self.buffer.put_slice(&data);
369        if self.buffer.len() >= MIN_CHUNK_SIZE {
370            self.send_chunk().await?;
371        }
372        Ok(())
373    }
374
375    #[cfg(all(test, feature = "sink-starrocks", not(madsim)))]
376    pub(crate) async fn wait_for_upload_receiver_closed(&self) {
377        // Synchronize tests without consuming the HTTP task's original result.
378        self.sender.as_ref().unwrap().closed().await;
379    }
380
381    async fn wait_handle(&mut self) -> Result<Vec<u8>> {
382        let res = match tokio::time::timeout(self.stream_load_http_timeout, &mut self.join_handle)
383            .await
384        {
385            Ok(res) => res.map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))??,
386            Err(err) => return Err(SinkError::DorisStarrocksConnect(anyhow!(err))),
387        };
388        Ok(res)
389    }
390
391    pub async fn finish(mut self) -> Result<Vec<u8>> {
392        if !self.buffer.is_empty() {
393            self.send_chunk().await?;
394        }
395        self.sender = None;
396        self.wait_handle().await
397    }
398}
399
400enum StreamLoadResponse {
401    BeRequest(Request),
402    HttpResponse(Response),
403}
404
405/// Send the request and handle redirection if any.
406/// The reason we handle the redirection manually is that if we let `reqwest` handle the redirection
407/// automatically, it will remove sensitive headers (such as Authorization) during the redirection,
408/// and there's no way to prevent this behavior.
409/// Please note, the FE address that user specified might be a FE follower not the leader, in this case,
410/// the follower FE will redirect request to leader FE and then to BE.
411async fn send_stream_load_request(
412    client: Client,
413    mut request: Request,
414    fe_host: &str,
415) -> Result<StreamLoadResponse> {
416    // possible redirection paths:
417    // RW <-> follower FE -> leader FE -> BE
418    // RW <-> leader FE -> BE
419    // RW <-> leader FE
420    for _ in 0..2 {
421        let original_http_port = request.url().port();
422        let mut request_for_redirection = request
423            .try_clone()
424            .ok_or_else(|| SinkError::DorisStarrocksConnect(anyhow!("Can't clone request")))?;
425        let resp = client.execute(request).await.map_err(|err| {
426            SinkError::DorisStarrocksConnect(
427                anyhow!(err).context("sending stream load request failed"),
428            )
429        })?;
430        let be_url = try_get_be_url(&resp, fe_host)?;
431        match be_url {
432            Some(be_url) => {
433                // we used an unconventional method to detect if we are currently redirecting to FE leader, i.e.,
434                // by comparing the port of the redirected url with that of the original request, if they are same, we consider
435                // this is a FE address. Because in practice, no one would deploy their `StarRocks` cluster with the same
436                // http port for both FE and BE. However, this is a potentially problematic assumption,
437                // we may investigate a better way to do this. For example, we could use the `show backends` command to check
438                // if the host of the redirected url is in the list. However, `show backends` requires
439                // the system-level privilege, which could break the backward compatibility.
440                let redirected_port = be_url.port();
441                *request_for_redirection.url_mut() = be_url;
442                if redirected_port == original_http_port {
443                    // redirected to FE, continue another round.
444                    request = request_for_redirection;
445                } else {
446                    // we got BE address here
447                    return Ok(StreamLoadResponse::BeRequest(request_for_redirection));
448                }
449            }
450            None => return Ok(StreamLoadResponse::HttpResponse(resp)),
451        }
452    }
453    Err(SinkError::DorisStarrocksConnect(anyhow!(
454        "redirection occur more than twice when sending stream load request"
455    )))
456}
457
458pub struct MetaRequestSender {
459    client: Client,
460    request: Request,
461    fe_host: String,
462}
463
464impl MetaRequestSender {
465    pub fn new(client: Client, request: Request, fe_host: String) -> Self {
466        Self {
467            client,
468            request,
469            fe_host,
470        }
471    }
472
473    pub async fn send(self) -> Result<Bytes> {
474        match send_stream_load_request(self.client.clone(), self.request, &self.fe_host).await? {
475            StreamLoadResponse::BeRequest(be_request) => self
476                .client
477                .execute(be_request)
478                .await
479                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?
480                .bytes()
481                .await
482                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err))),
483            StreamLoadResponse::HttpResponse(resp) => resp
484                .bytes()
485                .await
486                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err))),
487        }
488    }
489}
490
491pub struct StarrocksTxnRequestBuilder {
492    url_begin: String,
493    url_load: String,
494    url_prepare: String,
495    url_commit: String,
496    url_rollback: String,
497    header: HashMap<String, String>,
498    fe_host: String,
499    stream_load_http_timeout: Duration,
500    ignore_json_size: bool,
501    load_mem_limit: Option<u64>,
502    transaction_timeout_seconds: Option<u32>,
503    // The `reqwest` crate suggests us reuse the Client, and we don't need make it Arc, because it
504    // already uses an Arc internally.
505    client: Client,
506}
507
508impl StarrocksTxnRequestBuilder {
509    pub fn new(
510        url: String,
511        header: HashMap<String, String>,
512        stream_load_http_timeout_ms: u64,
513    ) -> Result<Self> {
514        let fe_host = Url::parse(&url)
515            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?
516            .host_str()
517            .ok_or_else(|| SinkError::DorisStarrocksConnect(anyhow!("Can't get fe host from url")))?
518            .to_owned();
519
520        let url_begin = format!("{}/api/transaction/begin", url);
521        let url_load = format!("{}/api/transaction/load", url);
522        let url_prepare = format!("{}/api/transaction/prepare", url);
523        let url_commit = format!("{}/api/transaction/commit", url);
524        let url_rollback = format!("{}/api/transaction/rollback", url);
525
526        let stream_load_http_timeout = Duration::from_millis(stream_load_http_timeout_ms);
527
528        let client = Client::builder()
529            .pool_idle_timeout(POOL_IDLE_TIMEOUT)
530            .redirect(redirect::Policy::none())
531            .build()
532            .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
533
534        Ok(Self {
535            url_begin,
536            url_load,
537            url_prepare,
538            url_commit,
539            url_rollback,
540            header,
541            fe_host,
542            stream_load_http_timeout,
543            ignore_json_size: false,
544            load_mem_limit: None,
545            transaction_timeout_seconds: None,
546            client,
547        })
548    }
549
550    pub fn with_load_options(
551        mut self,
552        ignore_json_size: bool,
553        load_mem_limit: Option<u64>,
554    ) -> Self {
555        self.ignore_json_size = ignore_json_size;
556        self.load_mem_limit = load_mem_limit;
557        self
558    }
559
560    pub fn with_transaction_timeout_seconds(mut self, timeout: Option<u32>) -> Self {
561        self.transaction_timeout_seconds = timeout;
562        self
563    }
564
565    fn build_request(&self, uri: String, method: Method, label: String) -> Result<Request> {
566        let parsed_url =
567            Url::parse(&uri).map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
568        let mut request = Request::new(method, parsed_url);
569
570        // Preserve the existing URL-based timeout policy, including rebuilt BE load requests.
571        if uri != self.url_load {
572            *request.timeout_mut() = Some(self.stream_load_http_timeout);
573        }
574
575        let header = request.headers_mut();
576        for (k, v) in &self.header {
577            header.insert(
578                HeaderName::try_from(k)
579                    .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?,
580                HeaderValue::try_from(v)
581                    .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?,
582            );
583        }
584        header.insert(
585            "label",
586            HeaderValue::try_from(label)
587                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?,
588        );
589
590        Ok(request)
591    }
592
593    pub fn build_begin_request_sender(&self, label: String) -> Result<MetaRequestSender> {
594        let mut request = self.build_request(self.url_begin.clone(), Method::POST, label)?;
595        if let Some(timeout) = self.transaction_timeout_seconds {
596            request
597                .headers_mut()
598                .insert("timeout", HeaderValue::from(timeout));
599        }
600        Ok(MetaRequestSender::new(
601            self.client.clone(),
602            request,
603            self.fe_host.clone(),
604        ))
605    }
606
607    pub fn build_prepare_request_sender(&self, label: String) -> Result<MetaRequestSender> {
608        let request = self.build_request(self.url_prepare.clone(), Method::POST, label)?;
609        Ok(MetaRequestSender::new(
610            self.client.clone(),
611            request,
612            self.fe_host.clone(),
613        ))
614    }
615
616    pub fn build_commit_request_sender(&self, label: String) -> Result<MetaRequestSender> {
617        let request = self.build_request(self.url_commit.clone(), Method::POST, label)?;
618        Ok(MetaRequestSender::new(
619            self.client.clone(),
620            request,
621            self.fe_host.clone(),
622        ))
623    }
624
625    pub fn build_rollback_request_sender(&self, label: String) -> Result<MetaRequestSender> {
626        let request = self.build_request(self.url_rollback.clone(), Method::POST, label)?;
627        Ok(MetaRequestSender::new(
628            self.client.clone(),
629            request,
630            self.fe_host.clone(),
631        ))
632    }
633
634    pub async fn build_txn_inserter(&self, label: String) -> Result<InserterInner> {
635        let request = self.build_load_request(self.url_load.clone(), label.clone())?;
636        let mut be_request =
637            match send_stream_load_request(self.client.clone(), request, &self.fe_host).await? {
638                StreamLoadResponse::BeRequest(be_request) => be_request,
639                StreamLoadResponse::HttpResponse(resp) => {
640                    // If we get a response here, it should be from BE, so we extract the URL
641                    // and create a new request based on it.
642                    let url = resp.url().clone();
643                    self.build_load_request(url.into(), label)?
644                }
645            };
646        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
647        let body = Body::wrap_stream(
648            tokio_stream::wrappers::UnboundedReceiverStream::new(receiver).map(Ok::<_, Infallible>),
649        );
650        *be_request.body_mut() = Some(body);
651
652        let client = self.client.clone();
653        let handle: JoinHandle<Result<Vec<u8>>> = tokio::spawn(async move {
654            let response = client
655                .execute(be_request)
656                .await
657                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?;
658
659            let status = response.status();
660            let raw = response
661                .bytes()
662                .await
663                .map_err(|err| SinkError::DorisStarrocksConnect(anyhow!(err)))?
664                .into();
665
666            if status == StatusCode::OK {
667                Ok(raw)
668            } else {
669                let response_body = String::from_utf8(raw).map_err(|err| {
670                    SinkError::DorisStarrocksConnect(
671                        anyhow!(err).context("failed to parse response body"),
672                    )
673                })?;
674                Err(SinkError::DorisStarrocksConnect(anyhow!(
675                    "Failed connection {:?},{:?}",
676                    status,
677                    response_body
678                )))
679            }
680        });
681        Ok(InserterInner::new(
682            sender,
683            handle,
684            self.stream_load_http_timeout,
685        ))
686    }
687
688    fn build_load_request(&self, uri: String, label: String) -> Result<Request> {
689        let mut request = self.build_request(uri, Method::PUT, label)?;
690        let headers = request.headers_mut();
691        if self.ignore_json_size {
692            headers.insert("ignore_json_size", HeaderValue::from_static("true"));
693        }
694        if let Some(limit) = self.load_mem_limit {
695            headers.insert("load_mem_limit", HeaderValue::from(limit));
696        }
697        Ok(request)
698    }
699}
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704
705    fn starrocks_request_builder() -> StarrocksTxnRequestBuilder {
706        let headers = HeaderBuilder::new()
707            .add_common_header()
708            .set_user_password("user".to_owned(), "password".to_owned())
709            .add_json_format()
710            .set_db("db".to_owned())
711            .set_table("table".to_owned())
712            .build();
713        StarrocksTxnRequestBuilder::new("http://127.0.0.1:8030".to_owned(), headers, 1234).unwrap()
714    }
715
716    fn starrocks_requests(builder: &StarrocksTxnRequestBuilder) -> [Request; 5] {
717        let label = "test-transaction".to_owned();
718        [
719            builder
720                .build_begin_request_sender(label.clone())
721                .unwrap()
722                .request,
723            builder
724                .build_load_request(builder.url_load.clone(), label.clone())
725                .unwrap(),
726            builder
727                .build_prepare_request_sender(label.clone())
728                .unwrap()
729                .request,
730            builder
731                .build_commit_request_sender(label.clone())
732                .unwrap()
733                .request,
734            builder
735                .build_rollback_request_sender(label)
736                .unwrap()
737                .request,
738        ]
739    }
740
741    #[test]
742    fn starrocks_default_requests_preserve_server_defaults() {
743        for request in starrocks_requests(&starrocks_request_builder()) {
744            for name in ["ignore_json_size", "load_mem_limit", "timeout"] {
745                assert!(!request.headers().contains_key(name));
746            }
747            assert_eq!(request.headers()["label"], "test-transaction");
748            assert_eq!(request.headers()["db"], "db");
749            assert_eq!(request.headers()["table"], "table");
750            assert_eq!(
751                request.headers()["authorization"],
752                "Basic dXNlcjpwYXNzd29yZA=="
753            );
754            if request.method() == Method::PUT {
755                assert_eq!(request.timeout(), None);
756            } else {
757                assert_eq!(request.timeout(), Some(&Duration::from_millis(1234)));
758            }
759        }
760    }
761
762    #[test]
763    fn starrocks_options_are_scoped_to_begin_and_load() {
764        let builder = starrocks_request_builder()
765            .with_load_options(true, Some(268435456))
766            .with_transaction_timeout_seconds(Some(900));
767        for request in starrocks_requests(&builder) {
768            let headers = request.headers();
769            if request.url().path().ends_with("/begin") {
770                assert_eq!(headers["timeout"], "900");
771            } else {
772                assert!(!headers.contains_key("timeout"));
773            }
774            if request.url().path().ends_with("/load") {
775                assert_eq!(headers["ignore_json_size"], "true");
776                assert_eq!(headers["load_mem_limit"], "268435456");
777            } else {
778                assert!(!headers.contains_key("ignore_json_size"));
779                assert!(!headers.contains_key("load_mem_limit"));
780            }
781        }
782    }
783
784    #[test]
785    fn starrocks_backend_load_paths_preserve_options_and_timeouts() {
786        let builder = starrocks_request_builder()
787            .with_load_options(true, Some(i64::MAX as u64))
788            .with_transaction_timeout_seconds(Some(900));
789        let backend_url = Url::parse("http://127.0.0.1:8040/api/transaction/load").unwrap();
790        // Normal redirects clone the FE request and preserve its lack of a total deadline.
791        let mut redirected = builder
792            .build_load_request(builder.url_load.clone(), "txn".to_owned())
793            .unwrap()
794            .try_clone()
795            .unwrap();
796        *redirected.url_mut() = backend_url.clone();
797        assert_eq!(redirected.timeout(), None);
798
799        // The response fallback rebuilds the BE request and retains its original deadline.
800        let request = builder
801            .build_load_request(backend_url.into(), "txn".to_owned())
802            .unwrap();
803        assert_eq!(request.headers(), redirected.headers());
804        assert_eq!(request.headers()["ignore_json_size"], "true");
805        assert_eq!(request.headers()["load_mem_limit"], "9223372036854775807");
806        assert!(!request.headers().contains_key("timeout"));
807        assert_eq!(request.headers()["label"], "txn");
808        assert_eq!(request.timeout(), Some(&Duration::from_millis(1234)));
809    }
810
811    #[test]
812    fn starrocks_false_omits_size_override_and_zero_memory_is_forwarded() {
813        let builder = starrocks_request_builder().with_load_options(false, Some(0));
814        let request = builder
815            .build_load_request(builder.url_load.clone(), "txn".to_owned())
816            .unwrap();
817        assert!(!request.headers().contains_key("ignore_json_size"));
818        assert_eq!(request.headers()["load_mem_limit"], "0");
819    }
820}