use std::collections::BTreeMap;
use std::time::{SystemTime, UNIX_EPOCH};
use serde::Serialize;
pub const MAX_METRICS: usize = 100;
pub const MAX_DIMENSIONS: usize = 30;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub enum Unit {
Count,
Milliseconds,
Bytes,
Percent,
None,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Metrics {
namespace: String,
dimensions: BTreeMap<String, String>,
metrics: Vec<(String, Unit)>,
values: BTreeMap<String, f64>,
properties: BTreeMap<String, serde_json::Value>,
}
impl Metrics {
#[must_use]
pub fn new(namespace: impl Into<String>) -> Self {
Self {
namespace: namespace.into(),
dimensions: BTreeMap::new(),
metrics: Vec::new(),
values: BTreeMap::new(),
properties: BTreeMap::new(),
}
}
#[must_use]
pub fn dimension(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
let name = name.into();
if self.dimensions.len() < MAX_DIMENSIONS || self.dimensions.contains_key(&name) {
self.dimensions.insert(name, value.into());
}
self
}
#[must_use]
pub fn metric(mut self, name: impl Into<String>, value: f64, unit: Unit) -> Self {
let name = name.into();
match self.values.entry(name) {
std::collections::btree_map::Entry::Occupied(mut existing) => {
existing.insert(value);
}
std::collections::btree_map::Entry::Vacant(slot) => {
if self.metrics.len() < MAX_METRICS {
self.metrics.push((slot.key().clone(), unit));
slot.insert(value);
}
}
}
self
}
#[must_use]
pub fn property(
mut self,
name: impl Into<String>,
value: impl Into<serde_json::Value>,
) -> Self {
self.properties.insert(name.into(), value.into());
self
}
pub fn to_json(&self, at: SystemTime) -> Result<String, crate::RuntimeError> {
if self.values.values().any(|value| !value.is_finite()) {
return Err(crate::RuntimeError::message("metric values must be finite"));
}
if self.dimensions.keys().any(|name| {
name == "_aws" || self.values.contains_key(name) || self.properties.contains_key(name)
}) || self
.values
.keys()
.any(|name| name == "_aws" || self.properties.contains_key(name))
|| self.properties.contains_key("_aws")
{
return Err(crate::RuntimeError::message(
"metric, dimension and property names must be distinct and cannot be _aws",
));
}
let timestamp = at.duration_since(UNIX_EPOCH).unwrap_or_default();
let mut root = serde_json::Map::new();
root.insert(
"_aws".to_owned(),
serde_json::json!({
"Timestamp": timestamp.as_millis() as u64,
"CloudWatchMetrics": [{
"Namespace": self.namespace,
"Dimensions": [self.dimensions.keys().collect::<Vec<_>>()],
"Metrics": self.metrics.iter().map(|(name, unit)| serde_json::json!({ "Name": name, "Unit": unit })).collect::<Vec<_>>(),
}],
}),
);
for (name, value) in &self.dimensions {
root.insert(name.clone(), serde_json::Value::String(value.clone()));
}
for (name, value) in &self.values {
root.insert(name.clone(), serde_json::json!(value));
}
for (name, value) in &self.properties {
root.insert(name.clone(), value.clone());
}
serde_json::to_string(&root)
.map_err(|error| crate::RuntimeError::other("serializing metrics", error))
}
#[must_use]
pub fn len(&self) -> usize {
self.metrics.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.metrics.is_empty()
}
}