Files
continuwuity/src/service/globals/data.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

82 lines
1.8 KiB
Rust
Raw Normal View History

use std::sync::{Arc, RwLock};
2022-10-05 15:33:57 +02:00
2024-12-14 21:58:01 -05:00
use conduwuit::{utils, Result};
use database::{Database, Deserialized, Map};
2024-05-26 21:29:19 +00:00
2024-05-27 03:17:20 +00:00
pub struct Data {
2024-06-28 22:51:39 +00:00
global: Arc<Map>,
2024-07-02 07:56:45 +00:00
counter: RwLock<u64>,
2024-07-18 06:37:47 +00:00
pub(super) db: Arc<Database>,
2022-09-07 13:25:51 +02:00
}
2024-05-26 21:29:19 +00:00
2024-07-13 08:07:49 +00:00
const COUNTER: &[u8] = b"c";
2024-05-27 03:17:20 +00:00
impl Data {
2024-07-18 06:37:47 +00:00
pub(super) fn new(args: &crate::Args<'_>) -> Self {
let db = &args.db;
2024-05-27 03:17:20 +00:00
Self {
2024-06-28 22:51:39 +00:00
global: db["global"].clone(),
counter: RwLock::new(
Self::stored_count(&db["global"]).expect("initialized global counter"),
),
2024-07-18 06:37:47 +00:00
db: args.db.clone(),
2024-05-27 03:17:20 +00:00
}
}
pub fn next_count(&self) -> Result<u64> {
let _cork = self.db.cork();
2024-07-02 07:56:45 +00:00
let mut lock = self.counter.write().expect("locked");
let counter: &mut u64 = &mut lock;
debug_assert!(
*counter == Self::stored_count(&self.global).expect("database failure"),
"counter mismatch"
);
2024-07-07 04:46:16 +00:00
*counter = counter
.checked_add(1)
.expect("counter must not overflow u64");
2024-10-07 17:54:27 +00:00
self.global.insert(COUNTER, counter.to_be_bytes());
2024-07-02 07:56:45 +00:00
Ok(*counter)
2024-05-26 21:29:19 +00:00
}
2024-07-02 07:56:45 +00:00
#[inline]
pub fn current_count(&self) -> u64 {
let lock = self.counter.read().expect("locked");
let counter: &u64 = &lock;
debug_assert!(
*counter == Self::stored_count(&self.global).expect("database failure"),
"counter mismatch"
);
*counter
}
fn stored_count(global: &Arc<Map>) -> Result<u64> {
global
2024-09-29 07:37:43 +00:00
.get_blocking(COUNTER)
2024-07-02 07:56:45 +00:00
.as_deref()
.map_or(Ok(0_u64), utils::u64_from_bytes)
2024-05-26 21:29:19 +00:00
}
pub async fn database_version(&self) -> u64 {
self.global
.get(b"version")
.await
.deserialized()
.unwrap_or(0)
}
2024-05-26 21:29:19 +00:00
#[inline]
2024-05-27 03:17:20 +00:00
pub fn bump_database_version(&self, new_version: u64) -> Result<()> {
2024-10-07 17:54:27 +00:00
self.global.raw_put(b"version", new_version);
2024-05-26 21:29:19 +00:00
Ok(())
}
#[inline]
pub fn backup(&self) -> Result { self.db.db.backup() }
2024-05-26 21:29:19 +00:00
#[inline]
2024-05-27 03:17:20 +00:00
pub fn backup_list(&self) -> Result<String> { self.db.db.backup_list() }
2024-05-26 21:29:19 +00:00
}