use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use crate::blob::{BlobBackend, BlobError, Entry, KeyLayout, Page};
use crate::capability::provider::ProviderNeeds;
use crate::kv::{BatchOp, KeyPage, KvBackend, KvError, ValuePage};
use crate::registry::{Endpoint, Handle, OpenError, OpenOptions};
use crate::relational::{
Dialect, Isolation, RelError, RelationalBackend, RelationalTx, Row, Value,
};
pub use crate::registry::{Listing, providers, providers_ranked};
use super::{Worker, on_worker};
pub struct KvHandle {
inner: Option<Arc<Handle>>,
worker: Worker,
}
impl std::fmt::Debug for KvHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("blocking::registry::KvHandle")
.field("id", &self.id())
.finish_non_exhaustive()
}
}
pub fn open_named(
id: &str,
endpoint: &Endpoint,
needs: &ProviderNeeds,
) -> Result<KvHandle, OpenError> {
open_named_with(id, endpoint, needs, &OpenOptions::new())
}
pub fn open_named_with(
id: &str,
endpoint: &Endpoint,
needs: &ProviderNeeds,
options: &OpenOptions,
) -> Result<KvHandle, OpenError> {
if on_worker() {
return Err(OpenError::Open(
"a blocking call from a persistant worker thread".to_string(),
));
}
let worker = Worker::start().map_err(|e| OpenError::Open(e.to_string()))?;
let (id, endpoint, needs, options) = (
id.to_string(),
endpoint.clone(),
needs.clone(),
options.clone(),
);
let opened = worker
.run(async move {
Ok(
crate::registry::open_named_with(&id, &endpoint, &needs, &options)
.await
.map(Arc::new),
)
})
.map_err(|e| OpenError::Open(e.to_string()))??;
Ok(KvHandle {
inner: Some(opened),
worker,
})
}
impl KvHandle {
fn handle(&self) -> &Arc<Handle> {
self.inner.as_ref().expect("present until dropped")
}
pub fn version_notes(&self) -> &[String] {
self.handle().version_notes()
}
pub fn id(&self) -> &'static str {
self.handle().id()
}
pub fn backend(&self) -> (String, String) {
let kv = self.handle().kv();
(kv.backend().to_string(), kv.version().to_string())
}
fn call<T, F, Fut>(&self, f: F) -> Result<T, KvError>
where
T: Send + 'static,
F: FnOnce(Arc<Handle>) -> Fut,
Fut: std::future::Future<Output = Result<T, KvError>> + Send + 'static,
{
let fut = f(self.handle().clone());
self.worker
.run(async move { Ok(fut.await) })
.map_err(|e| KvError::Backend(e.to_string()))?
}
fn call_as<T, E, Fut>(&self, fut: Fut, worker_failed: fn(String) -> E) -> Result<T, E>
where
T: Send + 'static,
E: Send + 'static,
Fut: Future<Output = Result<T, E>> + Send + 'static,
{
self.worker
.run(async move { Ok(fut.await) })
.map_err(|e| worker_failed(e.to_string()))?
}
pub fn blob(&self) -> Option<BlobHandle<'_>> {
self.handle().blob().map(|_| BlobHandle { owner: self })
}
pub fn rel(&self) -> Option<RelHandle<'_>> {
self.handle().rel().map(|_| RelHandle { owner: self })
}
#[cfg(feature = "text-index")]
pub fn text(&self) -> TextHandle<'_> {
TextHandle { owner: self }
}
pub fn get(&self, key: &str) -> Result<Option<Vec<u8>>, KvError> {
let key = key.to_string();
self.call(|h| async move { h.kv().get(&key).await })
}
pub fn put(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<(), KvError> {
let key = key.to_string();
self.call(|h| async move { h.kv().put(&key, value, ttl).await })
}
pub fn delete(&self, key: &str) -> Result<(), KvError> {
let key = key.to_string();
self.call(|h| async move { h.kv().delete(&key).await })
}
pub fn delete_erased(&self, key: &str) -> Result<(), KvError> {
let key = key.to_string();
self.call(|h| async move { h.kv().delete_erased(&key).await })
}
pub fn put_if_absent(
&self,
key: &str,
value: Vec<u8>,
ttl: Option<Duration>,
) -> Result<bool, KvError> {
let key = key.to_string();
self.call(|h| async move { h.kv().put_if_absent(&key, value, ttl).await })
}
pub fn prefix_list(
&self,
prefix: &str,
after: Option<&str>,
limit: usize,
) -> Result<KeyPage, KvError> {
let (prefix, after) = (prefix.to_string(), after.map(str::to_string));
self.call(|h| async move { h.kv().prefix_list(&prefix, after.as_deref(), limit).await })
}
pub fn ordered_scan(
&self,
prefix: &str,
after: Option<&str>,
limit: usize,
) -> Result<KeyPage, KvError> {
let (prefix, after) = (prefix.to_string(), after.map(str::to_string));
self.call(|h| async move { h.kv().ordered_scan(&prefix, after.as_deref(), limit).await })
}
pub fn ordered_scan_values(
&self,
prefix: &str,
after: Option<&str>,
limit: usize,
) -> Result<ValuePage, KvError> {
let (prefix, after) = (prefix.to_string(), after.map(str::to_string));
self.call(|h| async move {
h.kv()
.ordered_scan_values(&prefix, after.as_deref(), limit)
.await
})
}
pub fn compare_and_swap(
&self,
key: &str,
expected: &[u8],
new: Vec<u8>,
ttl: Option<Duration>,
) -> Result<bool, KvError> {
let (key, expected) = (key.to_string(), expected.to_vec());
self.call(|h| async move { h.kv().compare_and_swap(&key, &expected, new, ttl).await })
}
pub fn compare_and_delete(&self, key: &str, expected: &[u8]) -> Result<bool, KvError> {
let (key, expected) = (key.to_string(), expected.to_vec());
self.call(|h| async move { h.kv().compare_and_delete(&key, &expected).await })
}
pub fn take(&self, key: &str) -> Result<Option<Vec<u8>>, KvError> {
let key = key.to_string();
self.call(|h| async move { h.kv().take(&key).await })
}
pub fn count(&self, prefix: &str) -> Result<u64, KvError> {
let prefix = prefix.to_string();
self.call(|h| async move { h.kv().count(&prefix).await })
}
pub fn ttl_remaining(&self, key: &str) -> Result<Option<Duration>, KvError> {
let key = key.to_string();
self.call(|h| async move { h.kv().ttl_remaining(&key).await })
}
pub fn purge_expired(&self) -> Result<u64, KvError> {
self.call(|h| async move { h.kv().purge_expired().await })
}
pub fn batch(&self, ops: &[BatchOp]) -> Result<bool, KvError> {
let ops = ops.to_vec();
self.call(|h| async move { h.kv().batch(&ops).await })
}
}
#[cfg(feature = "text-index")]
#[derive(Debug)]
pub struct TextHandle<'a> {
owner: &'a KvHandle,
}
#[cfg(feature = "text-index")]
impl TextHandle<'_> {
pub fn put(&self, index: &str, doc_id: &str, terms: &[(String, u32)]) -> Result<(), KvError> {
let (index, doc_id, terms) = (index.to_string(), doc_id.to_string(), terms.to_vec());
self.owner.call(|h| async move {
crate::kv::text::TextIndex::new(h.kv())
.put(&index, &doc_id, &terms)
.await
})
}
pub fn remove_many(&self, index: &str, doc_ids: &[&str]) -> Result<usize, KvError> {
let (index, ids) = (index.to_string(), own(doc_ids));
self.owner.call(|h| async move {
let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
crate::kv::text::TextIndex::new(h.kv())
.remove_many(&index, &ids)
.await
})
}
pub fn remove_many_erased(&self, index: &str, doc_ids: &[&str]) -> Result<usize, KvError> {
let (index, ids) = (index.to_string(), own(doc_ids));
self.owner.call(|h| async move {
let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
crate::kv::text::TextIndex::new(h.kv())
.remove_many_erased(&index, &ids)
.await
})
}
pub fn remove_prefix_erased(&self, index: &str, id_prefix: &str) -> Result<usize, KvError> {
let (index, prefix) = (index.to_string(), id_prefix.to_string());
self.owner.call(|h| async move {
crate::kv::text::TextIndex::new(h.kv())
.remove_prefix_erased(&index, &prefix)
.await
})
}
pub fn postings(
&self,
index: &str,
term: &str,
after: Option<&str>,
limit: usize,
) -> Result<crate::kv::text::PostingPage, KvError> {
let (index, term, after) = (
index.to_string(),
term.to_string(),
after.map(str::to_string),
);
self.owner.call(|h| async move {
crate::kv::text::TextIndex::new(h.kv())
.postings(&index, &term, after.as_deref(), limit)
.await
})
}
pub fn doc_len(&self, index: &str, doc_id: &str) -> Result<Option<u32>, KvError> {
let (index, doc_id) = (index.to_string(), doc_id.to_string());
self.owner.call(|h| async move {
crate::kv::text::TextIndex::new(h.kv())
.doc_len(&index, &doc_id)
.await
})
}
pub fn stats(&self, index: &str) -> Result<crate::kv::text::Stats, KvError> {
let index = index.to_string();
self.owner
.call(|h| async move { crate::kv::text::TextIndex::new(h.kv()).stats(&index).await })
}
pub fn docs(
&self,
index: &str,
after: Option<&str>,
limit: usize,
) -> Result<crate::kv::text::DocPage, KvError> {
let (index, after) = (index.to_string(), after.map(str::to_string));
self.owner.call(|h| async move {
crate::kv::text::TextIndex::new(h.kv())
.docs(&index, after.as_deref(), limit)
.await
})
}
pub fn docs_with_prefix(
&self,
index: &str,
id_prefix: &str,
after: Option<&str>,
limit: usize,
) -> Result<crate::kv::text::DocPage, KvError> {
let (index, prefix, after) = (
index.to_string(),
id_prefix.to_string(),
after.map(str::to_string),
);
self.owner.call(|h| async move {
crate::kv::text::TextIndex::new(h.kv())
.docs_with_prefix(&index, &prefix, after.as_deref(), limit)
.await
})
}
pub fn search(
&self,
index: &str,
terms: &[String],
mode: crate::kv::text::Match,
limit: usize,
) -> Result<Vec<crate::kv::text::Hit>, KvError> {
let (index, terms) = (index.to_string(), terms.to_vec());
self.owner.call(|h| async move {
crate::kv::text::TextIndex::new(h.kv())
.search(&index, &terms, mode, limit)
.await
})
}
}
#[cfg(feature = "text-index")]
fn own(ids: &[&str]) -> Vec<String> {
ids.iter().map(|s| (*s).to_string()).collect()
}
impl Drop for KvHandle {
fn drop(&mut self) {
if let Some(inner) = self.inner.take()
&& !on_worker()
{
let _ = self.worker.run(async move {
drop(inner);
Ok(())
});
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct BlobHandle<'a> {
owner: &'a KvHandle,
}
impl BlobHandle<'_> {
fn run<T, Fut>(&self, f: impl FnOnce(Arc<Handle>) -> Fut) -> Result<T, BlobError>
where
T: Send + 'static,
Fut: Future<Output = Result<T, BlobError>> + Send + 'static,
{
let fut = f(self.owner.handle().clone());
self.owner.call_as(fut, BlobError::Backend)
}
fn blob(&self) -> &crate::registry::AnyBlob {
self.owner
.handle()
.blob()
.expect("a blob handle has a blob")
}
pub fn backend(&self) -> (String, String) {
(
self.blob().backend().to_string(),
self.blob().version().to_string(),
)
}
pub fn key_layout(&self) -> KeyLayout {
self.blob().key_layout()
}
pub fn read(&self, key: &str) -> Result<Option<Vec<u8>>, BlobError> {
let key = key.to_string();
self.run(|h| async move { h.blob().expect("present").read(&key).await })
}
pub fn write(&self, key: &str, bytes: Vec<u8>) -> Result<(), BlobError> {
let key = key.to_string();
self.run(|h| async move { h.blob().expect("present").write(&key, bytes).await })
}
pub fn delete(&self, key: &str) -> Result<(), BlobError> {
let key = key.to_string();
self.run(|h| async move { h.blob().expect("present").delete(&key).await })
}
pub fn delete_erased(&self, key: &str) -> Result<(), BlobError> {
let key = key.to_string();
self.run(|h| async move { h.blob().expect("present").delete_erased(&key).await })
}
pub fn stat(&self, key: &str) -> Result<Option<Entry>, BlobError> {
let key = key.to_string();
self.run(|h| async move { h.blob().expect("present").stat(&key).await })
}
pub fn list(&self, prefix: &str, after: Option<&str>, limit: usize) -> Result<Page, BlobError> {
let (prefix, after) = (prefix.to_string(), after.map(str::to_string));
self.run(|h| async move {
h.blob()
.expect("present")
.list(&prefix, after.as_deref(), limit)
.await
})
}
pub fn create_exclusive(&self, key: &str, bytes: Vec<u8>) -> Result<bool, BlobError> {
let key = key.to_string();
self.run(|h| async move {
h.blob()
.expect("present")
.create_exclusive(&key, bytes)
.await
})
}
pub fn replace_atomic(&self, key: &str, bytes: Vec<u8>) -> Result<(), BlobError> {
let key = key.to_string();
self.run(|h| async move { h.blob().expect("present").replace_atomic(&key, bytes).await })
}
pub fn append(&self, key: &str, bytes: Vec<u8>) -> Result<(), BlobError> {
let key = key.to_string();
self.run(|h| async move { h.blob().expect("present").append(&key, bytes).await })
}
pub fn read_range(
&self,
key: &str,
offset: u64,
len: u64,
) -> Result<Option<Vec<u8>>, BlobError> {
let key = key.to_string();
self.run(|h| async move {
h.blob()
.expect("present")
.read_range(&key, offset, len)
.await
})
}
pub fn read_range_if(
&self,
key: &str,
offset: u64,
len: u64,
tag: &str,
) -> Result<Option<Vec<u8>>, BlobError> {
let (key, tag) = (key.to_string(), tag.to_string());
self.run(|h| async move {
h.blob()
.expect("present")
.read_range_if(&key, offset, len, &tag)
.await
})
}
pub fn write_stream(&self, key: &str) -> Result<BlobWriter<'_>, BlobError> {
let key = key.to_string();
let sink =
self.run(|h| async move { h.blob().expect("present").write_stream(&key).await })?;
Ok(BlobWriter::new(self.owner, sink))
}
pub fn write_stream_atomic(&self, key: &str) -> Result<BlobWriter<'_>, BlobError> {
let key = key.to_string();
let sink = self
.run(|h| async move { h.blob().expect("present").write_stream_atomic(&key).await })?;
Ok(BlobWriter::new(self.owner, sink))
}
}
pub struct BlobWriter<'a> {
owner: &'a KvHandle,
sink: Option<Box<dyn crate::blob::BlobSink>>,
}
impl std::fmt::Debug for BlobWriter<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("blocking::registry::BlobWriter")
.field("open", &self.sink.is_some())
.finish_non_exhaustive()
}
}
impl<'a> BlobWriter<'a> {
fn new(owner: &'a KvHandle, sink: Box<dyn crate::blob::BlobSink>) -> Self {
Self {
owner,
sink: Some(sink),
}
}
fn lost() -> BlobError {
BlobError::Backend("the stream was lost after an earlier failure of the worker".to_string())
}
pub fn write(&mut self, chunk: &[u8]) -> Result<(), BlobError> {
let mut sink = self.sink.take().ok_or_else(Self::lost)?;
let chunk = chunk.to_vec();
let (sink, result) = self.owner.call_as(
async move {
let r = sink.write(&chunk).await;
Ok((sink, r))
},
BlobError::Backend,
)?;
self.sink = Some(sink);
result
}
pub fn finish(mut self) -> Result<(), BlobError> {
let sink = self.sink.take().ok_or_else(Self::lost)?;
self.owner.call_as(sink.finish(), BlobError::Backend)
}
pub fn abort(mut self) -> Result<(), BlobError> {
let sink = self.sink.take().ok_or_else(Self::lost)?;
self.owner.call_as(sink.abort(), BlobError::Backend)
}
}
#[derive(Debug, Clone, Copy)]
pub struct RelHandle<'a> {
owner: &'a KvHandle,
}
impl RelHandle<'_> {
fn run<T, Fut>(&self, f: impl FnOnce(Arc<Handle>) -> Fut) -> Result<T, RelError>
where
T: Send + 'static,
Fut: Future<Output = Result<T, RelError>> + Send + 'static,
{
let fut = f(self.owner.handle().clone());
self.owner.call_as(fut, RelError::Backend)
}
fn rel(&self) -> &crate::registry::AnyRel {
self.owner.handle().rel().expect("a rel handle has a rel")
}
pub fn backend(&self) -> (String, String) {
(
self.rel().backend().to_string(),
self.rel().version().to_string(),
)
}
pub fn dialect(&self) -> Dialect {
self.rel().dialect()
}
pub fn call_bound(&self) -> Option<Duration> {
self.rel().call_bound()
}
pub fn execute(&self, sql: &str, params: &[Value]) -> Result<u64, RelError> {
let (sql, params) = (sql.to_string(), params.to_vec());
self.run(|h| async move { h.rel().expect("present").execute(&sql, ¶ms).await })
}
pub fn execute_erased(&self, sql: &str, params: &[Value]) -> Result<u64, RelError> {
let (sql, params) = (sql.to_string(), params.to_vec());
self.run(|h| async move {
h.rel()
.expect("present")
.execute_erased(&sql, ¶ms)
.await
})
}
pub fn query(&self, sql: &str, params: &[Value]) -> Result<Vec<Row>, RelError> {
let (sql, params) = (sql.to_string(), params.to_vec());
self.run(|h| async move { h.rel().expect("present").query(&sql, ¶ms).await })
}
pub fn transaction(
&self,
isolation: Isolation,
statements: &[(&str, &[Value])],
) -> Result<Vec<u64>, RelError> {
let statements: Vec<(String, Vec<Value>)> = statements
.iter()
.map(|(sql, params)| (sql.to_string(), params.to_vec()))
.collect();
self.run(|h| async move {
let mut tx = h.rel().expect("present").begin(isolation).await?;
let mut affected = Vec::with_capacity(statements.len());
for (sql, params) in &statements {
match tx.execute(sql, params).await {
Ok(n) => affected.push(n),
Err(e) => {
let _ = tx.rollback().await;
return Err(e);
}
}
}
tx.commit().await?;
Ok(affected)
})
}
}