use std::any;
use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt::{self, Debug};
use std::marker::{self, PhantomData};
use std::ops::{self, DerefMut, Range};
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use bitcoin::hex::DisplayHex as _;
use fedimint_core::util::BoxFuture;
use fedimint_logging::LOG_DB;
use fedimint_util_error::FmtCompact as _;
use futures::{Stream, StreamExt};
use macro_rules_attribute::apply;
use rand::Rng;
use serde::Serialize;
use strum_macros::EnumIter;
use thiserror::Error;
use tracing::{debug, info, instrument, trace, warn};
use crate::core::{ModuleInstanceId, ModuleKind};
use crate::encoding::{Decodable, DecodeError, Encodable};
use crate::fmt_utils::AbbreviateHexBytes;
use crate::task::{MaybeSend, MaybeSync};
use crate::{async_trait_maybe_send, maybe_add_send, maybe_add_send_sync, timing};
pub mod mem_impl;
pub mod notifications;
pub use test_utils::*;
use self::notifications::{Notifications, NotifyQueue};
use crate::module::registry::{ModuleDecoderRegistry, ModuleRegistry};
pub const MODULE_GLOBAL_PREFIX: u8 = 0xff;
pub type DatabaseResult<T> = std::result::Result<T, DatabaseError>;
pub trait DatabaseKeyPrefix: Debug {
fn to_bytes(&self) -> Vec<u8>;
}
pub trait DatabaseRecord: DatabaseKeyPrefix {
const DB_PREFIX: u8;
const NOTIFY_ON_MODIFY: bool = false;
type Key: DatabaseKey + Debug;
type Value: DatabaseValue + Debug;
}
pub trait DatabaseLookup: DatabaseKeyPrefix {
type Record: DatabaseRecord;
}
impl<Record> DatabaseLookup for Record
where
Record: DatabaseRecord + Debug + Decodable + Encodable,
{
type Record = Record;
}
pub trait DatabaseKey: Sized {
const NOTIFY_ON_MODIFY: bool = false;
fn from_bytes(
data: &[u8],
modules: &ModuleDecoderRegistry,
) -> std::result::Result<Self, DecodingError>;
}
pub trait DatabaseKeyWithNotify {}
pub trait DatabaseValue: Sized + Debug {
fn from_bytes(
data: &[u8],
modules: &ModuleDecoderRegistry,
) -> std::result::Result<Self, DecodingError>;
fn to_bytes(&self) -> Vec<u8>;
}
pub type PrefixStream<'a> = Pin<Box<maybe_add_send!(dyn Stream<Item = (Vec<u8>, Vec<u8>)> + 'a)>>;
pub type PhantomBound<'big, 'small> = PhantomData<&'small &'big ()>;
#[derive(Debug, Error)]
pub enum AutocommitError<E> {
#[error("Commit Failed: {last_error}")]
CommitFailed {
attempts: usize,
last_error: DatabaseError,
},
#[error("Closure error: {error}")]
ClosureError {
attempts: usize,
error: E,
},
}
pub trait AutocommitResultExt<T, E> {
fn unwrap_autocommit(self) -> std::result::Result<T, E>;
}
impl<T, E> AutocommitResultExt<T, E> for std::result::Result<T, AutocommitError<E>> {
fn unwrap_autocommit(self) -> std::result::Result<T, E> {
match self {
Ok(value) => Ok(value),
Err(AutocommitError::CommitFailed { .. }) => {
panic!("`unwrap_autocommit` called on a autocommit result with finite retries");
}
Err(AutocommitError::ClosureError { error, .. }) => Err(error),
}
}
}
#[apply(async_trait_maybe_send!)]
pub trait IRawDatabase: Debug + MaybeSend + MaybeSync + 'static {
type Transaction<'a>: IRawDatabaseTransaction + Debug;
async fn begin_transaction<'a>(&'a self) -> Self::Transaction<'a>;
fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()>;
}
#[apply(async_trait_maybe_send!)]
impl<T> IRawDatabase for Box<T>
where
T: IRawDatabase,
{
type Transaction<'a> = <T as IRawDatabase>::Transaction<'a>;
async fn begin_transaction<'a>(&'a self) -> Self::Transaction<'a> {
(**self).begin_transaction().await
}
fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()> {
(**self).checkpoint(backup_path)
}
}
pub trait IRawDatabaseExt: IRawDatabase + Sized {
fn into_database(self) -> Database {
Database::new(self, ModuleRegistry::default())
}
}
impl<T> IRawDatabaseExt for T where T: IRawDatabase {}
impl<T> From<T> for Database
where
T: IRawDatabase,
{
fn from(raw: T) -> Self {
Self::new(raw, ModuleRegistry::default())
}
}
#[apply(async_trait_maybe_send!)]
pub trait IDatabase: Debug + MaybeSend + MaybeSync + 'static {
async fn begin_transaction<'a>(&'a self) -> Box<dyn IDatabaseTransaction + 'a>;
async fn register<'a>(&'a self, key: &[u8]) -> BoxFuture<'a, ()>;
async fn notify(&self, key: &[u8]);
fn is_global(&self) -> bool;
fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()>;
}
#[apply(async_trait_maybe_send!)]
impl<T> IDatabase for Arc<T>
where
T: IDatabase + ?Sized,
{
async fn begin_transaction<'a>(&'a self) -> Box<dyn IDatabaseTransaction + 'a> {
(**self).begin_transaction().await
}
async fn register<'a>(&'a self, key: &[u8]) -> BoxFuture<'a, ()> {
(**self).register(key).await
}
async fn notify(&self, key: &[u8]) {
(**self).notify(key).await;
}
fn is_global(&self) -> bool {
(**self).is_global()
}
fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()> {
(**self).checkpoint(backup_path)
}
}
struct BaseDatabase<RawDatabase> {
notifications: Arc<Notifications>,
raw: RawDatabase,
}
impl<RawDatabase> fmt::Debug for BaseDatabase<RawDatabase> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("BaseDatabase")
}
}
#[apply(async_trait_maybe_send!)]
impl<RawDatabase: IRawDatabase + MaybeSend + 'static> IDatabase for BaseDatabase<RawDatabase> {
async fn begin_transaction<'a>(&'a self) -> Box<dyn IDatabaseTransaction + 'a> {
Box::new(BaseDatabaseTransaction::new(
self.raw.begin_transaction().await,
self.notifications.clone(),
))
}
async fn register<'a>(&'a self, key: &[u8]) -> BoxFuture<'a, ()> {
Box::pin(self.notifications.register(key))
}
async fn notify(&self, key: &[u8]) {
self.notifications.notify(key);
}
fn is_global(&self) -> bool {
true
}
fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()> {
self.raw.checkpoint(backup_path)
}
}
#[derive(Clone, Debug)]
pub struct Database {
inner: Arc<dyn IDatabase + 'static>,
module_decoders: ModuleDecoderRegistry,
}
impl Database {
pub fn strong_count(&self) -> usize {
Arc::strong_count(&self.inner)
}
pub fn into_inner(self) -> Arc<dyn IDatabase + 'static> {
self.inner
}
}
impl Database {
pub fn new(raw: impl IRawDatabase + 'static, module_decoders: ModuleDecoderRegistry) -> Self {
let inner = BaseDatabase {
raw,
notifications: Arc::new(Notifications::new()),
};
Self::new_from_arc(
Arc::new(inner) as Arc<dyn IDatabase + 'static>,
module_decoders,
)
}
pub fn new_from_arc(
inner: Arc<dyn IDatabase + 'static>,
module_decoders: ModuleDecoderRegistry,
) -> Self {
Self {
inner,
module_decoders,
}
}
pub fn with_prefix(&self, prefix: Vec<u8>) -> Self {
Self {
inner: Arc::new(PrefixDatabase {
inner: self.inner.clone(),
global_dbtx_access_token: None,
prefix,
}),
module_decoders: self.module_decoders.clone(),
}
}
pub fn with_prefix_module_id(
&self,
module_instance_id: ModuleInstanceId,
) -> (Self, GlobalDBTxAccessToken) {
let prefix = module_instance_id_to_byte_prefix(module_instance_id);
let global_dbtx_access_token = GlobalDBTxAccessToken::from_prefix(&prefix);
(
Self {
inner: Arc::new(PrefixDatabase {
inner: self.inner.clone(),
global_dbtx_access_token: Some(global_dbtx_access_token),
prefix,
}),
module_decoders: self.module_decoders.clone(),
},
global_dbtx_access_token,
)
}
pub fn with_decoders(&self, module_decoders: ModuleDecoderRegistry) -> Self {
Self {
inner: self.inner.clone(),
module_decoders,
}
}
pub fn is_global(&self) -> bool {
self.inner.is_global()
}
pub fn ensure_global(&self) -> DatabaseResult<()> {
if !self.is_global() {
return Err(DatabaseError::NotGlobal);
}
Ok(())
}
pub fn ensure_isolated(&self) -> DatabaseResult<()> {
if self.is_global() {
return Err(DatabaseError::NotIsolated);
}
Ok(())
}
pub async fn begin_transaction<'s, 'tx>(&'s self) -> DatabaseTransaction<'tx, Committable>
where
's: 'tx,
{
DatabaseTransaction::<Committable>::new(
self.inner.begin_transaction().await,
self.module_decoders.clone(),
)
}
pub async fn begin_transaction_nc<'s, 'tx>(&'s self) -> DatabaseTransaction<'tx, NonCommittable>
where
's: 'tx,
{
self.begin_transaction().await.into_nc()
}
pub fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()> {
self.inner.checkpoint(backup_path)
}
pub async fn autocommit<'s, 'dbtx, F, T, E>(
&'s self,
tx_fn: F,
max_attempts: Option<usize>,
) -> std::result::Result<T, AutocommitError<E>>
where
's: 'dbtx,
for<'r, 'o> F: Fn(
&'r mut DatabaseTransaction<'o>,
PhantomBound<'dbtx, 'o>,
) -> BoxFuture<'r, std::result::Result<T, E>>,
{
assert_ne!(max_attempts, Some(0));
let mut curr_attempts: usize = 0;
loop {
curr_attempts = curr_attempts
.checked_add(1)
.expect("db autocommit attempt counter overflowed");
let mut dbtx = self.begin_transaction().await;
let tx_fn_res = tx_fn(&mut dbtx.to_ref_nc(), PhantomData).await;
let val = match tx_fn_res {
Ok(val) => val,
Err(err) => {
dbtx.ignore_uncommitted();
return Err(AutocommitError::ClosureError {
attempts: curr_attempts,
error: err,
});
}
};
let _timing = timing::TimeReporter::new("autocommit - commit_tx");
match dbtx.commit_tx_result().await {
Ok(()) => {
return Ok(val);
}
Err(err) => {
if max_attempts.is_some_and(|max_att| max_att <= curr_attempts) {
warn!(
target: LOG_DB,
curr_attempts,
err = %err.fmt_compact(),
"Database commit failed in an autocommit block - terminating"
);
return Err(AutocommitError::CommitFailed {
attempts: curr_attempts,
last_error: err,
});
}
let delay = (2u64.pow(curr_attempts.min(7) as u32) * 10).min(1000);
let delay = rand::thread_rng().gen_range(delay..(2 * delay));
warn!(
target: LOG_DB,
curr_attempts,
err = %err.fmt_compact(),
delay_ms = %delay,
"Database commit failed in an autocommit block - retrying"
);
crate::runtime::sleep(Duration::from_millis(delay)).await;
}
}
}
}
pub async fn wait_key_check<'a, K, T>(
&'a self,
key: &K,
checker: impl Fn(Option<K::Value>) -> Option<T>,
) -> (T, DatabaseTransaction<'a, Committable>)
where
K: DatabaseKey + DatabaseRecord + DatabaseKeyWithNotify,
{
let key_bytes = key.to_bytes();
loop {
let notify = self.inner.register(&key_bytes).await;
let mut tx = self.inner.begin_transaction().await;
let maybe_value_bytes = tx
.raw_get_bytes(&key_bytes)
.await
.expect("Unrecoverable error when reading from database")
.map(|value_bytes| {
decode_value_expect(&value_bytes, &self.module_decoders, &key_bytes)
});
if let Some(value) = checker(maybe_value_bytes) {
return (
value,
DatabaseTransaction::new(tx, self.module_decoders.clone()),
);
}
notify.await;
}
}
pub async fn wait_key_exists<K>(&self, key: &K) -> K::Value
where
K: DatabaseKey + DatabaseRecord + DatabaseKeyWithNotify,
{
self.wait_key_check(key, std::convert::identity).await.0
}
}
fn module_instance_id_to_byte_prefix(module_instance_id: u16) -> Vec<u8> {
let mut bytes = vec![MODULE_GLOBAL_PREFIX];
bytes.append(&mut module_instance_id.consensus_encode_to_vec());
bytes
}
#[derive(Clone, Debug)]
struct PrefixDatabase<Inner>
where
Inner: Debug,
{
prefix: Vec<u8>,
global_dbtx_access_token: Option<GlobalDBTxAccessToken>,
inner: Inner,
}
impl<Inner> PrefixDatabase<Inner>
where
Inner: Debug,
{
fn get_full_key(&self, key: &[u8]) -> Vec<u8> {
let mut full_key = self.prefix.clone();
full_key.extend_from_slice(key);
full_key
}
}
#[apply(async_trait_maybe_send!)]
impl<Inner> IDatabase for PrefixDatabase<Inner>
where
Inner: Debug + MaybeSend + MaybeSync + 'static + IDatabase,
{
async fn begin_transaction<'a>(&'a self) -> Box<dyn IDatabaseTransaction + 'a> {
Box::new(PrefixDatabaseTransaction {
inner: self.inner.begin_transaction().await,
global_dbtx_access_token: self.global_dbtx_access_token,
prefix: self.prefix.clone(),
})
}
async fn register<'a>(&'a self, key: &[u8]) -> BoxFuture<'a, ()> {
self.inner.register(&self.get_full_key(key)).await
}
async fn notify(&self, key: &[u8]) {
self.inner.notify(&self.get_full_key(key)).await;
}
fn is_global(&self) -> bool {
if self.global_dbtx_access_token.is_some() {
false
} else {
self.inner.is_global()
}
}
fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()> {
self.inner.checkpoint(backup_path)
}
}
#[derive(Debug)]
struct PrefixDatabaseTransaction<Inner> {
inner: Inner,
global_dbtx_access_token: Option<GlobalDBTxAccessToken>,
prefix: Vec<u8>,
}
impl<Inner> PrefixDatabaseTransaction<Inner> {
fn get_full_key(&self, key: &[u8]) -> Vec<u8> {
let mut full_key = self.prefix.clone();
full_key.extend_from_slice(key);
full_key
}
fn get_full_range(&self, range: Range<&[u8]>) -> Range<Vec<u8>> {
Range {
start: self.get_full_key(range.start),
end: self.get_full_key(range.end),
}
}
fn adapt_prefix_stream(stream: PrefixStream<'_>, prefix_len: usize) -> PrefixStream<'_> {
Box::pin(stream.map(move |(k, v)| (k[prefix_len..].to_owned(), v)))
}
}
#[apply(async_trait_maybe_send!)]
impl<Inner> IDatabaseTransaction for PrefixDatabaseTransaction<Inner>
where
Inner: IDatabaseTransaction,
{
async fn commit_tx(&mut self) -> DatabaseResult<()> {
self.inner.commit_tx().await
}
fn is_global(&self) -> bool {
if self.global_dbtx_access_token.is_some() {
false
} else {
self.inner.is_global()
}
}
fn global_dbtx(
&mut self,
access_token: GlobalDBTxAccessToken,
) -> &mut dyn IDatabaseTransaction {
if let Some(self_global_dbtx_access_token) = self.global_dbtx_access_token {
assert_eq!(
access_token, self_global_dbtx_access_token,
"Invalid access key used to access global_dbtx"
);
&mut self.inner
} else {
self.inner.global_dbtx(access_token)
}
}
}
#[apply(async_trait_maybe_send!)]
impl<Inner> IDatabaseTransactionOpsCore for PrefixDatabaseTransaction<Inner>
where
Inner: IDatabaseTransactionOpsCore,
{
async fn raw_insert_bytes(
&mut self,
key: &[u8],
value: &[u8],
) -> DatabaseResult<Option<Vec<u8>>> {
let key = self.get_full_key(key);
self.inner.raw_insert_bytes(&key, value).await
}
async fn raw_get_bytes(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
let key = self.get_full_key(key);
self.inner.raw_get_bytes(&key).await
}
async fn raw_remove_entry(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
let key = self.get_full_key(key);
self.inner.raw_remove_entry(&key).await
}
async fn raw_find_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<PrefixStream<'_>> {
let key = self.get_full_key(key_prefix);
let stream = self.inner.raw_find_by_prefix(&key).await?;
Ok(Self::adapt_prefix_stream(stream, self.prefix.len()))
}
async fn raw_find_by_prefix_sorted_descending(
&mut self,
key_prefix: &[u8],
) -> DatabaseResult<PrefixStream<'_>> {
let key = self.get_full_key(key_prefix);
let stream = self
.inner
.raw_find_by_prefix_sorted_descending(&key)
.await?;
Ok(Self::adapt_prefix_stream(stream, self.prefix.len()))
}
async fn raw_find_by_range(&mut self, range: Range<&[u8]>) -> DatabaseResult<PrefixStream<'_>> {
let range = self.get_full_range(range);
let stream = self
.inner
.raw_find_by_range(Range {
start: &range.start,
end: &range.end,
})
.await?;
Ok(Self::adapt_prefix_stream(stream, self.prefix.len()))
}
async fn raw_remove_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<()> {
let key = self.get_full_key(key_prefix);
self.inner.raw_remove_by_prefix(&key).await
}
}
impl<Inner> IDatabaseTransactionOps for PrefixDatabaseTransaction<Inner> where
Inner: IDatabaseTransactionOps
{
}
#[apply(async_trait_maybe_send!)]
pub trait IDatabaseTransactionOpsCore: MaybeSend {
async fn raw_insert_bytes(
&mut self,
key: &[u8],
value: &[u8],
) -> DatabaseResult<Option<Vec<u8>>>;
async fn raw_get_bytes(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>>;
async fn raw_remove_entry(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>>;
async fn raw_find_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<PrefixStream<'_>>;
async fn raw_find_by_prefix_sorted_descending(
&mut self,
key_prefix: &[u8],
) -> DatabaseResult<PrefixStream<'_>>;
async fn raw_find_by_range(&mut self, range: Range<&[u8]>) -> DatabaseResult<PrefixStream<'_>>;
async fn raw_remove_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<()>;
}
#[apply(async_trait_maybe_send!)]
impl<T> IDatabaseTransactionOpsCore for Box<T>
where
T: IDatabaseTransactionOpsCore + ?Sized,
{
async fn raw_insert_bytes(
&mut self,
key: &[u8],
value: &[u8],
) -> DatabaseResult<Option<Vec<u8>>> {
(**self).raw_insert_bytes(key, value).await
}
async fn raw_get_bytes(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
(**self).raw_get_bytes(key).await
}
async fn raw_remove_entry(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
(**self).raw_remove_entry(key).await
}
async fn raw_find_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<PrefixStream<'_>> {
(**self).raw_find_by_prefix(key_prefix).await
}
async fn raw_find_by_prefix_sorted_descending(
&mut self,
key_prefix: &[u8],
) -> DatabaseResult<PrefixStream<'_>> {
(**self)
.raw_find_by_prefix_sorted_descending(key_prefix)
.await
}
async fn raw_find_by_range(&mut self, range: Range<&[u8]>) -> DatabaseResult<PrefixStream<'_>> {
(**self).raw_find_by_range(range).await
}
async fn raw_remove_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<()> {
(**self).raw_remove_by_prefix(key_prefix).await
}
}
#[apply(async_trait_maybe_send!)]
impl<T> IDatabaseTransactionOpsCore for &mut T
where
T: IDatabaseTransactionOpsCore + ?Sized,
{
async fn raw_insert_bytes(
&mut self,
key: &[u8],
value: &[u8],
) -> DatabaseResult<Option<Vec<u8>>> {
(**self).raw_insert_bytes(key, value).await
}
async fn raw_get_bytes(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
(**self).raw_get_bytes(key).await
}
async fn raw_remove_entry(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
(**self).raw_remove_entry(key).await
}
async fn raw_find_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<PrefixStream<'_>> {
(**self).raw_find_by_prefix(key_prefix).await
}
async fn raw_find_by_prefix_sorted_descending(
&mut self,
key_prefix: &[u8],
) -> DatabaseResult<PrefixStream<'_>> {
(**self)
.raw_find_by_prefix_sorted_descending(key_prefix)
.await
}
async fn raw_find_by_range(&mut self, range: Range<&[u8]>) -> DatabaseResult<PrefixStream<'_>> {
(**self).raw_find_by_range(range).await
}
async fn raw_remove_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<()> {
(**self).raw_remove_by_prefix(key_prefix).await
}
}
pub trait IDatabaseTransactionOps: IDatabaseTransactionOpsCore + MaybeSend {}
impl<T> IDatabaseTransactionOps for Box<T> where T: IDatabaseTransactionOps + ?Sized {}
impl<T> IDatabaseTransactionOps for &mut T where T: IDatabaseTransactionOps + ?Sized {}
#[apply(async_trait_maybe_send!)]
pub trait IDatabaseTransactionOpsCoreTyped<'a> {
async fn get_value<K>(&mut self, key: &K) -> Option<K::Value>
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync;
async fn insert_entry<K>(&mut self, key: &K, value: &K::Value) -> Option<K::Value>
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync,
K::Value: MaybeSend + MaybeSync;
async fn insert_new_entry<K>(&mut self, key: &K, value: &K::Value)
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync,
K::Value: MaybeSend + MaybeSync;
async fn find_by_range<K>(
&mut self,
key_range: Range<K>,
) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (K, K::Value)> + '_)>>
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync,
K::Value: MaybeSend + MaybeSync;
async fn find_by_prefix<KP>(
&mut self,
key_prefix: &KP,
) -> Pin<
Box<
maybe_add_send!(
dyn Stream<
Item = (
KP::Record,
<<KP as DatabaseLookup>::Record as DatabaseRecord>::Value,
),
> + '_
),
>,
>
where
KP: DatabaseLookup + MaybeSend + MaybeSync,
KP::Record: DatabaseKey;
async fn find_by_prefix_sorted_descending<KP>(
&mut self,
key_prefix: &KP,
) -> Pin<
Box<
maybe_add_send!(
dyn Stream<
Item = (
KP::Record,
<<KP as DatabaseLookup>::Record as DatabaseRecord>::Value,
),
> + '_
),
>,
>
where
KP: DatabaseLookup + MaybeSend + MaybeSync,
KP::Record: DatabaseKey;
async fn remove_entry<K>(&mut self, key: &K) -> Option<K::Value>
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync;
async fn remove_by_prefix<KP>(&mut self, key_prefix: &KP)
where
KP: DatabaseLookup + MaybeSend + MaybeSync;
}
#[apply(async_trait_maybe_send!)]
impl<T> IDatabaseTransactionOpsCoreTyped<'_> for T
where
T: IDatabaseTransactionOpsCore + WithDecoders,
{
async fn get_value<K>(&mut self, key: &K) -> Option<K::Value>
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync,
{
let key_bytes = key.to_bytes();
let raw = self
.raw_get_bytes(&key_bytes)
.await
.expect("Unrecoverable error occurred while reading and entry from the database");
raw.map(|value_bytes| {
decode_value_expect::<K::Value>(&value_bytes, self.decoders(), &key_bytes)
})
}
async fn insert_entry<K>(&mut self, key: &K, value: &K::Value) -> Option<K::Value>
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync,
K::Value: MaybeSend + MaybeSync,
{
let key_bytes = key.to_bytes();
self.raw_insert_bytes(&key_bytes, &value.to_bytes())
.await
.expect("Unrecoverable error occurred while inserting entry into the database")
.map(|value_bytes| {
decode_value_expect::<K::Value>(&value_bytes, self.decoders(), &key_bytes)
})
}
async fn insert_new_entry<K>(&mut self, key: &K, value: &K::Value)
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync,
K::Value: MaybeSend + MaybeSync,
{
if let Some(prev) = self.insert_entry(key, value).await {
panic!(
"Database overwriting element when expecting insertion of new entry. Key: {key:?} Prev Value: {prev:?}"
);
}
}
async fn find_by_range<K>(
&mut self,
key_range: Range<K>,
) -> Pin<Box<maybe_add_send!(dyn Stream<Item = (K, K::Value)> + '_)>>
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync,
K::Value: MaybeSend + MaybeSync,
{
let decoders = self.decoders().clone();
Box::pin(
self.raw_find_by_range(Range {
start: &key_range.start.to_bytes(),
end: &key_range.end.to_bytes(),
})
.await
.expect("Unrecoverable error occurred while listing entries from the database")
.map(move |(key_bytes, value_bytes)| {
let key = decode_key_expect(&key_bytes, &decoders);
let value = decode_value_expect(&value_bytes, &decoders, &key_bytes);
(key, value)
}),
)
}
async fn find_by_prefix<KP>(
&mut self,
key_prefix: &KP,
) -> Pin<
Box<
maybe_add_send!(
dyn Stream<
Item = (
KP::Record,
<<KP as DatabaseLookup>::Record as DatabaseRecord>::Value,
),
> + '_
),
>,
>
where
KP: DatabaseLookup + MaybeSend + MaybeSync,
KP::Record: DatabaseKey,
{
let decoders = self.decoders().clone();
Box::pin(
self.raw_find_by_prefix(&key_prefix.to_bytes())
.await
.expect("Unrecoverable error occurred while listing entries from the database")
.map(move |(key_bytes, value_bytes)| {
let key = decode_key_expect(&key_bytes, &decoders);
let value = decode_value_expect(&value_bytes, &decoders, &key_bytes);
(key, value)
}),
)
}
async fn find_by_prefix_sorted_descending<KP>(
&mut self,
key_prefix: &KP,
) -> Pin<
Box<
maybe_add_send!(
dyn Stream<
Item = (
KP::Record,
<<KP as DatabaseLookup>::Record as DatabaseRecord>::Value,
),
> + '_
),
>,
>
where
KP: DatabaseLookup + MaybeSend + MaybeSync,
KP::Record: DatabaseKey,
{
let decoders = self.decoders().clone();
Box::pin(
self.raw_find_by_prefix_sorted_descending(&key_prefix.to_bytes())
.await
.expect("Unrecoverable error occurred while listing entries from the database")
.map(move |(key_bytes, value_bytes)| {
let key = decode_key_expect(&key_bytes, &decoders);
let value = decode_value_expect(&value_bytes, &decoders, &key_bytes);
(key, value)
}),
)
}
async fn remove_entry<K>(&mut self, key: &K) -> Option<K::Value>
where
K: DatabaseKey + DatabaseRecord + MaybeSend + MaybeSync,
{
let key_bytes = key.to_bytes();
self.raw_remove_entry(&key_bytes)
.await
.expect("Unrecoverable error occurred while inserting removing entry from the database")
.map(|value_bytes| {
decode_value_expect::<K::Value>(&value_bytes, self.decoders(), &key_bytes)
})
}
async fn remove_by_prefix<KP>(&mut self, key_prefix: &KP)
where
KP: DatabaseLookup + MaybeSend + MaybeSync,
{
self.raw_remove_by_prefix(&key_prefix.to_bytes())
.await
.expect("Unrecoverable error when removing entries from the database");
}
}
pub trait WithDecoders {
fn decoders(&self) -> &ModuleDecoderRegistry;
}
#[apply(async_trait_maybe_send!)]
pub trait IRawDatabaseTransaction: MaybeSend + IDatabaseTransactionOps {
async fn commit_tx(self) -> DatabaseResult<()>;
}
#[apply(async_trait_maybe_send!)]
pub trait IDatabaseTransaction: MaybeSend + IDatabaseTransactionOps + fmt::Debug {
async fn commit_tx(&mut self) -> DatabaseResult<()>;
fn is_global(&self) -> bool;
#[doc(hidden)]
fn global_dbtx(&mut self, access_token: GlobalDBTxAccessToken)
-> &mut dyn IDatabaseTransaction;
}
#[apply(async_trait_maybe_send!)]
impl<T> IDatabaseTransaction for Box<T>
where
T: IDatabaseTransaction + ?Sized,
{
async fn commit_tx(&mut self) -> DatabaseResult<()> {
(**self).commit_tx().await
}
fn is_global(&self) -> bool {
(**self).is_global()
}
fn global_dbtx(
&mut self,
access_token: GlobalDBTxAccessToken,
) -> &mut dyn IDatabaseTransaction {
(**self).global_dbtx(access_token)
}
}
#[apply(async_trait_maybe_send!)]
impl<'a, T> IDatabaseTransaction for &'a mut T
where
T: IDatabaseTransaction + ?Sized,
{
async fn commit_tx(&mut self) -> DatabaseResult<()> {
(**self).commit_tx().await
}
fn is_global(&self) -> bool {
(**self).is_global()
}
fn global_dbtx(&mut self, access_key: GlobalDBTxAccessToken) -> &mut dyn IDatabaseTransaction {
(**self).global_dbtx(access_key)
}
}
struct BaseDatabaseTransaction<Tx> {
raw: Option<Tx>,
notify_queue: Option<NotifyQueue>,
notifications: Arc<Notifications>,
}
impl<Tx> fmt::Debug for BaseDatabaseTransaction<Tx>
where
Tx: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!(
"BaseDatabaseTransaction{{ raw={:?} }}",
self.raw
))
}
}
impl<Tx> BaseDatabaseTransaction<Tx>
where
Tx: IRawDatabaseTransaction,
{
fn new(dbtx: Tx, notifications: Arc<Notifications>) -> Self {
Self {
raw: Some(dbtx),
notifications,
notify_queue: Some(NotifyQueue::new()),
}
}
fn add_notification_key(&mut self, key: &[u8]) -> DatabaseResult<()> {
self.notify_queue
.as_mut()
.ok_or(DatabaseError::TransactionConsumed)?
.add(key);
Ok(())
}
}
#[apply(async_trait_maybe_send!)]
impl<Tx: IRawDatabaseTransaction> IDatabaseTransactionOpsCore for BaseDatabaseTransaction<Tx> {
async fn raw_insert_bytes(
&mut self,
key: &[u8],
value: &[u8],
) -> DatabaseResult<Option<Vec<u8>>> {
self.add_notification_key(key)?;
self.raw
.as_mut()
.ok_or(DatabaseError::TransactionConsumed)?
.raw_insert_bytes(key, value)
.await
}
async fn raw_get_bytes(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
self.raw
.as_mut()
.ok_or(DatabaseError::TransactionConsumed)?
.raw_get_bytes(key)
.await
}
async fn raw_remove_entry(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
self.add_notification_key(key)?;
self.raw
.as_mut()
.ok_or(DatabaseError::TransactionConsumed)?
.raw_remove_entry(key)
.await
}
async fn raw_find_by_range(
&mut self,
key_range: Range<&[u8]>,
) -> DatabaseResult<PrefixStream<'_>> {
self.raw
.as_mut()
.ok_or(DatabaseError::TransactionConsumed)?
.raw_find_by_range(key_range)
.await
}
async fn raw_find_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<PrefixStream<'_>> {
self.raw
.as_mut()
.ok_or(DatabaseError::TransactionConsumed)?
.raw_find_by_prefix(key_prefix)
.await
}
async fn raw_find_by_prefix_sorted_descending(
&mut self,
key_prefix: &[u8],
) -> DatabaseResult<PrefixStream<'_>> {
self.raw
.as_mut()
.ok_or(DatabaseError::TransactionConsumed)?
.raw_find_by_prefix_sorted_descending(key_prefix)
.await
}
async fn raw_remove_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<()> {
self.raw
.as_mut()
.ok_or(DatabaseError::TransactionConsumed)?
.raw_remove_by_prefix(key_prefix)
.await
}
}
impl<Tx: IRawDatabaseTransaction> IDatabaseTransactionOps for BaseDatabaseTransaction<Tx> {}
#[apply(async_trait_maybe_send!)]
impl<Tx: IRawDatabaseTransaction + fmt::Debug> IDatabaseTransaction
for BaseDatabaseTransaction<Tx>
{
async fn commit_tx(&mut self) -> DatabaseResult<()> {
self.raw
.take()
.ok_or(DatabaseError::TransactionConsumed)?
.commit_tx()
.await?;
self.notifications.submit_queue(
&self
.notify_queue
.take()
.expect("commit must be called only once"),
);
Ok(())
}
fn is_global(&self) -> bool {
true
}
fn global_dbtx(
&mut self,
_access_token: GlobalDBTxAccessToken,
) -> &mut dyn IDatabaseTransaction {
panic!("Illegal to call global_dbtx on BaseDatabaseTransaction");
}
}
#[derive(Clone)]
struct CommitTracker {
is_committed: bool,
has_writes: bool,
ignore_uncommitted: bool,
}
impl Drop for CommitTracker {
fn drop(&mut self) {
if self.has_writes && !self.is_committed {
if self.ignore_uncommitted {
trace!(
target: LOG_DB,
"DatabaseTransaction has writes and has not called commit, but that's expected."
);
} else {
warn!(
target: LOG_DB,
location = ?backtrace::Backtrace::new(),
"DatabaseTransaction has writes and has not called commit."
);
}
}
}
}
enum MaybeRef<'a, T> {
Owned(T),
Borrowed(&'a mut T),
}
impl<T> ops::Deref for MaybeRef<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match self {
MaybeRef::Owned(o) => o,
MaybeRef::Borrowed(r) => r,
}
}
}
impl<T> ops::DerefMut for MaybeRef<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
MaybeRef::Owned(o) => o,
MaybeRef::Borrowed(r) => r,
}
}
}
pub struct Committable;
pub struct NonCommittable;
pub struct DatabaseTransaction<'tx, Cap = NonCommittable> {
tx: Box<dyn IDatabaseTransaction + 'tx>,
decoders: ModuleDecoderRegistry,
commit_tracker: MaybeRef<'tx, CommitTracker>,
on_commit_hooks: MaybeRef<'tx, Vec<Box<maybe_add_send!(dyn FnOnce())>>>,
capability: marker::PhantomData<Cap>,
}
impl<Cap> fmt::Debug for DatabaseTransaction<'_, Cap> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!(
"DatabaseTransaction {{ tx: {:?}, decoders={:?} }}",
self.tx, self.decoders
))
}
}
impl<Cap> WithDecoders for DatabaseTransaction<'_, Cap> {
fn decoders(&self) -> &ModuleDecoderRegistry {
&self.decoders
}
}
#[instrument(target = LOG_DB, level = "trace", skip_all, fields(value_type = std::any::type_name::<V>()), err)]
fn decode_value<V: DatabaseValue>(
value_bytes: &[u8],
decoders: &ModuleDecoderRegistry,
) -> std::result::Result<V, DecodingError> {
trace!(
bytes = %AbbreviateHexBytes(value_bytes),
"decoding value",
);
V::from_bytes(value_bytes, decoders)
}
#[track_caller]
fn decode_value_expect<V: DatabaseValue>(
value_bytes: &[u8],
decoders: &ModuleDecoderRegistry,
key_bytes: &[u8],
) -> V {
decode_value(value_bytes, decoders).unwrap_or_else(|err| {
panic!(
"Unrecoverable decoding DatabaseValue as {}; err={}, key_bytes={}, val_bytes={}",
any::type_name::<V>(),
err.fmt_compact(),
AbbreviateHexBytes(key_bytes),
AbbreviateHexBytes(value_bytes),
)
})
}
#[track_caller]
fn decode_key_expect<K: DatabaseKey>(key_bytes: &[u8], decoders: &ModuleDecoderRegistry) -> K {
trace!(
bytes = %AbbreviateHexBytes(key_bytes),
"decoding key",
);
K::from_bytes(key_bytes, decoders).unwrap_or_else(|err| {
panic!(
"Unrecoverable decoding DatabaseKey as {}; err={}; bytes={}",
any::type_name::<K>(),
err.fmt_compact(),
AbbreviateHexBytes(key_bytes)
)
})
}
impl<'tx, Cap> DatabaseTransaction<'tx, Cap> {
pub fn into_nc(self) -> DatabaseTransaction<'tx, NonCommittable> {
DatabaseTransaction {
tx: self.tx,
decoders: self.decoders,
commit_tracker: self.commit_tracker,
on_commit_hooks: self.on_commit_hooks,
capability: PhantomData::<NonCommittable>,
}
}
pub fn to_ref_nc<'s, 'a>(&'s mut self) -> DatabaseTransaction<'a, NonCommittable>
where
's: 'a,
{
self.to_ref().into_nc()
}
pub fn with_prefix<'a: 'tx>(self, prefix: Vec<u8>) -> DatabaseTransaction<'a, Cap>
where
'tx: 'a,
{
DatabaseTransaction {
tx: Box::new(PrefixDatabaseTransaction {
inner: self.tx,
global_dbtx_access_token: None,
prefix,
}),
decoders: self.decoders,
commit_tracker: self.commit_tracker,
on_commit_hooks: self.on_commit_hooks,
capability: self.capability,
}
}
pub fn with_prefix_module_id<'a: 'tx>(
self,
module_instance_id: ModuleInstanceId,
) -> (DatabaseTransaction<'a, Cap>, GlobalDBTxAccessToken)
where
'tx: 'a,
{
let prefix = module_instance_id_to_byte_prefix(module_instance_id);
let global_dbtx_access_token = GlobalDBTxAccessToken::from_prefix(&prefix);
(
DatabaseTransaction {
tx: Box::new(PrefixDatabaseTransaction {
inner: self.tx,
global_dbtx_access_token: Some(global_dbtx_access_token),
prefix,
}),
decoders: self.decoders,
commit_tracker: self.commit_tracker,
on_commit_hooks: self.on_commit_hooks,
capability: self.capability,
},
global_dbtx_access_token,
)
}
pub fn to_ref<'s, 'a>(&'s mut self) -> DatabaseTransaction<'a, Cap>
where
's: 'a,
{
let decoders = self.decoders.clone();
DatabaseTransaction {
tx: Box::new(&mut self.tx),
decoders,
commit_tracker: match self.commit_tracker {
MaybeRef::Owned(ref mut o) => MaybeRef::Borrowed(o),
MaybeRef::Borrowed(ref mut b) => MaybeRef::Borrowed(b),
},
on_commit_hooks: match self.on_commit_hooks {
MaybeRef::Owned(ref mut o) => MaybeRef::Borrowed(o),
MaybeRef::Borrowed(ref mut b) => MaybeRef::Borrowed(b),
},
capability: self.capability,
}
}
pub fn to_ref_with_prefix<'a>(&'a mut self, prefix: Vec<u8>) -> DatabaseTransaction<'a, Cap>
where
'tx: 'a,
{
DatabaseTransaction {
tx: Box::new(PrefixDatabaseTransaction {
inner: &mut self.tx,
global_dbtx_access_token: None,
prefix,
}),
decoders: self.decoders.clone(),
commit_tracker: match self.commit_tracker {
MaybeRef::Owned(ref mut o) => MaybeRef::Borrowed(o),
MaybeRef::Borrowed(ref mut b) => MaybeRef::Borrowed(b),
},
on_commit_hooks: match self.on_commit_hooks {
MaybeRef::Owned(ref mut o) => MaybeRef::Borrowed(o),
MaybeRef::Borrowed(ref mut b) => MaybeRef::Borrowed(b),
},
capability: self.capability,
}
}
pub fn to_ref_with_prefix_module_id<'a>(
&'a mut self,
module_instance_id: ModuleInstanceId,
) -> (DatabaseTransaction<'a, Cap>, GlobalDBTxAccessToken)
where
'tx: 'a,
{
let prefix = module_instance_id_to_byte_prefix(module_instance_id);
let global_dbtx_access_token = GlobalDBTxAccessToken::from_prefix(&prefix);
(
DatabaseTransaction {
tx: Box::new(PrefixDatabaseTransaction {
inner: &mut self.tx,
global_dbtx_access_token: Some(global_dbtx_access_token),
prefix,
}),
decoders: self.decoders.clone(),
commit_tracker: match self.commit_tracker {
MaybeRef::Owned(ref mut o) => MaybeRef::Borrowed(o),
MaybeRef::Borrowed(ref mut b) => MaybeRef::Borrowed(b),
},
on_commit_hooks: match self.on_commit_hooks {
MaybeRef::Owned(ref mut o) => MaybeRef::Borrowed(o),
MaybeRef::Borrowed(ref mut b) => MaybeRef::Borrowed(b),
},
capability: self.capability,
},
global_dbtx_access_token,
)
}
pub fn is_global(&self) -> bool {
self.tx.is_global()
}
pub fn ensure_global(&self) -> DatabaseResult<()> {
if !self.is_global() {
return Err(DatabaseError::NotGlobal);
}
Ok(())
}
pub fn ensure_isolated(&self) -> DatabaseResult<()> {
if self.is_global() {
return Err(DatabaseError::NotIsolated);
}
Ok(())
}
pub fn ignore_uncommitted(&mut self) -> &mut Self {
self.commit_tracker.ignore_uncommitted = true;
self
}
pub fn warn_uncommitted(&mut self) -> &mut Self {
self.commit_tracker.ignore_uncommitted = false;
self
}
#[instrument(target = LOG_DB, level = "trace", skip_all)]
pub fn on_commit(&mut self, f: maybe_add_send!(impl FnOnce() + 'static)) {
self.on_commit_hooks.push(Box::new(f));
}
pub fn global_dbtx<'a>(
&'a mut self,
access_token: GlobalDBTxAccessToken,
) -> DatabaseTransaction<'a, Cap>
where
'tx: 'a,
{
let decoders = self.decoders.clone();
DatabaseTransaction {
tx: Box::new(self.tx.global_dbtx(access_token)),
decoders,
commit_tracker: match self.commit_tracker {
MaybeRef::Owned(ref mut o) => MaybeRef::Borrowed(o),
MaybeRef::Borrowed(ref mut b) => MaybeRef::Borrowed(b),
},
on_commit_hooks: match self.on_commit_hooks {
MaybeRef::Owned(ref mut o) => MaybeRef::Borrowed(o),
MaybeRef::Borrowed(ref mut b) => MaybeRef::Borrowed(b),
},
capability: self.capability,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct GlobalDBTxAccessToken(u32);
impl GlobalDBTxAccessToken {
fn from_prefix(prefix: &[u8]) -> Self {
Self(prefix.iter().fold(0, |acc, b| acc + u32::from(*b)) + 513)
}
}
impl<'tx> DatabaseTransaction<'tx, Committable> {
pub fn new(dbtx: Box<dyn IDatabaseTransaction + 'tx>, decoders: ModuleDecoderRegistry) -> Self {
Self {
tx: dbtx,
decoders,
commit_tracker: MaybeRef::Owned(CommitTracker {
is_committed: false,
has_writes: false,
ignore_uncommitted: false,
}),
on_commit_hooks: MaybeRef::Owned(vec![]),
capability: PhantomData,
}
}
pub async fn commit_tx_result(mut self) -> DatabaseResult<()> {
self.commit_tracker.is_committed = true;
let commit_result = self.tx.commit_tx().await;
if commit_result.is_ok() {
for hook in self.on_commit_hooks.deref_mut().drain(..) {
hook();
}
}
commit_result
}
pub async fn commit_tx(mut self) {
self.commit_tracker.is_committed = true;
self.commit_tx_result()
.await
.expect("Unrecoverable error occurred while committing to the database.");
}
}
#[apply(async_trait_maybe_send!)]
impl<Cap> IDatabaseTransactionOpsCore for DatabaseTransaction<'_, Cap>
where
Cap: Send,
{
async fn raw_insert_bytes(
&mut self,
key: &[u8],
value: &[u8],
) -> DatabaseResult<Option<Vec<u8>>> {
self.commit_tracker.has_writes = true;
self.tx.raw_insert_bytes(key, value).await
}
async fn raw_get_bytes(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
self.tx.raw_get_bytes(key).await
}
async fn raw_remove_entry(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
self.tx.raw_remove_entry(key).await
}
async fn raw_find_by_range(
&mut self,
key_range: Range<&[u8]>,
) -> DatabaseResult<PrefixStream<'_>> {
self.tx.raw_find_by_range(key_range).await
}
async fn raw_find_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<PrefixStream<'_>> {
self.tx.raw_find_by_prefix(key_prefix).await
}
async fn raw_find_by_prefix_sorted_descending(
&mut self,
key_prefix: &[u8],
) -> DatabaseResult<PrefixStream<'_>> {
self.tx
.raw_find_by_prefix_sorted_descending(key_prefix)
.await
}
async fn raw_remove_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<()> {
self.commit_tracker.has_writes = true;
self.tx.raw_remove_by_prefix(key_prefix).await
}
}
impl IDatabaseTransactionOps for DatabaseTransaction<'_, Committable> {}
impl<T> DatabaseKeyPrefix for T
where
T: DatabaseLookup + crate::encoding::Encodable + Debug,
{
fn to_bytes(&self) -> Vec<u8> {
let mut data = vec![<Self as DatabaseLookup>::Record::DB_PREFIX];
data.append(&mut self.consensus_encode_to_vec());
data
}
}
impl<T> DatabaseKey for T
where
T: DatabaseRecord + crate::encoding::Decodable + Sized,
{
const NOTIFY_ON_MODIFY: bool = <T as DatabaseRecord>::NOTIFY_ON_MODIFY;
fn from_bytes(
data: &[u8],
modules: &ModuleDecoderRegistry,
) -> std::result::Result<Self, DecodingError> {
if data.is_empty() {
return Err(DecodingError::wrong_length(1, 0));
}
if data[0] != Self::DB_PREFIX {
return Err(DecodingError::wrong_prefix(Self::DB_PREFIX, data[0]));
}
<Self as crate::encoding::Decodable>::consensus_decode_whole(&data[1..], modules)
.map_err(DecodingError::from)
}
}
impl<T> DatabaseValue for T
where
T: Debug + Encodable + Decodable,
{
fn from_bytes(
data: &[u8],
modules: &ModuleDecoderRegistry,
) -> std::result::Result<Self, DecodingError> {
T::consensus_decode_whole(data, modules).map_err(DecodingError::from)
}
fn to_bytes(&self) -> Vec<u8> {
self.consensus_encode_to_vec()
}
}
#[macro_export]
macro_rules! impl_db_record {
(key = $key:ty, value = $val:ty, db_prefix = $db_prefix:expr_2021 $(, notify_on_modify = $notify:tt)? $(,)?) => {
impl $crate::db::DatabaseRecord for $key {
const DB_PREFIX: u8 = $db_prefix as u8;
$(const NOTIFY_ON_MODIFY: bool = $notify;)?
type Key = Self;
type Value = $val;
}
$(
impl_db_record! {
@impl_notify_marker key = $key, notify_on_modify = $notify
}
)?
};
(@impl_notify_marker key = $key:ty, notify_on_modify = true) => {
impl $crate::db::DatabaseKeyWithNotify for $key {}
};
(@impl_notify_marker key = $key:ty, notify_on_modify = false) => {};
}
#[macro_export]
macro_rules! impl_db_lookup{
(key = $key:ty $(, query_prefix = $query_prefix:ty)* $(,)?) => {
$(
impl $crate::db::DatabaseLookup for $query_prefix {
type Record = $key;
}
)*
};
}
#[derive(Debug, Encodable, Decodable, Serialize)]
pub struct DatabaseVersionKeyV0;
#[derive(Debug, Encodable, Decodable, Serialize)]
pub struct DatabaseVersionKey(pub ModuleInstanceId);
#[derive(Debug, Encodable, Decodable, Serialize, Clone, PartialOrd, Ord, PartialEq, Eq, Copy)]
pub struct DatabaseVersion(pub u64);
impl_db_record!(
key = DatabaseVersionKeyV0,
value = DatabaseVersion,
db_prefix = DbKeyPrefix::DatabaseVersion
);
impl_db_record!(
key = DatabaseVersionKey,
value = DatabaseVersion,
db_prefix = DbKeyPrefix::DatabaseVersion
);
impl std::fmt::Display for DatabaseVersion {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl DatabaseVersion {
pub fn increment(&self) -> Self {
Self(self.0 + 1)
}
}
impl std::fmt::Display for DbKeyPrefix {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
#[repr(u8)]
#[derive(Clone, EnumIter, Debug)]
pub enum DbKeyPrefix {
DatabaseVersion = 0x50,
ClientBackup = 0x51,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DecodingError {
#[error("Key had a wrong prefix, expected {expected} but got {found}")]
WrongPrefix { expected: u8, found: u8 },
#[error("Key had a wrong length, expected {expected} but got {found}")]
WrongLength { expected: usize, found: usize },
#[error("Other decoding error")]
Other(#[source] Box<dyn Error + Send + Sync>),
#[error("Invalid consensus encoding")]
Decode(#[from] DecodeError),
}
impl DecodingError {
pub fn other<E: Error + Send + Sync + 'static>(error: E) -> Self {
Self::Other(Box::new(error))
}
pub fn wrong_prefix(expected: u8, found: u8) -> Self {
Self::WrongPrefix { expected, found }
}
pub fn wrong_length(expected: usize, found: usize) -> Self {
Self::WrongLength { expected, found }
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DatabaseError {
#[error("Write-write conflict detected")]
WriteConflict,
#[error("Transaction snapshot is older than the retained write history: {0}")]
SnapshotTooOld(Box<dyn Error + Send + Sync>),
#[error("Transaction already consumed")]
TransactionConsumed,
#[error("Database backend error: {0}")]
DatabaseBackend(#[from] Box<dyn Error + Send + Sync>),
#[error("Database instance is not global")]
NotGlobal,
#[error("Database instance is not isolated")]
NotIsolated,
}
impl DatabaseError {
pub fn backend<E: Error + Send + Sync + 'static>(error: E) -> Self {
Self::DatabaseBackend(Box::new(error))
}
pub fn snapshot_too_old<E: Error + Send + Sync + 'static>(error: E) -> Self {
Self::SnapshotTooOld(Box::new(error))
}
}
#[macro_export]
macro_rules! push_db_pair_items {
($dbtx:ident, $prefix_type:expr_2021, $key_type:ty, $value_type:ty, $map:ident, $key_literal:literal) => {
let db_items =
$crate::db::IDatabaseTransactionOpsCoreTyped::find_by_prefix($dbtx, &$prefix_type)
.await
.map(|(key, val)| {
(
$crate::encoding::Encodable::consensus_encode_to_hex(&key),
val,
)
})
.collect::<BTreeMap<String, $value_type>>()
.await;
$map.insert($key_literal.to_string(), Box::new(db_items));
};
}
#[macro_export]
macro_rules! push_db_key_items {
($dbtx:ident, $prefix_type:expr_2021, $key_type:ty, $map:ident, $key_literal:literal) => {
let db_items =
$crate::db::IDatabaseTransactionOpsCoreTyped::find_by_prefix($dbtx, &$prefix_type)
.await
.map(|(key, _)| key)
.collect::<Vec<$key_type>>()
.await;
$map.insert($key_literal.to_string(), Box::new(db_items));
};
}
pub struct DbMigrationFnContext<'tx, C> {
dbtx: DatabaseTransaction<'tx>,
module_instance_id: Option<ModuleInstanceId>,
ctx: C,
__please_use_constructor: (),
}
impl<'tx, C> DbMigrationFnContext<'tx, C> {
pub fn new(
dbtx: DatabaseTransaction<'tx>,
module_instance_id: Option<ModuleInstanceId>,
ctx: C,
) -> Self {
dbtx.ensure_global().expect("Must pass global dbtx");
Self {
dbtx,
module_instance_id,
ctx,
__please_use_constructor: (),
}
}
pub fn map<R>(self, f: impl FnOnce(C) -> R) -> DbMigrationFnContext<'tx, R> {
DbMigrationFnContext::new(self.dbtx, self.module_instance_id, f(self.ctx))
}
#[doc(hidden)]
pub fn split_dbtx_ctx<'s>(&'s mut self) -> (&'s mut DatabaseTransaction<'tx>, &'s C) {
let Self { dbtx, ctx, .. } = self;
(dbtx, ctx)
}
pub fn dbtx(&'_ mut self) -> DatabaseTransaction<'_> {
if let Some(module_instance_id) = self.module_instance_id {
self.dbtx.to_ref_with_prefix_module_id(module_instance_id).0
} else {
self.dbtx.to_ref_nc()
}
}
#[doc(hidden)]
pub fn module_instance_id(&self) -> Option<ModuleInstanceId> {
self.module_instance_id
}
}
pub type GeneralDbMigrationFn = DbMigrationFn<()>;
pub type GeneralDbMigrationFnContext<'tx> = DbMigrationFnContext<'tx, ()>;
pub type ClientCoreDbMigrationFn = DbMigrationFn<()>;
pub type ClientCoreDbMigrationFnContext<'tx> = DbMigrationFnContext<'tx, ()>;
pub type DbMigrationFn<C> = Box<
maybe_add_send_sync!(
dyn for<'tx> Fn(
DbMigrationFnContext<'tx, C>,
) -> Pin<
Box<maybe_add_send!(dyn futures::Future<Output = Result<(), DbMigrationError>> + 'tx)>,
>
),
>;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DbMigrationError {
#[error("Database error")]
Database(#[from] DatabaseError),
#[error("Failed to consensus-decode a database entry")]
Decode(#[from] DecodeError),
#[error(
"On disk database version {on_disk} for module {kind} is higher than the code \
database version {target}"
)]
VersionTooHigh {
kind: String,
on_disk: DatabaseVersion,
target: DatabaseVersion,
},
#[error("Migration failed")]
Other(#[source] Box<dyn Error + Send + Sync>),
}
impl DbMigrationError {
pub fn other<E>(error: E) -> Self
where
E: Into<Box<dyn Error + Send + Sync>>,
{
Self::Other(error.into())
}
}
pub fn get_current_database_version<F>(
migrations: &BTreeMap<DatabaseVersion, F>,
) -> DatabaseVersion {
let versions = migrations.keys().copied().collect::<Vec<_>>();
if !versions
.windows(2)
.all(|window| window[0].increment() == window[1])
{
panic!("Database Migrations are not defined contiguously");
}
versions
.last()
.map_or(DatabaseVersion(0), DatabaseVersion::increment)
}
pub async fn apply_migrations<C>(
db: &Database,
ctx: C,
kind: String,
migrations: BTreeMap<DatabaseVersion, DbMigrationFn<C>>,
module_instance_id: Option<ModuleInstanceId>,
external_prefixes_above: Option<u8>,
) -> Result<(), DbMigrationError>
where
C: Clone,
{
let mut dbtx = db.begin_transaction().await;
apply_migrations_dbtx(
&mut dbtx.to_ref_nc(),
ctx,
kind,
migrations,
module_instance_id,
external_prefixes_above,
)
.await?;
Ok(dbtx.commit_tx_result().await?)
}
pub async fn apply_migrations_dbtx<C>(
global_dbtx: &mut DatabaseTransaction<'_>,
ctx: C,
kind: String,
migrations: BTreeMap<DatabaseVersion, DbMigrationFn<C>>,
module_instance_id: Option<ModuleInstanceId>,
external_prefixes_above: Option<u8>,
) -> Result<(), DbMigrationError>
where
C: Clone,
{
let is_new_db = global_dbtx
.raw_find_by_prefix(&[])
.await?
.filter(|(key, _v)| {
std::future::ready(
external_prefixes_above.is_none_or(|external_prefixes_above| {
!key.is_empty() && key[0] < external_prefixes_above
}),
)
})
.next()
.await
.is_none();
let target_db_version = get_current_database_version(&migrations);
create_database_version_dbtx(
global_dbtx,
target_db_version,
module_instance_id,
kind.clone(),
is_new_db,
)
.await;
let module_instance_id_key = module_instance_id_or_global(module_instance_id);
let disk_version = global_dbtx
.get_value(&DatabaseVersionKey(module_instance_id_key))
.await;
let db_version = if let Some(disk_version) = disk_version {
let mut current_db_version = disk_version;
if current_db_version > target_db_version {
return Err(DbMigrationError::VersionTooHigh {
kind,
on_disk: current_db_version,
target: target_db_version,
});
}
while current_db_version < target_db_version {
if let Some(migration) = migrations.get(¤t_db_version) {
info!(target: LOG_DB, ?kind, ?current_db_version, ?target_db_version, "Migrating module...");
migration(DbMigrationFnContext::new(
global_dbtx.to_ref_nc(),
module_instance_id,
ctx.clone(),
))
.await?;
} else {
warn!(target: LOG_DB, ?current_db_version, "Missing server db migration");
}
current_db_version = current_db_version.increment();
global_dbtx
.insert_entry(
&DatabaseVersionKey(module_instance_id_key),
¤t_db_version,
)
.await;
}
current_db_version
} else {
target_db_version
};
debug!(target: LOG_DB, ?kind, ?db_version, "DB Version");
Ok(())
}
pub async fn create_database_version(
db: &Database,
target_db_version: DatabaseVersion,
module_instance_id: Option<ModuleInstanceId>,
kind: String,
is_new_db: bool,
) -> Result<(), DbMigrationError> {
let mut dbtx = db.begin_transaction().await;
create_database_version_dbtx(
&mut dbtx.to_ref_nc(),
target_db_version,
module_instance_id,
kind,
is_new_db,
)
.await;
dbtx.commit_tx_result().await?;
Ok(())
}
pub async fn create_database_version_dbtx(
global_dbtx: &mut DatabaseTransaction<'_>,
target_db_version: DatabaseVersion,
module_instance_id: Option<ModuleInstanceId>,
kind: String,
is_new_db: bool,
) {
let key_module_instance_id = module_instance_id_or_global(module_instance_id);
if global_dbtx
.get_value(&DatabaseVersionKey(key_module_instance_id))
.await
.is_none()
{
let current_version_in_module = if let Some(module_instance_id) = module_instance_id {
remove_current_db_version_if_exists(
&mut global_dbtx
.to_ref_with_prefix_module_id(module_instance_id)
.0
.into_nc(),
is_new_db,
target_db_version,
)
.await
} else {
remove_current_db_version_if_exists(
&mut global_dbtx.to_ref().into_nc(),
is_new_db,
target_db_version,
)
.await
};
debug!(target: LOG_DB, ?kind, ?current_version_in_module, ?target_db_version, ?is_new_db, "Creating DatabaseVersionKey...");
global_dbtx
.insert_new_entry(
&DatabaseVersionKey(key_module_instance_id),
¤t_version_in_module,
)
.await;
}
}
async fn remove_current_db_version_if_exists(
version_dbtx: &mut DatabaseTransaction<'_>,
is_new_db: bool,
target_db_version: DatabaseVersion,
) -> DatabaseVersion {
let current_version_in_module = version_dbtx.remove_entry(&DatabaseVersionKeyV0).await;
match current_version_in_module {
Some(database_version) => database_version,
None if is_new_db => target_db_version,
None => DatabaseVersion(0),
}
}
fn module_instance_id_or_global(module_instance_id: Option<ModuleInstanceId>) -> ModuleInstanceId {
module_instance_id.unwrap_or_else(|| MODULE_GLOBAL_PREFIX.into())
}
#[allow(unused_imports)]
mod test_utils;
pub async fn find_by_prefix_sorted_descending<'r, 'inner, KP>(
tx: &'r mut (dyn IDatabaseTransaction + 'inner),
decoders: ModuleDecoderRegistry,
key_prefix: &KP,
) -> impl Stream<
Item = (
KP::Record,
<<KP as DatabaseLookup>::Record as DatabaseRecord>::Value,
),
>
+ 'r
+ use<'r, KP>
where
'inner: 'r,
KP: DatabaseLookup,
KP::Record: DatabaseKey,
{
debug!(target: LOG_DB, "find by prefix sorted descending");
let prefix_bytes = key_prefix.to_bytes();
tx.raw_find_by_prefix_sorted_descending(&prefix_bytes)
.await
.expect("Error doing prefix search in database")
.map(move |(key_bytes, value_bytes)| {
let key = decode_key_expect(&key_bytes, &decoders);
let value = decode_value_expect(&value_bytes, &decoders, &key_bytes);
(key, value)
})
}
pub async fn verify_module_db_integrity_dbtx(
dbtx: &mut DatabaseTransaction<'_>,
module_id: ModuleInstanceId,
module_kind: ModuleKind,
prefixes: &BTreeSet<u8>,
) {
let module_db_prefix = module_instance_id_to_byte_prefix(module_id);
if module_id < 250 {
assert_eq!(module_db_prefix.len(), 2);
}
let mut records = dbtx
.raw_find_by_prefix(&module_db_prefix)
.await
.expect("DB fail");
while let Some((k, v)) = records.next().await {
assert!(
prefixes.contains(&k[module_db_prefix.len()]),
"Unexpected module {module_kind} {module_id} db record found: {}: {}",
k.as_hex(),
v.as_hex()
);
}
}
#[cfg(test)]
mod tests;