-
Notifications
You must be signed in to change notification settings - Fork 221
/
store.rs
415 lines (370 loc) · 13.8 KB
/
store.rs
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
use std::{
ops::Deref,
path::{Path, PathBuf},
};
use once_cell::sync::OnceCell;
use remote_settings::{self, Attachment, GetItemsOptions, RemoteSettingsConfig, SortOrder};
use serde_derive::*;
use crate::{
db::{ConnectionType, SuggestDb, LAST_FETCH_META_KEY},
error::SuggestApiError,
RemoteRecordId, RemoteSuggestion, Result, Suggestion, SuggestionQuery,
};
const RS_COLLECTION: &str = "quicksuggest";
/// The store is the entry point to the Suggest component. It incrementally
/// fetches suggestions from the Remote Settings service, stores them in a local
/// database, and returns them in response to user queries.
///
/// Your application should create a single store, and manage it as a singleton.
/// The store is thread-safe, and supports concurrent fetches and ingests. We
/// expect that your application will call `query` to show suggestions as the
/// user types into the address bar, and periodically call `ingest` in the
/// background to update the database with new suggestions from Remote Settings.
///
/// The store keeps track of the state needed to support incremental ingestion,
/// but doesn't schedule the ingestion work itself, because the primitives for
/// scheduling background work vary across platforms: Desktop might use an idle
/// timer to poll for changes, Android has `WorkManager`, and iOS has
/// `BGTaskScheduler`.
///
/// Ingestion limits can vary between platforms, too: a mobile browser on a
/// metered connection might want to request a small subset of the Suggest data
/// and fetch the rest later, while a Desktop browser on a fast link might
/// request the entire dataset on first launch.
pub struct SuggestStore {
path: PathBuf,
dbs: OnceCell<SuggestStoreDbs>,
settings_client: remote_settings::Client,
}
/// Limits for an ingestion from Remote Settings.
pub struct IngestLimits {
/// The maximum number of records to request from Remote Settings.
/// Each record has about 200 suggestions.
pub records: Option<u64>,
}
impl SuggestStore {
/// Creates a suggestion provider.
pub fn new(
path: &str,
settings_config: Option<RemoteSettingsConfig>,
) -> Result<Self, SuggestApiError> {
Ok(Self::new_inner(path, settings_config)?)
}
fn new_inner(
path: impl AsRef<Path>,
settings_config: Option<RemoteSettingsConfig>,
) -> Result<Self> {
let settings_client = remote_settings::Client::new(settings_config.unwrap_or_else(|| {
RemoteSettingsConfig {
server_url: None,
bucket_name: None,
collection_name: RS_COLLECTION.into(),
}
}))?;
Ok(Self {
path: path.as_ref().into(),
dbs: OnceCell::new(),
settings_client,
})
}
/// Returns this provider's database connections, initializing them if
/// they're not already open.
fn dbs(&self) -> Result<&SuggestStoreDbs> {
self.dbs
.get_or_try_init(|| SuggestStoreDbs::open(&self.path))
}
/// Queries the database for suggestions that match the `keyword`.
pub fn query(&self, query: &SuggestionQuery) -> Result<Vec<Suggestion>, SuggestApiError> {
if query.keyword.is_empty() {
return Ok(Vec::new());
}
Ok(self
.dbs()?
.reader
.fetch_by_keyword(&query.keyword)?
.into_iter()
.filter(|suggestion| {
(suggestion.is_sponsored && query.include_sponsored)
|| (!suggestion.is_sponsored && query.include_non_sponsored)
})
.collect())
}
/// Interrupts any ongoing queries. This should be called when the
/// user types a new keyword into the address bar, to ensure that they
/// see fresh suggestions as they type.
pub fn interrupt(&self) {
if let Some(dbs) = self.dbs.get() {
// Only interrupt if the databases are already open.
dbs.reader.interrupt_handle.interrupt();
}
}
/// Ingests new suggestions from Remote Settings. `limits` can be used to
/// constrain the amount of work done.
pub fn ingest(&self, limits: &IngestLimits) -> Result<(), SuggestApiError> {
Ok(self.ingest_inner(limits)?)
}
fn ingest_inner(&self, limits: &IngestLimits) -> Result<()> {
let writer = &self.dbs()?.writer;
let scope = writer.interrupt_handle.begin_interrupt_scope()?;
let mut options = GetItemsOptions::new();
// Remote Settings returns records in descending modification order
// (newest first), but we want them in ascending order (oldest first),
// so that we can eventually resume fetching where we left off.
options.sort("last_modified", SortOrder::Ascending);
if let Some(last_fetch) = writer.get_meta::<u64>(LAST_FETCH_META_KEY)? {
// Only fetch changes since our last fetch. If our last fetch was
// interrupted, we'll pick up where we left off.
options.gt("last_modified", last_fetch.to_string());
}
if let Some(records) = &limits.records {
options.limit(*records);
}
scope.err_if_interrupted()?;
let records = self
.settings_client
.get_records_raw_with_options(&options)?
.json::<SuggestRecordsResponse>()?
.data;
for record in &records {
scope.err_if_interrupted()?;
match record {
FetchedChange::Record(SuggestRecord::Data {
id: record_id,
last_modified,
attachment,
}) => {
// Drop any suggestions that we previously ingested from
// this record's attachment. Suggestions don't have a
// stable identifier, and determining which suggestions in
// the attachment actually changed is more complicated than
// dropping and re-ingesting all of them.
writer.drop(record_id)?;
// Ingest (or re-ingest) all suggestions in the attachment.
scope.err_if_interrupted()?;
let suggestions = self
.settings_client
.get_attachment(&attachment.location)?
.json::<SuggestAttachmentData>()?
.0;
writer.ingest(record_id, &suggestions)?;
// Advance the last fetch time, so that we can resume
// fetching after this record if we're interrupted.
writer.put_meta(LAST_FETCH_META_KEY, last_modified)?;
}
FetchedChange::Unknown {
id: record_id,
last_modified,
deleted,
} if *deleted => {
// If the entire record was deleted, drop all its
// suggestions and advance the last fetch time.
match record_id.as_icon_id() {
Some(icon_id) => writer.drop_icon(icon_id)?,
None => writer.drop(record_id)?,
};
writer.put_meta(LAST_FETCH_META_KEY, last_modified)?
}
FetchedChange::Record(SuggestRecord::Icon {
id: record_id,
last_modified,
attachment,
}) => {
let Some(icon_id) = record_id.as_icon_id() else {
continue
};
scope.err_if_interrupted()?;
let data = self
.settings_client
.get_attachment(&attachment.location)?
.body;
writer.put_icon(icon_id, &data)?;
writer.put_meta(LAST_FETCH_META_KEY, last_modified)?;
}
_ => continue,
}
}
Ok(())
}
pub fn clear(&self) -> Result<(), SuggestApiError> {
let writer = &self.dbs()?.writer;
Ok(writer.clear()?)
}
}
struct SuggestStoreDbs {
/// A read-write connection used to update the database with new data.
writer: SuggestDb,
/// A read-only connection used to query the database.
reader: SuggestDb,
}
impl SuggestStoreDbs {
fn open(path: &Path) -> Result<Self> {
// Order is important here: the writer must be opened first, so that it
// can set up the database and run any migrations.
let writer = SuggestDb::open(path, ConnectionType::ReadWrite)?;
let reader = SuggestDb::open(path, ConnectionType::ReadOnly)?;
Ok(Self { writer, reader })
}
}
#[derive(Debug, Deserialize)]
struct SuggestRecordsResponse {
data: Vec<FetchedChange>,
}
#[derive(Debug, Deserialize, PartialEq)]
#[serde(tag = "type")]
enum SuggestRecord {
#[serde(rename = "icon")]
Icon {
id: RemoteRecordId,
last_modified: u64,
attachment: Attachment,
},
#[serde(rename = "data")]
Data {
id: RemoteRecordId,
last_modified: u64,
attachment: Attachment,
},
}
#[derive(Debug, Deserialize, PartialEq)]
#[serde(untagged)]
enum FetchedChange {
Record(SuggestRecord),
Unknown {
id: RemoteRecordId,
last_modified: u64,
#[serde(default)]
deleted: bool,
},
}
/// Represents either a single value, or a list of values. This is used to
/// deserialize suggestion attachment bodies.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum OneOrMany<T> {
One(T),
Many(Vec<T>),
}
impl<T> Deref for OneOrMany<T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
match self {
OneOrMany::One(value) => std::slice::from_ref(value),
OneOrMany::Many(values) => values,
}
}
}
#[derive(Debug, Deserialize)]
#[serde(transparent)]
struct SuggestAttachmentData(OneOrMany<RemoteSuggestion>);
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Once;
use mockito::{mock, Matcher};
use serde_json::json;
fn before_each() {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
env_logger::init();
});
}
#[test]
fn is_thread_safe() {
before_each();
// Ensure that `SuggestStore` is usable with UniFFI, which requires
// exposed interfaces to be `Send` and `Sync`.
fn is_send_sync<T: Send + Sync>() {}
is_send_sync::<SuggestStore>();
}
#[test]
fn ingest() -> anyhow::Result<()> {
before_each();
viaduct_reqwest::use_reqwest_backend();
let server_info_m = mock("GET", "/")
.with_body(serde_json::to_vec(&attachment_metadata(&mockito::server_url())).unwrap())
.with_status(200)
.with_header("content-type", "application/json")
.create();
let records = json!({
"data": [{
"id": "1234",
"type": "data",
"last_modified": 15,
"attachment": {
"filename": "data-1.json",
"mimetype": "application/json",
"location": "data-1.json",
"hash": "",
"size": 0,
},
}],
});
let records_m = mock("GET", "/v1/buckets/main/collections/quicksuggest/records")
.match_query(Matcher::Any)
.with_body(serde_json::to_vec(&records).unwrap())
.with_status(200)
.with_header("content-type", "application/json")
.create();
let attachment = json!([{
"id": 0,
"advertiser": "Los Pollos Hermanos",
"iab_category": "8 - Food & Drink",
"keywords": ["lo", "los", "los p", "los pollos", "los pollos h", "los pollos hermanos"],
"title": "Los Pollos Hermanos - Albuquerque",
"url": "https://www.lph-nm.biz",
"icon": "5678",
}]);
let attachment_m = mock("GET", "/attachments/data-1.json")
.with_body(serde_json::to_vec(&attachment).unwrap())
.with_status(200)
.with_header("content-type", "application/json")
.create();
let settings_config = RemoteSettingsConfig {
server_url: Some(mockito::server_url()),
bucket_name: None,
collection_name: "quicksuggest".into(),
};
let store = SuggestStore::new_inner(
"file:ingest?mode=memory&cache=shared",
Some(settings_config),
)?;
store.ingest(&IngestLimits { records: None })?;
server_info_m.expect(1).assert();
records_m.expect(1).assert();
attachment_m.expect(1).assert();
assert_eq!(
store.dbs()?.reader.get_meta(LAST_FETCH_META_KEY)?,
Some(15u64)
);
let suggestions = store.query(&SuggestionQuery {
keyword: "lo".into(),
include_sponsored: true,
..Default::default()
})?;
assert_eq!(
suggestions,
&[Suggestion {
block_id: 0,
advertiser: "Los Pollos Hermanos".into(),
iab_category: "8 - Food & Drink".into(),
is_sponsored: true,
full_keyword: "los".into(),
title: "Los Pollos Hermanos - Albuquerque".into(),
url: "https://www.lph-nm.biz".into(),
icon: None,
impression_url: None,
click_url: None,
}]
);
Ok(())
}
fn attachment_metadata(base_url: &str) -> serde_json::Value {
json!({
"capabilities": {
"attachments": {
"base_url": format!("{}/attachments/", base_url),
},
},
})
}
}