hyperlane-plugin-canary 23.3.2

A deterministic feature-flag, A/B testing, and progressive canary rollout plugin for the Hyperlane framework with XxHash3_64 basis-point sticky bucketing, header overrides, Context CanaryDecision injection, and X-Variant/Vary headers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use super::*;

/// Constructors for [`VariantWeight`].
impl VariantWeight {
    /// Creates a weighted variant arm.
    ///
    /// # Arguments
    ///
    /// - `S` - Variant label.
    /// - `u16` - Share in basis points (`0..=10_000`, `100` = 1%).
    ///
    /// # Returns
    ///
    /// - `Self` - Variant weight entry.
    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),
        }
    }
}

/// Constructors for [`ExperimentRule`].
impl ExperimentRule {
    /// Creates an [`ExperimentRule`] with `name`, `path_prefix`, and `default_variant`.
    ///
    /// # Arguments
    ///
    /// - `N` - Experiment name.
    /// - `P` - Path prefix scope.
    /// - `D` - Fallback variant label.
    ///
    /// # Returns
    ///
    /// - `Self` - New experiment rule.
    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(),
        }
    }

    /// Appends a weighted variant arm to this experiment.
    ///
    /// # Arguments
    ///
    /// - `S` - Variant name.
    /// - `u16` - Share in basis points (`0..=10_000`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated experiment rule.
    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
    }
}

/// Context extraction helpers for [`CanaryDecision`].
impl CanaryDecision {
    /// Retrieves the [`CanaryDecision`] attached by [`CanaryRequestHook`] from `ctx`.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Active request context.
    ///
    /// # Returns
    ///
    /// - `Option<Self>` - Assigned variant decision, if an experiment matched.
    #[inline]
    pub fn from_context(ctx: &Context) -> Option<Self> {
        ctx.try_get_attribute::<Self, _>(ATTR_CANARY_DECISION)
    }

    /// Reports whether the selected variant equals `expected`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Variant name to test.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when matched.
    #[inline]
    pub fn is_variant(&self, expected: &str) -> bool {
        self.get_variant().as_str() == expected
    }
}

/// Default construction for [`CanaryConfig`].
impl Default for CanaryConfig {
    /// Builds a default [`CanaryConfig`] bucketing on `x-user-id` and emitting `x-variant`.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    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,
        }
    }
}

/// Fluent builders for [`CanaryConfig`].
impl CanaryConfig {
    /// Registers an [`ExperimentRule`] in this configuration.
    ///
    /// # Arguments
    ///
    /// - `ExperimentRule` - Experiment or feature-flag rollout rule.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_experiment(mut self, rule: ExperimentRule) -> Self {
        self.get_mut_experiments().push(rule);
        self
    }

    /// Sets the sticky identity header name.
    ///
    /// # Arguments
    ///
    /// - `S` - Header name.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_sticky_header<S>(mut self, header: S) -> Self
    where
        S: Into<String>,
    {
        self.set_sticky_header(header.into());
        self
    }

    /// Sets an optional fallback sticky cookie name.
    ///
    /// # Arguments
    ///
    /// - `S` - Cookie name.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_sticky_cookie<S>(mut self, cookie: S) -> Self
    where
        S: Into<String>,
    {
        self.set_sticky_cookie(Some(cookie.into()));
        self
    }
}

/// Evaluation and assignment methods for [`CanaryPlugin`].
impl CanaryPlugin {
    /// Compiles `config` into sorted cumulative-threshold experiment tables.
    ///
    /// # Arguments
    ///
    /// - `CanaryConfig` - Canary configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Compiled plugin.
    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,
        }
    }

    /// Initializes the global [`CanaryPlugin`] singleton once.
    ///
    /// # Arguments
    ///
    /// - `CanaryConfig` - Canary configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init(config: CanaryConfig) -> &'static Self {
        CANARY_PLUGIN.get_or_init(|| Self::new(config))
    }

    /// Returns the initialized global [`CanaryPlugin`], if configured.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        CANARY_PLUGIN.get()
    }

    /// Evaluates the highest-specificity matching experiment for `request`.
    ///
    /// # Arguments
    ///
    /// - `&Request` - Incoming HTTP request.
    ///
    /// # Returns
    ///
    /// - `Option<CanaryDecision>` - Selected variant decision when an experiment matches.
    #[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,
        })
    }

    /// Emits `X-Variant` and optional `Vary` response headers when a [`CanaryDecision`] is present.
    ///
    /// # Arguments
    ///
    /// - `&mut Context` - Active request/response context.
    #[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);
        }
    }
}

/// Implements [`ServerHook`] for [`CanaryRequestHook`].
impl ServerHook for CanaryRequestHook {
    /// Constructs a per-request [`CanaryRequestHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Evaluates matching experiment rules and attaches [`CanaryDecision`] to `ctx`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    #[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
    }
}

/// Implements [`ServerHook`] for [`CanaryResponseHook`].
impl ServerHook for CanaryResponseHook {
    /// Constructs a per-response [`CanaryResponseHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Writes configured variant and `Vary` headers onto the outgoing response.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    #[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
    }
}