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/// # fn main() -> Result<(), thinkingdata_core::TDError> {
55/// # #[cfg(feature = "blocking")]
56/// # {
57/// # use thinkingdata_core::consumer::{Consumer, DebugConsumer};
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/// # }
64/// # Ok(())
65/// # }
66/// ```
67#[derive(Debug, Clone)]
68pub struct DebugConsumer {
69    server_url: String,
70    app_id: String,
71    write_data: bool,
72    device_id: String,
73    client: reqwest::Client,
74}
75
76impl DebugConsumer {
77    /// Create a debug consumer.
78    ///
79    /// * `server_url` — receiver URL; the path is rewritten to `/data_debug`.
80    /// * `app_id` — ThinkingData APP ID.
81    /// * `write_data` — when false, the receiver validates without archiving.
82    pub fn new(server_url: &str, app_id: &str, write_data: bool) -> Result<Self> {
83        Self::with_device_id(server_url, app_id, write_data, "")
84    }
85
86    /// Create a debug consumer bound to a device id, which lets you find the
87    /// validated data in the TE console.
88    pub fn with_device_id(
89        server_url: &str,
90        app_id: &str,
91        write_data: bool,
92        device_id: &str,
93    ) -> Result<Self> {
94        if server_url.is_empty() {
95            let message = "ServerUrl not be empty";
96            td_log_error(message);
97            return Err(TDError::msg(message));
98        }
99        let mut url = url::Url::parse(server_url)?;
100        url.set_path("/data_debug");
101
102        let client = reqwest::Client::builder()
103            .timeout(Duration::from_millis(DEFAULT_DEBUG_TIMEOUT_MS))
104            .build()?;
105
106        let consumer = Self {
107            server_url: url.to_string(),
108            app_id: app_id.to_string(),
109            write_data,
110            device_id: device_id.to_string(),
111            client,
112        };
113
114        // Enable debug logging only after initialization succeeds, matching
115        // the Go SDK.
116        set_log_level(TDLogLevel::Debug);
117        td_log_info(&format!(
118            "Mode: debug consumer, appId: {}, serverUrl: {}",
119            consumer.app_id, consumer.server_url
120        ));
121
122        Ok(consumer)
123    }
124
125    /// Serialize and POST one event as a form request.
126    async fn do_add(&self, data: &Data) -> Result<()> {
127        let json = serde_json::to_string(data)?;
128        // RFC 3339 timestamps anywhere in the payload — the hoisted `#time`
129        // header, a plain string property, or a nested value — are rewritten
130        // to the receiver format like the log/batch consumers do. The rewrite
131        // is a no-op for payloads already in that format.
132        let json_str = parse_time(&json);
133        td_log_info(&json_str);
134
135        let dry_run = if self.write_data { "0" } else { "1" };
136        let mut form = vec![
137            ("data", json_str.as_str()),
138            ("appid", self.app_id.as_str()),
139            ("source", "server"),
140            ("dryRun", dry_run),
141        ];
142        if !self.device_id.is_empty() {
143            form.push(("deviceId", self.device_id.as_str()));
144        }
145
146        let response = self
147            .client
148            .post(&self.server_url)
149            .form(&form)
150            .send()
151            .await?;
152        let status = response.status().as_u16();
153        if status != 200 {
154            return Err(TDError::msg(format!("Unexpected Status Code: {status}")));
155        }
156
157        let body = response.text().await?;
158        let parsed: DebugResponse = serde_json::from_str(&body).map_err(TDError::from)?;
159        match parsed.error_level {
160            Some(0) => {
161                td_log_info("send success");
162                Ok(())
163            }
164            Some(_) => {
165                let message = format!("send to receiver failed with return content:  {body}");
166                td_log_error(&message);
167                Err(TDError::msg(message))
168            }
169            None => Err(TDError::msg(
170                "invalid debug response: errorLevel is missing or null",
171            )),
172        }
173    }
174}
175
176#[cfg(feature = "blocking")]
177impl Consumer for DebugConsumer {
178    /// Serialize and POST one event, blocking until the receiver answers.
179    fn add(&self, data: &Data) -> Result<()> {
180        crate::consumer::shared_runtime().block_on(self.do_add(data))
181    }
182
183    /// The debug consumer sends every event immediately; nothing to flush.
184    fn flush(&self) -> Result<()> {
185        Ok(())
186    }
187
188    /// The debug consumer is stateless; nothing to close.
189    fn close(&self) -> Result<()> {
190        Ok(())
191    }
192
193    /// The debug consumer validates property keys strictly.
194    fn is_stringent(&self) -> bool {
195        true
196    }
197}
198
199#[cfg(feature = "async")]
200#[async_trait::async_trait]
201impl AsyncConsumer for DebugConsumer {
202    /// Serialize and POST one event without blocking the calling task.
203    async fn add_async(&self, data: &Data) -> Result<()> {
204        self.do_add(data).await
205    }
206
207    /// The debug consumer sends every event immediately; nothing to flush.
208    async fn flush_async(&self) -> Result<()> {
209        Ok(())
210    }
211
212    /// The debug consumer is stateless; nothing to close.
213    async fn close_async(&self) -> Result<()> {
214        Ok(())
215    }
216
217    /// The debug consumer validates property keys strictly.
218    fn is_stringent(&self) -> bool {
219        true
220    }
221}