nimbus/stateful/
updating.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 https://mozilla.org/MPL/2.0/. */
4
5//! This module implements the primitive functions to implement
6//! safe updating from the server.
7
8use crate::error::Result;
9use crate::stateful::persistence::{Database, StoreId, Writer};
10use crate::Experiment;
11
12const KEY_PENDING_UPDATES: &str = "pending-experiment-updates";
13
14pub fn write_pending_experiments(
15    db: &Database,
16    writer: &mut Writer,
17    experiments: Vec<Experiment>,
18) -> Result<()> {
19    db.get_store(StoreId::Updates)
20        .put(writer, KEY_PENDING_UPDATES, &experiments)
21}
22
23pub fn read_and_remove_pending_experiments(
24    db: &Database,
25    writer: &mut Writer,
26) -> Result<Option<Vec<Experiment>>> {
27    let store = db.get_store(StoreId::Updates);
28    let experiments = store.get::<Vec<Experiment>, _>(writer, KEY_PENDING_UPDATES)?;
29
30    // Only clear the store if there's updates available.
31    // If we're accidentally called from the main thread,
32    // we don't want to be writing unless we absolutely have to.
33    if experiments.is_some() {
34        store.clear(writer)?;
35    }
36
37    // An empty Some(vec![]) is "updates of an empty list" i.e. unenrolling from all experiments
38    // None is "there are no pending updates".
39    Ok(experiments)
40}