Debian Codegraph @

third_party/rust/suggest/src/query.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use std::collections::HashSet;
6
7 use crate::{LabeledTimingSample, Suggestion, SuggestionProvider, SuggestionProviderConstraints};
8
9 /// A query for suggestions to show in the address bar.
10 #[derive(Clone, Debug, Default, uniffi::Record)]
11 pub struct SuggestionQuery {
12 pub keyword: String,
13 pub providers: Vec<SuggestionProvider>,
14 #[uniffi(default = None)]
15 pub provider_constraints: Option<SuggestionProviderConstraints>,
16 #[uniffi(default = None)]
17 pub limit: Option<i32>,
18 }
19
20 #[derive(uniffi::Record)]
21 pub struct QueryWithMetricsResult {
22 pub suggestions: Vec<Suggestion>,
23 /// Samples for the `suggest.query_time` metric
24 pub query_times: Vec<LabeledTimingSample>,
25 }
26
27 impl SuggestionQuery {
28 // Builder style methods for creating queries (mostly used by the test code)
29
30 pub fn all_providers(keyword: &str) -> Self {
31 Self {
32 keyword: keyword.to_string(),
33 providers: Vec::from(SuggestionProvider::all()),
34 ..Self::default()
35 }
36 }
37
38 pub fn with_providers(keyword: &str, providers: Vec<SuggestionProvider>) -> Self {
39 Self {
40 keyword: keyword.to_string(),
41 providers,
42 ..Self::default()
43 }
44 }
45
46 pub fn all_providers_except(keyword: &str, provider: SuggestionProvider) -> Self {
47 Self::with_providers(
48 keyword,
49 SuggestionProvider::all()
50 .into_iter()
51 .filter(|p| *p != provider)
52 .collect(),
53 )
54 }
55
56 pub fn amp(keyword: &str) -> Self {
57 Self {
58 keyword: keyword.into(),
59 providers: vec![SuggestionProvider::Amp],
60 ..Self::default()
61 }
62 }
63
64 pub fn wikipedia(keyword: &str) -> Self {
65 Self {
66 keyword: keyword.into(),
67 providers: vec![SuggestionProvider::Wikipedia],
68 ..Self::default()
69 }
70 }
71
72 pub fn amo(keyword: &str) -> Self {
73 Self {
74 keyword: keyword.into(),
75 providers: vec![SuggestionProvider::Amo],
76 ..Self::default()
77 }
78 }
79
80 pub fn pocket(keyword: &str) -> Self {
81 Self {
82 keyword: keyword.into(),
83 providers: vec![SuggestionProvider::Pocket],
84 ..Self::default()
85 }
86 }
87
88 pub fn yelp(keyword: &str) -> Self {
89 Self {
90 keyword: keyword.into(),
91 providers: vec![SuggestionProvider::Yelp],
92 ..Self::default()
93 }
94 }
95
96 pub fn mdn(keyword: &str) -> Self {
97 Self {
98 keyword: keyword.into(),
99 providers: vec![SuggestionProvider::Mdn],
100 ..Self::default()
101 }
102 }
103
104 pub fn fakespot(keyword: &str) -> Self {
105 Self {
106 keyword: keyword.into(),
107 providers: vec![SuggestionProvider::Fakespot],
108 ..Self::default()
109 }
110 }
111
112 pub fn weather(keyword: &str) -> Self {
113 Self {
114 keyword: keyword.into(),
115 providers: vec![SuggestionProvider::Weather],
116 ..Self::default()
117 }
118 }
119
120 pub fn dynamic(keyword: &str, suggestion_types: &[&str]) -> Self {
121 Self {
122 keyword: keyword.into(),
123 providers: vec![SuggestionProvider::Dynamic],
124 provider_constraints: Some(SuggestionProviderConstraints {
125 dynamic_suggestion_types: Some(
126 suggestion_types.iter().map(|s| s.to_string()).collect(),
127 ),
128 ..SuggestionProviderConstraints::default()
129 }),
130 ..Self::default()
131 }
132 }
133
134 pub fn limit(self, limit: i32) -> Self {
135 Self {
136 limit: Some(limit),
137 ..self
138 }
139 }
140
141 /// Create an FTS query term for our keyword(s)
142 pub(crate) fn fts_query(&self) -> FtsQuery<'_> {
143 FtsQuery::new(&self.keyword)
144 }
145 }
146
147 pub struct FtsQuery<'a> {
148 pub match_arg: String,
149 pub match_arg_without_prefix_match: String,
150 pub is_prefix_query: bool,
151 keyword_terms: Vec<&'a str>,
152 }
153
154 impl<'a> FtsQuery<'a> {
155 fn new(keyword: &'a str) -> Self {
156 // Parse the `keyword` field into a set of keywords.
157 //
158 // This is used when passing the keywords into an FTS search. It:
159 // - Strips out any `():^*"` chars. These are typically used for advanced searches, which
160 // we don't support and it would be weird to only support for FTS searches.
161 // - splits on whitespace to get a list of individual keywords
162 let keywords = Self::split_terms(keyword);
163 if keywords.is_empty() {
164 return Self {
165 keyword_terms: keywords,
166 match_arg: String::from(r#""""#),
167 match_arg_without_prefix_match: String::from(r#""""#),
168 is_prefix_query: false,
169 };
170 }
171 // Quote each term from `query` and join them together
172 let mut sqlite_match = keywords
173 .iter()
174 .map(|keyword| format!(r#""{keyword}""#))
175 .collect::<Vec<_>>()
176 .join(" ");
177 // If the input is > 3 characters, and there's no whitespace at the end.
178 // We want to append a `*` char to the end to do a prefix match on it.
179 let total_chars = keywords.iter().fold(0, |count, s| count + s.len());
180 let query_ends_in_whitespace = keyword.ends_with(' ');
181 let prefix_match = (total_chars > 3) && !query_ends_in_whitespace;
182 let sqlite_match_without_prefix_match = sqlite_match.clone();
183 if prefix_match {
184 sqlite_match.push('*');
185 }
186 Self {
187 keyword_terms: keywords,
188 is_prefix_query: prefix_match,
189 match_arg: sqlite_match,
190 match_arg_without_prefix_match: sqlite_match_without_prefix_match,
191 }
192 }
193
194 /// Try to figure out if a FTS match required stemming
195 ///
196 /// To test this, we have to try to mimic the SQLite FTS logic. This code doesn't do it
197 /// perfectly, but it should return the correct result most of the time.
198 pub fn match_required_stemming(&self, title: &str) -> bool {
199 let title = title.to_lowercase();
200 let split_title = Self::split_terms(&title);
201
202 !self.keyword_terms.iter().enumerate().all(|(i, keyword)| {
203 split_title.iter().any(|title_word| {
204 let last_keyword = i == self.keyword_terms.len() - 1;
205
206 if last_keyword && self.is_prefix_query {
207 title_word.starts_with(keyword)
208 } else {
209 title_word == keyword
210 }
211 })
212 })
213 }
214
215 fn split_terms(phrase: &str) -> Vec<&str> {
216 phrase
217 .split([' ', '(', ')', ':', '^', '*', '"', ','])
218 .filter(|s| !s.is_empty())
219 .collect()
220 }
221 }
222
223 /// Given a list of full keywords, create an FTS string to match against.
224 ///
225 /// Creates a string with de-duped keywords.
226 pub fn full_keywords_to_fts_content<'a>(
227 full_keywords: impl IntoIterator<Item = &'a str>,
228 ) -> String {
229 let parts: HashSet<_> = full_keywords
230 .into_iter()
231 .flat_map(str::split_whitespace)
232 .map(str::to_lowercase)
233 .collect();
234 let mut result = String::new();
235 for (i, part) in parts.into_iter().enumerate() {
236 if i != 0 {
237 result.push(' ');
238 }
239 result.push_str(&part);
240 }
241 result
242 }
243
244 #[cfg(test)]
245 mod test {
246 use super::*;
247 use std::collections::HashMap;
248
249 fn check_parse_keywords(input: &str, expected: Vec<&str>) {
250 let query = SuggestionQuery::all_providers(input);
251 assert_eq!(query.fts_query().keyword_terms, expected);
252 }
253
254 #[test]
255 fn test_quote() {
256 check_parse_keywords("foo", vec!["foo"]);
257 check_parse_keywords("foo bar", vec!["foo", "bar"]);
258 // Special chars should be stripped
259 check_parse_keywords("\"foo()* ^bar:\"", vec!["foo", "bar"]);
260 // test some corner cases
261 check_parse_keywords("", vec![]);
262 check_parse_keywords(" ", vec![]);
263 check_parse_keywords(" foo bar ", vec!["foo", "bar"]);
264 check_parse_keywords("foo:bar", vec!["foo", "bar"]);
265 }
266
267 fn check_fts_query(input: &str, expected: &str) {
268 let query = SuggestionQuery::all_providers(input);
269 assert_eq!(query.fts_query().match_arg, expected);
270 }
271
272 #[test]
273 fn test_fts_query() {
274 // String with < 3 chars shouldn't get a prefix query
275 check_fts_query("r", r#""r""#);
276 check_fts_query("ru", r#""ru""#);
277 check_fts_query("run", r#""run""#);
278 // After 3 chars, we should append `*` to the last term to make it a prefix query
279 check_fts_query("runn", r#""runn"*"#);
280 check_fts_query("running", r#""running"*"#);
281 // The total number of chars is counted, not the number of chars in the last term
282 check_fts_query("running s", r#""running" "s"*"#);
283 // if the input ends in whitespace, then don't do a prefix query
284 check_fts_query("running ", r#""running""#);
285 // Special chars are filtered out
286 check_fts_query("running*\"()^: s", r#""running" "s"*"#);
287 check_fts_query("running *\"()^: s", r#""running" "s"*"#);
288 // Special chars shouldn't count towards the input size when deciding whether to do a
289 // prefix query or not
290 check_fts_query("r():", r#""r""#);
291 // Test empty strings
292 check_fts_query("", r#""""#);
293 check_fts_query(" ", r#""""#);
294 check_fts_query("()", r#""""#);
295 }
296
297 #[test]
298 fn test_fts_query_match_required_stemming() {
299 // These don't require stemming, since each keyword matches a term in the title
300 assert!(!FtsQuery::new("running shoes").match_required_stemming("running shoes"));
301 assert!(
302 !FtsQuery::new("running shoes").match_required_stemming("new balance running shoes")
303 );
304 // Case changes shouldn't matter
305 assert!(!FtsQuery::new("running shoes").match_required_stemming("Running Shoes"));
306 // This doesn't require stemming, since `:` is not part of the word
307 assert!(!FtsQuery::new("running shoes").match_required_stemming("Running: Shoes"));
308 // This requires the keywords to be stemmed in order to match
309 assert!(FtsQuery::new("run shoes").match_required_stemming("running shoes"));
310 // This didn't require stemming, since the last keyword was a prefix match
311 assert!(!FtsQuery::new("running sh").match_required_stemming("running shoes"));
312 // This does require stemming (we know it wasn't a prefix match since there's not enough
313 // characters).
314 assert!(FtsQuery::new("run").match_required_stemming("running shoes"));
315 }
316
317 #[test]
318 fn test_full_keywords_to_fts_content() {
319 check_full_keywords_to_fts_content(["a", "b", "c"], "a b c");
320 check_full_keywords_to_fts_content(["a", "b c"], "a b c");
321 check_full_keywords_to_fts_content(["a", "b c a"], "a b c");
322 check_full_keywords_to_fts_content(["a", "b C A"], "a b c");
323 }
324
325 fn check_full_keywords_to_fts_content<const N: usize>(input: [&str; N], expected: &str) {
326 let mut expected_counts = HashMap::<&str, usize>::new();
327 let mut actual_counts = HashMap::<&str, usize>::new();
328 for term in expected.split_whitespace() {
329 *expected_counts.entry(term).or_default() += 1;
330 }
331 let fts_content = full_keywords_to_fts_content(input);
332 for term in fts_content.split_whitespace() {
333 *actual_counts.entry(term).or_default() += 1;
334 }
335 assert_eq!(actual_counts, expected_counts);
336 }
337 }