remote_settings/
lib.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use 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/// Application-level Remote Settings manager.
35///
36/// This handles application-level operations, like syncing all the collections, and acts as a
37/// factory for creating clients.
38#[derive(uniffi::Object)]
39pub struct RemoteSettingsService {
40    // This struct adapts server::RemoteSettingsService into the public API
41    internal: service::RemoteSettingsService,
42}
43
44#[uniffi::export]
45impl RemoteSettingsService {
46    /// Construct a [RemoteSettingsService]
47    ///
48    /// This is typically done early in the application-startup process.
49    ///
50    /// This method performs no IO or network requests and is safe to run in a main thread that
51    /// can't be blocked.
52    ///
53    /// `storage_dir` is a directory to store SQLite files in -- one per collection. If the
54    /// directory does not exist, it will be created when the storage is first used. Only the
55    /// directory and the SQLite files will be created, any parent directories must already exist.
56    #[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    /// Create a new Remote Settings client
64    ///
65    /// This method performs no IO or network requests and is safe to run in a main thread that can't be blocked.
66    pub fn make_client(&self, collection_name: String) -> Arc<RemoteSettingsClient> {
67        self.internal.make_client(collection_name)
68    }
69
70    /// Sync collections for all active clients
71    ///
72    /// The returned list is the list of collections for which updates were seen
73    /// and then synced.
74    #[handle_error(Error)]
75    pub fn sync(&self) -> ApiResult<Vec<String>> {
76        self.internal.sync()
77    }
78
79    /// Update the remote settings config
80    ///
81    /// This will cause all current and future clients to use new config and will delete any stored
82    /// records causing the clients to return new results from the new config.
83    ///
84    /// Only intended for QA/debugging.  Swapping the remote settings server in the middle of
85    /// execution can cause weird effects.
86    #[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/// Client for a single Remote Settings collection
97///
98/// Use [RemoteSettingsService::make_client] to create these.
99#[derive(uniffi::Object)]
100pub struct RemoteSettingsClient {
101    // This struct adapts client::RemoteSettingsClient into the public API
102    internal: client::RemoteSettingsClient,
103}
104
105#[uniffi::export]
106impl RemoteSettingsClient {
107    /// Collection this client is for
108    pub fn collection_name(&self) -> String {
109        self.internal.collection_name().to_owned()
110    }
111
112    /// Get the current set of records.
113    ///
114    /// This method normally fetches records from the last sync.  This means that it returns fast
115    /// and does not make any network requests.
116    ///
117    /// If records have not yet been synced it will return None.  Use `sync_if_empty = true` to
118    /// change this behavior and perform a network request in this case.  That this is probably a
119    /// bad idea if you want to fetch the setting in application startup or when building the UI.
120    ///
121    /// None will also be returned on disk IO errors or other unexpected errors.  The reason for
122    /// this is that there is not much an application can do in this situation other than fall back
123    /// to the same default handling as if records have not been synced.
124    ///
125    /// Application-services schedules regular dumps of the server data for specific collections.
126    /// For these collections, `get_records` will never return None.  If you would like to add your
127    /// collection to this list, please reach out to the DISCO team.
128    #[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                // Log/report the error
134                trace!("get_records error: {e}");
135                convert_log_report_error(e);
136                // Throw away the converted result and return None, there's nothing a client can
137                // really do with an error except treat it as the None case
138                None
139            }
140        }
141    }
142
143    /// Get the current set of records as a map of record_id -> record.
144    ///
145    /// See [Self::get_records] for an explanation of when this makes network requests, error
146    /// handling, and how the `sync_if_empty` param works.
147    #[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    /// Get attachment data for a remote settings record
157    ///
158    /// Attachments are large binary blobs used for data that doesn't fit in a normal record.  They
159    /// are handled differently than other record data:
160    ///
161    ///   - Attachments are not downloaded in [RemoteSettingsService::sync]
162    ///   - This method will make network requests if the attachment is not cached
163    ///   - This method will throw if there is a network or other error when fetching the
164    ///     attachment data.
165    #[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    /// Shutdown the client, releasing the SQLite connection used to cache records.
176    pub fn shutdown(&self) {
177        self.internal.shutdown()
178    }
179}
180
181impl RemoteSettingsClient {
182    /// Create a new client.  This is not exposed to foreign code, consumers need to call
183    /// [RemoteSettingsService::make_client]
184    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    /// Construct a new Remote Settings client with the given configuration.
212    #[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    /// Fetch all records for the configuration this client was initialized with.
222    #[handle_error(Error)]
223    pub fn get_records(&self) -> ApiResult<RemoteSettingsResponse> {
224        let resp = self.client.get_records()?;
225        Ok(resp)
226    }
227
228    /// Fetch all records added to the server since the provided timestamp,
229    /// using the configuration this client was initialized with.
230    #[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    /// Download an attachment with the provided id to the provided path.
237    #[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
250// Public functions that we don't expose via UniFFI.
251//
252// The long-term plan is to create a new remote settings client, transition nimbus + suggest to the
253// new API, then delete this code.
254impl RemoteSettings {
255    /// Fetches all records for a collection that can be found in the server,
256    /// bucket, and collection defined by the [ClientConfig] used to generate
257    /// this [Client]. This function will return the raw viaduct [Response].
258    #[handle_error(Error)]
259    pub fn get_records_raw(&self) -> ApiResult<viaduct::Response> {
260        self.client.get_records_raw()
261    }
262
263    /// Downloads an attachment from [attachment_location]. NOTE: there are no
264    /// guarantees about a maximum size, so use care when fetching potentially
265    /// large attachments.
266    #[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    // This test was designed as a proof-of-concept and requires a locally-run Remote Settings server.
339    // If this were to be included in CI, it would require pulling the RS docker image and scripting
340    // its configuration, as well as dynamically finding the attachment id, which would more closely
341    // mimic a real world usecase.
342    // #[test]
343    #[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}