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//! # // Blocking (feature `blocking`): returns immediately after the request.
28//! # #[cfg(feature = "blocking")]
29//! # fn demo() -> Result<(), thinkingdata_core::TDError> {
30//! # use thinkingdata_core::consumer::{BatchConsumer, Consumer};
31//!
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, BatchConsumer};
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
61// The traits are feature-gated, so their imports must be too; the shared
62// runtime is not — every consumer spawns its pipeline regardless of features.
63#[cfg(any(feature = "blocking", feature = "async"))]
64use crate::data::Data;
65#[cfg(any(feature = "blocking", feature = "async"))]
66use crate::error::Result;
67#[cfg(any(feature = "blocking", feature = "async"))]
68use std::sync::Arc;
69use std::sync::OnceLock;
70use tokio::runtime::Runtime;
71
72/// Synchronous delivery interface implemented by all consumers.
73///
74/// This is the Rust counterpart of the Go SDK's `TDConsumer` interface: the
75/// [`TDAnalytics`](crate::analytics::TDAnalytics) facade validates and builds
76/// events, then delegates delivery to a consumer. Available with the
77/// `blocking` feature.
78#[cfg(feature = "blocking")]
79pub trait Consumer: Send + Sync {
80 /// Deliver one event. Called with an already validated snapshot.
81 fn add(&self, data: &Data) -> Result<()>;
82
83 /// Deliver everything currently buffered.
84 fn flush(&self) -> Result<()>;
85
86 /// Flush, release resources and stop accepting new events. Repeated calls
87 /// return the same result.
88 fn close(&self) -> Result<()>;
89
90 /// Whether this consumer validates property keys strictly. Only the debug
91 /// consumer is stringent.
92 fn is_stringent(&self) -> bool {
93 false
94 }
95}
96
97/// Asynchronous delivery interface implemented by all consumers.
98///
99/// Mirrors [`Consumer`] with async methods; available with the `async`
100/// feature. Background work (file writing, HTTP upload) always runs on
101/// streaming Tokio tasks, so `add_async` performs no blocking I/O on the
102/// calling task.
103#[cfg(feature = "async")]
104#[async_trait::async_trait]
105pub trait AsyncConsumer: Send + Sync {
106 /// Deliver one event. Called with an already validated snapshot.
107 async fn add_async(&self, data: &Data) -> Result<()>;
108
109 /// Deliver everything currently buffered.
110 async fn flush_async(&self) -> Result<()>;
111
112 /// Flush, release resources and stop accepting new events. Repeated calls
113 /// return the same result.
114 async fn close_async(&self) -> Result<()>;
115
116 /// Whether this consumer validates property keys strictly. Only the debug
117 /// consumer is stringent.
118 fn is_stringent(&self) -> bool {
119 false
120 }
121}
122
123#[cfg(feature = "blocking")]
124impl<C: Consumer + ?Sized> Consumer for Arc<C> {
125 fn add(&self, data: &Data) -> Result<()> {
126 (**self).add(data)
127 }
128
129 fn flush(&self) -> Result<()> {
130 (**self).flush()
131 }
132
133 fn close(&self) -> Result<()> {
134 (**self).close()
135 }
136
137 fn is_stringent(&self) -> bool {
138 (**self).is_stringent()
139 }
140}
141
142#[cfg(feature = "blocking")]
143impl<C: Consumer + ?Sized> Consumer for Box<C> {
144 fn add(&self, data: &Data) -> Result<()> {
145 (**self).add(data)
146 }
147
148 fn flush(&self) -> Result<()> {
149 (**self).flush()
150 }
151
152 fn close(&self) -> Result<()> {
153 (**self).close()
154 }
155
156 fn is_stringent(&self) -> bool {
157 (**self).is_stringent()
158 }
159}
160
161#[cfg(feature = "async")]
162#[async_trait::async_trait]
163impl<C: AsyncConsumer + ?Sized + Sync> AsyncConsumer for Arc<C> {
164 async fn add_async(&self, data: &Data) -> Result<()> {
165 (**self).add_async(data).await
166 }
167
168 async fn flush_async(&self) -> Result<()> {
169 (**self).flush_async().await
170 }
171
172 async fn close_async(&self) -> Result<()> {
173 (**self).close_async().await
174 }
175
176 fn is_stringent(&self) -> bool {
177 (**self).is_stringent()
178 }
179}
180
181#[cfg(feature = "async")]
182#[async_trait::async_trait]
183impl<C: AsyncConsumer + ?Sized + Sync> AsyncConsumer for Box<C> {
184 async fn add_async(&self, data: &Data) -> Result<()> {
185 (**self).add_async(data).await
186 }
187
188 async fn flush_async(&self) -> Result<()> {
189 (**self).flush_async().await
190 }
191
192 async fn close_async(&self) -> Result<()> {
193 (**self).close_async().await
194 }
195
196 fn is_stringent(&self) -> bool {
197 (**self).is_stringent()
198 }
199}
200
201/// Process-wide async runtime shared by the consumers.
202///
203/// The consumers drive their streaming pipelines (log writer task, batch
204/// sender task, HTTP requests) on this runtime. The blocking API additionally
205/// uses `Runtime::block_on` to await pipeline results from synchronous code —
206/// therefore consumer methods must not be called from inside an async context
207/// when using the blocking API.
208pub(crate) fn shared_runtime() -> &'static Runtime {
209 static RUNTIME: OnceLock<Runtime> = OnceLock::new();
210 RUNTIME.get_or_init(|| {
211 tokio::runtime::Builder::new_multi_thread()
212 .worker_threads(1)
213 .thread_name("thinkingdata-runtime")
214 .enable_all()
215 .build()
216 .expect("failed to start the ThinkingData async runtime")
217 })
218}