| 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 |
use std::cell::{Cell, RefCell}; |
| 6 |
use std::collections::btree_map::Entry; |
| 7 |
use std::collections::BTreeMap; |
| 8 |
use std::fs; |
| 9 |
use std::io; |
| 10 |
use std::num::NonZeroU64; |
| 11 |
use std::path::Path; |
| 12 |
use std::str; |
| 13 |
use std::sync::atomic::{AtomicUsize, Ordering}; |
| 14 |
use std::sync::RwLock; |
| 15 |
use std::time::{Duration, Instant}; |
| 16 |
|
| 17 |
use crate::ErrorKind; |
| 18 |
|
| 19 |
use malloc_size_of::MallocSizeOf; |
| 20 |
use rkv::{StoreError, StoreOptions}; |
| 21 |
|
| 22 |
/// Unwrap a `Result`s `Ok` value or do the specified action. |
| 23 |
/// |
| 24 |
/// This is an alternative to the question-mark operator (`?`), |
| 25 |
/// when the other action should not be to return the error. |
| 26 |
macro_rules! unwrap_or { |
| 27 |
($expr:expr, $or:expr) => { |
| 28 |
match $expr { |
| 29 |
Ok(x) => x, |
| 30 |
Err(_) => { |
| 31 |
$or; |
| 32 |
} |
| 33 |
} |
| 34 |
}; |
| 35 |
} |
| 36 |
|
| 37 |
macro_rules! measure_commit { |
| 38 |
($this:ident, $expr:expr) => {{ |
| 39 |
let now = ::std::time::Instant::now(); |
| 40 |
let res = $expr; |
| 41 |
let elapsed = now.elapsed(); |
| 42 |
if let Ok(elapsed) = elapsed.as_micros().try_into() { |
| 43 |
let mut samples = $this.write_timings.borrow_mut(); |
| 44 |
samples.push(elapsed); |
| 45 |
} |
| 46 |
res |
| 47 |
}}; |
| 48 |
} |
| 49 |
|
| 50 |
/// cbindgen:ignore |
| 51 |
pub type Rkv = rkv::Rkv<rkv::backend::SafeModeEnvironment>; |
| 52 |
/// cbindgen:ignore |
| 53 |
pub type SingleStore = rkv::SingleStore<rkv::backend::SafeModeDatabase>; |
| 54 |
/// cbindgen:ignore |
| 55 |
pub type Writer<'t> = rkv::Writer<rkv::backend::SafeModeRwTransaction<'t>>; |
| 56 |
|
| 57 |
#[derive(Debug)] |
| 58 |
pub enum RkvLoadState { |
| 59 |
Ok, |
| 60 |
Err(rkv::StoreError), |
| 61 |
} |
| 62 |
|
| 63 |
pub fn rkv_new(path: &Path) -> std::result::Result<(Rkv, RkvLoadState), rkv::StoreError> { |
| 64 |
match Rkv::new::<rkv::backend::SafeMode>(path) { |
| 65 |
// An invalid file can mean: |
| 66 |
// 1. An empty file. |
| 67 |
// 2. A corrupted file. |
| 68 |
// |
| 69 |
// In both instances there's not much we can do. |
| 70 |
// Drop the data by removing the file, and start over. |
| 71 |
Err(rkv::StoreError::FileInvalid) => { |
| 72 |
let safebin = path.join("data.safe.bin"); |
| 73 |
fs::remove_file(safebin).map_err(|_| rkv::StoreError::FileInvalid)?; |
| 74 |
// Now try again, we only handle that error once. |
| 75 |
let rkv = Rkv::new::<rkv::backend::SafeMode>(path)?; |
| 76 |
Ok((rkv, RkvLoadState::Err(rkv::StoreError::FileInvalid))) |
| 77 |
} |
| 78 |
Err(rkv::StoreError::DatabaseCorrupted) => { |
| 79 |
let safebin = path.join("data.safe.bin"); |
| 80 |
fs::remove_file(safebin).map_err(|_| rkv::StoreError::DatabaseCorrupted)?; |
| 81 |
// Try again, only allowing the error once. |
| 82 |
let rkv = Rkv::new::<rkv::backend::SafeMode>(path)?; |
| 83 |
Ok((rkv, RkvLoadState::Err(rkv::StoreError::DatabaseCorrupted))) |
| 84 |
} |
| 85 |
other => { |
| 86 |
let rkv = other?; |
| 87 |
Ok((rkv, RkvLoadState::Ok)) |
| 88 |
} |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
use crate::common_metric_data::CommonMetricDataInternal; |
| 93 |
use crate::metrics::Metric; |
| 94 |
use crate::Glean; |
| 95 |
use crate::Lifetime; |
| 96 |
use crate::Result; |
| 97 |
|
| 98 |
pub struct Database { |
| 99 |
/// Handle to the database environment. |
| 100 |
rkv: Rkv, |
| 101 |
|
| 102 |
/// Handles to the "lifetime" stores. |
| 103 |
/// |
| 104 |
/// A "store" is a handle to the underlying database. |
| 105 |
/// We keep them open for fast and frequent access. |
| 106 |
user_store: SingleStore, |
| 107 |
ping_store: SingleStore, |
| 108 |
application_store: SingleStore, |
| 109 |
|
| 110 |
/// If the `delay_ping_lifetime_io` Glean config option is `true`, |
| 111 |
/// we will save metrics with 'ping' lifetime data in a map temporarily |
| 112 |
/// so as to persist them to disk using rkv in bulk on demand. |
| 113 |
ping_lifetime_data: Option<RwLock<BTreeMap<String, Metric>>>, |
| 114 |
|
| 115 |
/// A count of how many database writes have been done since the last ping-lifetime flush. |
| 116 |
/// |
| 117 |
/// A ping-lifetime flush is automatically done after `ping_lifetime_threshold` writes. |
| 118 |
/// |
| 119 |
/// Only relevant if `delay_ping_lifetime_io` is set to `true`, |
| 120 |
ping_lifetime_count: AtomicUsize, |
| 121 |
|
| 122 |
/// Write-count threshold when to auto-flush. `0` disables it. |
| 123 |
ping_lifetime_threshold: usize, |
| 124 |
|
| 125 |
/// The last time the `lifetime=ping` data was flushed to disk. |
| 126 |
/// |
| 127 |
/// Data is flushed to disk automatically when the last flush was more than |
| 128 |
/// `ping_lifetime_max_time` ago. |
| 129 |
/// |
| 130 |
/// Only relevant if `delay_ping_lifetime_io` is set to `true`, |
| 131 |
ping_lifetime_store_ts: Cell<Instant>, |
| 132 |
|
| 133 |
/// After what time to auto-flush. 0 disables it. |
| 134 |
ping_lifetime_max_time: Duration, |
| 135 |
|
| 136 |
/// Initial file size when opening the database. |
| 137 |
file_size: Option<NonZeroU64>, |
| 138 |
|
| 139 |
/// RKV load state |
| 140 |
rkv_load_state: RkvLoadState, |
| 141 |
|
| 142 |
/// Times an Rkv write-commit took. |
| 143 |
/// Re-applied as samples in a timing distribution later. |
| 144 |
pub(crate) write_timings: RefCell<Vec<i64>>, |
| 145 |
} |
| 146 |
|
| 147 |
impl MallocSizeOf for Database { |
| 148 |
fn size_of(&self, _ops: &mut malloc_size_of::MallocSizeOfOps) -> usize { |
| 149 |
// TODO(bug 1960592): Fill in gaps. |
| 150 |
|
| 151 |
/* |
| 152 |
let mut n = 0; |
| 153 |
|
| 154 |
n += 0; // self.rkv.size_of(ops) -- not implemented. |
| 155 |
n += 0; // self.user_store.size_of(ops) -- not implemented. |
| 156 |
|
| 157 |
n += self |
| 158 |
.ping_lifetime_data |
| 159 |
.as_ref() |
| 160 |
.map(|_data| { |
| 161 |
// TODO(bug 1960592): servo's malloc_size_of implements it for BTreeMap. |
| 162 |
//let lock = data.read().unwrap(); |
| 163 |
//(*lock).size_of(ops) |
| 164 |
0 |
| 165 |
}) |
| 166 |
.unwrap_or(0); |
| 167 |
|
| 168 |
n |
| 169 |
*/ |
| 170 |
|
| 171 |
0 |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
impl std::fmt::Debug for Database { |
| 176 |
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 177 |
fmt.debug_struct("Database") |
| 178 |
.field("rkv", &self.rkv) |
| 179 |
.field("user_store", &"SingleStore") |
| 180 |
.field("ping_store", &"SingleStore") |
| 181 |
.field("application_store", &"SingleStore") |
| 182 |
.field("ping_lifetime_data", &self.ping_lifetime_data) |
| 183 |
.finish() |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
/// Calculate the database size from all the files in the directory. |
| 188 |
/// |
| 189 |
/// # Arguments |
| 190 |
/// |
| 191 |
/// *`path` - The path to the directory |
| 192 |
/// |
| 193 |
/// # Returns |
| 194 |
/// |
| 195 |
/// Returns the non-zero combined size of all files in a directory, |
| 196 |
/// or `None` on error or if the size is `0`. |
| 197 |
fn database_size(dir: &Path) -> Option<NonZeroU64> { |
| 198 |
let mut total_size = 0; |
| 199 |
if let Ok(entries) = fs::read_dir(dir) { |
| 200 |
for entry in entries.flatten() { |
| 201 |
if let Ok(file_type) = entry.file_type() { |
| 202 |
if file_type.is_file() { |
| 203 |
let path = entry.path(); |
| 204 |
if let Ok(metadata) = fs::metadata(path) { |
| 205 |
total_size += metadata.len(); |
| 206 |
} else { |
| 207 |
continue; |
| 208 |
} |
| 209 |
} |
| 210 |
} |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
NonZeroU64::new(total_size) |
| 215 |
} |
| 216 |
|
| 217 |
impl Database { |
| 218 |
/// Initializes the data store. |
| 219 |
/// |
| 220 |
/// This opens the underlying rkv store and creates |
| 221 |
/// the underlying directory structure. |
| 222 |
/// |
| 223 |
/// It also loads any Lifetime::Ping data that might be |
| 224 |
/// persisted, in case `delay_ping_lifetime_io` is set. |
| 225 |
pub fn new( |
| 226 |
data_path: &Path, |
| 227 |
delay_ping_lifetime_io: bool, |
| 228 |
ping_lifetime_threshold: usize, |
| 229 |
ping_lifetime_max_time: Duration, |
| 230 |
) -> Result<Self> { |
| 231 |
let path = data_path.join("db"); |
| 232 |
log::debug!("Database path: {:?}", path.display()); |
| 233 |
let file_size = database_size(&path); |
| 234 |
|
| 235 |
let (rkv, rkv_load_state) = Self::open_rkv(&path)?; |
| 236 |
let user_store = rkv.open_single(Lifetime::User.as_str(), StoreOptions::create())?; |
| 237 |
let ping_store = rkv.open_single(Lifetime::Ping.as_str(), StoreOptions::create())?; |
| 238 |
let application_store = |
| 239 |
rkv.open_single(Lifetime::Application.as_str(), StoreOptions::create())?; |
| 240 |
let ping_lifetime_data = if delay_ping_lifetime_io { |
| 241 |
Some(RwLock::new(BTreeMap::new())) |
| 242 |
} else { |
| 243 |
None |
| 244 |
}; |
| 245 |
|
| 246 |
// We are gonna write, so we allocate some capacity upfront. |
| 247 |
// The value was chosen at random. |
| 248 |
let write_timings = RefCell::new(Vec::with_capacity(64)); |
| 249 |
|
| 250 |
let now = Instant::now(); |
| 251 |
|
| 252 |
let db = Self { |
| 253 |
rkv, |
| 254 |
user_store, |
| 255 |
ping_store, |
| 256 |
application_store, |
| 257 |
ping_lifetime_data, |
| 258 |
ping_lifetime_count: AtomicUsize::new(0), |
| 259 |
ping_lifetime_threshold, |
| 260 |
ping_lifetime_store_ts: Cell::new(now), |
| 261 |
ping_lifetime_max_time, |
| 262 |
file_size, |
| 263 |
rkv_load_state, |
| 264 |
write_timings, |
| 265 |
}; |
| 266 |
|
| 267 |
db.load_ping_lifetime_data(); |
| 268 |
|
| 269 |
Ok(db) |
| 270 |
} |
| 271 |
|
| 272 |
/// Get the initial database file size. |
| 273 |
pub fn file_size(&self) -> Option<NonZeroU64> { |
| 274 |
self.file_size |
| 275 |
} |
| 276 |
|
| 277 |
/// Get the rkv load state. |
| 278 |
pub fn rkv_load_state(&self) -> Option<String> { |
| 279 |
if let RkvLoadState::Err(e) = &self.rkv_load_state { |
| 280 |
Some(e.to_string()) |
| 281 |
} else { |
| 282 |
None |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
fn get_store(&self, lifetime: Lifetime) -> &SingleStore { |
| 287 |
match lifetime { |
| 288 |
Lifetime::User => &self.user_store, |
| 289 |
Lifetime::Ping => &self.ping_store, |
| 290 |
Lifetime::Application => &self.application_store, |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
/// Creates the storage directories and inits rkv. |
| 295 |
fn open_rkv(path: &Path) -> Result<(Rkv, RkvLoadState)> { |
| 296 |
fs::create_dir_all(path)?; |
| 297 |
|
| 298 |
let (rkv, load_state) = rkv_new(path)?; |
| 299 |
|
| 300 |
log::info!("Database initialized"); |
| 301 |
Ok((rkv, load_state)) |
| 302 |
} |
| 303 |
|
| 304 |
/// Build the key of the final location of the data in the database. |
| 305 |
/// Such location is built using the storage name and the metric |
| 306 |
/// key/name (if available). |
| 307 |
/// |
| 308 |
/// # Arguments |
| 309 |
/// |
| 310 |
/// * `storage_name` - the name of the storage to store/fetch data from. |
| 311 |
/// * `metric_key` - the optional metric key/name. |
| 312 |
/// |
| 313 |
/// # Returns |
| 314 |
/// |
| 315 |
/// A string representing the location in the database. |
| 316 |
fn get_storage_key(storage_name: &str, metric_key: Option<&str>) -> String { |
| 317 |
match metric_key { |
| 318 |
Some(k) => format!("{}#{}", storage_name, k), |
| 319 |
None => format!("{}#", storage_name), |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
/// Loads Lifetime::Ping data from rkv to memory, |
| 324 |
/// if `delay_ping_lifetime_io` is set to true. |
| 325 |
/// |
| 326 |
/// Does nothing if it isn't or if there is not data to load. |
| 327 |
fn load_ping_lifetime_data(&self) { |
| 328 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 329 |
let mut data = ping_lifetime_data |
| 330 |
.write() |
| 331 |
.expect("Can't read ping lifetime data"); |
| 332 |
|
| 333 |
let reader = unwrap_or!(self.rkv.read(), return); |
| 334 |
let store = self.get_store(Lifetime::Ping); |
| 335 |
let mut iter = unwrap_or!(store.iter_start(&reader), return); |
| 336 |
|
| 337 |
while let Some(Ok((metric_id, value))) = iter.next() { |
| 338 |
let metric_id = match str::from_utf8(metric_id) { |
| 339 |
Ok(metric_id) => metric_id.to_string(), |
| 340 |
_ => continue, |
| 341 |
}; |
| 342 |
let metric: Metric = match value { |
| 343 |
rkv::Value::Blob(blob) => unwrap_or!(bincode::deserialize(blob), continue), |
| 344 |
_ => continue, |
| 345 |
}; |
| 346 |
|
| 347 |
data.insert(metric_id, metric); |
| 348 |
} |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
/// Iterates with the provided transaction function |
| 353 |
/// over the requested data from the given storage. |
| 354 |
/// |
| 355 |
/// * If the storage is unavailable, the transaction function is never invoked. |
| 356 |
/// * If the read data cannot be deserialized it will be silently skipped. |
| 357 |
/// |
| 358 |
/// # Arguments |
| 359 |
/// |
| 360 |
/// * `lifetime` - The metric lifetime to iterate over. |
| 361 |
/// * `storage_name` - The storage name to iterate over. |
| 362 |
/// * `metric_key` - The metric key to iterate over. All metrics iterated over |
| 363 |
/// will have this prefix. For example, if `metric_key` is of the form `{category}.`, |
| 364 |
/// it will iterate over all metrics in the given category. If the `metric_key` is of the |
| 365 |
/// form `{category}.{name}/`, the iterator will iterate over all specific metrics for |
| 366 |
/// a given labeled metric. If not provided, the entire storage for the given lifetime |
| 367 |
/// will be iterated over. |
| 368 |
/// * `transaction_fn` - Called for each entry being iterated over. It is |
| 369 |
/// passed two arguments: `(metric_id: &[u8], metric: &Metric)`. |
| 370 |
/// |
| 371 |
/// # Panics |
| 372 |
/// |
| 373 |
/// This function will **not** panic on database errors. |
| 374 |
pub fn iter_store_from<F>( |
| 375 |
&self, |
| 376 |
lifetime: Lifetime, |
| 377 |
storage_name: &str, |
| 378 |
metric_key: Option<&str>, |
| 379 |
mut transaction_fn: F, |
| 380 |
) where |
| 381 |
F: FnMut(&[u8], &Metric), |
| 382 |
{ |
| 383 |
let iter_start = Self::get_storage_key(storage_name, metric_key); |
| 384 |
let len = iter_start.len(); |
| 385 |
|
| 386 |
// Lifetime::Ping data is not immediately persisted to disk if |
| 387 |
// Glean has `delay_ping_lifetime_io` set to true |
| 388 |
if lifetime == Lifetime::Ping { |
| 389 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 390 |
let data = ping_lifetime_data |
| 391 |
.read() |
| 392 |
.expect("Can't read ping lifetime data"); |
| 393 |
for (key, value) in data.iter() { |
| 394 |
if key.starts_with(&iter_start) { |
| 395 |
let key = &key[len..]; |
| 396 |
transaction_fn(key.as_bytes(), value); |
| 397 |
} |
| 398 |
} |
| 399 |
return; |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
let reader = unwrap_or!(self.rkv.read(), return); |
| 404 |
let mut iter = unwrap_or!( |
| 405 |
self.get_store(lifetime).iter_from(&reader, &iter_start), |
| 406 |
return |
| 407 |
); |
| 408 |
|
| 409 |
while let Some(Ok((metric_id, value))) = iter.next() { |
| 410 |
if !metric_id.starts_with(iter_start.as_bytes()) { |
| 411 |
break; |
| 412 |
} |
| 413 |
|
| 414 |
let metric_id = &metric_id[len..]; |
| 415 |
let metric: Metric = match value { |
| 416 |
rkv::Value::Blob(blob) => unwrap_or!(bincode::deserialize(blob), continue), |
| 417 |
_ => continue, |
| 418 |
}; |
| 419 |
transaction_fn(metric_id, &metric); |
| 420 |
} |
| 421 |
} |
| 422 |
|
| 423 |
/// Determines if the storage has the given metric. |
| 424 |
/// |
| 425 |
/// If data cannot be read it is assumed that the storage does not have the metric. |
| 426 |
/// |
| 427 |
/// # Arguments |
| 428 |
/// |
| 429 |
/// * `lifetime` - The lifetime of the metric. |
| 430 |
/// * `storage_name` - The storage name to look in. |
| 431 |
/// * `metric_identifier` - The metric identifier. |
| 432 |
/// |
| 433 |
/// # Panics |
| 434 |
/// |
| 435 |
/// This function will **not** panic on database errors. |
| 436 |
pub fn has_metric( |
| 437 |
&self, |
| 438 |
lifetime: Lifetime, |
| 439 |
storage_name: &str, |
| 440 |
metric_identifier: &str, |
| 441 |
) -> bool { |
| 442 |
let key = Self::get_storage_key(storage_name, Some(metric_identifier)); |
| 443 |
|
| 444 |
// Lifetime::Ping data is not persisted to disk if |
| 445 |
// Glean has `delay_ping_lifetime_io` set to true |
| 446 |
if lifetime == Lifetime::Ping { |
| 447 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 448 |
return ping_lifetime_data |
| 449 |
.read() |
| 450 |
.map(|data| data.contains_key(&key)) |
| 451 |
.unwrap_or(false); |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
let reader = unwrap_or!(self.rkv.read(), return false); |
| 456 |
self.get_store(lifetime) |
| 457 |
.get(&reader, &key) |
| 458 |
.unwrap_or(None) |
| 459 |
.is_some() |
| 460 |
} |
| 461 |
|
| 462 |
/// Writes to the specified storage with the provided transaction function. |
| 463 |
/// |
| 464 |
/// If the storage is unavailable, it will return an error. |
| 465 |
/// |
| 466 |
/// # Panics |
| 467 |
/// |
| 468 |
/// * This function will **not** panic on database errors. |
| 469 |
fn write_with_store<F>(&self, store_name: Lifetime, mut transaction_fn: F) -> Result<()> |
| 470 |
where |
| 471 |
F: FnMut(Writer, &SingleStore) -> Result<()>, |
| 472 |
{ |
| 473 |
let writer = self.rkv.write().unwrap(); |
| 474 |
let store = self.get_store(store_name); |
| 475 |
transaction_fn(writer, store) |
| 476 |
} |
| 477 |
|
| 478 |
/// Records a metric in the underlying storage system. |
| 479 |
pub fn record(&self, glean: &Glean, data: &CommonMetricDataInternal, value: &Metric) { |
| 480 |
let name = data.identifier(glean); |
| 481 |
for ping_name in data.storage_names() { |
| 482 |
if glean.is_ping_enabled(ping_name) { |
| 483 |
if let Err(e) = |
| 484 |
self.record_per_lifetime(data.inner.lifetime, ping_name, &name, value) |
| 485 |
{ |
| 486 |
log::error!( |
| 487 |
"Failed to record metric '{}' into {}: {:?}", |
| 488 |
data.base_identifier(), |
| 489 |
ping_name, |
| 490 |
e |
| 491 |
); |
| 492 |
} |
| 493 |
} |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
/// Records a metric in the underlying storage system, for a single lifetime. |
| 498 |
/// |
| 499 |
/// # Returns |
| 500 |
/// |
| 501 |
/// If the storage is unavailable or the write fails, no data will be stored and an error will be returned. |
| 502 |
/// |
| 503 |
/// Otherwise `Ok(())` is returned. |
| 504 |
/// |
| 505 |
/// # Panics |
| 506 |
/// |
| 507 |
/// This function will **not** panic on database errors. |
| 508 |
fn record_per_lifetime( |
| 509 |
&self, |
| 510 |
lifetime: Lifetime, |
| 511 |
storage_name: &str, |
| 512 |
key: &str, |
| 513 |
metric: &Metric, |
| 514 |
) -> Result<()> { |
| 515 |
let final_key = Self::get_storage_key(storage_name, Some(key)); |
| 516 |
|
| 517 |
// Lifetime::Ping data is not immediately persisted to disk if |
| 518 |
// Glean has `delay_ping_lifetime_io` set to true |
| 519 |
if lifetime == Lifetime::Ping { |
| 520 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 521 |
let mut data = ping_lifetime_data |
| 522 |
.write() |
| 523 |
.expect("Can't read ping lifetime data"); |
| 524 |
data.insert(final_key, metric.clone()); |
| 525 |
|
| 526 |
// flush ping lifetime |
| 527 |
self.persist_ping_lifetime_data_if_full(&data)?; |
| 528 |
return Ok(()); |
| 529 |
} |
| 530 |
} |
| 531 |
|
| 532 |
let encoded = bincode::serialize(&metric).expect("IMPOSSIBLE: Serializing metric failed"); |
| 533 |
let value = rkv::Value::Blob(&encoded); |
| 534 |
|
| 535 |
let mut writer = self.rkv.write()?; |
| 536 |
self.get_store(lifetime) |
| 537 |
.put(&mut writer, final_key, &value)?; |
| 538 |
measure_commit!(self, writer.commit())?; |
| 539 |
Ok(()) |
| 540 |
} |
| 541 |
|
| 542 |
/// Records the provided value, with the given lifetime, |
| 543 |
/// after applying a transformation function. |
| 544 |
pub fn record_with<F>(&self, glean: &Glean, data: &CommonMetricDataInternal, mut transform: F) |
| 545 |
where |
| 546 |
F: FnMut(Option<Metric>) -> Metric, |
| 547 |
{ |
| 548 |
let name = data.identifier(glean); |
| 549 |
for ping_name in data.storage_names() { |
| 550 |
if glean.is_ping_enabled(ping_name) { |
| 551 |
if let Err(e) = self.record_per_lifetime_with( |
| 552 |
data.inner.lifetime, |
| 553 |
ping_name, |
| 554 |
&name, |
| 555 |
&mut transform, |
| 556 |
) { |
| 557 |
log::error!( |
| 558 |
"Failed to record metric '{}' into {}: {:?}", |
| 559 |
data.base_identifier(), |
| 560 |
ping_name, |
| 561 |
e |
| 562 |
); |
| 563 |
} |
| 564 |
} |
| 565 |
} |
| 566 |
} |
| 567 |
|
| 568 |
/// Records a metric in the underlying storage system, |
| 569 |
/// after applying the given transformation function, for a single lifetime. |
| 570 |
/// |
| 571 |
/// # Returns |
| 572 |
/// |
| 573 |
/// If the storage is unavailable or the write fails, no data will be stored and an error will be returned. |
| 574 |
/// |
| 575 |
/// Otherwise `Ok(())` is returned. |
| 576 |
/// |
| 577 |
/// # Panics |
| 578 |
/// |
| 579 |
/// This function will **not** panic on database errors. |
| 580 |
fn record_per_lifetime_with<F>( |
| 581 |
&self, |
| 582 |
lifetime: Lifetime, |
| 583 |
storage_name: &str, |
| 584 |
key: &str, |
| 585 |
mut transform: F, |
| 586 |
) -> Result<()> |
| 587 |
where |
| 588 |
F: FnMut(Option<Metric>) -> Metric, |
| 589 |
{ |
| 590 |
let final_key = Self::get_storage_key(storage_name, Some(key)); |
| 591 |
|
| 592 |
// Lifetime::Ping data is not persisted to disk if |
| 593 |
// Glean has `delay_ping_lifetime_io` set to true |
| 594 |
if lifetime == Lifetime::Ping { |
| 595 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 596 |
let mut data = ping_lifetime_data |
| 597 |
.write() |
| 598 |
.expect("Can't access ping lifetime data as writable"); |
| 599 |
let entry = data.entry(final_key); |
| 600 |
match entry { |
| 601 |
Entry::Vacant(entry) => { |
| 602 |
entry.insert(transform(None)); |
| 603 |
} |
| 604 |
Entry::Occupied(mut entry) => { |
| 605 |
let old_value = entry.get().clone(); |
| 606 |
entry.insert(transform(Some(old_value))); |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
// flush ping lifetime |
| 611 |
self.persist_ping_lifetime_data_if_full(&data)?; |
| 612 |
return Ok(()); |
| 613 |
} |
| 614 |
} |
| 615 |
|
| 616 |
let mut writer = self.rkv.write()?; |
| 617 |
let store = self.get_store(lifetime); |
| 618 |
let new_value: Metric = { |
| 619 |
let old_value = store.get(&writer, &final_key)?; |
| 620 |
|
| 621 |
match old_value { |
| 622 |
Some(rkv::Value::Blob(blob)) => { |
| 623 |
let old_value = bincode::deserialize(blob).ok(); |
| 624 |
transform(old_value) |
| 625 |
} |
| 626 |
_ => transform(None), |
| 627 |
} |
| 628 |
}; |
| 629 |
|
| 630 |
let encoded = |
| 631 |
bincode::serialize(&new_value).expect("IMPOSSIBLE: Serializing metric failed"); |
| 632 |
let value = rkv::Value::Blob(&encoded); |
| 633 |
store.put(&mut writer, final_key, &value)?; |
| 634 |
measure_commit!(self, writer.commit())?; |
| 635 |
Ok(()) |
| 636 |
} |
| 637 |
|
| 638 |
/// Clears a storage (only Ping Lifetime). |
| 639 |
/// |
| 640 |
/// # Returns |
| 641 |
/// |
| 642 |
/// * If the storage is unavailable an error is returned. |
| 643 |
/// * If any individual delete fails, an error is returned, but other deletions might have |
| 644 |
/// happened. |
| 645 |
/// |
| 646 |
/// Otherwise `Ok(())` is returned. |
| 647 |
/// |
| 648 |
/// # Panics |
| 649 |
/// |
| 650 |
/// This function will **not** panic on database errors. |
| 651 |
pub fn clear_ping_lifetime_storage(&self, storage_name: &str) -> Result<()> { |
| 652 |
// Lifetime::Ping data will be saved to `ping_lifetime_data` |
| 653 |
// in case `delay_ping_lifetime_io` is set to true |
| 654 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 655 |
ping_lifetime_data |
| 656 |
.write() |
| 657 |
.expect("Can't access ping lifetime data as writable") |
| 658 |
.retain(|metric_id, _| !metric_id.starts_with(storage_name)); |
| 659 |
} |
| 660 |
|
| 661 |
self.write_with_store(Lifetime::Ping, |mut writer, store| { |
| 662 |
let mut metrics = Vec::new(); |
| 663 |
{ |
| 664 |
let mut iter = store.iter_from(&writer, storage_name)?; |
| 665 |
while let Some(Ok((metric_id, _))) = iter.next() { |
| 666 |
if let Ok(metric_id) = std::str::from_utf8(metric_id) { |
| 667 |
if !metric_id.starts_with(storage_name) { |
| 668 |
break; |
| 669 |
} |
| 670 |
metrics.push(metric_id.to_owned()); |
| 671 |
} |
| 672 |
} |
| 673 |
} |
| 674 |
|
| 675 |
let mut res = Ok(()); |
| 676 |
for to_delete in metrics { |
| 677 |
if let Err(e) = store.delete(&mut writer, to_delete) { |
| 678 |
log::warn!("Can't delete from store: {:?}", e); |
| 679 |
res = Err(e); |
| 680 |
} |
| 681 |
} |
| 682 |
|
| 683 |
measure_commit!(self, writer.commit())?; |
| 684 |
Ok(res?) |
| 685 |
}) |
| 686 |
} |
| 687 |
|
| 688 |
pub fn clear_lifetime_storage(&self, lifetime: Lifetime, storage_name: &str) -> Result<()> { |
| 689 |
self.write_with_store(lifetime, |mut writer, store| { |
| 690 |
let mut metrics = Vec::new(); |
| 691 |
{ |
| 692 |
let mut iter = store.iter_from(&writer, storage_name)?; |
| 693 |
while let Some(Ok((metric_id, _))) = iter.next() { |
| 694 |
if let Ok(metric_id) = std::str::from_utf8(metric_id) { |
| 695 |
if !metric_id.starts_with(storage_name) { |
| 696 |
break; |
| 697 |
} |
| 698 |
metrics.push(metric_id.to_owned()); |
| 699 |
} |
| 700 |
} |
| 701 |
} |
| 702 |
|
| 703 |
let mut res = Ok(()); |
| 704 |
for to_delete in metrics { |
| 705 |
if let Err(e) = store.delete(&mut writer, to_delete) { |
| 706 |
log::warn!("Can't delete from store: {:?}", e); |
| 707 |
res = Err(e); |
| 708 |
} |
| 709 |
} |
| 710 |
|
| 711 |
measure_commit!(self, writer.commit())?; |
| 712 |
Ok(res?) |
| 713 |
}) |
| 714 |
} |
| 715 |
|
| 716 |
/// Removes a single metric from the storage. |
| 717 |
/// |
| 718 |
/// # Arguments |
| 719 |
/// |
| 720 |
/// * `lifetime` - the lifetime of the storage in which to look for the metric. |
| 721 |
/// * `storage_name` - the name of the storage to store/fetch data from. |
| 722 |
/// * `metric_id` - the metric category + name. |
| 723 |
/// |
| 724 |
/// # Returns |
| 725 |
/// |
| 726 |
/// * If the storage is unavailable an error is returned. |
| 727 |
/// * If the metric could not be deleted, an error is returned. |
| 728 |
/// |
| 729 |
/// Otherwise `Ok(())` is returned. |
| 730 |
/// |
| 731 |
/// # Panics |
| 732 |
/// |
| 733 |
/// This function will **not** panic on database errors. |
| 734 |
pub fn remove_single_metric( |
| 735 |
&self, |
| 736 |
lifetime: Lifetime, |
| 737 |
storage_name: &str, |
| 738 |
metric_id: &str, |
| 739 |
) -> Result<()> { |
| 740 |
let final_key = Self::get_storage_key(storage_name, Some(metric_id)); |
| 741 |
|
| 742 |
// Lifetime::Ping data is not persisted to disk if |
| 743 |
// Glean has `delay_ping_lifetime_io` set to true |
| 744 |
if lifetime == Lifetime::Ping { |
| 745 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 746 |
let mut data = ping_lifetime_data |
| 747 |
.write() |
| 748 |
.expect("Can't access app lifetime data as writable"); |
| 749 |
data.remove(&final_key); |
| 750 |
} |
| 751 |
} |
| 752 |
|
| 753 |
self.write_with_store(lifetime, |mut writer, store| { |
| 754 |
if let Err(e) = store.delete(&mut writer, final_key.clone()) { |
| 755 |
if self.ping_lifetime_data.is_some() { |
| 756 |
// If ping_lifetime_data exists, it might be |
| 757 |
// that data is in memory, but not yet in rkv. |
| 758 |
return Ok(()); |
| 759 |
} |
| 760 |
return Err(e.into()); |
| 761 |
} |
| 762 |
measure_commit!(self, writer.commit())?; |
| 763 |
Ok(()) |
| 764 |
}) |
| 765 |
} |
| 766 |
|
| 767 |
/// Clears all the metrics in the database, for the provided lifetime. |
| 768 |
/// |
| 769 |
/// Errors are logged. |
| 770 |
/// |
| 771 |
/// # Panics |
| 772 |
/// |
| 773 |
/// * This function will **not** panic on database errors. |
| 774 |
pub fn clear_lifetime(&self, lifetime: Lifetime) { |
| 775 |
let res = self.write_with_store(lifetime, |mut writer, store| { |
| 776 |
store.clear(&mut writer)?; |
| 777 |
measure_commit!(self, writer.commit())?; |
| 778 |
Ok(()) |
| 779 |
}); |
| 780 |
|
| 781 |
if let Err(e) = res { |
| 782 |
// We try to clear everything. |
| 783 |
// If there was no data to begin with we encounter a `NotFound` error. |
| 784 |
// There's no point in logging that. |
| 785 |
if let ErrorKind::Rkv(StoreError::IoError(ioerr)) = e.kind() { |
| 786 |
if let io::ErrorKind::NotFound = ioerr.kind() { |
| 787 |
log::debug!( |
| 788 |
"Could not clear store for lifetime {:?}: {:?}", |
| 789 |
lifetime, |
| 790 |
ioerr |
| 791 |
); |
| 792 |
return; |
| 793 |
} |
| 794 |
} |
| 795 |
|
| 796 |
log::warn!("Could not clear store for lifetime {:?}: {:?}", lifetime, e); |
| 797 |
} |
| 798 |
} |
| 799 |
|
| 800 |
/// Clears all metrics in the database. |
| 801 |
/// |
| 802 |
/// Errors are logged. |
| 803 |
/// |
| 804 |
/// # Panics |
| 805 |
/// |
| 806 |
/// * This function will **not** panic on database errors. |
| 807 |
pub fn clear_all(&self) { |
| 808 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 809 |
ping_lifetime_data |
| 810 |
.write() |
| 811 |
.expect("Can't access ping lifetime data as writable") |
| 812 |
.clear(); |
| 813 |
} |
| 814 |
|
| 815 |
for lifetime in [Lifetime::User, Lifetime::Ping, Lifetime::Application].iter() { |
| 816 |
self.clear_lifetime(*lifetime); |
| 817 |
} |
| 818 |
} |
| 819 |
|
| 820 |
/// Persists ping_lifetime_data to disk. |
| 821 |
/// |
| 822 |
/// Does nothing in case there is nothing to persist. |
| 823 |
/// |
| 824 |
/// # Panics |
| 825 |
/// |
| 826 |
/// * This function will **not** panic on database errors. |
| 827 |
pub fn persist_ping_lifetime_data(&self) -> Result<()> { |
| 828 |
if let Some(ping_lifetime_data) = &self.ping_lifetime_data { |
| 829 |
let data = ping_lifetime_data |
| 830 |
.read() |
| 831 |
.expect("Can't read ping lifetime data"); |
| 832 |
|
| 833 |
// We can reset the write-counter. Current data has been persisted. |
| 834 |
self.ping_lifetime_count.store(0, Ordering::Release); |
| 835 |
self.ping_lifetime_store_ts.replace(Instant::now()); |
| 836 |
|
| 837 |
self.write_with_store(Lifetime::Ping, |mut writer, store| { |
| 838 |
for (key, value) in data.iter() { |
| 839 |
let encoded = |
| 840 |
bincode::serialize(&value).expect("IMPOSSIBLE: Serializing metric failed"); |
| 841 |
// There is no need for `get_storage_key` here because |
| 842 |
// the key is already formatted from when it was saved |
| 843 |
// to ping_lifetime_data. |
| 844 |
store.put(&mut writer, key, &rkv::Value::Blob(&encoded))?; |
| 845 |
} |
| 846 |
measure_commit!(self, writer.commit())?; |
| 847 |
Ok(()) |
| 848 |
})?; |
| 849 |
} |
| 850 |
Ok(()) |
| 851 |
} |
| 852 |
|
| 853 |
pub fn persist_ping_lifetime_data_if_full( |
| 854 |
&self, |
| 855 |
data: &BTreeMap<String, Metric>, |
| 856 |
) -> Result<()> { |
| 857 |
if self.ping_lifetime_threshold == 0 && self.ping_lifetime_max_time.is_zero() { |
| 858 |
return Ok(()); |
| 859 |
} |
| 860 |
|
| 861 |
let write_count = self.ping_lifetime_count.fetch_add(1, Ordering::Release) + 1; |
| 862 |
let last_write = self.ping_lifetime_store_ts.get(); |
| 863 |
let elapsed = last_write.elapsed(); |
| 864 |
|
| 865 |
if (self.ping_lifetime_threshold == 0 || write_count < self.ping_lifetime_threshold) |
| 866 |
&& (self.ping_lifetime_max_time.is_zero() || elapsed < self.ping_lifetime_max_time) |
| 867 |
{ |
| 868 |
log::trace!( |
| 869 |
"Not flushing. write_count={} (threshold={}), elapsed={:?} (max={:?})", |
| 870 |
write_count, |
| 871 |
self.ping_lifetime_threshold, |
| 872 |
elapsed, |
| 873 |
self.ping_lifetime_max_time |
| 874 |
); |
| 875 |
return Ok(()); |
| 876 |
} |
| 877 |
|
| 878 |
if self.ping_lifetime_threshold > 0 && write_count >= self.ping_lifetime_threshold { |
| 879 |
log::debug!( |
| 880 |
"Flushing database due to threshold of {} reached.", |
| 881 |
self.ping_lifetime_threshold |
| 882 |
) |
| 883 |
} else if !self.ping_lifetime_max_time.is_zero() && elapsed >= self.ping_lifetime_max_time { |
| 884 |
log::debug!( |
| 885 |
"Flushing database due to last write more than {:?} ago", |
| 886 |
self.ping_lifetime_max_time |
| 887 |
); |
| 888 |
} |
| 889 |
|
| 890 |
self.ping_lifetime_count.store(0, Ordering::Release); |
| 891 |
self.ping_lifetime_store_ts.replace(Instant::now()); |
| 892 |
self.write_with_store(Lifetime::Ping, |mut writer, store| { |
| 893 |
for (key, value) in data.iter() { |
| 894 |
let encoded = |
| 895 |
bincode::serialize(&value).expect("IMPOSSIBLE: Serializing metric failed"); |
| 896 |
// There is no need for `get_storage_key` here because |
| 897 |
// the key is already formatted from when it was saved |
| 898 |
// to ping_lifetime_data. |
| 899 |
store.put(&mut writer, key, &rkv::Value::Blob(&encoded))?; |
| 900 |
} |
| 901 |
writer.commit()?; |
| 902 |
Ok(()) |
| 903 |
}) |
| 904 |
} |
| 905 |
} |
| 906 |
|
| 907 |
#[cfg(test)] |
| 908 |
mod test { |
| 909 |
use super::*; |
| 910 |
use crate::tests::new_glean; |
| 911 |
use std::collections::HashMap; |
| 912 |
use tempfile::tempdir; |
| 913 |
|
| 914 |
#[test] |
| 915 |
fn test_panicks_if_fails_dir_creation() { |
| 916 |
let path = Path::new("/!#\"'@#°ç"); |
| 917 |
assert!(Database::new(path, false, 0, Duration::ZERO).is_err()); |
| 918 |
} |
| 919 |
|
| 920 |
#[test] |
| 921 |
#[cfg(windows)] |
| 922 |
fn windows_invalid_utf16_panicfree() { |
| 923 |
use std::ffi::OsString; |
| 924 |
use std::os::windows::prelude::*; |
| 925 |
|
| 926 |
// Here the values 0x0066 and 0x006f correspond to 'f' and 'o' |
| 927 |
// respectively. The value 0xD800 is a lone surrogate half, invalid |
| 928 |
// in a UTF-16 sequence. |
| 929 |
let source = [0x0066, 0x006f, 0xD800, 0x006f]; |
| 930 |
let os_string = OsString::from_wide(&source[..]); |
| 931 |
let os_str = os_string.as_os_str(); |
| 932 |
let dir = tempdir().unwrap(); |
| 933 |
let path = dir.path().join(os_str); |
| 934 |
|
| 935 |
let res = Database::new(&path, false, 0, Duration::ZERO); |
| 936 |
|
| 937 |
assert!( |
| 938 |
res.is_ok(), |
| 939 |
"Database should succeed at {}: {:?}", |
| 940 |
path.display(), |
| 941 |
res |
| 942 |
); |
| 943 |
} |
| 944 |
|
| 945 |
#[test] |
| 946 |
#[cfg(target_os = "linux")] |
| 947 |
fn linux_invalid_utf8_panicfree() { |
| 948 |
use std::ffi::OsStr; |
| 949 |
use std::os::unix::ffi::OsStrExt; |
| 950 |
|
| 951 |
// Here, the values 0x66 and 0x6f correspond to 'f' and 'o' |
| 952 |
// respectively. The value 0x80 is a lone continuation byte, invalid |
| 953 |
// in a UTF-8 sequence. |
| 954 |
let source = [0x66, 0x6f, 0x80, 0x6f]; |
| 955 |
let os_str = OsStr::from_bytes(&source[..]); |
| 956 |
let dir = tempdir().unwrap(); |
| 957 |
let path = dir.path().join(os_str); |
| 958 |
|
| 959 |
let res = Database::new(&path, false, 0, Duration::ZERO); |
| 960 |
assert!( |
| 961 |
res.is_ok(), |
| 962 |
"Database should not fail at {}: {:?}", |
| 963 |
path.display(), |
| 964 |
res |
| 965 |
); |
| 966 |
} |
| 967 |
|
| 968 |
#[test] |
| 969 |
#[cfg(target_os = "macos")] |
| 970 |
fn macos_invalid_utf8_panicfree() { |
| 971 |
use std::ffi::OsStr; |
| 972 |
use std::os::unix::ffi::OsStrExt; |
| 973 |
|
| 974 |
// Here, the values 0x66 and 0x6f correspond to 'f' and 'o' |
| 975 |
// respectively. The value 0x80 is a lone continuation byte, invalid |
| 976 |
// in a UTF-8 sequence. |
| 977 |
let source = [0x66, 0x6f, 0x80, 0x6f]; |
| 978 |
let os_str = OsStr::from_bytes(&source[..]); |
| 979 |
let dir = tempdir().unwrap(); |
| 980 |
let path = dir.path().join(os_str); |
| 981 |
|
| 982 |
let res = Database::new(&path, false, 0, Duration::ZERO); |
| 983 |
assert!( |
| 984 |
res.is_err(), |
| 985 |
"Database should not fail at {}: {:?}", |
| 986 |
path.display(), |
| 987 |
res |
| 988 |
); |
| 989 |
} |
| 990 |
|
| 991 |
#[test] |
| 992 |
fn test_data_dir_rkv_inits() { |
| 993 |
let dir = tempdir().unwrap(); |
| 994 |
Database::new(dir.path(), false, 0, Duration::ZERO).unwrap(); |
| 995 |
|
| 996 |
assert!(dir.path().exists()); |
| 997 |
} |
| 998 |
|
| 999 |
#[test] |
| 1000 |
fn test_ping_lifetime_metric_recorded() { |
| 1001 |
// Init the database in a temporary directory. |
| 1002 |
let dir = tempdir().unwrap(); |
| 1003 |
let db = Database::new(dir.path(), false, 0, Duration::ZERO).unwrap(); |
| 1004 |
|
| 1005 |
assert!(db.ping_lifetime_data.is_none()); |
| 1006 |
|
| 1007 |
// Attempt to record a known value. |
| 1008 |
let test_value = "test-value"; |
| 1009 |
let test_storage = "test-storage"; |
| 1010 |
let test_metric_id = "telemetry_test.test_name"; |
| 1011 |
db.record_per_lifetime( |
| 1012 |
Lifetime::Ping, |
| 1013 |
test_storage, |
| 1014 |
test_metric_id, |
| 1015 |
&Metric::String(test_value.to_string()), |
| 1016 |
) |
| 1017 |
.unwrap(); |
| 1018 |
|
| 1019 |
// Verify that the data is correctly recorded. |
| 1020 |
let mut found_metrics = 0; |
| 1021 |
let mut snapshotter = |metric_id: &[u8], metric: &Metric| { |
| 1022 |
found_metrics += 1; |
| 1023 |
let metric_id = String::from_utf8_lossy(metric_id).into_owned(); |
| 1024 |
assert_eq!(test_metric_id, metric_id); |
| 1025 |
match metric { |
| 1026 |
Metric::String(s) => assert_eq!(test_value, s), |
| 1027 |
_ => panic!("Unexpected data found"), |
| 1028 |
} |
| 1029 |
}; |
| 1030 |
|
| 1031 |
db.iter_store_from(Lifetime::Ping, test_storage, None, &mut snapshotter); |
| 1032 |
assert_eq!(1, found_metrics, "We only expect 1 Lifetime.Ping metric."); |
| 1033 |
} |
| 1034 |
|
| 1035 |
#[test] |
| 1036 |
fn test_application_lifetime_metric_recorded() { |
| 1037 |
// Init the database in a temporary directory. |
| 1038 |
let dir = tempdir().unwrap(); |
| 1039 |
let db = Database::new(dir.path(), false, 0, Duration::ZERO).unwrap(); |
| 1040 |
|
| 1041 |
// Attempt to record a known value. |
| 1042 |
let test_value = "test-value"; |
| 1043 |
let test_storage = "test-storage1"; |
| 1044 |
let test_metric_id = "telemetry_test.test_name"; |
| 1045 |
db.record_per_lifetime( |
| 1046 |
Lifetime::Application, |
| 1047 |
test_storage, |
| 1048 |
test_metric_id, |
| 1049 |
&Metric::String(test_value.to_string()), |
| 1050 |
) |
| 1051 |
.unwrap(); |
| 1052 |
|
| 1053 |
// Verify that the data is correctly recorded. |
| 1054 |
let mut found_metrics = 0; |
| 1055 |
let mut snapshotter = |metric_id: &[u8], metric: &Metric| { |
| 1056 |
found_metrics += 1; |
| 1057 |
let metric_id = String::from_utf8_lossy(metric_id).into_owned(); |
| 1058 |
assert_eq!(test_metric_id, metric_id); |
| 1059 |
match metric { |
| 1060 |
Metric::String(s) => assert_eq!(test_value, s), |
| 1061 |
_ => panic!("Unexpected data found"), |
| 1062 |
} |
| 1063 |
}; |
| 1064 |
|
| 1065 |
db.iter_store_from(Lifetime::Application, test_storage, None, &mut snapshotter); |
| 1066 |
assert_eq!( |
| 1067 |
1, found_metrics, |
| 1068 |
"We only expect 1 Lifetime.Application metric." |
| 1069 |
); |
| 1070 |
} |
| 1071 |
|
| 1072 |
#[test] |
| 1073 |
fn test_user_lifetime_metric_recorded() { |
| 1074 |
// Init the database in a temporary directory. |
| 1075 |
let dir = tempdir().unwrap(); |
| 1076 |
let db = Database::new(dir.path(), false, 0, Duration::ZERO).unwrap(); |
| 1077 |
|
| 1078 |
// Attempt to record a known value. |
| 1079 |
let test_value = "test-value"; |
| 1080 |
let test_storage = "test-storage2"; |
| 1081 |
let test_metric_id = "telemetry_test.test_name"; |
| 1082 |
db.record_per_lifetime( |
| 1083 |
Lifetime::User, |
| 1084 |
test_storage, |
| 1085 |
test_metric_id, |
| 1086 |
&Metric::String(test_value.to_string()), |
| 1087 |
) |
| 1088 |
.unwrap(); |
| 1089 |
|
| 1090 |
// Verify that the data is correctly recorded. |
| 1091 |
let mut found_metrics = 0; |
| 1092 |
let mut snapshotter = |metric_id: &[u8], metric: &Metric| { |
| 1093 |
found_metrics += 1; |
| 1094 |
let metric_id = String::from_utf8_lossy(metric_id).into_owned(); |
| 1095 |
assert_eq!(test_metric_id, metric_id); |
| 1096 |
match metric { |
| 1097 |
Metric::String(s) => assert_eq!(test_value, s), |
| 1098 |
_ => panic!("Unexpected data found"), |
| 1099 |
} |
| 1100 |
}; |
| 1101 |
|
| 1102 |
db.iter_store_from(Lifetime::User, test_storage, None, &mut snapshotter); |
| 1103 |
assert_eq!(1, found_metrics, "We only expect 1 Lifetime.User metric."); |
| 1104 |
} |
| 1105 |
|
| 1106 |
#[test] |
| 1107 |
fn test_clear_ping_storage() { |
| 1108 |
// Init the database in a temporary directory. |
| 1109 |
let dir = tempdir().unwrap(); |
| 1110 |
let db = Database::new(dir.path(), false, 0, Duration::ZERO).unwrap(); |
| 1111 |
|
| 1112 |
// Attempt to record a known value for every single lifetime. |
| 1113 |
let test_storage = "test-storage"; |
| 1114 |
db.record_per_lifetime( |
| 1115 |
Lifetime::User, |
| 1116 |
test_storage, |
| 1117 |
"telemetry_test.test_name_user", |
| 1118 |
&Metric::String("test-value-user".to_string()), |
| 1119 |
) |
| 1120 |
.unwrap(); |
| 1121 |
db.record_per_lifetime( |
| 1122 |
Lifetime::Ping, |
| 1123 |
test_storage, |
| 1124 |
"telemetry_test.test_name_ping", |
| 1125 |
&Metric::String("test-value-ping".to_string()), |
| 1126 |
) |
| 1127 |
.unwrap(); |
| 1128 |
db.record_per_lifetime( |
| 1129 |
Lifetime::Application, |
| 1130 |
test_storage, |
| 1131 |
"telemetry_test.test_name_application", |
| 1132 |
&Metric::String("test-value-application".to_string()), |
| 1133 |
) |
| 1134 |
.unwrap(); |
| 1135 |
|
| 1136 |
// Take a snapshot for the data, all the lifetimes. |
| 1137 |
{ |
| 1138 |
let mut snapshot: HashMap<String, String> = HashMap::new(); |
| 1139 |
let mut snapshotter = |metric_id: &[u8], metric: &Metric| { |
| 1140 |
let metric_id = String::from_utf8_lossy(metric_id).into_owned(); |
| 1141 |
match metric { |
| 1142 |
Metric::String(s) => snapshot.insert(metric_id, s.to_string()), |
| 1143 |
_ => panic!("Unexpected data found"), |
| 1144 |
}; |
| 1145 |
}; |
| 1146 |
|
| 1147 |
db.iter_store_from(Lifetime::User, test_storage, None, &mut snapshotter); |
| 1148 |
db.iter_store_from(Lifetime::Ping, test_storage, None, &mut snapshotter); |
| 1149 |
db.iter_store_from(Lifetime::Application, test_storage, None, &mut snapshotter); |
| 1150 |
|
| 1151 |
assert_eq!(3, snapshot.len(), "We expect all lifetimes to be present."); |
| 1152 |
assert!(snapshot.contains_key("telemetry_test.test_name_user")); |
| 1153 |
assert!(snapshot.contains_key("telemetry_test.test_name_ping")); |
| 1154 |
assert!(snapshot.contains_key("telemetry_test.test_name_application")); |
| 1155 |
} |
| 1156 |
|
| 1157 |
// Clear the Ping lifetime. |
| 1158 |
db.clear_ping_lifetime_storage(test_storage).unwrap(); |
| 1159 |
|
| 1160 |
// Take a snapshot again and check that we're only clearing the Ping lifetime. |
| 1161 |
{ |
| 1162 |
let mut snapshot: HashMap<String, String> = HashMap::new(); |
| 1163 |
let mut snapshotter = |metric_id: &[u8], metric: &Metric| { |
| 1164 |
let metric_id = String::from_utf8_lossy(metric_id).into_owned(); |
| 1165 |
match metric { |
| 1166 |
Metric::String(s) => snapshot.insert(metric_id, s.to_string()), |
| 1167 |
_ => panic!("Unexpected data found"), |
| 1168 |
}; |
| 1169 |
}; |
| 1170 |
|
| 1171 |
db.iter_store_from(Lifetime::User, test_storage, None, &mut snapshotter); |
| 1172 |
db.iter_store_from(Lifetime::Ping, test_storage, None, &mut snapshotter); |
| 1173 |
db.iter_store_from(Lifetime::Application, test_storage, None, &mut snapshotter); |
| 1174 |
|
| 1175 |
assert_eq!(2, snapshot.len(), "We only expect 2 metrics to be left."); |
| 1176 |
assert!(snapshot.contains_key("telemetry_test.test_name_user")); |
| 1177 |
assert!(snapshot.contains_key("telemetry_test.test_name_application")); |
| 1178 |
} |
| 1179 |
} |
| 1180 |
|
| 1181 |
#[test] |
| 1182 |
fn test_remove_single_metric() { |
| 1183 |
// Init the database in a temporary directory. |
| 1184 |
let dir = tempdir().unwrap(); |
| 1185 |
let db = Database::new(dir.path(), false, 0, Duration::ZERO).unwrap(); |
| 1186 |
|
| 1187 |
let test_storage = "test-storage-single-lifetime"; |
| 1188 |
let metric_id_pattern = "telemetry_test.single_metric"; |
| 1189 |
|
| 1190 |
// Write sample metrics to the database. |
| 1191 |
let lifetimes = [Lifetime::User, Lifetime::Ping, Lifetime::Application]; |
| 1192 |
|
| 1193 |
for lifetime in lifetimes.iter() { |
| 1194 |
for value in &["retain", "delete"] { |
| 1195 |
db.record_per_lifetime( |
| 1196 |
*lifetime, |
| 1197 |
test_storage, |
| 1198 |
&format!("{}_{}", metric_id_pattern, value), |
| 1199 |
&Metric::String((*value).to_string()), |
| 1200 |
) |
| 1201 |
.unwrap(); |
| 1202 |
} |
| 1203 |
} |
| 1204 |
|
| 1205 |
// Remove "telemetry_test.single_metric_delete" from each lifetime. |
| 1206 |
for lifetime in lifetimes.iter() { |
| 1207 |
db.remove_single_metric( |
| 1208 |
*lifetime, |
| 1209 |
test_storage, |
| 1210 |
&format!("{}_delete", metric_id_pattern), |
| 1211 |
) |
| 1212 |
.unwrap(); |
| 1213 |
} |
| 1214 |
|
| 1215 |
// Verify that "telemetry_test.single_metric_retain" is still around for all lifetimes. |
| 1216 |
for lifetime in lifetimes.iter() { |
| 1217 |
let mut found_metrics = 0; |
| 1218 |
let mut snapshotter = |metric_id: &[u8], metric: &Metric| { |
| 1219 |
found_metrics += 1; |
| 1220 |
let metric_id = String::from_utf8_lossy(metric_id).into_owned(); |
| 1221 |
assert_eq!(format!("{}_retain", metric_id_pattern), metric_id); |
| 1222 |
match metric { |
| 1223 |
Metric::String(s) => assert_eq!("retain", s), |
| 1224 |
_ => panic!("Unexpected data found"), |
| 1225 |
} |
| 1226 |
}; |
| 1227 |
|
| 1228 |
// Check the User lifetime. |
| 1229 |
db.iter_store_from(*lifetime, test_storage, None, &mut snapshotter); |
| 1230 |
assert_eq!( |
| 1231 |
1, found_metrics, |
| 1232 |
"We only expect 1 metric for this lifetime." |
| 1233 |
); |
| 1234 |
} |
| 1235 |
} |
| 1236 |
|
| 1237 |
#[test] |
| 1238 |
fn test_delayed_ping_lifetime_persistence() { |
| 1239 |
// Init the database in a temporary directory. |
| 1240 |
let dir = tempdir().unwrap(); |
| 1241 |
let db = Database::new(dir.path(), true, 0, Duration::ZERO).unwrap(); |
| 1242 |
let test_storage = "test-storage"; |
| 1243 |
|
| 1244 |
assert!(db.ping_lifetime_data.is_some()); |
| 1245 |
|
| 1246 |
// Attempt to record a known value. |
| 1247 |
let test_value1 = "test-value1"; |
| 1248 |
let test_metric_id1 = "telemetry_test.test_name1"; |
| 1249 |
db.record_per_lifetime( |
| 1250 |
Lifetime::Ping, |
| 1251 |
test_storage, |
| 1252 |
test_metric_id1, |
| 1253 |
&Metric::String(test_value1.to_string()), |
| 1254 |
) |
| 1255 |
.unwrap(); |
| 1256 |
|
| 1257 |
// Attempt to persist data. |
| 1258 |
db.persist_ping_lifetime_data().unwrap(); |
| 1259 |
|
| 1260 |
// Attempt to record another known value. |
| 1261 |
let test_value2 = "test-value2"; |
| 1262 |
let test_metric_id2 = "telemetry_test.test_name2"; |
| 1263 |
db.record_per_lifetime( |
| 1264 |
Lifetime::Ping, |
| 1265 |
test_storage, |
| 1266 |
test_metric_id2, |
| 1267 |
&Metric::String(test_value2.to_string()), |
| 1268 |
) |
| 1269 |
.unwrap(); |
| 1270 |
|
| 1271 |
{ |
| 1272 |
// At this stage we expect `test_value1` to be persisted and in memory, |
| 1273 |
// since it was recorded before calling `persist_ping_lifetime_data`, |
| 1274 |
// and `test_value2` to be only in memory, since it was recorded after. |
| 1275 |
let store: SingleStore = db |
| 1276 |
.rkv |
| 1277 |
.open_single(Lifetime::Ping.as_str(), StoreOptions::create()) |
| 1278 |
.unwrap(); |
| 1279 |
let reader = db.rkv.read().unwrap(); |
| 1280 |
|
| 1281 |
// Verify that test_value1 is in rkv. |
| 1282 |
assert!(store |
| 1283 |
.get(&reader, format!("{}#{}", test_storage, test_metric_id1)) |
| 1284 |
.unwrap_or(None) |
| 1285 |
.is_some()); |
| 1286 |
// Verifiy that test_value2 is **not** in rkv. |
| 1287 |
assert!(store |
| 1288 |
.get(&reader, format!("{}#{}", test_storage, test_metric_id2)) |
| 1289 |
.unwrap_or(None) |
| 1290 |
.is_none()); |
| 1291 |
|
| 1292 |
let data = match &db.ping_lifetime_data { |
| 1293 |
Some(ping_lifetime_data) => ping_lifetime_data, |
| 1294 |
None => panic!("Expected `ping_lifetime_data` to exist here!"), |
| 1295 |
}; |
| 1296 |
let data = data.read().unwrap(); |
| 1297 |
// Verify that test_value1 is also in memory. |
| 1298 |
assert!(data |
| 1299 |
.get(&format!("{}#{}", test_storage, test_metric_id1)) |
| 1300 |
.is_some()); |
| 1301 |
// Verify that test_value2 is in memory. |
| 1302 |
assert!(data |
| 1303 |
.get(&format!("{}#{}", test_storage, test_metric_id2)) |
| 1304 |
.is_some()); |
| 1305 |
} |
| 1306 |
|
| 1307 |
// Attempt to persist data again. |
| 1308 |
db.persist_ping_lifetime_data().unwrap(); |
| 1309 |
|
| 1310 |
{ |
| 1311 |
// At this stage we expect `test_value1` and `test_value2` to |
| 1312 |
// be persisted, since both were created before a call to |
| 1313 |
// `persist_ping_lifetime_data`. |
| 1314 |
let store: SingleStore = db |
| 1315 |
.rkv |
| 1316 |
.open_single(Lifetime::Ping.as_str(), StoreOptions::create()) |
| 1317 |
.unwrap(); |
| 1318 |
let reader = db.rkv.read().unwrap(); |
| 1319 |
|
| 1320 |
// Verify that test_value1 is in rkv. |
| 1321 |
assert!(store |
| 1322 |
.get(&reader, format!("{}#{}", test_storage, test_metric_id1)) |
| 1323 |
.unwrap_or(None) |
| 1324 |
.is_some()); |
| 1325 |
// Verifiy that test_value2 is also in rkv. |
| 1326 |
assert!(store |
| 1327 |
.get(&reader, format!("{}#{}", test_storage, test_metric_id2)) |
| 1328 |
.unwrap_or(None) |
| 1329 |
.is_some()); |
| 1330 |
|
| 1331 |
let data = match &db.ping_lifetime_data { |
| 1332 |
Some(ping_lifetime_data) => ping_lifetime_data, |
| 1333 |
None => panic!("Expected `ping_lifetime_data` to exist here!"), |
| 1334 |
}; |
| 1335 |
let data = data.read().unwrap(); |
| 1336 |
// Verify that test_value1 is also in memory. |
| 1337 |
assert!(data |
| 1338 |
.get(&format!("{}#{}", test_storage, test_metric_id1)) |
| 1339 |
.is_some()); |
| 1340 |
// Verify that test_value2 is also in memory. |
| 1341 |
assert!(data |
| 1342 |
.get(&format!("{}#{}", test_storage, test_metric_id2)) |
| 1343 |
.is_some()); |
| 1344 |
} |
| 1345 |
} |
| 1346 |
|
| 1347 |
#[test] |
| 1348 |
fn test_load_ping_lifetime_data_from_memory() { |
| 1349 |
// Init the database in a temporary directory. |
| 1350 |
let dir = tempdir().unwrap(); |
| 1351 |
|
| 1352 |
let test_storage = "test-storage"; |
| 1353 |
let test_value = "test-value"; |
| 1354 |
let test_metric_id = "telemetry_test.test_name"; |
| 1355 |
|
| 1356 |
{ |
| 1357 |
let db = Database::new(dir.path(), true, 0, Duration::ZERO).unwrap(); |
| 1358 |
|
| 1359 |
// Attempt to record a known value. |
| 1360 |
db.record_per_lifetime( |
| 1361 |
Lifetime::Ping, |
| 1362 |
test_storage, |
| 1363 |
test_metric_id, |
| 1364 |
&Metric::String(test_value.to_string()), |
| 1365 |
) |
| 1366 |
.unwrap(); |
| 1367 |
|
| 1368 |
// Verify that test_value is in memory. |
| 1369 |
let data = match &db.ping_lifetime_data { |
| 1370 |
Some(ping_lifetime_data) => ping_lifetime_data, |
| 1371 |
None => panic!("Expected `ping_lifetime_data` to exist here!"), |
| 1372 |
}; |
| 1373 |
let data = data.read().unwrap(); |
| 1374 |
assert!(data |
| 1375 |
.get(&format!("{}#{}", test_storage, test_metric_id)) |
| 1376 |
.is_some()); |
| 1377 |
|
| 1378 |
// Attempt to persist data. |
| 1379 |
db.persist_ping_lifetime_data().unwrap(); |
| 1380 |
|
| 1381 |
// Verify that test_value is now in rkv. |
| 1382 |
let store: SingleStore = db |
| 1383 |
.rkv |
| 1384 |
.open_single(Lifetime::Ping.as_str(), StoreOptions::create()) |
| 1385 |
.unwrap(); |
| 1386 |
let reader = db.rkv.read().unwrap(); |
| 1387 |
assert!(store |
| 1388 |
.get(&reader, format!("{}#{}", test_storage, test_metric_id)) |
| 1389 |
.unwrap_or(None) |
| 1390 |
.is_some()); |
| 1391 |
} |
| 1392 |
|
| 1393 |
// Now create a new instace of the db and check if data was |
| 1394 |
// correctly loaded from rkv to memory. |
| 1395 |
{ |
| 1396 |
let db = Database::new(dir.path(), true, 0, Duration::ZERO).unwrap(); |
| 1397 |
|
| 1398 |
// Verify that test_value is in memory. |
| 1399 |
let data = match &db.ping_lifetime_data { |
| 1400 |
Some(ping_lifetime_data) => ping_lifetime_data, |
| 1401 |
None => panic!("Expected `ping_lifetime_data` to exist here!"), |
| 1402 |
}; |
| 1403 |
let data = data.read().unwrap(); |
| 1404 |
assert!(data |
| 1405 |
.get(&format!("{}#{}", test_storage, test_metric_id)) |
| 1406 |
.is_some()); |
| 1407 |
|
| 1408 |
// Verify that test_value is also in rkv. |
| 1409 |
let store: SingleStore = db |
| 1410 |
.rkv |
| 1411 |
.open_single(Lifetime::Ping.as_str(), StoreOptions::create()) |
| 1412 |
.unwrap(); |
| 1413 |
let reader = db.rkv.read().unwrap(); |
| 1414 |
assert!(store |
| 1415 |
.get(&reader, format!("{}#{}", test_storage, test_metric_id)) |
| 1416 |
.unwrap_or(None) |
| 1417 |
.is_some()); |
| 1418 |
} |
| 1419 |
} |
| 1420 |
|
| 1421 |
#[test] |
| 1422 |
fn test_delayed_ping_lifetime_clear() { |
| 1423 |
// Init the database in a temporary directory. |
| 1424 |
let dir = tempdir().unwrap(); |
| 1425 |
let db = Database::new(dir.path(), true, 0, Duration::ZERO).unwrap(); |
| 1426 |
let test_storage = "test-storage"; |
| 1427 |
|
| 1428 |
assert!(db.ping_lifetime_data.is_some()); |
| 1429 |
|
| 1430 |
// Attempt to record a known value. |
| 1431 |
let test_value1 = "test-value1"; |
| 1432 |
let test_metric_id1 = "telemetry_test.test_name1"; |
| 1433 |
db.record_per_lifetime( |
| 1434 |
Lifetime::Ping, |
| 1435 |
test_storage, |
| 1436 |
test_metric_id1, |
| 1437 |
&Metric::String(test_value1.to_string()), |
| 1438 |
) |
| 1439 |
.unwrap(); |
| 1440 |
|
| 1441 |
{ |
| 1442 |
let data = match &db.ping_lifetime_data { |
| 1443 |
Some(ping_lifetime_data) => ping_lifetime_data, |
| 1444 |
None => panic!("Expected `ping_lifetime_data` to exist here!"), |
| 1445 |
}; |
| 1446 |
let data = data.read().unwrap(); |
| 1447 |
// Verify that test_value1 is in memory. |
| 1448 |
assert!(data |
| 1449 |
.get(&format!("{}#{}", test_storage, test_metric_id1)) |
| 1450 |
.is_some()); |
| 1451 |
} |
| 1452 |
|
| 1453 |
// Clear ping lifetime storage for a storage that isn't test_storage. |
| 1454 |
// Doesn't matter what it's called, just that it isn't test_storage. |
| 1455 |
db.clear_ping_lifetime_storage(&(test_storage.to_owned() + "x")) |
| 1456 |
.unwrap(); |
| 1457 |
|
| 1458 |
{ |
| 1459 |
let data = match &db.ping_lifetime_data { |
| 1460 |
Some(ping_lifetime_data) => ping_lifetime_data, |
| 1461 |
None => panic!("Expected `ping_lifetime_data` to exist here!"), |
| 1462 |
}; |
| 1463 |
let data = data.read().unwrap(); |
| 1464 |
// Verify that test_value1 is still in memory. |
| 1465 |
assert!(data |
| 1466 |
.get(&format!("{}#{}", test_storage, test_metric_id1)) |
| 1467 |
.is_some()); |
| 1468 |
} |
| 1469 |
|
| 1470 |
// Clear test_storage's ping lifetime storage. |
| 1471 |
db.clear_ping_lifetime_storage(test_storage).unwrap(); |
| 1472 |
|
| 1473 |
{ |
| 1474 |
let data = match &db.ping_lifetime_data { |
| 1475 |
Some(ping_lifetime_data) => ping_lifetime_data, |
| 1476 |
None => panic!("Expected `ping_lifetime_data` to exist here!"), |
| 1477 |
}; |
| 1478 |
let data = data.read().unwrap(); |
| 1479 |
// Verify that test_value1 is no longer in memory. |
| 1480 |
assert!(data |
| 1481 |
.get(&format!("{}#{}", test_storage, test_metric_id1)) |
| 1482 |
.is_none()); |
| 1483 |
} |
| 1484 |
} |
| 1485 |
|
| 1486 |
#[test] |
| 1487 |
fn doesnt_record_when_upload_is_disabled() { |
| 1488 |
let (mut glean, dir) = new_glean(None); |
| 1489 |
|
| 1490 |
// Init the database in a temporary directory. |
| 1491 |
|
| 1492 |
let test_storage = "test-storage"; |
| 1493 |
let test_data = CommonMetricDataInternal::new("category", "name", test_storage); |
| 1494 |
let test_metric_id = test_data.identifier(&glean); |
| 1495 |
|
| 1496 |
// Attempt to record metric with the record and record_with functions, |
| 1497 |
// this should work since upload is enabled. |
| 1498 |
let db = Database::new(dir.path(), true, 0, Duration::ZERO).unwrap(); |
| 1499 |
db.record(&glean, &test_data, &Metric::String("record".to_owned())); |
| 1500 |
db.iter_store_from( |
| 1501 |
Lifetime::Ping, |
| 1502 |
test_storage, |
| 1503 |
None, |
| 1504 |
&mut |metric_id: &[u8], metric: &Metric| { |
| 1505 |
assert_eq!( |
| 1506 |
String::from_utf8_lossy(metric_id).into_owned(), |
| 1507 |
test_metric_id |
| 1508 |
); |
| 1509 |
match metric { |
| 1510 |
Metric::String(v) => assert_eq!("record", *v), |
| 1511 |
_ => panic!("Unexpected data found"), |
| 1512 |
} |
| 1513 |
}, |
| 1514 |
); |
| 1515 |
|
| 1516 |
db.record_with(&glean, &test_data, |_| { |
| 1517 |
Metric::String("record_with".to_owned()) |
| 1518 |
}); |
| 1519 |
db.iter_store_from( |
| 1520 |
Lifetime::Ping, |
| 1521 |
test_storage, |
| 1522 |
None, |
| 1523 |
&mut |metric_id: &[u8], metric: &Metric| { |
| 1524 |
assert_eq!( |
| 1525 |
String::from_utf8_lossy(metric_id).into_owned(), |
| 1526 |
test_metric_id |
| 1527 |
); |
| 1528 |
match metric { |
| 1529 |
Metric::String(v) => assert_eq!("record_with", *v), |
| 1530 |
_ => panic!("Unexpected data found"), |
| 1531 |
} |
| 1532 |
}, |
| 1533 |
); |
| 1534 |
|
| 1535 |
// Disable upload |
| 1536 |
glean.set_upload_enabled(false); |
| 1537 |
|
| 1538 |
// Attempt to record metric with the record and record_with functions, |
| 1539 |
// this should work since upload is now **disabled**. |
| 1540 |
db.record(&glean, &test_data, &Metric::String("record_nop".to_owned())); |
| 1541 |
db.iter_store_from( |
| 1542 |
Lifetime::Ping, |
| 1543 |
test_storage, |
| 1544 |
None, |
| 1545 |
&mut |metric_id: &[u8], metric: &Metric| { |
| 1546 |
assert_eq!( |
| 1547 |
String::from_utf8_lossy(metric_id).into_owned(), |
| 1548 |
test_metric_id |
| 1549 |
); |
| 1550 |
match metric { |
| 1551 |
Metric::String(v) => assert_eq!("record_with", *v), |
| 1552 |
_ => panic!("Unexpected data found"), |
| 1553 |
} |
| 1554 |
}, |
| 1555 |
); |
| 1556 |
db.record_with(&glean, &test_data, |_| { |
| 1557 |
Metric::String("record_with_nop".to_owned()) |
| 1558 |
}); |
| 1559 |
db.iter_store_from( |
| 1560 |
Lifetime::Ping, |
| 1561 |
test_storage, |
| 1562 |
None, |
| 1563 |
&mut |metric_id: &[u8], metric: &Metric| { |
| 1564 |
assert_eq!( |
| 1565 |
String::from_utf8_lossy(metric_id).into_owned(), |
| 1566 |
test_metric_id |
| 1567 |
); |
| 1568 |
match metric { |
| 1569 |
Metric::String(v) => assert_eq!("record_with", *v), |
| 1570 |
_ => panic!("Unexpected data found"), |
| 1571 |
} |
| 1572 |
}, |
| 1573 |
); |
| 1574 |
} |
| 1575 |
|
| 1576 |
mod safe_mode { |
| 1577 |
use std::fs::File; |
| 1578 |
|
| 1579 |
use super::*; |
| 1580 |
|
| 1581 |
#[test] |
| 1582 |
fn empty_data_file() { |
| 1583 |
let dir = tempdir().unwrap(); |
| 1584 |
|
| 1585 |
// Create database directory structure. |
| 1586 |
let database_dir = dir.path().join("db"); |
| 1587 |
fs::create_dir_all(&database_dir).expect("create database dir"); |
| 1588 |
|
| 1589 |
// Create empty database file. |
| 1590 |
let safebin = database_dir.join("data.safe.bin"); |
| 1591 |
let f = File::create(safebin).expect("create database file"); |
| 1592 |
drop(f); |
| 1593 |
|
| 1594 |
let db = Database::new(dir.path(), false, 0, Duration::ZERO).unwrap(); |
| 1595 |
|
| 1596 |
assert!(dir.path().exists()); |
| 1597 |
assert!( |
| 1598 |
matches!(db.rkv_load_state, RkvLoadState::Err(_)), |
| 1599 |
"Load error recorded" |
| 1600 |
); |
| 1601 |
} |
| 1602 |
|
| 1603 |
#[test] |
| 1604 |
fn corrupted_data_file() { |
| 1605 |
let dir = tempdir().unwrap(); |
| 1606 |
|
| 1607 |
// Create database directory structure. |
| 1608 |
let database_dir = dir.path().join("db"); |
| 1609 |
fs::create_dir_all(&database_dir).expect("create database dir"); |
| 1610 |
|
| 1611 |
// Create empty database file. |
| 1612 |
let safebin = database_dir.join("data.safe.bin"); |
| 1613 |
fs::write(safebin, "<broken>").expect("write to database file"); |
| 1614 |
|
| 1615 |
let db = Database::new(dir.path(), false, 0, Duration::ZERO).unwrap(); |
| 1616 |
|
| 1617 |
assert!(dir.path().exists()); |
| 1618 |
assert!( |
| 1619 |
matches!(db.rkv_load_state, RkvLoadState::Err(_)), |
| 1620 |
"Load error recorded" |
| 1621 |
); |
| 1622 |
} |
| 1623 |
} |
| 1624 |
} |