Skip to content

Commit b310c3a

Browse files
committed
[DISCO-3212] Switch Relevancy to new remote settings API
A side effect is the relevancy constructor is now infallible.
1 parent cce6a00 commit b310c3a

File tree

9 files changed

+70
-56
lines changed

9 files changed

+70
-56
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ text, the list view has been slimmed down and a detail view has been added.
3939

4040
### Remote Settings
4141
- Several methods `RemoteSettingsService` are now infallible, which is a breaking change for Swift code.
42+
- `RelevancyStore` constructor
4243
- `RemoteSettingsService` constructor
4344
- `RemoteSettingsService::make_client()`
4445
- `SearchEngineSelector::use_remote_settings_server()`

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

components/relevancy/src/ingest.rs

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,8 @@ fn fetch_interest_data_inner<C: RelevancyRemoteSettingsClient>(
4242
let remote_settings_response = client.get_records()?;
4343
let mut result = vec![];
4444

45-
for record in remote_settings_response.records {
46-
let attachment_data = match &record.attachment {
47-
None => return Err(Error::FetchInterestDataError),
48-
Some(a) => client.get_attachment(&a.location)?,
49-
};
45+
for record in remote_settings_response {
46+
let attachment_data = client.get_attachment(&record)?;
5047
let interest = get_interest(&record)?;
5148
let urls = get_hash_urls(attachment_data)?;
5249
result.extend(std::iter::repeat(interest).zip(urls));
@@ -98,7 +95,6 @@ mod test {
9895
use std::{cell::RefCell, collections::HashMap};
9996

10097
use anyhow::Context;
101-
use remote_settings::RemoteSettingsResponse;
10298
use serde_json::json;
10399

104100
use super::*;
@@ -160,20 +156,12 @@ mod test {
160156
}
161157

162158
impl RelevancyRemoteSettingsClient for SnapshotSettingsClient {
163-
fn get_records(&self) -> Result<RemoteSettingsResponse> {
164-
let records = self.snapshot.borrow().records.clone();
165-
let last_modified = records
166-
.iter()
167-
.map(|record: &RemoteSettingsRecord| record.last_modified)
168-
.max()
169-
.unwrap_or(0);
170-
Ok(RemoteSettingsResponse {
171-
records,
172-
last_modified,
173-
})
159+
fn get_records(&self) -> Result<Vec<RemoteSettingsRecord>> {
160+
Ok(self.snapshot.borrow().records.clone())
174161
}
175162

176-
fn get_attachment(&self, location: &str) -> Result<Vec<u8>> {
163+
fn get_attachment(&self, record: &RemoteSettingsRecord) -> Result<Vec<u8>> {
164+
let location = record.attachment.as_ref().unwrap().location.as_str();
177165
Ok(self
178166
.snapshot
179167
.borrow()

components/relevancy/src/lib.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,22 +20,25 @@ pub mod url_hash;
2020

2121
use rand_distr::{Beta, Distribution};
2222

23+
use std::{collections::HashMap, sync::Arc};
24+
25+
use parking_lot::Mutex;
26+
use remote_settings::{RemoteSettingsClient, RemoteSettingsService};
27+
2328
pub use db::RelevancyDb;
2429
pub use error::{ApiResult, Error, RelevancyApiError, Result};
2530
pub use interest::{Interest, InterestVector};
26-
use parking_lot::Mutex;
2731
pub use ranker::score;
2832

2933
use error_support::handle_error;
3034

3135
use db::BanditData;
32-
use std::collections::HashMap;
3336

3437
uniffi::setup_scaffolding!();
3538

3639
#[derive(uniffi::Object)]
3740
pub struct RelevancyStore {
38-
inner: RelevancyStoreInner<remote_settings::RemoteSettings>,
41+
inner: RelevancyStoreInner<Arc<RemoteSettingsClient>>,
3942
}
4043

4144
/// Top-level API for the Relevancy component
@@ -46,11 +49,13 @@ impl RelevancyStore {
4649
///
4750
/// This is non-blocking since databases and other resources are lazily opened.
4851
#[uniffi::constructor]
49-
#[handle_error(Error)]
50-
pub fn new(db_path: String) -> ApiResult<Self> {
51-
Ok(Self {
52-
inner: RelevancyStoreInner::new(db_path, rs::create_client()?),
53-
})
52+
pub fn new(db_path: String, remote_settings: Arc<RemoteSettingsService>) -> Self {
53+
Self {
54+
inner: RelevancyStoreInner::new(
55+
db_path,
56+
remote_settings.make_client(rs::REMOTE_SETTINGS_COLLECTION.to_string()),
57+
),
58+
}
5459
}
5560

5661
/// Close any open resources (for example databases)

components/relevancy/src/rs.rs

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@
44
*/
55

66
use crate::{Error, Result};
7-
use remote_settings::{
8-
RemoteSettings, RemoteSettingsConfig, RemoteSettingsResponse, RemoteSettingsServer,
9-
};
7+
use remote_settings::{RemoteSettingsClient, RemoteSettingsRecord};
108
use serde::Deserialize;
119
/// The Remote Settings collection name.
1210
pub(crate) const REMOTE_SETTINGS_COLLECTION: &str = "content-relevance";
@@ -16,45 +14,46 @@ pub(crate) const REMOTE_SETTINGS_COLLECTION: &str = "content-relevance";
1614
/// This trait lets tests use a mock client.
1715
pub(crate) trait RelevancyRemoteSettingsClient {
1816
/// Fetches records from the Suggest Remote Settings collection.
19-
fn get_records(&self) -> Result<RemoteSettingsResponse>;
17+
fn get_records(&self) -> Result<Vec<RemoteSettingsRecord>>;
2018

2119
/// Fetches a record's attachment from the Suggest Remote Settings
2220
/// collection.
23-
fn get_attachment(&self, location: &str) -> Result<Vec<u8>>;
21+
fn get_attachment(&self, location: &RemoteSettingsRecord) -> Result<Vec<u8>>;
2422
}
2523

26-
impl RelevancyRemoteSettingsClient for remote_settings::RemoteSettings {
27-
fn get_records(&self) -> Result<RemoteSettingsResponse> {
28-
Ok(remote_settings::RemoteSettings::get_records(self)?)
24+
impl RelevancyRemoteSettingsClient for RemoteSettingsClient {
25+
fn get_records(&self) -> Result<Vec<RemoteSettingsRecord>> {
26+
self.sync()?;
27+
Ok(self
28+
.get_records(false)
29+
.expect("RemoteSettingsClient::get_records() returned None after `sync()` called"))
2930
}
3031

31-
fn get_attachment(&self, location: &str) -> Result<Vec<u8>> {
32-
Ok(remote_settings::RemoteSettings::get_attachment(
33-
self, location,
34-
)?)
32+
fn get_attachment(&self, record: &RemoteSettingsRecord) -> Result<Vec<u8>> {
33+
Ok(self.get_attachment(record)?)
3534
}
3635
}
3736

3837
impl<T: RelevancyRemoteSettingsClient> RelevancyRemoteSettingsClient for &T {
39-
fn get_records(&self) -> Result<RemoteSettingsResponse> {
38+
fn get_records(&self) -> Result<Vec<RemoteSettingsRecord>> {
4039
(*self).get_records()
4140
}
4241

43-
fn get_attachment(&self, location: &str) -> Result<Vec<u8>> {
44-
(*self).get_attachment(location)
42+
fn get_attachment(&self, record: &RemoteSettingsRecord) -> Result<Vec<u8>> {
43+
(*self).get_attachment(record)
4544
}
4645
}
4746

48-
pub fn create_client() -> Result<RemoteSettings> {
49-
Ok(RemoteSettings::new(RemoteSettingsConfig {
50-
collection_name: REMOTE_SETTINGS_COLLECTION.to_string(),
51-
server: Some(RemoteSettingsServer::Prod),
52-
server_url: None,
53-
bucket_name: None,
54-
})?)
47+
impl<T: RelevancyRemoteSettingsClient> RelevancyRemoteSettingsClient for std::sync::Arc<T> {
48+
fn get_records(&self) -> Result<Vec<RemoteSettingsRecord>> {
49+
(**self).get_records()
50+
}
51+
52+
fn get_attachment(&self, record: &RemoteSettingsRecord) -> Result<Vec<u8>> {
53+
(**self).get_attachment(record)
54+
}
5555
}
5656

57-
/// A record in the Relevancy Remote Settings collection.
5857
#[derive(Clone, Debug, Deserialize)]
5958
pub struct RelevancyRecord {
6059
#[allow(dead_code)]
@@ -115,11 +114,11 @@ pub mod test {
115114
pub struct NullRelavancyRemoteSettingsClient;
116115

117116
impl RelevancyRemoteSettingsClient for NullRelavancyRemoteSettingsClient {
118-
fn get_records(&self) -> Result<RemoteSettingsResponse> {
117+
fn get_records(&self) -> Result<Vec<RemoteSettingsRecord>> {
119118
panic!("NullRelavancyRemoteSettingsClient::get_records was called")
120119
}
121120

122-
fn get_attachment(&self, _location: &str) -> Result<Vec<u8>> {
121+
fn get_attachment(&self, _record: &RemoteSettingsRecord) -> Result<Vec<u8>> {
123122
panic!("NullRelavancyRemoteSettingsClient::get_records was called")
124123
}
125124
}

components/remote_settings/src/config.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::{ApiResult, Error, RemoteSettingsContext, Result};
1717
/// This is the version used in the new API, hence the `2` at the end. The plan is to move
1818
/// consumers to the new API, remove the RemoteSettingsConfig struct, then remove the `2` from this
1919
/// name.
20-
#[derive(Debug, Clone, uniffi::Record)]
20+
#[derive(Debug, Default, Clone, uniffi::Record)]
2121
pub struct RemoteSettingsConfig2 {
2222
/// The Remote Settings server to use. Defaults to [RemoteSettingsServer::Prod],
2323
#[uniffi(default = None)]

examples/cli-support/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ license = "MPL-2.0"
88
[dependencies]
99
anyhow = "1.0"
1010
fxa-client = { path = "../../components/fxa-client" }
11+
remote_settings = { path = "../../components/remote_settings" }
1112
sync_manager = { path = "../../components/sync_manager" }
1213
log = "0.4"
1314
sync15 = { path = "../../components/sync15", features=["sync-client"] }

examples/cli-support/src/lib.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@
55
#![allow(unknown_lints)]
66
#![warn(rust_2018_idioms)]
77

8-
use std::path::{Path, PathBuf};
8+
use std::{
9+
path::{Path, PathBuf},
10+
sync::Arc,
11+
};
12+
13+
use remote_settings::{RemoteSettingsConfig2, RemoteSettingsService};
914

1015
pub mod fxa_creds;
1116
pub mod prompt;
@@ -68,3 +73,12 @@ pub fn workspace_root_dir() -> PathBuf {
6873
let cargo_toml_path = Path::new(std::str::from_utf8(&cargo_output).unwrap().trim());
6974
cargo_toml_path.parent().unwrap().to_path_buf()
7075
}
76+
77+
pub fn remote_settings_service() -> Arc<RemoteSettingsService> {
78+
Arc::new(RemoteSettingsService::new(
79+
data_path(Some("remote-settings"))
80+
.to_string_lossy()
81+
.to_string(),
82+
RemoteSettingsConfig2::default(),
83+
))
84+
}

examples/relevancy-cli/src/main.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@
55
use std::sync::Arc;
66

77
use clap::Parser;
8-
use cli_support::fxa_creds::{get_cli_fxa, get_default_fxa_config, SYNC_SCOPE};
8+
use cli_support::{
9+
fxa_creds::{get_cli_fxa, get_default_fxa_config, SYNC_SCOPE},
10+
remote_settings_service,
11+
};
912
use env_logger::Builder;
1013
use interrupt_support::NeverInterrupts;
1114
use places::{ConnectionType, PlacesApi};
@@ -44,8 +47,10 @@ fn main() -> Result<()> {
4447
}
4548
builder.init();
4649
println!("================== Initializing Relevancy ===================");
47-
let relevancy_store =
48-
RelevancyStore::new("file:relevancy-cli-relevancy?mode=memory&cache=shared".to_owned())?;
50+
let relevancy_store = RelevancyStore::new(
51+
"file:relevancy-cli-relevancy?mode=memory&cache=shared".to_owned(),
52+
remote_settings_service(),
53+
);
4954
relevancy_store.ensure_interest_data_populated()?;
5055

5156
println!("==================== Downloading History ====================");

0 commit comments

Comments
 (0)