ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
//! The changes intake: a store's change feed, the capability that says a store HAS one, and the
//! portable floor that gives one to a store that only has an ordered pull.

use core::{future::Future, marker::PhantomData, time::Duration};

use std::{
  collections::{BTreeMap, HashSet},
  sync::Arc,
  time::SystemTime,
};

// Only the SQLite floor's refusal holds one: the intake itself names no node any more, because an
// answer carries the name of the node it describes.
#[cfg(feature = "sqlite")]
use smol_bytes::Utf8Bytes;

use super::{
  ItemId, Rings,
  channel::Outbox,
  journal::{Attributes, JournalRow},
  lifecycle::{LifecycleTap, Taps},
  message::{Delivery, Item, Payload, ack_channel},
  progress::{PositionKey, Positions, Track},
  registry::{Counting, Registries, RootKey},
  window::Outbound,
};

/// The ringing half of a coalescing doorbell — held by whoever WRITES the store.
///
/// A hint carries nothing and is safe to lose: it says "look again", and a look that did not happen
/// is caught by the next one or by the sweep. That is why it rings with a non-blocking send and
/// drops on a full channel — a writer must never wait on a reader, and a second ring queued behind
/// the first would say exactly what the first already says.
///
/// # `M` is a reserved seam
///
/// `M` is what a ring CARRIES, and it is `()` for every doorbell this crate builds — see
/// [`doorbell`], which is the only constructor there is. It is spelled now rather than later because
/// adding a parameter to a type is a change to every signature that names it: [`AsyncChanges::doorbell`]
/// and its [`Message`](AsyncChanges::Message), [`SqliteFeed`], [`ChangeIntake::doorbell`]. With the
/// default in place, a feed that one day rings with a partition or a table name changes its own
/// declaration and nobody else's.
pub struct Hint<M = ()> {
  tx: flume::Sender<M>,
}

impl Hint {
  /// Ring it. `false` once the feed is gone.
  #[inline]
  pub fn ring(&self) -> bool {
    !matches!(
      self.tx.try_send(()),
      Err(flume::TrySendError::Disconnected(()))
    )
  }
}

impl Rings for Hint {
  #[inline]
  fn ring(&self) -> bool {
    Self::ring(self)
  }
}

// Written out rather than derived, both of them: a derive would demand `M: Clone` and `M: Debug`,
// while the channel halves are cloneable and printable whatever they carry. The bound belongs where
// something actually consumes it, and neither of these does.
impl<M> Clone for Hint<M> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      tx: self.tx.clone(),
    }
  }
}

impl<M> core::fmt::Debug for Hint<M> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Hint").finish_non_exhaustive()
  }
}

/// The listening half — held by the feed.
///
/// `M` is [`Hint`]'s, and the two halves are minted together.
pub struct Doorbell<M = ()> {
  rx: flume::Receiver<M>,
}

impl<M> Doorbell<M> {
  /// Wait for a ring or for `sweep` to elapse — the BLOCKING floor the record names.
  ///
  /// The timeout is the liveness guarantee that makes a hint genuinely optional: everything the
  /// doorbell does for latency, the sweep would eventually do anyway.
  ///
  /// It answers WHETHER a ring arrived and not what it carried, which costs nothing while
  /// [`doorbell`] is the only constructor: every doorbell that exists carries `()`. The reader that
  /// hands a message back arrives with the constructor that can produce one.
  #[inline]
  pub fn wait(&self, sweep: Duration) -> Rung {
    match self.rx.recv_timeout(sweep) {
      Ok(_) => Rung::Rung,
      Err(flume::RecvTimeoutError::Timeout) => Rung::Swept,
      Err(flume::RecvTimeoutError::Disconnected) => Rung::Silent,
    }
  }

  /// Wait for a ring, for a task.
  ///
  /// No timeout, for the reason [`Inbox::park_async`](super::Inbox::park_async) has none: flume has
  /// no async deadline receive and this crate names no async runtime, so the sweep arrives as a ring
  /// from a [`Sweeper`](super::Sweeper) holding a [`Hint`] instead of as a timer this crate would
  /// have to acquire a dependency to build.
  #[inline]
  pub async fn rung(&self) -> Rung {
    match self.rx.recv_async().await {
      Ok(_) => Rung::Rung,
      Err(flume::RecvError::Disconnected) => Rung::Silent,
    }
  }

  /// Take a ring if one is already queued, without waiting.
  #[inline]
  pub fn take(&self) -> Rung {
    match self.rx.try_recv() {
      Ok(_) => Rung::Rung,
      Err(flume::TryRecvError::Empty) => Rung::Swept,
      Err(flume::TryRecvError::Disconnected) => Rung::Silent,
    }
  }
}

impl<M> core::fmt::Debug for Doorbell<M> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Doorbell").finish_non_exhaustive()
  }
}

/// What a wait on a [`Doorbell`] found.
#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Display, derive_more::IsVariant)]
#[display("{}", self.as_str())]
pub enum Rung {
  /// Somebody wrote the store — look now.
  Rung,
  /// Nobody rang and the wait expired. Look anyway: that is what makes the hint optional.
  Swept,
  /// Every hint holder is gone. Nothing will ever be written again, so the feed can stop.
  Silent,
}

impl Rung {
  /// A stable name for logs.
  #[inline]
  #[must_use]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Rung => "rung",
      Self::Swept => "swept",
      Self::Silent => "silent",
    }
  }
}

/// One doorbell: the ringing half and the listening half.
///
/// Capacity ONE, which is the coalescing. A second ring while one is queued finds the channel full
/// and is dropped, so a thousand writes between two looks cost one wake — the behaviour a hint
/// channel exists for, expressed as a capacity rather than as a policy somebody has to obey.
///
/// It mints the `()` pair and there is no other constructor, which is what makes [`Hint`]'s message
/// parameter a reserved seam rather than a message this layer could lose.
#[inline]
#[must_use]
pub fn doorbell() -> (Hint, Doorbell) {
  let (tx, rx) = flume::bounded(1);
  (Hint { tx }, Doorbell { rx })
}

/// One page of a change feed — what a pull hands back.
///
/// A TYPE and not an alias, because an alias is a spelling and not a check. `Vec<Item<T, K>>` and a
/// page are the same bytes and a different fact: a page is what a feed answered IN ITS OWN ORDER,
/// which is the property everything downstream rests on, and an alias would let any vector of items
/// stand in for one. This crate already holds a second [`Page`](crate::query::Page) — a cursor
/// window over a query — and two answers to two questions should not be interchangeable by
/// accident.
///
/// Its surface is what its call sites ask for and nothing else: a pull `collect`s one, a drain
/// asks whether it is empty and how long it is, and then walks it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Page<T, K> {
  items: Vec<Item<T, K>>,
}

impl<T, K> Page<T, K> {
  /// A page of `items`, in the feed's order.
  #[inline]
  #[must_use]
  pub const fn new(items: Vec<Item<T, K>>) -> Self {
    Self { items }
  }

  /// The items, in the feed's order.
  #[inline]
  #[must_use]
  pub fn items(&self) -> &[Item<T, K>] {
    &self.items
  }

  /// How many items this page carries.
  #[inline]
  #[must_use]
  pub const fn len(&self) -> usize {
    self.items.len()
  }

  /// Whether the feed had nothing past the cursor — which is what ends a drain.
  #[inline]
  #[must_use]
  pub const fn is_empty(&self) -> bool {
    self.items.is_empty()
  }

  /// The items, owned.
  #[inline]
  #[must_use]
  pub fn into_items(self) -> Vec<Item<T, K>> {
    self.items
  }
}

impl<T, K> FromIterator<Item<T, K>> for Page<T, K> {
  #[inline]
  fn from_iter<I: IntoIterator<Item = Item<T, K>>>(items: I) -> Self {
    Self::new(items.into_iter().collect())
  }
}

impl<T, K> IntoIterator for Page<T, K> {
  type IntoIter = std::vec::IntoIter<Item<T, K>>;
  type Item = Item<T, K>;

  #[inline]
  fn into_iter(self) -> Self::IntoIter {
    self.items.into_iter()
  }
}

/// A store that publishes a change feed on `Db`.
///
/// # What implements it, and what cannot
///
/// A RECORD store on a backend with either change data capture or an ordered pull. Mongo change
/// streams, Postgres logical decoding and MySQL binlog are three native feeds behind this one trait;
/// [`SqliteFeed`] is the portable FLOOR — a doorbell plus `WHERE key > p ORDER BY key LIMIT n` —
/// which any ordered store can be given.
///
/// A fulltext, vector or blob store publishes nothing of the kind: its rows have no order a cursor
/// can walk and no feed to subscribe to. There is therefore no impl, and `listen(changes)` at one is
/// `E0277` at the authored string rather than a runtime surprise — the truth table is (storage kind
/// × backend), and this trait is where it is enforced.
///
/// # The key is the ORDER, not merely an identity
///
/// [`pull`](Self::pull) must return items strictly after `after` in a total order that a later pull
/// reproduces. Everything downstream rests on that: the position is a key, resuming means asking for
/// what is past it, and a feed whose order was unstable would silently skip rows on a restart.
///
/// # Examples
///
/// A record store with an ordered pull is listenable, and the `Db` parameter is what lets one store
/// be listenable on several backends:
///
/// ```
/// use ingraph::{AsyncChanges, Doorbell, Item, Page, doorbell};
///
/// struct Scenes {
///   doorbell: Doorbell,
///   rows: Vec<(i64, String)>,
/// }
///
/// struct MyDb;
///
/// impl AsyncChanges<MyDb> for Scenes {
///   type Key = i64;
///   type Item = String;
///   // A ring says "look again" and nothing more, which is what the default is for.
///   type Message = ();
///   type Error = core::convert::Infallible;
///
///   fn doorbell(&self) -> &Doorbell {
///     &self.doorbell
///   }
///
///   async fn pull(
///     &mut self,
///     after: Option<&i64>,
///     limit: usize,
///   ) -> Result<Page<String, i64>, Self::Error> {
///     Ok(
///       self
///         .rows
///         .iter()
///         .filter(|(key, _)| after.is_none_or(|after| key > after))
///         .take(limit)
///         .map(|(key, row)| Item::new(*key, row.clone()))
///         .collect(),
///     )
///   }
/// }
///
/// fn listenable<S: AsyncChanges<Db>, Db>() {}
///
/// listenable::<Scenes, MyDb>();
/// ```
///
/// A store that publishes no feed is not, and the refusal is a COMPILE error at the position where
/// the mode was authored rather than an empty stream at run time:
///
/// ```compile_fail,E0277
/// use ingraph::AsyncChanges;
///
/// // A vector index: its rows have no order a cursor can walk, and there is nothing to subscribe
/// // to. Listening to the record store that FEEDS it is the answer, which is why there is no impl
/// // here to write.
/// struct KeyframeVectors;
/// struct MyDb;
///
/// fn listenable<S: AsyncChanges<Db>, Db>() {}
///
/// listenable::<KeyframeVectors, MyDb>();
/// ```
#[diagnostic::on_unimplemented(
  message = "`{Self}` publishes no change feed on `{Db}`",
  label = "not listenable",
  note = "a store is listenable where it has change data capture or an ORDERED PULL — a record \
          store on a backend that can answer `WHERE key > p ORDER BY key LIMIT n`. A fulltext, \
          vector or blob store publishes neither, so `listen(changes)` at one has nothing to \
          subscribe to; listen to the record store that feeds it instead",
  note = "the portable floor is `SqliteFeed`, which gives any ordered SQLite table a feed. A \
          backend with a native feed implements this trait over its own"
)]
pub trait AsyncChanges<Db> {
  /// The key the feed's order runs on, and therefore the type a position is.
  type Key;
  /// What one change carries — the declared struct an edge would move.
  type Item;
  /// What a RING on this feed's doorbell carries — `()` for a feed whose hint is only "look
  /// again", which is every feed this crate ships.
  ///
  /// An associated type and not a parameter on [`doorbell`](Self::doorbell), because the method
  /// answers a reference to the feed's OWN doorbell: a generic one would have to produce a
  /// `&Doorbell<M>` for whatever `M` its caller picked, and a feed holds exactly one. It carries no
  /// bound, since nothing in this trait or its driver consumes the message.
  type Message;
  /// What a pull can fail with.
  type Error;

  /// The doorbell a writer rings.
  fn doorbell(&self) -> &Doorbell<Self::Message>;

  /// The next page after `after`, at most `limit` items, in the feed's order.
  ///
  /// `None` means "from the beginning" — the backlog, which is the reindex posture: a consumer with
  /// no position reads the store's whole content and needs no separate replay path, because a
  /// backlog IS a query.
  fn pull(
    &mut self,
    after: Option<&Self::Key>,
    limit: usize,
  ) -> impl Future<Output = Result<Page<Self::Item, Self::Key>, Self::Error>> + Send;
}

/// What one [`ChangeIntake::drain`] pass did.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Pulled {
  pulled: usize,
  delivered: usize,
  retracted: usize,
  recorded: usize,
  advanced: bool,
}

impl Pulled {
  /// How many items came out of the store.
  #[inline]
  #[must_use]
  pub const fn pulled(&self) -> usize {
    self.pulled
  }

  /// How many deliveries went to the consumer.
  #[inline]
  #[must_use]
  pub const fn delivered(&self) -> usize {
    self.delivered
  }

  /// How many items were taken back because a delivery's ack hung up.
  #[inline]
  #[must_use]
  pub const fn retracted(&self) -> usize {
    self.retracted
  }

  /// How many journal rows this pass wrote.
  ///
  /// The STRONG half's count: rows written in the control store, either inside the transaction that
  /// moved the position or — where none moved — on their own. Nothing here counts what reached a
  /// tap or a queue.
  #[inline]
  #[must_use]
  pub const fn recorded(&self) -> usize {
    self.recorded
  }

  /// Whether the durable position moved.
  #[inline]
  #[must_use]
  pub const fn advanced(&self) -> bool {
    self.advanced
  }
}

/// Why a [`ChangeIntake`] pass stopped.
#[derive(Debug, derive_more::Display, derive_more::IsVariant)]
pub enum IntakeError<F, P> {
  /// The feed refused a pull.
  #[display("the change feed refused a pull: {_0}")]
  Feed(F),
  /// The positions map refused a read or a write.
  #[display("the positions map refused: {_0}")]
  Positions(P),
  /// The consumer's inbox is gone, so nothing this feed pulls can be delivered.
  #[display("the consumer's inbox has hung up")]
  Disconnected,
}

impl<F, P> core::error::Error for IntakeError<F, P>
where
  F: core::error::Error + 'static,
  P: core::error::Error + 'static,
{
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Feed(e) => Some(e),
      Self::Positions(e) => Some(e),
      Self::Disconnected => None,
    }
  }
}

/// The driver that turns a [`AsyncChanges`] feed into ordinary deliveries.
///
/// It is a PRODUCER and not a second kind of consumer, and that is what makes the two delivery modes
/// mixable: a node listening to a channel and to a change feed at once is a node with two producers
/// on one inbox. The loop that runs the operator never learns which one a delivery came from.
///
/// # The ordering it exists to keep
///
/// The pull cursor is not the durable position. A page that has been SENT moves the read head, so
/// the next page is new work; the durable position moves only when the consumer's ack comes back —
/// which the consumer sends after its own write commits. A crash between the two re-reads the
/// unacknowledged tail, which keyed replace makes harmless. Advancing the durable position on the
/// send instead would skip exactly the rows a crash lost.
#[derive(Debug)]
pub struct ChangeIntake<Db, F, P, A = ()>
where
  F: AsyncChanges<Db>,
  A: Attributes<F::Item>,
{
  feed: F,
  positions: P,
  track: Track,
  outbox: Outbox<ItemId, F::Item>,
  window: Outbound<ItemId>,
  // The sent-but-unsettled keys, kept so a watermark expressed in transport ids can be turned back
  // into the store key a position is. Ordered, because the watermark retires a PREFIX of it.
  keys: BTreeMap<ItemId, F::Key>,
  // The chain ROOT each sent row descends from, projected out of the row itself. Beside `keys` and
  // not inside it: the feed's key is the store's own ORDER — an integer rowid on the floor — and a
  // root is a declared key's first columns, so the two are different facts about the same row.
  roots: BTreeMap<ItemId, A::Root>,
  // THE ROOT-KEY REGISTRIES — [`Resident`](super::Resident)'s own seat, on the same terms: shared
  // by the whole deployment, `None` where nothing wired one, and never reachable from the rows this
  // intake pulls. What it counts is the same fact the resident counts one hop downstream: an item
  // this party sent and has not been answered for.
  registries: Option<Arc<Registries>>,
  next: u64,
  page: usize,
  taps: Taps,
  attribution: A,
  durable: Option<F::Key>,
  cursor: Option<F::Key>,
  loaded: bool,
  _db: PhantomData<fn() -> Db>,
}

impl<Db, F, P> ChangeIntake<Db, F, P, ()>
where
  F: AsyncChanges<Db>,
{
  /// The default page size — how many rows one pull asks for.
  ///
  /// It is the memory bound INSIDE the intake: a page is built, delivered and forgotten, so the
  /// intake holds one page and the window's keys, never the backlog. 256 is the record's own
  /// example of a batch whose ack is partial.
  pub const PAGE: usize = 256;

  /// Feed `outbox` from `feed`, keeping `track`'s position in `positions`.
  #[must_use]
  pub fn new(track: Track, feed: F, positions: P, outbox: Outbox<ItemId, F::Item>) -> Self {
    Self {
      feed,
      positions,
      track,
      outbox,
      window: Outbound::new(),
      keys: BTreeMap::new(),
      roots: BTreeMap::new(),
      registries: None,
      next: 0,
      page: Self::PAGE,
      taps: Taps::new(),
      attribution: (),
      durable: None,
      cursor: None,
      loaded: false,
      _db: PhantomData,
    }
  }
}

impl<Db, F, P, A> ChangeIntake<Db, F, P, A>
where
  F: AsyncChanges<Db>,
  A: Attributes<F::Item>,
{
  /// Attribute the rows this intake sends to the chain ROOT they descend from, through
  /// `attribution`.
  ///
  /// [`Resident::attributing`](super::Resident::attributing)'s sibling, and the same seam: this one
  /// projects out of the row the FEED pulled, which is the declared struct a source-listening node's
  /// upstream store holds.
  #[must_use]
  pub fn attributing<B>(self, attribution: B) -> ChangeIntake<Db, F, P, B>
  where
    B: Attributes<F::Item>,
  {
    ChangeIntake {
      feed: self.feed,
      positions: self.positions,
      track: self.track,
      outbox: self.outbox,
      window: self.window,
      keys: self.keys,
      // The old projection's answers, which a wiring call made before the intake ran cannot have.
      roots: BTreeMap::new(),
      registries: self.registries,
      next: self.next,
      page: self.page,
      taps: self.taps,
      attribution,
      durable: self.durable,
      cursor: self.cursor,
      loaded: self.loaded,
      _db: PhantomData,
    }
  }

  /// Pull `page` rows at a time.
  #[inline]
  #[must_use]
  pub const fn with_page(mut self, page: usize) -> Self {
    self.set_page(page);
    self
  }

  /// [`with_page`](Self::with_page), in place.
  #[inline]
  pub const fn set_page(&mut self, page: usize) -> &mut Self {
    self.page = page;
    self
  }

  /// Observe through `taps`.
  #[inline]
  #[must_use]
  pub fn with_taps(mut self, taps: Taps) -> Self {
    self.set_taps(taps);
    self
  }

  /// [`with_taps`](Self::with_taps), in place.
  #[inline]
  pub fn set_taps(&mut self, taps: Taps) -> &mut Self {
    self.taps = taps;
    self
  }

  /// **SHARE THE ROOT-KEY REGISTRIES**: count the rows this intake sends through `registries`.
  ///
  /// [`Resident::with_registries`](super::Resident::with_registries)'s sibling, and the deployment
  /// hands over the same object — an intake is a PRODUCER, so the items it sends are inflight for
  /// their root exactly as a node's emissions are, and a graph fed by a change feed whose intake
  /// counted nothing would show every key idle while its first hop was still running.
  ///
  /// Wiring none is legal and is what every hand-built intake that never asked does; see the
  /// resident's own note.
  #[inline]
  #[must_use]
  pub fn with_registries(mut self, registries: Arc<Registries>) -> Self {
    self.set_registries(registries);
    self
  }

  /// [`with_registries`](Self::with_registries), in place.
  #[inline]
  pub fn set_registries(&mut self, registries: Arc<Registries>) -> &mut Self {
    self.registries = Some(registries);
    self
  }

  /// The root-key registries it counts through, or `None` where none was wired.
  #[inline]
  #[must_use]
  pub fn registries(&self) -> Option<&Registries> {
    self.registries.as_deref()
  }

  /// The doorbell this feed is woken on — what a [`Sweeper`](super::Sweeper)'s [`Hint`] rings.
  #[inline]
  #[must_use]
  pub fn doorbell(&self) -> &Doorbell<F::Message> {
    self.feed.doorbell()
  }

  /// The durable position, as far as this intake has read or written it.
  #[inline]
  #[must_use]
  pub const fn position(&self) -> Option<&F::Key> {
    self.durable.as_ref()
  }

  /// The feed it pulls from.
  #[inline]
  #[must_use]
  pub const fn feed(&self) -> &F {
    &self.feed
  }

  /// Where it keeps its position.
  #[inline]
  #[must_use]
  pub const fn positions(&self) -> &P {
    &self.positions
  }

  /// Which `(unit, source)` position it is the cursor of.
  #[inline]
  #[must_use]
  pub const fn track(&self) -> &Track {
    &self.track
  }

  /// How many rows one pull asks for.
  #[inline]
  #[must_use]
  pub const fn page(&self) -> usize {
    self.page
  }

  /// The taps it observes through.
  #[inline]
  #[must_use]
  pub const fn taps(&self) -> &Taps {
    &self.taps
  }

  /// The projection its rows' roots are read through, or `()` where none was wired.
  #[inline]
  #[must_use]
  pub const fn attribution(&self) -> &A {
    &self.attribution
  }

  /// The feed back.
  #[inline]
  #[must_use]
  pub fn into_feed(self) -> F {
    self.feed
  }
}

impl<Db, F, P, A> ChangeIntake<Db, F, P, A>
where
  F: AsyncChanges<Db>,
  F::Key: PositionKey,
  P: Positions<F::Key>,
  P::Row: JournalRow<A::Root>,
  A: Attributes<F::Item>,
  // Hashed and compared for what a PAGE costs rather than for a lookup — see the de-duplication in
  // `settle`. `RootKey` is that pair plus what sharing the family table costs; see
  // [`Resident`](super::Resident)'s own widening of the same bound, where it is argued.
  A::Root: RootKey,
{
  /// **THIS PASS'S COUNTING SEAT** — [`Resident::counting`](super::Resident)'s twin, and see its
  /// note. `None` where nothing wired registries, or where this intake carries no projection.
  fn counting(&self) -> Option<Counting<A::Root>> {
    Counting::open(self.registries.as_ref(), A::FAMILY)
  }

  /// One pass: settle what came back, then pull and deliver until the store has nothing more.
  ///
  /// # Errors
  ///
  /// [`IntakeError`] when the feed refuses a pull, the positions map refuses, or the consumer's
  /// inbox has hung up.
  pub async fn drain(&mut self) -> Result<Pulled, IntakeError<F::Error, P::Error>> {
    if !self.loaded {
      self.durable = self
        .positions
        .position_async(&self.track)
        .await
        .map_err(IntakeError::Positions)?;
      self.cursor = self.durable.clone();
      self.loaded = true;
    }

    let mut report = self.settle().await?;
    // Opened once for the whole drain, however many pages it walks — see [`Counting`].
    let counting = self.counting();
    loop {
      let page = self
        .feed
        .pull(self.cursor.as_ref(), self.page)
        .await
        .map_err(IntakeError::Feed)?;
      if page.is_empty() {
        break;
      }
      report.pulled += page.len();
      report.delivered += 1;

      let mut ids = Vec::with_capacity(page.len());
      let mut items = Vec::with_capacity(page.len());
      for change in page {
        let (key, value) = change.into_parts();
        let id = ItemId::new(self.next);
        self.next += 1;
        // The read head moves with the SEND, so the next page is new work. The durable position
        // does not — see the type note.
        self.cursor = Some(key.clone());
        self.keys.insert(id, key);
        // Projected before the row goes on the wire, because that is the last moment this side
        // holds it: what comes back is an ack keyed by the transport id and nothing else.
        let root = self.attribution.root(&value);
        // **THE `+1`**, and R1 holds here for the same reason it holds in a resident, one hop
        // further up: the whole page is counted out before `deliver_async` below hands it over, and
        // this party sends no ack at all — it advances a durable POSITION, and it does that in
        // `settle`, after the answers have already been counted back in.
        if let Some(counting) = counting.as_ref() {
          counting.dispatched(&root);
        }
        self.roots.insert(id, root);
        ids.push(id);
        items.push(Item::new(id, value));
      }

      let (ack, answers) = ack_channel();
      self.window.record(ids, answers);
      self
        .outbox
        .deliver_async(Delivery::new(Payload::Batch(items), ack))
        .await
        .map_err(|_| IntakeError::Disconnected)?;
    }

    let settled = self.settle().await?;
    report.retracted += settled.retracted;
    report.advanced |= settled.advanced;
    Ok(report)
  }

  /// Collect answers, advance the durable position, and rewind on a lost delivery.
  ///
  /// The STRONG half of the journal is here, and it is here because this is the party that owns
  /// the position: the completion rows the answers earned go into the SAME transaction the position
  /// advances in, so a crash cannot leave a node's cursor ahead of what the record says it finished
  /// — or behind it. Nothing about that goes through a tap; a tap could drop it.
  async fn settle(&mut self) -> Result<Pulled, IntakeError<F::Error, P::Error>> {
    let mut report = Pulled::default();
    // `roots` is exactly the set of rows whose answers could decrement anything — see
    // [`Resident::harvest`](super::Resident)'s own gate, which this is.
    let counting = if self.roots.is_empty() {
      None
    } else {
      self.counting()
    };
    let harvest = self.window.harvest();
    let now = SystemTime::now();
    let mut journal: Vec<P::Row> = Vec::new();
    // Under the WORKER's name — the consumer that answered — and never under this intake's node.
    // The station is a fact about the consumer's work, and this intake's own name is the one thing
    // the answer certainly is not about.
    for answer in harvest.answers() {
      self.taps.observe(answer.worker(), answer.observation());
      // One answer states ONE station for ONE worker, so a page of 256 rows from one root is ONE
      // `(root, node)` row rather than 256 identical upserts of it.
      let mut seen: HashSet<A::Root> = HashSet::new();
      // Every key the answer spoke for, released or not: a failure releases nothing and is exactly
      // the observation a journal is read for. Every one of them is taken OUT of the map, dropped
      // row or not, because a held item comes back under a fresh id.
      // A COMPLETION and not merely an observation: the strong half owns final states, so a station
      // that settles earns a row in the control store and a `Failed` — which holds the window and
      // will be tried again — reaches the record through the diagnostic half or not at all. Writing
      // a failure here would put a non-final state in the half that cannot be dropped, and the row
      // would then have to be un-written by the retry that succeeds.
      //
      // An ack always carries an ARRIVAL, a consumer answering about an ITEM — so an observation
      // with no station is not one of this window's and there is nothing keyed `(root, node,
      // station)` to write for it.
      let Some(arrival) = answer.observation().arrival() else {
        continue;
      };
      let settled = arrival.station().is_settled();
      for id in answer.covered() {
        let Some(root) = self.roots.remove(id) else {
          continue;
        };
        // **THE `-1`**, and it is taken BEFORE the de-duplication below. The two counts are of
        // different things: a journal row is one per `(root, node)` however many rows of that root
        // the page carried, while an inflight count is one per ITEM — so a page of 256 rows from
        // one root that was counted out 256 times has to be counted back in 256 times.
        if let Some(counting) = counting.as_ref() {
          counting.observed(&root);
        }
        if !seen.insert(root.clone()) {
          continue;
        }
        if settled {
          journal.push(P::Row::of(&root, answer.worker(), arrival, now));
        }
        self.attribution.observe(&root, answer.worker(), arrival);
      }
    }

    if let Some(&watermark) = self.window.position() {
      // Split the sent keys at the watermark: everything up to it is settled and retires, and the
      // LAST of those is the store key the position becomes.
      let mut settled = self.keys.split_off(&ItemId::new(watermark.seq() + 1));
      core::mem::swap(&mut self.keys, &mut settled);
      if let Some((_, key)) = settled.into_iter().next_back()
        && self.durable.as_ref() != Some(&key)
      {
        self
          .positions
          .advance_async(&self.track, key.clone(), &journal)
          .await
          .map_err(IntakeError::Positions)?;
        self.durable = Some(key);
        report.advanced = true;
        report.recorded += journal.len();
        journal.clear();
      }
    }

    // Rows the answers earned while the watermark did not move — a partial batch, or a failure. They
    // still belong to the record, and a lone upsert is what they get: there is no position for them
    // to be atomic with, because none moved.
    if !journal.is_empty() {
      self
        .positions
        .record_async(&journal)
        .await
        .map_err(IntakeError::Positions)?;
      report.recorded += journal.len();
    }

    if self.window.lost() > 0 {
      let retracted = self.window.rewind();
      report.retracted = retracted.len();
      for id in retracted {
        self.keys.remove(&id);
        // The retracted rows come back under fresh ids, so the old projections are dead weight.
        //
        // And so is their COUNT: these items were counted out and their answers are never coming,
        // because the delivery carrying them was lost. Crediting them here is what keeps the
        // re-read — which counts them out again under those fresh ids — from adding a second `+1`
        // on top of a first that nothing will ever cancel. It is
        // [`Resident::hung_up`](super::Resident)'s act, for the same reason.
        let credited = self.roots.remove(&id);
        if let (Some(counting), Some(root)) = (counting.as_ref(), credited) {
          counting.observed(&root);
        }
      }
      // Back to the last position that is actually durable — the retracted rows are re-read.
      self.cursor = self.durable.clone();
    }

    Ok(report)
  }

  /// Drain, then keep draining whenever the doorbell rings, until it goes silent.
  ///
  /// The initial drain is the backlog, and it needs no separate path: a consumer with no position
  /// starts at the beginning of the feed's order, which is the reindex posture. This is also what
  /// makes a DISABLED upstream legal for a changes listener — nobody is writing, so nobody rings,
  /// and the listener still walks everything already there.
  ///
  /// # Errors
  ///
  /// [`IntakeError`], as [`drain`](Self::drain).
  pub async fn run(&mut self) -> Result<(), IntakeError<F::Error, P::Error>> {
    self.drain().await?;
    while !self.feed.doorbell().rung().await.is_silent() {
      self.drain().await?;
    }
    Ok(())
  }
}

/// The portable floor: a SQLite table with an ordered integer key, given a change feed.
///
/// What makes it the floor rather than the protocol is that it asks the store for nothing a store
/// might not have — one indexed, monotone column and the ability to answer `WHERE key > ? ORDER BY
/// key LIMIT ?`. A backend with a native feed implements [`AsyncChanges`] over that instead and this type
/// is not in its path.
///
/// # The identifiers are validated, not quoted
///
/// A table and a column name reach a statement by SPLICING, so both are refused at construction
/// unless they are bare identifiers. That is the one place a caller-supplied name could acquire a
/// second meaning, and the check is the crate's own slot rule — the same one an index name passes.
#[cfg(feature = "sqlite")]
#[derive(Debug)]
pub struct SqliteFeed<T> {
  conn: sqlx::SqliteConnection,
  key: String,
  from_start: String,
  after: String,
  doorbell: Doorbell,
  row: PhantomData<fn() -> T>,
}

#[cfg(feature = "sqlite")]
impl<T> SqliteFeed<T> {
  /// A feed over `table`, ordered by `key`, woken by `doorbell`.
  ///
  /// # Errors
  ///
  /// [`SqliteFeedError::Identifier`] when `table` or `key` is not a bare identifier.
  pub fn new(
    conn: sqlx::SqliteConnection,
    table: &str,
    key: &str,
    doorbell: Doorbell,
  ) -> Result<Self, SqliteFeedError> {
    for name in [table, key] {
      if !crate::slot::is_identifier(name.as_bytes()) {
        return Err(SqliteFeedError::Identifier(Utf8Bytes::from(
          name.to_owned(),
        )));
      }
    }
    Ok(Self {
      conn,
      key: key.to_owned(),
      from_start: format!("SELECT * FROM {table} ORDER BY {key} LIMIT ?"),
      after: format!("SELECT * FROM {table} WHERE {key} > ? ORDER BY {key} LIMIT ?"),
      doorbell,
      row: PhantomData,
    })
  }

  /// The connection back.
  #[inline]
  #[must_use]
  pub fn into_connection(self) -> sqlx::SqliteConnection {
    self.conn
  }
}

/// Why a [`SqliteFeed`] refused.
#[cfg(feature = "sqlite")]
#[derive(Debug, derive_more::Display, derive_more::IsVariant)]
pub enum SqliteFeedError {
  /// A table or column name is not a bare identifier, so splicing it would be a second meaning.
  #[display("`{_0}` is not a bare identifier, so it cannot name a table or a key column")]
  Identifier(Utf8Bytes),
  /// The statement failed.
  #[display("the change feed's pull failed: {_0}")]
  Pull(sqlx::Error),
}

#[cfg(feature = "sqlite")]
impl core::error::Error for SqliteFeedError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Identifier(_) => None,
      Self::Pull(e) => Some(e),
    }
  }
}

#[cfg(feature = "sqlite")]
impl<T> AsyncChanges<sqlx::Sqlite> for SqliteFeed<T>
where
  T: for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow> + Send + Unpin,
{
  type Error = SqliteFeedError;
  type Item = T;
  type Key = i64;
  type Message = ();

  #[inline]
  fn doorbell(&self) -> &Doorbell {
    &self.doorbell
  }

  async fn pull(
    &mut self,
    after: Option<&i64>,
    limit: usize,
  ) -> Result<Page<T, i64>, SqliteFeedError> {
    use sqlx::Row as _;

    // `i64` and not `usize`: SQLite binds an integer, and a limit wider than the column's own type
    // is a limit the engine would have to truncate. Saturating rather than casting, so a limit
    // nobody could mean becomes the largest one that exists.
    let limit = i64::try_from(limit).unwrap_or(i64::MAX);
    // AUDIT (`AssertSqlSafe`, sqlx 0.9's dynamic-SQL gate): the two statements are built ONCE in
    // `new`, from a fixed template plus exactly two spliced identifiers — the table and the key
    // column — each of which `new` refused unless `slot::is_identifier` accepted it. That charset
    // is ASCII alphanumerics and `_`, not digit-leading, so no accepted name can carry a quote, a
    // comment, a semicolon or whitespace, and there is no third spliced value: the cursor and the
    // limit are BOUND. A caller-supplied name reaches this only through the refusal, which is why
    // the check is a `Result` at construction rather than an assertion here.
    let rows = match after {
      Some(after) => {
        sqlx::query(sqlx::AssertSqlSafe(self.after.clone()))
          .bind(*after)
          .bind(limit)
          .fetch_all(&mut self.conn)
          .await
      }
      None => {
        sqlx::query(sqlx::AssertSqlSafe(self.from_start.clone()))
          .bind(limit)
          .fetch_all(&mut self.conn)
          .await
      }
    }
    .map_err(SqliteFeedError::Pull)?;

    rows
      .into_iter()
      .map(|row| {
        let key = row
          .try_get::<i64, _>(self.key.as_str())
          .map_err(SqliteFeedError::Pull)?;
        let item = T::from_row(&row).map_err(SqliteFeedError::Pull)?;
        Ok(Item::new(key, item))
      })
      .collect()
  }
}

#[cfg(test)]
mod tests;