Skip to main content

thinkingdata_core/consumer/
batch_consumer.rs

1// Copyright 2026 houseme
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
15//! The batch consumer: buffers events and uploads them to the receiver.
16//!
17//! Architecture (ported from the Go SDK, made async-native): `add` appends the
18//! serialized event onto an in-memory buffer; a single sender task owns the
19//! upload pipeline, which serializes concurrent flushes, retries transient
20//! failures three times, keeps undelivered batches in a bounded cache, and
21//! optionally auto-flushes on a timer.
22
23use std::collections::VecDeque;
24use std::io::Write;
25use std::sync::{Arc, Mutex, OnceLock};
26use std::time::Duration;
27
28use tokio::sync::{mpsc, oneshot};
29
30use crate::data::Data;
31use crate::error::{Result, TDError};
32use crate::log::{td_log_error, td_log_info};
33use crate::utils::parse_time;
34
35/// Event count threshold for triggering a flush.
36pub const DEFAULT_BATCH_SIZE: usize = 20;
37/// Hard upper bound for the batch size.
38pub const MAX_BATCH_SIZE: usize = 200;
39/// Request deadline in milliseconds.
40pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
41/// Auto flush spacing in seconds.
42pub const DEFAULT_INTERVAL_SECS: u64 = 30;
43/// Maximum number of cached (undelivered) batches.
44pub const DEFAULT_CACHE_CAPACITY: usize = 50;
45
46/// Configuration for [`BatchConsumer`], mirroring the Go SDK's
47/// `TDBatchConfig`.
48#[derive(Debug, Clone)]
49pub struct BatchConsumerConfig {
50    /// Receiver URL, e.g. `https://receiver.thinkingdata.io`. The path is
51    /// always rewritten to `/sync_server`.
52    pub server_url: String,
53    /// ThinkingData APP ID.
54    pub app_id: String,
55    /// Event count threshold for triggering a flush; `0` selects
56    /// [`DEFAULT_BATCH_SIZE`], values above [`MAX_BATCH_SIZE`] are clamped.
57    pub batch_size: usize,
58    /// Request deadline in milliseconds; `0` selects [`DEFAULT_TIMEOUT_MS`].
59    pub timeout_ms: u64,
60    /// Whether to gzip-compress request bodies (default: enabled).
61    pub compress: bool,
62    /// Whether a background task flushes on a fixed interval.
63    pub auto_flush: bool,
64    /// Auto flush spacing in seconds; `0` selects [`DEFAULT_INTERVAL_SECS`].
65    pub interval_secs: u64,
66    /// Maximum number of cached (undelivered) batches; `0` selects
67    /// [`DEFAULT_CACHE_CAPACITY`].
68    pub cache_capacity: usize,
69}
70
71impl Default for BatchConsumerConfig {
72    fn default() -> Self {
73        Self {
74            server_url: String::new(),
75            app_id: String::new(),
76            batch_size: DEFAULT_BATCH_SIZE,
77            timeout_ms: DEFAULT_TIMEOUT_MS,
78            compress: true,
79            auto_flush: false,
80            interval_secs: DEFAULT_INTERVAL_SECS,
81            cache_capacity: DEFAULT_CACHE_CAPACITY,
82        }
83    }
84}
85
86/// Buffered events waiting for delivery.
87#[derive(Default)]
88struct Queue {
89    /// Serialized events not yet assigned to a batch.
90    buffer: Vec<Vec<u8>>,
91    /// Complete batches that failed delivery and will be retried.
92    cache: VecDeque<Vec<Vec<u8>>>,
93    /// Set when the consumer is closed; stops admission.
94    closed: bool,
95}
96
97/// A request for the streaming sender task.
98enum Request {
99    Flush {
100        all: bool,
101        respond: oneshot::Sender<Result<()>>,
102    },
103    Close {
104        respond: oneshot::Sender<Result<()>>,
105    },
106}
107
108/// Shared state of the batch consumer.
109struct Inner {
110    server_url: String,
111    app_id: String,
112    compress: bool,
113    batch_size: usize,
114    cache_capacity: usize,
115    client: reqwest::Client,
116    queue: Mutex<Queue>,
117    req_tx: mpsc::UnboundedSender<Request>,
118    close_result: OnceLock<Result<()>>,
119}
120
121/// Buffer events and upload them in batches to the ThinkingData receiver over
122/// HTTPS.
123///
124/// This is the Rust counterpart of the Go SDK's `TDBatchConsumer`. When the
125/// buffer reaches `batch_size`, or when cached batches exist, the next add
126/// (or an explicit `flush`) triggers a delivery. Delivered batches are
127/// dropped; undelivered batches stay in a bounded cache and are retried by
128/// subsequent flushes.
129///
130/// ```no_run
131/// # fn main() -> Result<(), thinkingdata_core::TDError> {
132/// # #[cfg(feature = "blocking")]
133/// # {
134/// # use thinkingdata_core::consumer::{BatchConsumer, Consumer};
135/// # let consumer = BatchConsumer::new("https://receiver.thinkingdata.io", "your_app_id")?;
136/// # let data = thinkingdata_core::Data::new(thinkingdata_core::DataType::Track);
137/// # consumer.add(&data)?;
138/// # consumer.close()?;
139/// # }
140/// # Ok(())
141/// # }
142/// ```
143#[derive(Clone)]
144pub struct BatchConsumer {
145    inner: Arc<Inner>,
146}
147
148impl std::fmt::Debug for BatchConsumer {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        f.debug_struct("BatchConsumer")
151            .field("server_url", &self.inner.server_url)
152            .field("app_id", &self.inner.app_id)
153            .field("batch_size", &self.inner.batch_size)
154            .field("cache_capacity", &self.inner.cache_capacity)
155            .field("compress", &self.inner.compress)
156            .finish_non_exhaustive()
157    }
158}
159
160impl BatchConsumer {
161    /// Create a batch consumer with default settings (gzip compression
162    /// enabled, batch size 20).
163    pub fn new(server_url: &str, app_id: &str) -> Result<Self> {
164        Self::with_config(BatchConsumerConfig {
165            server_url: server_url.to_string(),
166            app_id: app_id.to_string(),
167            ..BatchConsumerConfig::default()
168        })
169    }
170
171    /// Create a batch consumer with an explicit batch size.
172    pub fn with_batch_size(server_url: &str, app_id: &str, batch_size: usize) -> Result<Self> {
173        Self::with_config(BatchConsumerConfig {
174            server_url: server_url.to_string(),
175            app_id: app_id.to_string(),
176            batch_size,
177            ..BatchConsumerConfig::default()
178        })
179    }
180
181    /// Create a batch consumer with explicit compression control.
182    pub fn with_compress(server_url: &str, app_id: &str, compress: bool) -> Result<Self> {
183        Self::with_config(BatchConsumerConfig {
184            server_url: server_url.to_string(),
185            app_id: app_id.to_string(),
186            compress,
187            ..BatchConsumerConfig::default()
188        })
189    }
190
191    /// Create a batch consumer from a full configuration.
192    pub fn with_config(config: BatchConsumerConfig) -> Result<Self> {
193        if config.server_url.is_empty() {
194            return Err(TDError::msg("ServerUrl not be empty"));
195        }
196        let mut server_url = url::Url::parse(&config.server_url)?;
197        server_url.set_path("/sync_server");
198
199        let batch_size = if config.batch_size > MAX_BATCH_SIZE {
200            MAX_BATCH_SIZE
201        } else if config.batch_size == 0 {
202            DEFAULT_BATCH_SIZE
203        } else {
204            config.batch_size
205        };
206        let cache_capacity = if config.cache_capacity == 0 {
207            DEFAULT_CACHE_CAPACITY
208        } else {
209            config.cache_capacity
210        };
211        let timeout_ms = if config.timeout_ms == 0 {
212            DEFAULT_TIMEOUT_MS
213        } else {
214            config.timeout_ms
215        };
216        let interval_secs = if config.interval_secs == 0 {
217            DEFAULT_INTERVAL_SECS
218        } else {
219            config.interval_secs
220        };
221
222        let client = reqwest::Client::builder()
223            .timeout(Duration::from_millis(timeout_ms))
224            .build()?;
225        let (req_tx, req_rx) = mpsc::unbounded_channel::<Request>();
226
227        let inner = Arc::new(Inner {
228            server_url: server_url.to_string(),
229            app_id: config.app_id.clone(),
230            compress: config.compress,
231            batch_size,
232            cache_capacity,
233            client,
234            queue: Mutex::new(Queue::default()),
235            req_tx,
236            close_result: OnceLock::new(),
237        });
238
239        // Spawn the streaming sender task that owns all uploads.
240        let task_inner = inner.clone();
241        let auto_flush = config.auto_flush;
242        let interval = Duration::from_secs(interval_secs);
243        crate::consumer::shared_runtime().spawn(async move {
244            sender_loop(task_inner, req_rx, auto_flush, interval).await;
245        });
246
247        td_log_info(&format!(
248            "Mode: batch consumer, appId: {}, serverUrl: {}",
249            config.app_id, inner.server_url
250        ));
251
252        Ok(Self { inner })
253    }
254
255    /// Enqueue one event; flushes when the buffer reaches the batch size or
256    /// when cached batches are waiting for retry.
257    async fn do_add(&self, data: &Data) -> Result<()> {
258        let json = serde_json::to_vec(data)?;
259        let enqueue_log = parse_time(&String::from_utf8_lossy(&json));
260        let (ready, has_cache) = {
261            let mut queue = self
262                .inner
263                .queue
264                .lock()
265                .expect("ThinkingData queue poisoned");
266            if queue.closed {
267                return Err(TDError::ConsumerClosed);
268            }
269            queue.buffer.push(json);
270            (
271                queue.buffer.len() >= self.inner.batch_size,
272                !queue.cache.is_empty(),
273            )
274        };
275        td_log_info(&format!("Enqueue event data: {enqueue_log}"));
276        if ready || has_cache {
277            self.do_flush_inner(false).await
278        } else {
279            Ok(())
280        }
281    }
282
283    /// Request a delivery of one (or, with `all`, every) pending batch.
284    async fn do_flush_inner(&self, all: bool) -> Result<()> {
285        let (respond_tx, respond_rx) = oneshot::channel();
286        self.inner
287            .req_tx
288            .send(Request::Flush {
289                all,
290                respond: respond_tx,
291            })
292            .map_err(|_| TDError::ConsumerClosed)?;
293        match respond_rx.await {
294            Ok(result) => result,
295            // A concurrent `close` won the race and shut the sender task down
296            // before this request was served. The enqueued data was part of
297            // the close-time delivery, so its retained result is the answer.
298            Err(_) => match self.inner.close_result.get() {
299                Some(result) => result.clone(),
300                None => Err(TDError::ConsumerClosed),
301            },
302        }
303    }
304
305    /// Deliver every currently pending batch.
306    pub async fn flush_all_async(&self) -> Result<()> {
307        self.do_flush_inner(true).await
308    }
309
310    /// Stop admission, deliver every pending batch and shut the sender task
311    /// down. Repeated calls return the same result and do not resend failed
312    /// batches.
313    async fn do_close(&self) -> Result<()> {
314        if let Some(result) = self.inner.close_result.get() {
315            return result.clone();
316        }
317        let (respond_tx, respond_rx) = oneshot::channel();
318        self.inner
319            .req_tx
320            .send(Request::Close {
321                respond: respond_tx,
322            })
323            .map_err(|_| TDError::ConsumerClosed)?;
324        let result = match respond_rx.await {
325            Ok(result) => result,
326            // A concurrent `close` won the race and shut the sender task down
327            // before this request was served; report its retained result.
328            Err(_) => match self.inner.close_result.get() {
329                Some(result) => result.clone(),
330                None => Err(TDError::ConsumerClosed),
331            },
332        };
333        let _ = self.inner.close_result.set(result.clone());
334        result
335    }
336}
337
338/// The streaming sender task: serializes all deliveries, runs the auto-flush
339/// timer and processes close.
340async fn sender_loop(
341    inner: Arc<Inner>,
342    mut req_rx: mpsc::UnboundedReceiver<Request>,
343    auto_flush: bool,
344    interval: Duration,
345) {
346    loop {
347        let request = if auto_flush {
348            tokio::select! {
349                request = req_rx.recv() => request,
350                _ = tokio::time::sleep(interval) => {
351                    // Timer-triggered flush never surfaces errors to a caller.
352                    let _ = flush_batches(&inner, false, false).await;
353                    continue;
354                }
355            }
356        } else {
357            req_rx.recv().await
358        };
359
360        match request {
361            None => return,
362            Some(Request::Flush { all, respond }) => {
363                let result = flush_batches(&inner, all, false).await;
364                let _ = respond.send(result);
365            }
366            Some(Request::Close { respond }) => {
367                {
368                    let mut queue = inner.queue.lock().expect("ThinkingData queue poisoned");
369                    queue.closed = true;
370                }
371                let result = flush_batches(&inner, true, true).await;
372                let _ = inner.close_result.set(result.clone());
373                let _ = respond.send(result);
374                return;
375            }
376        }
377    }
378}
379
380/// Move the buffer into the cache, deliver pending batches, and put failed
381/// batches back (bounded by the cache capacity, keeping the newest).
382async fn flush_batches(inner: &Arc<Inner>, all: bool, closing: bool) -> Result<()> {
383    let pending: Vec<Vec<Vec<u8>>> = {
384        let mut queue = inner.queue.lock().expect("ThinkingData queue poisoned");
385        if !closing && queue.closed {
386            return Err(TDError::ConsumerClosed);
387        }
388        if !queue.buffer.is_empty()
389            && (all || queue.cache.is_empty() || queue.buffer.len() >= inner.batch_size)
390        {
391            let buffer = std::mem::take(&mut queue.buffer);
392            queue.cache.push_back(buffer);
393        }
394        let count = if all {
395            queue.cache.len()
396        } else {
397            queue.cache.len().min(1)
398        };
399        queue.cache.drain(..count).collect()
400    };
401
402    let mut first_err: Option<TDError> = None;
403    let mut retained: Vec<Vec<Vec<u8>>> = Vec::new();
404    for batch in pending {
405        let (discard, err) = upload_batch(inner, &batch).await;
406        if !discard {
407            retained.push(batch);
408        }
409        if err.is_some() && first_err.is_none() {
410            first_err = err;
411        }
412    }
413
414    let mut queue = inner.queue.lock().expect("ThinkingData queue poisoned");
415    // Re-add failed batches in their original order, ahead of newer batches.
416    for batch in retained.into_iter().rev() {
417        queue.cache.push_front(batch);
418    }
419    // Keep only the newest `cache_capacity` batches; say so when data is
420    // dropped, mirroring the Go SDK's discard logging.
421    if queue.cache.len() > inner.cache_capacity {
422        let dropped = queue.cache.len() - inner.cache_capacity;
423        td_log_error(&format!(
424            "cache is full, discard {dropped} batch(es) and keep the newest {}",
425            inner.cache_capacity
426        ));
427        while queue.cache.len() > inner.cache_capacity {
428            queue.cache.pop_front();
429        }
430    }
431    first_err.map_or(Ok(()), Err)
432}
433
434/// Deliver one batch: gzip-encode (optional), POST with retries and interpret
435/// the receiver's response code.
436///
437/// `discard` is true for every HTTP 200 response, preserving the deletion
438/// policy of the Go SDK: batches acknowledged with a data error are dropped.
439async fn upload_batch(inner: &Arc<Inner>, batch: &[Vec<u8>]) -> (bool, Option<TDError>) {
440    let mut payload = Vec::new();
441    payload.push(b'[');
442    for (index, event) in batch.iter().enumerate() {
443        if index > 0 {
444            payload.push(b',');
445        }
446        payload.extend_from_slice(event);
447    }
448    payload.push(b']');
449    let params = parse_time(&String::from_utf8_lossy(&payload));
450
451    // Encode the request body once; every retry attempt reuses the same bytes.
452    let body = if inner.compress {
453        match gzip_encode(params.as_bytes()) {
454            Ok(encoded) => encoded,
455            Err(err) => return (false, Some(err)),
456        }
457    } else {
458        params.clone().into_bytes()
459    };
460
461    for attempt in 0..3 {
462        let (status, code, err) = send_once(inner, &body, batch.len()).await;
463        if status == 200 {
464            if let Some(err) = err {
465                return (true, Some(err));
466            }
467            return match code {
468                Some(0) => {
469                    td_log_info(&format!("send success: {params}"));
470                    (true, None)
471                }
472                Some(1) | Some(-1) => (true, Some(TDError::msg("invalid data format"))),
473                Some(-2) => (true, Some(TDError::msg("APP ID doesn't exist"))),
474                Some(-3) => (true, Some(TDError::msg("invalid ip transmission"))),
475                _ => (true, Some(TDError::msg("unknown error"))),
476            };
477        }
478        // Transport errors surface immediately without a retry, matching Go.
479        if let Some(err) = err {
480            return (false, Some(err));
481        }
482        if attempt == 2 {
483            return (
484                false,
485                Some(TDError::msg(format!(
486                    "upload failed after 3 attempts. Status code is: {status}"
487                ))),
488            );
489        }
490    }
491    (false, None)
492}
493
494/// The receiver's response envelope: `{"code": 0}`.
495#[derive(Debug, serde::Deserialize)]
496struct BatchResponse {
497    code: Option<i64>,
498}
499
500/// POST one request; returns `(status, code, error)`.
501async fn send_once(
502    inner: &Arc<Inner>,
503    body: &[u8],
504    size: usize,
505) -> (u16, Option<i64>, Option<TDError>) {
506    let request = inner
507        .client
508        .post(&inner.server_url)
509        .header("appid", &inner.app_id)
510        .header("user-agent", "ta-rust-sdk")
511        .header("version", crate::SDK_VERSION)
512        .header("compress", if inner.compress { "gzip" } else { "none" })
513        .header("TA-Integration-Type", crate::LIB_NAME)
514        .header("TA-Integration-Version", crate::SDK_VERSION)
515        .header("TA-Integration-Count", size.to_string())
516        .header("Content-Type", "application/json")
517        .body(body.to_vec());
518
519    let response = match request.send().await {
520        Ok(response) => response,
521        Err(err) => return (0, None, Some(err.into())),
522    };
523    let status = response.status().as_u16();
524    if status != 200 {
525        return (status, None, None);
526    }
527
528    let body = match response.text().await {
529        Ok(body) => body,
530        Err(err) => {
531            return (
532                status,
533                Some(1),
534                Some(TDError::msg(format!("read batch response: {err}"))),
535            );
536        }
537    };
538    let parsed: BatchResponse = match serde_json::from_str(&body) {
539        Ok(parsed) => parsed,
540        Err(err) => {
541            return (
542                status,
543                Some(1),
544                Some(TDError::msg(format!("decode batch response: {err}"))),
545            );
546        }
547    };
548    match parsed.code {
549        Some(code) => (status, Some(code), None),
550        None => (
551            status,
552            Some(1),
553            Some(TDError::msg(
554                "invalid batch response: code is missing or null",
555            )),
556        ),
557    }
558}
559
560/// Gzip-compress a request body.
561fn gzip_encode(data: &[u8]) -> Result<Vec<u8>> {
562    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
563    encoder.write_all(data)?;
564    encoder.finish().map_err(Into::into)
565}
566
567#[cfg(feature = "blocking")]
568impl crate::consumer::Consumer for BatchConsumer {
569    /// Enqueue one event, blocking until a triggered delivery finishes.
570    fn add(&self, data: &Data) -> Result<()> {
571        crate::consumer::shared_runtime().block_on(self.do_add(data))
572    }
573
574    /// Deliver the next pending batch, blocking until it completes.
575    fn flush(&self) -> Result<()> {
576        crate::consumer::shared_runtime().block_on(self.do_flush_inner(false))
577    }
578
579    /// Stop admission, deliver every pending batch and shut down. Repeated
580    /// calls return the same result.
581    fn close(&self) -> Result<()> {
582        crate::consumer::shared_runtime().block_on(self.do_close())
583    }
584}
585
586#[cfg(feature = "blocking")]
587impl BatchConsumer {
588    /// Deliver every currently pending batch.
589    pub fn flush_all(&self) -> Result<()> {
590        crate::consumer::shared_runtime().block_on(self.flush_all_async())
591    }
592}
593
594#[cfg(feature = "async")]
595#[async_trait::async_trait]
596impl crate::consumer::AsyncConsumer for BatchConsumer {
597    /// Enqueue one event; flushes when the buffer reaches the batch size or
598    /// when cached batches are waiting for retry.
599    async fn add_async(&self, data: &Data) -> Result<()> {
600        self.do_add(data).await
601    }
602
603    /// Deliver the next pending batch.
604    async fn flush_async(&self) -> Result<()> {
605        self.do_flush_inner(false).await
606    }
607
608    /// Stop admission, deliver every pending batch and shut the sender task
609    /// down. Repeated calls return the same result.
610    async fn close_async(&self) -> Result<()> {
611        self.do_close().await
612    }
613}