use crate::{Error, Result};
use remote_settings::{
RemoteSettings, RemoteSettingsConfig, RemoteSettingsResponse, RemoteSettingsServer,
};
use serde::Deserialize;
pub(crate) const REMOTE_SETTINGS_COLLECTION: &str = "content-relevance";
pub(crate) trait RelevancyRemoteSettingsClient {
fn get_records(&self) -> Result<RemoteSettingsResponse>;
fn get_attachment(&self, location: &str) -> Result<Vec<u8>>;
}
impl RelevancyRemoteSettingsClient for remote_settings::RemoteSettings {
fn get_records(&self) -> Result<RemoteSettingsResponse> {
Ok(remote_settings::RemoteSettings::get_records(self)?)
}
fn get_attachment(&self, location: &str) -> Result<Vec<u8>> {
Ok(remote_settings::RemoteSettings::get_attachment(
self, location,
)?)
}
}
impl<T: RelevancyRemoteSettingsClient> RelevancyRemoteSettingsClient for &T {
fn get_records(&self) -> Result<RemoteSettingsResponse> {
(*self).get_records()
}
fn get_attachment(&self, location: &str) -> Result<Vec<u8>> {
(*self).get_attachment(location)
}
}
pub fn create_client() -> Result<RemoteSettings> {
Ok(RemoteSettings::new(RemoteSettingsConfig {
collection_name: REMOTE_SETTINGS_COLLECTION.to_string(),
server: Some(RemoteSettingsServer::Prod),
server_url: None,
bucket_name: None,
})?)
}
#[derive(Clone, Debug, Deserialize)]
pub struct RelevancyRecord {
#[allow(dead_code)]
#[serde(rename = "type")]
pub record_type: String,
pub record_custom_details: RecordCustomDetails,
}
#[derive(Clone, Debug, Deserialize)]
pub struct RecordCustomDetails {
pub category_to_domains: CategoryToDomains,
}
#[derive(Clone, Debug, Deserialize)]
pub struct CategoryToDomains {
#[allow(dead_code)]
pub version: i32,
#[allow(dead_code)]
pub category: String,
pub category_code: i32,
}
#[derive(Clone, Debug, Deserialize)]
pub struct RelevancyAttachmentData {
pub domain: String,
}
pub fn from_json<T: serde::de::DeserializeOwned>(value: serde_json::Value) -> Result<T> {
serde_path_to_error::deserialize(value).map_err(|e| Error::RemoteSettingsParseError {
type_name: std::any::type_name::<T>().to_owned(),
path: e.path().to_string(),
error: e.into_inner(),
})
}
pub fn from_json_slice<T: serde::de::DeserializeOwned>(value: &[u8]) -> Result<T> {
let json_value =
serde_json::from_slice(value).map_err(|e| Error::RemoteSettingsParseError {
type_name: std::any::type_name::<T>().to_owned(),
path: "<while parsing JSON>".to_owned(),
error: e,
})?;
from_json(json_value)
}
#[cfg(test)]
pub mod test {
use super::*;
pub struct NullRelavancyRemoteSettingsClient;
impl RelevancyRemoteSettingsClient for NullRelavancyRemoteSettingsClient {
fn get_records(&self) -> Result<RemoteSettingsResponse> {
panic!("NullRelavancyRemoteSettingsClient::get_records was called")
}
fn get_attachment(&self, _location: &str) -> Result<Vec<u8>> {
panic!("NullRelavancyRemoteSettingsClient::get_records was called")
}
}
}