pigeonhole 0.3.4

Embedded, single-file, wide-column store: BigTable's data model with SQLite's deployment model. Experimental 0.x: format and API may change before 1.0.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! The async front door (Phase 3, #42): the same operations as the sync API, over the same
//! engine, as futures: commits, gets, row reads and scan streams. It is behind the `async`
//! feature, which is on by default (D17). The user guide's Async page lists the calls that
//! are blocking only.
//!
//! Futures depend only on `std::task`, so they run on any executor (Tokio, smol, a custom
//! one); none of them spawns a thread or uses `spawn_blocking`. A commit future is woken by
//! the shard that applies it and by the watermark that makes it visible; a read future by
//! the completion of the block read it is waiting for.
//!
//! **Reads.** [`Table::get_async`](crate::Table::get_async) and
//! [`RowRead::read_async`](crate::RowRead::read_async) resolve to owned results
//! ([`Cell`], [`Row`]), safe to hold across `.await`. Memtable and
//! cache hits resolve on the first poll, as cheaply as the sync calls. A block the cache
//! does not hold is read through the VFS's asynchronous reads, and the read runs again once
//! it is cached; the read point is taken on the first poll, so every attempt sees the same
//! data. Dropping a read future is always safe. Two cases read synchronously inside the
//! future, counted by [`Pigeonhole::async_sync_reads`](crate::Pigeonhole::async_sync_reads)
//! (D196, #398): a separated value too large to cache (above an eighth of the block cache,
//! at most 1 MiB), and a block the cache cannot keep (a cache of size 0).
//!
//! **Commits.** `commit_async` and `commit_with_async` submit at the call when the commit's
//! shard has room, then resolve when the record meets the requested durability and is
//! visible, exactly when the sync `commit` would return. Async and sync committers join the
//! same commit groups. A [`CommitTicket`] is also a future (`ticket.await`).
//!
//! **Backpressure (D210).** Each shard holds at most half `memtable_budget` of async
//! commits submitted and not yet resolved. Over that bound a commit future waits, in
//! arrival order, and submits when earlier commits resolve; polling it is what submits it.
//! Blocking commits are never held.
//!
//! **Dropping a commit future:**
//! - **Once submitted,** dropping does **not** roll the commit back: it lands or fails
//!   atomically either way.
//! - **Dropped while it still waits for room, it writes nothing.**
//!
//! So fire and forget (`let _ = t.mutate(..).commit_async();`) can lose the commit when the
//! shard is over its bound. Await the future, or use the blocking `commit` or
//! [`WriteBatch::commit_with_ticket`] if you need the commit without waiting for it.
//!
//! ```
//! use pigeonhole::{Durability, Family, Options, Pigeonhole};
//!
//! # fn main() -> pigeonhole::Result<()> {
//! # let dir = pigeonhole::doc_support::temp_dir();
//! let db = Pigeonhole::open(dir.join("app.phdb"), Options::default().shards(2))?;
//! let t = db.table("t")?.family("f", Family::default()).create_if_missing()?;
//! let commit = t.mutate(b"r").put("f", b"q", b"v").commit_async();
//! // Poll it on any executor; here, a minimal one.
//! let info = pigeonhole::doc_support::block_on(commit)?;
//! assert!(info.seqno > 0);
//! # db.close()?;
//! # Ok(())
//! # }
//! ```

use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::task::{Context, Poll};

use pigeonhole_format::Durability;

use crate::cell::RowBuf;
use crate::write::{Submitted, SubmittedCheck, TicketState};
use crate::{
    Cell, CommitInfo, CommitTicket, Condition, Error, Pigeonhole, Result, Row, RowMutation,
    Transaction, WriteBatch,
};
use pigeonhole_engine::ScanCursor;

/// An async commit, as a future: it submits when its shard has room and resolves when the
/// commit meets its durability level and is visible (see the [module docs](self)). Dropped
/// once submitted, it does not roll the commit back; dropped while it still waits for room
/// (D210), it writes nothing.
#[derive(Debug)]
#[must_use = "a commit future dropped while it waits for room writes nothing (D210); await it"]
pub struct CommitFuture {
    state: State,
}

#[derive(Debug)]
enum State {
    /// Submitted (or waiting for room, D210: the engine's pending commit submits once
    /// admitted), not resolved.
    Pending(Submitted),
    /// Resolved without waiting (refused before submission, or a ticket already done);
    /// `None` once taken.
    Ready(Option<Result<CommitInfo>>),
}

impl CommitFuture {
    fn new(submitted: Result<Submitted>) -> Self {
        Self {
            state: match submitted {
                Ok(s) => State::Pending(s),
                Err(e) => State::Ready(Some(Err(e))),
            },
        }
    }
}

impl Future for CommitFuture {
    type Output = Result<CommitInfo>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match &mut self.state {
            State::Pending(s) => match Pin::new(&mut s.pending).poll(cx) {
                Poll::Ready(r) => {
                    let out = s.outcome(r);
                    self.state = State::Ready(None);
                    Poll::Ready(out)
                }
                Poll::Pending => Poll::Pending,
            },
            State::Ready(r) => Poll::Ready(r.take().unwrap_or_else(|| {
                Err(Error::new(
                    crate::ErrorCode::InvalidArgument,
                    "commit future polled after it resolved",
                ))
            })),
        }
    }
}

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) => State::Pending(s),
                TicketState::Done(r) => State::Ready(Some(r)),
            },
        }
    }
}

impl RowMutation<'_> {
    /// [`commit`](RowMutation::commit), as a future: submits now when its shard has room,
    /// else once earlier async commits resolve (D210), and resolves when the commit is
    /// durable at its level and visible. Dropped once submitted, the future does not roll
    /// the commit back. **Dropped while it still waits for room, it writes nothing**, so
    /// `let _ = ...commit_async();` can lose the commit (see the [module docs](self)).
    pub fn commit_async(self) -> CommitFuture {
        CommitFuture::new(self.submit_async())
    }
}

impl RowMutation<'_> {
    /// [`commit_if`](RowMutation::commit_if), as a future: submits when its shard has room
    /// (D210), resolves to `None` if the condition failed, or to the commit once it is
    /// durable at its level and visible. Dropped once submitted, the future does not roll
    /// it back: the check and the write happen atomically on the row's shard either way.
    /// **Dropped while it still waits for room, it writes nothing** (see the
    /// [module docs](self)).
    pub fn commit_if_async(self, condition: &Condition) -> CheckFuture {
        CheckFuture {
            state: match self.submit_if_async(condition) {
                Ok(s) => CheckState::Pending(s),
                Err(e) => CheckState::Ready(Some(Err(e))),
            },
        }
    }
}

impl WriteBatch {
    /// [`commit`](WriteBatch::commit), as a future (writer default durability), submitted
    /// when its shard has room (D210). Dropped once submitted, the future does not roll it
    /// back. **Dropped while it still waits for room, it writes nothing** (see the
    /// [module docs](self)).
    pub fn commit_async(self) -> CommitFuture {
        self.async_commit(None)
    }

    /// [`commit_with`](WriteBatch::commit_with), as a future, submitted when its shard has
    /// room (D210). Dropped once submitted, the future does not roll it back. **Dropped
    /// while it still waits for room, it writes nothing** (see the [module docs](self)).
    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 {
    /// [`commit`](Transaction::commit), as a future, submitted when its shard has room
    /// (D210); resolves to [`ErrorCode::Conflict`](crate::ErrorCode::Conflict) on a
    /// conflicting commit. Dropped once submitted, the future does not roll it back: it
    /// commits or aborts atomically either way. **Dropped while it still waits for room, it
    /// writes nothing** (see the [module docs](self)).
    pub fn commit_async(self) -> CommitFuture {
        self.async_commit(None)
    }

    /// [`commit_with`](Transaction::commit_with), as a future, submitted when its shard has
    /// room (D210). Dropped once submitted, the future does not roll it back. **Dropped
    /// while it still waits for room, it writes nothing** (see the [module docs](self)).
    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))
    }
}

/// A conditional commit, as a future ([`RowMutation::commit_if_async`]): `None` if the
/// condition failed. Dropped once submitted, it does not roll the commit back; dropped while
/// it still waits for room (D210), it writes nothing.
#[derive(Debug)]
#[must_use = "a commit future dropped while it waits for room writes nothing (D210); await it"]
pub struct CheckFuture {
    state: CheckState,
}

#[derive(Debug)]
enum CheckState {
    /// Submitted (or waiting for room, D210), not resolved.
    Pending(SubmittedCheck),
    /// Refused before submission; `None` once taken.
    Ready(Option<Result<Option<CommitInfo>>>),
}

impl Future for CheckFuture {
    type Output = Result<Option<CommitInfo>>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match &mut self.state {
            CheckState::Pending(s) => match Pin::new(&mut s.pending).poll(cx) {
                Poll::Ready(r) => {
                    let out = s.outcome(r);
                    self.state = CheckState::Ready(None);
                    Poll::Ready(out)
                }
                Poll::Pending => Poll::Pending,
            },
            CheckState::Ready(r) => Poll::Ready(r.take().unwrap_or_else(|| {
                Err(Error::new(
                    crate::ErrorCode::InvalidArgument,
                    "commit future polled after it resolved",
                ))
            })),
        }
    }
}

/// A flush or a compaction as a future ([`Pigeonhole::flush_async`],
/// [`Pigeonhole::compact_async`]). Dropping it does not stop the operation.
#[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 {
    /// [`flush`](Pigeonhole::flush), as a future: submitted to every shard now, resolved
    /// when the flushed SSTs are in the manifest, woken by the shards' replies (no thread).
    /// Dropping it does not stop the flush.
    pub fn flush_async(&self) -> MaintenanceFuture {
        MaintenanceFuture {
            inner: self.db.engine.submit_flush().map_err(|e| Some(e.into())),
        }
    }

    /// [`compact`](Pigeonhole::compact), as a future, as [`flush_async`](Self::flush_async).
    /// Dropping it does not stop the compaction.
    pub fn compact_async(&self) -> MaintenanceFuture {
        MaintenanceFuture {
            inner: self
                .db
                .engine
                .submit_compact(None)
                .map_err(|e| Some(e.into())),
        }
    }
}

/// A get as a future, resolving to an owned [`Cell`] ([`Table::get_async`](crate::Table::get_async)).
#[derive(Debug)]
#[must_use = "a read does nothing unless 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))),
        }
    }
}

/// A row read as a future, resolving to an owned [`Row`], or `None` if the row has no
/// matching cell ([`RowRead::read_async`](crate::RowRead::read_async)).
#[derive(Debug)]
#[must_use = "a read does nothing unless polled"]
pub struct RowFuture {
    inner: std::result::Result<pigeonhole_engine::RowFuture<RowBuf>, Option<Error>>,
    key: Vec<u8>,
}

impl RowFuture {
    pub(crate) fn new(started: Result<pigeonhole_engine::RowFuture<RowBuf>>, key: Vec<u8>) -> Self {
        Self {
            inner: started.map_err(Some),
            key,
        }
    }
}

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;
        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",
    )
}

/// A scan as a [`Stream`](futures_core::Stream) of owned [`Row`]s ([`Scan::stream`](crate::Scan::stream)).
/// Borrows its table as a lifetime, as [`RowIter`](crate::RowIter) does. Dropping it is
/// always safe.
#[must_use = "a stream does nothing unless polled"]
pub struct RowStream<'t> {
    inner: std::result::Result<(ScanCursor, RowBuf), Option<Error>>,
    done: bool,
    _table: std::marker::PhantomData<&'t crate::Table>,
}

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 RowStream<'_> {
    pub(crate) fn new(started: Result<(ScanCursor, RowBuf)>, limit_zero: bool) -> Self {
        Self {
            inner: started.map_err(Some),
            done: limit_zero,
            _table: std::marker::PhantomData,
        }
    }
}

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));
            }
        };
        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)
    }
}