|
| 1 | +use serde_json::Value; |
| 2 | + |
| 3 | +use crate::error::Error; |
| 4 | +use crate::http::{construct_request, submit_request, RequestPrep}; |
| 5 | +use crate::jobs; |
| 6 | + |
| 7 | +byond_fn!( |
| 8 | + fn influxdb2_publish(data, endpoint, token) { |
| 9 | + let data = data.to_owned(); |
| 10 | + let endpoint = endpoint.to_owned(); |
| 11 | + let token = token.to_owned(); |
| 12 | + Some(jobs::start(move || { |
| 13 | + fn handle(data: &str, endpoint: &str, token: &str) -> Result<RequestPrep, Error> { |
| 14 | + let mut lines = vec!(); |
| 15 | + |
| 16 | + let data: Value = serde_json::from_str(data)?; |
| 17 | + for entry in data.as_array().unwrap() { |
| 18 | + let entry = entry.as_object().ok_or(Error::InvalidMetrics)?; |
| 19 | + |
| 20 | + let measurement = entry.get("@measurement").ok_or(Error::InvalidMetrics)?.as_str().ok_or(Error::InvalidMetrics)?.to_owned(); |
| 21 | + let mut measurement_tags = vec!{measurement}; |
| 22 | + |
| 23 | + let tags = entry.get("@tags").ok_or(Error::InvalidMetrics)?.as_object().ok_or(Error::InvalidMetrics)?; |
| 24 | + for (key, val) in tags { |
| 25 | + measurement_tags.push(concat_string!(key, "=", val.as_str().ok_or(Error::InvalidMetrics)?)) |
| 26 | + }; |
| 27 | + |
| 28 | + let mut fields = vec!{}; |
| 29 | + for (key, val) in entry { |
| 30 | + if key.starts_with('@') { |
| 31 | + continue; |
| 32 | + } |
| 33 | + fields.push(concat_string!(key, "=", val.to_string())) |
| 34 | + }; |
| 35 | + |
| 36 | + let timestamp = entry.get("@timestamp").ok_or(Error::InvalidMetrics)?.as_str().ok_or(Error::InvalidMetrics)?; |
| 37 | + lines.push(concat_string!(measurement_tags.join(","), " ", fields.join(",") , " ", timestamp)); |
| 38 | + } |
| 39 | + |
| 40 | + construct_request( |
| 41 | + "post", |
| 42 | + endpoint, |
| 43 | + lines.join("\n").as_str(), |
| 44 | + concat_string!("{\"Authorization\":\"Token ", token ,"\"}").as_str(), |
| 45 | + "" |
| 46 | + ) |
| 47 | + } |
| 48 | + |
| 49 | + let req = match handle(data.as_str(), endpoint.as_str(), token.as_str()) { |
| 50 | + Ok(r) => r, |
| 51 | + Err(e) => return e.to_string() |
| 52 | + }; |
| 53 | + match submit_request(req) { |
| 54 | + Ok(r) => r, |
| 55 | + Err(e) => e.to_string() |
| 56 | + } |
| 57 | + })) |
| 58 | + } |
| 59 | +); |
0 commit comments