use std::time::Duration;
use serde::Deserialize;
use crate::data::Data;
use crate::error::{Result, TDError};
use crate::log::{TDLogLevel, set_log_level, td_log_error, td_log_info};
use crate::utils::parse_time;
#[cfg(feature = "async")]
use crate::consumer::AsyncConsumer;
#[cfg(feature = "blocking")]
use crate::consumer::Consumer;
pub const DEFAULT_DEBUG_TIMEOUT_MS: u64 = crate::consumer::DEFAULT_TIMEOUT_MS;
#[derive(Debug, Deserialize)]
struct DebugResponse {
#[serde(rename = "errorLevel")]
error_level: Option<i32>,
}
#[derive(Debug, Clone)]
pub struct DebugConsumer {
server_url: String,
app_id: String,
write_data: bool,
device_id: String,
client: reqwest::Client,
}
impl DebugConsumer {
pub fn new(server_url: &str, app_id: &str, write_data: bool) -> Result<Self> {
Self::with_device_id(server_url, app_id, write_data, "")
}
pub fn with_device_id(
server_url: &str,
app_id: &str,
write_data: bool,
device_id: &str,
) -> Result<Self> {
if server_url.is_empty() {
let message = "ServerUrl not be empty";
td_log_error(message);
return Err(TDError::msg(message));
}
let mut url = url::Url::parse(server_url)?;
url.set_path("/data_debug");
let client = reqwest::Client::builder()
.timeout(Duration::from_millis(DEFAULT_DEBUG_TIMEOUT_MS))
.build()?;
let consumer = Self {
server_url: url.to_string(),
app_id: app_id.to_string(),
write_data,
device_id: device_id.to_string(),
client,
};
set_log_level(TDLogLevel::Debug);
td_log_info(&format!(
"Mode: debug consumer, appId: {}, serverUrl: {}",
consumer.app_id, consumer.server_url
));
Ok(consumer)
}
async fn do_add(&self, data: &Data) -> Result<()> {
let json = serde_json::to_string(data)?;
let json_str = if data.is_complex {
parse_time(&json)
} else {
json
};
td_log_info(&json_str);
let dry_run = if self.write_data { "0" } else { "1" };
let mut form = vec![
("data", json_str.as_str()),
("appid", self.app_id.as_str()),
("source", "server"),
("dryRun", dry_run),
];
if !self.device_id.is_empty() {
form.push(("deviceId", self.device_id.as_str()));
}
let response = self
.client
.post(&self.server_url)
.form(&form)
.send()
.await?;
let status = response.status().as_u16();
if status != 200 {
return Err(TDError::msg(format!("Unexpected Status Code: {status}")));
}
let body = response.text().await?;
let parsed: DebugResponse = serde_json::from_str(&body).map_err(TDError::from)?;
match parsed.error_level {
Some(0) => {
td_log_info("send success");
Ok(())
}
Some(_) => {
let message = format!("send to receiver failed with return content: {body}");
td_log_error(&message);
Err(TDError::msg(message))
}
None => Err(TDError::msg(
"invalid debug response: errorLevel is missing or null",
)),
}
}
}
#[cfg(feature = "blocking")]
impl Consumer for DebugConsumer {
fn add(&self, data: &Data) -> Result<()> {
crate::consumer::shared_runtime().block_on(self.do_add(data))
}
fn flush(&self) -> Result<()> {
Ok(())
}
fn close(&self) -> Result<()> {
Ok(())
}
fn is_stringent(&self) -> bool {
true
}
}
#[cfg(feature = "async")]
#[async_trait::async_trait]
impl AsyncConsumer for DebugConsumer {
async fn add_async(&self, data: &Data) -> Result<()> {
self.do_add(data).await
}
async fn flush_async(&self) -> Result<()> {
Ok(())
}
async fn close_async(&self) -> Result<()> {
Ok(())
}
fn is_stringent(&self) -> bool {
true
}
}