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 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
437async 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 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 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#[derive(Debug, serde::Deserialize)]
499struct BatchResponse {
500 code: Option<i64>,
501}
502
503async 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
563fn 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 fn add(&self, data: &Data) -> Result<()> {
574 crate::consumer::shared_runtime().block_on(self.do_add(data))
575 }
576
577 fn flush(&self) -> Result<()> {
579 crate::consumer::shared_runtime().block_on(self.do_flush_inner(false))
580 }
581
582 fn close(&self) -> Result<()> {
585 crate::consumer::shared_runtime().block_on(self.do_close())
586 }
587}
588
589#[cfg(feature = "blocking")]
590impl BatchConsumer {
591 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 async fn add_async(&self, data: &Data) -> Result<()> {
603 self.do_add(data).await
604 }
605
606 async fn flush_async(&self) -> Result<()> {
608 self.do_flush_inner(false).await
609 }
610
611 async fn close_async(&self) -> Result<()> {
614 self.do_close().await
615 }
616}