1use 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
35pub const DEFAULT_BATCH_SIZE: usize = 20;
37pub const MAX_BATCH_SIZE: usize = 200;
39pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
41pub const DEFAULT_INTERVAL_SECS: u64 = 30;
43pub const DEFAULT_CACHE_CAPACITY: usize = 50;
45
46#[derive(Debug, Clone)]
49pub struct BatchConsumerConfig {
50 pub server_url: String,
53 pub app_id: String,
55 pub batch_size: usize,
58 pub timeout_ms: u64,
60 pub compress: bool,
62 pub auto_flush: bool,
64 pub interval_secs: u64,
66 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#[derive(Default)]
88struct Queue {
89 buffer: Vec<Vec<u8>>,
91 cache: VecDeque<Vec<Vec<u8>>>,
93 closed: bool,
95}
96
97enum Request {
99 Flush {
100 all: bool,
101 respond: oneshot::Sender<Result<()>>,
102 },
103 Close {
104 respond: oneshot::Sender<Result<()>>,
105 },
106}
107
108struct 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#[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 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 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 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 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 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 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 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 Err(_) => match self.inner.close_result.get() {
299 Some(result) => result.clone(),
300 None => Err(TDError::ConsumerClosed),
301 },
302 }
303 }
304
305 pub async fn flush_all_async(&self) -> Result<()> {
307 self.do_flush_inner(true).await
308 }
309
310 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 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
338async 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 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
380async 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 for batch in retained.into_iter().rev() {
417 queue.cache.push_front(batch);
418 }
419 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
434async 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 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 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#[derive(Debug, serde::Deserialize)]
496struct BatchResponse {
497 code: Option<i64>,
498}
499
500async 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
560fn 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 fn add(&self, data: &Data) -> Result<()> {
571 crate::consumer::shared_runtime().block_on(self.do_add(data))
572 }
573
574 fn flush(&self) -> Result<()> {
576 crate::consumer::shared_runtime().block_on(self.do_flush_inner(false))
577 }
578
579 fn close(&self) -> Result<()> {
582 crate::consumer::shared_runtime().block_on(self.do_close())
583 }
584}
585
586#[cfg(feature = "blocking")]
587impl BatchConsumer {
588 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 async fn add_async(&self, data: &Data) -> Result<()> {
600 self.do_add(data).await
601 }
602
603 async fn flush_async(&self) -> Result<()> {
605 self.do_flush_inner(false).await
606 }
607
608 async fn close_async(&self) -> Result<()> {
611 self.do_close().await
612 }
613}