use std::{marker::PhantomData, ops::Deref, sync::Arc};
use actionable::{Action, Identifier};
use arc_bytes::serde::Bytes;
use async_trait::async_trait;
use futures::{future::BoxFuture, Future, FutureExt};
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;
use crate::{
document::{CollectionDocument, CollectionHeader, Document, HasHeader, Header, OwnedDocument},
key::{IntoPrefixRange, Key, KeyEncoding},
permissions::Permissions,
schema::{
self,
view::{self, map::MappedDocuments},
Map, MappedValue, Nameable, NamedReference, Schema, SchemaName, SerializedCollection,
},
transaction, Error,
};
mod has_session;
mod lowlevel;
pub use self::{
has_session::HasSession,
lowlevel::{AsyncLowLevelConnection, LowLevelConnection},
};
pub trait Connection: LowLevelConnection + Sized + Send + Sync {
type Storage: StorageConnection<Database = Self>;
fn storage(&self) -> Self::Storage;
fn collection<C: schema::Collection>(&self) -> Collection<'_, Self, C> {
Collection::new(self)
}
fn view<V: schema::SerializedView>(&'_ self) -> View<'_, Self, V, V::Key> {
View::new(self)
}
fn list_executed_transactions(
&self,
starting_id: Option<u64>,
result_limit: Option<u32>,
) -> Result<Vec<transaction::Executed>, Error>;
fn last_transaction_id(&self) -> Result<Option<u64>, Error>;
fn compact(&self) -> Result<(), crate::Error>;
fn compact_collection<C: schema::Collection>(&self) -> Result<(), crate::Error> {
self.compact_collection_by_name(C::collection_name())
}
fn compact_key_value_store(&self) -> Result<(), crate::Error>;
}
pub struct Collection<'a, Cn, Cl> {
connection: &'a Cn,
_phantom: PhantomData<Cl>,
}
impl<'a, Cn, Cl> Clone for Collection<'a, Cn, Cl> {
fn clone(&self) -> Self {
Self {
connection: self.connection,
_phantom: PhantomData,
}
}
}
impl<'a, Cn, Cl> Collection<'a, Cn, Cl>
where
Cn: Connection,
Cl: schema::Collection,
{
fn new(connection: &'a Cn) -> Self {
Self {
connection,
_phantom: PhantomData::default(),
}
}
pub fn push(
&self,
item: &<Cl as SerializedCollection>::Contents,
) -> Result<CollectionHeader<Cl::PrimaryKey>, crate::Error>
where
Cl: schema::SerializedCollection,
{
let contents = Cl::serialize(item)?;
if let Some(natural_id) = Cl::natural_id(item) {
self.insert_bytes(natural_id, contents)
} else {
self.push_bytes(contents)
}
}
pub fn push_bytes<B: Into<Bytes> + Send>(
&self,
contents: B,
) -> Result<CollectionHeader<Cl::PrimaryKey>, crate::Error> {
self.connection
.insert::<Cl, _, B>(Option::<Cl::PrimaryKey>::None, contents)
}
pub fn insert<PrimaryKey>(
&self,
id: PrimaryKey,
item: &<Cl as SerializedCollection>::Contents,
) -> Result<CollectionHeader<Cl::PrimaryKey>, crate::Error>
where
Cl: schema::SerializedCollection,
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
let contents = Cl::serialize(item)?;
self.connection.insert::<Cl, _, _>(Some(id), contents)
}
pub fn insert_bytes<B: Into<Bytes> + Send>(
&self,
id: Cl::PrimaryKey,
contents: B,
) -> Result<CollectionHeader<Cl::PrimaryKey>, crate::Error> {
self.connection.insert::<Cl, _, B>(Some(id), contents)
}
pub fn update<D: Document<Cl> + Send + Sync>(&self, doc: &mut D) -> Result<(), Error> {
self.connection.update::<Cl, D>(doc)
}
pub fn overwrite<D: Document<Cl> + Send + Sync>(&self, doc: &mut D) -> Result<(), Error> {
let contents = doc.bytes()?;
doc.set_collection_header(self.connection.overwrite::<Cl, _>(doc.id(), contents)?)
}
pub fn get<PrimaryKey>(&self, id: PrimaryKey) -> Result<Option<OwnedDocument>, Error>
where
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
self.connection.get::<Cl, _>(id)
}
pub fn get_multiple<DocumentIds, PrimaryKey, I>(
&self,
ids: DocumentIds,
) -> Result<Vec<OwnedDocument>, Error>
where
DocumentIds: IntoIterator<Item = PrimaryKey, IntoIter = I> + Send + Sync,
I: Iterator<Item = PrimaryKey> + Send + Sync,
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
self.connection.get_multiple::<Cl, _, _, _>(ids)
}
pub fn list<PrimaryKey, R>(&'a self, ids: R) -> List<'a, Cn, Cl, PrimaryKey>
where
R: Into<Range<PrimaryKey>>,
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
List::new(PossiblyOwned::Borrowed(self), ids.into())
}
pub fn list_with_prefix(&'a self, prefix: Cl::PrimaryKey) -> List<'a, Cn, Cl, Cl::PrimaryKey>
where
Cl::PrimaryKey: IntoPrefixRange,
{
List::new(PossiblyOwned::Borrowed(self), prefix.into_prefix_range())
}
pub fn all(&'a self) -> List<'a, Cn, Cl, Cl::PrimaryKey> {
List::new(PossiblyOwned::Borrowed(self), Range::from(..))
}
pub fn delete<H: HasHeader + Send + Sync>(&self, doc: &H) -> Result<(), Error> {
self.connection.delete::<Cl, H>(doc)
}
}
#[must_use]
pub struct List<'a, Cn, Cl, PrimaryKey>
where
Cl: schema::Collection,
{
collection: PossiblyOwned<'a, Collection<'a, Cn, Cl>>,
range: Range<PrimaryKey>,
sort: Sort,
limit: Option<u32>,
}
impl<'a, Cn, Cl, PrimaryKey> List<'a, Cn, Cl, PrimaryKey>
where
Cl: schema::Collection,
Cn: Connection,
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
pub(crate) fn new(
collection: PossiblyOwned<'a, Collection<'a, Cn, Cl>>,
range: Range<PrimaryKey>,
) -> Self {
Self {
collection,
range,
sort: Sort::Ascending,
limit: None,
}
}
pub fn ascending(mut self) -> Self {
self.sort = Sort::Ascending;
self
}
pub fn descending(mut self) -> Self {
self.sort = Sort::Descending;
self
}
pub fn limit(mut self, maximum_results: u32) -> Self {
self.limit = Some(maximum_results);
self
}
pub fn count(self) -> Result<u64, Error> {
let Self {
collection, range, ..
} = self;
collection.connection.count::<Cl, _, _>(range)
}
pub fn headers(self) -> Result<Vec<Header>, Error> {
let Self {
collection,
range,
sort,
limit,
..
} = self;
collection
.connection
.list_headers::<Cl, _, _>(range, sort, limit)
}
pub fn query(self) -> Result<Vec<OwnedDocument>, Error> {
let Self {
collection,
range,
sort,
limit,
} = self;
collection.connection.list::<Cl, _, _>(range, sort, limit)
}
}
#[must_use]
pub struct View<'a, Cn, V: schema::SerializedView, Key> {
connection: &'a Cn,
pub key: Option<QueryKey<Key>>,
pub access_policy: AccessPolicy,
pub sort: Sort,
pub limit: Option<u32>,
_view: PhantomData<V>,
}
impl<'a, Cn, V, Key> View<'a, Cn, V, Key>
where
V: schema::SerializedView,
Cn: Connection,
Key: for<'k> KeyEncoding<'k, V::Key>,
{
fn new(connection: &'a Cn) -> Self {
Self {
connection,
key: None,
access_policy: AccessPolicy::UpdateBefore,
sort: Sort::Ascending,
limit: None,
_view: PhantomData,
}
}
pub fn with_key<K: for<'k> KeyEncoding<'k, V::Key>>(self, key: K) -> View<'a, Cn, V, K> {
View {
connection: self.connection,
key: Some(QueryKey::Matches(key)),
access_policy: self.access_policy,
sort: self.sort,
limit: self.limit,
_view: PhantomData,
}
}
pub fn with_keys<K, IntoIter: IntoIterator<Item = K>>(
self,
keys: IntoIter,
) -> View<'a, Cn, V, K> {
View {
connection: self.connection,
key: Some(QueryKey::Multiple(keys.into_iter().collect())),
access_policy: self.access_policy,
sort: self.sort,
limit: self.limit,
_view: PhantomData,
}
}
pub fn with_key_range<K, R: Into<Range<K>>>(self, range: R) -> View<'a, Cn, V, K> {
View {
connection: self.connection,
key: Some(QueryKey::Range(range.into())),
access_policy: self.access_policy,
sort: self.sort,
limit: self.limit,
_view: PhantomData,
}
}
pub fn with_key_prefix(self, prefix: V::Key) -> View<'a, Cn, V, V::Key>
where
V::Key: IntoPrefixRange,
{
View {
connection: self.connection,
key: Some(QueryKey::Range(prefix.into_prefix_range())),
access_policy: self.access_policy,
sort: self.sort,
limit: self.limit,
_view: PhantomData,
}
}
pub fn with_access_policy(mut self, policy: AccessPolicy) -> Self {
self.access_policy = policy;
self
}
pub fn ascending(mut self) -> Self {
self.sort = Sort::Ascending;
self
}
pub fn descending(mut self) -> Self {
self.sort = Sort::Descending;
self
}
pub fn limit(mut self, maximum_results: u32) -> Self {
self.limit = Some(maximum_results);
self
}
pub fn query(self) -> Result<ViewMappings<V>, Error> {
self.connection
.query::<V, Key>(self.key, self.sort, self.limit, self.access_policy)
}
pub fn query_with_docs(self) -> Result<MappedDocuments<OwnedDocument, V>, Error> {
self.connection.query_with_docs::<V, Key>(
self.key,
self.sort,
self.limit,
self.access_policy,
)
}
pub fn query_with_collection_docs(
self,
) -> Result<MappedDocuments<CollectionDocument<V::Collection>, V>, Error>
where
V::Collection: SerializedCollection,
<V::Collection as SerializedCollection>::Contents: std::fmt::Debug,
{
self.connection.query_with_collection_docs::<V, Key>(
self.key,
self.sort,
self.limit,
self.access_policy,
)
}
pub fn reduce(self) -> Result<V::Value, Error> {
self.connection
.reduce::<V, Key>(self.key, self.access_policy)
}
pub fn reduce_grouped(self) -> Result<GroupedReductions<V>, Error> {
self.connection
.reduce_grouped::<V, Key>(self.key, self.access_policy)
}
pub fn delete_docs(self) -> Result<u64, Error> {
self.connection
.delete_docs::<V, Key>(self.key, self.access_policy)
}
}
pub type ViewMappings<V> = Vec<Map<<V as schema::View>::Key, <V as schema::View>::Value>>;
pub type GroupedReductions<V> =
Vec<MappedValue<<V as schema::View>::Key, <V as schema::View>::Value>>;
#[async_trait]
pub trait AsyncConnection: AsyncLowLevelConnection + Sized + Send + Sync {
type Storage: AsyncStorageConnection<Database = Self>;
fn storage(&self) -> Self::Storage;
fn collection<C: schema::Collection>(&self) -> AsyncCollection<'_, Self, C> {
AsyncCollection::new(self)
}
fn view<V: schema::SerializedView>(&'_ self) -> AsyncView<'_, Self, V> {
AsyncView::new(self)
}
async fn list_executed_transactions(
&self,
starting_id: Option<u64>,
result_limit: Option<u32>,
) -> Result<Vec<transaction::Executed>, Error>;
async fn last_transaction_id(&self) -> Result<Option<u64>, Error>;
async fn compact(&self) -> Result<(), crate::Error>;
async fn compact_collection<C: schema::Collection>(&self) -> Result<(), crate::Error> {
self.compact_collection_by_name(C::collection_name()).await
}
async fn compact_key_value_store(&self) -> Result<(), crate::Error>;
}
pub struct AsyncCollection<'a, Cn, Cl> {
connection: &'a Cn,
_phantom: PhantomData<Cl>,
}
impl<'a, Cn, Cl> Clone for AsyncCollection<'a, Cn, Cl> {
fn clone(&self) -> Self {
Self {
connection: self.connection,
_phantom: PhantomData,
}
}
}
impl<'a, Cn, Cl> AsyncCollection<'a, Cn, Cl>
where
Cn: AsyncConnection,
Cl: schema::Collection,
{
fn new(connection: &'a Cn) -> Self {
Self {
connection,
_phantom: PhantomData::default(),
}
}
pub async fn push(
&self,
item: &<Cl as SerializedCollection>::Contents,
) -> Result<CollectionHeader<Cl::PrimaryKey>, crate::Error>
where
Cl: schema::SerializedCollection,
{
let contents = Cl::serialize(item)?;
if let Some(natural_id) = Cl::natural_id(item) {
self.insert_bytes(natural_id, contents).await
} else {
self.push_bytes(contents).await
}
}
pub async fn push_bytes<B: Into<Bytes> + Send>(
&self,
contents: B,
) -> Result<CollectionHeader<Cl::PrimaryKey>, crate::Error> {
self.connection
.insert::<Cl, _, B>(Option::<Cl::PrimaryKey>::None, contents)
.await
}
pub async fn insert<PrimaryKey>(
&self,
id: PrimaryKey,
item: &<Cl as SerializedCollection>::Contents,
) -> Result<CollectionHeader<Cl::PrimaryKey>, crate::Error>
where
Cl: schema::SerializedCollection,
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
let contents = Cl::serialize(item)?;
self.connection.insert::<Cl, _, _>(Some(id), contents).await
}
pub async fn insert_bytes<B: Into<Bytes> + Send>(
&self,
id: Cl::PrimaryKey,
contents: B,
) -> Result<CollectionHeader<Cl::PrimaryKey>, crate::Error> {
self.connection.insert::<Cl, _, B>(Some(id), contents).await
}
pub async fn update<D: Document<Cl> + Send + Sync>(&self, doc: &mut D) -> Result<(), Error> {
self.connection.update::<Cl, D>(doc).await
}
pub async fn overwrite<D: Document<Cl> + Send + Sync>(&self, doc: &mut D) -> Result<(), Error> {
let contents = doc.bytes()?;
doc.set_collection_header(
self.connection
.overwrite::<Cl, _>(doc.id(), contents)
.await?,
)
}
pub async fn get<PrimaryKey>(&self, id: PrimaryKey) -> Result<Option<OwnedDocument>, Error>
where
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
self.connection.get::<Cl, _>(id).await
}
pub async fn get_multiple<DocumentIds, PrimaryKey, I>(
&self,
ids: DocumentIds,
) -> Result<Vec<OwnedDocument>, Error>
where
DocumentIds: IntoIterator<Item = PrimaryKey, IntoIter = I> + Send + Sync,
I: Iterator<Item = PrimaryKey> + Send + Sync,
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
self.connection.get_multiple::<Cl, _, _, _>(ids).await
}
pub fn list<PrimaryKey, R>(&'a self, ids: R) -> AsyncList<'a, Cn, Cl, PrimaryKey>
where
R: Into<Range<PrimaryKey>>,
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
AsyncList::new(PossiblyOwned::Borrowed(self), ids.into())
}
pub fn list_with_prefix(
&'a self,
prefix: Cl::PrimaryKey,
) -> AsyncList<'a, Cn, Cl, Cl::PrimaryKey>
where
Cl::PrimaryKey: IntoPrefixRange,
{
AsyncList::new(PossiblyOwned::Borrowed(self), prefix.into_prefix_range())
}
pub fn all(&'a self) -> AsyncList<'a, Cn, Cl, Cl::PrimaryKey> {
AsyncList::new(PossiblyOwned::Borrowed(self), Range::from(..))
}
pub async fn delete<H: HasHeader + Send + Sync>(&self, doc: &H) -> Result<(), Error> {
self.connection.delete::<Cl, H>(doc).await
}
}
pub(crate) struct AsyncListBuilder<'a, Cn, Cl, PrimaryKey>
where
Cl: schema::Collection,
{
collection: PossiblyOwned<'a, AsyncCollection<'a, Cn, Cl>>,
range: Range<PrimaryKey>,
sort: Sort,
limit: Option<u32>,
}
pub(crate) enum PossiblyOwned<'a, Cl> {
Owned(Cl),
Borrowed(&'a Cl),
}
impl<'a, Cl> Deref for PossiblyOwned<'a, Cl> {
type Target = Cl;
fn deref(&self) -> &Self::Target {
match self {
PossiblyOwned::Owned(value) => value,
PossiblyOwned::Borrowed(value) => value,
}
}
}
pub(crate) enum ListState<'a, Cn, Cl, PrimaryKey>
where
Cl: schema::Collection,
{
Pending(Option<AsyncListBuilder<'a, Cn, Cl, PrimaryKey>>),
Executing(BoxFuture<'a, Result<Vec<OwnedDocument>, Error>>),
}
#[must_use]
pub struct AsyncList<'a, Cn, Cl, PrimaryKey>
where
Cl: schema::Collection,
{
state: ListState<'a, Cn, Cl, PrimaryKey>,
}
impl<'a, Cn, Cl, PrimaryKey> AsyncList<'a, Cn, Cl, PrimaryKey>
where
Cl: schema::Collection,
Cn: AsyncConnection,
PrimaryKey: for<'k> KeyEncoding<'k, Cl::PrimaryKey>,
{
pub(crate) fn new(
collection: PossiblyOwned<'a, AsyncCollection<'a, Cn, Cl>>,
range: Range<PrimaryKey>,
) -> Self {
Self {
state: ListState::Pending(Some(AsyncListBuilder {
collection,
range,
sort: Sort::Ascending,
limit: None,
})),
}
}
fn builder(&mut self) -> &mut AsyncListBuilder<'a, Cn, Cl, PrimaryKey> {
if let ListState::Pending(Some(builder)) = &mut self.state {
builder
} else {
unreachable!("Attempted to use after retrieving the result")
}
}
pub fn ascending(mut self) -> Self {
self.builder().sort = Sort::Ascending;
self
}
pub fn descending(mut self) -> Self {
self.builder().sort = Sort::Descending;
self
}
pub fn limit(mut self, maximum_results: u32) -> Self {
self.builder().limit = Some(maximum_results);
self
}
pub async fn headers(self) -> Result<Vec<Header>, Error> {
match self.state {
ListState::Pending(Some(AsyncListBuilder {
collection,
range,
sort,
limit,
..
})) => {
collection
.connection
.list_headers::<Cl, _, _>(range, sort, limit)
.await
}
_ => unreachable!("Attempted to use after retrieving the result"),
}
}
pub async fn count(self) -> Result<u64, Error> {
match self.state {
ListState::Pending(Some(AsyncListBuilder {
collection, range, ..
})) => collection.connection.count::<Cl, _, _>(range).await,
_ => unreachable!("Attempted to use after retrieving the result"),
}
}
}
#[allow(clippy::type_repetition_in_bounds)]
impl<'a, Cn, Cl, PrimaryKey> Future for AsyncList<'a, Cn, Cl, PrimaryKey>
where
Cn: AsyncConnection,
Cl: schema::Collection + Unpin,
Cl::PrimaryKey: Unpin,
PrimaryKey: Unpin + for<'k> KeyEncoding<'k, Cl::PrimaryKey> + 'a,
{
type Output = Result<Vec<OwnedDocument>, Error>;
fn poll(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
match &mut self.state {
ListState::Executing(future) => future.as_mut().poll(cx),
ListState::Pending(builder) => {
let AsyncListBuilder {
collection,
range,
sort,
limit,
} = builder.take().unwrap();
let future = async move {
collection
.connection
.list::<Cl, _, _>(range, sort, limit)
.await
}
.boxed();
self.state = ListState::Executing(future);
self.poll(cx)
}
}
}
}
#[must_use]
pub struct AsyncView<'a, Cn, V: schema::SerializedView> {
connection: &'a Cn,
pub key: Option<QueryKey<V::Key>>,
pub access_policy: AccessPolicy,
pub sort: Sort,
pub limit: Option<u32>,
}
impl<'a, Cn, V> AsyncView<'a, Cn, V>
where
V: schema::SerializedView,
Cn: AsyncConnection,
{
fn new(connection: &'a Cn) -> Self {
Self {
connection,
key: None,
access_policy: AccessPolicy::UpdateBefore,
sort: Sort::Ascending,
limit: None,
}
}
pub fn with_key(mut self, key: V::Key) -> Self {
self.key = Some(QueryKey::Matches(key));
self
}
pub fn with_keys<IntoIter: IntoIterator<Item = V::Key>>(mut self, keys: IntoIter) -> Self {
self.key = Some(QueryKey::Multiple(keys.into_iter().collect()));
self
}
pub fn with_key_range<R: Into<Range<V::Key>>>(mut self, range: R) -> Self {
self.key = Some(QueryKey::Range(range.into()));
self
}
pub fn with_key_prefix(mut self, prefix: V::Key) -> Self
where
V::Key: IntoPrefixRange,
{
self.key = Some(QueryKey::Range(prefix.into_prefix_range()));
self
}
pub fn with_access_policy(mut self, policy: AccessPolicy) -> Self {
self.access_policy = policy;
self
}
pub fn ascending(mut self) -> Self {
self.sort = Sort::Ascending;
self
}
pub fn descending(mut self) -> Self {
self.sort = Sort::Descending;
self
}
pub fn limit(mut self, maximum_results: u32) -> Self {
self.limit = Some(maximum_results);
self
}
pub async fn query(self) -> Result<Vec<Map<V::Key, V::Value>>, Error> {
self.connection
.query::<V>(self.key, self.sort, self.limit, self.access_policy)
.await
}
pub async fn query_with_docs(self) -> Result<MappedDocuments<OwnedDocument, V>, Error> {
self.connection
.query_with_docs::<V>(self.key, self.sort, self.limit, self.access_policy)
.await
}
pub async fn query_with_collection_docs(
self,
) -> Result<MappedDocuments<CollectionDocument<V::Collection>, V>, Error>
where
V::Collection: SerializedCollection,
<V::Collection as SerializedCollection>::Contents: std::fmt::Debug,
{
self.connection
.query_with_collection_docs::<V>(self.key, self.sort, self.limit, self.access_policy)
.await
}
pub async fn reduce(self) -> Result<V::Value, Error> {
self.connection
.reduce::<V>(self.key, self.access_policy)
.await
}
pub async fn reduce_grouped(self) -> Result<Vec<MappedValue<V::Key, V::Value>>, Error> {
self.connection
.reduce_grouped::<V>(self.key, self.access_policy)
.await
}
pub async fn delete_docs(self) -> Result<u64, Error> {
self.connection
.delete_docs::<V>(self.key, self.access_policy)
.await
}
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub enum Sort {
Ascending,
Descending,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum QueryKey<K> {
Matches(K),
Range(Range<K>),
Multiple(Vec<K>),
}
#[allow(clippy::use_self)] impl<K> QueryKey<K> {
pub fn serialized<ViewKey>(&self) -> Result<QueryKey<Bytes>, Error>
where
K: for<'k> KeyEncoding<'k, ViewKey>,
ViewKey: for<'k> Key<'k>,
{
match self {
Self::Matches(key) => key
.as_ord_bytes()
.map_err(|err| Error::Database(view::Error::key_serialization(err).to_string()))
.map(|v| QueryKey::Matches(Bytes::from(v.to_vec()))),
Self::Range(range) => Ok(QueryKey::Range(range.as_ord_bytes().map_err(|err| {
Error::Database(view::Error::key_serialization(err).to_string())
})?)),
Self::Multiple(keys) => {
let keys = keys
.iter()
.map(|key| {
key.as_ord_bytes()
.map(|key| Bytes::from(key.to_vec()))
.map_err(|err| {
Error::Database(view::Error::key_serialization(err).to_string())
})
})
.collect::<Result<Vec<_>, Error>>()?;
Ok(QueryKey::Multiple(keys))
}
}
}
}
#[allow(clippy::use_self)] impl<'a, T> QueryKey<T>
where
T: AsRef<[u8]>,
{
pub fn deserialized<K: for<'k> Key<'k>>(&self) -> Result<QueryKey<K>, Error> {
match self {
Self::Matches(key) => K::from_ord_bytes(key.as_ref())
.map_err(|err| Error::Database(view::Error::key_serialization(err).to_string()))
.map(QueryKey::Matches),
Self::Range(range) => Ok(QueryKey::Range(range.deserialize().map_err(|err| {
Error::Database(view::Error::key_serialization(err).to_string())
})?)),
Self::Multiple(keys) => {
let keys = keys
.iter()
.map(|key| {
K::from_ord_bytes(key.as_ref()).map_err(|err| {
Error::Database(view::Error::key_serialization(err).to_string())
})
})
.collect::<Result<Vec<_>, Error>>()?;
Ok(QueryKey::Multiple(keys))
}
}
}
}
#[derive(Serialize, Deserialize, Default, Debug, Copy, Clone, Eq, PartialEq)]
#[must_use]
pub struct Range<T> {
pub start: Bound<T>,
pub end: Bound<T>,
}
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Eq, PartialEq)]
#[must_use]
pub enum Bound<T> {
Unbounded,
Included(T),
Excluded(T),
}
impl<T> Default for Bound<T> {
fn default() -> Self {
Self::Unbounded
}
}
impl<T> Range<T> {
#[allow(clippy::missing_const_for_fn)]
pub fn after(mut self, excluded_start: T) -> Self {
self.start = Bound::Excluded(excluded_start);
self
}
#[allow(clippy::missing_const_for_fn)]
pub fn start_at(mut self, included_start: T) -> Self {
self.start = Bound::Included(included_start);
self
}
#[allow(clippy::missing_const_for_fn)]
pub fn before(mut self, excluded_end: T) -> Self {
self.end = Bound::Excluded(excluded_end);
self
}
#[allow(clippy::missing_const_for_fn)]
pub fn end_at(mut self, included_end: T) -> Self {
self.end = Bound::Included(included_end);
self
}
pub fn map<U, F: Fn(T) -> U>(self, map: F) -> Range<U> {
Range {
start: self.start.map(&map),
end: self.end.map(&map),
}
}
pub fn map_result<U, E, F: Fn(T) -> Result<U, E>>(self, map: F) -> Result<Range<U>, E> {
Ok(Range {
start: self.start.map_result(&map)?,
end: self.end.map_result(&map)?,
})
}
pub fn map_ref<U: ?Sized, F: Fn(&T) -> &U>(&self, map: F) -> Range<&U> {
Range {
start: self.start.map_ref(&map),
end: self.end.map_ref(&map),
}
}
}
#[test]
fn range_constructors() {
assert_eq!(
Range::default().after(1_u32),
Range {
start: Bound::Excluded(1),
end: Bound::Unbounded
}
);
assert_eq!(
Range::default().start_at(1_u32),
Range {
start: Bound::Included(1),
end: Bound::Unbounded
}
);
assert_eq!(
Range::default().before(1_u32),
Range {
start: Bound::Unbounded,
end: Bound::Excluded(1),
}
);
assert_eq!(
Range::default().end_at(1_u32),
Range {
start: Bound::Unbounded,
end: Bound::Included(1),
}
);
}
impl<'a, T> Range<T> {
pub fn as_ord_bytes<K>(&'a self) -> Result<Range<Bytes>, T::Error>
where
T: KeyEncoding<'a, K>,
K: for<'k> Key<'k>,
{
Ok(Range {
start: self.start.as_ord_bytes()?,
end: self.end.as_ord_bytes()?,
})
}
}
impl<'a, B> Range<B>
where
B: AsRef<[u8]>,
{
pub fn deserialize<T: for<'k> Key<'k>>(
&'a self,
) -> Result<Range<T>, <T as KeyEncoding<'_, T>>::Error> {
Ok(Range {
start: self.start.deserialize()?,
end: self.start.deserialize()?,
})
}
}
impl<T> Bound<T> {
pub fn map<U, F: Fn(T) -> U>(self, map: F) -> Bound<U> {
match self {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(value) => Bound::Included(map(value)),
Bound::Excluded(value) => Bound::Excluded(map(value)),
}
}
pub fn map_result<U, E, F: Fn(T) -> Result<U, E>>(self, map: F) -> Result<Bound<U>, E> {
Ok(match self {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(value) => Bound::Included(map(value)?),
Bound::Excluded(value) => Bound::Excluded(map(value)?),
})
}
pub fn map_ref<U: ?Sized, F: Fn(&T) -> &U>(&self, map: F) -> Bound<&U> {
match self {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(value) => Bound::Included(map(value)),
Bound::Excluded(value) => Bound::Excluded(map(value)),
}
}
}
impl<'a, T> Bound<T> {
pub fn as_ord_bytes<K>(&'a self) -> Result<Bound<Bytes>, T::Error>
where
T: KeyEncoding<'a, K>,
K: for<'k> Key<'k>,
{
match self {
Bound::Unbounded => Ok(Bound::Unbounded),
Bound::Included(value) => {
Ok(Bound::Included(Bytes::from(value.as_ord_bytes()?.to_vec())))
}
Bound::Excluded(value) => {
Ok(Bound::Excluded(Bytes::from(value.as_ord_bytes()?.to_vec())))
}
}
}
}
impl<'a, B> Bound<B>
where
B: AsRef<[u8]>,
{
pub fn deserialize<T: for<'k> Key<'k>>(
&'a self,
) -> Result<Bound<T>, <T as KeyEncoding<'_, T>>::Error> {
match self {
Bound::Unbounded => Ok(Bound::Unbounded),
Bound::Included(value) => Ok(Bound::Included(T::from_ord_bytes(value.as_ref())?)),
Bound::Excluded(value) => Ok(Bound::Excluded(T::from_ord_bytes(value.as_ref())?)),
}
}
}
impl<T> std::ops::RangeBounds<T> for Range<T> {
fn start_bound(&self) -> std::ops::Bound<&T> {
std::ops::Bound::from(&self.start)
}
fn end_bound(&self) -> std::ops::Bound<&T> {
std::ops::Bound::from(&self.end)
}
}
impl<'a, T> From<&'a Bound<T>> for std::ops::Bound<&'a T> {
fn from(bound: &'a Bound<T>) -> Self {
match bound {
Bound::Unbounded => std::ops::Bound::Unbounded,
Bound::Included(value) => std::ops::Bound::Included(value),
Bound::Excluded(value) => std::ops::Bound::Excluded(value),
}
}
}
impl<T> From<std::ops::Range<T>> for Range<T> {
fn from(range: std::ops::Range<T>) -> Self {
Self {
start: Bound::Included(range.start),
end: Bound::Excluded(range.end),
}
}
}
impl<T> From<std::ops::RangeFrom<T>> for Range<T> {
fn from(range: std::ops::RangeFrom<T>) -> Self {
Self {
start: Bound::Included(range.start),
end: Bound::Unbounded,
}
}
}
impl<T> From<std::ops::RangeTo<T>> for Range<T> {
fn from(range: std::ops::RangeTo<T>) -> Self {
Self {
start: Bound::Unbounded,
end: Bound::Excluded(range.end),
}
}
}
impl<T: Clone> From<std::ops::RangeInclusive<T>> for Range<T> {
fn from(range: std::ops::RangeInclusive<T>) -> Self {
Self {
start: Bound::Included(range.start().clone()),
end: Bound::Included(range.end().clone()),
}
}
}
impl<T> From<std::ops::RangeToInclusive<T>> for Range<T> {
fn from(range: std::ops::RangeToInclusive<T>) -> Self {
Self {
start: Bound::Unbounded,
end: Bound::Included(range.end),
}
}
}
impl<T> From<std::ops::RangeFull> for Range<T> {
fn from(_: std::ops::RangeFull) -> Self {
Self {
start: Bound::Unbounded,
end: Bound::Unbounded,
}
}
}
#[derive(Copy, Clone, Serialize, Deserialize, Debug)]
pub enum AccessPolicy {
UpdateBefore,
UpdateAfter,
NoUpdate,
}
#[async_trait]
pub trait StorageConnection: HasSession + Sized + Send + Sync {
type Database: Connection;
type Authenticated: StorageConnection;
fn admin(&self) -> Self::Database;
fn create_database<DB: Schema>(
&self,
name: &str,
only_if_needed: bool,
) -> Result<Self::Database, crate::Error> {
self.create_database_with_schema(name, DB::schema_name(), only_if_needed)?;
self.database::<DB>(name)
}
fn database<DB: Schema>(&self, name: &str) -> Result<Self::Database, crate::Error>;
fn create_database_with_schema(
&self,
name: &str,
schema: SchemaName,
only_if_needed: bool,
) -> Result<(), crate::Error>;
fn delete_database(&self, name: &str) -> Result<(), crate::Error>;
fn list_databases(&self) -> Result<Vec<Database>, crate::Error>;
fn list_available_schemas(&self) -> Result<Vec<SchemaName>, crate::Error>;
fn create_user(&self, username: &str) -> Result<u64, crate::Error>;
fn delete_user<'user, U: Nameable<'user, u64> + Send + Sync>(
&self,
user: U,
) -> Result<(), crate::Error>;
#[cfg(feature = "password-hashing")]
fn set_user_password<'user, U: Nameable<'user, u64> + Send + Sync>(
&self,
user: U,
password: SensitiveString,
) -> Result<(), crate::Error>;
#[cfg(feature = "password-hashing")]
fn authenticate<'user, U: Nameable<'user, u64> + Send + Sync>(
&self,
user: U,
authentication: Authentication,
) -> Result<Self::Authenticated, crate::Error>;
fn assume_identity(
&self,
identity: IdentityReference<'_>,
) -> Result<Self::Authenticated, crate::Error>;
fn add_permission_group_to_user<
'user,
'group,
U: Nameable<'user, u64> + Send + Sync,
G: Nameable<'group, u64> + Send + Sync,
>(
&self,
user: U,
permission_group: G,
) -> Result<(), crate::Error>;
fn remove_permission_group_from_user<
'user,
'group,
U: Nameable<'user, u64> + Send + Sync,
G: Nameable<'group, u64> + Send + Sync,
>(
&self,
user: U,
permission_group: G,
) -> Result<(), crate::Error>;
fn add_role_to_user<
'user,
'role,
U: Nameable<'user, u64> + Send + Sync,
R: Nameable<'role, u64> + Send + Sync,
>(
&self,
user: U,
role: R,
) -> Result<(), crate::Error>;
fn remove_role_from_user<
'user,
'role,
U: Nameable<'user, u64> + Send + Sync,
R: Nameable<'role, u64> + Send + Sync,
>(
&self,
user: U,
role: R,
) -> Result<(), crate::Error>;
}
#[async_trait]
pub trait AsyncStorageConnection: HasSession + Sized + Send + Sync {
type Database: AsyncConnection;
type Authenticated: AsyncStorageConnection;
async fn admin(&self) -> Self::Database;
async fn create_database<DB: Schema>(
&self,
name: &str,
only_if_needed: bool,
) -> Result<Self::Database, crate::Error> {
self.create_database_with_schema(name, DB::schema_name(), only_if_needed)
.await?;
self.database::<DB>(name).await
}
async fn database<DB: Schema>(&self, name: &str) -> Result<Self::Database, crate::Error>;
async fn create_database_with_schema(
&self,
name: &str,
schema: SchemaName,
only_if_needed: bool,
) -> Result<(), crate::Error>;
async fn delete_database(&self, name: &str) -> Result<(), crate::Error>;
async fn list_databases(&self) -> Result<Vec<Database>, crate::Error>;
async fn list_available_schemas(&self) -> Result<Vec<SchemaName>, crate::Error>;
async fn create_user(&self, username: &str) -> Result<u64, crate::Error>;
async fn delete_user<'user, U: Nameable<'user, u64> + Send + Sync>(
&self,
user: U,
) -> Result<(), crate::Error>;
#[cfg(feature = "password-hashing")]
async fn set_user_password<'user, U: Nameable<'user, u64> + Send + Sync>(
&self,
user: U,
password: SensitiveString,
) -> Result<(), crate::Error>;
#[cfg(feature = "password-hashing")]
async fn authenticate<'user, U: Nameable<'user, u64> + Send + Sync>(
&self,
user: U,
authentication: Authentication,
) -> Result<Self::Authenticated, crate::Error>;
async fn assume_identity(
&self,
identity: IdentityReference<'_>,
) -> Result<Self::Authenticated, crate::Error>;
async fn add_permission_group_to_user<
'user,
'group,
U: Nameable<'user, u64> + Send + Sync,
G: Nameable<'group, u64> + Send + Sync,
>(
&self,
user: U,
permission_group: G,
) -> Result<(), crate::Error>;
async fn remove_permission_group_from_user<
'user,
'group,
U: Nameable<'user, u64> + Send + Sync,
G: Nameable<'group, u64> + Send + Sync,
>(
&self,
user: U,
permission_group: G,
) -> Result<(), crate::Error>;
async fn add_role_to_user<
'user,
'role,
U: Nameable<'user, u64> + Send + Sync,
R: Nameable<'role, u64> + Send + Sync,
>(
&self,
user: U,
role: R,
) -> Result<(), crate::Error>;
async fn remove_role_from_user<
'user,
'role,
U: Nameable<'user, u64> + Send + Sync,
R: Nameable<'role, u64> + Send + Sync,
>(
&self,
user: U,
role: R,
) -> Result<(), crate::Error>;
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Database {
pub name: String,
pub schema: SchemaName,
}
#[derive(Clone, Serialize, Deserialize, Zeroize)]
#[zeroize(drop)]
#[serde(transparent)]
pub struct SensitiveString(pub String);
impl std::fmt::Debug for SensitiveString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("SensitiveString(...)")
}
}
impl Deref for SensitiveString {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Authentication {
#[cfg(feature = "password-hashing")]
Password(crate::connection::SensitiveString),
}
#[doc(hidden)]
#[macro_export]
macro_rules! __doctest_prelude {
() => {
use bonsaidb_core::{
connection::AccessPolicy,
define_basic_unique_mapped_view,
document::{CollectionDocument,Emit, Document, OwnedDocument},
schema::{
Collection, CollectionName, CollectionViewSchema, DefaultSerialization,
DefaultViewSerialization, Name, NamedCollection, ReduceResult, Schema, SchemaName,
Schematic, SerializedCollection, View, ViewMapResult, ViewMappedValue,
},
Error,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Schema)]
#[schema(name = "MySchema", collections = [MyCollection], core = $crate)]
pub struct MySchema;
#[derive( Debug, Serialize, Deserialize, Default, Collection)]
#[collection(name = "MyCollection", views = [MyCollectionByName], core = $crate)]
pub struct MyCollection {
pub name: String,
pub rank: u32,
pub score: f32,
}
impl MyCollection {
pub fn named(s: impl Into<String>) -> Self {
Self::new(s, 0, 0.)
}
pub fn new(s: impl Into<String>, rank: u32, score: f32) -> Self {
Self {
name: s.into(),
rank,
score,
}
}
}
impl NamedCollection for MyCollection {
type ByNameView = MyCollectionByName;
}
#[derive(Debug, Clone, View)]
#[view(collection = MyCollection, key = u32, value = f32, name = "scores-by-rank", core = $crate)]
pub struct ScoresByRank;
impl CollectionViewSchema for ScoresByRank {
type View = Self;
fn map(
&self,
document: CollectionDocument<<Self::View as View>::Collection>,
) -> ViewMapResult<Self::View> {
document
.header
.emit_key_and_value(document.contents.rank, document.contents.score)
}
fn reduce(
&self,
mappings: &[ViewMappedValue<Self::View>],
rereduce: bool,
) -> ReduceResult<Self::View> {
if mappings.is_empty() {
Ok(0.)
} else {
Ok(mappings.iter().map(|map| map.value).sum::<f32>() / mappings.len() as f32)
}
}
}
define_basic_unique_mapped_view!(
MyCollectionByName,
MyCollection,
1,
"by-name",
String,
(),
|document: CollectionDocument<MyCollection>| {
document.header.emit_key(document.contents.name.clone())
},
);
};
}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
#[must_use]
pub struct Session {
pub id: Option<SessionId>,
pub identity: Option<Arc<Identity>>,
pub permissions: Permissions,
}
#[derive(Default, Clone, Copy, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionId(pub u64);
impl Session {
pub fn allowed_to<'a, R: AsRef<[Identifier<'a>]>, P: Action>(
&self,
resource_name: R,
action: &P,
) -> bool {
self.permissions.allowed_to(resource_name, action)
}
pub fn check_permission<'a, R: AsRef<[Identifier<'a>]>, P: Action>(
&self,
resource_name: R,
action: &P,
) -> Result<(), Error> {
self.permissions
.check(resource_name, action)
.map_err(Error::from)
}
}
impl Eq for Session {}
impl PartialEq for Session {
fn eq(&self, other: &Self) -> bool {
self.identity == other.identity
}
}
impl std::hash::Hash for Session {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.identity.hash(state);
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Identity {
User {
id: u64,
username: String,
},
Role {
id: u64,
name: String,
},
}
impl Eq for Identity {}
impl PartialEq for Identity {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::User { id: l_id, .. }, Self::User { id: r_id, .. })
| (Self::Role { id: l_id, .. }, Self::Role { id: r_id, .. }) => l_id == r_id,
_ => false,
}
}
}
impl std::hash::Hash for Identity {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
Identity::User { id, .. } => {
0_u8.hash(state); id.hash(state);
}
Identity::Role { id, .. } => {
1_u8.hash(state); id.hash(state);
}
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub enum IdentityReference<'name> {
User(NamedReference<'name, u64>),
Role(NamedReference<'name, u64>),
}
impl<'name> IdentityReference<'name> {
#[must_use]
pub fn into_owned(self) -> IdentityReference<'static> {
match self {
IdentityReference::User(user) => IdentityReference::User(user.into_owned()),
IdentityReference::Role(role) => IdentityReference::Role(role.into_owned()),
}
}
}