Debian Codegraph @

third_party/rust/suggest/src/store.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::{hash_map::Entry, HashMap, HashSet},
8 path::{Path, PathBuf},
9 sync::Arc,
10 };
11
12 use error_support::{breadcrumb, handle_error, trace};
13 use once_cell::sync::OnceCell;
14 use parking_lot::Mutex;
15 use remote_settings::{self, RemoteSettingsError, RemoteSettingsServer, RemoteSettingsService};
16
17 use serde::de::DeserializeOwned;
18
19 use crate::{
20 config::{SuggestGlobalConfig, SuggestProviderConfig},
21 db::{ConnectionType, IngestedRecord, Sqlite3Extension, SuggestDao, SuggestDb},
22 error::Error,
23 geoname::{Geoname, GeonameAlternates, GeonameMatch},
24 metrics::{MetricsContext, SuggestIngestionMetrics, SuggestQueryMetrics},
25 provider::{SuggestionProvider, SuggestionProviderConstraints, DEFAULT_INGEST_PROVIDERS},
26 rs::{
27 Client, Collection, DownloadedDynamicRecord, Record, SuggestAttachment, SuggestRecord,
28 SuggestRecordId, SuggestRecordType, SuggestRemoteSettingsClient,
29 },
30 QueryWithMetricsResult, Result, SuggestApiResult, Suggestion, SuggestionQuery,
31 };
32
33 /// Builder for [SuggestStore]
34 ///
35 /// Using a builder is preferred to calling the constructor directly since it's harder to confuse
36 /// the data_path and cache_path strings.
37 #[derive(uniffi::Object)]
38 pub struct SuggestStoreBuilder(Mutex<SuggestStoreBuilderInner>);
39
40 #[derive(Default)]
41 struct SuggestStoreBuilderInner {
42 data_path: Option<String>,
43 remote_settings_server: Option<RemoteSettingsServer>,
44 remote_settings_service: Option<Arc<RemoteSettingsService>>,
45 remote_settings_bucket_name: Option<String>,
46 extensions_to_load: Vec<Sqlite3Extension>,
47 }
48
49 impl Default for SuggestStoreBuilder {
50 fn default() -> Self {
51 Self::new()
52 }
53 }
54
55 #[uniffi::export]
56 impl SuggestStoreBuilder {
57 #[uniffi::constructor]
58 pub fn new() -> SuggestStoreBuilder {
59 Self(Mutex::new(SuggestStoreBuilderInner::default()))
60 }
61
62 pub fn data_path(self: Arc<Self>, path: String) -> Arc<Self> {
63 self.0.lock().data_path = Some(path);
64 self
65 }
66
67 /// Deprecated: this is no longer used by the suggest component.
68 pub fn cache_path(self: Arc<Self>, _path: String) -> Arc<Self> {
69 // We used to use this, but we're not using it anymore, just ignore the call
70 self
71 }
72
73 pub fn remote_settings_server(self: Arc<Self>, server: RemoteSettingsServer) -> Arc<Self> {
74 self.0.lock().remote_settings_server = Some(server);
75 self
76 }
77
78 pub fn remote_settings_bucket_name(self: Arc<Self>, bucket_name: String) -> Arc<Self> {
79 self.0.lock().remote_settings_bucket_name = Some(bucket_name);
80 self
81 }
82
83 pub fn remote_settings_service(
84 self: Arc<Self>,
85 rs_service: Arc<RemoteSettingsService>,
86 ) -> Arc<Self> {
87 self.0.lock().remote_settings_service = Some(rs_service);
88 self
89 }
90
91 /// Add an sqlite3 extension to load
92 ///
93 /// library_name should be the name of the library without any extension, for example `libmozsqlite3`.
94 /// entrypoint should be the entry point, for example `sqlite3_fts5_init`. If `null` (the default)
95 /// entry point will be used (see https://sqlite.org/loadext.html for details).
96 pub fn load_extension(
97 self: Arc<Self>,
98 library: String,
99 entry_point: Option<String>,
100 ) -> Arc<Self> {
101 self.0.lock().extensions_to_load.push(Sqlite3Extension {
102 library,
103 entry_point,
104 });
105 self
106 }
107
108 #[handle_error(Error)]
109 pub fn build(&self) -> SuggestApiResult<Arc<SuggestStore>> {
110 let inner = self.0.lock();
111 let extensions_to_load = inner.extensions_to_load.clone();
112 let data_path = inner
113 .data_path
114 .clone()
115 .ok_or_else(|| Error::SuggestStoreBuilder("data_path not specified".to_owned()))?;
116 let rs_service = inner.remote_settings_service.clone().ok_or_else(|| {
117 Error::RemoteSettings(RemoteSettingsError::Other {
118 reason: "remote_settings_service_not_specified".to_string(),
119 })
120 })?;
121 Ok(Arc::new(SuggestStore {
122 inner: SuggestStoreInner::new(
123 data_path,
124 extensions_to_load,
125 SuggestRemoteSettingsClient::new(&rs_service),
126 ),
127 }))
128 }
129 }
130
131 /// What should be interrupted when [SuggestStore::interrupt] is called?
132 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, uniffi::Enum)]
133 pub enum InterruptKind {
134 /// Interrupt read operations like [SuggestStore::query]
135 Read,
136 /// Interrupt write operations. This mostly means [SuggestStore::ingest], but
137 /// other operations may also be interrupted.
138 Write,
139 /// Interrupt both read and write operations,
140 ReadWrite,
141 }
142
143 /// The store is the entry point to the Suggest component. It incrementally
144 /// downloads suggestions from the Remote Settings service, stores them in a
145 /// local database, and returns them in response to user queries.
146 ///
147 /// Your application should create a single store, and manage it as a singleton.
148 /// The store is thread-safe, and supports concurrent queries and ingests. We
149 /// expect that your application will call [`SuggestStore::query()`] to show
150 /// suggestions as the user types into the address bar, and periodically call
151 /// [`SuggestStore::ingest()`] in the background to update the database with
152 /// new suggestions from Remote Settings.
153 ///
154 /// For responsiveness, we recommend always calling `query()` on a worker
155 /// thread. When the user types new input into the address bar, call
156 /// [`SuggestStore::interrupt()`] on the main thread to cancel the query
157 /// for the old input, and unblock the worker thread for the new query.
158 ///
159 /// The store keeps track of the state needed to support incremental ingestion,
160 /// but doesn't schedule the ingestion work itself, or decide how many
161 /// suggestions to ingest at once. This is for two reasons:
162 ///
163 /// 1. The primitives for scheduling background work vary between platforms, and
164 /// aren't available to the lower-level Rust layer. You might use an idle
165 /// timer on Desktop, `WorkManager` on Android, or `BGTaskScheduler` on iOS.
166 /// 2. Ingestion constraints can change, depending on the platform and the needs
167 /// of your application. A mobile device on a metered connection might want
168 /// to request a small subset of the Suggest data and download the rest
169 /// later, while a desktop on a fast link might download the entire dataset
170 /// on the first launch.
171 #[derive(uniffi::Object)]
172 pub struct SuggestStore {
173 inner: SuggestStoreInner<SuggestRemoteSettingsClient>,
174 }
175
176 #[uniffi::export]
177 impl SuggestStore {
178 /// Creates a Suggest store.
179 #[uniffi::constructor()]
180 pub fn new(path: &str, remote_settings_service: Arc<RemoteSettingsService>) -> Self {
181 let client = SuggestRemoteSettingsClient::new(&remote_settings_service);
182 Self {
183 inner: SuggestStoreInner::new(path.to_owned(), vec![], client),
184 }
185 }
186
187 /// Queries the database for suggestions.
188 #[handle_error(Error)]
189 pub fn query(&self, query: SuggestionQuery) -> SuggestApiResult<Vec<Suggestion>> {
190 Ok(self.inner.query(query)?.suggestions)
191 }
192
193 /// Queries the database for suggestions.
194 #[handle_error(Error)]
195 pub fn query_with_metrics(
196 &self,
197 query: SuggestionQuery,
198 ) -> SuggestApiResult<QueryWithMetricsResult> {
199 self.inner.query(query)
200 }
201
202 /// Dismiss a suggestion.
203 ///
204 /// Dismissed suggestions cannot be fetched again.
205 #[handle_error(Error)]
206 pub fn dismiss_by_suggestion(&self, suggestion: &Suggestion) -> SuggestApiResult<()> {
207 self.inner.dismiss_by_suggestion(suggestion)
208 }
209
210 /// Dismiss a suggestion by its dismissal key.
211 ///
212 /// Dismissed suggestions cannot be fetched again.
213 ///
214 /// Prefer [SuggestStore::dismiss_by_suggestion] if you have a
215 /// `crate::Suggestion`. This method is intended for cases where a
216 /// suggestion originates outside this component.
217 #[handle_error(Error)]
218 pub fn dismiss_by_key(&self, key: &str) -> SuggestApiResult<()> {
219 self.inner.dismiss_by_key(key)
220 }
221
222 /// Deprecated, use [SuggestStore::dismiss_by_suggestion] or
223 /// [SuggestStore::dismiss_by_key] instead.
224 ///
225 /// Dismiss a suggestion
226 ///
227 /// Dismissed suggestions will not be returned again
228 #[handle_error(Error)]
229 pub fn dismiss_suggestion(&self, suggestion_url: String) -> SuggestApiResult<()> {
230 self.inner.dismiss_suggestion(suggestion_url)
231 }
232
233 /// Clear dismissed suggestions
234 #[handle_error(Error)]
235 pub fn clear_dismissed_suggestions(&self) -> SuggestApiResult<()> {
236 self.inner.clear_dismissed_suggestions()
237 }
238
239 /// Return whether a suggestion has been dismissed.
240 ///
241 /// [SuggestStore::query] will never return dismissed suggestions, so
242 /// normally you never need to know whether a `Suggestion` has been
243 /// dismissed, but this method can be used to do so.
244 #[handle_error(Error)]
245 pub fn is_dismissed_by_suggestion(&self, suggestion: &Suggestion) -> SuggestApiResult<bool> {
246 self.inner.is_dismissed_by_suggestion(suggestion)
247 }
248
249 /// Return whether a suggestion has been dismissed given its dismissal key.
250 ///
251 /// [SuggestStore::query] will never return dismissed suggestions, so
252 /// normally you never need to know whether a suggestion has been dismissed.
253 /// This method is intended for cases where a dismissal key originates
254 /// outside this component.
255 #[handle_error(Error)]
256 pub fn is_dismissed_by_key(&self, key: &str) -> SuggestApiResult<bool> {
257 self.inner.is_dismissed_by_key(key)
258 }
259
260 /// Return whether any suggestions have been dismissed.
261 #[handle_error(Error)]
262 pub fn any_dismissed_suggestions(&self) -> SuggestApiResult<bool> {
263 self.inner.any_dismissed_suggestions()
264 }
265
266 /// Interrupts any ongoing queries.
267 ///
268 /// This should be called when the user types new input into the address
269 /// bar, to ensure that they see fresh suggestions as they type. This
270 /// method does not interrupt any ongoing ingests.
271 #[uniffi::method(default(kind = None))]
272 pub fn interrupt(&self, kind: Option<InterruptKind>) {
273 self.inner.interrupt(kind)
274 }
275
276 /// Ingests new suggestions from Remote Settings.
277 #[handle_error(Error)]
278 pub fn ingest(
279 &self,
280 constraints: SuggestIngestionConstraints,
281 ) -> SuggestApiResult<SuggestIngestionMetrics> {
282 self.inner.ingest(constraints)
283 }
284
285 /// Removes all content from the database.
286 #[handle_error(Error)]
287 pub fn clear(&self) -> SuggestApiResult<()> {
288 self.inner.clear()
289 }
290
291 /// Returns global Suggest configuration data.
292 #[handle_error(Error)]
293 pub fn fetch_global_config(&self) -> SuggestApiResult<SuggestGlobalConfig> {
294 self.inner.fetch_global_config()
295 }
296
297 /// Returns per-provider Suggest configuration data.
298 #[handle_error(Error)]
299 pub fn fetch_provider_config(
300 &self,
301 provider: SuggestionProvider,
302 ) -> SuggestApiResult<Option<SuggestProviderConfig>> {
303 self.inner.fetch_provider_config(provider)
304 }
305
306 /// Fetches geonames stored in the database. A geoname represents a
307 /// geographic place.
308 ///
309 /// See `fetch_geonames` in `geoname.rs` for documentation.
310 #[handle_error(Error)]
311 pub fn fetch_geonames(
312 &self,
313 query: &str,
314 match_name_prefix: bool,
315 filter: Option<Vec<Geoname>>,
316 ) -> SuggestApiResult<Vec<GeonameMatch>> {
317 self.inner.fetch_geonames(query, match_name_prefix, filter)
318 }
319
320 /// Fetches a geoname's names stored in the database.
321 ///
322 /// See `fetch_geoname_alternates` in `geoname.rs` for documentation.
323 #[handle_error(Error)]
324 pub fn fetch_geoname_alternates(
325 &self,
326 geoname: &Geoname,
327 ) -> SuggestApiResult<GeonameAlternates> {
328 self.inner.fetch_geoname_alternates(geoname)
329 }
330 }
331
332 impl SuggestStore {
333 pub fn force_reingest(&self) {
334 self.inner.force_reingest()
335 }
336 }
337
338 #[cfg(feature = "benchmark_api")]
339 impl SuggestStore {
340 /// Creates a WAL checkpoint. This will cause changes in the write-ahead log
341 /// to be written to the DB. See:
342 /// https://sqlite.org/pragma.html#pragma_wal_checkpoint
343 pub fn checkpoint(&self) {
344 self.inner.checkpoint();
345 }
346 }
347
348 /// Constraints limit which suggestions to ingest from Remote Settings.
349 #[derive(Clone, Default, Debug, uniffi::Record)]
350 pub struct SuggestIngestionConstraints {
351 #[uniffi(default = None)]
352 pub providers: Option<Vec<SuggestionProvider>>,
353 #[uniffi(default = None)]
354 pub provider_constraints: Option<SuggestionProviderConstraints>,
355 /// Only run ingestion if the table `suggestions` is empty
356 ///
357 // This is indented to handle periodic updates. Consumers can schedule an ingest with
358 // `empty_only=true` on startup and a regular ingest with `empty_only=false` to run on a long periodic schedule (maybe
359 // once a day). This allows ingestion to normally be run at a slow, periodic rate. However, if
360 // there is a schema upgrade that causes the database to be thrown away, then the
361 // `empty_only=true` ingestion that runs on startup will repopulate it.
362 #[uniffi(default = false)]
363 pub empty_only: bool,
364 }
365
366 impl SuggestIngestionConstraints {
367 pub fn all_providers() -> Self {
368 Self {
369 providers: Some(vec![
370 SuggestionProvider::Amp,
371 SuggestionProvider::Wikipedia,
372 SuggestionProvider::Amo,
373 SuggestionProvider::Pocket,
374 SuggestionProvider::Yelp,
375 SuggestionProvider::Mdn,
376 SuggestionProvider::Weather,
377 SuggestionProvider::Fakespot,
378 SuggestionProvider::Dynamic,
379 ]),
380 ..Self::default()
381 }
382 }
383
384 fn matches_dynamic_record(&self, record: &DownloadedDynamicRecord) -> bool {
385 match self
386 .provider_constraints
387 .as_ref()
388 .and_then(|c| c.dynamic_suggestion_types.as_ref())
389 {
390 None => false,
391 Some(suggestion_types) => suggestion_types
392 .iter()
393 .any(|t| *t == record.suggestion_type),
394 }
395 }
396
397 fn amp_matching_uses_fts(&self) -> bool {
398 self.provider_constraints
399 .as_ref()
400 .and_then(|c| c.amp_alternative_matching.as_ref())
401 .map(|constraints| constraints.uses_fts())
402 .unwrap_or(false)
403 }
404 }
405
406 /// The implementation of the store. This is generic over the Remote Settings
407 /// client, and is split out from the concrete [`SuggestStore`] for testing
408 /// with a mock client.
409 pub(crate) struct SuggestStoreInner<S> {
410 /// Path to the persistent SQL database.
411 ///
412 /// This stores things that should persist when the user clears their cache.
413 /// It's not currently used because not all consumers pass this in yet.
414 #[allow(unused)]
415 data_path: PathBuf,
416 dbs: OnceCell<SuggestStoreDbs>,
417 extensions_to_load: Vec<Sqlite3Extension>,
418 settings_client: S,
419 }
420
421 impl<S> SuggestStoreInner<S> {
422 pub fn new(
423 data_path: impl Into<PathBuf>,
424 extensions_to_load: Vec<Sqlite3Extension>,
425 settings_client: S,
426 ) -> Self {
427 Self {
428 data_path: data_path.into(),
429 extensions_to_load,
430 dbs: OnceCell::new(),
431 settings_client,
432 }
433 }
434
435 /// Returns this store's database connections, initializing them if
436 /// they're not already open.
437 fn dbs(&self) -> Result<&SuggestStoreDbs> {
438 self.dbs
439 .get_or_try_init(|| SuggestStoreDbs::open(&self.data_path, &self.extensions_to_load))
440 }
441
442 fn query(&self, query: SuggestionQuery) -> Result<QueryWithMetricsResult> {
443 let mut metrics = SuggestQueryMetrics::default();
444 let mut suggestions = vec![];
445
446 let unique_providers = query.providers.iter().collect::<HashSet<_>>();
447 let reader = &self.dbs()?.reader;
448 for provider in unique_providers {
449 let new_suggestions = metrics.measure_query(provider.to_string(), || {
450 reader.read(|dao| match provider {
451 SuggestionProvider::Amp => dao.fetch_amp_suggestions(&query),
452 SuggestionProvider::Wikipedia => dao.fetch_wikipedia_suggestions(&query),
453 SuggestionProvider::Amo => dao.fetch_amo_suggestions(&query),
454 SuggestionProvider::Pocket => dao.fetch_pocket_suggestions(&query),
455 SuggestionProvider::Yelp => dao.fetch_yelp_suggestions(&query),
456 SuggestionProvider::Mdn => dao.fetch_mdn_suggestions(&query),
457 SuggestionProvider::Weather => dao.fetch_weather_suggestions(&query),
458 SuggestionProvider::Fakespot => dao.fetch_fakespot_suggestions(&query),
459 SuggestionProvider::Dynamic => dao.fetch_dynamic_suggestions(&query),
460 })
461 })?;
462 suggestions.extend(new_suggestions);
463 }
464
465 // Note: it's important that this is a stable sort to keep the intra-provider order stable.
466 // For example, we can return multiple fakespot-suggestions all with `score=0.245`. In
467 // that case, they must be in the same order that `fetch_fakespot_suggestions` returned
468 // them in.
469 suggestions.sort();
470 if let Some(limit) = query.limit.and_then(|limit| usize::try_from(limit).ok()) {
471 suggestions.truncate(limit);
472 }
473 Ok(QueryWithMetricsResult {
474 suggestions,
475 query_times: metrics.times,
476 })
477 }
478
479 fn dismiss_by_suggestion(&self, suggestion: &Suggestion) -> Result<()> {
480 if let Some(key) = suggestion.dismissal_key() {
481 self.dismiss_by_key(key)?;
482 }
483 Ok(())
484 }
485
486 fn dismiss_by_key(&self, key: &str) -> Result<()> {
487 self.dbs()?.writer.write(|dao| dao.insert_dismissal(key))
488 }
489
490 fn dismiss_suggestion(&self, suggestion_url: String) -> Result<()> {
491 self.dbs()?
492 .writer
493 .write(|dao| dao.insert_dismissal(&suggestion_url))
494 }
495
496 fn clear_dismissed_suggestions(&self) -> Result<()> {
497 self.dbs()?.writer.write(|dao| dao.clear_dismissals())?;
498 Ok(())
499 }
500
501 fn is_dismissed_by_suggestion(&self, suggestion: &Suggestion) -> Result<bool> {
502 if let Some(key) = suggestion.dismissal_key() {
503 self.dbs()?.reader.read(|dao| dao.has_dismissal(key))
504 } else {
505 Ok(false)
506 }
507 }
508
509 fn is_dismissed_by_key(&self, key: &str) -> Result<bool> {
510 self.dbs()?.reader.read(|dao| dao.has_dismissal(key))
511 }
512
513 fn any_dismissed_suggestions(&self) -> Result<bool> {
514 self.dbs()?.reader.read(|dao| dao.any_dismissals())
515 }
516
517 fn interrupt(&self, kind: Option<InterruptKind>) {
518 if let Some(dbs) = self.dbs.get() {
519 // Only interrupt if the databases are already open.
520 match kind.unwrap_or(InterruptKind::Read) {
521 InterruptKind::Read => {
522 dbs.reader.interrupt_handle.interrupt();
523 }
524 InterruptKind::Write => {
525 dbs.writer.interrupt_handle.interrupt();
526 }
527 InterruptKind::ReadWrite => {
528 dbs.reader.interrupt_handle.interrupt();
529 dbs.writer.interrupt_handle.interrupt();
530 }
531 }
532 }
533 }
534
535 fn clear(&self) -> Result<()> {
536 self.dbs()?.writer.write(|dao| dao.clear())
537 }
538
539 pub fn fetch_global_config(&self) -> Result<SuggestGlobalConfig> {
540 self.dbs()?.reader.read(|dao| dao.get_global_config())
541 }
542
543 pub fn fetch_provider_config(
544 &self,
545 provider: SuggestionProvider,
546 ) -> Result<Option<SuggestProviderConfig>> {
547 self.dbs()?
548 .reader
549 .read(|dao| dao.get_provider_config(provider))
550 }
551
552 // Cause the next ingestion to re-ingest all data
553 pub fn force_reingest(&self) {
554 let writer = &self.dbs().unwrap().writer;
555 writer.write(|dao| dao.force_reingest()).unwrap();
556 }
557
558 fn fetch_geonames(
559 &self,
560 query: &str,
561 match_name_prefix: bool,
562 filter: Option<Vec<Geoname>>,
563 ) -> Result<Vec<GeonameMatch>> {
564 self.dbs()?.reader.read(|dao| {
565 dao.fetch_geonames(
566 query,
567 match_name_prefix,
568 filter.as_ref().map(|f| f.iter().collect()),
569 )
570 })
571 }
572
573 pub fn fetch_geoname_alternates(&self, geoname: &Geoname) -> Result<GeonameAlternates> {
574 self.dbs()?
575 .reader
576 .read(|dao| dao.fetch_geoname_alternates(geoname))
577 }
578 }
579
580 impl<S> SuggestStoreInner<S>
581 where
582 S: Client,
583 {
584 pub fn ingest(
585 &self,
586 constraints: SuggestIngestionConstraints,
587 ) -> Result<SuggestIngestionMetrics> {
588 breadcrumb!("Ingestion starting");
589 let writer = &self.dbs()?.writer;
590 let mut metrics = SuggestIngestionMetrics::default();
591 if constraints.empty_only && !writer.read(|dao| dao.suggestions_table_empty())? {
592 return Ok(metrics);
593 }
594
595 // Figure out which record types we're ingesting and group them by
596 // collection. A record type may be used by multiple providers, but we
597 // want to ingest each one at most once. We always ingest some types
598 // like global config.
599 let mut record_types_by_collection = HashMap::from([(
600 Collection::Other,
601 HashSet::from([SuggestRecordType::GlobalConfig]),
602 )]);
603 for provider in constraints
604 .providers
605 .as_ref()
606 .unwrap_or(&DEFAULT_INGEST_PROVIDERS.to_vec())
607 .iter()
608 {
609 for (collection, provider_rts) in provider.record_types_by_collection() {
610 record_types_by_collection
611 .entry(collection)
612 .or_default()
613 .extend(provider_rts.into_iter());
614 }
615 }
616
617 // Create a single write scope for all DB operations
618 let mut write_scope = writer.write_scope()?;
619
620 // Read the previously ingested records. We use this to calculate what's changed
621 let ingested_records = write_scope.read(|dao| dao.get_ingested_records())?;
622
623 // For each collection, fetch all records
624 for (collection, record_types) in record_types_by_collection {
625 breadcrumb!("Ingesting collection {}", collection.name());
626 let records = self.settings_client.get_records(collection)?;
627
628 // For each record type in that collection, calculate the changes and pass them to
629 // [Self::ingest_records]
630 for record_type in record_types {
631 breadcrumb!("Ingesting record_type: {record_type}");
632 metrics.measure_ingest(record_type.to_string(), |context| {
633 let changes = RecordChanges::new(
634 records.iter().filter(|r| r.record_type() == record_type),
635 ingested_records.iter().filter(|i| {
636 i.record_type == record_type.as_str()
637 && i.collection == collection.name()
638 }),
639 );
640 write_scope.write(|dao| {
641 self.process_changes(dao, collection, changes, &constraints, context)
642 })
643 })?;
644 write_scope.err_if_interrupted()?;
645 }
646 }
647 breadcrumb!("Ingestion complete");
648
649 Ok(metrics)
650 }
651
652 fn process_changes(
653 &self,
654 dao: &mut SuggestDao,
655 collection: Collection,
656 changes: RecordChanges<'_>,
657 constraints: &SuggestIngestionConstraints,
658 context: &mut MetricsContext,
659 ) -> Result<()> {
660 for record in &changes.new {
661 trace!("Ingesting record ID: {}", record.id.as_str());
662 self.process_record(dao, record, constraints, context)?;
663 }
664 for record in &changes.updated {
665 // Drop any data that we previously ingested from this record.
666 // Suggestions in particular don't have a stable identifier, and
667 // determining which suggestions in the record actually changed is
668 // more complicated than dropping and re-ingesting all of them.
669 trace!("Reingesting updated record ID: {}", record.id.as_str());
670 dao.delete_record_data(&record.id)?;
671 self.process_record(dao, record, constraints, context)?;
672 }
673 for record in &changes.unchanged {
674 if self.should_reprocess_record(dao, record, constraints)? {
675 trace!("Reingesting unchanged record ID: {}", record.id.as_str());
676 self.process_record(dao, record, constraints, context)?;
677 } else {
678 trace!("Skipping unchanged record ID: {}", record.id.as_str());
679 }
680 }
681 for record in &changes.deleted {
682 trace!("Deleting record ID: {:?}", record.id);
683 dao.delete_record_data(&record.id)?;
684 }
685 dao.update_ingested_records(
686 collection.name(),
687 &changes.new,
688 &changes.updated,
689 &changes.deleted,
690 )?;
691 Ok(())
692 }
693
694 fn process_record(
695 &self,
696 dao: &mut SuggestDao,
697 record: &Record,
698 constraints: &SuggestIngestionConstraints,
699 context: &mut MetricsContext,
700 ) -> Result<()> {
701 match &record.payload {
702 SuggestRecord::Amp => {
703 self.download_attachment(dao, record, context, |dao, record_id, suggestions| {
704 dao.insert_amp_suggestions(
705 record_id,
706 suggestions,
707 constraints.amp_matching_uses_fts(),
708 )
709 })?;
710 }
711 SuggestRecord::Wikipedia => {
712 self.download_attachment(dao, record, context, |dao, record_id, suggestions| {
713 dao.insert_wikipedia_suggestions(record_id, suggestions)
714 })?;
715 }
716 SuggestRecord::Icon => {
717 let (Some(icon_id), Some(attachment)) =
718 (record.id.as_icon_id(), record.attachment.as_ref())
719 else {
720 // An icon record should have an icon ID and an
721 // attachment. Icons that don't have these are
722 // malformed, so skip to the next record.
723 return Ok(());
724 };
725 let data = context
726 .measure_download(|| self.settings_client.download_attachment(record))?;
727 dao.put_icon(icon_id, &data, &attachment.mimetype)?;
728 }
729 SuggestRecord::Amo => {
730 self.download_attachment(dao, record, context, |dao, record_id, suggestions| {
731 dao.insert_amo_suggestions(record_id, suggestions)
732 })?;
733 }
734 SuggestRecord::Pocket => {
735 self.download_attachment(dao, record, context, |dao, record_id, suggestions| {
736 dao.insert_pocket_suggestions(record_id, suggestions)
737 })?;
738 }
739 SuggestRecord::Yelp => {
740 self.download_attachment(dao, record, context, |dao, record_id, suggestions| {
741 match suggestions.first() {
742 Some(suggestion) => dao.insert_yelp_suggestions(record_id, suggestion),
743 None => Ok(()),
744 }
745 })?;
746 }
747 SuggestRecord::Mdn => {
748 self.download_attachment(dao, record, context, |dao, record_id, suggestions| {
749 dao.insert_mdn_suggestions(record_id, suggestions)
750 })?;
751 }
752 SuggestRecord::Weather => self.process_weather_record(dao, record, context)?,
753 SuggestRecord::GlobalConfig(config) => {
754 dao.put_global_config(&SuggestGlobalConfig::from(config))?
755 }
756 SuggestRecord::Fakespot => {
757 self.download_attachment(dao, record, context, |dao, record_id, suggestions| {
758 dao.insert_fakespot_suggestions(record_id, suggestions)
759 })?;
760 }
761 SuggestRecord::Dynamic(r) => {
762 if constraints.matches_dynamic_record(r) {
763 self.download_attachment(
764 dao,
765 record,
766 context,
767 |dao, record_id, suggestions| {
768 dao.insert_dynamic_suggestions(record_id, r, suggestions)
769 },
770 )?;
771 }
772 }
773 SuggestRecord::Geonames => self.process_geonames_record(dao, record, context)?,
774 SuggestRecord::GeonamesAlternates => {
775 self.process_geonames_alternates_record(dao, record, context)?
776 }
777 }
778 Ok(())
779 }
780
781 pub(crate) fn download_attachment<T>(
782 &self,
783 dao: &mut SuggestDao,
784 record: &Record,
785 context: &mut MetricsContext,
786 ingestion_handler: impl FnOnce(&mut SuggestDao<'_>, &SuggestRecordId, &[T]) -> Result<()>,
787 ) -> Result<()>
788 where
789 T: DeserializeOwned,
790 {
791 if record.attachment.is_none() {
792 return Ok(());
793 };
794
795 let attachment_data =
796 context.measure_download(|| self.settings_client.download_attachment(record))?;
797 match serde_json::from_slice::<SuggestAttachment<T>>(&attachment_data) {
798 Ok(attachment) => ingestion_handler(dao, &record.id, attachment.suggestions()),
799 // If the attachment doesn't match our expected schema, just skip it. It's possible
800 // that we're using an older version. If so, we'll get the data when we re-ingest
801 // after updating the schema.
802 Err(_) => Ok(()),
803 }
804 }
805
806 fn should_reprocess_record(
807 &self,
808 dao: &mut SuggestDao,
809 record: &Record,
810 constraints: &SuggestIngestionConstraints,
811 ) -> Result<bool> {
812 match &record.payload {
813 SuggestRecord::Dynamic(r) => Ok(!dao
814 .are_suggestions_ingested_for_record(&record.id)?
815 && constraints.matches_dynamic_record(r)),
816 SuggestRecord::Amp => {
817 Ok(constraints.amp_matching_uses_fts()
818 && !dao.is_amp_fts_data_ingested(&record.id)?)
819 }
820 _ => Ok(false),
821 }
822 }
823 }
824
825 /// Tracks changes in suggest records since the last ingestion
826 struct RecordChanges<'a> {
827 new: Vec<&'a Record>,
828 updated: Vec<&'a Record>,
829 deleted: Vec<&'a IngestedRecord>,
830 unchanged: Vec<&'a Record>,
831 }
832
833 impl<'a> RecordChanges<'a> {
834 fn new(
835 current: impl Iterator<Item = &'a Record>,
836 previously_ingested: impl Iterator<Item = &'a IngestedRecord>,
837 ) -> Self {
838 let mut ingested_map: HashMap<&str, &IngestedRecord> =
839 previously_ingested.map(|i| (i.id.as_str(), i)).collect();
840 // Iterate through current, finding new/updated records.
841 // Remove existing records from ingested_map.
842 let mut new = vec![];
843 let mut updated = vec![];
844 let mut unchanged = vec![];
845 for r in current {
846 match ingested_map.entry(r.id.as_str()) {
847 Entry::Vacant(_) => new.push(r),
848 Entry::Occupied(e) => {
849 if e.remove().last_modified != r.last_modified {
850 updated.push(r);
851 } else {
852 unchanged.push(r);
853 }
854 }
855 }
856 }
857 // Anything left in ingested_map is a deleted record
858 let deleted = ingested_map.into_values().collect();
859 Self {
860 new,
861 deleted,
862 updated,
863 unchanged,
864 }
865 }
866 }
867
868 #[cfg(feature = "benchmark_api")]
869 impl<S> SuggestStoreInner<S>
870 where
871 S: Client,
872 {
873 pub fn into_settings_client(self) -> S {
874 self.settings_client
875 }
876
877 pub fn ensure_db_initialized(&self) {
878 self.dbs().unwrap();
879 }
880
881 fn checkpoint(&self) {
882 let conn = self.dbs().unwrap().writer.conn.lock();
883 conn.pragma_update(None, "wal_checkpoint", "TRUNCATE")
884 .expect("Error performing checkpoint");
885 }
886
887 pub fn ingest_records_by_type(
888 &self,
889 collection: Collection,
890 ingest_record_type: SuggestRecordType,
891 ) {
892 let writer = &self.dbs().unwrap().writer;
893 let mut context = MetricsContext::default();
894 let ingested_records = writer.read(|dao| dao.get_ingested_records()).unwrap();
895 let records = self.settings_client.get_records(collection).unwrap();
896
897 let changes = RecordChanges::new(
898 records
899 .iter()
900 .filter(|r| r.record_type() == ingest_record_type),
901 ingested_records
902 .iter()
903 .filter(|i| i.record_type == ingest_record_type.as_str()),
904 );
905 writer
906 .write(|dao| {
907 self.process_changes(
908 dao,
909 collection,
910 changes,
911 &SuggestIngestionConstraints::default(),
912 &mut context,
913 )
914 })
915 .unwrap();
916 }
917
918 pub fn table_row_counts(&self) -> Vec<(String, u32)> {
919 use sql_support::ConnExt;
920
921 // Note: since this is just used for debugging, use unwrap to simplify the error handling.
922 let reader = &self.dbs().unwrap().reader;
923 let conn = reader.conn.lock();
924 let table_names: Vec<String> = conn
925 .query_rows_and_then(
926 "SELECT name FROM sqlite_master where type = 'table'",
927 (),
928 |row| row.get(0),
929 )
930 .unwrap();
931 let mut table_names_with_counts: Vec<(String, u32)> = table_names
932 .into_iter()
933 .map(|name| {
934 let count: u32 = conn
935 .query_one(&format!("SELECT COUNT(*) FROM {name}"))
936 .unwrap();
937 (name, count)
938 })
939 .collect();
940 table_names_with_counts.sort_by(|a, b| (b.1.cmp(&a.1)));
941 table_names_with_counts
942 }
943
944 pub fn db_size(&self) -> usize {
945 use sql_support::ConnExt;
946
947 let reader = &self.dbs().unwrap().reader;
948 let conn = reader.conn.lock();
949 conn.query_one("SELECT page_size * page_count FROM pragma_page_count(), pragma_page_size()")
950 .unwrap()
951 }
952 }
953
954 /// Holds a store's open connections to the Suggest database.
955 struct SuggestStoreDbs {
956 /// A read-write connection used to update the database with new data.
957 writer: SuggestDb,
958 /// A read-only connection used to query the database.
959 reader: SuggestDb,
960 }
961
962 impl SuggestStoreDbs {
963 fn open(path: &Path, extensions_to_load: &[Sqlite3Extension]) -> Result<Self> {
964 // Order is important here: the writer must be opened first, so that it
965 // can set up the database and run any migrations.
966 let writer = SuggestDb::open(path, extensions_to_load, ConnectionType::ReadWrite)?;
967 let reader = SuggestDb::open(path, extensions_to_load, ConnectionType::ReadOnly)?;
968 Ok(Self { writer, reader })
969 }
970 }
971
972 #[cfg(test)]
973 pub(crate) mod tests {
974 use super::*;
975 use crate::suggestion::YelpSubjectType;
976
977 use std::sync::atomic::{AtomicUsize, Ordering};
978
979 use crate::{
980 db::DEFAULT_SUGGESTION_SCORE, provider::AmpMatchingStrategy, suggestion::FtsMatchInfo,
981 testing::*, SuggestionProvider,
982 };
983
984 // Extra methods for the tests
985 impl SuggestIngestionConstraints {
986 fn amp_with_fts() -> Self {
987 Self {
988 providers: Some(vec![SuggestionProvider::Amp]),
989 provider_constraints: Some(SuggestionProviderConstraints {
990 amp_alternative_matching: Some(AmpMatchingStrategy::FtsAgainstFullKeywords),
991 ..SuggestionProviderConstraints::default()
992 }),
993 ..Self::default()
994 }
995 }
996 fn amp_without_fts() -> Self {
997 Self {
998 providers: Some(vec![SuggestionProvider::Amp]),
999 ..Self::default()
1000 }
1001 }
1002 }
1003
1004 /// In-memory Suggest store for testing
1005 pub(crate) struct TestStore {
1006 pub inner: SuggestStoreInner<MockRemoteSettingsClient>,
1007 }
1008
1009 impl TestStore {
1010 pub fn new(client: MockRemoteSettingsClient) -> Self {
1011 static COUNTER: AtomicUsize = AtomicUsize::new(0);
1012 let db_path = format!(
1013 "file:test_store_data_{}?mode=memory&cache=shared",
1014 COUNTER.fetch_add(1, Ordering::Relaxed),
1015 );
1016 Self {
1017 inner: SuggestStoreInner::new(db_path, vec![], client),
1018 }
1019 }
1020
1021 pub fn client_mut(&mut self) -> &mut MockRemoteSettingsClient {
1022 &mut self.inner.settings_client
1023 }
1024
1025 pub fn read<T>(&self, op: impl FnOnce(&SuggestDao) -> Result<T>) -> Result<T> {
1026 self.inner.dbs().unwrap().reader.read(op)
1027 }
1028
1029 pub fn count_rows(&self, table_name: &str) -> u64 {
1030 let sql = format!("SELECT count(*) FROM {table_name}");
1031 self.read(|dao| Ok(dao.conn.query_one(&sql)?))
1032 .unwrap_or_else(|e| panic!("SQL error in count: {e}"))
1033 }
1034
1035 pub fn ingest(&self, constraints: SuggestIngestionConstraints) {
1036 self.inner.ingest(constraints).unwrap();
1037 }
1038
1039 pub fn fetch_suggestions(&self, query: SuggestionQuery) -> Vec<Suggestion> {
1040 self.inner.query(query).unwrap().suggestions
1041 }
1042
1043 pub fn fetch_global_config(&self) -> SuggestGlobalConfig {
1044 self.inner
1045 .fetch_global_config()
1046 .expect("Error fetching global config")
1047 }
1048
1049 pub fn fetch_provider_config(
1050 &self,
1051 provider: SuggestionProvider,
1052 ) -> Option<SuggestProviderConfig> {
1053 self.inner
1054 .fetch_provider_config(provider)
1055 .expect("Error fetching provider config")
1056 }
1057
1058 pub fn fetch_geonames(
1059 &self,
1060 query: &str,
1061 match_name_prefix: bool,
1062 filter: Option<Vec<Geoname>>,
1063 ) -> Vec<GeonameMatch> {
1064 self.inner
1065 .fetch_geonames(query, match_name_prefix, filter)
1066 .expect("Error fetching geonames")
1067 }
1068 }
1069
1070 /// Tests that `SuggestStore` is usable with UniFFI, which requires exposed
1071 /// interfaces to be `Send` and `Sync`.
1072 #[test]
1073 fn is_thread_safe() {
1074 before_each();
1075
1076 fn is_send_sync<T: Send + Sync>() {}
1077 is_send_sync::<SuggestStore>();
1078 }
1079
1080 /// Tests ingesting suggestions into an empty database.
1081 #[test]
1082 fn ingest_suggestions() -> anyhow::Result<()> {
1083 before_each();
1084
1085 let store = TestStore::new(
1086 MockRemoteSettingsClient::default()
1087 .with_record(SuggestionProvider::Amp.record("1234", json![los_pollos_amp()]))
1088 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon())),
1089 );
1090 store.ingest(SuggestIngestionConstraints::all_providers());
1091 assert_eq!(
1092 store.fetch_suggestions(SuggestionQuery::amp("lo")),
1093 vec![los_pollos_suggestion("los pollos", None)],
1094 );
1095 Ok(())
1096 }
1097
1098 /// Tests ingesting suggestions into an empty database.
1099 #[test]
1100 fn ingest_empty_only() -> anyhow::Result<()> {
1101 before_each();
1102
1103 let mut store = TestStore::new(
1104 MockRemoteSettingsClient::default()
1105 .with_record(SuggestionProvider::Amp.record("1234", json![los_pollos_amp()])),
1106 );
1107 // suggestions_table_empty returns true before the ingestion is complete
1108 assert!(store.read(|dao| dao.suggestions_table_empty())?);
1109 // This ingestion should run, since the DB is empty
1110 store.ingest(SuggestIngestionConstraints {
1111 empty_only: true,
1112 ..SuggestIngestionConstraints::all_providers()
1113 });
1114 // suggestions_table_empty returns false after the ingestion is complete
1115 assert!(!store.read(|dao| dao.suggestions_table_empty())?);
1116
1117 // This ingestion should not run since the DB is no longer empty
1118 store.client_mut().update_record(
1119 SuggestionProvider::Amp
1120 .record("1234", json!([los_pollos_amp(), good_place_eats_amp()])),
1121 );
1122
1123 store.ingest(SuggestIngestionConstraints {
1124 empty_only: true,
1125 ..SuggestIngestionConstraints::all_providers()
1126 });
1127 // "la" should not match the good place eats suggestion, since that should not have been
1128 // ingested.
1129 assert_eq!(store.fetch_suggestions(SuggestionQuery::amp("la")), vec![]);
1130
1131 Ok(())
1132 }
1133
1134 /// Tests ingesting suggestions with icons.
1135 #[test]
1136 fn ingest_amp_icons() -> anyhow::Result<()> {
1137 before_each();
1138
1139 let store = TestStore::new(
1140 MockRemoteSettingsClient::default()
1141 .with_record(
1142 SuggestionProvider::Amp
1143 .record("1234", json!([los_pollos_amp(), good_place_eats_amp()])),
1144 )
1145 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon()))
1146 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon())),
1147 );
1148 // This ingestion should run, since the DB is empty
1149 store.ingest(SuggestIngestionConstraints::all_providers());
1150
1151 assert_eq!(
1152 store.fetch_suggestions(SuggestionQuery::amp("lo")),
1153 vec![los_pollos_suggestion("los pollos", None)]
1154 );
1155 assert_eq!(
1156 store.fetch_suggestions(SuggestionQuery::amp("la")),
1157 vec![good_place_eats_suggestion("lasagna", None)]
1158 );
1159
1160 Ok(())
1161 }
1162
1163 #[test]
1164 fn ingest_amp_full_keywords() -> anyhow::Result<()> {
1165 before_each();
1166
1167 let store = TestStore::new(MockRemoteSettingsClient::default()
1168 .with_record(
1169 SuggestionProvider::Amp.record("1234", json!([
1170 // AMP attachment with full keyword data
1171 los_pollos_amp().merge(json!({
1172 "keywords": ["lo", "los", "los p", "los pollos", "los pollos h", "los pollos hermanos"],
1173 "full_keywords": [
1174 // Full keyword for the first 4 keywords
1175 ("los pollos", 4),
1176 // Full keyword for the next 2 keywords
1177 ("los pollos hermanos (restaurant)", 2),
1178 ],
1179 })),
1180 // AMP attachment without full keyword data
1181 good_place_eats_amp().remove("full_keywords"),
1182 ])))
1183 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon()))
1184 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon()))
1185 );
1186 store.ingest(SuggestIngestionConstraints::all_providers());
1187
1188 // (query string, expected suggestion, expected dismissal key)
1189 let tests = [
1190 (
1191 "lo",
1192 los_pollos_suggestion("los pollos", None),
1193 Some("los pollos"),
1194 ),
1195 (
1196 "los pollos",
1197 los_pollos_suggestion("los pollos", None),
1198 Some("los pollos"),
1199 ),
1200 (
1201 "los pollos h",
1202 los_pollos_suggestion("los pollos hermanos (restaurant)", None),
1203 Some("los pollos hermanos (restaurant)"),
1204 ),
1205 (
1206 "la",
1207 good_place_eats_suggestion("", None),
1208 Some("https://www.lasagna.restaurant"),
1209 ),
1210 (
1211 "lasagna",
1212 good_place_eats_suggestion("", None),
1213 Some("https://www.lasagna.restaurant"),
1214 ),
1215 (
1216 "lasagna come out tomorrow",
1217 good_place_eats_suggestion("", None),
1218 Some("https://www.lasagna.restaurant"),
1219 ),
1220 ];
1221 for (query, expected_suggestion, expected_dismissal_key) in tests {
1222 // Do a query and check the returned suggestions.
1223 let suggestions = store.fetch_suggestions(SuggestionQuery::amp(query));
1224 assert_eq!(suggestions, vec![expected_suggestion.clone()]);
1225
1226 // Check the returned suggestion's dismissal key.
1227 assert_eq!(suggestions[0].dismissal_key(), expected_dismissal_key);
1228
1229 // Dismiss the suggestion.
1230 let dismissal_key = suggestions[0].dismissal_key().unwrap();
1231 store.inner.dismiss_by_suggestion(&suggestions[0])?;
1232 assert_eq!(store.fetch_suggestions(SuggestionQuery::amp(query)), vec![]);
1233 assert!(store.inner.is_dismissed_by_suggestion(&suggestions[0])?);
1234 assert!(store.inner.is_dismissed_by_key(dismissal_key)?);
1235 assert!(store.inner.any_dismissed_suggestions()?);
1236
1237 // Clear dismissals and fetch again.
1238 store.inner.clear_dismissed_suggestions()?;
1239 assert_eq!(
1240 store.fetch_suggestions(SuggestionQuery::amp(query)),
1241 vec![expected_suggestion.clone()]
1242 );
1243 assert!(!store.inner.is_dismissed_by_suggestion(&suggestions[0])?);
1244 assert!(!store.inner.is_dismissed_by_key(dismissal_key)?);
1245 assert!(!store.inner.any_dismissed_suggestions()?);
1246
1247 // Dismiss the suggestion by its dismissal key.
1248 store.inner.dismiss_by_key(dismissal_key)?;
1249 assert_eq!(store.fetch_suggestions(SuggestionQuery::amp(query)), vec![]);
1250 assert!(store.inner.is_dismissed_by_suggestion(&suggestions[0])?);
1251 assert!(store.inner.is_dismissed_by_key(dismissal_key)?);
1252 assert!(store.inner.any_dismissed_suggestions()?);
1253
1254 // Clear dismissals and fetch again.
1255 store.inner.clear_dismissed_suggestions()?;
1256 assert_eq!(
1257 store.fetch_suggestions(SuggestionQuery::amp(query)),
1258 vec![expected_suggestion.clone()]
1259 );
1260 assert!(!store.inner.is_dismissed_by_suggestion(&suggestions[0])?);
1261 assert!(!store.inner.is_dismissed_by_key(dismissal_key)?);
1262 assert!(!store.inner.any_dismissed_suggestions()?);
1263
1264 // Dismiss the suggestion by its raw URL using the deprecated API.
1265 let raw_url = expected_suggestion.raw_url().unwrap();
1266 store.inner.dismiss_suggestion(raw_url.to_string())?;
1267 assert_eq!(store.fetch_suggestions(SuggestionQuery::amp(query)), vec![]);
1268 assert!(store.inner.is_dismissed_by_key(raw_url)?);
1269 assert!(store.inner.any_dismissed_suggestions()?);
1270
1271 // Clear dismissals and fetch again.
1272 store.inner.clear_dismissed_suggestions()?;
1273 assert_eq!(
1274 store.fetch_suggestions(SuggestionQuery::amp(query)),
1275 vec![expected_suggestion.clone()]
1276 );
1277 assert!(!store.inner.is_dismissed_by_suggestion(&suggestions[0])?);
1278 assert!(!store.inner.is_dismissed_by_key(dismissal_key)?);
1279 assert!(!store.inner.is_dismissed_by_key(raw_url)?);
1280 assert!(!store.inner.any_dismissed_suggestions()?);
1281 }
1282
1283 Ok(())
1284 }
1285
1286 #[test]
1287 fn ingest_wikipedia_full_keywords() -> anyhow::Result<()> {
1288 before_each();
1289
1290 let store = TestStore::new(
1291 MockRemoteSettingsClient::default()
1292 .with_record(SuggestionProvider::Wikipedia.record(
1293 "1234",
1294 json!([
1295 // Wikipedia attachment with full keyword data. We should ignore the full
1296 // keyword data for Wikipedia suggestions
1297 california_wiki(),
1298 // california_wiki().merge(json!({
1299 // "keywords": ["cal", "cali", "california"],
1300 // "full_keywords": [("california institute of technology", 3)],
1301 // })),
1302 ]),
1303 ))
1304 .with_record(SuggestionProvider::Wikipedia.icon(california_icon())),
1305 );
1306 store.ingest(SuggestIngestionConstraints::all_providers());
1307
1308 assert_eq!(
1309 store.fetch_suggestions(SuggestionQuery::wikipedia("cal")),
1310 // Even though this had a full_keywords field, we should ignore it since it's a
1311 // wikipedia suggestion and use the keywords.rs code instead
1312 vec![california_suggestion("california")],
1313 );
1314
1315 Ok(())
1316 }
1317
1318 #[test]
1319 fn amp_no_keyword_expansion() -> anyhow::Result<()> {
1320 before_each();
1321
1322 let store = TestStore::new(
1323 MockRemoteSettingsClient::default()
1324 // Setup the keywords such that:
1325 // * There's a `chicken` keyword, which is not a substring of any full
1326 // keywords (i.e. it was the result of keyword expansion).
1327 // * There's a `los pollos ` keyword with an extra space
1328 .with_record(
1329 SuggestionProvider::Amp.record(
1330 "1234",
1331 los_pollos_amp().merge(json!({
1332 "keywords": ["los", "los pollos", "los pollos ", "los pollos hermanos", "chicken"],
1333 "full_keywords": [("los pollos", 3), ("los pollos hermanos", 2)],
1334 }))
1335 ))
1336 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon())),
1337 );
1338 store.ingest(SuggestIngestionConstraints::all_providers());
1339 assert_eq!(
1340 store.fetch_suggestions(SuggestionQuery {
1341 provider_constraints: Some(SuggestionProviderConstraints {
1342 amp_alternative_matching: Some(AmpMatchingStrategy::NoKeywordExpansion),
1343 ..SuggestionProviderConstraints::default()
1344 }),
1345 // Should not match, because `chicken` is not a substring of a full keyword.
1346 // i.e. it was added because of keyword expansion.
1347 ..SuggestionQuery::amp("chicken")
1348 }),
1349 vec![],
1350 );
1351 assert_eq!(
1352 store.fetch_suggestions(SuggestionQuery {
1353 provider_constraints: Some(SuggestionProviderConstraints {
1354 amp_alternative_matching: Some(AmpMatchingStrategy::NoKeywordExpansion),
1355 ..SuggestionProviderConstraints::default()
1356 }),
1357 // Should match, even though "los pollos " technically is not a substring
1358 // because there's an extra space. The reason these keywords are in the DB is
1359 // because we want to keep showing the current suggestion when the user types
1360 // the space key.
1361 ..SuggestionQuery::amp("los pollos ")
1362 }),
1363 vec![los_pollos_suggestion("los pollos", None)],
1364 );
1365 Ok(())
1366 }
1367
1368 #[test]
1369 fn amp_fts_against_full_keywords() -> anyhow::Result<()> {
1370 before_each();
1371
1372 let store = TestStore::new(
1373 MockRemoteSettingsClient::default()
1374 // Make sure there's full keywords to match against
1375 .with_record(SuggestionProvider::Amp.record(
1376 "1234",
1377 los_pollos_amp().merge(json!({
1378 "keywords": ["los", "los pollos", "los pollos ", "los pollos hermanos"],
1379 "full_keywords": [("los pollos", 3), ("los pollos hermanos", 1)],
1380 })),
1381 ))
1382 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon())),
1383 );
1384 store.ingest(SuggestIngestionConstraints::amp_with_fts());
1385 assert_eq!(
1386 store.fetch_suggestions(SuggestionQuery {
1387 provider_constraints: Some(SuggestionProviderConstraints {
1388 amp_alternative_matching: Some(AmpMatchingStrategy::FtsAgainstFullKeywords),
1389 ..SuggestionProviderConstraints::default()
1390 }),
1391 // "Hermanos" should match, even though it's not listed in the keywords,
1392 // because this strategy uses an FTS match against the full keyword list.
1393 ..SuggestionQuery::amp("hermanos")
1394 }),
1395 vec![los_pollos_suggestion(
1396 "hermanos",
1397 Some(FtsMatchInfo {
1398 prefix: false,
1399 stemming: false,
1400 })
1401 )],
1402 );
1403 Ok(())
1404 }
1405
1406 #[test]
1407 fn amp_fts_against_title() -> anyhow::Result<()> {
1408 before_each();
1409
1410 let store = TestStore::new(
1411 MockRemoteSettingsClient::default()
1412 .with_record(SuggestionProvider::Amp.record("1234", los_pollos_amp()))
1413 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon())),
1414 );
1415 store.ingest(SuggestIngestionConstraints::amp_with_fts());
1416 assert_eq!(
1417 store.fetch_suggestions(SuggestionQuery {
1418 provider_constraints: Some(SuggestionProviderConstraints {
1419 amp_alternative_matching: Some(AmpMatchingStrategy::FtsAgainstTitle),
1420 ..SuggestionProviderConstraints::default()
1421 }),
1422 // "Albuquerque" should match, even though it's not listed in the keywords,
1423 // because this strategy uses an FTS match against the title
1424 ..SuggestionQuery::amp("albuquerque")
1425 }),
1426 vec![los_pollos_suggestion(
1427 "albuquerque",
1428 Some(FtsMatchInfo {
1429 prefix: false,
1430 stemming: false,
1431 })
1432 )],
1433 );
1434 Ok(())
1435 }
1436
1437 /// Tests ingesting a data attachment containing a single suggestion,
1438 /// instead of an array of suggestions.
1439 #[test]
1440 fn ingest_one_suggestion_in_data_attachment() -> anyhow::Result<()> {
1441 before_each();
1442
1443 let store = TestStore::new(
1444 MockRemoteSettingsClient::default()
1445 // This record contains just one JSON object, rather than an array of them
1446 .with_record(SuggestionProvider::Amp.record("1234", los_pollos_amp()))
1447 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon())),
1448 );
1449 store.ingest(SuggestIngestionConstraints::all_providers());
1450 assert_eq!(
1451 store.fetch_suggestions(SuggestionQuery::amp("lo")),
1452 vec![los_pollos_suggestion("los pollos", None)],
1453 );
1454
1455 Ok(())
1456 }
1457
1458 /// Tests re-ingesting suggestions from an updated attachment.
1459 #[test]
1460 fn reingest_amp_suggestions() -> anyhow::Result<()> {
1461 before_each();
1462
1463 let mut store = TestStore::new(
1464 MockRemoteSettingsClient::default().with_record(
1465 SuggestionProvider::Amp
1466 .record("1234", json!([los_pollos_amp(), good_place_eats_amp()])),
1467 ),
1468 );
1469 // Ingest once
1470 store.ingest(SuggestIngestionConstraints::all_providers());
1471 // Update the snapshot with new suggestions: Los pollos has a new name and Good place eats
1472 // is now serving Penne
1473 store
1474 .client_mut()
1475 .update_record(SuggestionProvider::Amp.record(
1476 "1234",
1477 json!([
1478 los_pollos_amp().merge(json!({
1479 "title": "Los Pollos Hermanos - Now Serving at 14 Locations!",
1480 })),
1481 good_place_eats_amp().merge(json!({
1482 "keywords": ["pe", "pen", "penne", "penne for your thoughts"],
1483 "title": "Penne for Your Thoughts",
1484 "url": "https://penne.biz",
1485 }))
1486 ]),
1487 ));
1488 store.ingest(SuggestIngestionConstraints::all_providers());
1489
1490 assert!(matches!(
1491 store.fetch_suggestions(SuggestionQuery::amp("lo")).as_slice(),
1492 [ Suggestion::Amp { title, .. } ] if title == "Los Pollos Hermanos - Now Serving at 14 Locations!",
1493 ));
1494
1495 assert_eq!(store.fetch_suggestions(SuggestionQuery::amp("la")), vec![]);
1496 assert!(matches!(
1497 store.fetch_suggestions(SuggestionQuery::amp("pe")).as_slice(),
1498 [ Suggestion::Amp { title, url, .. } ] if title == "Penne for Your Thoughts" && url == "https://penne.biz"
1499 ));
1500
1501 Ok(())
1502 }
1503
1504 #[test]
1505 fn reingest_amp_after_fts_constraint_changes() -> anyhow::Result<()> {
1506 before_each();
1507
1508 // Ingest with FTS enabled, this will populate the FTS table
1509 let store = TestStore::new(
1510 MockRemoteSettingsClient::default()
1511 .with_record(SuggestionProvider::Amp.record(
1512 "data-1",
1513 json!([los_pollos_amp().merge(json!({
1514 "keywords": ["los", "los pollos", "los pollos ", "los pollos hermanos"],
1515 "full_keywords": [("los pollos", 3), ("los pollos hermanos", 1)],
1516 }))]),
1517 ))
1518 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon())),
1519 );
1520 // Ingest without FTS
1521 store.ingest(SuggestIngestionConstraints::amp_without_fts());
1522 // Ingest again with FTS
1523 store.ingest(SuggestIngestionConstraints::amp_with_fts());
1524
1525 assert_eq!(
1526 store.fetch_suggestions(SuggestionQuery {
1527 provider_constraints: Some(SuggestionProviderConstraints {
1528 amp_alternative_matching: Some(AmpMatchingStrategy::FtsAgainstFullKeywords),
1529 ..SuggestionProviderConstraints::default()
1530 }),
1531 // "Hermanos" should match, even though it's not listed in the keywords,
1532 // because this strategy uses an FTS match against the full keyword list.
1533 ..SuggestionQuery::amp("hermanos")
1534 }),
1535 vec![los_pollos_suggestion(
1536 "hermanos",
1537 Some(FtsMatchInfo {
1538 prefix: false,
1539 stemming: false,
1540 }),
1541 )],
1542 );
1543 Ok(())
1544 }
1545
1546 /// Tests re-ingesting icons from an updated attachment.
1547 #[test]
1548 fn reingest_icons() -> anyhow::Result<()> {
1549 before_each();
1550
1551 let mut store = TestStore::new(
1552 MockRemoteSettingsClient::default()
1553 .with_record(
1554 SuggestionProvider::Amp
1555 .record("1234", json!([los_pollos_amp(), good_place_eats_amp()])),
1556 )
1557 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon()))
1558 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon())),
1559 );
1560 // This ingestion should run, since the DB is empty
1561 store.ingest(SuggestIngestionConstraints::all_providers());
1562
1563 // Reingest with updated icon data
1564 // - Los pollos gets new data and a new id
1565 // - Good place eats gets new data only
1566 store
1567 .client_mut()
1568 .update_record(SuggestionProvider::Amp.record(
1569 "1234",
1570 json!([
1571 los_pollos_amp().merge(json!({"icon": "1000"})),
1572 good_place_eats_amp()
1573 ]),
1574 ))
1575 .delete_record(SuggestionProvider::Amp.icon(los_pollos_icon()))
1576 .add_record(SuggestionProvider::Amp.icon(MockIcon {
1577 id: "1000",
1578 data: "new-los-pollos-icon",
1579 ..los_pollos_icon()
1580 }))
1581 .update_record(SuggestionProvider::Amp.icon(MockIcon {
1582 data: "new-good-place-eats-icon",
1583 ..good_place_eats_icon()
1584 }));
1585 store.ingest(SuggestIngestionConstraints::all_providers());
1586
1587 assert!(matches!(
1588 store.fetch_suggestions(SuggestionQuery::amp("lo")).as_slice(),
1589 [ Suggestion::Amp { icon, .. } ] if *icon == Some("new-los-pollos-icon".as_bytes().to_vec())
1590 ));
1591
1592 assert!(matches!(
1593 store.fetch_suggestions(SuggestionQuery::amp("la")).as_slice(),
1594 [ Suggestion::Amp { icon, .. } ] if *icon == Some("new-good-place-eats-icon".as_bytes().to_vec())
1595 ));
1596
1597 Ok(())
1598 }
1599
1600 /// Tests re-ingesting AMO suggestions from an updated attachment.
1601 #[test]
1602 fn reingest_amo_suggestions() -> anyhow::Result<()> {
1603 before_each();
1604
1605 let mut store = TestStore::new(
1606 MockRemoteSettingsClient::default()
1607 .with_record(SuggestionProvider::Amo.record("data-1", json!([relay_amo()])))
1608 .with_record(
1609 SuggestionProvider::Amo
1610 .record("data-2", json!([dark_mode_amo(), foxy_guestures_amo()])),
1611 ),
1612 );
1613
1614 store.ingest(SuggestIngestionConstraints::all_providers());
1615
1616 assert_eq!(
1617 store.fetch_suggestions(SuggestionQuery::amo("masking e")),
1618 vec![relay_suggestion()],
1619 );
1620 assert_eq!(
1621 store.fetch_suggestions(SuggestionQuery::amo("night")),
1622 vec![dark_mode_suggestion()],
1623 );
1624 assert_eq!(
1625 store.fetch_suggestions(SuggestionQuery::amo("grammar")),
1626 vec![foxy_guestures_suggestion()],
1627 );
1628
1629 // Update the snapshot with new suggestions: update the second, drop the
1630 // third, and add the fourth.
1631 store
1632 .client_mut()
1633 .update_record(SuggestionProvider::Amo.record("data-1", json!([relay_amo()])))
1634 .update_record(SuggestionProvider::Amo.record(
1635 "data-2",
1636 json!([
1637 dark_mode_amo().merge(json!({"title": "Updated second suggestion"})),
1638 new_tab_override_amo(),
1639 ]),
1640 ));
1641 store.ingest(SuggestIngestionConstraints::all_providers());
1642
1643 assert_eq!(
1644 store.fetch_suggestions(SuggestionQuery::amo("masking e")),
1645 vec![relay_suggestion()],
1646 );
1647 assert!(matches!(
1648 store.fetch_suggestions(SuggestionQuery::amo("night")).as_slice(),
1649 [Suggestion::Amo { title, .. } ] if title == "Updated second suggestion"
1650 ));
1651 assert_eq!(
1652 store.fetch_suggestions(SuggestionQuery::amo("grammar")),
1653 vec![],
1654 );
1655 assert_eq!(
1656 store.fetch_suggestions(SuggestionQuery::amo("image search")),
1657 vec![new_tab_override_suggestion()],
1658 );
1659
1660 Ok(())
1661 }
1662
1663 /// Tests ingestion when previously-ingested suggestions/icons have been deleted.
1664 #[test]
1665 fn ingest_with_deletions() -> anyhow::Result<()> {
1666 before_each();
1667
1668 let mut store = TestStore::new(
1669 MockRemoteSettingsClient::default()
1670 .with_record(SuggestionProvider::Amp.record("data-1", json!([los_pollos_amp()])))
1671 .with_record(
1672 SuggestionProvider::Amp.record("data-2", json!([good_place_eats_amp()])),
1673 )
1674 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon()))
1675 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon())),
1676 );
1677 store.ingest(SuggestIngestionConstraints::all_providers());
1678 assert_eq!(
1679 store.fetch_suggestions(SuggestionQuery::amp("lo")),
1680 vec![los_pollos_suggestion("los pollos", None)],
1681 );
1682 assert_eq!(
1683 store.fetch_suggestions(SuggestionQuery::amp("la")),
1684 vec![good_place_eats_suggestion("lasagna", None)],
1685 );
1686 // Re-ingest without los-pollos and good place eat's icon. The suggest store should
1687 // recognize that they're missing and delete them.
1688 store
1689 .client_mut()
1690 .delete_record(SuggestionProvider::Amp.empty_record("data-1"))
1691 .delete_record(SuggestionProvider::Amp.icon(good_place_eats_icon()));
1692 store.ingest(SuggestIngestionConstraints::all_providers());
1693
1694 assert_eq!(store.fetch_suggestions(SuggestionQuery::amp("lo")), vec![]);
1695 assert!(matches!(
1696 store.fetch_suggestions(SuggestionQuery::amp("la")).as_slice(),
1697 [
1698 Suggestion::Amp { icon, icon_mimetype, .. }
1699 ] if icon.is_none() && icon_mimetype.is_none(),
1700 ));
1701 Ok(())
1702 }
1703
1704 /// Tests clearing the store.
1705 #[test]
1706 fn clear() -> anyhow::Result<()> {
1707 before_each();
1708
1709 let store = TestStore::new(
1710 MockRemoteSettingsClient::default()
1711 .with_record(SuggestionProvider::Amp.record("data-1", json!([los_pollos_amp()])))
1712 .with_record(
1713 SuggestionProvider::Amp.record("data-2", json!([good_place_eats_amp()])),
1714 )
1715 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon()))
1716 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon())),
1717 );
1718 store.ingest(SuggestIngestionConstraints::all_providers());
1719 assert!(store.count_rows("suggestions") > 0);
1720 assert!(store.count_rows("keywords") > 0);
1721 assert!(store.count_rows("icons") > 0);
1722
1723 store.inner.clear()?;
1724 assert!(store.count_rows("suggestions") == 0);
1725 assert!(store.count_rows("keywords") == 0);
1726 assert!(store.count_rows("icons") == 0);
1727
1728 Ok(())
1729 }
1730
1731 /// Tests querying suggestions.
1732 #[test]
1733 fn query() -> anyhow::Result<()> {
1734 before_each();
1735
1736 let store = TestStore::new(
1737 MockRemoteSettingsClient::default()
1738 .with_record(
1739 SuggestionProvider::Amp.record("data-1", json!([good_place_eats_amp(),])),
1740 )
1741 .with_record(SuggestionProvider::Wikipedia.record(
1742 "wikipedia-1",
1743 json!([california_wiki(), caltech_wiki(), multimatch_wiki(),]),
1744 ))
1745 .with_record(
1746 SuggestionProvider::Amo
1747 .record("data-2", json!([relay_amo(), multimatch_amo(),])),
1748 )
1749 .with_record(
1750 SuggestionProvider::Pocket
1751 .record("data-3", json!([burnout_pocket(), multimatch_pocket(),])),
1752 )
1753 .with_record(SuggestionProvider::Yelp.record("data-4", json!([ramen_yelp(),])))
1754 .with_record(SuggestionProvider::Mdn.record("data-5", json!([array_mdn(),])))
1755 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon()))
1756 .with_record(SuggestionProvider::Wikipedia.icon(california_icon()))
1757 .with_record(SuggestionProvider::Wikipedia.icon(caltech_icon()))
1758 .with_record(SuggestionProvider::Yelp.icon(yelp_favicon()))
1759 .with_record(SuggestionProvider::Wikipedia.icon(multimatch_wiki_icon())),
1760 );
1761
1762 store.ingest(SuggestIngestionConstraints::all_providers());
1763
1764 assert_eq!(
1765 store.fetch_suggestions(SuggestionQuery::all_providers("")),
1766 vec![]
1767 );
1768 assert_eq!(
1769 store.fetch_suggestions(SuggestionQuery::all_providers("la")),
1770 vec![good_place_eats_suggestion("lasagna", None),]
1771 );
1772 assert_eq!(
1773 store.fetch_suggestions(SuggestionQuery::all_providers("multimatch")),
1774 vec![
1775 multimatch_pocket_suggestion(true),
1776 multimatch_amo_suggestion(),
1777 multimatch_wiki_suggestion(),
1778 ]
1779 );
1780 assert_eq!(
1781 store.fetch_suggestions(SuggestionQuery::all_providers("MultiMatch")),
1782 vec![
1783 multimatch_pocket_suggestion(true),
1784 multimatch_amo_suggestion(),
1785 multimatch_wiki_suggestion(),
1786 ]
1787 );
1788 assert_eq!(
1789 store.fetch_suggestions(SuggestionQuery::all_providers("multimatch").limit(2)),
1790 vec![
1791 multimatch_pocket_suggestion(true),
1792 multimatch_amo_suggestion(),
1793 ],
1794 );
1795 assert_eq!(
1796 store.fetch_suggestions(SuggestionQuery::amp("la")),
1797 vec![good_place_eats_suggestion("lasagna", None)],
1798 );
1799 assert_eq!(
1800 store.fetch_suggestions(SuggestionQuery::all_providers_except(
1801 "la",
1802 SuggestionProvider::Amp
1803 )),
1804 vec![],
1805 );
1806 assert_eq!(
1807 store.fetch_suggestions(SuggestionQuery::with_providers("la", vec![])),
1808 vec![],
1809 );
1810 assert_eq!(
1811 store.fetch_suggestions(SuggestionQuery::with_providers(
1812 "cal",
1813 vec![
1814 SuggestionProvider::Amp,
1815 SuggestionProvider::Amo,
1816 SuggestionProvider::Pocket,
1817 ]
1818 )),
1819 vec![],
1820 );
1821 assert_eq!(
1822 store.fetch_suggestions(SuggestionQuery::wikipedia("cal")),
1823 vec![
1824 california_suggestion("california"),
1825 caltech_suggestion("california"),
1826 ],
1827 );
1828 assert_eq!(
1829 store.fetch_suggestions(SuggestionQuery::wikipedia("cal").limit(1)),
1830 vec![california_suggestion("california"),],
1831 );
1832 assert_eq!(
1833 store.fetch_suggestions(SuggestionQuery::with_providers("cal", vec![])),
1834 vec![],
1835 );
1836 assert_eq!(
1837 store.fetch_suggestions(SuggestionQuery::amo("spam")),
1838 vec![relay_suggestion()],
1839 );
1840 assert_eq!(
1841 store.fetch_suggestions(SuggestionQuery::amo("masking")),
1842 vec![relay_suggestion()],
1843 );
1844 assert_eq!(
1845 store.fetch_suggestions(SuggestionQuery::amo("masking e")),
1846 vec![relay_suggestion()],
1847 );
1848 assert_eq!(
1849 store.fetch_suggestions(SuggestionQuery::amo("masking s")),
1850 vec![],
1851 );
1852 assert_eq!(
1853 store.fetch_suggestions(SuggestionQuery::with_providers(
1854 "soft",
1855 vec![SuggestionProvider::Amp, SuggestionProvider::Wikipedia]
1856 )),
1857 vec![],
1858 );
1859 assert_eq!(
1860 store.fetch_suggestions(SuggestionQuery::pocket("soft")),
1861 vec![burnout_suggestion(false),],
1862 );
1863 assert_eq!(
1864 store.fetch_suggestions(SuggestionQuery::pocket("soft l")),
1865 vec![burnout_suggestion(false),],
1866 );
1867 assert_eq!(
1868 store.fetch_suggestions(SuggestionQuery::pocket("sof")),
1869 vec![],
1870 );
1871 assert_eq!(
1872 store.fetch_suggestions(SuggestionQuery::pocket("burnout women")),
1873 vec![burnout_suggestion(true),],
1874 );
1875 assert_eq!(
1876 store.fetch_suggestions(SuggestionQuery::pocket("burnout person")),
1877 vec![],
1878 );
1879 assert_eq!(
1880 store.fetch_suggestions(SuggestionQuery::yelp("best spicy ramen delivery in tokyo")),
1881 vec![ramen_suggestion(
1882 "best spicy ramen delivery in tokyo",
1883 "https://www.yelp.com/search?find_desc=best+spicy+ramen+delivery&find_loc=tokyo"
1884 ),],
1885 );
1886 assert_eq!(
1887 store.fetch_suggestions(SuggestionQuery::yelp("BeSt SpIcY rAmEn DeLiVeRy In ToKyO")),
1888 vec![ramen_suggestion(
1889 "BeSt SpIcY rAmEn DeLiVeRy In ToKyO",
1890 "https://www.yelp.com/search?find_desc=BeSt+SpIcY+rAmEn+DeLiVeRy&find_loc=ToKyO"
1891 ),],
1892 );
1893 assert_eq!(
1894 store.fetch_suggestions(SuggestionQuery::yelp("best ramen delivery in tokyo")),
1895 vec![ramen_suggestion(
1896 "best ramen delivery in tokyo",
1897 "https://www.yelp.com/search?find_desc=best+ramen+delivery&find_loc=tokyo"
1898 ),],
1899 );
1900 assert_eq!(
1901 store.fetch_suggestions(SuggestionQuery::yelp(
1902 "best invalid_ramen delivery in tokyo"
1903 )),
1904 vec![],
1905 );
1906 assert_eq!(
1907 store.fetch_suggestions(SuggestionQuery::yelp("best in tokyo")),
1908 vec![],
1909 );
1910 assert_eq!(
1911 store.fetch_suggestions(SuggestionQuery::yelp("super best ramen in tokyo")),
1912 vec![ramen_suggestion(
1913 "super best ramen in tokyo",
1914 "https://www.yelp.com/search?find_desc=super+best+ramen&find_loc=tokyo"
1915 ),],
1916 );
1917 assert_eq!(
1918 store.fetch_suggestions(SuggestionQuery::yelp("invalid_best ramen in tokyo")),
1919 vec![],
1920 );
1921 assert_eq!(
1922 store.fetch_suggestions(SuggestionQuery::yelp("ramen delivery in tokyo")),
1923 vec![ramen_suggestion(
1924 "ramen delivery in tokyo",
1925 "https://www.yelp.com/search?find_desc=ramen+delivery&find_loc=tokyo"
1926 ),],
1927 );
1928 assert_eq!(
1929 store.fetch_suggestions(SuggestionQuery::yelp("ramen super delivery in tokyo")),
1930 vec![ramen_suggestion(
1931 "ramen super delivery in tokyo",
1932 "https://www.yelp.com/search?find_desc=ramen+super+delivery&find_loc=tokyo"
1933 ),],
1934 );
1935 assert_eq!(
1936 store.fetch_suggestions(SuggestionQuery::yelp("ramen invalid_delivery")),
1937 vec![ramen_suggestion(
1938 "ramen invalid_delivery",
1939 "https://www.yelp.com/search?find_desc=ramen&find_loc=invalid_delivery"
1940 )
1941 .has_location_sign(false),],
1942 );
1943 assert_eq!(
1944 store.fetch_suggestions(SuggestionQuery::yelp("ramen invalid_delivery in tokyo")),
1945 vec![ramen_suggestion(
1946 "ramen invalid_delivery in tokyo",
1947 "https://www.yelp.com/search?find_desc=ramen&find_loc=invalid_delivery+in+tokyo"
1948 )
1949 .has_location_sign(false),],
1950 );
1951 assert_eq!(
1952 store.fetch_suggestions(SuggestionQuery::yelp("ramen in tokyo")),
1953 vec![ramen_suggestion(
1954 "ramen in tokyo",
1955 "https://www.yelp.com/search?find_desc=ramen&find_loc=tokyo"
1956 ),],
1957 );
1958 assert_eq!(
1959 store.fetch_suggestions(SuggestionQuery::yelp("ramen near tokyo")),
1960 vec![ramen_suggestion(
1961 "ramen near tokyo",
1962 "https://www.yelp.com/search?find_desc=ramen&find_loc=tokyo"
1963 ),],
1964 );
1965 assert_eq!(
1966 store.fetch_suggestions(SuggestionQuery::yelp("ramen invalid_in tokyo")),
1967 vec![ramen_suggestion(
1968 "ramen invalid_in tokyo",
1969 "https://www.yelp.com/search?find_desc=ramen&find_loc=invalid_in+tokyo"
1970 )
1971 .has_location_sign(false),],
1972 );
1973 assert_eq!(
1974 store.fetch_suggestions(SuggestionQuery::yelp("ramen in San Francisco")),
1975 vec![ramen_suggestion(
1976 "ramen in San Francisco",
1977 "https://www.yelp.com/search?find_desc=ramen&find_loc=San+Francisco"
1978 ),],
1979 );
1980 assert_eq!(
1981 store.fetch_suggestions(SuggestionQuery::yelp("ramen in")),
1982 vec![ramen_suggestion(
1983 "ramen in",
1984 "https://www.yelp.com/search?find_desc=ramen"
1985 ),],
1986 );
1987 assert_eq!(
1988 store.fetch_suggestions(SuggestionQuery::yelp("ramen near by")),
1989 vec![ramen_suggestion(
1990 "ramen near by",
1991 "https://www.yelp.com/search?find_desc=ramen"
1992 )],
1993 );
1994 assert_eq!(
1995 store.fetch_suggestions(SuggestionQuery::yelp("ramen near me")),
1996 vec![ramen_suggestion(
1997 "ramen near me",
1998 "https://www.yelp.com/search?find_desc=ramen"
1999 )],
2000 );
2001 assert_eq!(
2002 store.fetch_suggestions(SuggestionQuery::yelp("ramen near by tokyo")),
2003 vec![ramen_suggestion(
2004 "ramen near by tokyo",
2005 "https://www.yelp.com/search?find_desc=ramen&find_loc=tokyo"
2006 )],
2007 );
2008 assert_eq!(
2009 store.fetch_suggestions(SuggestionQuery::yelp("ramen")),
2010 vec![
2011 ramen_suggestion("ramen", "https://www.yelp.com/search?find_desc=ramen")
2012 .has_location_sign(false),
2013 ],
2014 );
2015 // Test an extremely long yelp query
2016 assert_eq!(
2017 store.fetch_suggestions(SuggestionQuery::yelp(
2018 "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
2019 )),
2020 vec![
2021 ramen_suggestion(
2022 "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
2023 "https://www.yelp.com/search?find_desc=012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
2024 ).has_location_sign(false),
2025 ],
2026 );
2027 // This query is over the limit and no suggestions should be returned
2028 assert_eq!(
2029 store.fetch_suggestions(SuggestionQuery::yelp(
2030 "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789Z"
2031 )),
2032 vec![],
2033 );
2034 assert_eq!(
2035 store.fetch_suggestions(SuggestionQuery::yelp("best delivery")),
2036 vec![],
2037 );
2038 assert_eq!(
2039 store.fetch_suggestions(SuggestionQuery::yelp("same_modifier same_modifier")),
2040 vec![],
2041 );
2042 assert_eq!(
2043 store.fetch_suggestions(SuggestionQuery::yelp("same_modifier ")),
2044 vec![],
2045 );
2046 assert_eq!(
2047 store.fetch_suggestions(SuggestionQuery::yelp("yelp ramen")),
2048 vec![
2049 ramen_suggestion("ramen", "https://www.yelp.com/search?find_desc=ramen")
2050 .has_location_sign(false),
2051 ],
2052 );
2053 assert_eq!(
2054 store.fetch_suggestions(SuggestionQuery::yelp("yelp keyword ramen")),
2055 vec![
2056 ramen_suggestion("ramen", "https://www.yelp.com/search?find_desc=ramen")
2057 .has_location_sign(false),
2058 ],
2059 );
2060 assert_eq!(
2061 store.fetch_suggestions(SuggestionQuery::yelp("ramen in tokyo yelp")),
2062 vec![ramen_suggestion(
2063 "ramen in tokyo",
2064 "https://www.yelp.com/search?find_desc=ramen&find_loc=tokyo"
2065 )],
2066 );
2067 assert_eq!(
2068 store.fetch_suggestions(SuggestionQuery::yelp("ramen in tokyo yelp keyword")),
2069 vec![ramen_suggestion(
2070 "ramen in tokyo",
2071 "https://www.yelp.com/search?find_desc=ramen&find_loc=tokyo"
2072 )],
2073 );
2074 assert_eq!(
2075 store.fetch_suggestions(SuggestionQuery::yelp("yelp ramen yelp")),
2076 vec![
2077 ramen_suggestion("ramen", "https://www.yelp.com/search?find_desc=ramen")
2078 .has_location_sign(false)
2079 ],
2080 );
2081 assert_eq!(
2082 store.fetch_suggestions(SuggestionQuery::yelp("best yelp ramen")),
2083 vec![],
2084 );
2085 assert_eq!(
2086 store.fetch_suggestions(SuggestionQuery::yelp("Spicy R")),
2087 vec![ramen_suggestion(
2088 "Spicy Ramen",
2089 "https://www.yelp.com/search?find_desc=Spicy+Ramen"
2090 )
2091 .has_location_sign(false)
2092 .subject_exact_match(false)],
2093 );
2094 assert_eq!(
2095 store.fetch_suggestions(SuggestionQuery::yelp("spi")),
2096 vec![ramen_suggestion(
2097 "spicy ramen",
2098 "https://www.yelp.com/search?find_desc=spicy+ramen"
2099 )
2100 .has_location_sign(false)
2101 .subject_exact_match(false)],
2102 );
2103 assert_eq!(
2104 store.fetch_suggestions(SuggestionQuery::yelp("BeSt Ramen")),
2105 vec![ramen_suggestion(
2106 "BeSt Ramen",
2107 "https://www.yelp.com/search?find_desc=BeSt+Ramen"
2108 )
2109 .has_location_sign(false)],
2110 );
2111 assert_eq!(
2112 store.fetch_suggestions(SuggestionQuery::yelp("BeSt Spicy R")),
2113 vec![ramen_suggestion(
2114 "BeSt Spicy Ramen",
2115 "https://www.yelp.com/search?find_desc=BeSt+Spicy+Ramen"
2116 )
2117 .has_location_sign(false)
2118 .subject_exact_match(false)],
2119 );
2120 assert_eq!(
2121 store.fetch_suggestions(SuggestionQuery::yelp("BeSt R")),
2122 vec![],
2123 );
2124 assert_eq!(store.fetch_suggestions(SuggestionQuery::yelp("r")), vec![],);
2125 assert_eq!(
2126 store.fetch_suggestions(SuggestionQuery::yelp("ra")),
2127 vec![
2128 ramen_suggestion("rats", "https://www.yelp.com/search?find_desc=rats")
2129 .has_location_sign(false)
2130 .subject_exact_match(false)
2131 ],
2132 );
2133 assert_eq!(
2134 store.fetch_suggestions(SuggestionQuery::yelp("ram")),
2135 vec![
2136 ramen_suggestion("ramen", "https://www.yelp.com/search?find_desc=ramen")
2137 .has_location_sign(false)
2138 .subject_exact_match(false)
2139 ],
2140 );
2141 assert_eq!(
2142 store.fetch_suggestions(SuggestionQuery::yelp("rac")),
2143 vec![
2144 ramen_suggestion("raccoon", "https://www.yelp.com/search?find_desc=raccoon")
2145 .has_location_sign(false)
2146 .subject_exact_match(false)
2147 ],
2148 );
2149 assert_eq!(
2150 store.fetch_suggestions(SuggestionQuery::yelp("best r")),
2151 vec![],
2152 );
2153 assert_eq!(
2154 store.fetch_suggestions(SuggestionQuery::yelp("best ra")),
2155 vec![ramen_suggestion(
2156 "best rats",
2157 "https://www.yelp.com/search?find_desc=best+rats"
2158 )
2159 .has_location_sign(false)
2160 .subject_exact_match(false)],
2161 );
2162 assert_eq!(
2163 store.fetch_suggestions(SuggestionQuery::yelp("best sp")),
2164 vec![ramen_suggestion(
2165 "best spicy ramen",
2166 "https://www.yelp.com/search?find_desc=best+spicy+ramen"
2167 )
2168 .has_location_sign(false)
2169 .subject_exact_match(false)],
2170 );
2171 assert_eq!(
2172 store.fetch_suggestions(SuggestionQuery::yelp("ramenabc")),
2173 vec![],
2174 );
2175 assert_eq!(
2176 store.fetch_suggestions(SuggestionQuery::yelp("ramenabc xyz")),
2177 vec![],
2178 );
2179 assert_eq!(
2180 store.fetch_suggestions(SuggestionQuery::yelp("best ramenabc")),
2181 vec![],
2182 );
2183 assert_eq!(
2184 store.fetch_suggestions(SuggestionQuery::yelp("bestabc ra")),
2185 vec![],
2186 );
2187 assert_eq!(
2188 store.fetch_suggestions(SuggestionQuery::yelp("bestabc ramen")),
2189 vec![],
2190 );
2191 assert_eq!(
2192 store.fetch_suggestions(SuggestionQuery::yelp("bestabc ramen xyz")),
2193 vec![],
2194 );
2195 assert_eq!(
2196 store.fetch_suggestions(SuggestionQuery::yelp("best spi ram")),
2197 vec![],
2198 );
2199 assert_eq!(
2200 store.fetch_suggestions(SuggestionQuery::yelp("bes ram")),
2201 vec![],
2202 );
2203 assert_eq!(
2204 store.fetch_suggestions(SuggestionQuery::yelp("bes ramen")),
2205 vec![],
2206 );
2207 // Test for prefix match.
2208 assert_eq!(
2209 store.fetch_suggestions(SuggestionQuery::yelp("ramen D")),
2210 vec![ramen_suggestion(
2211 "ramen Delivery",
2212 "https://www.yelp.com/search?find_desc=ramen+Delivery"
2213 )
2214 .has_location_sign(false)],
2215 );
2216 assert_eq!(
2217 store.fetch_suggestions(SuggestionQuery::yelp("ramen I")),
2218 vec![ramen_suggestion(
2219 "ramen In",
2220 "https://www.yelp.com/search?find_desc=ramen"
2221 )],
2222 );
2223 assert_eq!(
2224 store.fetch_suggestions(SuggestionQuery::yelp("ramen Y")),
2225 vec![
2226 ramen_suggestion("ramen", "https://www.yelp.com/search?find_desc=ramen")
2227 .has_location_sign(false)
2228 ],
2229 );
2230 // Prefix match is available only for last words.
2231 assert_eq!(
2232 store.fetch_suggestions(SuggestionQuery::yelp("ramen D Yelp")),
2233 vec![ramen_suggestion(
2234 "ramen D",
2235 "https://www.yelp.com/search?find_desc=ramen&find_loc=D"
2236 )
2237 .has_location_sign(false)],
2238 );
2239 assert_eq!(
2240 store.fetch_suggestions(SuggestionQuery::yelp("ramen I Tokyo")),
2241 vec![ramen_suggestion(
2242 "ramen I Tokyo",
2243 "https://www.yelp.com/search?find_desc=ramen&find_loc=I+Tokyo"
2244 )
2245 .has_location_sign(false)],
2246 );
2247 // Business subject.
2248 assert_eq!(
2249 store.fetch_suggestions(SuggestionQuery::yelp("the shop tokyo")),
2250 vec![ramen_suggestion(
2251 "the shop tokyo",
2252 "https://www.yelp.com/search?find_desc=the+shop&find_loc=tokyo"
2253 )
2254 .has_location_sign(false)
2255 .subject_type(YelpSubjectType::Business)]
2256 );
2257 assert_eq!(
2258 store.fetch_suggestions(SuggestionQuery::yelp("the sho")),
2259 vec![
2260 ramen_suggestion("the shop", "https://www.yelp.com/search?find_desc=the+shop")
2261 .has_location_sign(false)
2262 .subject_exact_match(false)
2263 .subject_type(YelpSubjectType::Business)
2264 ]
2265 );
2266
2267 Ok(())
2268 }
2269
2270 // Tests querying AMP / Wikipedia / Pocket
2271 #[test]
2272 fn query_with_multiple_providers_and_diff_scores() -> anyhow::Result<()> {
2273 before_each();
2274
2275 let store = TestStore::new(
2276 // Create a data set where one keyword matches multiple suggestions from each provider
2277 // where the scores are manually set. We will test that the fetched suggestions are in
2278 // the correct order.
2279 MockRemoteSettingsClient::default()
2280 .with_record(SuggestionProvider::Amp.record(
2281 "data-1",
2282 json!([
2283 los_pollos_amp().merge(json!({
2284 "keywords": ["amp wiki match"],
2285 "full_keywords": [("amp wiki match", 1)],
2286 "score": 0.3,
2287 })),
2288 good_place_eats_amp().merge(json!({
2289 "keywords": ["amp wiki match"],
2290 "full_keywords": [("amp wiki match", 1)],
2291 "score": 0.1,
2292 })),
2293 ]),
2294 ))
2295 .with_record(SuggestionProvider::Wikipedia.record(
2296 "wikipedia-1",
2297 json!([california_wiki().merge(json!({
2298 "keywords": ["amp wiki match", "pocket wiki match"],
2299 })),]),
2300 ))
2301 .with_record(SuggestionProvider::Pocket.record(
2302 "data-3",
2303 json!([
2304 burnout_pocket().merge(json!({
2305 "lowConfidenceKeywords": ["work-life balance", "pocket wiki match"],
2306 "score": 0.05,
2307 })),
2308 multimatch_pocket().merge(json!({
2309 "highConfidenceKeywords": ["pocket wiki match"],
2310 "score": 0.88,
2311 })),
2312 ]),
2313 ))
2314 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon()))
2315 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon()))
2316 .with_record(SuggestionProvider::Wikipedia.icon(california_icon())),
2317 );
2318
2319 store.ingest(SuggestIngestionConstraints::all_providers());
2320 assert_eq!(
2321 store.fetch_suggestions(SuggestionQuery::all_providers("amp wiki match")),
2322 vec![
2323 los_pollos_suggestion("amp wiki match", None).with_score(0.3),
2324 // Wikipedia entries default to a 0.2 score
2325 california_suggestion("amp wiki match"),
2326 good_place_eats_suggestion("amp wiki match", None).with_score(0.1),
2327 ]
2328 );
2329 assert_eq!(
2330 store.fetch_suggestions(SuggestionQuery::all_providers("amp wiki match").limit(2)),
2331 vec![
2332 los_pollos_suggestion("amp wiki match", None).with_score(0.3),
2333 california_suggestion("amp wiki match"),
2334 ]
2335 );
2336 assert_eq!(
2337 store.fetch_suggestions(SuggestionQuery::all_providers("pocket wiki match")),
2338 vec![
2339 multimatch_pocket_suggestion(true).with_score(0.88),
2340 california_suggestion("pocket wiki match"),
2341 burnout_suggestion(false).with_score(0.05),
2342 ]
2343 );
2344 assert_eq!(
2345 store.fetch_suggestions(SuggestionQuery::all_providers("pocket wiki match").limit(1)),
2346 vec![multimatch_pocket_suggestion(true).with_score(0.88),]
2347 );
2348 // test duplicate providers
2349 assert_eq!(
2350 store.fetch_suggestions(SuggestionQuery::with_providers(
2351 "work-life balance",
2352 vec![SuggestionProvider::Pocket, SuggestionProvider::Pocket],
2353 )),
2354 vec![burnout_suggestion(false).with_score(0.05),]
2355 );
2356
2357 Ok(())
2358 }
2359
2360 /// Tests ingesting malformed Remote Settings records that we understand,
2361 /// but that are missing fields, or aren't in the format we expect.
2362 #[test]
2363 fn ingest_malformed() -> anyhow::Result<()> {
2364 before_each();
2365
2366 let store = TestStore::new(
2367 MockRemoteSettingsClient::default()
2368 // Amp record without an attachment.
2369 .with_record(SuggestionProvider::Amp.empty_record("data-1"))
2370 // Wikipedia record without an attachment.
2371 .with_record(SuggestionProvider::Wikipedia.empty_record("wikipedia-1"))
2372 // Icon record without an attachment.
2373 .with_record(MockRecord {
2374 collection: Collection::Amp,
2375 record_type: SuggestRecordType::Icon,
2376 id: "icon-1".to_string(),
2377 inline_data: None,
2378 attachment: None,
2379 })
2380 // Icon record with an ID that's not `icon-{id}`, so suggestions in
2381 // the data attachment won't be able to reference it.
2382 .with_record(MockRecord {
2383 collection: Collection::Amp,
2384 record_type: SuggestRecordType::Icon,
2385 id: "bad-icon-id".to_string(),
2386 inline_data: None,
2387 attachment: Some(MockAttachment::Icon(MockIcon {
2388 id: "bad-icon-id",
2389 data: "",
2390 mimetype: "image/png",
2391 })),
2392 }),
2393 );
2394
2395 store.ingest(SuggestIngestionConstraints::all_providers());
2396
2397 store.read(|dao| {
2398 assert_eq!(
2399 dao.conn
2400 .query_one::<i64>("SELECT count(*) FROM suggestions")?,
2401 0
2402 );
2403 assert_eq!(dao.conn.query_one::<i64>("SELECT count(*) FROM icons")?, 0);
2404
2405 Ok(())
2406 })?;
2407
2408 Ok(())
2409 }
2410
2411 /// Tests that we only ingest providers that we're concerned with.
2412 #[test]
2413 fn ingest_constraints_provider() -> anyhow::Result<()> {
2414 before_each();
2415
2416 let store = TestStore::new(
2417 MockRemoteSettingsClient::default()
2418 .with_record(SuggestionProvider::Amp.record("data-1", json!([los_pollos_amp()])))
2419 .with_record(SuggestionProvider::Yelp.record("yelp-1", json!([ramen_yelp()])))
2420 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon())),
2421 );
2422
2423 let constraints = SuggestIngestionConstraints {
2424 providers: Some(vec![SuggestionProvider::Amp, SuggestionProvider::Pocket]),
2425 ..SuggestIngestionConstraints::all_providers()
2426 };
2427 store.ingest(constraints);
2428
2429 // This should have been ingested
2430 assert_eq!(
2431 store.fetch_suggestions(SuggestionQuery::amp("lo")),
2432 vec![los_pollos_suggestion("los pollos", None)]
2433 );
2434 // This should not have been ingested, since it wasn't in the providers list
2435 assert_eq!(
2436 store.fetch_suggestions(SuggestionQuery::yelp("best ramen")),
2437 vec![]
2438 );
2439
2440 Ok(())
2441 }
2442
2443 /// Tests that records with invalid attachments are ignored
2444 #[test]
2445 fn skip_over_invalid_records() -> anyhow::Result<()> {
2446 before_each();
2447
2448 let store = TestStore::new(
2449 MockRemoteSettingsClient::default()
2450 // valid record
2451 .with_record(
2452 SuggestionProvider::Amp.record("data-1", json!([good_place_eats_amp()])),
2453 )
2454 // This attachment is missing the `title` field and is invalid
2455 .with_record(SuggestionProvider::Amp.record(
2456 "data-2",
2457 json!([{
2458 "id": 1,
2459 "advertiser": "Los Pollos Hermanos",
2460 "iab_category": "8 - Food & Drink",
2461 "keywords": ["lo", "los", "los pollos"],
2462 "url": "https://www.lph-nm.biz",
2463 "icon": "5678",
2464 "impression_url": "https://example.com/impression_url",
2465 "click_url": "https://example.com/click_url",
2466 "score": 0.3
2467 }]),
2468 ))
2469 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon())),
2470 );
2471
2472 store.ingest(SuggestIngestionConstraints::all_providers());
2473
2474 // Test that the valid record was read
2475 assert_eq!(
2476 store.fetch_suggestions(SuggestionQuery::amp("la")),
2477 vec![good_place_eats_suggestion("lasagna", None)]
2478 );
2479 // Test that the invalid record was skipped
2480 assert_eq!(store.fetch_suggestions(SuggestionQuery::amp("lo")), vec![]);
2481
2482 Ok(())
2483 }
2484
2485 #[test]
2486 fn query_mdn() -> anyhow::Result<()> {
2487 before_each();
2488
2489 let store = TestStore::new(
2490 MockRemoteSettingsClient::default()
2491 .with_record(SuggestionProvider::Mdn.record("mdn-1", json!([array_mdn()]))),
2492 );
2493 store.ingest(SuggestIngestionConstraints::all_providers());
2494 // prefix
2495 assert_eq!(
2496 store.fetch_suggestions(SuggestionQuery::mdn("array")),
2497 vec![array_suggestion(),]
2498 );
2499 // prefix + partial suffix
2500 assert_eq!(
2501 store.fetch_suggestions(SuggestionQuery::mdn("array java")),
2502 vec![array_suggestion(),]
2503 );
2504 // prefix + entire suffix
2505 assert_eq!(
2506 store.fetch_suggestions(SuggestionQuery::mdn("javascript array")),
2507 vec![array_suggestion(),]
2508 );
2509 // partial prefix word
2510 assert_eq!(
2511 store.fetch_suggestions(SuggestionQuery::mdn("wild")),
2512 vec![]
2513 );
2514 // single word
2515 assert_eq!(
2516 store.fetch_suggestions(SuggestionQuery::mdn("wildcard")),
2517 vec![array_suggestion()]
2518 );
2519 Ok(())
2520 }
2521
2522 #[test]
2523 fn query_no_yelp_icon_data() -> anyhow::Result<()> {
2524 before_each();
2525
2526 let store = TestStore::new(MockRemoteSettingsClient::default().with_record(
2527 SuggestionProvider::Yelp.record("yelp-1", json!([ramen_yelp()])), // Note: yelp_favicon() is missing
2528 ));
2529 store.ingest(SuggestIngestionConstraints::all_providers());
2530 assert!(matches!(
2531 store.fetch_suggestions(SuggestionQuery::yelp("ramen")).as_slice(),
2532 [Suggestion::Yelp { icon, icon_mimetype, .. }] if icon.is_none() && icon_mimetype.is_none()
2533 ));
2534
2535 Ok(())
2536 }
2537
2538 #[test]
2539 fn fetch_global_config() -> anyhow::Result<()> {
2540 before_each();
2541
2542 let store = TestStore::new(MockRemoteSettingsClient::default().with_record(MockRecord {
2543 collection: Collection::Other,
2544 record_type: SuggestRecordType::GlobalConfig,
2545 id: "configuration-1".to_string(),
2546 inline_data: Some(json!({
2547 "configuration": {
2548 "show_less_frequently_cap": 3,
2549 },
2550 })),
2551 attachment: None,
2552 }));
2553
2554 store.ingest(SuggestIngestionConstraints::all_providers());
2555 assert_eq!(
2556 store.fetch_global_config(),
2557 SuggestGlobalConfig {
2558 show_less_frequently_cap: 3,
2559 }
2560 );
2561
2562 Ok(())
2563 }
2564
2565 #[test]
2566 fn fetch_global_config_default() -> anyhow::Result<()> {
2567 before_each();
2568
2569 let store = TestStore::new(MockRemoteSettingsClient::default());
2570 store.ingest(SuggestIngestionConstraints::all_providers());
2571 assert_eq!(
2572 store.fetch_global_config(),
2573 SuggestGlobalConfig {
2574 show_less_frequently_cap: 0,
2575 }
2576 );
2577
2578 Ok(())
2579 }
2580
2581 #[test]
2582 fn fetch_provider_config_none() -> anyhow::Result<()> {
2583 before_each();
2584
2585 let store = TestStore::new(MockRemoteSettingsClient::default());
2586 store.ingest(SuggestIngestionConstraints::all_providers());
2587 assert_eq!(store.fetch_provider_config(SuggestionProvider::Amp), None);
2588 assert_eq!(
2589 store.fetch_provider_config(SuggestionProvider::Weather),
2590 None
2591 );
2592
2593 Ok(())
2594 }
2595
2596 #[test]
2597 fn fetch_provider_config_other() -> anyhow::Result<()> {
2598 before_each();
2599
2600 let store = TestStore::new(MockRemoteSettingsClient::default().with_record(
2601 SuggestionProvider::Weather.record(
2602 "weather-1",
2603 json!({
2604 "min_keyword_length": 3,
2605 "score": 0.24,
2606 "max_keyword_length": 1,
2607 "max_keyword_word_count": 1,
2608 "keywords": []
2609 }),
2610 ),
2611 ));
2612 store.ingest(SuggestIngestionConstraints::all_providers());
2613
2614 // Sanity-check that the weather config was ingested.
2615 assert_eq!(
2616 store.fetch_provider_config(SuggestionProvider::Weather),
2617 Some(SuggestProviderConfig::Weather {
2618 min_keyword_length: 3,
2619 score: 0.24,
2620 })
2621 );
2622
2623 // Getting the config for a different provider should return None.
2624 assert_eq!(store.fetch_provider_config(SuggestionProvider::Amp), None);
2625
2626 Ok(())
2627 }
2628
2629 #[test]
2630 fn remove_dismissed_suggestions() -> anyhow::Result<()> {
2631 before_each();
2632
2633 let store = TestStore::new(
2634 MockRemoteSettingsClient::default()
2635 .with_record(SuggestionProvider::Amp.record(
2636 "data-1",
2637 json!([good_place_eats_amp().merge(json!({"keywords": ["cats"]})),]),
2638 ))
2639 .with_record(SuggestionProvider::Wikipedia.record(
2640 "wikipedia-1",
2641 json!([california_wiki().merge(json!({"keywords": ["cats"]})),]),
2642 ))
2643 .with_record(SuggestionProvider::Amo.record(
2644 "amo-1",
2645 json!([relay_amo().merge(json!({"keywords": ["cats"]})),]),
2646 ))
2647 .with_record(SuggestionProvider::Pocket.record(
2648 "pocket-1",
2649 json!([burnout_pocket().merge(json!({
2650 "lowConfidenceKeywords": ["cats"],
2651 }))]),
2652 ))
2653 .with_record(SuggestionProvider::Mdn.record(
2654 "mdn-1",
2655 json!([array_mdn().merge(json!({"keywords": ["cats"]})),]),
2656 ))
2657 .with_record(SuggestionProvider::Amp.icon(good_place_eats_icon()))
2658 .with_record(SuggestionProvider::Wikipedia.icon(caltech_icon())),
2659 );
2660 store.ingest(SuggestIngestionConstraints::all_providers());
2661
2662 // A query for cats should return all suggestions
2663 let query = SuggestionQuery::all_providers("cats");
2664 let results = store.fetch_suggestions(query.clone());
2665 assert_eq!(results.len(), 5);
2666
2667 assert!(!store.inner.any_dismissed_suggestions()?);
2668
2669 for result in &results {
2670 let dismissal_key = result.dismissal_key().unwrap();
2671 assert!(!store.inner.is_dismissed_by_suggestion(result)?);
2672 assert!(!store.inner.is_dismissed_by_key(dismissal_key)?);
2673 store.inner.dismiss_by_suggestion(result)?;
2674 assert!(store.inner.is_dismissed_by_suggestion(result)?);
2675 assert!(store.inner.is_dismissed_by_key(dismissal_key)?);
2676 assert!(store.inner.any_dismissed_suggestions()?);
2677 }
2678
2679 // After dismissing the suggestions, the next query shouldn't return them
2680 assert_eq!(store.fetch_suggestions(query.clone()), vec![]);
2681
2682 // Clearing the dismissals should cause them to be returned again
2683 store.inner.clear_dismissed_suggestions()?;
2684 assert_eq!(store.fetch_suggestions(query.clone()).len(), 5);
2685
2686 for result in &results {
2687 let dismissal_key = result.dismissal_key().unwrap();
2688 assert!(!store.inner.is_dismissed_by_suggestion(result)?);
2689 assert!(!store.inner.is_dismissed_by_key(dismissal_key)?);
2690 }
2691 assert!(!store.inner.any_dismissed_suggestions()?);
2692
2693 Ok(())
2694 }
2695
2696 #[test]
2697 fn query_fakespot() -> anyhow::Result<()> {
2698 before_each();
2699
2700 let store = TestStore::new(
2701 MockRemoteSettingsClient::default()
2702 .with_record(SuggestionProvider::Fakespot.record(
2703 "fakespot-1",
2704 json!([snowglobe_fakespot(), simpsons_fakespot()]),
2705 ))
2706 .with_record(SuggestionProvider::Fakespot.icon(fakespot_amazon_icon())),
2707 );
2708 store.ingest(SuggestIngestionConstraints::all_providers());
2709 assert_eq!(
2710 store.fetch_suggestions(SuggestionQuery::fakespot("globe")),
2711 vec![snowglobe_suggestion(Some(FtsMatchInfo {
2712 prefix: false,
2713 stemming: false,
2714 }),)
2715 .with_fakespot_product_type_bonus(0.5)],
2716 );
2717 assert_eq!(
2718 store.fetch_suggestions(SuggestionQuery::fakespot("simpsons")),
2719 vec![simpsons_suggestion(Some(FtsMatchInfo {
2720 prefix: false,
2721 stemming: false,
2722 }),)],
2723 );
2724 // The snowglobe suggestion should come before the simpsons one, since `snow` is a partial
2725 // match on the product_type field.
2726 assert_eq!(
2727 store.fetch_suggestions(SuggestionQuery::fakespot("snow")),
2728 vec![
2729 snowglobe_suggestion(Some(FtsMatchInfo {
2730 prefix: false,
2731 stemming: false,
2732 }),)
2733 .with_fakespot_product_type_bonus(0.5),
2734 simpsons_suggestion(None),
2735 ],
2736 );
2737 // Test FTS by using a query where the keywords are separated in the source text
2738 assert_eq!(
2739 store.fetch_suggestions(SuggestionQuery::fakespot("simpsons snow")),
2740 vec![simpsons_suggestion(Some(FtsMatchInfo {
2741 prefix: false,
2742 stemming: false,
2743 }),)],
2744 );
2745 // Special characters should be stripped out
2746 assert_eq!(
2747 store.fetch_suggestions(SuggestionQuery::fakespot("simpsons + snow")),
2748 vec![simpsons_suggestion(Some(FtsMatchInfo {
2749 prefix: false,
2750 // This is incorrectly counted as stemming, since nothing matches the `+`
2751 // character. TODO: fix this be improving the tokenizer in `FtsQuery`.
2752 stemming: true,
2753 }),)],
2754 );
2755
2756 Ok(())
2757 }
2758
2759 #[test]
2760 fn fakespot_keywords() -> anyhow::Result<()> {
2761 before_each();
2762
2763 let store = TestStore::new(
2764 MockRemoteSettingsClient::default()
2765 .with_record(SuggestionProvider::Fakespot.record(
2766 "fakespot-1",
2767 json!([
2768 // Snow normally returns the snowglobe first. Test using the keyword field
2769 // to force the simpsons result first.
2770 snowglobe_fakespot(),
2771 simpsons_fakespot().merge(json!({"keywords": "snow"})),
2772 ]),
2773 ))
2774 .with_record(SuggestionProvider::Fakespot.icon(fakespot_amazon_icon())),
2775 );
2776 store.ingest(SuggestIngestionConstraints::all_providers());
2777 assert_eq!(
2778 store.fetch_suggestions(SuggestionQuery::fakespot("snow")),
2779 vec![
2780 simpsons_suggestion(Some(FtsMatchInfo {
2781 prefix: false,
2782 stemming: false,
2783 }),)
2784 .with_fakespot_keyword_bonus(),
2785 snowglobe_suggestion(None).with_fakespot_product_type_bonus(0.5),
2786 ],
2787 );
2788 Ok(())
2789 }
2790
2791 #[test]
2792 fn fakespot_prefix_matching() -> anyhow::Result<()> {
2793 before_each();
2794
2795 let store = TestStore::new(
2796 MockRemoteSettingsClient::default()
2797 .with_record(SuggestionProvider::Fakespot.record(
2798 "fakespot-1",
2799 json!([snowglobe_fakespot(), simpsons_fakespot()]),
2800 ))
2801 .with_record(SuggestionProvider::Fakespot.icon(fakespot_amazon_icon())),
2802 );
2803 store.ingest(SuggestIngestionConstraints::all_providers());
2804 assert_eq!(
2805 store.fetch_suggestions(SuggestionQuery::fakespot("simp")),
2806 vec![simpsons_suggestion(Some(FtsMatchInfo {
2807 prefix: true,
2808 stemming: false,
2809 }),)],
2810 );
2811 assert_eq!(
2812 store.fetch_suggestions(SuggestionQuery::fakespot("simps")),
2813 vec![simpsons_suggestion(Some(FtsMatchInfo {
2814 prefix: true,
2815 stemming: false,
2816 }),)],
2817 );
2818 assert_eq!(
2819 store.fetch_suggestions(SuggestionQuery::fakespot("simpson")),
2820 vec![simpsons_suggestion(Some(FtsMatchInfo {
2821 prefix: false,
2822 stemming: false,
2823 }),)],
2824 );
2825
2826 Ok(())
2827 }
2828
2829 #[test]
2830 fn fakespot_updates_and_deletes() -> anyhow::Result<()> {
2831 before_each();
2832
2833 let mut store = TestStore::new(
2834 MockRemoteSettingsClient::default()
2835 .with_record(SuggestionProvider::Fakespot.record(
2836 "fakespot-1",
2837 json!([snowglobe_fakespot(), simpsons_fakespot()]),
2838 ))
2839 .with_record(SuggestionProvider::Fakespot.icon(fakespot_amazon_icon())),
2840 );
2841 store.ingest(SuggestIngestionConstraints::all_providers());
2842
2843 // Update the snapshot so that:
2844 // - The Simpsons entry is deleted
2845 // - Snow globes now use sea glass instead of glitter
2846 store
2847 .client_mut()
2848 .update_record(SuggestionProvider::Fakespot.record(
2849 "fakespot-1",
2850 json!([
2851 snowglobe_fakespot().merge(json!({"title": "Make Your Own Sea Glass Snow Globes"}))
2852 ]),
2853 ));
2854 store.ingest(SuggestIngestionConstraints::all_providers());
2855
2856 assert_eq!(
2857 store.fetch_suggestions(SuggestionQuery::fakespot("glitter")),
2858 vec![],
2859 );
2860 assert!(matches!(
2861 store.fetch_suggestions(SuggestionQuery::fakespot("sea glass")).as_slice(),
2862 [
2863 Suggestion::Fakespot { title, .. }
2864 ]
2865 if title == "Make Your Own Sea Glass Snow Globes"
2866 ));
2867
2868 assert_eq!(
2869 store.fetch_suggestions(SuggestionQuery::fakespot("simpsons")),
2870 vec![],
2871 );
2872
2873 Ok(())
2874 }
2875
2876 /// Test the pathological case where we ingest records with the same id, but from different
2877 /// collections
2878 #[test]
2879 fn same_record_id_different_collections() -> anyhow::Result<()> {
2880 before_each();
2881
2882 let mut store = TestStore::new(
2883 MockRemoteSettingsClient::default()
2884 // This record is in the fakespot-suggest-products collection
2885 .with_record(
2886 SuggestionProvider::Fakespot
2887 .record("fakespot-1", json!([snowglobe_fakespot()])),
2888 )
2889 // This record is in the Amp collection, but it has a fakespot record ID
2890 // for some reason.
2891 .with_record(SuggestionProvider::Amp.record("fakespot-1", json![los_pollos_amp()]))
2892 .with_record(SuggestionProvider::Amp.icon(los_pollos_icon()))
2893 .with_record(SuggestionProvider::Fakespot.icon(fakespot_amazon_icon())),
2894 );
2895 store.ingest(SuggestIngestionConstraints::all_providers());
2896 assert_eq!(
2897 store.fetch_suggestions(SuggestionQuery::fakespot("globe")),
2898 vec![snowglobe_suggestion(Some(FtsMatchInfo {
2899 prefix: false,
2900 stemming: false,
2901 }),)
2902 .with_fakespot_product_type_bonus(0.5)],
2903 );
2904 assert_eq!(
2905 store.fetch_suggestions(SuggestionQuery::amp("lo")),
2906 vec![los_pollos_suggestion("los pollos", None)],
2907 );
2908 // Test deleting one of the records
2909 store
2910 .client_mut()
2911 .delete_record(SuggestionProvider::Amp.empty_record("fakespot-1"))
2912 .delete_record(SuggestionProvider::Amp.icon(los_pollos_icon()));
2913 store.ingest(SuggestIngestionConstraints::all_providers());
2914 // FIXME(Bug 1912283): this setup currently deletes both suggestions, since
2915 // `drop_suggestions` only checks against record ID.
2916 //
2917 // assert_eq!(
2918 // store.fetch_suggestions(SuggestionQuery::fakespot("globe")),
2919 // vec![snowglobe_suggestion()],
2920 // );
2921 // assert_eq!(
2922 // store.fetch_suggestions(SuggestionQuery::amp("lo")),
2923 // vec![],
2924 // );
2925
2926 // However, we can test that the ingested records table has the correct entries
2927
2928 let record_keys = store
2929 .read(|dao| dao.get_ingested_records())
2930 .unwrap()
2931 .into_iter()
2932 .map(|r| format!("{}:{}", r.collection, r.id.as_str()))
2933 .collect::<Vec<_>>();
2934 assert_eq!(
2935 record_keys
2936 .iter()
2937 .map(String::as_str)
2938 .collect::<HashSet<_>>(),
2939 HashSet::from([
2940 "fakespot-suggest-products:fakespot-1",
2941 "fakespot-suggest-products:icon-fakespot-amazon",
2942 ]),
2943 );
2944 Ok(())
2945 }
2946
2947 #[test]
2948 fn dynamic_basic() -> anyhow::Result<()> {
2949 before_each();
2950
2951 let store = TestStore::new(
2952 MockRemoteSettingsClient::default()
2953 // A dynamic record whose attachment is a JSON object that only
2954 // contains keywords
2955 .with_record(SuggestionProvider::Dynamic.full_record(
2956 "dynamic-0",
2957 Some(json!({
2958 "suggestion_type": "aaa",
2959 })),
2960 Some(MockAttachment::Json(json!({
2961 "keywords": [
2962 "aaa keyword",
2963 "common keyword",
2964 ["common prefix", [" aaa"]],
2965 ["choco", ["bo", "late"]],
2966 ["dup", ["licate 1", "licate 2"]],
2967 ],
2968 }))),
2969 ))
2970 // A dynamic record with a score whose attachment is a JSON
2971 // array with multiple suggestions with various properties
2972 .with_record(SuggestionProvider::Dynamic.full_record(
2973 "dynamic-1",
2974 Some(json!({
2975 "suggestion_type": "bbb",
2976 "score": 1.0,
2977 })),
2978 Some(MockAttachment::Json(json!([
2979 {
2980 "keywords": [
2981 "bbb keyword 0",
2982 "common keyword",
2983 "common bbb keyword",
2984 ["common prefix", [" bbb 0"]],
2985 ],
2986 },
2987 {
2988 "keywords": [
2989 "bbb keyword 1",
2990 "common keyword",
2991 "common bbb keyword",
2992 ["common prefix", [" bbb 1"]],
2993 ],
2994 "dismissal_key": "bbb-1-dismissal-key",
2995 },
2996 {
2997 "keywords": [
2998 "bbb keyword 2",
2999 "common keyword",
3000 "common bbb keyword",
3001 ["common prefix", [" bbb 2"]],
3002 ],
3003 "data": json!("bbb-2-data"),
3004 "dismissal_key": "bbb-2-dismissal-key",
3005 },
3006 {
3007 "keywords": [
3008 "bbb keyword 3",
3009 "common keyword",
3010 "common bbb keyword",
3011 ["common prefix", [" bbb 3"]],
3012 ],
3013 "data": json!("bbb-3-data"),
3014 },
3015 ]))),
3016 )),
3017 );
3018 store.ingest(SuggestIngestionConstraints {
3019 providers: Some(vec![SuggestionProvider::Dynamic]),
3020 provider_constraints: Some(SuggestionProviderConstraints {
3021 dynamic_suggestion_types: Some(vec!["aaa".to_string(), "bbb".to_string()]),
3022 ..SuggestionProviderConstraints::default()
3023 }),
3024 ..SuggestIngestionConstraints::all_providers()
3025 });
3026
3027 // queries that shouldn't match anything
3028 let no_match_queries = vec!["aaa", "common", "common prefi", "choc", "chocolate extra"];
3029 for query in &no_match_queries {
3030 assert_eq!(
3031 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3032 vec![],
3033 );
3034 assert_eq!(
3035 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["bbb"])),
3036 vec![],
3037 );
3038 assert_eq!(
3039 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa", "bbb"])),
3040 vec![],
3041 );
3042 assert_eq!(
3043 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa", "zzz"])),
3044 vec![],
3045 );
3046 assert_eq!(
3047 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["zzz"])),
3048 vec![],
3049 );
3050 }
3051
3052 // queries that should match only the "aaa" suggestion
3053 let aaa_queries = [
3054 "aaa keyword",
3055 "common prefix a",
3056 "common prefix aa",
3057 "common prefix aaa",
3058 "choco",
3059 "chocob",
3060 "chocobo",
3061 "chocol",
3062 "chocolate",
3063 "dup",
3064 "dupl",
3065 "duplicate",
3066 "duplicate ",
3067 "duplicate 1",
3068 "duplicate 2",
3069 ];
3070 for query in aaa_queries {
3071 for suggestion_types in [
3072 ["aaa"].as_slice(),
3073 &["aaa", "bbb"],
3074 &["bbb", "aaa"],
3075 &["aaa", "zzz"],
3076 &["zzz", "aaa"],
3077 ] {
3078 assert_eq!(
3079 store.fetch_suggestions(SuggestionQuery::dynamic(query, suggestion_types)),
3080 vec![Suggestion::Dynamic {
3081 suggestion_type: "aaa".into(),
3082 data: None,
3083 dismissal_key: None,
3084 score: DEFAULT_SUGGESTION_SCORE,
3085 }],
3086 );
3087 }
3088 assert_eq!(
3089 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["bbb"])),
3090 vec![],
3091 );
3092 assert_eq!(
3093 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["zzz"])),
3094 vec![],
3095 );
3096 }
3097
3098 // queries that should match only the "bbb 0" suggestion
3099 let bbb_0_queries = ["bbb keyword 0", "common prefix bbb 0"];
3100 for query in &bbb_0_queries {
3101 for suggestion_types in [
3102 ["bbb"].as_slice(),
3103 &["bbb", "aaa"],
3104 &["aaa", "bbb"],
3105 &["bbb", "zzz"],
3106 &["zzz", "bbb"],
3107 ] {
3108 assert_eq!(
3109 store.fetch_suggestions(SuggestionQuery::dynamic(query, suggestion_types)),
3110 vec![Suggestion::Dynamic {
3111 suggestion_type: "bbb".into(),
3112 data: None,
3113 dismissal_key: None,
3114 score: 1.0,
3115 }],
3116 );
3117 }
3118 assert_eq!(
3119 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3120 vec![],
3121 );
3122 assert_eq!(
3123 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["zzz"])),
3124 vec![],
3125 );
3126 }
3127
3128 // queries that should match only the "bbb 1" suggestion
3129 let bbb_1_queries = ["bbb keyword 1", "common prefix bbb 1"];
3130 for query in &bbb_1_queries {
3131 for suggestion_types in [
3132 ["bbb"].as_slice(),
3133 &["bbb", "aaa"],
3134 &["aaa", "bbb"],
3135 &["bbb", "zzz"],
3136 &["zzz", "bbb"],
3137 ] {
3138 assert_eq!(
3139 store.fetch_suggestions(SuggestionQuery::dynamic(query, suggestion_types)),
3140 vec![Suggestion::Dynamic {
3141 suggestion_type: "bbb".into(),
3142 data: None,
3143 dismissal_key: Some("bbb-1-dismissal-key".to_string()),
3144 score: 1.0,
3145 }],
3146 );
3147 }
3148 assert_eq!(
3149 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3150 vec![],
3151 );
3152 assert_eq!(
3153 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["zzz"])),
3154 vec![],
3155 );
3156 }
3157
3158 // queries that should match only the "bbb 2" suggestion
3159 let bbb_2_queries = ["bbb keyword 2", "common prefix bbb 2"];
3160 for query in &bbb_2_queries {
3161 for suggestion_types in [
3162 ["bbb"].as_slice(),
3163 &["bbb", "aaa"],
3164 &["aaa", "bbb"],
3165 &["bbb", "zzz"],
3166 &["zzz", "bbb"],
3167 ] {
3168 assert_eq!(
3169 store.fetch_suggestions(SuggestionQuery::dynamic(query, suggestion_types)),
3170 vec![Suggestion::Dynamic {
3171 suggestion_type: "bbb".into(),
3172 data: Some(json!("bbb-2-data")),
3173 dismissal_key: Some("bbb-2-dismissal-key".to_string()),
3174 score: 1.0,
3175 }],
3176 );
3177 }
3178 assert_eq!(
3179 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3180 vec![],
3181 );
3182 assert_eq!(
3183 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["zzz"])),
3184 vec![],
3185 );
3186 }
3187
3188 // queries that should match only the "bbb 3" suggestion
3189 let bbb_3_queries = ["bbb keyword 3", "common prefix bbb 3"];
3190 for query in &bbb_3_queries {
3191 for suggestion_types in [
3192 ["bbb"].as_slice(),
3193 &["bbb", "aaa"],
3194 &["aaa", "bbb"],
3195 &["bbb", "zzz"],
3196 &["zzz", "bbb"],
3197 ] {
3198 assert_eq!(
3199 store.fetch_suggestions(SuggestionQuery::dynamic(query, suggestion_types)),
3200 vec![Suggestion::Dynamic {
3201 suggestion_type: "bbb".into(),
3202 data: Some(json!("bbb-3-data")),
3203 dismissal_key: None,
3204 score: 1.0,
3205 }],
3206 );
3207 }
3208 assert_eq!(
3209 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3210 vec![],
3211 );
3212 assert_eq!(
3213 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["zzz"])),
3214 vec![],
3215 );
3216 }
3217
3218 // queries that should match only the "bbb" suggestions
3219 let bbb_queries = [
3220 "common bbb keyword",
3221 "common prefix b",
3222 "common prefix bb",
3223 "common prefix bbb",
3224 "common prefix bbb ",
3225 ];
3226 for query in &bbb_queries {
3227 for suggestion_types in [
3228 ["bbb"].as_slice(),
3229 &["bbb", "aaa"],
3230 &["aaa", "bbb"],
3231 &["bbb", "zzz"],
3232 &["zzz", "bbb"],
3233 ] {
3234 assert_eq!(
3235 store.fetch_suggestions(SuggestionQuery::dynamic(query, suggestion_types)),
3236 vec![
3237 Suggestion::Dynamic {
3238 suggestion_type: "bbb".into(),
3239 data: None,
3240 dismissal_key: None,
3241 score: 1.0,
3242 },
3243 Suggestion::Dynamic {
3244 suggestion_type: "bbb".into(),
3245 data: None,
3246 dismissal_key: Some("bbb-1-dismissal-key".to_string()),
3247 score: 1.0,
3248 },
3249 Suggestion::Dynamic {
3250 suggestion_type: "bbb".into(),
3251 data: Some(json!("bbb-2-data")),
3252 dismissal_key: Some("bbb-2-dismissal-key".to_string()),
3253 score: 1.0,
3254 },
3255 Suggestion::Dynamic {
3256 suggestion_type: "bbb".into(),
3257 data: Some(json!("bbb-3-data")),
3258 dismissal_key: None,
3259 score: 1.0,
3260 }
3261 ],
3262 );
3263 }
3264 assert_eq!(
3265 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3266 vec![],
3267 );
3268 assert_eq!(
3269 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["zzz"])),
3270 vec![],
3271 );
3272 }
3273
3274 // queries that should match all suggestions
3275 let common_queries = ["common keyword", "common prefix", "common prefix "];
3276 for query in &common_queries {
3277 for suggestion_types in [
3278 ["aaa", "bbb"].as_slice(),
3279 &["bbb", "aaa"],
3280 &["zzz", "aaa", "bbb"],
3281 &["aaa", "zzz", "bbb"],
3282 &["aaa", "bbb", "zzz"],
3283 ] {
3284 assert_eq!(
3285 store.fetch_suggestions(SuggestionQuery::dynamic(query, suggestion_types)),
3286 vec![
3287 Suggestion::Dynamic {
3288 suggestion_type: "bbb".into(),
3289 data: None,
3290 dismissal_key: None,
3291 score: 1.0,
3292 },
3293 Suggestion::Dynamic {
3294 suggestion_type: "bbb".into(),
3295 data: None,
3296 dismissal_key: Some("bbb-1-dismissal-key".to_string()),
3297 score: 1.0,
3298 },
3299 Suggestion::Dynamic {
3300 suggestion_type: "bbb".into(),
3301 data: Some(json!("bbb-2-data")),
3302 dismissal_key: Some("bbb-2-dismissal-key".to_string()),
3303 score: 1.0,
3304 },
3305 Suggestion::Dynamic {
3306 suggestion_type: "bbb".into(),
3307 data: Some(json!("bbb-3-data")),
3308 dismissal_key: None,
3309 score: 1.0,
3310 },
3311 Suggestion::Dynamic {
3312 suggestion_type: "aaa".into(),
3313 data: None,
3314 dismissal_key: None,
3315 score: DEFAULT_SUGGESTION_SCORE,
3316 },
3317 ],
3318 );
3319 assert_eq!(
3320 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["zzz"])),
3321 vec![],
3322 );
3323 }
3324 }
3325
3326 Ok(())
3327 }
3328
3329 #[test]
3330 fn dynamic_same_type_in_different_records() -> anyhow::Result<()> {
3331 before_each();
3332
3333 // Make a store with the same dynamic suggestion type in three different
3334 // records.
3335 let mut store = TestStore::new(
3336 MockRemoteSettingsClient::default()
3337 // A record whose attachment is a JSON object
3338 .with_record(SuggestionProvider::Dynamic.full_record(
3339 "dynamic-0",
3340 Some(json!({
3341 "suggestion_type": "aaa",
3342 })),
3343 Some(MockAttachment::Json(json!({
3344 "keywords": [
3345 "record 0 keyword",
3346 "common keyword",
3347 ["common prefix", [" 0"]],
3348 ],
3349 "data": json!("record-0-data"),
3350 }))),
3351 ))
3352 // Another record whose attachment is a JSON object
3353 .with_record(SuggestionProvider::Dynamic.full_record(
3354 "dynamic-1",
3355 Some(json!({
3356 "suggestion_type": "aaa",
3357 })),
3358 Some(MockAttachment::Json(json!({
3359 "keywords": [
3360 "record 1 keyword",
3361 "common keyword",
3362 ["common prefix", [" 1"]],
3363 ],
3364 "data": json!("record-1-data"),
3365 }))),
3366 ))
3367 // A record whose attachment is a JSON array with some
3368 // suggestions
3369 .with_record(SuggestionProvider::Dynamic.full_record(
3370 "dynamic-2",
3371 Some(json!({
3372 "suggestion_type": "aaa",
3373 })),
3374 Some(MockAttachment::Json(json!([
3375 {
3376 "keywords": [
3377 "record 2 keyword",
3378 "record 2 keyword 0",
3379 "common keyword",
3380 ["common prefix", [" 2-0"]],
3381 ],
3382 "data": json!("record-2-data-0"),
3383 },
3384 {
3385 "keywords": [
3386 "record 2 keyword",
3387 "record 2 keyword 1",
3388 "common keyword",
3389 ["common prefix", [" 2-1"]],
3390 ],
3391 "data": json!("record-2-data-1"),
3392 },
3393 ]))),
3394 )),
3395 );
3396 store.ingest(SuggestIngestionConstraints {
3397 providers: Some(vec![SuggestionProvider::Dynamic]),
3398 provider_constraints: Some(SuggestionProviderConstraints {
3399 dynamic_suggestion_types: Some(vec!["aaa".to_string()]),
3400 ..SuggestionProviderConstraints::default()
3401 }),
3402 ..SuggestIngestionConstraints::all_providers()
3403 });
3404
3405 // queries that should match only the suggestion in record 0
3406 let record_0_queries = ["record 0 keyword", "common prefix 0"];
3407 for query in record_0_queries {
3408 assert_eq!(
3409 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3410 vec![Suggestion::Dynamic {
3411 suggestion_type: "aaa".into(),
3412 data: Some(json!("record-0-data")),
3413 dismissal_key: None,
3414 score: DEFAULT_SUGGESTION_SCORE,
3415 }],
3416 );
3417 }
3418
3419 // queries that should match only the suggestion in record 1
3420 let record_1_queries = ["record 1 keyword", "common prefix 1"];
3421 for query in record_1_queries {
3422 assert_eq!(
3423 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3424 vec![Suggestion::Dynamic {
3425 suggestion_type: "aaa".into(),
3426 data: Some(json!("record-1-data")),
3427 dismissal_key: None,
3428 score: DEFAULT_SUGGESTION_SCORE,
3429 }],
3430 );
3431 }
3432
3433 // queries that should match only the suggestions in record 2
3434 let record_2_queries = ["record 2 keyword", "common prefix 2", "common prefix 2-"];
3435 for query in record_2_queries {
3436 assert_eq!(
3437 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3438 vec![
3439 Suggestion::Dynamic {
3440 suggestion_type: "aaa".into(),
3441 data: Some(json!("record-2-data-0")),
3442 dismissal_key: None,
3443 score: DEFAULT_SUGGESTION_SCORE,
3444 },
3445 Suggestion::Dynamic {
3446 suggestion_type: "aaa".into(),
3447 data: Some(json!("record-2-data-1")),
3448 dismissal_key: None,
3449 score: DEFAULT_SUGGESTION_SCORE,
3450 },
3451 ],
3452 );
3453 }
3454
3455 // queries that should match only record 2 suggestion 0
3456 let record_2_0_queries = ["record 2 keyword 0", "common prefix 2-0"];
3457 for query in record_2_0_queries {
3458 assert_eq!(
3459 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3460 vec![Suggestion::Dynamic {
3461 suggestion_type: "aaa".into(),
3462 data: Some(json!("record-2-data-0")),
3463 dismissal_key: None,
3464 score: DEFAULT_SUGGESTION_SCORE,
3465 }],
3466 );
3467 }
3468
3469 // queries that should match only record 2 suggestion 1
3470 let record_2_1_queries = ["record 2 keyword 1", "common prefix 2-1"];
3471 for query in record_2_1_queries {
3472 assert_eq!(
3473 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3474 vec![Suggestion::Dynamic {
3475 suggestion_type: "aaa".into(),
3476 data: Some(json!("record-2-data-1")),
3477 dismissal_key: None,
3478 score: DEFAULT_SUGGESTION_SCORE,
3479 }],
3480 );
3481 }
3482
3483 // queries that should match all suggestions
3484 let common_queries = ["common keyword", "common prefix", "common prefix "];
3485 for query in common_queries {
3486 assert_eq!(
3487 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3488 vec![
3489 Suggestion::Dynamic {
3490 suggestion_type: "aaa".into(),
3491 data: Some(json!("record-0-data")),
3492 dismissal_key: None,
3493 score: DEFAULT_SUGGESTION_SCORE,
3494 },
3495 Suggestion::Dynamic {
3496 suggestion_type: "aaa".into(),
3497 data: Some(json!("record-1-data")),
3498 dismissal_key: None,
3499 score: DEFAULT_SUGGESTION_SCORE,
3500 },
3501 Suggestion::Dynamic {
3502 suggestion_type: "aaa".into(),
3503 data: Some(json!("record-2-data-0")),
3504 dismissal_key: None,
3505 score: DEFAULT_SUGGESTION_SCORE,
3506 },
3507 Suggestion::Dynamic {
3508 suggestion_type: "aaa".into(),
3509 data: Some(json!("record-2-data-1")),
3510 dismissal_key: None,
3511 score: DEFAULT_SUGGESTION_SCORE,
3512 },
3513 ],
3514 );
3515 }
3516
3517 // Delete record 0.
3518 store
3519 .client_mut()
3520 .delete_record(SuggestionProvider::Dynamic.empty_record("dynamic-0"));
3521 store.ingest(SuggestIngestionConstraints {
3522 providers: Some(vec![SuggestionProvider::Dynamic]),
3523 provider_constraints: Some(SuggestionProviderConstraints {
3524 dynamic_suggestion_types: Some(vec!["aaa".to_string()]),
3525 ..SuggestionProviderConstraints::default()
3526 }),
3527 ..SuggestIngestionConstraints::all_providers()
3528 });
3529
3530 // Keywords from record 0 should not match anything.
3531 for query in record_0_queries {
3532 assert_eq!(
3533 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3534 vec![],
3535 );
3536 }
3537
3538 // The suggestion in record 1 should remain fetchable.
3539 for query in record_1_queries {
3540 assert_eq!(
3541 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3542 vec![Suggestion::Dynamic {
3543 suggestion_type: "aaa".into(),
3544 data: Some(json!("record-1-data")),
3545 dismissal_key: None,
3546 score: DEFAULT_SUGGESTION_SCORE,
3547 }],
3548 );
3549 }
3550
3551 // The suggestions in record 2 should remain fetchable.
3552 for query in record_2_queries {
3553 assert_eq!(
3554 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3555 vec![
3556 Suggestion::Dynamic {
3557 suggestion_type: "aaa".into(),
3558 data: Some(json!("record-2-data-0")),
3559 dismissal_key: None,
3560 score: DEFAULT_SUGGESTION_SCORE,
3561 },
3562 Suggestion::Dynamic {
3563 suggestion_type: "aaa".into(),
3564 data: Some(json!("record-2-data-1")),
3565 dismissal_key: None,
3566 score: DEFAULT_SUGGESTION_SCORE,
3567 },
3568 ],
3569 );
3570 }
3571 for query in record_2_0_queries {
3572 assert_eq!(
3573 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3574 vec![Suggestion::Dynamic {
3575 suggestion_type: "aaa".into(),
3576 data: Some(json!("record-2-data-0")),
3577 dismissal_key: None,
3578 score: DEFAULT_SUGGESTION_SCORE,
3579 }],
3580 );
3581 }
3582 for query in record_2_1_queries {
3583 assert_eq!(
3584 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3585 vec![Suggestion::Dynamic {
3586 suggestion_type: "aaa".into(),
3587 data: Some(json!("record-2-data-1")),
3588 dismissal_key: None,
3589 score: DEFAULT_SUGGESTION_SCORE,
3590 }],
3591 );
3592 }
3593
3594 // All remaining suggestions should remain fetchable via the common
3595 // keywords.
3596 for query in common_queries {
3597 assert_eq!(
3598 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3599 vec![
3600 Suggestion::Dynamic {
3601 suggestion_type: "aaa".into(),
3602 data: Some(json!("record-1-data")),
3603 dismissal_key: None,
3604 score: DEFAULT_SUGGESTION_SCORE,
3605 },
3606 Suggestion::Dynamic {
3607 suggestion_type: "aaa".into(),
3608 data: Some(json!("record-2-data-0")),
3609 dismissal_key: None,
3610 score: DEFAULT_SUGGESTION_SCORE,
3611 },
3612 Suggestion::Dynamic {
3613 suggestion_type: "aaa".into(),
3614 data: Some(json!("record-2-data-1")),
3615 dismissal_key: None,
3616 score: DEFAULT_SUGGESTION_SCORE,
3617 },
3618 ],
3619 );
3620 }
3621
3622 // Delete record 2.
3623 store
3624 .client_mut()
3625 .delete_record(SuggestionProvider::Dynamic.empty_record("dynamic-2"));
3626 store.ingest(SuggestIngestionConstraints {
3627 providers: Some(vec![SuggestionProvider::Dynamic]),
3628 provider_constraints: Some(SuggestionProviderConstraints {
3629 dynamic_suggestion_types: Some(vec!["aaa".to_string()]),
3630 ..SuggestionProviderConstraints::default()
3631 }),
3632 ..SuggestIngestionConstraints::all_providers()
3633 });
3634
3635 // Keywords from record 0 still should not match anything.
3636 for query in record_0_queries {
3637 assert_eq!(
3638 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3639 vec![],
3640 );
3641 }
3642
3643 // The suggestion in record 1 should remain fetchable.
3644 for query in record_1_queries {
3645 assert_eq!(
3646 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3647 vec![Suggestion::Dynamic {
3648 suggestion_type: "aaa".into(),
3649 data: Some(json!("record-1-data")),
3650 dismissal_key: None,
3651 score: DEFAULT_SUGGESTION_SCORE,
3652 }],
3653 );
3654 }
3655
3656 // The suggestions in record 2 should not be fetchable.
3657 for query in record_2_queries
3658 .iter()
3659 .chain(record_2_0_queries.iter().chain(record_2_1_queries.iter()))
3660 {
3661 assert_eq!(
3662 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3663 vec![]
3664 );
3665 }
3666
3667 // The one remaining suggestion, from record 1, should remain fetchable
3668 // via the common keywords.
3669 for query in common_queries {
3670 assert_eq!(
3671 store.fetch_suggestions(SuggestionQuery::dynamic(query, &["aaa"])),
3672 vec![Suggestion::Dynamic {
3673 suggestion_type: "aaa".into(),
3674 data: Some(json!("record-1-data")),
3675 dismissal_key: None,
3676 score: DEFAULT_SUGGESTION_SCORE,
3677 },],
3678 );
3679 }
3680
3681 Ok(())
3682 }
3683
3684 #[test]
3685 fn dynamic_ingest_provider_constraints() -> anyhow::Result<()> {
3686 before_each();
3687
3688 // Create suggestions with types "aaa" and "bbb".
3689 let store = TestStore::new(
3690 MockRemoteSettingsClient::default()
3691 .with_record(SuggestionProvider::Dynamic.full_record(
3692 "dynamic-0",
3693 Some(json!({
3694 "suggestion_type": "aaa",
3695 })),
3696 Some(MockAttachment::Json(json!({
3697 "keywords": ["aaa keyword", "both keyword"],
3698 }))),
3699 ))
3700 .with_record(SuggestionProvider::Dynamic.full_record(
3701 "dynamic-1",
3702 Some(json!({
3703 "suggestion_type": "bbb",
3704 })),
3705 Some(MockAttachment::Json(json!({
3706 "keywords": ["bbb keyword", "both keyword"],
3707 }))),
3708 )),
3709 );
3710
3711 // Ingest but don't pass in any provider constraints. The records will
3712 // be ingested but their attachments won't be, so fetches shouldn't
3713 // return any suggestions.
3714 store.ingest(SuggestIngestionConstraints {
3715 providers: Some(vec![SuggestionProvider::Dynamic]),
3716 provider_constraints: None,
3717 ..SuggestIngestionConstraints::all_providers()
3718 });
3719
3720 let ingest_1_queries = [
3721 ("aaa keyword", vec!["aaa"]),
3722 ("aaa keyword", vec!["bbb"]),
3723 ("aaa keyword", vec!["aaa", "bbb"]),
3724 ("bbb keyword", vec!["aaa"]),
3725 ("bbb keyword", vec!["bbb"]),
3726 ("bbb keyword", vec!["aaa", "bbb"]),
3727 ("both keyword", vec!["aaa"]),
3728 ("both keyword", vec!["bbb"]),
3729 ("both keyword", vec!["aaa", "bbb"]),
3730 ];
3731 for (query, types) in &ingest_1_queries {
3732 assert_eq!(
3733 store.fetch_suggestions(SuggestionQuery::dynamic(query, types)),
3734 vec![],
3735 );
3736 }
3737
3738 // Ingest only the "bbb" suggestion. The "bbb" attachment should be
3739 // ingested, so "bbb" fetches should return the "bbb" suggestion.
3740 store.ingest(SuggestIngestionConstraints {
3741 providers: Some(vec![SuggestionProvider::Dynamic]),
3742 provider_constraints: Some(SuggestionProviderConstraints {
3743 dynamic_suggestion_types: Some(vec!["bbb".to_string()]),
3744 ..SuggestionProviderConstraints::default()
3745 }),
3746 ..SuggestIngestionConstraints::all_providers()
3747 });
3748
3749 let ingest_2_queries = [
3750 ("aaa keyword", vec!["aaa"], vec![]),
3751 ("aaa keyword", vec!["bbb"], vec![]),
3752 ("aaa keyword", vec!["aaa", "bbb"], vec![]),
3753 ("bbb keyword", vec!["aaa"], vec![]),
3754 ("bbb keyword", vec!["bbb"], vec!["bbb"]),
3755 ("bbb keyword", vec!["aaa", "bbb"], vec!["bbb"]),
3756 ("both keyword", vec!["aaa"], vec![]),
3757 ("both keyword", vec!["bbb"], vec!["bbb"]),
3758 ("both keyword", vec!["aaa", "bbb"], vec!["bbb"]),
3759 ];
3760 for (query, types, expected_types) in &ingest_2_queries {
3761 assert_eq!(
3762 store.fetch_suggestions(SuggestionQuery::dynamic(query, types)),
3763 expected_types
3764 .iter()
3765 .map(|t| Suggestion::Dynamic {
3766 suggestion_type: t.to_string(),
3767 data: None,
3768 dismissal_key: None,
3769 score: DEFAULT_SUGGESTION_SCORE,
3770 })
3771 .collect::<Vec<Suggestion>>(),
3772 );
3773 }
3774
3775 // Now ingest the "aaa" suggestion.
3776 store.ingest(SuggestIngestionConstraints {
3777 providers: Some(vec![SuggestionProvider::Dynamic]),
3778 provider_constraints: Some(SuggestionProviderConstraints {
3779 dynamic_suggestion_types: Some(vec!["aaa".to_string()]),
3780 ..SuggestionProviderConstraints::default()
3781 }),
3782 ..SuggestIngestionConstraints::all_providers()
3783 });
3784
3785 let ingest_3_queries = [
3786 ("aaa keyword", vec!["aaa"], vec!["aaa"]),
3787 ("aaa keyword", vec!["bbb"], vec![]),
3788 ("aaa keyword", vec!["aaa", "bbb"], vec!["aaa"]),
3789 ("bbb keyword", vec!["aaa"], vec![]),
3790 ("bbb keyword", vec!["bbb"], vec!["bbb"]),
3791 ("bbb keyword", vec!["aaa", "bbb"], vec!["bbb"]),
3792 ("both keyword", vec!["aaa"], vec!["aaa"]),
3793 ("both keyword", vec!["bbb"], vec!["bbb"]),
3794 ("both keyword", vec!["aaa", "bbb"], vec!["aaa", "bbb"]),
3795 ];
3796 for (query, types, expected_types) in &ingest_3_queries {
3797 assert_eq!(
3798 store.fetch_suggestions(SuggestionQuery::dynamic(query, types)),
3799 expected_types
3800 .iter()
3801 .map(|t| Suggestion::Dynamic {
3802 suggestion_type: t.to_string(),
3803 data: None,
3804 dismissal_key: None,
3805 score: DEFAULT_SUGGESTION_SCORE,
3806 })
3807 .collect::<Vec<Suggestion>>(),
3808 );
3809 }
3810
3811 Ok(())
3812 }
3813
3814 #[test]
3815 fn dynamic_ingest_new_record() -> anyhow::Result<()> {
3816 before_each();
3817
3818 // Create a dynamic suggestion and ingest it.
3819 let mut store = TestStore::new(MockRemoteSettingsClient::default().with_record(
3820 SuggestionProvider::Dynamic.full_record(
3821 "dynamic-0",
3822 Some(json!({
3823 "suggestion_type": "aaa",
3824 })),
3825 Some(MockAttachment::Json(json!({
3826 "keywords": ["old keyword"],
3827 }))),
3828 ),
3829 ));
3830 store.ingest(SuggestIngestionConstraints {
3831 providers: Some(vec![SuggestionProvider::Dynamic]),
3832 provider_constraints: Some(SuggestionProviderConstraints {
3833 dynamic_suggestion_types: Some(vec!["aaa".to_string()]),
3834 ..SuggestionProviderConstraints::default()
3835 }),
3836 ..SuggestIngestionConstraints::all_providers()
3837 });
3838
3839 // Add a new record of the same dynamic type.
3840 store
3841 .client_mut()
3842 .add_record(SuggestionProvider::Dynamic.full_record(
3843 "dynamic-1",
3844 Some(json!({
3845 "suggestion_type": "aaa",
3846 })),
3847 Some(MockAttachment::Json(json!({
3848 "keywords": ["new keyword"],
3849 }))),
3850 ));
3851
3852 // Ingest, but don't ingest the dynamic type. The store will download
3853 // the new record but shouldn't ingest its attachment.
3854 store.ingest(SuggestIngestionConstraints {
3855 providers: Some(vec![SuggestionProvider::Dynamic]),
3856 provider_constraints: None,
3857 ..SuggestIngestionConstraints::all_providers()
3858 });
3859 assert_eq!(
3860 store.fetch_suggestions(SuggestionQuery::dynamic("new keyword", &["aaa"])),
3861 vec![],
3862 );
3863
3864 // Ingest again with the dynamic type. The new record will be
3865 // unchanged, but the store should now ingest its attachment.
3866 store.ingest(SuggestIngestionConstraints {
3867 providers: Some(vec![SuggestionProvider::Dynamic]),
3868 provider_constraints: Some(SuggestionProviderConstraints {
3869 dynamic_suggestion_types: Some(vec!["aaa".to_string()]),
3870 ..SuggestionProviderConstraints::default()
3871 }),
3872 ..SuggestIngestionConstraints::all_providers()
3873 });
3874
3875 // The keyword in the new attachment should match the suggestion,
3876 // confirming that the new record's attachment was ingested.
3877 assert_eq!(
3878 store.fetch_suggestions(SuggestionQuery::dynamic("new keyword", &["aaa"])),
3879 vec![Suggestion::Dynamic {
3880 suggestion_type: "aaa".to_string(),
3881 data: None,
3882 dismissal_key: None,
3883 score: DEFAULT_SUGGESTION_SCORE,
3884 }]
3885 );
3886
3887 Ok(())
3888 }
3889
3890 #[test]
3891 fn dynamic_dismissal() -> anyhow::Result<()> {
3892 before_each();
3893
3894 let store = TestStore::new(MockRemoteSettingsClient::default().with_record(
3895 SuggestionProvider::Dynamic.full_record(
3896 "dynamic-0",
3897 Some(json!({
3898 "suggestion_type": "aaa",
3899 })),
3900 Some(MockAttachment::Json(json!([
3901 {
3902 "keywords": ["aaa"],
3903 "dismissal_key": "dk0",
3904 },
3905 {
3906 "keywords": ["aaa"],
3907 "dismissal_key": "dk1",
3908 },
3909 {
3910 "keywords": ["aaa"],
3911 },
3912 ]))),
3913 ),
3914 ));
3915 store.ingest(SuggestIngestionConstraints {
3916 providers: Some(vec![SuggestionProvider::Dynamic]),
3917 provider_constraints: Some(SuggestionProviderConstraints {
3918 dynamic_suggestion_types: Some(vec!["aaa".to_string()]),
3919 ..SuggestionProviderConstraints::default()
3920 }),
3921 ..SuggestIngestionConstraints::all_providers()
3922 });
3923
3924 // Make sure the suggestions are initially fetchable.
3925 let suggestions = store.fetch_suggestions(SuggestionQuery::dynamic("aaa", &["aaa"]));
3926 assert_eq!(
3927 suggestions,
3928 vec![
3929 Suggestion::Dynamic {
3930 suggestion_type: "aaa".to_string(),
3931 data: None,
3932 dismissal_key: Some("dk0".to_string()),
3933 score: DEFAULT_SUGGESTION_SCORE,
3934 },
3935 Suggestion::Dynamic {
3936 suggestion_type: "aaa".to_string(),
3937 data: None,
3938 dismissal_key: Some("dk1".to_string()),
3939 score: DEFAULT_SUGGESTION_SCORE,
3940 },
3941 Suggestion::Dynamic {
3942 suggestion_type: "aaa".to_string(),
3943 data: None,
3944 dismissal_key: None,
3945 score: DEFAULT_SUGGESTION_SCORE,
3946 },
3947 ],
3948 );
3949
3950 // Dismiss the first suggestion.
3951 assert_eq!(suggestions[0].dismissal_key(), Some("dk0"));
3952 store.inner.dismiss_by_suggestion(&suggestions[0])?;
3953 assert_eq!(
3954 store.fetch_suggestions(SuggestionQuery::dynamic("aaa", &["aaa"])),
3955 vec![
3956 Suggestion::Dynamic {
3957 suggestion_type: "aaa".to_string(),
3958 data: None,
3959 dismissal_key: Some("dk1".to_string()),
3960 score: DEFAULT_SUGGESTION_SCORE,
3961 },
3962 Suggestion::Dynamic {
3963 suggestion_type: "aaa".to_string(),
3964 data: None,
3965 dismissal_key: None,
3966 score: DEFAULT_SUGGESTION_SCORE,
3967 },
3968 ],
3969 );
3970
3971 // Dismiss the second suggestion.
3972 assert_eq!(suggestions[1].dismissal_key(), Some("dk1"));
3973 store.inner.dismiss_by_suggestion(&suggestions[1])?;
3974 assert_eq!(
3975 store.fetch_suggestions(SuggestionQuery::dynamic("aaa", &["aaa"])),
3976 vec![Suggestion::Dynamic {
3977 suggestion_type: "aaa".to_string(),
3978 data: None,
3979 dismissal_key: None,
3980 score: DEFAULT_SUGGESTION_SCORE,
3981 },],
3982 );
3983
3984 // Clear dismissals. All suggestions should be fetchable again.
3985 store.inner.clear_dismissed_suggestions()?;
3986 assert_eq!(
3987 store.fetch_suggestions(SuggestionQuery::dynamic("aaa", &["aaa"])),
3988 vec![
3989 Suggestion::Dynamic {
3990 suggestion_type: "aaa".to_string(),
3991 data: None,
3992 dismissal_key: Some("dk0".to_string()),
3993 score: DEFAULT_SUGGESTION_SCORE,
3994 },
3995 Suggestion::Dynamic {
3996 suggestion_type: "aaa".to_string(),
3997 data: None,
3998 dismissal_key: Some("dk1".to_string()),
3999 score: DEFAULT_SUGGESTION_SCORE,
4000 },
4001 Suggestion::Dynamic {
4002 suggestion_type: "aaa".to_string(),
4003 data: None,
4004 dismissal_key: None,
4005 score: DEFAULT_SUGGESTION_SCORE,
4006 },
4007 ],
4008 );
4009
4010 Ok(())
4011 }
4012 }