Skip to main content

relay_ua/
lib.rs

1//! User agent parser with built-in rules.
2//!
3//! # Test Performance
4//!
5//! Adding user agent parsing to your module will incur a latency penalty on first use. Because of
6//! this, integration tests could fail. To fix this, you will need to add a timeout to your
7//! consumer.
8
9use std::borrow::Cow;
10use std::cell::RefCell;
11use std::sync::LazyLock;
12
13use ua_parser::{Extractor, Regexes};
14
15/// The family used when a user agent, device, or operating system could not be detected.
16const UNKNOWN_FAMILY: &str = "Other";
17
18/// Describes the family as well as the major, minor, and patch versions of a user agent client.
19#[derive(Clone, Debug, Eq, Hash, PartialEq)]
20pub struct UserAgent<'a> {
21    /// The family of the user agent client, for example `Chrome`.
22    pub family: Cow<'a, str>,
23    /// The major version of the user agent client.
24    pub major: Option<Cow<'a, str>>,
25    /// The minor version of the user agent client.
26    pub minor: Option<Cow<'a, str>>,
27    /// The patch version of the user agent client.
28    pub patch: Option<Cow<'a, str>>,
29}
30
31impl Default for UserAgent<'_> {
32    fn default() -> Self {
33        Self {
34            family: Cow::Borrowed(UNKNOWN_FAMILY),
35            major: None,
36            minor: None,
37            patch: None,
38        }
39    }
40}
41
42/// Describes the family as well as the major, minor, patch, and patch minor versions of an
43/// operating system.
44#[derive(Clone, Debug, Eq, Hash, PartialEq)]
45pub struct OS<'a> {
46    /// The family of the operating system, for example `Windows`.
47    pub family: Cow<'a, str>,
48    /// The major version of the operating system.
49    pub major: Option<Cow<'a, str>>,
50    /// The minor version of the operating system.
51    pub minor: Option<Cow<'a, str>>,
52    /// The patch version of the operating system.
53    pub patch: Option<Cow<'a, str>>,
54    /// The patch minor version of the operating system.
55    pub patch_minor: Option<Cow<'a, str>>,
56}
57
58impl Default for OS<'_> {
59    fn default() -> Self {
60        Self {
61            family: Cow::Borrowed(UNKNOWN_FAMILY),
62            major: None,
63            minor: None,
64            patch: None,
65            patch_minor: None,
66        }
67    }
68}
69
70/// Describes the family, brand, and model of a device.
71#[derive(Clone, Debug, Eq, Hash, PartialEq)]
72pub struct Device<'a> {
73    /// The family of the device, for example `iPhone`.
74    pub family: Cow<'a, str>,
75    /// The brand of the device, for example `Apple`.
76    pub brand: Option<Cow<'a, str>>,
77    /// The model of the device.
78    pub model: Option<Cow<'a, str>>,
79}
80
81impl Default for Device<'_> {
82    fn default() -> Self {
83        Self {
84            family: Cow::Borrowed(UNKNOWN_FAMILY),
85            brand: None,
86            model: None,
87        }
88    }
89}
90
91/// A [`Extractor`] already configured with the user agent database.
92static UA_PARSER: LazyLock<Extractor<'static>> = LazyLock::new(|| {
93    let ua_regexes = include_bytes!("../uap-core/regexes.yaml");
94    let regexes: Regexes<'_> =
95        serde_yaml::from_slice(ua_regexes).expect("user agent regexes to be valid");
96    Extractor::try_from(regexes).expect("user agent regexes to be valid")
97});
98
99/// Initializes the user agent parser.
100///
101/// This loads and compiles user agent patterns, which takes a few seconds to complete. The user
102/// agent parser initializes on-demand when using one of the parse methods. This function forces
103/// initialization at a convenient point without introducing unwanted delays.
104pub fn init_parser() {
105    LazyLock::force(&UA_PARSER);
106}
107
108/// Returns the family and version of a user agent client.
109///
110/// Defaults to an empty user agent.
111pub fn parse_user_agent(user_agent: &str) -> UserAgent<'_> {
112    // The same user agent is often parsed many times in a row: once for every log, span or trace
113    // metric in a container, and once more by inbound filters after normalization. Each thread
114    // remembers its last result.
115    thread_local! {
116        static LAST: RefCell<Option<(String, UserAgent<'static>)>> = const { RefCell::new(None) };
117    }
118
119    LAST.with_borrow_mut(|last| {
120        if let Some((raw, parsed)) = last
121            && raw == user_agent
122        {
123            return parsed.clone();
124        }
125
126        let parsed = extract_user_agent(user_agent);
127        let owned = UserAgent {
128            family: Cow::Owned(parsed.family.into_owned()),
129            major: parsed.major.map(|v| Cow::Owned(v.into_owned())),
130            minor: parsed.minor.map(|v| Cow::Owned(v.into_owned())),
131            patch: parsed.patch.map(|v| Cow::Owned(v.into_owned())),
132        };
133        *last = Some((user_agent.to_owned(), owned.clone()));
134        owned
135    })
136}
137
138fn extract_user_agent(user_agent: &str) -> UserAgent<'_> {
139    let Some(value) = UA_PARSER.ua.extract(user_agent) else {
140        return UserAgent::default();
141    };
142
143    UserAgent {
144        family: family_or_unknown(value.family),
145        major: non_empty(value.major.map(Cow::Borrowed)),
146        minor: non_empty(value.minor.map(Cow::Borrowed)),
147        patch: non_empty(value.patch.map(Cow::Borrowed)),
148    }
149}
150
151/// Returns the family, brand, and model of the device of the requesting client.
152///
153/// Defaults to an empty device.
154pub fn parse_device(user_agent: &str) -> Device<'_> {
155    let Some(value) = UA_PARSER.dev.extract(user_agent) else {
156        return Device::default();
157    };
158
159    Device {
160        family: family_or_unknown(value.device),
161        brand: non_empty(value.brand),
162        model: non_empty(value.model),
163    }
164}
165
166/// Returns the family and version of the operating system of the requesting client.
167///
168/// Defaults to an empty operating system.
169pub fn parse_os(user_agent: &str) -> OS<'_> {
170    let Some(value) = UA_PARSER.os.extract(user_agent) else {
171        return OS::default();
172    };
173
174    OS {
175        family: family_or_unknown(value.os),
176        major: non_empty(value.major),
177        minor: non_empty(value.minor),
178        patch: non_empty(value.patch),
179        patch_minor: non_empty(value.patch_minor),
180    }
181}
182
183fn family_or_unknown(family: Cow<'_, str>) -> Cow<'_, str> {
184    match family.is_empty() {
185        true => Cow::Borrowed(UNKNOWN_FAMILY),
186        false => family,
187    }
188}
189
190fn non_empty(value: Option<Cow<'_, str>>) -> Option<Cow<'_, str>> {
191    value.filter(|value| !value.is_empty())
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    const FIREFOX_ON_MAC: &str =
199        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:160.0) Gecko/20100101 Firefox/160.0";
200    const IPHONE: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1.2 Mobile/15E148 Safari/604.1";
201
202    #[test]
203    fn test_parse_firefox_on_mac() {
204        insta::assert_debug_snapshot!(parse_user_agent(FIREFOX_ON_MAC), @r#"
205        UserAgent {
206            family: "Firefox",
207            major: Some(
208                "160",
209            ),
210            minor: Some(
211                "0",
212            ),
213            patch: None,
214        }
215        "#);
216        insta::assert_debug_snapshot!(parse_os(FIREFOX_ON_MAC), @r#"
217        OS {
218            family: "Mac OS X",
219            major: Some(
220                "10",
221            ),
222            minor: Some(
223                "15",
224            ),
225            patch: None,
226            patch_minor: None,
227        }
228        "#);
229        insta::assert_debug_snapshot!(parse_device(FIREFOX_ON_MAC), @r#"
230        Device {
231            family: "Mac",
232            brand: Some(
233                "Apple",
234            ),
235            model: Some(
236                "Mac",
237            ),
238        }
239        "#);
240    }
241
242    #[test]
243    fn test_parse_iphone() {
244        insta::assert_debug_snapshot!(parse_user_agent(IPHONE), @r#"
245        UserAgent {
246            family: "Mobile Safari",
247            major: Some(
248                "17",
249            ),
250            minor: Some(
251                "1",
252            ),
253            patch: Some(
254                "2",
255            ),
256        }
257        "#);
258        insta::assert_debug_snapshot!(parse_os(IPHONE), @r#"
259        OS {
260            family: "iOS",
261            major: Some(
262                "17",
263            ),
264            minor: Some(
265                "1",
266            ),
267            patch: Some(
268                "2",
269            ),
270            patch_minor: None,
271        }
272        "#);
273        insta::assert_debug_snapshot!(parse_device(IPHONE), @r#"
274        Device {
275            family: "iPhone",
276            brand: Some(
277                "Apple",
278            ),
279            model: Some(
280                "iPhone",
281            ),
282        }
283        "#);
284    }
285
286    #[test]
287    fn test_parse_unknown_user_agent() {
288        let user_agent = "some user agent";
289
290        assert_eq!(parse_user_agent(user_agent), Default::default());
291        assert_eq!(parse_os(user_agent), Default::default());
292        assert_eq!(parse_device(user_agent), Default::default());
293
294        insta::assert_debug_snapshot!(parse_user_agent(user_agent), @r#"
295        UserAgent {
296            family: "Other",
297            major: None,
298            minor: None,
299            patch: None,
300        }
301        "#);
302        insta::assert_debug_snapshot!(parse_os(user_agent), @r#"
303        OS {
304            family: "Other",
305            major: None,
306            minor: None,
307            patch: None,
308            patch_minor: None,
309        }
310        "#);
311        insta::assert_debug_snapshot!(parse_device(user_agent), @r#"
312        Device {
313            family: "Other",
314            brand: None,
315            model: None,
316        }
317        "#);
318    }
319
320    #[test]
321    fn test_parse_user_agent_repeated() {
322        for ua in [
323            IPHONE,
324            IPHONE,
325            FIREFOX_ON_MAC,
326            IPHONE,
327            "",
328            "",
329            FIREFOX_ON_MAC,
330        ] {
331            assert_eq!(
332                parse_user_agent(ua),
333                extract_user_agent(ua),
334                "input: {ua:?}"
335            );
336        }
337    }
338}