Debian Codegraph @

third_party/rust/suggest/src/provider.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
6 use std::{
7 collections::{HashMap, HashSet},
8 fmt,
9 };
10
11 use rusqlite::{
12 types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef},
13 Result as RusqliteResult,
14 };
15
16 use crate::rs::{Collection, SuggestRecordType};
17
18 #[cfg(test)]
19 use serde_json::Value as JsonValue;
20
21 #[cfg(test)]
22 use crate::testing::{MockAttachment, MockIcon, MockRecord};
23
24 /// Record types from these providers will be ingested when consumers do not
25 /// specify providers in `SuggestIngestionConstraints`.
26 pub(crate) const DEFAULT_INGEST_PROVIDERS: [SuggestionProvider; 5] = [
27 SuggestionProvider::Amp,
28 SuggestionProvider::Wikipedia,
29 SuggestionProvider::Amo,
30 SuggestionProvider::Yelp,
31 SuggestionProvider::Mdn,
32 ];
33
34 /// A provider is a source of search suggestions.
35 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, uniffi::Enum)]
36 #[repr(u8)]
37 pub enum SuggestionProvider {
38 Amp = 1,
39 Wikipedia = 2,
40 Amo = 3,
41 Pocket = 4,
42 Yelp = 5,
43 Mdn = 6,
44 Weather = 7,
45 Fakespot = 8,
46 Dynamic = 9,
47 }
48
49 impl fmt::Display for SuggestionProvider {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 match self {
52 Self::Amp => write!(f, "amp"),
53 Self::Wikipedia => write!(f, "wikipedia"),
54 Self::Amo => write!(f, "amo"),
55 Self::Pocket => write!(f, "pocket"),
56 Self::Yelp => write!(f, "yelp"),
57 Self::Mdn => write!(f, "mdn"),
58 Self::Weather => write!(f, "weather"),
59 Self::Fakespot => write!(f, "fakespot"),
60 Self::Dynamic => write!(f, "dynamic"),
61 }
62 }
63 }
64
65 impl FromSql for SuggestionProvider {
66 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
67 let v = value.as_i64()?;
68 u8::try_from(v)
69 .ok()
70 .and_then(SuggestionProvider::from_u8)
71 .ok_or_else(|| FromSqlError::OutOfRange(v))
72 }
73 }
74
75 impl SuggestionProvider {
76 pub fn all() -> [Self; 9] {
77 [
78 Self::Amp,
79 Self::Wikipedia,
80 Self::Amo,
81 Self::Pocket,
82 Self::Yelp,
83 Self::Mdn,
84 Self::Weather,
85 Self::Fakespot,
86 Self::Dynamic,
87 ]
88 }
89
90 #[inline]
91 pub(crate) fn from_u8(v: u8) -> Option<Self> {
92 match v {
93 1 => Some(Self::Amp),
94 2 => Some(Self::Wikipedia),
95 3 => Some(Self::Amo),
96 4 => Some(Self::Pocket),
97 5 => Some(Self::Yelp),
98 6 => Some(Self::Mdn),
99 7 => Some(Self::Weather),
100 8 => Some(Self::Fakespot),
101 9 => Some(Self::Dynamic),
102 _ => None,
103 }
104 }
105
106 /// The collection that stores the provider's primary record.
107 pub(crate) fn primary_collection(&self) -> Collection {
108 match self {
109 Self::Amp => Collection::Amp,
110 Self::Fakespot => Collection::Fakespot,
111 _ => Collection::Other,
112 }
113 }
114
115 /// The provider's primary record type.
116 pub(crate) fn primary_record_type(&self) -> SuggestRecordType {
117 match self {
118 Self::Amp => SuggestRecordType::Amp,
119 Self::Wikipedia => SuggestRecordType::Wikipedia,
120 Self::Amo => SuggestRecordType::Amo,
121 Self::Pocket => SuggestRecordType::Pocket,
122 Self::Yelp => SuggestRecordType::Yelp,
123 Self::Mdn => SuggestRecordType::Mdn,
124 Self::Weather => SuggestRecordType::Weather,
125 Self::Fakespot => SuggestRecordType::Fakespot,
126 Self::Dynamic => SuggestRecordType::Dynamic,
127 }
128 }
129
130 /// Other record types and their collections that the provider depends on.
131 fn secondary_record_types(&self) -> Option<HashMap<Collection, HashSet<SuggestRecordType>>> {
132 match self {
133 Self::Amp => Some(HashMap::from([(
134 Collection::Amp,
135 HashSet::from([SuggestRecordType::Icon]),
136 )])),
137 Self::Wikipedia => Some(HashMap::from([(
138 Collection::Other,
139 HashSet::from([SuggestRecordType::Icon]),
140 )])),
141 Self::Yelp => Some(HashMap::from([(
142 Collection::Other,
143 HashSet::from([
144 SuggestRecordType::Icon,
145 SuggestRecordType::Geonames,
146 SuggestRecordType::GeonamesAlternates,
147 ]),
148 )])),
149 Self::Weather => Some(HashMap::from([(
150 Collection::Other,
151 HashSet::from([
152 SuggestRecordType::Geonames,
153 SuggestRecordType::GeonamesAlternates,
154 ]),
155 )])),
156 Self::Fakespot => Some(HashMap::from([(
157 Collection::Fakespot,
158 HashSet::from([SuggestRecordType::Icon]),
159 )])),
160 _ => None,
161 }
162 }
163
164 /// All record types and their collections that the provider depends on,
165 /// including primary and secondary records.
166 pub(crate) fn record_types_by_collection(
167 &self,
168 ) -> HashMap<Collection, HashSet<SuggestRecordType>> {
169 let mut rts = self.secondary_record_types().unwrap_or_default();
170 rts.entry(self.primary_collection())
171 .or_default()
172 .insert(self.primary_record_type());
173 rts
174 }
175 }
176
177 impl ToSql for SuggestionProvider {
178 fn to_sql(&self) -> RusqliteResult<ToSqlOutput<'_>> {
179 Ok(ToSqlOutput::from(*self as u8))
180 }
181 }
182
183 #[cfg(test)]
184 impl SuggestionProvider {
185 pub fn record(&self, record_id: &str, attachment: JsonValue) -> MockRecord {
186 self.full_record(record_id, None, Some(MockAttachment::Json(attachment)))
187 }
188
189 pub fn empty_record(&self, record_id: &str) -> MockRecord {
190 self.full_record(record_id, None, None)
191 }
192
193 pub fn full_record(
194 &self,
195 record_id: &str,
196 inline_data: Option<JsonValue>,
197 attachment: Option<MockAttachment>,
198 ) -> MockRecord {
199 MockRecord {
200 collection: self.primary_collection(),
201 record_type: self.primary_record_type(),
202 id: record_id.to_string(),
203 inline_data,
204 attachment,
205 }
206 }
207
208 pub fn icon(&self, icon: MockIcon) -> MockRecord {
209 MockRecord {
210 collection: self.primary_collection(),
211 record_type: SuggestRecordType::Icon,
212 id: format!("icon-{}", icon.id),
213 inline_data: None,
214 attachment: Some(MockAttachment::Icon(icon)),
215 }
216 }
217 }
218
219 /// Some providers manage multiple suggestion subtypes. Queries, ingests, and
220 /// other operations on those providers must be constrained to a desired subtype.
221 #[derive(Clone, Default, Debug, uniffi::Record)]
222 pub struct SuggestionProviderConstraints {
223 /// Which dynamic suggestions should we fetch or ingest? Corresponds to the
224 /// `suggestion_type` value in dynamic suggestions remote settings records.
225 #[uniffi(default = None)]
226 pub dynamic_suggestion_types: Option<Vec<String>>,
227 /// Which strategy should we use for the AMP queries?
228 /// Use None for the default strategy.
229 #[uniffi(default = None)]
230 pub amp_alternative_matching: Option<AmpMatchingStrategy>,
231 }
232
233 #[derive(Clone, Debug, uniffi::Enum)]
234 pub enum AmpMatchingStrategy {
235 /// Disable keywords added via keyword expansion.
236 /// This eliminates keywords that for terms related to the "real" keywords, for example
237 /// misspellings like "underarmor" instead of "under armor"'.
238 NoKeywordExpansion = 1, // The desktop consumer assumes this starts at `1`
239 /// Use FTS matching against the full keywords, joined together.
240 FtsAgainstFullKeywords,
241 /// Use FTS matching against the title field
242 FtsAgainstTitle,
243 }
244
245 impl AmpMatchingStrategy {
246 pub fn uses_fts(&self) -> bool {
247 matches!(self, Self::FtsAgainstFullKeywords | Self::FtsAgainstTitle)
248 }
249 }