1use crate::ids::{MAX_ID, check_id};
9use crate::{Error, Result, Timestamp};
10use semver::Version;
11use serde::{Deserialize, Serialize};
12use std::collections::{BTreeMap, BTreeSet};
13use std::fmt;
14
15pub const MAX_DEPTH: usize = 16;
17pub const MAX_NODES: usize = 256;
19pub const MAX_IN: usize = 64;
21pub const BUCKETS: u16 = 10_000;
23
24pub const BUILTIN_ATTRS: &[&str] = &[
26 "app_version",
27 "base_release",
28 "channel",
29 "platform",
30 "os",
31 "os_version",
32 "arch",
33 "package_type",
34 "store",
35 "device_class",
36 "form_factor",
37 "locale",
38 "region",
39];
40
41pub const CUSTOM_PREFIX: &str = "custom.";
43
44#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(rename_all = "kebab-case")]
47pub enum Value {
48 Str(String),
50 Int(i64),
52 Bool(bool),
54 Version(Version),
56}
57
58impl From<&str> for Value {
59 fn from(s: &str) -> Self {
60 Self::Str(s.to_owned())
61 }
62}
63
64impl From<String> for Value {
65 fn from(s: String) -> Self {
66 Self::Str(s)
67 }
68}
69
70impl From<i64> for Value {
71 fn from(n: i64) -> Self {
72 Self::Int(n)
73 }
74}
75
76impl From<bool> for Value {
77 fn from(b: bool) -> Self {
78 Self::Bool(b)
79 }
80}
81
82impl From<Version> for Value {
83 fn from(v: Version) -> Self {
84 Self::Version(v)
85 }
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "kebab-case")]
91#[allow(missing_docs)]
92pub enum CmpOp {
93 Lt,
94 Le,
95 Gt,
96 Ge,
97}
98
99#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "kebab-case")]
102pub enum Rule {
103 True,
105 All(Vec<Rule>),
107 Any(Vec<Rule>),
109 Not(Box<Rule>),
111 Eq {
113 attr: String,
115 value: Value,
117 },
118 In {
120 attr: String,
122 values: Vec<Value>,
124 },
125 Cmp {
127 attr: String,
129 op: CmpOp,
131 value: Value,
133 },
134 StartsWith {
136 attr: String,
138 prefix: String,
140 },
141 Cohort(String),
143 Window {
145 from: Timestamp,
147 until: Timestamp,
149 },
150}
151
152fn check_attr(attr: &str) -> Result<()> {
153 let ok =
154 BUILTIN_ATTRS.contains(&attr) || (attr.len() > CUSTOM_PREFIX.len() && attr.starts_with(CUSTOM_PREFIX) && check_id("attribute", attr).is_ok());
155 if !ok {
156 return Err(Error::Rule(format!("unknown attribute {attr:?}; custom attributes start with {CUSTOM_PREFIX:?}")));
157 }
158 Ok(())
159}
160
161fn check_value(v: &Value) -> Result<()> {
162 if let Value::Str(s) = v
163 && s.len() > MAX_ID * 2
164 {
165 return Err(Error::Rule("string value too long".into()));
166 }
167 Ok(())
168}
169
170impl Rule {
171 pub fn validate(&self) -> Result<()> {
173 let mut nodes = 0;
174 self.validate_at(1, &mut nodes)
175 }
176
177 fn validate_at(&self, depth: usize, nodes: &mut usize) -> Result<()> {
178 *nodes += 1;
179 if depth > MAX_DEPTH {
180 return Err(Error::Rule(format!("nested deeper than {MAX_DEPTH}")));
181 }
182 if *nodes > MAX_NODES {
183 return Err(Error::Rule(format!("more than {MAX_NODES} nodes")));
184 }
185 match self {
186 Self::True => {}
187 Self::All(rules) | Self::Any(rules) => {
188 for r in rules {
189 r.validate_at(depth + 1, nodes)?;
190 }
191 }
192 Self::Not(r) => r.validate_at(depth + 1, nodes)?,
193 Self::Eq { attr, value } => {
194 check_attr(attr)?;
195 check_value(value)?;
196 }
197 Self::In { attr, values } => {
198 check_attr(attr)?;
199 if values.is_empty() || values.len() > MAX_IN {
200 return Err(Error::Rule(format!("`in` needs 1..={MAX_IN} values")));
201 }
202 values.iter().try_for_each(check_value)?;
203 }
204 Self::Cmp { attr, value, .. } => {
205 check_attr(attr)?;
206 if !matches!(value, Value::Int(_) | Value::Version(_)) {
207 return Err(Error::Rule("ordered comparisons take an integer or a version".into()));
208 }
209 }
210 Self::StartsWith { attr, prefix } => {
211 check_attr(attr)?;
212 check_value(&Value::Str(prefix.clone()))?;
213 }
214 Self::Cohort(name) => check_id("cohort", name).map_err(|e| Error::Rule(e.to_string()))?,
215 Self::Window { from, until } => {
216 if from >= until {
217 return Err(Error::Rule("window must end after it starts".into()));
218 }
219 }
220 }
221 Ok(())
222 }
223
224 pub fn evaluate(&self, device: &Device) -> bool {
226 match self {
227 Self::True => true,
228 Self::All(rules) => rules.iter().all(|r| r.evaluate(device)),
229 Self::Any(rules) => rules.iter().any(|r| r.evaluate(device)),
230 Self::Not(r) => !r.evaluate(device),
231 Self::Eq { attr, value } => device.attr(attr).is_some_and(|v| v == value),
232 Self::In { attr, values } => device.attr(attr).is_some_and(|v| values.contains(v)),
233 Self::Cmp { attr, op, value } => {
234 let ord = match (device.attr(attr), value) {
235 (Some(Value::Int(a)), Value::Int(b)) => a.cmp(b),
236 (Some(Value::Version(a)), Value::Version(b)) => a.cmp(b),
237 _ => return false,
238 };
239 match op {
240 CmpOp::Lt => ord.is_lt(),
241 CmpOp::Le => ord.is_le(),
242 CmpOp::Gt => ord.is_gt(),
243 CmpOp::Ge => ord.is_ge(),
244 }
245 }
246 Self::StartsWith { attr, prefix } => matches!(device.attr(attr), Some(Value::Str(s)) if s.starts_with(prefix.as_str())),
247 Self::Cohort(name) => device.cohorts.contains(name),
248 Self::Window { from, until } => *from <= device.now && device.now < *until,
249 }
250 }
251}
252
253#[derive(Clone)]
255pub struct Device {
256 attrs: BTreeMap<String, Value>,
257 cohorts: BTreeSet<String>,
258 bucket_secret: [u8; 32],
259 pub now: Timestamp,
261}
262
263impl Device {
264 pub fn new(bucket_secret: [u8; 32], now: Timestamp) -> Self {
267 Self { attrs: BTreeMap::new(), cohorts: BTreeSet::new(), bucket_secret, now }
268 }
269
270 pub fn set(&mut self, attr: &str, value: impl Into<Value>) -> Result<&mut Self> {
272 check_attr(attr)?;
273 self.attrs.insert(attr.to_owned(), value.into());
274 Ok(self)
275 }
276
277 pub fn join_cohort(&mut self, name: &str) -> &mut Self {
279 self.cohorts.insert(name.to_owned());
280 self
281 }
282
283 pub fn attr(&self, attr: &str) -> Option<&Value> {
285 self.attrs.get(attr)
286 }
287
288 pub fn bucket(&self, update_id: &str) -> u16 {
291 let mut h = blake3::Hasher::new_keyed(&self.bucket_secret);
292 h.update(b"weirdnet-update/v1/bucket\0");
293 h.update(update_id.as_bytes());
294 let out = h.finalize();
295 let mut first = [0u8; 8];
296 first.copy_from_slice(&out.as_bytes()[..8]);
297 (u64::from_le_bytes(first) % u64::from(BUCKETS)) as u16
298 }
299}
300
301impl fmt::Debug for Device {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 f.debug_struct("Device")
304 .field("attrs", &self.attrs)
305 .field("cohorts", &self.cohorts)
306 .field("bucket_secret", &"<redacted>")
307 .field("now", &self.now)
308 .finish()
309 }
310}