| 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 |
//! Crate-internal types for interacting with Remote Settings (`rs`). Types in |
| 7 |
//! this module describe records and attachments in the Suggest Remote Settings |
| 8 |
//! collection. |
| 9 |
//! |
| 10 |
//! To add a new suggestion `T` to this component, you'll generally need to: |
| 11 |
//! |
| 12 |
//! 1. Add a variant named `T` to [`SuggestRecord`]. The variant must have a |
| 13 |
//! `#[serde(rename)]` attribute that matches the suggestion record's |
| 14 |
//! `type` field. |
| 15 |
//! 2. Define a `DownloadedTSuggestion` type with the new suggestion's fields, |
| 16 |
//! matching their attachment's schema. Your new type must derive or |
| 17 |
//! implement [`serde::Deserialize`]. |
| 18 |
//! 3. Update the database schema in the [`schema`] module to store the new |
| 19 |
//! suggestion. |
| 20 |
//! 4. Add an `insert_t_suggestions()` method to [`db::SuggestDao`] that |
| 21 |
//! inserts `DownloadedTSuggestion`s into the database. |
| 22 |
//! 5. Update [`store::SuggestStoreInner::ingest()`] to download, deserialize, |
| 23 |
//! and store the new suggestion. |
| 24 |
//! 6. Add a variant named `T` to [`suggestion::Suggestion`], with the fields |
| 25 |
//! that you'd like to expose to the application. These can be the same |
| 26 |
//! fields as `DownloadedTSuggestion`, or slightly different, depending on |
| 27 |
//! what the application needs to show the suggestion. |
| 28 |
//! 7. Update the `Suggestion` enum definition in `suggest.udl` to match your |
| 29 |
//! new [`suggestion::Suggestion`] variant. |
| 30 |
//! 8. Update any [`db::SuggestDao`] methods that query the database to include |
| 31 |
//! the new suggestion in their results, and return `Suggestion::T` variants |
| 32 |
//! as needed. |
| 33 |
|
| 34 |
use std::{fmt, sync::Arc}; |
| 35 |
|
| 36 |
use remote_settings::{ |
| 37 |
Attachment, RemoteSettingsClient, RemoteSettingsError, RemoteSettingsRecord, |
| 38 |
RemoteSettingsService, |
| 39 |
}; |
| 40 |
use serde::{Deserialize, Serialize}; |
| 41 |
use serde_json::{Map, Value}; |
| 42 |
|
| 43 |
use crate::{error::Error, query::full_keywords_to_fts_content, Result}; |
| 44 |
use rusqlite::{types::ToSqlOutput, ToSql}; |
| 45 |
|
| 46 |
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 47 |
pub enum Collection { |
| 48 |
Amp, |
| 49 |
Fakespot, |
| 50 |
Other, |
| 51 |
} |
| 52 |
|
| 53 |
impl Collection { |
| 54 |
pub fn name(&self) -> &'static str { |
| 55 |
match self { |
| 56 |
Self::Amp => "quicksuggest-amp", |
| 57 |
Self::Fakespot => "fakespot-suggest-products", |
| 58 |
Self::Other => "quicksuggest-other", |
| 59 |
} |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
/// A trait for a client that downloads suggestions from Remote Settings. |
| 64 |
/// |
| 65 |
/// This trait lets tests use a mock client. |
| 66 |
pub(crate) trait Client { |
| 67 |
/// Get all records from the server |
| 68 |
/// |
| 69 |
/// We use this plus client-side filtering rather than any server-side filtering, as |
| 70 |
/// recommended by the remote settings docs |
| 71 |
/// (https://remote-settings.readthedocs.io/en/stable/client-specifications.html). This is |
| 72 |
/// relatively inexpensive since we use a cache and don't fetch attachments until after the |
| 73 |
/// client-side filtering. |
| 74 |
/// |
| 75 |
/// Records that can't be parsed as [SuggestRecord] are ignored. |
| 76 |
fn get_records(&self, collection: Collection) -> Result<Vec<Record>>; |
| 77 |
|
| 78 |
fn download_attachment(&self, record: &Record) -> Result<Vec<u8>>; |
| 79 |
} |
| 80 |
|
| 81 |
/// Implements the [Client] trait using a real remote settings client |
| 82 |
pub struct SuggestRemoteSettingsClient { |
| 83 |
// Create a separate client for each collection name |
| 84 |
amp_client: Arc<RemoteSettingsClient>, |
| 85 |
other_client: Arc<RemoteSettingsClient>, |
| 86 |
fakespot_client: Arc<RemoteSettingsClient>, |
| 87 |
} |
| 88 |
|
| 89 |
impl SuggestRemoteSettingsClient { |
| 90 |
pub fn new(rs_service: &RemoteSettingsService) -> Self { |
| 91 |
Self { |
| 92 |
amp_client: rs_service.make_client(Collection::Amp.name().to_owned()), |
| 93 |
other_client: rs_service.make_client(Collection::Other.name().to_owned()), |
| 94 |
fakespot_client: rs_service.make_client(Collection::Fakespot.name().to_owned()), |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
fn client_for_collection(&self, collection: Collection) -> &RemoteSettingsClient { |
| 99 |
match collection { |
| 100 |
Collection::Amp => &self.amp_client, |
| 101 |
Collection::Other => &self.other_client, |
| 102 |
Collection::Fakespot => &self.fakespot_client, |
| 103 |
} |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
impl Client for SuggestRemoteSettingsClient { |
| 108 |
fn get_records(&self, collection: Collection) -> Result<Vec<Record>> { |
| 109 |
let client = self.client_for_collection(collection); |
| 110 |
client.sync()?; |
| 111 |
let response = client.get_records(false); |
| 112 |
match response { |
| 113 |
Some(r) => Ok(r |
| 114 |
.into_iter() |
| 115 |
.filter_map(|r| Record::new(r, collection).ok()) |
| 116 |
.collect()), |
| 117 |
None => Err(Error::RemoteSettings(RemoteSettingsError::Other { |
| 118 |
reason: "Unable to get records".to_owned(), |
| 119 |
})), |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
fn download_attachment(&self, record: &Record) -> Result<Vec<u8>> { |
| 124 |
let converted_record: RemoteSettingsRecord = record.clone().into(); |
| 125 |
match &record.attachment { |
| 126 |
Some(_) => Ok(self |
| 127 |
.client_for_collection(record.collection) |
| 128 |
.get_attachment(&converted_record)?), |
| 129 |
None => Err(Error::MissingAttachment(record.id.to_string())), |
| 130 |
} |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
/// Remote settings record for suggest. |
| 135 |
/// |
| 136 |
/// This is a `remote_settings::RemoteSettingsRecord` parsed for suggest. |
| 137 |
#[derive(Clone, Debug)] |
| 138 |
pub(crate) struct Record { |
| 139 |
pub id: SuggestRecordId, |
| 140 |
pub last_modified: u64, |
| 141 |
pub attachment: Option<Attachment>, |
| 142 |
pub payload: SuggestRecord, |
| 143 |
pub collection: Collection, |
| 144 |
} |
| 145 |
|
| 146 |
impl Record { |
| 147 |
pub fn new(record: RemoteSettingsRecord, collection: Collection) -> Result<Self> { |
| 148 |
Ok(Self { |
| 149 |
id: SuggestRecordId::new(record.id), |
| 150 |
last_modified: record.last_modified, |
| 151 |
attachment: record.attachment, |
| 152 |
payload: serde_json::from_value(serde_json::Value::Object(record.fields))?, |
| 153 |
collection, |
| 154 |
}) |
| 155 |
} |
| 156 |
|
| 157 |
pub fn record_type(&self) -> SuggestRecordType { |
| 158 |
(&self.payload).into() |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
impl From<Record> for RemoteSettingsRecord { |
| 163 |
fn from(record: Record) -> Self { |
| 164 |
RemoteSettingsRecord { |
| 165 |
id: record.id.to_string(), |
| 166 |
last_modified: record.last_modified, |
| 167 |
deleted: false, |
| 168 |
attachment: record.attachment.clone(), |
| 169 |
fields: record.payload.to_json_map(), |
| 170 |
} |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
/// A record in the Suggest Remote Settings collection. |
| 175 |
/// |
| 176 |
/// Most Suggest records don't carry inline fields except for `type`. |
| 177 |
/// Suggestions themselves are typically stored in each record's attachment. |
| 178 |
#[derive(Clone, Debug, Deserialize, Serialize)] |
| 179 |
#[serde(tag = "type")] |
| 180 |
pub(crate) enum SuggestRecord { |
| 181 |
#[serde(rename = "icon")] |
| 182 |
Icon, |
| 183 |
#[serde(rename = "amp")] |
| 184 |
Amp, |
| 185 |
#[serde(rename = "wikipedia")] |
| 186 |
Wikipedia, |
| 187 |
#[serde(rename = "amo-suggestions")] |
| 188 |
Amo, |
| 189 |
#[serde(rename = "pocket-suggestions")] |
| 190 |
Pocket, |
| 191 |
#[serde(rename = "yelp-suggestions")] |
| 192 |
Yelp, |
| 193 |
#[serde(rename = "mdn-suggestions")] |
| 194 |
Mdn, |
| 195 |
#[serde(rename = "weather")] |
| 196 |
Weather, |
| 197 |
#[serde(rename = "configuration")] |
| 198 |
GlobalConfig(DownloadedGlobalConfig), |
| 199 |
#[serde(rename = "fakespot-suggestions")] |
| 200 |
Fakespot, |
| 201 |
#[serde(rename = "dynamic-suggestions")] |
| 202 |
Dynamic(DownloadedDynamicRecord), |
| 203 |
#[serde(rename = "geonames-2")] // version 2 |
| 204 |
Geonames, |
| 205 |
#[serde(rename = "geonames-alternates")] |
| 206 |
GeonamesAlternates, |
| 207 |
} |
| 208 |
|
| 209 |
impl SuggestRecord { |
| 210 |
fn to_json_map(&self) -> Map<String, Value> { |
| 211 |
match serde_json::to_value(self) { |
| 212 |
Ok(Value::Object(map)) => map, |
| 213 |
_ => unreachable!(), |
| 214 |
} |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
/// Enum for the different record types that can be consumed. |
| 219 |
/// Extracting this from the serialization enum so that we can |
| 220 |
/// extend it to get type metadata. |
| 221 |
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] |
| 222 |
pub enum SuggestRecordType { |
| 223 |
Icon, |
| 224 |
Amp, |
| 225 |
Wikipedia, |
| 226 |
Amo, |
| 227 |
Pocket, |
| 228 |
Yelp, |
| 229 |
Mdn, |
| 230 |
Weather, |
| 231 |
GlobalConfig, |
| 232 |
Fakespot, |
| 233 |
Dynamic, |
| 234 |
Geonames, |
| 235 |
GeonamesAlternates, |
| 236 |
} |
| 237 |
|
| 238 |
impl From<&SuggestRecord> for SuggestRecordType { |
| 239 |
fn from(suggest_record: &SuggestRecord) -> Self { |
| 240 |
match suggest_record { |
| 241 |
SuggestRecord::Amo => Self::Amo, |
| 242 |
SuggestRecord::Amp => Self::Amp, |
| 243 |
SuggestRecord::Wikipedia => Self::Wikipedia, |
| 244 |
SuggestRecord::Icon => Self::Icon, |
| 245 |
SuggestRecord::Mdn => Self::Mdn, |
| 246 |
SuggestRecord::Pocket => Self::Pocket, |
| 247 |
SuggestRecord::Weather => Self::Weather, |
| 248 |
SuggestRecord::Yelp => Self::Yelp, |
| 249 |
SuggestRecord::GlobalConfig(_) => Self::GlobalConfig, |
| 250 |
SuggestRecord::Fakespot => Self::Fakespot, |
| 251 |
SuggestRecord::Dynamic(_) => Self::Dynamic, |
| 252 |
SuggestRecord::Geonames => Self::Geonames, |
| 253 |
SuggestRecord::GeonamesAlternates => Self::GeonamesAlternates, |
| 254 |
} |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
impl fmt::Display for SuggestRecordType { |
| 259 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 260 |
write!(f, "{}", self.as_str()) |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
impl ToSql for SuggestRecordType { |
| 265 |
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> { |
| 266 |
Ok(ToSqlOutput::from(self.as_str())) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
impl SuggestRecordType { |
| 271 |
/// Get all record types to iterate over |
| 272 |
/// |
| 273 |
/// Currently only used by tests |
| 274 |
#[cfg(test)] |
| 275 |
pub fn all() -> &'static [SuggestRecordType] { |
| 276 |
&[ |
| 277 |
Self::Icon, |
| 278 |
Self::Amp, |
| 279 |
Self::Wikipedia, |
| 280 |
Self::Amo, |
| 281 |
Self::Pocket, |
| 282 |
Self::Yelp, |
| 283 |
Self::Mdn, |
| 284 |
Self::Weather, |
| 285 |
Self::GlobalConfig, |
| 286 |
Self::Fakespot, |
| 287 |
Self::Dynamic, |
| 288 |
Self::Geonames, |
| 289 |
Self::GeonamesAlternates, |
| 290 |
] |
| 291 |
} |
| 292 |
|
| 293 |
pub fn as_str(&self) -> &str { |
| 294 |
match self { |
| 295 |
Self::Icon => "icon", |
| 296 |
Self::Amp => "amp", |
| 297 |
Self::Wikipedia => "wikipedia", |
| 298 |
Self::Amo => "amo-suggestions", |
| 299 |
Self::Pocket => "pocket-suggestions", |
| 300 |
Self::Yelp => "yelp-suggestions", |
| 301 |
Self::Mdn => "mdn-suggestions", |
| 302 |
Self::Weather => "weather", |
| 303 |
Self::GlobalConfig => "configuration", |
| 304 |
Self::Fakespot => "fakespot-suggestions", |
| 305 |
Self::Dynamic => "dynamic-suggestions", |
| 306 |
Self::Geonames => "geonames-2", |
| 307 |
Self::GeonamesAlternates => "geonames-alternates", |
| 308 |
} |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
/// Represents either a single value, or a list of values. This is used to |
| 313 |
/// deserialize downloaded attachments. |
| 314 |
#[derive(Clone, Debug, Deserialize)] |
| 315 |
#[serde(untagged)] |
| 316 |
enum OneOrMany<T> { |
| 317 |
One(T), |
| 318 |
Many(Vec<T>), |
| 319 |
} |
| 320 |
|
| 321 |
/// A downloaded Remote Settings attachment that contains suggestions. |
| 322 |
#[derive(Clone, Debug, Deserialize)] |
| 323 |
#[serde(transparent)] |
| 324 |
pub(crate) struct SuggestAttachment<T>(OneOrMany<T>); |
| 325 |
|
| 326 |
impl<T> SuggestAttachment<T> { |
| 327 |
/// Returns a slice of suggestions to ingest from the downloaded attachment. |
| 328 |
pub fn suggestions(&self) -> &[T] { |
| 329 |
match &self.0 { |
| 330 |
OneOrMany::One(value) => std::slice::from_ref(value), |
| 331 |
OneOrMany::Many(values) => values, |
| 332 |
} |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
/// The ID of a record in the Suggest Remote Settings collection. |
| 337 |
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 338 |
#[serde(transparent)] |
| 339 |
pub(crate) struct SuggestRecordId(String); |
| 340 |
|
| 341 |
impl SuggestRecordId { |
| 342 |
pub fn new(id: String) -> Self { |
| 343 |
Self(id) |
| 344 |
} |
| 345 |
|
| 346 |
pub fn as_str(&self) -> &str { |
| 347 |
&self.0 |
| 348 |
} |
| 349 |
|
| 350 |
/// If this ID is for an icon record, extracts and returns the icon ID. |
| 351 |
/// |
| 352 |
/// The icon ID is the primary key for an ingested icon. Downloaded |
| 353 |
/// suggestions also reference these icon IDs, in |
| 354 |
/// [`DownloadedSuggestion::icon_id`]. |
| 355 |
pub fn as_icon_id(&self) -> Option<&str> { |
| 356 |
self.0.strip_prefix("icon-") |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
impl fmt::Display for SuggestRecordId { |
| 361 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 362 |
write!(f, "{}", self.0) |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
/// An AMP suggestion to ingest from an AMP attachment. |
| 367 |
#[derive(Clone, Debug, Default, Deserialize)] |
| 368 |
pub(crate) struct DownloadedAmpSuggestion { |
| 369 |
pub keywords: Vec<String>, |
| 370 |
pub title: String, |
| 371 |
pub url: String, |
| 372 |
pub score: Option<f64>, |
| 373 |
#[serde(default)] |
| 374 |
pub full_keywords: Vec<(String, usize)>, |
| 375 |
pub advertiser: String, |
| 376 |
#[serde(rename = "id")] |
| 377 |
pub block_id: i32, |
| 378 |
pub iab_category: String, |
| 379 |
pub click_url: String, |
| 380 |
pub impression_url: String, |
| 381 |
#[serde(rename = "icon")] |
| 382 |
pub icon_id: String, |
| 383 |
} |
| 384 |
|
| 385 |
/// A Wikipedia suggestion to ingest from a Wikipedia attachment. |
| 386 |
#[derive(Clone, Debug, Default, Deserialize)] |
| 387 |
pub(crate) struct DownloadedWikipediaSuggestion { |
| 388 |
pub keywords: Vec<String>, |
| 389 |
pub title: String, |
| 390 |
pub url: String, |
| 391 |
pub score: Option<f64>, |
| 392 |
#[serde(default)] |
| 393 |
pub full_keywords: Vec<(String, usize)>, |
| 394 |
#[serde(rename = "icon")] |
| 395 |
pub icon_id: String, |
| 396 |
} |
| 397 |
|
| 398 |
/// Iterate over all AMP/Wikipedia-style keywords. |
| 399 |
pub fn iterate_keywords<'a>( |
| 400 |
keywords: &'a [String], |
| 401 |
full_keywords: &'a [(String, usize)], |
| 402 |
) -> impl Iterator<Item = AmpKeyword<'a>> { |
| 403 |
let full_keywords_iter = full_keywords |
| 404 |
.iter() |
| 405 |
.flat_map(|(full_keyword, repeat_for)| { |
| 406 |
std::iter::repeat(Some(full_keyword.as_str())).take(*repeat_for) |
| 407 |
}) |
| 408 |
.chain(std::iter::repeat(None)); // In case of insufficient full keywords, just fill in with infinite `None`s |
| 409 |
// |
| 410 |
keywords |
| 411 |
.iter() |
| 412 |
.zip(full_keywords_iter) |
| 413 |
.enumerate() |
| 414 |
.map(move |(i, (keyword, full_keyword))| AmpKeyword { |
| 415 |
rank: i, |
| 416 |
keyword, |
| 417 |
full_keyword, |
| 418 |
}) |
| 419 |
} |
| 420 |
|
| 421 |
impl DownloadedAmpSuggestion { |
| 422 |
pub fn keywords(&self) -> impl Iterator<Item = AmpKeyword<'_>> { |
| 423 |
iterate_keywords(&self.keywords, &self.full_keywords) |
| 424 |
} |
| 425 |
|
| 426 |
pub fn full_keywords_fts_column(&self) -> String { |
| 427 |
full_keywords_to_fts_content(self.full_keywords.iter().map(|(s, _)| s.as_str())) |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
impl DownloadedWikipediaSuggestion { |
| 432 |
pub fn keywords(&self) -> impl Iterator<Item = AmpKeyword<'_>> { |
| 433 |
iterate_keywords(&self.keywords, &self.full_keywords) |
| 434 |
} |
| 435 |
} |
| 436 |
|
| 437 |
#[derive(Debug, PartialEq, Eq)] |
| 438 |
pub(crate) struct AmpKeyword<'a> { |
| 439 |
pub rank: usize, |
| 440 |
pub keyword: &'a str, |
| 441 |
pub full_keyword: Option<&'a str>, |
| 442 |
} |
| 443 |
|
| 444 |
/// An AMO suggestion to ingest from an attachment |
| 445 |
#[derive(Clone, Debug, Deserialize)] |
| 446 |
pub(crate) struct DownloadedAmoSuggestion { |
| 447 |
pub description: String, |
| 448 |
pub url: String, |
| 449 |
pub guid: String, |
| 450 |
#[serde(rename = "icon")] |
| 451 |
pub icon_url: String, |
| 452 |
pub rating: Option<String>, |
| 453 |
pub number_of_ratings: i64, |
| 454 |
pub title: String, |
| 455 |
pub keywords: Vec<String>, |
| 456 |
pub score: f64, |
| 457 |
} |
| 458 |
/// A Pocket suggestion to ingest from a Pocket Suggestion Attachment |
| 459 |
#[derive(Clone, Debug, Deserialize)] |
| 460 |
pub(crate) struct DownloadedPocketSuggestion { |
| 461 |
pub url: String, |
| 462 |
pub title: String, |
| 463 |
#[serde(rename = "lowConfidenceKeywords")] |
| 464 |
pub low_confidence_keywords: Vec<String>, |
| 465 |
#[serde(rename = "highConfidenceKeywords")] |
| 466 |
pub high_confidence_keywords: Vec<String>, |
| 467 |
pub score: f64, |
| 468 |
} |
| 469 |
/// Yelp location sign data type |
| 470 |
#[derive(Clone, Debug, Deserialize)] |
| 471 |
#[serde(untagged)] |
| 472 |
pub enum DownloadedYelpLocationSign { |
| 473 |
V1 { keyword: String }, |
| 474 |
V2(String), |
| 475 |
} |
| 476 |
impl ToSql for DownloadedYelpLocationSign { |
| 477 |
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> { |
| 478 |
let keyword = match self { |
| 479 |
DownloadedYelpLocationSign::V1 { keyword } => keyword, |
| 480 |
DownloadedYelpLocationSign::V2(keyword) => keyword, |
| 481 |
}; |
| 482 |
Ok(ToSqlOutput::from(keyword.as_str())) |
| 483 |
} |
| 484 |
} |
| 485 |
/// A Yelp suggestion to ingest from a Yelp Attachment |
| 486 |
#[derive(Clone, Debug, Deserialize)] |
| 487 |
pub(crate) struct DownloadedYelpSuggestion { |
| 488 |
pub subjects: Vec<String>, |
| 489 |
#[serde(rename = "businessSubjects")] |
| 490 |
pub business_subjects: Option<Vec<String>>, |
| 491 |
#[serde(rename = "preModifiers")] |
| 492 |
pub pre_modifiers: Vec<String>, |
| 493 |
#[serde(rename = "postModifiers")] |
| 494 |
pub post_modifiers: Vec<String>, |
| 495 |
#[serde(rename = "locationSigns")] |
| 496 |
pub location_signs: Vec<DownloadedYelpLocationSign>, |
| 497 |
#[serde(rename = "yelpModifiers")] |
| 498 |
pub yelp_modifiers: Vec<String>, |
| 499 |
#[serde(rename = "icon")] |
| 500 |
pub icon_id: String, |
| 501 |
pub score: f64, |
| 502 |
} |
| 503 |
|
| 504 |
/// An MDN suggestion to ingest from an attachment |
| 505 |
#[derive(Clone, Debug, Deserialize)] |
| 506 |
pub(crate) struct DownloadedMdnSuggestion { |
| 507 |
pub url: String, |
| 508 |
pub title: String, |
| 509 |
pub description: String, |
| 510 |
pub keywords: Vec<String>, |
| 511 |
pub score: f64, |
| 512 |
} |
| 513 |
|
| 514 |
/// A Fakespot suggestion to ingest from an attachment |
| 515 |
#[derive(Clone, Debug, Deserialize)] |
| 516 |
pub(crate) struct DownloadedFakespotSuggestion { |
| 517 |
pub fakespot_grade: String, |
| 518 |
pub product_id: String, |
| 519 |
pub keywords: String, |
| 520 |
pub product_type: String, |
| 521 |
pub rating: f64, |
| 522 |
pub score: f64, |
| 523 |
pub title: String, |
| 524 |
pub total_reviews: i64, |
| 525 |
pub url: String, |
| 526 |
} |
| 527 |
|
| 528 |
/// A dynamic suggestion record's inline data |
| 529 |
#[derive(Clone, Debug, Deserialize, Serialize)] |
| 530 |
pub(crate) struct DownloadedDynamicRecord { |
| 531 |
pub suggestion_type: String, |
| 532 |
pub score: Option<f64>, |
| 533 |
} |
| 534 |
|
| 535 |
/// A dynamic suggestion to ingest from an attachment |
| 536 |
#[derive(Clone, Debug, Deserialize)] |
| 537 |
pub(crate) struct DownloadedDynamicSuggestion { |
| 538 |
keywords: Vec<FullOrPrefixKeywords<String>>, |
| 539 |
pub dismissal_key: Option<String>, |
| 540 |
pub data: Option<Value>, |
| 541 |
} |
| 542 |
|
| 543 |
impl DownloadedDynamicSuggestion { |
| 544 |
/// Iterate over all keywords for this suggestion. Iteration may contain |
| 545 |
/// duplicate keywords depending on the structure of the data, so do not |
| 546 |
/// assume keywords are unique. Duplicates are not filtered out because |
| 547 |
/// doing so would require O(number of keywords) space, and the number of |
| 548 |
/// keywords can be very large. If you are inserting into the store, rely on |
| 549 |
/// uniqueness constraints and use `INSERT OR IGNORE`. |
| 550 |
pub fn keywords(&self) -> impl Iterator<Item = String> + '_ { |
| 551 |
self.keywords.iter().flat_map(|e| e.keywords()) |
| 552 |
} |
| 553 |
} |
| 554 |
|
| 555 |
/// A single full keyword or a `(prefix, suffixes)` tuple representing multiple |
| 556 |
/// prefix keywords. Prefix keywords are enumerated by appending to `prefix` |
| 557 |
/// each possible prefix of each suffix, including the full suffix. The prefix |
| 558 |
/// is also enumerated by itself. Examples: |
| 559 |
/// |
| 560 |
/// `FullOrPrefixKeywords::Full("some full keyword")` |
| 561 |
/// => "some full keyword" |
| 562 |
/// |
| 563 |
/// `FullOrPrefixKeywords::Prefix(("sug", vec!["gest", "arplum"]))` |
| 564 |
/// => "sug" |
| 565 |
/// "sugg" |
| 566 |
/// "sugge" |
| 567 |
/// "sugges" |
| 568 |
/// "suggest" |
| 569 |
/// "suga" |
| 570 |
/// "sugar" |
| 571 |
/// "sugarp" |
| 572 |
/// "sugarpl" |
| 573 |
/// "sugarplu" |
| 574 |
/// "sugarplum" |
| 575 |
#[derive(Clone, Debug, Deserialize)] |
| 576 |
#[serde(untagged)] |
| 577 |
enum FullOrPrefixKeywords<T> { |
| 578 |
Full(T), |
| 579 |
Prefix((T, Vec<T>)), |
| 580 |
} |
| 581 |
|
| 582 |
impl<T> From<T> for FullOrPrefixKeywords<T> { |
| 583 |
fn from(full_keyword: T) -> Self { |
| 584 |
Self::Full(full_keyword) |
| 585 |
} |
| 586 |
} |
| 587 |
|
| 588 |
impl<T> From<(T, Vec<T>)> for FullOrPrefixKeywords<T> { |
| 589 |
fn from(prefix_suffixes: (T, Vec<T>)) -> Self { |
| 590 |
Self::Prefix(prefix_suffixes) |
| 591 |
} |
| 592 |
} |
| 593 |
|
| 594 |
impl FullOrPrefixKeywords<String> { |
| 595 |
pub fn keywords(&self) -> Box<dyn Iterator<Item = String> + '_> { |
| 596 |
match self { |
| 597 |
FullOrPrefixKeywords::Full(kw) => Box::new(std::iter::once(kw.to_owned())), |
| 598 |
FullOrPrefixKeywords::Prefix((prefix, suffixes)) => Box::new( |
| 599 |
std::iter::once(prefix.to_owned()).chain(suffixes.iter().flat_map(|suffix| { |
| 600 |
let mut kw = prefix.clone(); |
| 601 |
suffix.chars().map(move |c| { |
| 602 |
kw.push(c); |
| 603 |
kw.clone() |
| 604 |
}) |
| 605 |
})), |
| 606 |
), |
| 607 |
} |
| 608 |
} |
| 609 |
} |
| 610 |
|
| 611 |
/// Global Suggest configuration data to ingest from a configuration record |
| 612 |
#[derive(Clone, Debug, Deserialize, Serialize)] |
| 613 |
pub(crate) struct DownloadedGlobalConfig { |
| 614 |
pub configuration: DownloadedGlobalConfigInner, |
| 615 |
} |
| 616 |
#[derive(Clone, Debug, Deserialize, Serialize)] |
| 617 |
pub(crate) struct DownloadedGlobalConfigInner { |
| 618 |
/// The maximum number of times the user can click "Show less frequently" |
| 619 |
/// for a suggestion in the UI. |
| 620 |
pub show_less_frequently_cap: i32, |
| 621 |
} |
| 622 |
|
| 623 |
#[cfg(test)] |
| 624 |
mod test { |
| 625 |
use super::*; |
| 626 |
|
| 627 |
#[test] |
| 628 |
fn test_full_keywords() { |
| 629 |
let suggestion = DownloadedAmpSuggestion { |
| 630 |
keywords: vec![ |
| 631 |
String::from("f"), |
| 632 |
String::from("fo"), |
| 633 |
String::from("foo"), |
| 634 |
String::from("foo b"), |
| 635 |
String::from("foo ba"), |
| 636 |
String::from("foo bar"), |
| 637 |
], |
| 638 |
full_keywords: vec![(String::from("foo"), 3), (String::from("foo bar"), 3)], |
| 639 |
..DownloadedAmpSuggestion::default() |
| 640 |
}; |
| 641 |
|
| 642 |
assert_eq!( |
| 643 |
Vec::from_iter(suggestion.keywords()), |
| 644 |
vec![ |
| 645 |
AmpKeyword { |
| 646 |
rank: 0, |
| 647 |
keyword: "f", |
| 648 |
full_keyword: Some("foo"), |
| 649 |
}, |
| 650 |
AmpKeyword { |
| 651 |
rank: 1, |
| 652 |
keyword: "fo", |
| 653 |
full_keyword: Some("foo"), |
| 654 |
}, |
| 655 |
AmpKeyword { |
| 656 |
rank: 2, |
| 657 |
keyword: "foo", |
| 658 |
full_keyword: Some("foo"), |
| 659 |
}, |
| 660 |
AmpKeyword { |
| 661 |
rank: 3, |
| 662 |
keyword: "foo b", |
| 663 |
full_keyword: Some("foo bar"), |
| 664 |
}, |
| 665 |
AmpKeyword { |
| 666 |
rank: 4, |
| 667 |
keyword: "foo ba", |
| 668 |
full_keyword: Some("foo bar"), |
| 669 |
}, |
| 670 |
AmpKeyword { |
| 671 |
rank: 5, |
| 672 |
keyword: "foo bar", |
| 673 |
full_keyword: Some("foo bar"), |
| 674 |
}, |
| 675 |
], |
| 676 |
); |
| 677 |
} |
| 678 |
|
| 679 |
#[test] |
| 680 |
fn test_missing_full_keywords() { |
| 681 |
let suggestion = DownloadedAmpSuggestion { |
| 682 |
keywords: vec![ |
| 683 |
String::from("f"), |
| 684 |
String::from("fo"), |
| 685 |
String::from("foo"), |
| 686 |
String::from("foo b"), |
| 687 |
String::from("foo ba"), |
| 688 |
String::from("foo bar"), |
| 689 |
], |
| 690 |
// Only the first 3 keywords have full keywords associated with them |
| 691 |
full_keywords: vec![(String::from("foo"), 3)], |
| 692 |
..DownloadedAmpSuggestion::default() |
| 693 |
}; |
| 694 |
|
| 695 |
assert_eq!( |
| 696 |
Vec::from_iter(suggestion.keywords()), |
| 697 |
vec![ |
| 698 |
AmpKeyword { |
| 699 |
rank: 0, |
| 700 |
keyword: "f", |
| 701 |
full_keyword: Some("foo"), |
| 702 |
}, |
| 703 |
AmpKeyword { |
| 704 |
rank: 1, |
| 705 |
keyword: "fo", |
| 706 |
full_keyword: Some("foo"), |
| 707 |
}, |
| 708 |
AmpKeyword { |
| 709 |
rank: 2, |
| 710 |
keyword: "foo", |
| 711 |
full_keyword: Some("foo"), |
| 712 |
}, |
| 713 |
AmpKeyword { |
| 714 |
rank: 3, |
| 715 |
keyword: "foo b", |
| 716 |
full_keyword: None, |
| 717 |
}, |
| 718 |
AmpKeyword { |
| 719 |
rank: 4, |
| 720 |
keyword: "foo ba", |
| 721 |
full_keyword: None, |
| 722 |
}, |
| 723 |
AmpKeyword { |
| 724 |
rank: 5, |
| 725 |
keyword: "foo bar", |
| 726 |
full_keyword: None, |
| 727 |
}, |
| 728 |
], |
| 729 |
); |
| 730 |
} |
| 731 |
|
| 732 |
fn full_or_prefix_keywords_to_owned( |
| 733 |
kws: Vec<FullOrPrefixKeywords<&str>>, |
| 734 |
) -> Vec<FullOrPrefixKeywords<String>> { |
| 735 |
kws.iter() |
| 736 |
.map(|val| match val { |
| 737 |
FullOrPrefixKeywords::Full(s) => FullOrPrefixKeywords::Full(s.to_string()), |
| 738 |
FullOrPrefixKeywords::Prefix((prefix, suffixes)) => FullOrPrefixKeywords::Prefix(( |
| 739 |
prefix.to_string(), |
| 740 |
suffixes.iter().map(|s| s.to_string()).collect(), |
| 741 |
)), |
| 742 |
}) |
| 743 |
.collect() |
| 744 |
} |
| 745 |
|
| 746 |
#[test] |
| 747 |
fn test_dynamic_keywords() { |
| 748 |
let suggestion = DownloadedDynamicSuggestion { |
| 749 |
keywords: full_or_prefix_keywords_to_owned(vec![ |
| 750 |
"no suffixes".into(), |
| 751 |
("empty suffixes", vec![]).into(), |
| 752 |
("empty string suffix", vec![""]).into(), |
| 753 |
("choco", vec!["", "bo", "late"]).into(), |
| 754 |
"duplicate 1".into(), |
| 755 |
"duplicate 1".into(), |
| 756 |
("dup", vec!["licate 1", "licate 2"]).into(), |
| 757 |
("dup", vec!["lo", "licate 2", "licate 3"]).into(), |
| 758 |
("duplic", vec!["ate 3", "ar", "ate 4"]).into(), |
| 759 |
("du", vec!["plicate 4", "plicate 5", "nk"]).into(), |
| 760 |
]), |
| 761 |
data: None, |
| 762 |
dismissal_key: None, |
| 763 |
}; |
| 764 |
|
| 765 |
assert_eq!( |
| 766 |
Vec::from_iter(suggestion.keywords()), |
| 767 |
vec![ |
| 768 |
"no suffixes", |
| 769 |
"empty suffixes", |
| 770 |
"empty string suffix", |
| 771 |
"choco", |
| 772 |
"chocob", |
| 773 |
"chocobo", |
| 774 |
"chocol", |
| 775 |
"chocola", |
| 776 |
"chocolat", |
| 777 |
"chocolate", |
| 778 |
"duplicate 1", |
| 779 |
"duplicate 1", |
| 780 |
"dup", |
| 781 |
"dupl", |
| 782 |
"dupli", |
| 783 |
"duplic", |
| 784 |
"duplica", |
| 785 |
"duplicat", |
| 786 |
"duplicate", |
| 787 |
"duplicate ", |
| 788 |
"duplicate 1", |
| 789 |
"dupl", |
| 790 |
"dupli", |
| 791 |
"duplic", |
| 792 |
"duplica", |
| 793 |
"duplicat", |
| 794 |
"duplicate", |
| 795 |
"duplicate ", |
| 796 |
"duplicate 2", |
| 797 |
"dup", |
| 798 |
"dupl", |
| 799 |
"duplo", |
| 800 |
"dupl", |
| 801 |
"dupli", |
| 802 |
"duplic", |
| 803 |
"duplica", |
| 804 |
"duplicat", |
| 805 |
"duplicate", |
| 806 |
"duplicate ", |
| 807 |
"duplicate 2", |
| 808 |
"dupl", |
| 809 |
"dupli", |
| 810 |
"duplic", |
| 811 |
"duplica", |
| 812 |
"duplicat", |
| 813 |
"duplicate", |
| 814 |
"duplicate ", |
| 815 |
"duplicate 3", |
| 816 |
"duplic", |
| 817 |
"duplica", |
| 818 |
"duplicat", |
| 819 |
"duplicate", |
| 820 |
"duplicate ", |
| 821 |
"duplicate 3", |
| 822 |
"duplica", |
| 823 |
"duplicar", |
| 824 |
"duplica", |
| 825 |
"duplicat", |
| 826 |
"duplicate", |
| 827 |
"duplicate ", |
| 828 |
"duplicate 4", |
| 829 |
"du", |
| 830 |
"dup", |
| 831 |
"dupl", |
| 832 |
"dupli", |
| 833 |
"duplic", |
| 834 |
"duplica", |
| 835 |
"duplicat", |
| 836 |
"duplicate", |
| 837 |
"duplicate ", |
| 838 |
"duplicate 4", |
| 839 |
"dup", |
| 840 |
"dupl", |
| 841 |
"dupli", |
| 842 |
"duplic", |
| 843 |
"duplica", |
| 844 |
"duplicat", |
| 845 |
"duplicate", |
| 846 |
"duplicate ", |
| 847 |
"duplicate 5", |
| 848 |
"dun", |
| 849 |
"dunk", |
| 850 |
], |
| 851 |
); |
| 852 |
} |
| 853 |
} |