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_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/// # use thinkingdata_core::consumer::{BatchConsumer, Consumer};
132///
133/// # #[cfg(feature = "blocking")]
134/// # fn main() -> Result<(), thinkingdata_core::TDError> {
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/// # Ok(())
140/// # }
141/// ```
142#[derive(Clone)]
143pub struct BatchConsumer {
144    inner: Arc<Inner>,
145}
146
147impl std::fmt::Debug for BatchConsumer {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        f.debug_struct("BatchConsumer")
150            .field("server_url", &self.inner.server_url)
151            .field("app_id", &self.inner.app_id)
152            .field("batch_size", &self.inner.batch_size)
153            .field("cache_capacity", &self.inner.cache_capacity)
154            .field("compress", &self.inner.compress)
155            .finish_non_exhaustive()
156    }
157}
158
159impl BatchConsumer {
160    /// Create a batch consumer with default settings (gzip compression
161    /// enabled, batch size 20).
162    pub fn new(server_url: &str, app_id: &str) -> Result<Self> {
163        Self::with_config(BatchConsumerConfig {
164            server_url: server_url.to_string(),
165            app_id: app_id.to_string(),
166            ..BatchConsumerConfig::default()
167        })
168    }
169
170    /// Create a batch consumer with an explicit batch size.
171    pub fn with_batch_size(server_url: &str, app_id: &str, batch_size: usize) -> Result<Self> {
172        Self::with_config(BatchConsumerConfig {
173            server_url: server_url.to_string(),
174            app_id: app_id.to_string(),
175            batch_size,
176            ..BatchConsumerConfig::default()
177        })
178    }
179
180    /// Create a batch consumer with explicit compression control.
181    pub fn with_compress(server_url: &str, app_id: &str, compress: bool) -> Result<Self> {
182        Self::with_config(BatchConsumerConfig {
183            server_url: server_url.to_string(),
184            app_id: app_id.to_string(),
185            compress,
186            ..BatchConsumerConfig::default()
187        })
188    }
189
190    /// Create a batch consumer from a full configuration.
191    pub fn with_config(config: BatchConsumerConfig) -> Result<Self> {
192        if config.server_url.is_empty() {
193            return Err(TDError::msg("ServerUrl not be empty"));
194        }
195        let mut server_url = url::Url::parse(&config.server_url)?;
196        server_url.set_path("/sync_server");
197
198        let batch_size = if config.batch_size > MAX_BATCH_SIZE {
199            MAX_BATCH_SIZE
200        } else if config.batch_size == 0 {
201            DEFAULT_BATCH_SIZE
202        } else {
203            config.batch_size
204        };
205        let cache_capacity = if config.cache_capacity == 0 {
206            DEFAULT_CACHE_CAPACITY
207        } else {
208            config.cache_capacity
209        };
210        let timeout_ms = if config.timeout_ms == 0 {
211            DEFAULT_TIMEOUT_MS
212        } else {
213            config.timeout_ms
214        };
215        let interval_secs = if config.interval_secs == 0 {
216            DEFAULT_INTERVAL_SECS
217        } else {
218            config.interval_secs
219        };
220
221        let client = reqwest::Client::builder()
222            .timeout(Duration::from_millis(timeout_ms))
223            .build()?;
224        let (req_tx, req_rx) = mpsc::unbounded_channel::<Request>();
225
226        let inner = Arc::new(Inner {
227            server_url: server_url.to_string(),
228            app_id: config.app_id.clone(),
229            compress: config.compress,
230            batch_size,
231            cache_capacity,
232            client,
233            queue: Mutex::new(Queue::default()),
234            req_tx,
235            close_result: OnceLock::new(),
236        });
237
238        // Spawn the streaming sender task that owns all uploads.
239        let task_inner = inner.clone();
240        let auto_flush = config.auto_flush;
241        let interval = Duration::from_secs(interval_secs);
242        crate::consumer::shared_runtime().spawn(async move {
243            sender_loop(task_inner, req_rx, auto_flush, interval).await;
244        });
245
246        td_log_info(&format!(
247            "Mode: batch consumer, appId: {}, serverUrl: {}",
248            config.app_id, inner.server_url
249        ));
250
251        Ok(Self { inner })
252    }
253
254    /// Enqueue one event; flushes when the buffer reaches the batch size or
255    /// when cached batches are waiting for retry.
256    async fn do_add(&self, data: &Data) -> Result<()> {
257        let json = serde_json::to_vec(data)?;
258        let enqueue_log = parse_time(&String::from_utf8_lossy(&json));
259        let (ready, has_cache) = {
260            let mut queue = self
261                .inner
262                .queue
263                .lock()
264                .expect("ThinkingData queue poisoned");
265            if queue.closed {
266                return Err(TDError::ConsumerClosed);
267            }
268            queue.buffer.push(json);
269            (
270                queue.buffer.len() >= self.inner.batch_size,
271                !queue.cache.is_empty(),
272            )
273        };
274        td_log_info(&format!("Enqueue event data: {enqueue_log}"));
275        if ready || has_cache {
276            self.do_flush_inner(false).await
277        } else {
278            Ok(())
279        }
280    }
281
282    /// Request a delivery of one (or, with `all`, every) pending batch.
283    async fn do_flush_inner(&self, all: bool) -> Result<()> {
284        let (respond_tx, respond_rx) = oneshot::channel();
285        self.inner
286            .req_tx
287            .send(Request::Flush {
288                all,
289                respond: respond_tx,
290            })
291            .map_err(|_| TDError::ConsumerClosed)?;
292        respond_rx.await.map_err(|_| TDError::ConsumerClosed)?
293    }
294
295    /// Deliver every currently pending batch.
296    pub async fn flush_all_async(&self) -> Result<()> {
297        self.do_flush_inner(true).await
298    }
299
300    /// Stop admission, deliver every pending batch and shut the sender task
301    /// down. Repeated calls return the same result and do not resend failed
302    /// batches.
303    async fn do_close(&self) -> Result<()> {
304        if let Some(result) = self.inner.close_result.get() {
305            return result.clone();
306        }
307        let (respond_tx, respond_rx) = oneshot::channel();
308        self.inner
309            .req_tx
310            .send(Request::Close {
311                respond: respond_tx,
312            })
313            .map_err(|_| TDError::ConsumerClosed)?;
314        let result = respond_rx.await.map_err(|_| TDError::ConsumerClosed)?;
315        let _ = self.inner.close_result.set(result.clone());
316        result
317    }
318}
319
320/// The streaming sender task: serializes all deliveries, runs the auto-flush
321/// timer and processes close.
322async fn sender_loop(
323    inner: Arc<Inner>,
324    mut req_rx: mpsc::UnboundedReceiver<Request>,
325    auto_flush: bool,
326    interval: Duration,
327) {
328    loop {
329        let request = if auto_flush {
330            tokio::select! {
331                request = req_rx.recv() => request,
332                _ = tokio::time::sleep(interval) => {
333                    // Timer-triggered flush never surfaces errors to a caller.
334                    let _ = flush_batches(&inner, false, false).await;
335                    continue;
336                }
337            }
338        } else {
339            req_rx.recv().await
340        };
341
342        match request {
343            None => return,
344            Some(Request::Flush { all, respond }) => {
345                let result = flush_batches(&inner, all, false).await;
346                let _ = respond.send(result);
347            }
348            Some(Request::Close { respond }) => {
349                {
350                    let mut queue = inner.queue.lock().expect("ThinkingData queue poisoned");
351                    queue.closed = true;
352                }
353                let result = flush_batches(&inner, true, true).await;
354                let _ = inner.close_result.set(result.clone());
355                let _ = respond.send(result);
356                return;
357            }
358        }
359    }
360}
361
362/// Move the buffer into the cache, deliver pending batches, and put failed
363/// batches back (bounded by the cache capacity, keeping the newest).
364async fn flush_batches(inner: &Arc<Inner>, all: bool, closing: bool) -> Result<()> {
365    let pending: Vec<Vec<Vec<u8>>> = {
366        let mut queue = inner.queue.lock().expect("ThinkingData queue poisoned");
367        if !closing && queue.closed {
368            return Err(TDError::ConsumerClosed);
369        }
370        if !queue.buffer.is_empty()
371            && (all || queue.cache.is_empty() || queue.buffer.len() >= inner.batch_size)
372        {
373            let buffer = std::mem::take(&mut queue.buffer);
374            queue.cache.push_back(buffer);
375        }
376        let count = if all {
377            queue.cache.len()
378        } else {
379            queue.cache.len().min(1)
380        };
381        queue.cache.drain(..count).collect()
382    };
383
384    let mut first_err: Option<TDError> = None;
385    let mut retained: Vec<Vec<Vec<u8>>> = Vec::new();
386    for batch in pending {
387        let (discard, err) = upload_batch(inner, &batch).await;
388        if !discard {
389            retained.push(batch);
390        }
391        if err.is_some() && first_err.is_none() {
392            first_err = err;
393        }
394    }
395
396    let mut queue = inner.queue.lock().expect("ThinkingData queue poisoned");
397    // Re-add failed batches in their original order, ahead of newer batches.
398    for batch in retained.into_iter().rev() {
399        queue.cache.push_front(batch);
400    }
401    // Keep only the newest `cache_capacity` batches.
402    while queue.cache.len() > inner.cache_capacity {
403        queue.cache.pop_front();
404    }
405    first_err.map_or(Ok(()), Err)
406}
407
408/// Deliver one batch: gzip-encode (optional), POST with retries and interpret
409/// the receiver's response code.
410///
411/// `discard` is true for every HTTP 200 response, preserving the deletion
412/// policy of the Go SDK: batches acknowledged with a data error are dropped.
413async fn upload_batch(inner: &Arc<Inner>, batch: &[Vec<u8>]) -> (bool, Option<TDError>) {
414    let mut payload = Vec::new();
415    payload.push(b'[');
416    for (index, event) in batch.iter().enumerate() {
417        if index > 0 {
418            payload.push(b',');
419        }
420        payload.extend_from_slice(event);
421    }
422    payload.push(b']');
423    let params = parse_time(&String::from_utf8_lossy(&payload));
424
425    for attempt in 0..3 {
426        let (status, code, err) = send_once(inner, &params, batch.len()).await;
427        if status == 200 {
428            if let Some(err) = err {
429                return (true, Some(err));
430            }
431            return match code {
432                Some(0) => {
433                    td_log_info(&format!("send success: {params}"));
434                    (true, None)
435                }
436                Some(1) | Some(-1) => (true, Some(TDError::msg("invalid data format"))),
437                Some(-2) => (true, Some(TDError::msg("APP ID doesn't exist"))),
438                Some(-3) => (true, Some(TDError::msg("invalid ip transmission"))),
439                _ => (true, Some(TDError::msg("unknown error"))),
440            };
441        }
442        // Transport errors surface immediately without a retry, matching Go.
443        if let Some(err) = err {
444            return (false, Some(err));
445        }
446        if attempt == 2 {
447            return (
448                false,
449                Some(TDError::msg(format!(
450                    "network error, but err is nil. Status code is: {status}"
451                ))),
452            );
453        }
454    }
455    (false, None)
456}
457
458/// The receiver's response envelope: `{"code": 0}`.
459#[derive(Debug, serde::Deserialize)]
460struct BatchResponse {
461    code: Option<i64>,
462}
463
464/// POST one request; returns `(status, code, error)`.
465async fn send_once(
466    inner: &Arc<Inner>,
467    params: &str,
468    size: usize,
469) -> (u16, Option<i64>, Option<TDError>) {
470    let body = if inner.compress {
471        match gzip_encode(params.as_bytes()) {
472            Ok(encoded) => encoded,
473            Err(err) => return (0, None, Some(err)),
474        }
475    } else {
476        params.as_bytes().to_vec()
477    };
478
479    let request = inner
480        .client
481        .post(&inner.server_url)
482        .header("appid", &inner.app_id)
483        .header("user-agent", "ta-rust-sdk")
484        .header("version", crate::SDK_VERSION)
485        .header("compress", if inner.compress { "gzip" } else { "none" })
486        .header("TA-Integration-Type", crate::LIB_NAME)
487        .header("TA-Integration-Version", crate::SDK_VERSION)
488        .header("TA-Integration-Count", size.to_string())
489        .header("Content-Type", "application/json")
490        .body(body);
491
492    let response = match request.send().await {
493        Ok(response) => response,
494        Err(err) => return (0, None, Some(err.into())),
495    };
496    let status = response.status().as_u16();
497    if status != 200 {
498        return (status, None, None);
499    }
500
501    let body = match response.text().await {
502        Ok(body) => body,
503        Err(err) => {
504            return (
505                status,
506                Some(1),
507                Some(TDError::msg(format!("read batch response: {err}"))),
508            );
509        }
510    };
511    let parsed: BatchResponse = match serde_json::from_str(&body) {
512        Ok(parsed) => parsed,
513        Err(err) => {
514            return (
515                status,
516                Some(1),
517                Some(TDError::msg(format!("decode batch response: {err}"))),
518            );
519        }
520    };
521    match parsed.code {
522        Some(code) => (status, Some(code), None),
523        None => (
524            status,
525            Some(1),
526            Some(TDError::msg(
527                "invalid batch response: code is missing or null",
528            )),
529        ),
530    }
531}
532
533/// Gzip-compress a request body.
534fn gzip_encode(data: &[u8]) -> Result<Vec<u8>> {
535    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
536    encoder.write_all(data)?;
537    encoder.finish().map_err(Into::into)
538}
539
540#[cfg(feature = "blocking")]
541impl crate::consumer::Consumer for BatchConsumer {
542    /// Enqueue one event, blocking until a triggered delivery finishes.
543    fn add(&self, data: &Data) -> Result<()> {
544        crate::consumer::shared_runtime().block_on(self.do_add(data))
545    }
546
547    /// Deliver the next pending batch, blocking until it completes.
548    fn flush(&self) -> Result<()> {
549        crate::consumer::shared_runtime().block_on(self.do_flush_inner(false))
550    }
551
552    /// Stop admission, deliver every pending batch and shut down. Repeated
553    /// calls return the same result.
554    fn close(&self) -> Result<()> {
555        crate::consumer::shared_runtime().block_on(self.do_close())
556    }
557}
558
559#[cfg(feature = "blocking")]
560impl BatchConsumer {
561    /// Deliver every currently pending batch.
562    pub fn flush_all(&self) -> Result<()> {
563        crate::consumer::shared_runtime().block_on(self.flush_all_async())
564    }
565}
566
567#[cfg(feature = "async")]
568#[async_trait::async_trait]
569impl crate::consumer::AsyncConsumer for BatchConsumer {
570    /// Enqueue one event; flushes when the buffer reaches the batch size or
571    /// when cached batches are waiting for retry.
572    async fn add_async(&self, data: &Data) -> Result<()> {
573        self.do_add(data).await
574    }
575
576    /// Deliver the next pending batch.
577    async fn flush_async(&self) -> Result<()> {
578        self.do_flush_inner(false).await
579    }
580
581    /// Stop admission, deliver every pending batch and shut the sender task
582    /// down. Repeated calls return the same result.
583    async fn close_async(&self) -> Result<()> {
584        self.do_close().await
585    }
586}