thinkingdata_core/consumer/mod.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//! Delivery mechanisms for [`Data`]: the [`Consumer`] / [`AsyncConsumer`]
16//! traits and the three built-in consumers ported from the Go SDK.
17//!
18//! - [`LogConsumer`] writes NDJSON log files consumed later by LogBus. In
19//! async mode it runs a streaming writer task fed by an MPSC channel.
20//! - [`BatchConsumer`] buffers events and uploads them over HTTPS (gzip
21//! compression, three retry attempts, a failure cache, optional auto flush).
22//! - [`DebugConsumer`] validates each event against the receiver, one by one.
23//!
24//! # Choosing an API style
25//!
26//! ```no_run
27//! # use thinkingdata_core::consumer::{BatchConsumer, Consumer};
28//!
29//! # // Blocking (feature `blocking`): returns immediately after the request.
30//! # #[cfg(feature = "blocking")]
31//! # fn demo() -> Result<(), thinkingdata_core::TDError> {
32//! # let consumer = BatchConsumer::new("https://receiver.thinkingdata.io", "app_id")?;
33//! # consumer.flush()?;
34//! # consumer.close()?;
35//! # Ok(())
36//! # }
37//!
38//! # // Async (feature `async`): awaits the delivery result.
39//! # #[cfg(feature = "async")]
40//! # async fn demo_async() -> Result<(), thinkingdata_core::TDError> {
41//! # use thinkingdata_core::consumer::AsyncConsumer;
42//!
43//! # let consumer = BatchConsumer::new("https://receiver.thinkingdata.io", "app_id")?;
44//! # consumer.flush_async().await?;
45//! # consumer.close_async().await?;
46//! # Ok(())
47//! # }
48//! ```
49
50pub(crate) mod batch_consumer;
51pub(crate) mod debug_consumer;
52pub(crate) mod log_consumer;
53
54pub use batch_consumer::{
55 BatchConsumer, BatchConsumerConfig, DEFAULT_BATCH_SIZE, DEFAULT_CACHE_CAPACITY,
56 DEFAULT_INTERVAL_SECS, DEFAULT_TIMEOUT_MS, MAX_BATCH_SIZE,
57};
58pub use debug_consumer::DebugConsumer;
59pub use log_consumer::{LogConsumer, LogConsumerConfig, RotateMode};
60
61use crate::data::Data;
62use crate::error::Result;
63#[cfg(feature = "blocking")]
64use std::sync::Arc;
65use std::sync::OnceLock;
66#[cfg(feature = "blocking")]
67use tokio::runtime::Runtime;
68
69/// Synchronous delivery interface implemented by all consumers.
70///
71/// This is the Rust counterpart of the Go SDK's `TDConsumer` interface: the
72/// [`TDAnalytics`](crate::analytics::TDAnalytics) facade validates and builds
73/// events, then delegates delivery to a consumer. Available with the
74/// `blocking` feature.
75#[cfg(feature = "blocking")]
76pub trait Consumer: Send + Sync {
77 /// Deliver one event. Called with an already validated snapshot.
78 fn add(&self, data: &Data) -> Result<()>;
79
80 /// Deliver everything currently buffered.
81 fn flush(&self) -> Result<()>;
82
83 /// Flush, release resources and stop accepting new events. Repeated calls
84 /// return the same result.
85 fn close(&self) -> Result<()>;
86
87 /// Whether this consumer validates property keys strictly. Only the debug
88 /// consumer is stringent.
89 fn is_stringent(&self) -> bool {
90 false
91 }
92}
93
94/// Asynchronous delivery interface implemented by all consumers.
95///
96/// Mirrors [`Consumer`] with async methods; available with the `async`
97/// feature. Background work (file writing, HTTP upload) always runs on
98/// streaming Tokio tasks, so `add_async` performs no blocking I/O on the
99/// calling task.
100#[cfg(feature = "async")]
101#[async_trait::async_trait]
102pub trait AsyncConsumer: Send + Sync {
103 /// Deliver one event. Called with an already validated snapshot.
104 async fn add_async(&self, data: &Data) -> Result<()>;
105
106 /// Deliver everything currently buffered.
107 async fn flush_async(&self) -> Result<()>;
108
109 /// Flush, release resources and stop accepting new events. Repeated calls
110 /// return the same result.
111 async fn close_async(&self) -> Result<()>;
112
113 /// Whether this consumer validates property keys strictly. Only the debug
114 /// consumer is stringent.
115 fn is_stringent(&self) -> bool {
116 false
117 }
118}
119
120#[cfg(feature = "blocking")]
121impl<C: Consumer + ?Sized> Consumer for Arc<C> {
122 fn add(&self, data: &Data) -> Result<()> {
123 (**self).add(data)
124 }
125
126 fn flush(&self) -> Result<()> {
127 (**self).flush()
128 }
129
130 fn close(&self) -> Result<()> {
131 (**self).close()
132 }
133
134 fn is_stringent(&self) -> bool {
135 (**self).is_stringent()
136 }
137}
138
139#[cfg(feature = "blocking")]
140impl<C: Consumer + ?Sized> Consumer for Box<C> {
141 fn add(&self, data: &Data) -> Result<()> {
142 (**self).add(data)
143 }
144
145 fn flush(&self) -> Result<()> {
146 (**self).flush()
147 }
148
149 fn close(&self) -> Result<()> {
150 (**self).close()
151 }
152
153 fn is_stringent(&self) -> bool {
154 (**self).is_stringent()
155 }
156}
157
158#[cfg(feature = "async")]
159#[async_trait::async_trait]
160impl<C: AsyncConsumer + ?Sized + Sync> AsyncConsumer for Arc<C> {
161 async fn add_async(&self, data: &Data) -> Result<()> {
162 (**self).add_async(data).await
163 }
164
165 async fn flush_async(&self) -> Result<()> {
166 (**self).flush_async().await
167 }
168
169 async fn close_async(&self) -> Result<()> {
170 (**self).close_async().await
171 }
172
173 fn is_stringent(&self) -> bool {
174 (**self).is_stringent()
175 }
176}
177
178#[cfg(feature = "async")]
179#[async_trait::async_trait]
180impl<C: AsyncConsumer + ?Sized + Sync> AsyncConsumer for Box<C> {
181 async fn add_async(&self, data: &Data) -> Result<()> {
182 (**self).add_async(data).await
183 }
184
185 async fn flush_async(&self) -> Result<()> {
186 (**self).flush_async().await
187 }
188
189 async fn close_async(&self) -> Result<()> {
190 (**self).close_async().await
191 }
192
193 fn is_stringent(&self) -> bool {
194 (**self).is_stringent()
195 }
196}
197
198/// Process-wide async runtime shared by the consumers.
199///
200/// The consumers drive their streaming pipelines (log writer task, batch
201/// sender task, HTTP requests) on this runtime. The blocking API additionally
202/// uses `Runtime::block_on` to await pipeline results from synchronous code —
203/// therefore consumer methods must not be called from inside an async context
204/// when using the blocking API.
205pub(crate) fn shared_runtime() -> &'static Runtime {
206 static RUNTIME: OnceLock<Runtime> = OnceLock::new();
207 RUNTIME.get_or_init(|| {
208 tokio::runtime::Builder::new_multi_thread()
209 .worker_threads(1)
210 .thread_name("thinkingdata-runtime")
211 .enable_all()
212 .build()
213 .expect("failed to start the ThinkingData async runtime")
214 })
215}