Skip to main content

thinkingdata_core/consumer/
debug_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 debug consumer: reports events one by one and validates them against
16//! the receiver, printing the response on the console.
17//!
18//! Mirrors the Go SDK's `TDDebugConsumer`. Constructing it raises the global
19//! log level to [`TDLogLevel::Debug`](crate::log::TDLogLevel::Debug) — debug
20//! mode implies verbose diagnostics — and marks the consumer as *stringent*,
21//! so property keys are validated against the key pattern.
22
23use std::time::Duration;
24
25use serde::Deserialize;
26
27use crate::data::Data;
28use crate::error::{Result, TDError};
29use crate::log::{TDLogLevel, set_log_level, td_log_error, td_log_info};
30use crate::utils::parse_time;
31
32#[cfg(feature = "async")]
33use crate::consumer::AsyncConsumer;
34#[cfg(feature = "blocking")]
35use crate::consumer::Consumer;
36
37/// Request deadline for debug validation requests, matching the Go SDK's
38/// `DefaultTimeOut`.
39pub const DEFAULT_DEBUG_TIMEOUT_MS: u64 = crate::consumer::DEFAULT_TIMEOUT_MS;
40
41/// The receiver's response envelope: `{"errorLevel": 0}`.
42#[derive(Debug, Deserialize)]
43struct DebugResponse {
44    #[serde(rename = "errorLevel")]
45    error_level: Option<i32>,
46}
47
48/// Validate data against the ThinkingData receiver, one event per request.
49///
50/// `write_data = false` sends a dry run: the receiver validates and replies
51/// but archives nothing — handy during development.
52///
53/// ```no_run
54/// # use thinkingdata_core::consumer::{Consumer, DebugConsumer};
55///
56/// # #[cfg(feature = "blocking")]
57/// # fn main() -> Result<(), thinkingdata_core::TDError> {
58/// # // dry run: validate only, do not archive
59/// # let consumer = DebugConsumer::new("https://receiver.thinkingdata.io", "your_app_id", false)?;
60/// # let data = thinkingdata_core::Data::new(thinkingdata_core::DataType::Track);
61/// # consumer.add(&data)?;
62/// # consumer.close()?;
63/// # Ok(())
64/// # }
65/// ```
66#[derive(Debug, Clone)]
67pub struct DebugConsumer {
68    server_url: String,
69    app_id: String,
70    write_data: bool,
71    device_id: String,
72    client: reqwest::Client,
73}
74
75impl DebugConsumer {
76    /// Create a debug consumer.
77    ///
78    /// * `server_url` — receiver URL; the path is rewritten to `/data_debug`.
79    /// * `app_id` — ThinkingData APP ID.
80    /// * `write_data` — when false, the receiver validates without archiving.
81    pub fn new(server_url: &str, app_id: &str, write_data: bool) -> Result<Self> {
82        Self::with_device_id(server_url, app_id, write_data, "")
83    }
84
85    /// Create a debug consumer bound to a device id, which lets you find the
86    /// validated data in the TE console.
87    pub fn with_device_id(
88        server_url: &str,
89        app_id: &str,
90        write_data: bool,
91        device_id: &str,
92    ) -> Result<Self> {
93        if server_url.is_empty() {
94            let message = "ServerUrl not be empty";
95            td_log_error(message);
96            return Err(TDError::msg(message));
97        }
98        let mut url = url::Url::parse(server_url)?;
99        url.set_path("/data_debug");
100
101        let client = reqwest::Client::builder()
102            .timeout(Duration::from_millis(DEFAULT_DEBUG_TIMEOUT_MS))
103            .build()?;
104
105        let consumer = Self {
106            server_url: url.to_string(),
107            app_id: app_id.to_string(),
108            write_data,
109            device_id: device_id.to_string(),
110            client,
111        };
112
113        // Enable debug logging only after initialization succeeds, matching
114        // the Go SDK.
115        set_log_level(TDLogLevel::Debug);
116        td_log_info(&format!(
117            "Mode: debug consumer, appId: {}, serverUrl: {}",
118            consumer.app_id, consumer.server_url
119        ));
120
121        Ok(consumer)
122    }
123
124    /// Serialize and POST one event as a form request.
125    async fn do_add(&self, data: &Data) -> Result<()> {
126        let json = serde_json::to_string(data)?;
127        // Nested (complex) values may embed RFC 3339 timestamps that the
128        // receiver cannot read; rewrite them like the Go SDK does.
129        let json_str = if data.is_complex {
130            parse_time(&json)
131        } else {
132            json
133        };
134        td_log_info(&json_str);
135
136        let dry_run = if self.write_data { "0" } else { "1" };
137        let mut form = vec![
138            ("data", json_str.as_str()),
139            ("appid", self.app_id.as_str()),
140            ("source", "server"),
141            ("dryRun", dry_run),
142        ];
143        if !self.device_id.is_empty() {
144            form.push(("deviceId", self.device_id.as_str()));
145        }
146
147        let response = self
148            .client
149            .post(&self.server_url)
150            .form(&form)
151            .send()
152            .await?;
153        let status = response.status().as_u16();
154        if status != 200 {
155            return Err(TDError::msg(format!("Unexpected Status Code: {status}")));
156        }
157
158        let body = response.text().await?;
159        let parsed: DebugResponse = serde_json::from_str(&body).map_err(TDError::from)?;
160        match parsed.error_level {
161            Some(0) => {
162                td_log_info("send success");
163                Ok(())
164            }
165            Some(_) => {
166                let message = format!("send to receiver failed with return content:  {body}");
167                td_log_error(&message);
168                Err(TDError::msg(message))
169            }
170            None => Err(TDError::msg(
171                "invalid debug response: errorLevel is missing or null",
172            )),
173        }
174    }
175}
176
177#[cfg(feature = "blocking")]
178impl Consumer for DebugConsumer {
179    /// Serialize and POST one event, blocking until the receiver answers.
180    fn add(&self, data: &Data) -> Result<()> {
181        crate::consumer::shared_runtime().block_on(self.do_add(data))
182    }
183
184    /// The debug consumer sends every event immediately; nothing to flush.
185    fn flush(&self) -> Result<()> {
186        Ok(())
187    }
188
189    /// The debug consumer is stateless; nothing to close.
190    fn close(&self) -> Result<()> {
191        Ok(())
192    }
193
194    /// The debug consumer validates property keys strictly.
195    fn is_stringent(&self) -> bool {
196        true
197    }
198}
199
200#[cfg(feature = "async")]
201#[async_trait::async_trait]
202impl AsyncConsumer for DebugConsumer {
203    /// Serialize and POST one event without blocking the calling task.
204    async fn add_async(&self, data: &Data) -> Result<()> {
205        self.do_add(data).await
206    }
207
208    /// The debug consumer sends every event immediately; nothing to flush.
209    async fn flush_async(&self) -> Result<()> {
210        Ok(())
211    }
212
213    /// The debug consumer is stateless; nothing to close.
214    async fn close_async(&self) -> Result<()> {
215        Ok(())
216    }
217
218    /// The debug consumer validates property keys strictly.
219    fn is_stringent(&self) -> bool {
220        true
221    }
222}