use super::*;
impl VariantWeight {
pub fn new<S>(name: S, weight_bps: u16) -> Self
where
S: Into<String>,
{
Self {
name: name.into(),
weight_bps: weight_bps.min(BASIS_POINTS_MAX),
}
}
}
impl ExperimentRule {
pub fn new<N, P, D>(name: N, path_prefix: P, default_variant: D) -> Self
where
N: Into<String>,
P: Into<String>,
D: Into<String>,
{
Self {
name: name.into(),
path_prefix: path_prefix.into(),
variants: Vec::new(),
default_variant: default_variant.into(),
}
}
pub fn with_variant<S>(mut self, name: S, weight_bps: u16) -> Self
where
S: Into<String>,
{
self.get_mut_variants()
.push(VariantWeight::new(name, weight_bps));
self
}
}
impl CanaryDecision {
#[inline]
pub fn from_context(ctx: &Context) -> Option<Self> {
ctx.try_get_attribute::<Self, _>(ATTR_CANARY_DECISION)
}
#[inline]
pub fn is_variant(&self, expected: &str) -> bool {
self.get_variant().as_str() == expected
}
}
impl Default for CanaryConfig {
fn default() -> Self {
Self {
experiments: Vec::new(),
sticky_header: DEFAULT_STICKY_HEADER.to_owned(),
sticky_cookie: None,
override_header: Some(DEFAULT_OVERRIDE_HEADER.to_owned()),
variant_response_header: DEFAULT_VARIANT_HEADER.to_owned(),
emit_vary: true,
}
}
}
impl CanaryConfig {
pub fn with_experiment(mut self, rule: ExperimentRule) -> Self {
self.get_mut_experiments().push(rule);
self
}
pub fn with_sticky_header<S>(mut self, header: S) -> Self
where
S: Into<String>,
{
self.set_sticky_header(header.into());
self
}
pub fn with_sticky_cookie<S>(mut self, cookie: S) -> Self
where
S: Into<String>,
{
self.set_sticky_cookie(Some(cookie.into()));
self
}
}
impl CanaryPlugin {
pub fn new(config: CanaryConfig) -> Self {
let mut rules: Vec<CompiledExperiment> = config
.get_experiments()
.iter()
.map(|exp: &ExperimentRule| {
let mut acc: u16 = 0;
let mut cumulative: Vec<(u16, String)> =
Vec::with_capacity(exp.get_variants().len());
for arm in exp.get_variants() {
if arm.get_weight_bps() == 0 {
continue;
}
acc = acc
.saturating_add(arm.get_weight_bps())
.min(BASIS_POINTS_MAX);
cumulative.push((acc, arm.get_name().clone()));
}
CompiledExperiment {
name: exp.get_name().clone(),
prefix: normalize_prefix(exp.get_path_prefix()),
cumulative: cumulative.into_boxed_slice(),
default_variant: exp.get_default_variant().clone(),
}
})
.collect();
rules.sort_by(|a: &CompiledExperiment, b: &CompiledExperiment| {
b.prefix.len().cmp(&a.prefix.len())
});
let sticky_header_lower: String = config.get_sticky_header().trim().to_ascii_lowercase();
let override_header_lower: Option<String> = config
.try_get_override_header()
.as_ref()
.map(|h: &String| h.trim().to_ascii_lowercase())
.filter(|h: &String| !h.is_empty());
let variant_header_lower: String = config
.get_variant_response_header()
.trim()
.to_ascii_lowercase();
Self {
config,
rules: rules.into_boxed_slice(),
sticky_header_lower,
override_header_lower,
variant_header_lower,
}
}
pub fn init(config: CanaryConfig) -> &'static Self {
CANARY_PLUGIN.get_or_init(|| Self::new(config))
}
#[inline(always)]
pub fn get() -> Option<&'static Self> {
CANARY_PLUGIN.get()
}
#[inline]
pub fn evaluate(&self, request: &Request) -> Option<CanaryDecision> {
let Self {
config,
rules,
sticky_header_lower,
override_header_lower,
..
} = self;
let path: &str = request.get_path();
let rule: &CompiledExperiment = rules
.iter()
.find(|r: &&CompiledExperiment| path_matches_prefix(path, &r.prefix))?;
if let Some(ov_header) = override_header_lower
&& let Some(ov_val) = request
.get_headers()
.get(ov_header.as_str())
.and_then(|vals: &VecDeque<String>| vals.back())
{
let trimmed: &str = ov_val.trim();
if !trimmed.is_empty() {
return Some(CanaryDecision {
experiment: rule.name.clone(),
variant: trimmed.to_owned(),
bucket: 0,
overridden: true,
});
}
}
let subject: &str = if !sticky_header_lower.is_empty()
&& let Some(val) = request
.get_headers()
.get(sticky_header_lower.as_str())
.and_then(|vals: &VecDeque<String>| vals.back())
{
val.trim()
} else if let Some(cookie_name) = config.try_get_sticky_cookie()
&& let Some(raw_cookie) = request
.get_headers()
.get(COOKIE)
.and_then(|vals: &VecDeque<String>| vals.back())
&& let Some(found) = find_cookie_slice(raw_cookie, cookie_name)
{
found
} else {
path
};
let bucket: u16 = bucket_basis_points(&rule.name, subject);
for (upper, variant_name) in rule.cumulative.iter() {
if bucket < *upper {
return Some(CanaryDecision {
experiment: rule.name.clone(),
variant: variant_name.clone(),
bucket,
overridden: false,
});
}
}
Some(CanaryDecision {
experiment: rule.name.clone(),
variant: rule.default_variant.clone(),
bucket,
overridden: false,
})
}
#[inline]
pub fn apply_response_headers(&self, ctx: &mut Context) {
let Self {
config,
sticky_header_lower,
variant_header_lower,
..
} = self;
if variant_header_lower.is_empty() {
return;
}
let Some(variant_copy): Option<String> = ctx
.try_get_attribute_ref::<CanaryDecision, _>(ATTR_CANARY_DECISION)
.map(|d: &CanaryDecision| d.get_variant().clone())
else {
return;
};
let response: &mut Response = ctx.get_mut_response();
response.set_header(variant_header_lower.as_str(), variant_copy.as_str());
if config.get_emit_vary() && !sticky_header_lower.is_empty() {
merge_vary_header(response, sticky_header_lower);
}
}
}
impl ServerHook for CanaryRequestHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = CanaryPlugin::get() else {
return Status::Continue;
};
if let Some(decision) = plugin.evaluate(ctx.get_request()) {
ctx.set_attribute(ATTR_CANARY_DECISION, decision);
}
Status::Continue
}
}
impl ServerHook for CanaryResponseHook {
#[inline(always)]
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
#[inline(always)]
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = CanaryPlugin::get() else {
return Status::Continue;
};
plugin.apply_response_headers(ctx);
Status::Continue
}
}