1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
pub mod device_info;
mod domain;
pub mod metrics;
use std::hash::Hash;
use std::ops::Range;
use std::pin::Pin;
use std::time::Duration;
use std::{fmt::Debug, future::Future};
use crate::device_info::DeviceInfo;
pub use crate::domain::{CacheInputs, Proportion};
use actix_web::http::header::{AcceptLanguage, LanguageTag, Preference, QualityItem};
use anyhow::Context;
use async_trait::async_trait;
use fake::{
faker::{
address::en::{CityName, CountryCode, StateAbbr},
lorem::en::{Word, Words},
},
Fake, Faker,
};
use http::Uri;
use merino_settings::SuggestionProviderConfig;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DisplayFromStr};
use thiserror::Error;
pub const FIREFOX_TEST_VERSIONS: Range<u32> = 70..95;
#[derive(Debug, Clone, Hash, Serialize)]
pub struct SuggestionRequest {
pub query: String,
pub accepts_english: bool,
pub country: Option<String>,
pub region: Option<String>,
pub dma: Option<u16>,
pub city: Option<String>,
pub device_info: DeviceInfo,
pub client_variants: Option<Vec<String>>,
}
impl<F> fake::Dummy<F> for SuggestionRequest {
fn dummy_with_rng<R: rand::Rng + ?Sized>(_config: &F, rng: &mut R) -> Self {
Self {
query: Words(1..10).fake_with_rng::<Vec<String>, R>(rng).join(" "),
accepts_english: Faker.fake(),
country: Some(CountryCode().fake::<String>()),
region: Some(StateAbbr().fake::<String>()),
dma: Some(rng.gen_range(100_u16..1000)),
city: Some(CityName().fake::<String>()),
device_info: Faker.fake(),
client_variants: Some(Words(1..10).fake_with_rng::<Vec<String>, R>(rng)),
}
}
}
#[derive(Clone, Debug)]
pub struct SuggestionResponse {
pub cache_status: CacheStatus,
pub cache_ttl: Option<Duration>,
pub suggestions: Vec<Suggestion>,
}
impl SuggestionResponse {
pub fn new(suggestions: Vec<Suggestion>) -> Self {
Self {
suggestions,
cache_status: CacheStatus::NoCache,
cache_ttl: None,
}
}
pub fn with_cache_status(mut self, cache_status: CacheStatus) -> Self {
self.cache_status = cache_status;
self
}
pub fn with_cache_ttl(mut self, cache_ttl: Duration) -> Self {
self.cache_ttl = Some(cache_ttl);
self
}
}
impl<F> fake::Dummy<F> for SuggestionResponse {
fn dummy_with_rng<R: rand::Rng + ?Sized>(_config: &F, rng: &mut R) -> Self {
SuggestionResponse {
cache_status: CacheStatus::NoCache,
cache_ttl: None,
suggestions: std::iter::repeat_with(|| Faker.fake())
.take(rng.gen_range(0..=5))
.collect(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheStatus {
Hit,
Miss,
NoCache,
Mixed,
Error,
}
impl ToString for CacheStatus {
fn to_string(&self) -> String {
match self {
CacheStatus::Hit => "hit",
CacheStatus::Miss => "miss",
CacheStatus::NoCache => "no-cache",
CacheStatus::Mixed => "mixed",
CacheStatus::Error => "error",
}
.to_string()
}
}
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct Suggestion {
pub id: u32,
pub full_keyword: String,
pub title: String,
#[serde_as(as = "DisplayFromStr")]
pub url: Uri,
#[serde_as(as = "Option<DisplayFromStr>")]
#[serde(default)]
pub impression_url: Option<Uri>,
#[serde_as(as = "Option<DisplayFromStr>")]
#[serde(default)]
pub click_url: Option<Uri>,
pub provider: String,
pub advertiser: String,
pub is_sponsored: bool,
#[serde_as(as = "DisplayFromStr")]
pub icon: Uri,
pub score: Proportion,
}
impl<F> fake::Dummy<F> for Suggestion {
fn dummy_with_rng<R: rand::Rng + ?Sized>(_config: &F, rng: &mut R) -> Self {
Self {
id: Faker.fake(),
full_keyword: Word().fake_with_rng(rng),
title: Words(3..5).fake_with_rng::<Vec<String>, R>(rng).join(" "),
url: fake_example_url(rng),
impression_url: Some(fake_example_url(rng)),
click_url: Some(fake_example_url(rng)),
provider: Words(2..4).fake_with_rng::<Vec<String>, R>(rng).join(" "),
advertiser: Words(2..4).fake_with_rng::<Vec<String>, R>(rng).join(" "),
is_sponsored: rng.gen(),
icon: fake_example_url(rng),
score: rng.gen(),
}
}
}
fn fake_example_url<R: rand::Rng + ?Sized>(rng: &mut R) -> Uri {
Uri::builder()
.scheme("https")
.authority("example.com")
.path_and_query(format!(
"/fake#{}",
Words(2..5).fake_with_rng::<Vec<String>, R>(rng).join("-")
))
.build()
.unwrap()
}
#[async_trait]
pub trait SuggestionProvider: Send + Sync {
fn name(&self) -> String;
async fn suggest(&self, query: SuggestionRequest) -> Result<SuggestionResponse, SuggestError>;
fn is_null(&self) -> bool {
false
}
fn cache_inputs(&self, req: &SuggestionRequest, cache_inputs: &mut dyn CacheInputs) {
cache_inputs.add(req.query.as_bytes());
cache_inputs.add(&[req.accepts_english as u8]);
cache_inputs.add(req.country.as_deref().unwrap_or("<none>").as_bytes());
cache_inputs.add(req.region.as_deref().unwrap_or("<none>").as_bytes());
cache_inputs.add(&req.dma.map_or([0xFF, 0xFF], u16::to_be_bytes));
cache_inputs.add(req.city.as_deref().unwrap_or("<none>").as_bytes());
cache_inputs.add(req.device_info.to_string().as_bytes());
}
fn cache_key(&self, req: &SuggestionRequest) -> String {
let mut cache_inputs = blake3::Hasher::new();
cache_inputs.add(self.name().as_bytes());
self.cache_inputs(req, &mut cache_inputs);
format!("provider:v1:{}", cache_inputs.hash())
}
async fn reconfigure(
&mut self,
new_config: serde_json::Value,
make_fresh: &MakeFreshType,
) -> Result<(), SetupError>;
}
pub type MakeFreshType = Box<
dyn Send
+ Sync
+ Fn(
SuggestionProviderConfig,
) -> Pin<
Box<
(dyn Send
+ Future<Output = Result<Box<dyn SuggestionProvider>, SetupError>>
+ 'static),
>,
>,
>;
#[derive(Debug, Error)]
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
pub enum SetupError {
#[error("This suggestions provider cannot be used with the current Merino configuration")]
InvalidConfiguration(#[source] anyhow::Error),
#[error("There was a network error while setting up this suggestions provider")]
Network(#[source] anyhow::Error),
#[error("There was a local I/O error while setting up this suggestion provider")]
Io(#[source] anyhow::Error),
#[error("Required data was not in the expected format")]
Format(#[source] anyhow::Error),
#[error("An unexpected state was encountered")]
Internal(#[source] anyhow::Error),
}
#[derive(Debug, Error)]
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
pub enum SuggestError {
#[error("There was a network error while providing suggestions: {0}")]
Network(#[source] anyhow::Error),
#[error("There was an error serializing the suggestions: {0}")]
Serialization(#[source] serde_json::Error),
#[error("There was an internal error in the suggestion provider: {0}")]
Internal(#[source] anyhow::Error),
}
#[derive(Debug, PartialEq, Eq)]
pub struct SupportedLanguages(pub AcceptLanguage);
impl SupportedLanguages {
pub fn wildcard() -> Self {
Self(AcceptLanguage(vec![QualityItem::max(Preference::Any)]))
}
pub fn includes(&self, language_tag: LanguageTag) -> bool {
self.0.iter().any(|quality_item| {
language_tag.matches(&match &quality_item.item {
Preference::Any => return true,
Preference::Specific(item) => item.to_owned(),
})
})
}
}
pub struct NullProvider;
#[async_trait]
impl SuggestionProvider for NullProvider {
fn name(&self) -> String {
"NullProvider".into()
}
fn cache_inputs(&self, _req: &SuggestionRequest, _hasher: &mut dyn CacheInputs) {
}
fn is_null(&self) -> bool {
true
}
async fn suggest(&self, _query: SuggestionRequest) -> Result<SuggestionResponse, SuggestError> {
Ok(SuggestionResponse::new(vec![]))
}
async fn reconfigure(
&mut self,
new_config: serde_json::Value,
_make_fresh: &MakeFreshType,
) -> Result<(), SetupError> {
convert_config::<SuggestionProviderConfig>(new_config).map(|_| ())
}
}
pub fn convert_config<T: DeserializeOwned>(config: serde_json::Value) -> Result<T, SetupError> {
serde_json::from_value::<T>(config)
.context("loading provider config")
.map_err(SetupError::InvalidConfiguration)
}
pub async fn reconfigure_or_remake(
provider: &mut Box<dyn SuggestionProvider>,
new_config: SuggestionProviderConfig,
make_fresh: &MakeFreshType,
) -> Result<(), SetupError> {
let serialized_config = serde_json::to_value(new_config.clone())
.context("serializing provider config")
.map_err(SetupError::InvalidConfiguration)?;
if let Err(error) = provider.reconfigure(serialized_config, make_fresh).await {
tracing::warn!(
r#type = "suggest-traits.reconfigure-or-remake.reconfigure-error",
?error,
"Could not reconfigure provider in place"
);
*provider = make_fresh(new_config).await?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use actix_web::http::header::QualityItem;
#[test]
fn supported_languages_includes_example() {
let supported_languages = SupportedLanguages(AcceptLanguage(vec![
QualityItem::max("en-CA".parse().unwrap()),
QualityItem::max("fr".parse().unwrap()),
]));
assert!(supported_languages.includes(LanguageTag::parse("en-CA").unwrap()));
assert!(supported_languages.includes(LanguageTag::parse("en").unwrap()));
assert!(!supported_languages.includes(LanguageTag::parse("en-GB").unwrap()));
assert!(supported_languages.includes(LanguageTag::parse("fr").unwrap()));
assert!(!supported_languages.includes(LanguageTag::parse("fr-CH").unwrap()));
let supported_languages =
SupportedLanguages(AcceptLanguage(vec![QualityItem::max("*".parse().unwrap())]));
assert!(supported_languages.includes(LanguageTag::parse("en-CA").unwrap()));
assert!(supported_languages.includes(LanguageTag::parse("en").unwrap()));
assert!(supported_languages.includes(LanguageTag::parse("fr-CH").unwrap()));
}
struct TestProvider;
#[async_trait]
impl SuggestionProvider for TestProvider {
fn name(&self) -> String {
"test".to_string()
}
async fn suggest(
&self,
_query: SuggestionRequest,
) -> Result<SuggestionResponse, SuggestError> {
unimplemented!()
}
fn cache_inputs(&self, req: &SuggestionRequest, cache_inputs: &mut dyn CacheInputs) {
cache_inputs.add(req.query.as_bytes());
}
async fn reconfigure(
&mut self,
_new_config: serde_json::Value,
_make_fresh: &MakeFreshType,
) -> Result<(), SetupError> {
unimplemented!()
}
}
#[test]
fn cache_key_only_considers_included_inputs() {
let request1 = SuggestionRequest {
query: "a".to_string(),
accepts_english: true,
..Faker.fake()
};
let request2 = SuggestionRequest {
query: "a".to_string(),
accepts_english: false,
..request1.clone()
};
let request3 = SuggestionRequest {
query: "b".to_string(),
accepts_english: true,
..request1.clone()
};
let request4 = SuggestionRequest {
query: "b".to_string(),
accepts_english: false,
..request1.clone()
};
let provider = TestProvider;
assert_eq!(provider.cache_key(&request1), provider.cache_key(&request2));
assert_eq!(provider.cache_key(&request3), provider.cache_key(&request4));
assert_ne!(provider.cache_key(&request1), provider.cache_key(&request3));
}
}