Skip to main content

hyperlane_plugin_canary/
impl.rs

1use super::*;
2
3/// Constructors for [`VariantWeight`].
4impl VariantWeight {
5    /// Creates a weighted variant arm.
6    ///
7    /// # Arguments
8    ///
9    /// - `S` - Variant label.
10    /// - `u16` - Share in basis points (`0..=10_000`, `100` = 1%).
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Variant weight entry.
15    pub fn new<S>(name: S, weight_bps: u16) -> Self
16    where
17        S: Into<String>,
18    {
19        Self {
20            name: name.into(),
21            weight_bps: weight_bps.min(BASIS_POINTS_MAX),
22        }
23    }
24}
25
26/// Constructors for [`ExperimentRule`].
27impl ExperimentRule {
28    /// Creates an [`ExperimentRule`] with `name`, `path_prefix`, and `default_variant`.
29    ///
30    /// # Arguments
31    ///
32    /// - `N` - Experiment name.
33    /// - `P` - Path prefix scope.
34    /// - `D` - Fallback variant label.
35    ///
36    /// # Returns
37    ///
38    /// - `Self` - New experiment rule.
39    pub fn new<N, P, D>(name: N, path_prefix: P, default_variant: D) -> Self
40    where
41        N: Into<String>,
42        P: Into<String>,
43        D: Into<String>,
44    {
45        Self {
46            name: name.into(),
47            path_prefix: path_prefix.into(),
48            variants: Vec::new(),
49            default_variant: default_variant.into(),
50        }
51    }
52
53    /// Appends a weighted variant arm to this experiment.
54    ///
55    /// # Arguments
56    ///
57    /// - `S` - Variant name.
58    /// - `u16` - Share in basis points (`0..=10_000`).
59    ///
60    /// # Returns
61    ///
62    /// - `Self` - Updated experiment rule.
63    pub fn with_variant<S>(mut self, name: S, weight_bps: u16) -> Self
64    where
65        S: Into<String>,
66    {
67        self.get_mut_variants()
68            .push(VariantWeight::new(name, weight_bps));
69        self
70    }
71}
72
73/// Context extraction helpers for [`CanaryDecision`].
74impl CanaryDecision {
75    /// Retrieves the [`CanaryDecision`] attached by [`CanaryRequestHook`] from `ctx`.
76    ///
77    /// # Arguments
78    ///
79    /// - `&Context` - Active request context.
80    ///
81    /// # Returns
82    ///
83    /// - `Option<Self>` - Assigned variant decision, if an experiment matched.
84    #[inline]
85    pub fn from_context(ctx: &Context) -> Option<Self> {
86        ctx.try_get_attribute::<Self, _>(ATTR_CANARY_DECISION)
87    }
88
89    /// Reports whether the selected variant equals `expected`.
90    ///
91    /// # Arguments
92    ///
93    /// - `&str` - Variant name to test.
94    ///
95    /// # Returns
96    ///
97    /// - `bool` - `true` when matched.
98    #[inline]
99    pub fn is_variant(&self, expected: &str) -> bool {
100        self.get_variant().as_str() == expected
101    }
102}
103
104/// Default construction for [`CanaryConfig`].
105impl Default for CanaryConfig {
106    /// Builds a default [`CanaryConfig`] bucketing on `x-user-id` and emitting `x-variant`.
107    ///
108    /// # Returns
109    ///
110    /// - `Self` - Default configuration.
111    fn default() -> Self {
112        Self {
113            experiments: Vec::new(),
114            sticky_header: DEFAULT_STICKY_HEADER.to_owned(),
115            sticky_cookie: None,
116            override_header: Some(DEFAULT_OVERRIDE_HEADER.to_owned()),
117            variant_response_header: DEFAULT_VARIANT_HEADER.to_owned(),
118            emit_vary: true,
119        }
120    }
121}
122
123/// Fluent builders for [`CanaryConfig`].
124impl CanaryConfig {
125    /// Registers an [`ExperimentRule`] in this configuration.
126    ///
127    /// # Arguments
128    ///
129    /// - `ExperimentRule` - Experiment or feature-flag rollout rule.
130    ///
131    /// # Returns
132    ///
133    /// - `Self` - Updated configuration.
134    pub fn with_experiment(mut self, rule: ExperimentRule) -> Self {
135        self.get_mut_experiments().push(rule);
136        self
137    }
138
139    /// Sets the sticky identity header name.
140    ///
141    /// # Arguments
142    ///
143    /// - `S` - Header name.
144    ///
145    /// # Returns
146    ///
147    /// - `Self` - Updated configuration.
148    pub fn with_sticky_header<S>(mut self, header: S) -> Self
149    where
150        S: Into<String>,
151    {
152        self.set_sticky_header(header.into());
153        self
154    }
155
156    /// Sets an optional fallback sticky cookie name.
157    ///
158    /// # Arguments
159    ///
160    /// - `S` - Cookie name.
161    ///
162    /// # Returns
163    ///
164    /// - `Self` - Updated configuration.
165    pub fn with_sticky_cookie<S>(mut self, cookie: S) -> Self
166    where
167        S: Into<String>,
168    {
169        self.set_sticky_cookie(Some(cookie.into()));
170        self
171    }
172}
173
174/// Evaluation and assignment methods for [`CanaryPlugin`].
175impl CanaryPlugin {
176    /// Compiles `config` into sorted cumulative-threshold experiment tables.
177    ///
178    /// # Arguments
179    ///
180    /// - `CanaryConfig` - Canary configuration.
181    ///
182    /// # Returns
183    ///
184    /// - `Self` - Compiled plugin.
185    pub fn new(config: CanaryConfig) -> Self {
186        let mut rules: Vec<CompiledExperiment> = config
187            .get_experiments()
188            .iter()
189            .map(|exp: &ExperimentRule| {
190                let mut acc: u16 = 0;
191                let mut cumulative: Vec<(u16, String)> =
192                    Vec::with_capacity(exp.get_variants().len());
193                for arm in exp.get_variants() {
194                    if arm.get_weight_bps() == 0 {
195                        continue;
196                    }
197                    acc = acc
198                        .saturating_add(arm.get_weight_bps())
199                        .min(BASIS_POINTS_MAX);
200                    cumulative.push((acc, arm.get_name().clone()));
201                }
202                CompiledExperiment {
203                    name: exp.get_name().clone(),
204                    prefix: normalize_prefix(exp.get_path_prefix()),
205                    cumulative: cumulative.into_boxed_slice(),
206                    default_variant: exp.get_default_variant().clone(),
207                }
208            })
209            .collect();
210        rules.sort_by(|a: &CompiledExperiment, b: &CompiledExperiment| {
211            b.prefix.len().cmp(&a.prefix.len())
212        });
213        let sticky_header_lower: String = config.get_sticky_header().trim().to_ascii_lowercase();
214        let override_header_lower: Option<String> = config
215            .try_get_override_header()
216            .as_ref()
217            .map(|h: &String| h.trim().to_ascii_lowercase())
218            .filter(|h: &String| !h.is_empty());
219        let variant_header_lower: String = config
220            .get_variant_response_header()
221            .trim()
222            .to_ascii_lowercase();
223        Self {
224            config,
225            rules: rules.into_boxed_slice(),
226            sticky_header_lower,
227            override_header_lower,
228            variant_header_lower,
229        }
230    }
231
232    /// Initializes the global [`CanaryPlugin`] singleton once.
233    ///
234    /// # Arguments
235    ///
236    /// - `CanaryConfig` - Canary configuration.
237    ///
238    /// # Returns
239    ///
240    /// - `&'static Self` - Reference to the global plugin.
241    pub fn init(config: CanaryConfig) -> &'static Self {
242        CANARY_PLUGIN.get_or_init(|| Self::new(config))
243    }
244
245    /// Returns the initialized global [`CanaryPlugin`], if configured.
246    ///
247    /// # Returns
248    ///
249    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
250    #[inline(always)]
251    pub fn get() -> Option<&'static Self> {
252        CANARY_PLUGIN.get()
253    }
254
255    /// Evaluates the highest-specificity matching experiment for `request`.
256    ///
257    /// # Arguments
258    ///
259    /// - `&Request` - Incoming HTTP request.
260    ///
261    /// # Returns
262    ///
263    /// - `Option<CanaryDecision>` - Selected variant decision when an experiment matches.
264    #[inline]
265    pub fn evaluate(&self, request: &Request) -> Option<CanaryDecision> {
266        let Self {
267            config,
268            rules,
269            sticky_header_lower,
270            override_header_lower,
271            ..
272        } = self;
273        let path: &str = request.get_path();
274        let rule: &CompiledExperiment = rules
275            .iter()
276            .find(|r: &&CompiledExperiment| path_matches_prefix(path, &r.prefix))?;
277        if let Some(ov_header) = override_header_lower
278            && let Some(ov_val) = request
279                .get_headers()
280                .get(ov_header.as_str())
281                .and_then(|vals: &VecDeque<String>| vals.back())
282        {
283            let trimmed: &str = ov_val.trim();
284            if !trimmed.is_empty() {
285                return Some(CanaryDecision {
286                    experiment: rule.name.clone(),
287                    variant: trimmed.to_owned(),
288                    bucket: 0,
289                    overridden: true,
290                });
291            }
292        }
293        let subject: &str = if !sticky_header_lower.is_empty()
294            && let Some(val) = request
295                .get_headers()
296                .get(sticky_header_lower.as_str())
297                .and_then(|vals: &VecDeque<String>| vals.back())
298        {
299            val.trim()
300        } else if let Some(cookie_name) = config.try_get_sticky_cookie()
301            && let Some(raw_cookie) = request
302                .get_headers()
303                .get(COOKIE)
304                .and_then(|vals: &VecDeque<String>| vals.back())
305            && let Some(found) = find_cookie_slice(raw_cookie, cookie_name)
306        {
307            found
308        } else {
309            path
310        };
311        let bucket: u16 = bucket_basis_points(&rule.name, subject);
312        for (upper, variant_name) in rule.cumulative.iter() {
313            if bucket < *upper {
314                return Some(CanaryDecision {
315                    experiment: rule.name.clone(),
316                    variant: variant_name.clone(),
317                    bucket,
318                    overridden: false,
319                });
320            }
321        }
322        Some(CanaryDecision {
323            experiment: rule.name.clone(),
324            variant: rule.default_variant.clone(),
325            bucket,
326            overridden: false,
327        })
328    }
329
330    /// Evaluates matching experiment rules and writes [`CanaryDecision`] directly into `ctx`, reusing unique attribute buffers.
331    ///
332    /// # Arguments
333    ///
334    /// - `&mut Context` - Incoming request context.
335    #[inline]
336    pub(crate) fn evaluate_into_context(&self, ctx: &mut Context) {
337        let Self {
338            config,
339            rules,
340            sticky_header_lower,
341            override_header_lower,
342            ..
343        } = self;
344        let matched: Option<CanaryRuleMatch> = {
345            let request: &Request = ctx.get_request();
346            let path: &str = request.get_path();
347            if let Some((rule_idx, rule)) = rules
348                .iter()
349                .enumerate()
350                .find(|(_, r): &(usize, &CompiledExperiment)| path_matches_prefix(path, &r.prefix))
351            {
352                if let Some(ov_header) = override_header_lower
353                    && let Some(ov_val) = request
354                        .get_headers()
355                        .get(ov_header.as_str())
356                        .and_then(|vals: &VecDeque<String>| vals.back())
357                    && !ov_val.trim().is_empty()
358                {
359                    Some(CanaryRuleMatch {
360                        rule_idx,
361                        arm_idx: None,
362                        override_variant: Some(ov_val.trim().to_owned()),
363                        bucket: 0,
364                        overridden: true,
365                    })
366                } else {
367                    let subject: &str = if !sticky_header_lower.is_empty()
368                        && let Some(val) = request
369                            .get_headers()
370                            .get(sticky_header_lower.as_str())
371                            .and_then(|vals: &VecDeque<String>| vals.back())
372                    {
373                        val.trim()
374                    } else if let Some(cookie_name) = config.try_get_sticky_cookie()
375                        && let Some(raw_cookie) = request
376                            .get_headers()
377                            .get(COOKIE)
378                            .and_then(|vals: &VecDeque<String>| vals.back())
379                        && let Some(found) = find_cookie_slice(raw_cookie, cookie_name)
380                    {
381                        found
382                    } else {
383                        path
384                    };
385                    let bucket: u16 = bucket_basis_points(&rule.name, subject);
386                    let mut arm_idx: Option<usize> = None;
387                    for (idx, (upper, _)) in rule.cumulative.iter().enumerate() {
388                        if bucket < *upper {
389                            arm_idx = Some(idx);
390                            break;
391                        }
392                    }
393                    Some(CanaryRuleMatch {
394                        rule_idx,
395                        arm_idx,
396                        override_variant: None,
397                        bucket,
398                        overridden: false,
399                    })
400                }
401            } else {
402                None
403            }
404        };
405        let Some(CanaryRuleMatch {
406            rule_idx,
407            arm_idx,
408            override_variant,
409            bucket,
410            overridden,
411        }) = matched
412        else {
413            return;
414        };
415        let rule: &CompiledExperiment = &rules[rule_idx];
416        let rule_variant_ref: &str = if let Some(idx) = arm_idx {
417            rule.cumulative[idx].1.as_str()
418        } else {
419            rule.default_variant.as_str()
420        };
421        if let Some(slot) = ctx
422            .get_mut_attributes()
423            .get_mut(ATTR_CANARY_DECISION_MAP_KEY)
424        {
425            if let Some(any_mut) = Arc::get_mut(slot)
426                && let Some(existing) = any_mut.downcast_mut::<CanaryDecision>()
427            {
428                existing.experiment.clear();
429                existing.experiment.push_str(&rule.name);
430                if let Some(ov) = override_variant {
431                    existing.variant = ov;
432                } else {
433                    existing.variant.clear();
434                    existing.variant.push_str(rule_variant_ref);
435                }
436                existing.bucket = bucket;
437                existing.overridden = overridden;
438                return;
439            }
440            let variant_owned: String =
441                override_variant.unwrap_or_else(|| rule_variant_ref.to_owned());
442            *slot = Arc::new(CanaryDecision {
443                experiment: rule.name.clone(),
444                variant: variant_owned,
445                bucket,
446                overridden,
447            });
448            return;
449        }
450        let variant_owned: String = override_variant.unwrap_or_else(|| rule_variant_ref.to_owned());
451        ctx.get_mut_attributes().insert(
452            ATTR_CANARY_DECISION_MAP_KEY.to_owned(),
453            Arc::new(CanaryDecision {
454                experiment: rule.name.clone(),
455                variant: variant_owned,
456                bucket,
457                overridden,
458            }),
459        );
460    }
461
462    /// Emits `X-Variant` and optional `Vary` response headers when a [`CanaryDecision`] is present.
463    ///
464    /// # Arguments
465    ///
466    /// - `&mut Context` - Active request/response context.
467    #[inline]
468    pub fn apply_response_headers(&self, ctx: &mut Context) {
469        let Self {
470            config,
471            sticky_header_lower,
472            variant_header_lower,
473            ..
474        } = self;
475        if variant_header_lower.is_empty() {
476            return;
477        }
478        let mut stack_buf: [u8; VARIANT_STACK_CAP] = [0u8; VARIANT_STACK_CAP];
479        let mut stack_len: Option<usize> = None;
480        let mut heap_copy: Option<String> = None;
481        {
482            let Some(decision) = ctx
483                .get_attributes()
484                .get(ATTR_CANARY_DECISION_MAP_KEY)
485                .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<CanaryDecision>())
486            else {
487                return;
488            };
489            let var_bytes: &[u8] = decision.get_variant().as_bytes();
490            if var_bytes.len() <= VARIANT_STACK_CAP {
491                stack_buf[..var_bytes.len()].copy_from_slice(var_bytes);
492                stack_len = Some(var_bytes.len());
493            } else {
494                heap_copy = Some(decision.get_variant().clone());
495            }
496        }
497        let variant_str: &str = if let Some(len) = stack_len {
498            from_utf8(&stack_buf[..len]).unwrap_or_default()
499        } else if let Some(ref owned) = heap_copy {
500            owned.as_str()
501        } else {
502            return;
503        };
504        let response: &mut Response = ctx.get_mut_response();
505        if config.get_emit_vary() && !sticky_header_lower.is_empty() {
506            if !response.get_headers().contains_key(VARY) {
507                response.set_headers_batch(&[
508                    (variant_header_lower.as_str(), variant_str),
509                    (VARY, sticky_header_lower.as_str()),
510                ]);
511            } else {
512                response.set_header(variant_header_lower.as_str(), variant_str);
513                merge_vary_header(response, sticky_header_lower);
514            }
515        } else {
516            response.set_header(variant_header_lower.as_str(), variant_str);
517        }
518    }
519}
520
521/// Implements [`ServerHook`] for [`CanaryRequestHook`].
522impl ServerHook for CanaryRequestHook {
523    /// Constructs a per-request [`CanaryRequestHook`].
524    ///
525    /// # Arguments
526    ///
527    /// - `&mut Stream` - Connection stream.
528    /// - `&mut Context` - Request context.
529    ///
530    /// # Returns
531    ///
532    /// - `Self` - Hook instance.
533    #[inline(always)]
534    async fn new(_: &mut Stream, _: &mut Context) -> Self {
535        Self
536    }
537
538    /// Synchronously evaluates matching experiment rules and attaches [`CanaryDecision`] without async futures.
539    ///
540    /// # Arguments
541    ///
542    /// - `&mut Stream` - Connection stream.
543    /// - `&mut Context` - Request context.
544    ///
545    /// # Returns
546    ///
547    /// - `Option<Status>` - Always `Some(Status::Continue)`.
548    #[inline(always)]
549    fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option<Status> {
550        let Some(plugin) = CanaryPlugin::get() else {
551            return Some(Status::Continue);
552        };
553        plugin.evaluate_into_context(ctx);
554        Some(Status::Continue)
555    }
556
557    /// Evaluates matching experiment rules and attaches [`CanaryDecision`] to `ctx`.
558    ///
559    /// # Arguments
560    ///
561    /// - `Self` - Hook instance.
562    /// - `&mut Stream` - Connection stream.
563    /// - `&mut Context` - Request context.
564    ///
565    /// # Returns
566    ///
567    /// - `Status` - Always `Status::Continue`.
568    #[inline(always)]
569    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
570        Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue)
571    }
572}
573
574/// Implements [`ServerHook`] for [`CanaryResponseHook`].
575impl ServerHook for CanaryResponseHook {
576    /// Constructs a per-response [`CanaryResponseHook`].
577    ///
578    /// # Arguments
579    ///
580    /// - `&mut Stream` - Connection stream.
581    /// - `&mut Context` - Request context.
582    ///
583    /// # Returns
584    ///
585    /// - `Self` - Hook instance.
586    #[inline(always)]
587    async fn new(_: &mut Stream, _: &mut Context) -> Self {
588        Self
589    }
590
591    /// Synchronously writes configured variant and `Vary` headers onto the outgoing response without async futures.
592    ///
593    /// # Arguments
594    ///
595    /// - `&mut Stream` - Connection stream.
596    /// - `&mut Context` - Request context.
597    ///
598    /// # Returns
599    ///
600    /// - `Option<Status>` - Always `Some(Status::Continue)`.
601    #[inline(always)]
602    fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option<Status> {
603        let Some(plugin) = CanaryPlugin::get() else {
604            return Some(Status::Continue);
605        };
606        plugin.apply_response_headers(ctx);
607        Some(Status::Continue)
608    }
609
610    /// Writes configured variant and `Vary` headers onto the outgoing response.
611    ///
612    /// # Arguments
613    ///
614    /// - `Self` - Hook instance.
615    /// - `&mut Stream` - Connection stream.
616    /// - `&mut Context` - Request context.
617    ///
618    /// # Returns
619    ///
620    /// - `Status` - Always `Status::Continue`.
621    #[inline(always)]
622    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
623        Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue)
624    }
625}