1use std::{collections::HashMap, fs::File, io::prelude::Write, sync::Arc};
6
7use error_support::{convert_log_report_error, handle_error};
8
9pub mod cache;
10pub mod client;
11pub mod config;
12pub mod context;
13pub mod error;
14pub mod schema;
15pub mod service;
16#[cfg(feature = "signatures")]
17pub(crate) mod signatures;
18pub mod storage;
19
20pub(crate) mod jexl_filter;
21mod macros;
22
23pub use client::{Attachment, RemoteSettingsRecord, RemoteSettingsResponse, RsJsonObject};
24pub use config::{BaseUrl, RemoteSettingsConfig, RemoteSettingsConfig2, RemoteSettingsServer};
25pub use context::RemoteSettingsContext;
26pub use error::{trace, ApiResult, RemoteSettingsError, Result};
27
28use client::Client;
29use error::Error;
30use storage::Storage;
31
32uniffi::setup_scaffolding!("remote_settings");
33
34#[derive(uniffi::Object)]
39pub struct RemoteSettingsService {
40 internal: service::RemoteSettingsService,
42}
43
44#[uniffi::export]
45impl RemoteSettingsService {
46 #[uniffi::constructor]
57 pub fn new(storage_dir: String, config: RemoteSettingsConfig2) -> Self {
58 Self {
59 internal: service::RemoteSettingsService::new(storage_dir, config),
60 }
61 }
62
63 pub fn make_client(&self, collection_name: String) -> Arc<RemoteSettingsClient> {
67 self.internal.make_client(collection_name)
68 }
69
70 #[handle_error(Error)]
75 pub fn sync(&self) -> ApiResult<Vec<String>> {
76 self.internal.sync()
77 }
78
79 #[handle_error(Error)]
87 pub fn update_config(&self, config: RemoteSettingsConfig2) -> ApiResult<()> {
88 self.internal.update_config(config)
89 }
90
91 pub fn client_url(&self) -> String {
92 self.internal.client_url().to_string()
93 }
94}
95
96#[derive(uniffi::Object)]
100pub struct RemoteSettingsClient {
101 internal: client::RemoteSettingsClient,
103}
104
105#[uniffi::export]
106impl RemoteSettingsClient {
107 pub fn collection_name(&self) -> String {
109 self.internal.collection_name().to_owned()
110 }
111
112 #[uniffi::method(default(sync_if_empty = false))]
129 pub fn get_records(&self, sync_if_empty: bool) -> Option<Vec<RemoteSettingsRecord>> {
130 match self.internal.get_records(sync_if_empty) {
131 Ok(records) => records,
132 Err(e) => {
133 trace!("get_records error: {e}");
135 convert_log_report_error(e);
136 None
139 }
140 }
141 }
142
143 #[uniffi::method(default(sync_if_empty = false))]
148 pub fn get_records_map(
149 &self,
150 sync_if_empty: bool,
151 ) -> Option<HashMap<String, RemoteSettingsRecord>> {
152 self.get_records(sync_if_empty)
153 .map(|records| records.into_iter().map(|r| (r.id.clone(), r)).collect())
154 }
155
156 #[handle_error(Error)]
166 pub fn get_attachment(&self, record: &RemoteSettingsRecord) -> ApiResult<Vec<u8>> {
167 self.internal.get_attachment(record)
168 }
169
170 #[handle_error(Error)]
171 pub fn sync(&self) -> ApiResult<()> {
172 self.internal.sync()
173 }
174
175 pub fn shutdown(&self) {
177 self.internal.shutdown()
178 }
179}
180
181impl RemoteSettingsClient {
182 fn new(
185 base_url: BaseUrl,
186 bucket_name: String,
187 collection_name: String,
188 #[allow(unused)] context: Option<RemoteSettingsContext>,
189 storage: Storage,
190 ) -> Self {
191 Self {
192 internal: client::RemoteSettingsClient::new(
193 base_url,
194 bucket_name,
195 collection_name,
196 context,
197 storage,
198 ),
199 }
200 }
201}
202
203#[derive(uniffi::Object)]
204pub struct RemoteSettings {
205 pub config: RemoteSettingsConfig,
206 client: Client,
207}
208
209#[uniffi::export]
210impl RemoteSettings {
211 #[uniffi::constructor]
213 #[handle_error(Error)]
214 pub fn new(remote_settings_config: RemoteSettingsConfig) -> ApiResult<Self> {
215 Ok(RemoteSettings {
216 config: remote_settings_config.clone(),
217 client: Client::new(remote_settings_config)?,
218 })
219 }
220
221 #[handle_error(Error)]
223 pub fn get_records(&self) -> ApiResult<RemoteSettingsResponse> {
224 let resp = self.client.get_records()?;
225 Ok(resp)
226 }
227
228 #[handle_error(Error)]
231 pub fn get_records_since(&self, timestamp: u64) -> ApiResult<RemoteSettingsResponse> {
232 let resp = self.client.get_records_since(timestamp)?;
233 Ok(resp)
234 }
235
236 #[handle_error(Error)]
238 pub fn download_attachment_to_path(
239 &self,
240 attachment_id: String,
241 path: String,
242 ) -> ApiResult<()> {
243 let resp = self.client.get_attachment(&attachment_id)?;
244 let mut file = File::create(path).map_err(Error::AttachmentFileError)?;
245 file.write_all(&resp).map_err(Error::AttachmentFileError)?;
246 Ok(())
247 }
248}
249
250impl RemoteSettings {
255 #[handle_error(Error)]
259 pub fn get_records_raw(&self) -> ApiResult<viaduct::Response> {
260 self.client.get_records_raw()
261 }
262
263 #[handle_error(Error)]
267 pub fn get_attachment(&self, attachment_location: &str) -> ApiResult<Vec<u8>> {
268 self.client.get_attachment(attachment_location)
269 }
270}
271
272#[cfg(test)]
273mod test {
274 use super::*;
275 use crate::RemoteSettingsRecord;
276 use mockito::{mock, Matcher};
277
278 #[test]
279 fn test_get_records() {
280 viaduct_dev::init_backend_dev();
281 let m = mock(
282 "GET",
283 "/v1/buckets/the-bucket/collections/the-collection/records",
284 )
285 .with_body(response_body())
286 .with_status(200)
287 .with_header("content-type", "application/json")
288 .with_header("etag", "\"1000\"")
289 .create();
290
291 let config = RemoteSettingsConfig {
292 server: Some(RemoteSettingsServer::Custom {
293 url: mockito::server_url(),
294 }),
295 server_url: None,
296 bucket_name: Some(String::from("the-bucket")),
297 collection_name: String::from("the-collection"),
298 };
299 let remote_settings = RemoteSettings::new(config).unwrap();
300
301 let resp = remote_settings.get_records().unwrap();
302
303 assert!(are_equal_json(JPG_ATTACHMENT, &resp.records[0]));
304 assert_eq!(1000, resp.last_modified);
305 m.expect(1).assert();
306 }
307
308 #[test]
309 fn test_get_records_since() {
310 viaduct_dev::init_backend_dev();
311 let m = mock(
312 "GET",
313 "/v1/buckets/the-bucket/collections/the-collection/records",
314 )
315 .match_query(Matcher::UrlEncoded("gt_last_modified".into(), "500".into()))
316 .with_body(response_body())
317 .with_status(200)
318 .with_header("content-type", "application/json")
319 .with_header("etag", "\"1000\"")
320 .create();
321
322 let config = RemoteSettingsConfig {
323 server: Some(RemoteSettingsServer::Custom {
324 url: mockito::server_url(),
325 }),
326 server_url: None,
327 bucket_name: Some(String::from("the-bucket")),
328 collection_name: String::from("the-collection"),
329 };
330 let remote_settings = RemoteSettings::new(config).unwrap();
331
332 let resp = remote_settings.get_records_since(500).unwrap();
333 assert!(are_equal_json(JPG_ATTACHMENT, &resp.records[0]));
334 assert_eq!(1000, resp.last_modified);
335 m.expect(1).assert();
336 }
337
338 #[allow(dead_code)]
344 fn test_download() {
345 viaduct_dev::init_backend_dev();
346 let config = RemoteSettingsConfig {
347 server: Some(RemoteSettingsServer::Custom {
348 url: "http://localhost:8888".into(),
349 }),
350 server_url: None,
351 bucket_name: Some(String::from("the-bucket")),
352 collection_name: String::from("the-collection"),
353 };
354 let remote_settings = RemoteSettings::new(config).unwrap();
355
356 remote_settings
357 .download_attachment_to_path(
358 "d3a5eccc-f0ca-42c3-b0bb-c0d4408c21c9.jpg".to_string(),
359 "test.jpg".to_string(),
360 )
361 .unwrap();
362 }
363
364 fn are_equal_json(str: &str, rec: &RemoteSettingsRecord) -> bool {
365 let r1: RemoteSettingsRecord = serde_json::from_str(str).unwrap();
366 &r1 == rec
367 }
368
369 fn response_body() -> String {
370 format!(
371 r#"
372 {{
373 "data": [
374 {},
375 {},
376 {}
377 ]
378 }}"#,
379 JPG_ATTACHMENT, PDF_ATTACHMENT, NO_ATTACHMENT
380 )
381 }
382
383 const JPG_ATTACHMENT: &str = r#"
384 {
385 "title": "jpg-attachment",
386 "content": "content",
387 "attachment": {
388 "filename": "jgp-attachment.jpg",
389 "location": "the-bucket/the-collection/d3a5eccc-f0ca-42c3-b0bb-c0d4408c21c9.jpg",
390 "hash": "2cbd593f3fd5f1585f92265433a6696a863bc98726f03e7222135ff0d8e83543",
391 "mimetype": "image/jpeg",
392 "size": 1374325
393 },
394 "id": "c5dcd1da-7126-4abb-846b-ec85b0d4d0d7",
395 "schema": 1677694447771,
396 "last_modified": 1677694949407
397 }
398 "#;
399
400 const PDF_ATTACHMENT: &str = r#"
401 {
402 "title": "with-attachment",
403 "content": "content",
404 "attachment": {
405 "filename": "pdf-attachment.pdf",
406 "location": "the-bucket/the-collection/5f7347c2-af92-411d-a65b-f794f9b5084c.pdf",
407 "hash": "de1cde3571ef3faa77ea0493276de9231acaa6f6651602e93aa1036f51181e9b",
408 "mimetype": "application/pdf",
409 "size": 157
410 },
411 "id": "ff301910-6bf5-4cfe-bc4c-5c80308661a5",
412 "schema": 1677694447771,
413 "last_modified": 1677694470354
414 }
415 "#;
416
417 const NO_ATTACHMENT: &str = r#"
418 {
419 "title": "no-attachment",
420 "content": "content",
421 "schema": 1677694447771,
422 "id": "7403c6f9-79be-4e0c-a37a-8f2b5bd7ad58",
423 "last_modified": 1677694455368
424 }
425 "#;
426}