pigeonhole 1.3.2

Embedded, single-file, wide-column store: BigTable's data model with SQLite's deployment model.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! 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`. A read as of now (no snapshot) runs
//! at the call first, as the sync one does: a memtable or cache hit is read there, as of
//! the call, and the future resolves to it on its first poll, holding nothing else (#709).
//! On Linux, a block the operating system's page cache holds is copied on the calling thread
//! and the read carries on (D292). A block that must come from the device has its read
//! submitted at the call: the future waits for it and keeps the call's read point, so its
//! result is as of the call too. A read at a snapshot reads at that snapshot. Dropping a
//! read future is always safe. Two cases read synchronously, counted by
//! [`EngineMetrics::async_sync_reads`](crate::EngineMetrics::async_sync_reads) (D196, #398):
//! - a separated value too large to cache (above an eighth of the block cache, at most
//!   1 MiB): inside `get_async` or `read_async` itself when the rest of the read hits at
//!   the call, else inside the future;
//! - a block the cache cannot keep (a cache of size 0): inside the future.
//!
//! **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 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;

/// 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: Resolving<Submitted, CommitInfo>,
}

/// A submitted commit of one kind: what it waits on, and the public result it makes of the
/// engine's.
///
/// Two methods, so no public result crosses the trait: [`Resolving::poll`] builds it
/// straight into its own return value, as each future's own `poll` did. One method
/// returning `Poll<Result<Out>>` counted up to 34 instructions more a commit, even inlined
/// (#1970's callgrind runs).
trait Resolve {
    /// The engine's result.
    type Raw;
    type Out;

    /// Polls the engine's pending commit.
    fn poll_pending(&mut self, cx: &mut Context<'_>) -> Poll<Self::Raw>;

    /// The public result of the engine's.
    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,
}

/// The state of every commit future: `S` submitted, resolving to a `T`.
#[derive(Debug)]
enum Resolving<S, T> {
    /// Submitted (or waiting for room, D210: the engine's pending commit submits once
    /// admitted), not resolved.
    Pending(S),
    /// Resolved without waiting (refused before submission, or a ticket already done);
    /// `None` once taken.
    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))),
        }
    }

    // Inlined into each future's `poll`, as the four copies were: left to the optimizer,
    // `commit-async` counted 29 instructions more a commit (#1970's first callgrind run).
    #[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<'_> {
    /// [`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_returning`](RowMutation::commit_returning), as a future (D314): submits when
    /// its shard has room (D210) and resolves to the incremented cells once the commit is
    /// durable at its level and visible. **Dropped while it still waits for room, it writes
    /// nothing**; dropped after it was submitted, the commit lands and its values are lost (a
    /// gap in a sequence, never a repeat).
    pub fn commit_returning_async(self) -> ReturningFuture {
        ReturningFuture {
            state: Resolving::new(self.submit_returning_async()),
        }
    }
}

/// [`RowMutation::commit_returning_async`]'s future.
#[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<'_> {
    /// [`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: Resolving::new(self.submit_if_async(condition)),
        }
    }

    /// [`commit_if_returning`](RowMutation::commit_if_returning), as a future, submitted as
    /// [`commit_if_async`](RowMutation::commit_if_async) is (D210): the same
    /// [`Checked`](crate::Checked) either way. **Dropped while it still waits for room, it
    /// writes nothing.**
    pub fn commit_if_returning_async(self, condition: &Condition) -> CheckReturningFuture {
        CheckReturningFuture {
            state: Resolving::new(self.submit_if_returning_async(condition)),
        }
    }
}

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) -> TransactionCommitFuture {
        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) -> 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),
        }
    }
}

/// A transaction's commit, as a future ([`Transaction::commit_async`]): a [`CommitFuture`]
/// that also counts the outcome in the transaction counters of
/// [`EngineMetrics`](crate::EngineMetrics) (ICR 0061). Its own type, so the commit
/// futures of row mutations and batches carry nothing for it (ICR 0060). Dropped once
/// submitted, it does not roll the commit back; dropped while it still waits for room
/// (D210), it writes nothing, and counts nothing.
#[derive(Debug)]
#[must_use = "a commit future dropped while it waits for room writes nothing (D210); await it"]
pub struct TransactionCommitFuture {
    commit: CommitFuture,
    /// Taken when the outcome is counted, so a repeated poll does not count it again.
    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)
    }
}

/// 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: 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)
    }
}

/// A [`RowMutation::commit_if_returning`] as a future
/// ([`RowMutation::commit_if_returning_async`], D314 amendment 2).
#[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)
    }
}

/// 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.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'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))),
        }
    }
}

/// 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's result is lost unless it is polled"]
pub struct RowFuture {
    inner: std::result::Result<pigeonhole_engine::RowFuture<RowBuf>, Option<Error>>,
    key: Vec<u8>,
    /// Resolved at the call (a memtable or cache hit, #709); `None` once taken, or for a
    /// read that runs in the engine's future.
    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,
        }
    }

    /// A read that resolved at the call.
    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",
    )
}

/// A multi-get as a [`Stream`](futures_core::Stream) of owned [`Row`]s, each with its key's
/// index in the [`KeySet`](crate::KeySet) ([`KeyRows::into_owned_stream`](crate::KeyRows::into_owned_stream)).
/// It holds its table; after the database is closed, the next item is `Closed` and the
/// stream ends (#826). Dropping it is always safe.
#[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)
    }
}

/// A scan as a [`Stream`](futures_core::Stream) of owned [`Row`]s ([`Scan::stream`](crate::Scan::stream)).
/// After the database is closed, the next item is `Closed` and the stream ends (#826).
/// Borrows its table as a lifetime, as [`RowIter`](crate::RowIter) does, or holds it
/// ([`Scan::into_owned`](crate::Scan::into_owned)). 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,
    /// The table: borrowed, or held by an owned scan. Its database's closed flag stops the
    /// stream (#826).
    table: std::borrow::Cow<'t, std::sync::Arc<crate::table::TableCore>>,
    /// The engine generation the scan started in (D265): a step after the database
    /// recovered onto a newer engine fails with `SnapshotExpired`.
    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));
            }
        };
        // As `RowIter`: nothing is read after `close` (#826), nor after a recovery onto a
        // newer engine (D265); one check, one load.
        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)
    }
}

/// The public streams of a feed's owned items, `$item`s from [`Feed`](crate::Feed)'s `$poll`:
/// each a clone, the stream ending after the first error. [`FeedStream`] and
/// [`FeedEventStream`] differ only in those.
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 }
            }

            /// Where the stream is: [`FeedBuilder::resume`](crate::FeedBuilder::resume)
            #[doc = concat!("continues after the last ", $one, " it yielded.")]
            pub fn token(&self) -> crate::FeedToken {
                self.feed.token()
            }

            /// How far the stream has covered its history:
            /// [`Feed::position`](crate::Feed::position). Not part of the stable API.
            #[doc(hidden)]
            pub fn position(&self) -> crate::FeedPosition {
                self.feed.position()
            }

            /// The feed back, for its blocking calls.
            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! {
    /// A change feed as a `Stream` of owned commits (D310 PR 5a): [`Feed::poll_next`](crate::Feed::poll_next) for an
    /// async consumer, each commit a copy safe to hold across `.await`. Woken, never spinning,
    /// when the frontier can move. A feed doesn't end on its own: the stream ends only after an
    /// error, which it yields once (`FeedExpired` when the history is gone, `Closed` after
    /// `close()`). Take [`token`](Self::token) after handling a commit, as with the sync feed.
    ///
    /// The writer process only: in a reader process the first item is `Unsupported` (#1407);
    /// use the blocking [`Feed::next`](crate::Feed::next) there, on a thread of its own.
    ///
    /// ```
    /// use futures_core::Stream;
    /// use pigeonhole::nonblocking::FeedStream;
    /// use pigeonhole::{Family, FeedRetention, Options, Pigeonhole};
    ///
    /// # fn main() -> pigeonhole::Result<()> {
    /// # let dir = pigeonhole::doc_support::temp_dir();
    /// let db = Pigeonhole::open(
    ///     dir.join("app.phdb"),
    ///     Options::default().change_feed(FeedRetention::bytes(64 << 20)),
    /// )?;
    /// let t = db.table("t")?.family("f", Family::default()).create_if_missing()?;
    /// let mut stream = FeedStream::new(t.feed().open()?);
    /// t.mutate(b"row").put("f", b"q", b"v").commit()?;
    /// // Any executor drives it (here a minimal one).
    /// # use pigeonhole::doc_support::block_on;
    /// let next = std::future::poll_fn(|cx| std::pin::Pin::new(&mut stream).poll_next(cx));
    /// let commit = block_on(next).expect("a feed doesn't end on its own")?;
    /// assert_eq!(commit.changes()[0].row(), b"row");
    /// let _token = stream.token();
    /// # drop(stream);
    /// # db.close()?;
    /// # Ok(())
    /// # }
    /// ```
    FeedStream: Commit, poll_next, "commit", "commits"
}

feed_stream! {
    /// A change feed as a `Stream` of owned events (D315): [`FeedStream`] for
    /// [`Feed::poll_next_event`](crate::Feed::poll_next_event), so a feed of every table
    /// ([`Pigeonhole::feed`](crate::Pigeonhole::feed)) yields its catalog changes in their place
    /// among the commits. It ends as `FeedStream` does, and in a reader process too the first
    /// item is `Unsupported`.
    FeedEventStream: FeedEvent, poll_next_event, "event", "events"
}