use std::sync::Arc;
use serde_json::Value;
use crate::envelope::Envelope;
use crate::error::Error;
use crate::links::warn_uncharacterised_write;
use crate::routes;
use crate::transport::{RequestBody, Transport};
const REPORTER_DATA_DEPRECATION: &str = "The reporter_data parameter of create_burst_reporter is \
deprecated and will be removed in 9.0.0; the API operation takes no body.";
const DEPRECATED_BODY_OPERATION: &str =
"request live-usage burst with a deprecated body for network";
#[derive(Debug)]
pub struct BurstReportersApi {
transport: Arc<Transport>,
}
impl BurstReportersApi {
#[must_use]
pub fn new(transport: Arc<Transport>) -> Self {
Self { transport }
}
pub async fn create_burst_reporter(
&self,
network_id: &str,
reporter_data: Option<Value>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let reporter_data = reporter_data.filter(|data| !data.is_null());
if reporter_data.is_some() {
tracing::warn!("{REPORTER_DATA_DEPRECATION}");
}
let url =
routes::CREATE_BURST_REPORTER.resolve(self.transport.api_host(), network_id, parent)?;
let body = match reporter_data {
Some(data) if json_truthy(&data) => {
warn_uncharacterised_write(DEPRECATED_BODY_OPERATION);
RequestBody::Json(data)
}
_ => RequestBody::EmptyJsonString,
};
self.transport
.request(routes::CREATE_BURST_REPORTER.method.clone(), url, &[], body)
.await
}
}
fn json_truthy(value: &Value) -> bool {
match value {
Value::Null => false,
Value::Bool(flag) => *flag,
Value::Number(number) => number.as_f64().is_none_or(|float| float != 0.0),
Value::String(text) => !text.is_empty(),
Value::Array(items) => !items.is_empty(),
Value::Object(fields) => !fields.is_empty(),
}
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use super::json_truthy;
#[test]
fn python_falsy_values_are_falsy() {
for falsy in [
json!(null),
json!(false),
json!(0),
json!(0.0),
json!(-0.0),
json!(""),
json!([]),
json!({}),
] {
assert!(!json_truthy(&falsy), "{falsy} must be falsy");
}
}
#[test]
fn every_other_value_is_truthy() {
for truthy in [
json!(true),
json!(1),
json!(-1),
json!(0.5),
json!(" "),
json!("0"),
json!("false"),
json!([null]),
json!([0]),
json!({"type": "burst"}),
json!({"": null}),
] {
assert!(json_truthy(&truthy), "{truthy} must be truthy");
}
assert!(json_truthy(&Value::from(u64::MAX)));
}
}