use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::task::{Context, Poll};
use crate::Durability;
use crate::cell::RowBuf;
use crate::write::{
Submitted, SubmittedCheck, SubmittedCheckReturning, SubmittedReturning, TicketState,
};
use crate::{
Cell, CommitInfo, CommitTicket, Condition, Error, Pigeonhole, Result, Row, RowMutation,
Transaction, WriteBatch,
};
use pigeonhole_engine::ScanCursor;
#[derive(Debug)]
#[must_use = "a commit future dropped while it waits for room writes nothing (D210); await it"]
pub struct CommitFuture {
state: Resolving<Submitted, CommitInfo>,
}
trait Resolve {
type Raw;
type Out;
fn poll_pending(&mut self, cx: &mut Context<'_>) -> Poll<Self::Raw>;
fn resolved(&mut self, r: Self::Raw) -> Result<Self::Out>;
}
macro_rules! resolves {
($($submitted:ty: $pending:ty => $out:ty,)*) => {$(
impl Resolve for $submitted {
type Raw = <$pending as Future>::Output;
type Out = $out;
#[inline(always)]
fn poll_pending(&mut self, cx: &mut Context<'_>) -> Poll<Self::Raw> {
Pin::new(&mut self.pending).poll(cx)
}
#[inline(always)]
fn resolved(&mut self, r: Self::Raw) -> Result<$out> {
self.outcome(r)
}
}
)*};
}
resolves! {
Submitted: pigeonhole_engine::PendingCommit => CommitInfo,
SubmittedReturning: pigeonhole_engine::PendingReturning => crate::Returned,
SubmittedCheck: pigeonhole_engine::PendingCheck => Option<CommitInfo>,
SubmittedCheckReturning: pigeonhole_engine::PendingCheckReturning => crate::Checked,
}
#[derive(Debug)]
enum Resolving<S, T> {
Pending(S),
Ready(Option<Result<T>>),
}
impl<S: Resolve<Out = T>, T> Resolving<S, T> {
fn new(submitted: Result<S>) -> Self {
match submitted {
Ok(s) => Self::Pending(s),
Err(e) => Self::Ready(Some(Err(e))),
}
}
#[inline(always)]
fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Result<T>> {
match self {
Self::Pending(s) => match s.poll_pending(cx) {
Poll::Ready(r) => {
let out = s.resolved(r);
*self = Self::Ready(None);
Poll::Ready(out)
}
Poll::Pending => Poll::Pending,
},
Self::Ready(r) => Poll::Ready(r.take().unwrap_or_else(|| {
Err(Error::new(
crate::ErrorCode::InvalidArgument,
"commit future polled after it resolved",
))
})),
}
}
}
impl CommitFuture {
fn new(submitted: Result<Submitted>) -> Self {
Self {
state: Resolving::new(submitted),
}
}
}
impl Future for CommitFuture {
type Output = Result<CommitInfo>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.state.poll(cx)
}
}
impl IntoFuture for CommitTicket {
type Output = Result<CommitInfo>;
type IntoFuture = CommitFuture;
fn into_future(self) -> CommitFuture {
CommitFuture {
state: match self.into_state() {
TicketState::Pending(s) => Resolving::Pending(s),
TicketState::Done(r) => Resolving::Ready(Some(r)),
},
}
}
}
impl RowMutation<'_> {
pub fn commit_async(self) -> CommitFuture {
CommitFuture::new(self.submit_async())
}
}
impl RowMutation<'_> {
pub fn commit_returning_async(self) -> ReturningFuture {
ReturningFuture {
state: Resolving::new(self.submit_returning_async()),
}
}
}
#[derive(Debug)]
#[must_use = "a commit future dropped while it waits for room writes nothing (D210); await it"]
pub struct ReturningFuture {
state: Resolving<SubmittedReturning, crate::Returned>,
}
impl Future for ReturningFuture {
type Output = Result<crate::Returned>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.state.poll(cx)
}
}
impl RowMutation<'_> {
pub fn commit_if_async(self, condition: &Condition) -> CheckFuture {
CheckFuture {
state: Resolving::new(self.submit_if_async(condition)),
}
}
pub fn commit_if_returning_async(self, condition: &Condition) -> CheckReturningFuture {
CheckReturningFuture {
state: Resolving::new(self.submit_if_returning_async(condition)),
}
}
}
impl WriteBatch {
pub fn commit_async(self) -> CommitFuture {
self.async_commit(None)
}
pub fn commit_with_async(self, durability: Durability) -> CommitFuture {
self.async_commit(Some(durability))
}
fn async_commit(self, durability: Option<Durability>) -> CommitFuture {
CommitFuture::new(self.submit_async(durability))
}
}
impl Transaction {
pub fn commit_async(self) -> TransactionCommitFuture {
self.async_commit(None)
}
pub fn commit_with_async(self, durability: Durability) -> TransactionCommitFuture {
self.async_commit(Some(durability))
}
fn async_commit(self, durability: Option<Durability>) -> TransactionCommitFuture {
let db = std::sync::Arc::clone(&self.db);
TransactionCommitFuture {
commit: CommitFuture::new(self.submit_async(durability)),
counts: Some(db),
}
}
}
#[derive(Debug)]
#[must_use = "a commit future dropped while it waits for room writes nothing (D210); await it"]
pub struct TransactionCommitFuture {
commit: CommitFuture,
counts: Option<std::sync::Arc<crate::db::Db>>,
}
impl Future for TransactionCommitFuture {
type Output = Result<CommitInfo>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let out = std::task::ready!(Pin::new(&mut self.commit).poll(cx));
if let Some(db) = self.counts.take() {
db.txn_counts.count(&out);
}
Poll::Ready(out)
}
}
#[derive(Debug)]
#[must_use = "a commit future dropped while it waits for room writes nothing (D210); await it"]
pub struct CheckFuture {
state: Resolving<SubmittedCheck, Option<CommitInfo>>,
}
impl Future for CheckFuture {
type Output = Result<Option<CommitInfo>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.state.poll(cx)
}
}
#[derive(Debug)]
#[must_use = "a future does nothing unless polled; dropped once submitted, it does not roll back"]
pub struct CheckReturningFuture {
state: Resolving<SubmittedCheckReturning, crate::Checked>,
}
impl Future for CheckReturningFuture {
type Output = Result<crate::Checked>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.state.poll(cx)
}
}
#[derive(Debug)]
#[must_use = "dropping a flush or compaction future does not stop it, but its result is lost"]
pub struct MaintenanceFuture {
inner: std::result::Result<pigeonhole_engine::PendingMaintenance, Option<Error>>,
}
impl Future for MaintenanceFuture {
type Output = Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match &mut self.inner {
Ok(m) => Pin::new(m).poll(cx).map(|r| r.map_err(Error::from)),
Err(e) => Poll::Ready(Err(e.take().unwrap_or_else(polled_after_done))),
}
}
}
impl Pigeonhole {
pub fn flush_async(&self) -> MaintenanceFuture {
MaintenanceFuture {
inner: self.engine().submit_flush().map_err(|e| Some(e.into())),
}
}
pub fn compact_async(&self) -> MaintenanceFuture {
MaintenanceFuture {
inner: self
.db
.engine()
.submit_compact(None)
.map_err(|e| Some(e.into())),
}
}
}
#[derive(Debug)]
#[must_use = "a read's result is lost unless it is polled"]
pub struct GetFuture {
inner: std::result::Result<pigeonhole_engine::GetFuture, Option<Error>>,
}
impl GetFuture {
pub(crate) fn new(started: Result<pigeonhole_engine::GetFuture>) -> Self {
Self {
inner: started.map_err(Some),
}
}
}
impl Future for GetFuture {
type Output = Result<Option<Cell>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match &mut self.inner {
Ok(f) => Pin::new(f)
.poll(cx)
.map(|r| r.map(|c| c.map(Cell::from_data)).map_err(Error::from)),
Err(e) => Poll::Ready(Err(e.take().unwrap_or_else(polled_after_done))),
}
}
}
#[derive(Debug)]
#[must_use = "a read's result is lost unless it is polled"]
pub struct RowFuture {
inner: std::result::Result<pigeonhole_engine::RowFuture<RowBuf>, Option<Error>>,
key: Vec<u8>,
done: Option<Result<Option<Row>>>,
}
impl RowFuture {
pub(crate) fn new(started: Result<pigeonhole_engine::RowFuture<RowBuf>>, key: Vec<u8>) -> Self {
Self {
inner: started.map_err(Some),
key,
done: None,
}
}
pub(crate) fn done(r: Result<Option<Row>>) -> Self {
Self {
inner: Err(None),
key: Vec::new(),
done: Some(r),
}
}
}
impl Future for RowFuture {
type Output = Result<Option<Row>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
if let Some(r) = this.done.take() {
return Poll::Ready(r);
}
match &mut this.inner {
Ok(f) => Pin::new(f).poll(cx).map(|r| match r {
Ok(Some(mut buf)) => {
buf.key = std::mem::take(&mut this.key);
Ok(Some(Row::new(buf)))
}
Ok(None) => Ok(None),
Err(e) => Err(e.into()),
}),
Err(e) => Poll::Ready(Err(e.take().unwrap_or_else(polled_after_done))),
}
}
}
fn polled_after_done() -> Error {
Error::new(
crate::ErrorCode::InvalidArgument,
"a read future polled after it resolved",
)
}
#[must_use = "a stream does nothing unless polled"]
#[derive(Debug)]
pub struct KeyStream {
rows: crate::KeyRows<'static>,
}
impl KeyStream {
pub(crate) fn new(rows: crate::KeyRows<'static>) -> Self {
Self { rows }
}
}
impl futures_core::Stream for KeyStream {
type Item = Result<(usize, Row)>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.rows.poll_owned(cx)
}
}
#[must_use = "a stream does nothing unless polled"]
pub struct RowStream<'t> {
inner: std::result::Result<(ScanCursor, RowBuf), Option<Error>>,
done: bool,
table: std::borrow::Cow<'t, std::sync::Arc<crate::table::TableCore>>,
generation: u64,
}
impl std::fmt::Debug for RowStream<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RowStream")
.field("done", &self.done)
.finish()
}
}
impl<'t> RowStream<'t> {
pub(crate) fn new(
started: Result<(ScanCursor, RowBuf)>,
limit_zero: bool,
table: std::borrow::Cow<'t, std::sync::Arc<crate::table::TableCore>>,
generation: u64,
) -> Self {
Self {
inner: started.map_err(Some),
done: limit_zero,
table,
generation,
}
}
}
impl futures_core::Stream for RowStream<'_> {
type Item = Result<Row>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = &mut *self;
if this.done {
return Poll::Ready(None);
}
let (cursor, buf) = match &mut this.inner {
Ok(parts) => parts,
Err(e) => {
this.done = true;
return Poll::Ready(e.take().map(Err));
}
};
if let Err(e) = this.table.db.check_generation(this.generation) {
this.done = true;
return Poll::Ready(Some(Err(e)));
}
let item = match cursor.poll_next_row(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Ok(false)) => None,
Poll::Ready(Ok(true)) => match cursor.counted(|c| crate::read::fill_row(c, buf)) {
Ok(()) => {
let next = buf.empty_like();
Some(Ok(Row::new(std::mem::replace(buf, next))))
}
Err(e) => Some(Err(e)),
},
Poll::Ready(Err(e)) => Some(Err(e.into())),
};
if !matches!(item, Some(Ok(_))) {
this.done = true;
}
Poll::Ready(item)
}
}
macro_rules! feed_stream {
($(#[$doc:meta])* $name:ident: $item:ident, $poll:ident, $one:literal, $many:literal) => {
$(#[$doc])*
#[must_use = "a stream does nothing unless polled"]
#[derive(Debug)]
pub struct $name {
feed: crate::Feed,
done: bool,
}
impl $name {
#[doc = concat!("The stream of `feed`'s ", $many, ".")]
pub fn new(feed: crate::Feed) -> Self {
Self { feed, done: false }
}
#[doc = concat!("continues after the last ", $one, " it yielded.")]
pub fn token(&self) -> crate::FeedToken {
self.feed.token()
}
#[doc(hidden)]
pub fn position(&self) -> crate::FeedPosition {
self.feed.position()
}
pub fn into_inner(self) -> crate::Feed {
self.feed
}
}
impl futures_core::Stream for $name {
type Item = Result<crate::$item>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = &mut *self;
if this.done {
return Poll::Ready(None);
}
match this.feed.$poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(Ok(item)) => Poll::Ready(Some(Ok(item.clone()))),
Poll::Ready(Err(e)) => {
this.done = true;
Poll::Ready(Some(Err(e)))
}
}
}
}
};
}
feed_stream! {
FeedStream: Commit, poll_next, "commit", "commits"
}
feed_stream! {
FeedEventStream: FeedEvent, poll_next_event, "event", "events"
}