Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add IntervalData struct #5205

Merged
merged 6 commits into from
Oct 28, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES_UNRELEASED.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ Use the template below to make assigning a version number during the release cut

### What's Changed
- Disabled Glean events recorded when the SDK is not ready for a feature ([#5185](https://github.com/mozilla/application-services/pull/5185))
- Add struct for IntervalData (behavioral targeting) ([#5205](https://github.com/mozilla/application-services/pull/5205))
177 changes: 177 additions & 0 deletions components/nimbus/src/behavior.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
#![allow(dead_code)]

use crate::error::{BehaviorError, NimbusError, Result};
use chrono::{DateTime, Timelike, Utc};
use std::collections::{HashMap, VecDeque};

#[derive(Clone)]
enum Interval {
MINUTES,
HOURS,
DAYS,
WEEKS,
MONTHS,
YEARS,
jeddai marked this conversation as resolved.
Show resolved Hide resolved
}

#[derive(Clone)]
struct IntervalConfig {
bucket_count: usize,
interval: Interval,
}

pub struct IntervalData {
buckets: VecDeque<u64>,
bucket_count: usize,
starting_instant: DateTime<Utc>,
}

impl Default for IntervalData {
fn default() -> Self {
Self::new(1)
}
}

impl IntervalData {
pub fn new(bucket_count: usize) -> IntervalData {
let mut data = IntervalData {
buckets: VecDeque::new(),
jeddai marked this conversation as resolved.
Show resolved Hide resolved
bucket_count: bucket_count,
starting_instant: Utc::now(),
};
data.buckets.push_front(0);
data
}

fn increment(&mut self) -> Result<()> {
match self.buckets.front_mut() {
Some(x) => *x += 1,
None => {
return Err(NimbusError::BehaviorError(BehaviorError::InvalidState(
"Interval buckets cannot be empty".to_string(),
)))
}
};
Ok(())
}

fn rotate(&mut self, num_rotations: u64) -> Result<()> {
jeddai marked this conversation as resolved.
Show resolved Hide resolved
for _ in 1..=num_rotations {
jeddai marked this conversation as resolved.
Show resolved Hide resolved
self.buckets.push_front(0)
}
if self.buckets.len() > self.bucket_count {
self.buckets.drain((self.bucket_count - 1)..);
}
Ok(())
}
}

struct SingleIntervalCounter {
data: IntervalData,
config: IntervalConfig,
}

fn date_diff(a: DateTime<Utc>, b: DateTime<Utc>) -> u32 {
(a.date() - b.date()).num_days().try_into().unwrap()
jeddai marked this conversation as resolved.
Show resolved Hide resolved
}

impl SingleIntervalCounter {
fn new(interval_config: IntervalConfig) -> SingleIntervalCounter {
SingleIntervalCounter {
data: IntervalData::new(interval_config.bucket_count.clone()),
config: interval_config.clone(),
}
}

fn increment(&mut self) -> Result<()> {
self.data.increment()
}

fn maybe_advance(&mut self, now: DateTime<Utc>) -> Result<()> {
let then = self.data.starting_instant;
let rotations: u32 = match self.config.interval {
Interval::MINUTES => now.minute() - then.minute(),
Interval::HOURS => now.hour() - then.hour(),
Interval::DAYS => date_diff(now, then),
Interval::WEEKS => date_diff(now, then) / 7,
Interval::MONTHS => date_diff(now, then) / 28,
Interval::YEARS => date_diff(now, then) / 365,
};
if rotations > 0 {
return self.data.rotate(rotations.into());
}
jeddai marked this conversation as resolved.
Show resolved Hide resolved
Ok(())
}
}

struct MultiIntervalCounter {
intervals: HashMap<i64, SingleIntervalCounter>,
}

impl MultiIntervalCounter {
fn increment(&mut self) -> Result<()> {
self.intervals
.iter_mut()
.try_for_each(|(_, v)| v.increment())
}

fn maybe_advance(&mut self, now: DateTime<Utc>) -> Result<()> {
self.intervals
.iter_mut()
.try_for_each(|(_, v)| v.maybe_advance(now))
}
}

#[cfg(test)]
jeddai marked this conversation as resolved.
Show resolved Hide resolved
mod date_diff_tests {
use super::*;

#[test]
fn diffs_dates_ignoring_time() -> Result<()> {
let date1 = DateTime::parse_from_rfc3339("2022-10-26T08:00:00Z").unwrap();
let date2 = DateTime::parse_from_rfc3339("2022-10-27T01:00:00Z").unwrap();
assert!(matches!(
date_diff(date2.with_timezone(&Utc), date1.with_timezone(&Utc)),
1
));
Ok(())
}
}

#[cfg(test)]
mod interval_data_tests {
use super::*;

#[test]
fn increment_works_if_no_buckets_present() -> Result<()> {
let mut interval = IntervalData {
buckets: VecDeque::new(),
bucket_count: 7,
starting_instant: Utc::now(),
};
let result = interval.increment();

assert!(matches!(result.is_err(), true));
Ok(())
}

#[test]
fn increment_increments_front_bucket_if_it_exists() -> Result<()> {
let mut interval = IntervalData::new(7);
let result = interval.increment();

assert!(matches!(result.is_err(), false));
assert!(matches!(interval.buckets[0], 1));
Ok(())
}

#[test]
fn rotate_adds_buckets_for_each_rotation() -> Result<()> {
let mut interval = IntervalData::new(7);
let result = interval.rotate(3);

assert!(matches!(result.is_err(), false));
assert!(matches!(interval.buckets.len(), 4));
Ok(())
}
}
8 changes: 8 additions & 0 deletions components/nimbus/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ pub enum NimbusError {
DatabaseNotReady,
#[error("Error parsing a sting into a version {0}")]
VersionParsingError(String),
#[error("Behavior error: {0}")]
BehaviorError(#[from] BehaviorError),
}

#[derive(Debug, thiserror::Error)]
pub enum BehaviorError {
#[error("Invalid state: {0}")]
InvalidState(String),
}

impl<'a> From<jexl_eval::error::EvaluationError<'a>> for NimbusError {
Expand Down
1 change: 1 addition & 0 deletions components/nimbus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

mod behavior;
mod dbcache;
mod enrollment;
pub mod error;
Expand Down
2 changes: 1 addition & 1 deletion components/nimbus/src/nimbus.udl
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ enum NimbusError {
"TryFromSliceError", "EmptyRatiosError", "OutOfBoundsError","UrlParsingError",
"RequestError", "ResponseError", "UuidError", "InvalidExperimentFormat",
"InvalidPath", "InternalError", "NoSuchExperiment", "NoSuchBranch", "BackoffError",
"DatabaseNotReady", "VersionParsingError"
"DatabaseNotReady", "VersionParsingError", "BehaviorError"
};

interface NimbusClient {
Expand Down