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. The discard is logged
420    // after the lock is released: custom logger callbacks must never run
421    // while an SDK lock is held.
422    let mut dropped = 0usize;
423    while queue.cache.len() > inner.cache_capacity {
424        queue.cache.pop_front();
425        dropped += 1;
426    }
427    drop(queue);
428    if dropped > 0 {
429        td_log_error(&format!(
430            "cache is full, discard {dropped} batch(es) and keep the newest {}",
431            inner.cache_capacity
432        ));
433    }
434    first_err.map_or(Ok(()), Err)
435}
436
437/// Deliver one batch: gzip-encode (optional), POST with retries and interpret
438/// the receiver's response code.
439///
440/// `discard` is true for every HTTP 200 response, preserving the deletion
441/// policy of the Go SDK: batches acknowledged with a data error are dropped.
442async fn upload_batch(inner: &Arc<Inner>, batch: &[Vec<u8>]) -> (bool, Option<TDError>) {
443    let mut payload = Vec::new();
444    payload.push(b'[');
445    for (index, event) in batch.iter().enumerate() {
446        if index > 0 {
447            payload.push(b',');
448        }
449        payload.extend_from_slice(event);
450    }
451    payload.push(b']');
452    let params = parse_time(&String::from_utf8_lossy(&payload));
453
454    // Encode the request body once; every retry attempt reuses the same bytes.
455    let body = if inner.compress {
456        match gzip_encode(params.as_bytes()) {
457            Ok(encoded) => encoded,
458            Err(err) => return (false, Some(err)),
459        }
460    } else {
461        params.clone().into_bytes()
462    };
463
464    for attempt in 0..3 {
465        let (status, code, err) = send_once(inner, &body, batch.len()).await;
466        if status == 200 {
467            if let Some(err) = err {
468                return (true, Some(err));
469            }
470            return match code {
471                Some(0) => {
472                    td_log_info(&format!("send success: {params}"));
473                    (true, None)
474                }
475                Some(1) | Some(-1) => (true, Some(TDError::msg("invalid data format"))),
476                Some(-2) => (true, Some(TDError::msg("APP ID doesn't exist"))),
477                Some(-3) => (true, Some(TDError::msg("invalid ip transmission"))),
478                _ => (true, Some(TDError::msg("unknown error"))),
479            };
480        }
481        // Transport errors surface immediately without a retry, matching Go.
482        if let Some(err) = err {
483            return (false, Some(err));
484        }
485        if attempt == 2 {
486            return (
487                false,
488                Some(TDError::msg(format!(
489                    "upload failed after 3 attempts. Status code is: {status}"
490                ))),
491            );
492        }
493    }
494    (false, None)
495}
496
497/// The receiver's response envelope: `{"code": 0}`.
498#[derive(Debug, serde::Deserialize)]
499struct BatchResponse {
500    code: Option<i64>,
501}
502
503/// POST one request; returns `(status, code, error)`.
504async fn send_once(
505    inner: &Arc<Inner>,
506    body: &[u8],
507    size: usize,
508) -> (u16, Option<i64>, Option<TDError>) {
509    let request = inner
510        .client
511        .post(&inner.server_url)
512        .header("appid", &inner.app_id)
513        .header("user-agent", "ta-rust-sdk")
514        .header("version", crate::SDK_VERSION)
515        .header("compress", if inner.compress { "gzip" } else { "none" })
516        .header("TA-Integration-Type", crate::LIB_NAME)
517        .header("TA-Integration-Version", crate::SDK_VERSION)
518        .header("TA-Integration-Count", size.to_string())
519        .header("Content-Type", "application/json")
520        .body(body.to_vec());
521
522    let response = match request.send().await {
523        Ok(response) => response,
524        Err(err) => return (0, None, Some(err.into())),
525    };
526    let status = response.status().as_u16();
527    if status != 200 {
528        return (status, None, None);
529    }
530
531    let body = match response.text().await {
532        Ok(body) => body,
533        Err(err) => {
534            return (
535                status,
536                Some(1),
537                Some(TDError::msg(format!("read batch response: {err}"))),
538            );
539        }
540    };
541    let parsed: BatchResponse = match serde_json::from_str(&body) {
542        Ok(parsed) => parsed,
543        Err(err) => {
544            return (
545                status,
546                Some(1),
547                Some(TDError::msg(format!("decode batch response: {err}"))),
548            );
549        }
550    };
551    match parsed.code {
552        Some(code) => (status, Some(code), None),
553        None => (
554            status,
555            Some(1),
556            Some(TDError::msg(
557                "invalid batch response: code is missing or null",
558            )),
559        ),
560    }
561}
562
563/// Gzip-compress a request body.
564fn gzip_encode(data: &[u8]) -> Result<Vec<u8>> {
565    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
566    encoder.write_all(data)?;
567    encoder.finish().map_err(Into::into)
568}
569
570#[cfg(feature = "blocking")]
571impl crate::consumer::Consumer for BatchConsumer {
572    /// Enqueue one event, blocking until a triggered delivery finishes.
573    fn add(&self, data: &Data) -> Result<()> {
574        crate::consumer::shared_runtime().block_on(self.do_add(data))
575    }
576
577    /// Deliver the next pending batch, blocking until it completes.
578    fn flush(&self) -> Result<()> {
579        crate::consumer::shared_runtime().block_on(self.do_flush_inner(false))
580    }
581
582    /// Stop admission, deliver every pending batch and shut down. Repeated
583    /// calls return the same result.
584    fn close(&self) -> Result<()> {
585        crate::consumer::shared_runtime().block_on(self.do_close())
586    }
587}
588
589#[cfg(feature = "blocking")]
590impl BatchConsumer {
591    /// Deliver every currently pending batch.
592    pub fn flush_all(&self) -> Result<()> {
593        crate::consumer::shared_runtime().block_on(self.flush_all_async())
594    }
595}
596
597#[cfg(feature = "async")]
598#[async_trait::async_trait]
599impl crate::consumer::AsyncConsumer for BatchConsumer {
600    /// Enqueue one event; flushes when the buffer reaches the batch size or
601    /// when cached batches are waiting for retry.
602    async fn add_async(&self, data: &Data) -> Result<()> {
603        self.do_add(data).await
604    }
605
606    /// Deliver the next pending batch.
607    async fn flush_async(&self) -> Result<()> {
608        self.do_flush_inner(false).await
609    }
610
611    /// Stop admission, deliver every pending batch and shut the sender task
612    /// down. Repeated calls return the same result.
613    async fn close_async(&self) -> Result<()> {
614        self.do_close().await
615    }
616}