|
| 1 | +//! Routing-token boundary truncation shared by the HTTP, PD and gRPC |
| 2 | +//! selection paths. |
| 3 | +
|
| 4 | +use crate::observability::metrics::Metrics; |
| 5 | + |
| 6 | +/// Slice `tokens` at the first configured boundary id. Content past a |
| 7 | +/// boundary is never shareable across conversations, and match ratios over |
| 8 | +/// the full sequence shrink as conversations grow. |
| 9 | +pub(crate) fn truncate_slice<'a>( |
| 10 | + tokens: &'a [u32], |
| 11 | + boundaries: &[u32], |
| 12 | + router_type: &'static str, |
| 13 | +) -> &'a [u32] { |
| 14 | + if boundaries.is_empty() { |
| 15 | + return tokens; |
| 16 | + } |
| 17 | + match tokens.iter().position(|id| boundaries.contains(id)) { |
| 18 | + Some(cut) => { |
| 19 | + Metrics::record_routing_tokens_truncated(router_type); |
| 20 | + &tokens[..cut] |
| 21 | + } |
| 22 | + None => tokens, |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +/// Owned variant: truncates in place, no reallocation. |
| 27 | +pub(crate) fn truncate_owned( |
| 28 | + mut tokens: Vec<u32>, |
| 29 | + boundaries: &[u32], |
| 30 | + router_type: &'static str, |
| 31 | +) -> Vec<u32> { |
| 32 | + let keep = truncate_slice(&tokens, boundaries, router_type).len(); |
| 33 | + tokens.truncate(keep); |
| 34 | + tokens |
| 35 | +} |
| 36 | + |
| 37 | +#[cfg(test)] |
| 38 | +mod tests { |
| 39 | + use super::*; |
| 40 | + |
| 41 | + #[test] |
| 42 | + fn cuts_at_first_of_several_boundaries() { |
| 43 | + assert_eq!( |
| 44 | + truncate_slice(&[1, 2, 900, 3, 901], &[900, 901], "http"), |
| 45 | + &[1, 2] |
| 46 | + ); |
| 47 | + assert_eq!( |
| 48 | + truncate_owned(vec![1, 2, 901, 3, 900], &[900, 901], "http"), |
| 49 | + vec![1, 2] |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn boundary_first_yields_empty() { |
| 55 | + assert_eq!(truncate_slice(&[900, 1], &[900], "http"), &[] as &[u32]); |
| 56 | + assert_eq!( |
| 57 | + truncate_owned(vec![900, 1], &[900], "http"), |
| 58 | + Vec::<u32>::new() |
| 59 | + ); |
| 60 | + } |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn no_boundaries_or_no_match_is_identity() { |
| 64 | + assert_eq!(truncate_slice(&[1, 900, 2], &[], "http"), &[1, 900, 2]); |
| 65 | + assert_eq!(truncate_slice(&[1, 2, 3], &[900], "http"), &[1, 2, 3]); |
| 66 | + assert_eq!(truncate_owned(vec![1, 2], &[900], "http"), vec![1, 2]); |
| 67 | + } |
| 68 | +} |
0 commit comments