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        // Nested (complex) values may embed RFC 3339 timestamps that the
129        // receiver cannot read; rewrite them like the Go SDK does.
130        let json_str = if data.is_complex {
131            parse_time(&json)
132        } else {
133            json
134        };
135        td_log_info(&json_str);
136
137        let dry_run = if self.write_data { "0" } else { "1" };
138        let mut form = vec![
139            ("data", json_str.as_str()),
140            ("appid", self.app_id.as_str()),
141            ("source", "server"),
142            ("dryRun", dry_run),
143        ];
144        if !self.device_id.is_empty() {
145            form.push(("deviceId", self.device_id.as_str()));
146        }
147
148        let response = self
149            .client
150            .post(&self.server_url)
151            .form(&form)
152            .send()
153            .await?;
154        let status = response.status().as_u16();
155        if status != 200 {
156            return Err(TDError::msg(format!("Unexpected Status Code: {status}")));
157        }
158
159        let body = response.text().await?;
160        let parsed: DebugResponse = serde_json::from_str(&body).map_err(TDError::from)?;
161        match parsed.error_level {
162            Some(0) => {
163                td_log_info("send success");
164                Ok(())
165            }
166            Some(_) => {
167                let message = format!("send to receiver failed with return content:  {body}");
168                td_log_error(&message);
169                Err(TDError::msg(message))
170            }
171            None => Err(TDError::msg(
172                "invalid debug response: errorLevel is missing or null",
173            )),
174        }
175    }
176}
177
178#[cfg(feature = "blocking")]
179impl Consumer for DebugConsumer {
180    /// Serialize and POST one event, blocking until the receiver answers.
181    fn add(&self, data: &Data) -> Result<()> {
182        crate::consumer::shared_runtime().block_on(self.do_add(data))
183    }
184
185    /// The debug consumer sends every event immediately; nothing to flush.
186    fn flush(&self) -> Result<()> {
187        Ok(())
188    }
189
190    /// The debug consumer is stateless; nothing to close.
191    fn close(&self) -> Result<()> {
192        Ok(())
193    }
194
195    /// The debug consumer validates property keys strictly.
196    fn is_stringent(&self) -> bool {
197        true
198    }
199}
200
201#[cfg(feature = "async")]
202#[async_trait::async_trait]
203impl AsyncConsumer for DebugConsumer {
204    /// Serialize and POST one event without blocking the calling task.
205    async fn add_async(&self, data: &Data) -> Result<()> {
206        self.do_add(data).await
207    }
208
209    /// The debug consumer sends every event immediately; nothing to flush.
210    async fn flush_async(&self) -> Result<()> {
211        Ok(())
212    }
213
214    /// The debug consumer is stateless; nothing to close.
215    async fn close_async(&self) -> Result<()> {
216        Ok(())
217    }
218
219    /// The debug consumer validates property keys strictly.
220    fn is_stringent(&self) -> bool {
221        true
222    }
223}