use crate::ids::{MAX_ID, check_id};
use crate::{Error, Result, Timestamp};
use semver::Version;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
pub const MAX_DEPTH: usize = 16;
pub const MAX_NODES: usize = 256;
pub const MAX_IN: usize = 64;
pub const BUCKETS: u16 = 10_000;
pub const BUILTIN_ATTRS: &[&str] = &[
"app_version",
"base_release",
"channel",
"platform",
"os",
"os_version",
"arch",
"package_type",
"store",
"device_class",
"form_factor",
"locale",
"region",
];
pub const CUSTOM_PREFIX: &str = "custom.";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Value {
Str(String),
Int(i64),
Bool(bool),
Version(Version),
}
impl From<&str> for Value {
fn from(s: &str) -> Self {
Self::Str(s.to_owned())
}
}
impl From<String> for Value {
fn from(s: String) -> Self {
Self::Str(s)
}
}
impl From<i64> for Value {
fn from(n: i64) -> Self {
Self::Int(n)
}
}
impl From<bool> for Value {
fn from(b: bool) -> Self {
Self::Bool(b)
}
}
impl From<Version> for Value {
fn from(v: Version) -> Self {
Self::Version(v)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum CmpOp {
Lt,
Le,
Gt,
Ge,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Rule {
True,
All(Vec<Rule>),
Any(Vec<Rule>),
Not(Box<Rule>),
Eq {
attr: String,
value: Value,
},
In {
attr: String,
values: Vec<Value>,
},
Cmp {
attr: String,
op: CmpOp,
value: Value,
},
StartsWith {
attr: String,
prefix: String,
},
Cohort(String),
Window {
from: Timestamp,
until: Timestamp,
},
}
fn check_attr(attr: &str) -> Result<()> {
let ok =
BUILTIN_ATTRS.contains(&attr) || (attr.len() > CUSTOM_PREFIX.len() && attr.starts_with(CUSTOM_PREFIX) && check_id("attribute", attr).is_ok());
if !ok {
return Err(Error::Rule(format!("unknown attribute {attr:?}; custom attributes start with {CUSTOM_PREFIX:?}")));
}
Ok(())
}
fn check_value(v: &Value) -> Result<()> {
if let Value::Str(s) = v
&& s.len() > MAX_ID * 2
{
return Err(Error::Rule("string value too long".into()));
}
Ok(())
}
impl Rule {
pub fn validate(&self) -> Result<()> {
let mut nodes = 0;
self.validate_at(1, &mut nodes)
}
fn validate_at(&self, depth: usize, nodes: &mut usize) -> Result<()> {
*nodes += 1;
if depth > MAX_DEPTH {
return Err(Error::Rule(format!("nested deeper than {MAX_DEPTH}")));
}
if *nodes > MAX_NODES {
return Err(Error::Rule(format!("more than {MAX_NODES} nodes")));
}
match self {
Self::True => {}
Self::All(rules) | Self::Any(rules) => {
for r in rules {
r.validate_at(depth + 1, nodes)?;
}
}
Self::Not(r) => r.validate_at(depth + 1, nodes)?,
Self::Eq { attr, value } => {
check_attr(attr)?;
check_value(value)?;
}
Self::In { attr, values } => {
check_attr(attr)?;
if values.is_empty() || values.len() > MAX_IN {
return Err(Error::Rule(format!("`in` needs 1..={MAX_IN} values")));
}
values.iter().try_for_each(check_value)?;
}
Self::Cmp { attr, value, .. } => {
check_attr(attr)?;
if !matches!(value, Value::Int(_) | Value::Version(_)) {
return Err(Error::Rule("ordered comparisons take an integer or a version".into()));
}
}
Self::StartsWith { attr, prefix } => {
check_attr(attr)?;
check_value(&Value::Str(prefix.clone()))?;
}
Self::Cohort(name) => check_id("cohort", name).map_err(|e| Error::Rule(e.to_string()))?,
Self::Window { from, until } => {
if from >= until {
return Err(Error::Rule("window must end after it starts".into()));
}
}
}
Ok(())
}
pub fn evaluate(&self, device: &Device) -> bool {
match self {
Self::True => true,
Self::All(rules) => rules.iter().all(|r| r.evaluate(device)),
Self::Any(rules) => rules.iter().any(|r| r.evaluate(device)),
Self::Not(r) => !r.evaluate(device),
Self::Eq { attr, value } => device.attr(attr).is_some_and(|v| v == value),
Self::In { attr, values } => device.attr(attr).is_some_and(|v| values.contains(v)),
Self::Cmp { attr, op, value } => {
let ord = match (device.attr(attr), value) {
(Some(Value::Int(a)), Value::Int(b)) => a.cmp(b),
(Some(Value::Version(a)), Value::Version(b)) => a.cmp(b),
_ => return false,
};
match op {
CmpOp::Lt => ord.is_lt(),
CmpOp::Le => ord.is_le(),
CmpOp::Gt => ord.is_gt(),
CmpOp::Ge => ord.is_ge(),
}
}
Self::StartsWith { attr, prefix } => matches!(device.attr(attr), Some(Value::Str(s)) if s.starts_with(prefix.as_str())),
Self::Cohort(name) => device.cohorts.contains(name),
Self::Window { from, until } => *from <= device.now && device.now < *until,
}
}
}
#[derive(Clone)]
pub struct Device {
attrs: BTreeMap<String, Value>,
cohorts: BTreeSet<String>,
bucket_secret: [u8; 32],
pub now: Timestamp,
}
impl Device {
pub fn new(bucket_secret: [u8; 32], now: Timestamp) -> Self {
Self { attrs: BTreeMap::new(), cohorts: BTreeSet::new(), bucket_secret, now }
}
pub fn set(&mut self, attr: &str, value: impl Into<Value>) -> Result<&mut Self> {
check_attr(attr)?;
self.attrs.insert(attr.to_owned(), value.into());
Ok(self)
}
pub fn join_cohort(&mut self, name: &str) -> &mut Self {
self.cohorts.insert(name.to_owned());
self
}
pub fn attr(&self, attr: &str) -> Option<&Value> {
self.attrs.get(attr)
}
pub fn bucket(&self, update_id: &str) -> u16 {
let mut h = blake3::Hasher::new_keyed(&self.bucket_secret);
h.update(b"weirdnet-update/v1/bucket\0");
h.update(update_id.as_bytes());
let out = h.finalize();
let mut first = [0u8; 8];
first.copy_from_slice(&out.as_bytes()[..8]);
(u64::from_le_bytes(first) % u64::from(BUCKETS)) as u16
}
}
impl fmt::Debug for Device {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Device")
.field("attrs", &self.attrs)
.field("cohorts", &self.cohorts)
.field("bucket_secret", &"<redacted>")
.field("now", &self.now)
.finish()
}
}