use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextValue {
pub value: String,
}
impl ContextValue {
pub fn new(value: impl Into<String>) -> Self {
Self {
value: value.into(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attribute {
pub key: String,
pub values: Vec<ContextValue>,
}
impl Attribute {
pub fn new(key: impl Into<String>, values: Vec<impl Into<String>>) -> Self {
Self {
key: key.into(),
values: values.into_iter().map(ContextValue::new).collect(),
}
}
pub fn get_values(&self) -> Vec<&str> {
self.values.iter().map(|v| v.value.as_str()).collect()
}
pub fn add_value(mut self, value: impl Into<String>) -> Self {
self.values.push(ContextValue::new(value));
self
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Context {
#[serde(rename = "type")]
pub context_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attributes: Vec<Attribute>,
}
impl Context {
pub fn new(context_type: impl Into<String>) -> Self {
Self {
context_type: context_type.into(),
name: None,
identifier: None,
attributes: Vec::new(),
}
}
pub fn single(
context_type: impl Into<String>,
identifier: impl Into<String>,
name: Option<impl Into<String>>,
) -> Self {
let context = Self {
context_type: context_type.into(),
identifier: None,
name: name.map(Into::into),
attributes: Vec::new(),
};
context.with_identifier(identifier)
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn with_identifier(mut self, identifier: impl Into<String>) -> Self {
let identifier = identifier.into();
self.identifier = (!identifier.is_empty()).then_some(identifier);
self
}
pub fn add_attribute(mut self, attribute: Attribute) -> Self {
match self
.attributes
.iter_mut()
.find(|existing| existing.key == attribute.key)
{
Some(existing) => *existing = attribute,
None => self.attributes.push(attribute),
}
self
}
pub fn get_attribute(&self, key: &str) -> Option<&Attribute> {
self.attributes.iter().find(|attr| attr.key == key)
}
pub fn is_anonymous(&self) -> bool {
self.context_type == "anonymous"
&& self.name.is_none()
&& self.identifier.is_none()
&& self.attributes.is_empty()
}
}
impl Default for Context {
fn default() -> Self {
Self::new("anonymous")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_repeated_attribute_key_replaces_the_earlier_one() {
let context = Context::new("user")
.add_attribute(Attribute::new("plan", vec!["free"]))
.add_attribute(Attribute::new("country", vec!["US"]))
.add_attribute(Attribute::new("plan", vec!["pro"]));
assert_eq!(context.attributes.len(), 2);
assert_eq!(
context.get_attribute("plan").map(Attribute::get_values),
Some(vec!["pro"])
);
}
#[test]
fn empty_identifier_is_treated_as_missing() {
let context = Context::single("anonymous", "", None::<String>);
assert_eq!(context.identifier, None);
assert!(context.is_anonymous());
assert_eq!(
serde_json::to_value(&context).unwrap(),
serde_json::json!({"type": "anonymous"})
);
}
#[test]
fn context_round_trips_through_json() {
let context = Context::single("user", "user-42", Some("Ada"))
.add_attribute(Attribute::new("country", vec!["US"]));
let json = serde_json::to_string(&context).unwrap();
assert_eq!(serde_json::from_str::<Context>(&json).unwrap(), context);
}
#[test]
fn context_json_shape_matches_api_contract() {
let context = Context::single("user", "user-42", Some("Ada"))
.add_attribute(Attribute::new("country", vec!["US", "CA"]));
let json = serde_json::to_value(context).expect("serialize");
assert_eq!(json["type"], "user");
assert_eq!(json["identifier"], "user-42");
assert_eq!(json["name"], "Ada");
assert_eq!(json["attributes"][0]["key"], "country");
assert_eq!(json["attributes"][0]["values"][0]["value"], "US");
}
}