| 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 |
|
| 5 |
use crate::api::{self, StorageChanges}; |
| 6 |
use crate::db::{StorageDb, ThreadSafeStorageDb}; |
| 7 |
use crate::error::*; |
| 8 |
use crate::migration::{migrate, MigrationInfo}; |
| 9 |
use crate::sync; |
| 10 |
use std::path::Path; |
| 11 |
use std::sync::Arc; |
| 12 |
|
| 13 |
use interrupt_support::SqlInterruptHandle; |
| 14 |
use serde_json::Value as JsonValue; |
| 15 |
|
| 16 |
/// A store is used to access `storage.sync` data. It manages an underlying |
| 17 |
/// database connection, and exposes methods for reading and writing storage |
| 18 |
/// items scoped to an extension ID. Each item is a JSON object, with one or |
| 19 |
/// more string keys, and values of any type that can serialize to JSON. |
| 20 |
/// |
| 21 |
/// An application should create only one store, and manage the instance as a |
| 22 |
/// singleton. While this isn't enforced, if you make multiple stores pointing |
| 23 |
/// to the same database file, you are going to have a bad time: each store will |
| 24 |
/// create its own database connection, using up extra memory and CPU cycles, |
| 25 |
/// and causing write contention. For this reason, you should only call |
| 26 |
/// `Store::new()` (or `webext_store_new()`, from the FFI) once. |
| 27 |
/// |
| 28 |
/// Note that our Db implementation is behind an Arc<> because we share that |
| 29 |
/// connection with our sync engines - ie, these engines also hold an Arc<> |
| 30 |
/// around the same object. |
| 31 |
pub struct WebExtStorageStore { |
| 32 |
pub(crate) db: Arc<ThreadSafeStorageDb>, |
| 33 |
} |
| 34 |
|
| 35 |
impl WebExtStorageStore { |
| 36 |
/// Creates a store backed by a database at `db_path`. The path can be a |
| 37 |
/// file path or `file:` URI. |
| 38 |
pub fn new(db_path: impl AsRef<Path>) -> Result<Self> { |
| 39 |
let db = StorageDb::new(db_path)?; |
| 40 |
Ok(Self { |
| 41 |
db: Arc::new(ThreadSafeStorageDb::new(db)), |
| 42 |
}) |
| 43 |
} |
| 44 |
|
| 45 |
/// Creates a store backed by an in-memory database. |
| 46 |
#[cfg(test)] |
| 47 |
pub fn new_memory(db_path: &str) -> Result<Self> { |
| 48 |
let db = StorageDb::new_memory(db_path)?; |
| 49 |
Ok(Self { |
| 50 |
db: Arc::new(ThreadSafeStorageDb::new(db)), |
| 51 |
}) |
| 52 |
} |
| 53 |
|
| 54 |
/// Returns an interrupt handle for this store. |
| 55 |
pub fn interrupt_handle(&self) -> Arc<SqlInterruptHandle> { |
| 56 |
self.db.interrupt_handle() |
| 57 |
} |
| 58 |
|
| 59 |
/// Sets one or more JSON key-value pairs for an extension ID. Returns a |
| 60 |
/// list of changes, with existing and new values for each key in `val`. |
| 61 |
pub fn set(&self, ext_id: &str, val: JsonValue) -> Result<StorageChanges> { |
| 62 |
let db = &self.db.lock(); |
| 63 |
let conn = db.get_connection()?; |
| 64 |
let tx = conn.unchecked_transaction()?; |
| 65 |
let result = api::set(&tx, ext_id, val)?; |
| 66 |
tx.commit()?; |
| 67 |
Ok(result) |
| 68 |
} |
| 69 |
|
| 70 |
/// Returns information about per-extension usage |
| 71 |
pub fn usage(&self) -> Result<Vec<crate::UsageInfo>> { |
| 72 |
let db = &self.db.lock(); |
| 73 |
let conn = db.get_connection()?; |
| 74 |
api::usage(conn) |
| 75 |
} |
| 76 |
|
| 77 |
/// Returns the values for one or more keys `keys` can be: |
| 78 |
/// |
| 79 |
/// - `null`, in which case all key-value pairs for the extension are |
| 80 |
/// returned, or an empty object if the extension doesn't have any |
| 81 |
/// stored data. |
| 82 |
/// - A single string key, in which case an object with only that key |
| 83 |
/// and its value is returned, or an empty object if the key doesn't |
| 84 |
// exist. |
| 85 |
/// - An array of string keys, in which case an object with only those |
| 86 |
/// keys and their values is returned. Any keys that don't exist will be |
| 87 |
/// omitted. |
| 88 |
/// - An object where the property names are keys, and each value is the |
| 89 |
/// default value to return if the key doesn't exist. |
| 90 |
/// |
| 91 |
/// This method always returns an object (that is, a |
| 92 |
/// `serde_json::Value::Object`). |
| 93 |
pub fn get(&self, ext_id: &str, keys: JsonValue) -> Result<JsonValue> { |
| 94 |
// Don't care about transactions here. |
| 95 |
let db = &self.db.lock(); |
| 96 |
let conn = db.get_connection()?; |
| 97 |
api::get(conn, ext_id, keys) |
| 98 |
} |
| 99 |
|
| 100 |
/// Deletes the values for one or more keys. As with `get`, `keys` can be |
| 101 |
/// either a single string key, or an array of string keys. Returns a list |
| 102 |
/// of changes, where each change contains the old value for each deleted |
| 103 |
/// key. |
| 104 |
pub fn remove(&self, ext_id: &str, keys: JsonValue) -> Result<StorageChanges> { |
| 105 |
let db = &self.db.lock(); |
| 106 |
let conn = db.get_connection()?; |
| 107 |
let tx = conn.unchecked_transaction()?; |
| 108 |
let result = api::remove(&tx, ext_id, keys)?; |
| 109 |
tx.commit()?; |
| 110 |
Ok(result) |
| 111 |
} |
| 112 |
|
| 113 |
/// Deletes all key-value pairs for the extension. As with `remove`, returns |
| 114 |
/// a list of changes, where each change contains the old value for each |
| 115 |
/// deleted key. |
| 116 |
pub fn clear(&self, ext_id: &str) -> Result<StorageChanges> { |
| 117 |
let db = &self.db.lock(); |
| 118 |
let conn = db.get_connection()?; |
| 119 |
let tx = conn.unchecked_transaction()?; |
| 120 |
let result = api::clear(&tx, ext_id)?; |
| 121 |
tx.commit()?; |
| 122 |
Ok(result) |
| 123 |
} |
| 124 |
|
| 125 |
/// Returns the bytes in use for the specified items (which can be null, |
| 126 |
/// a string, or an array) |
| 127 |
pub fn get_bytes_in_use(&self, ext_id: &str, keys: JsonValue) -> Result<u64> { |
| 128 |
let db = &self.db.lock(); |
| 129 |
let conn = db.get_connection()?; |
| 130 |
Ok(api::get_bytes_in_use(conn, ext_id, keys)? as u64) |
| 131 |
} |
| 132 |
|
| 133 |
/// Closes the store and its database connection. See the docs for |
| 134 |
/// `StorageDb::close` for more details on when this can fail. |
| 135 |
pub fn close(&self) -> Result<()> { |
| 136 |
let mut db = self.db.lock(); |
| 137 |
db.close() |
| 138 |
} |
| 139 |
|
| 140 |
/// Gets the changes which the current sync applied. Should be used |
| 141 |
/// immediately after the bridged engine is told to apply incoming changes, |
| 142 |
/// and can be used to notify observers of the StorageArea of the changes |
| 143 |
/// that were applied. |
| 144 |
/// The result is a Vec of already JSON stringified changes. |
| 145 |
pub fn get_synced_changes(&self) -> Result<Vec<sync::SyncedExtensionChange>> { |
| 146 |
let db = self.db.lock(); |
| 147 |
sync::get_synced_changes(&db) |
| 148 |
} |
| 149 |
|
| 150 |
/// Migrates data from a database in the format of the "old" kinto |
| 151 |
/// implementation. Information about how the migration went is stored in |
| 152 |
/// the database, and can be read using `Self::take_migration_info`. |
| 153 |
/// |
| 154 |
/// Note that `filename` isn't normalized or canonicalized. |
| 155 |
pub fn migrate(&self, filename: impl AsRef<Path>) -> Result<()> { |
| 156 |
let db = &self.db.lock(); |
| 157 |
let conn = db.get_connection()?; |
| 158 |
let tx = conn.unchecked_transaction()?; |
| 159 |
let result = migrate(&tx, filename.as_ref())?; |
| 160 |
tx.commit()?; |
| 161 |
// Failing to store this information should not cause migration failure. |
| 162 |
if let Err(e) = result.store(conn) { |
| 163 |
debug_assert!(false, "Migration error: {:?}", e); |
| 164 |
warn!("Failed to record migration telmetry: {}", e); |
| 165 |
} |
| 166 |
Ok(()) |
| 167 |
} |
| 168 |
|
| 169 |
/// Read-and-delete (e.g. `take` in rust parlance, see Option::take) |
| 170 |
/// operation for any MigrationInfo stored in this database. |
| 171 |
pub fn take_migration_info(&self) -> Result<Option<MigrationInfo>> { |
| 172 |
let db = &self.db.lock(); |
| 173 |
let conn = db.get_connection()?; |
| 174 |
let tx = conn.unchecked_transaction()?; |
| 175 |
let result = MigrationInfo::take(&tx)?; |
| 176 |
tx.commit()?; |
| 177 |
Ok(result) |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
#[cfg(test)] |
| 182 |
pub mod test { |
| 183 |
use super::*; |
| 184 |
#[test] |
| 185 |
fn test_send() { |
| 186 |
fn ensure_send<T: Send>() {} |
| 187 |
// Compile will fail if not send. |
| 188 |
ensure_send::<WebExtStorageStore>(); |
| 189 |
} |
| 190 |
|
| 191 |
pub fn new_mem_store() -> WebExtStorageStore { |
| 192 |
WebExtStorageStore { |
| 193 |
db: Arc::new(ThreadSafeStorageDb::new(crate::db::test::new_mem_db())), |
| 194 |
} |
| 195 |
} |
| 196 |
} |