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
//! THE ROW — one impl per TYPE, and every engine that speaks columns takes it.
//!
//! A [`Field`] is a value that can be a key, or one member of one. It reports itself to a
//! [`ColumnWriter`] on the way in and takes itself back off a [`ColumnReader`] on the way out, and
//! it names NO ENGINE in either direction. That is the whole economics of the trait: a row that
//! projects through one engine's address type is written once PER ENGINE, so a vocabulary of N
//! types across M engines is N×M impls and each new engine starts at zero — while a row that speaks
//! columns is written once and every engine reads it, including engines written in crates that have
//! never heard of this one.
//!
//! # Why ONE trait, where the two families have one each
//!
//! `FulltextField` and `VectorField` — both now deleted — were the same trait written twice, and the
//! only thing that ever made them two is the FACE each projected through: its own family's
//! `Address`, an associated type a row had to be spelled against separately. The column language
//! takes the projection away, and the reason for the split goes with it. The full-text family is
//! where all thirty-seven shipped rows lived and the vector family shipped none at all, so the merge
//! is also how the second family got a vocabulary — not by copying one, but by there being one
//! vocabulary.
//!
//! # ONE VALUE PER COLUMN, and the read takes the sequence the write put down
//!
//! A key is a sequence of columns and a row is a member of it, so a row landing two columns where
//! its read takes one leaves every column after it out of step — and a key whose columns drift is a
//! key that addresses the wrong entity. Each row below appends exactly what its read takes, in the
//! same order, and that agreement is the whole contract; nothing in a signature holds the two halves
//! together.
//!
//! Whether the key took ALL of the columns is a different question and not this trait's: it is asked
//! once, at the end, through [`ColumnReader::finish`], by the caller that owns the reader.
//!
//! # A row's WRITE kind and its READ kind must be the same kind
//!
//! [`ColumnWriter::fixed`] falls back onto [`bytes`](ColumnWriter::bytes) until an engine has a
//! native fixed-width column, so on the shipped codec the two land identical bytes — and an engine
//! that overrides `fixed` lands something else entirely. A row that writes through `fixed` and reads
//! through `bytes` is therefore correct on one engine and broken on the next. The two untagged
//! members below are where this bites: [`IpAddr`](core::net::IpAddr) and
//! [`SocketAddr`](core::net::SocketAddr) read their arms apart BY WIDTH off a variable-width column,
//! so both of them write through `bytes` — including the socket enum, whose arms do NOT delegate to
//! [`SocketAddrV4`](core::net::SocketAddrV4)'s and [`SocketAddrV6`](core::net::SocketAddrV6)'s rows
//! for exactly this reason. The layout each writes is shared; the kind it is landed as is not.
//!
//! # THE LAYOUTS ARE THE STORED ONES, BYTE FOR BYTE
//!
//! Every row here lands what `store::tantivy`'s retired per-engine rows landed for the same type, in
//! the same order and the same bytes. That is a COMPATIBILITY OBLIGATION rather than a coincidence:
//! an index written before the engine moved onto the column language is read back after it by these
//! rows, and a key that renders differently is a key that finds nothing — a silent miss, not a
//! failed decode.
//!
//! `tests::the_layouts_are_the_ones_the_shipped_codec_lands` is where that is pinned, and its
//! expectations are HAND-WRITTEN transcripts of the stored layout rather than a restatement of any
//! live impl. Under the `tantivy` feature each is also driven through the shipped engine's own
//! `buffer` → `write` → `finalize`, so the new path is checked against the old bytes.
//!
//! # The shipped engine speaks this
//!
//! `store::tantivy` implements [`ColumnWriter`] and [`ColumnReader`] — its write phase frames each
//! typed column into the bytes a `Term` is built from — so these rows are what actually cross into
//! the shipped index. The tests also speak them through the toy sinks in `store::column`'s
//! `testkit`, which is what proves a row speaks the LANGUAGE rather than one engine's storage.

// The three pointer members live in `alloc`, and `ingraph` links `std` rather than declaring it —
// `crate::id` pulls it in the same way, for the same three impls.
extern crate alloc;

use super::{ColumnError, ColumnReader, ColumnWriter};

/// A KEY VALUE REPORTING ITSELF IN COLUMNS — engine-blind, written once, read by every engine.
///
/// The merged form of the two per-engine row traits, and the merge is what makes a row's cost
/// per-TYPE instead of per-(type × engine). A declaring crate writes `impl Field for MyId` once and
/// its id crosses into every engine there is; an engine implements the column language once and
/// takes every row anybody has written.
///
/// `Sized` because [`read`](Self::read) returns `Self` by value.
///
/// # Not object-safe, and it has no reason to be
///
/// [`write`](Self::write) takes `impl ColumnWriter` and [`read`](Self::read) is generic over the
/// reader, so a row is spent through a type parameter and never behind a `dyn`. A key's members are
/// known at compile time — the seam that spends them is generic anyway — and both column traits are
/// dyn-incompatible themselves.
pub trait Field: Sized {
  /// Report this value's columns to `w`, in the order [`read`](Self::read) takes them back off.
  fn write(&self, w: &mut impl ColumnWriter);

  /// Take this value's columns off `r`, in the order [`write`](Self::write) put them down.
  ///
  /// # Errors
  ///
  /// The engine's own refusal if a column is missing, or if the one that is there is not the kind
  /// this value's read asks for — and this value's OWN, worded through [`ColumnError`], when a
  /// well-formed column decodes to something the type does not admit.
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error>;
}

/// Every integer member: its own width's column, never widened into a wider one.
///
/// The reason is the READ rather than the write: a widened `u8` would come back as an `i64` needing
/// a fallible narrowing, so the column would carry a value the type does not admit and the read
/// would have to refuse it. At its own width every column the write can produce is a value the read
/// can return, which is also what lets an engine with native integer columns land each one in the
/// column it belongs in.
macro_rules! row_integer {
  ($($ty:ident),* $(,)?) => {
    $(impl Field for $ty {
      #[inline]
      fn write(&self, w: &mut impl ColumnWriter) {
        w.$ty(*self);
      }

      #[inline]
      fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
        r.$ty()
      }
    })*
  };
}

row_integer!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);

/// Every `NonZero*`: TRANSPARENT to the integer it wraps — the SAME column, so a `NonZeroU64` and
/// the `u64` inside it address one entry.
///
/// A wrapper is how a value is HELD rather than part of what it IS, so the two must render alike.
/// The narrowing therefore happens on the way OUT, where a zero is the one value that is
/// well-formed and inadmissible — and the row is engine-blind, so it raises that refusal through
/// [`ColumnError::domain`] and the engine words it, in its own vocabulary.
macro_rules! row_nonzero {
  ($($ty:ty => $int:ident),* $(,)?) => {
    $(impl Field for $ty {
      #[inline]
      fn write(&self, w: &mut impl ColumnWriter) {
        w.$int(self.get());
      }

      #[inline]
      fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
        // The refused VALUE travels with the refusal: it is well-formed, so an engine wording this
        // has something to name, and the one thing wrong with it is that this type has no room for
        // it.
        let raw = r.$int()?;
        Self::new(raw).ok_or_else(|| R::Error::domain(raw))
      }
    })*
  };
}

row_nonzero!(
  core::num::NonZeroI8 => i8,
  core::num::NonZeroI16 => i16,
  core::num::NonZeroI32 => i32,
  core::num::NonZeroI64 => i64,
  core::num::NonZeroI128 => i128,
  core::num::NonZeroU8 => u8,
  core::num::NonZeroU16 => u16,
  core::num::NonZeroU32 => u32,
  core::num::NonZeroU64 => u64,
  core::num::NonZeroU128 => u128,
);

/// `uuid::Uuid`: a column of its own kind, which is the sixteen bytes and never a spelling of them.
impl Field for uuid::Uuid {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.uuid(*self);
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    r.uuid()
  }
}

/// Every text member: a text column, holding the string's own characters.
///
/// No escape and no terminator — a column is a column, and what a separator scheme cannot make
/// injective (`("ab", "c")` against `("a", "bc")`) a typed column never has to.
macro_rules! row_text {
  ($($ty:ty),* $(,)?) => {
    $(impl Field for $ty {
      #[inline]
      fn write(&self, w: &mut impl ColumnWriter) {
        w.text(self.as_ref());
      }

      #[inline]
      fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
        Ok(Self::from(r.text()?))
      }
    })*
  };
}

row_text!(String);

impl Field for smol_bytes::Utf8Bytes {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.text(self.as_ref());
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    // Through an owned `String`: this type's `From<&str>` is not in its surface, and the copy is the
    // same one every other text member pays to take a borrowed column away with it.
    Ok(Self::from(r.text()?.to_owned()))
  }
}

#[cfg(feature = "smol_str")]
row_text!(smol_str::SmolStr);

/// The network family, each as the OCTETS its own identity is — never the textual form, whose
/// spellings are several per address.
///
/// The widths are what make the two ENUM members injective untagged: 4 against 16 for an
/// [`IpAddr`](core::net::IpAddr), 6 against 26 for a [`SocketAddr`](core::net::SocketAddr). A tag
/// byte would buy nothing a width already buys.
impl Field for core::net::Ipv4Addr {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.fixed(&self.octets());
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    Ok(Self::from(r.fixed::<4>()?))
  }
}

impl Field for core::net::Ipv6Addr {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.fixed(&self.octets());
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    Ok(Self::from(r.fixed::<16>()?))
  }
}

impl Field for core::net::IpAddr {
  /// A VARIABLE-width column, and deliberately not a fixed one: the width is this row's
  /// discriminant, so the read has to be able to ask for whatever is there. Writing through
  /// [`fixed`](ColumnWriter::fixed) would land the two arms in two different columns on any engine
  /// with a native fixed width, and the read asks for one.
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    match self {
      Self::V4(host) => w.bytes(&host.octets()),
      Self::V6(host) => w.bytes(&host.octets()),
    }
  }

  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    // The WIDTH is the discriminant, so the two arms are read apart rather than tagged apart, and a
    // width outside the set is not a value of this type at all.
    let value = r.bytes()?;
    match value.len() {
      4 => Ok(Self::V4(core::net::Ipv4Addr::from(
        <[u8; 4]>::try_from(value).expect("a column this arm measured at four bytes"),
      ))),
      16 => Ok(Self::V6(core::net::Ipv6Addr::from(
        <[u8; 16]>::try_from(value).expect("a column this arm measured at sixteen bytes"),
      ))),
      got => Err(R::Error::width(got, &[4, 16])),
    }
  }
}

/// A socket address's port, appended after the octets in std's own field order.
///
/// Big-endian for the codec's reason rather than for the network's: one value renders to one column
/// on every host.
const PORT: usize = 2;

/// A v4 socket address's value: the four octets, then the port.
const V4: usize = 4 + PORT;

/// A v6 socket address carries TWO values beyond the obvious pair, and both are part of its
/// identity: `flowinfo` and `scope_id`, each a `u32`. Dropping them would make two distinct
/// addresses render one, which is the one property this layout has.
const V6: usize = 16 + PORT + 4 + 4;

/// One v4 address PACKED, so the layout is written once and both this type's own row and
/// [`SocketAddr`](core::net::SocketAddr)'s untagged arm land the same bytes.
fn pack_v4(host: &core::net::SocketAddrV4) -> [u8; V4] {
  let mut value = [0u8; V4];
  value[..4].copy_from_slice(&host.ip().octets());
  value[4..].copy_from_slice(&host.port().to_be_bytes());
  value
}

/// One v4 value READ APART — [`pack_v4`]'s reason, in the other direction.
fn socket_v4(value: [u8; V4]) -> core::net::SocketAddrV4 {
  let (octets, port) = value.split_at(4);
  core::net::SocketAddrV4::new(
    core::net::Ipv4Addr::from(<[u8; 4]>::try_from(octets).expect("a 4-byte slice")),
    u16::from_be_bytes(<[u8; PORT]>::try_from(port).expect("a 2-byte slice")),
  )
}

/// One v6 address packed, over the four fields that make it.
fn pack_v6(host: &core::net::SocketAddrV6) -> [u8; V6] {
  let mut value = [0u8; V6];
  value[..16].copy_from_slice(&host.ip().octets());
  value[16..18].copy_from_slice(&host.port().to_be_bytes());
  value[18..22].copy_from_slice(&host.flowinfo().to_be_bytes());
  value[22..].copy_from_slice(&host.scope_id().to_be_bytes());
  value
}

/// One v6 value read apart, over the same four fields.
fn socket_v6(value: [u8; V6]) -> core::net::SocketAddrV6 {
  let word = |at: usize| {
    u32::from_be_bytes(<[u8; 4]>::try_from(&value[at..at + 4]).expect("a 4-byte slice"))
  };
  core::net::SocketAddrV6::new(
    core::net::Ipv6Addr::from(<[u8; 16]>::try_from(&value[..16]).expect("a 16-byte slice")),
    u16::from_be_bytes(<[u8; PORT]>::try_from(&value[16..18]).expect("a 2-byte slice")),
    word(18),
    word(22),
  )
}

impl Field for core::net::SocketAddrV4 {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.fixed(&pack_v4(self));
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    Ok(socket_v4(r.fixed()?))
  }
}

impl Field for core::net::SocketAddrV6 {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.fixed(&pack_v6(self));
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    Ok(socket_v6(r.fixed()?))
  }
}

impl Field for core::net::SocketAddr {
  /// The arms share the two PACKINGS and not the two rows, which is [`IpAddr`](core::net::IpAddr)'s
  /// argument one type over: this row reads its arms apart off a variable-width column, so it has to
  /// land one — where each arm's own row lands a fixed-width column an engine is free to make
  /// native. Same bytes, different kind, and the kind is what the read has to agree with.
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    match self {
      Self::V4(host) => w.bytes(&pack_v4(host)),
      Self::V6(host) => w.bytes(&pack_v6(host)),
    }
  }

  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    // Untagged on width again — 6 against 26 — and each arm is read apart by the SAME function its
    // own row uses, so neither layout is written twice.
    let value = r.bytes()?;
    match value.len() {
      V4 => Ok(Self::V4(socket_v4(
        <[u8; V4]>::try_from(value).expect("a column this arm measured at six bytes"),
      ))),
      V6 => Ok(Self::V6(socket_v6(
        <[u8; V6]>::try_from(value).expect("a column this arm measured at twenty-six bytes"),
      ))),
      got => Err(R::Error::width(got, &[V4, V6])),
    }
  }
}

/// A fixed-width byte member: the bytes themselves, at the width the TYPE states.
///
/// `N` is the admission — see [`Id`](crate::Id) — so the width the read demands is the type's own
/// and a column of another width is not this value.
impl<const N: usize> Field for [u8; N] {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.fixed(self);
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    r.fixed::<N>()
  }
}

/// The three POINTER members, each transparent to what it holds — the `NonZero` law one level out.
macro_rules! row_pointer {
  ($($ty:ty),* $(,)?) => {
    $(impl<T: Field> Field for $ty {
      #[inline]
      fn write(&self, w: &mut impl ColumnWriter) {
        T::write(self, w);
      }

      #[inline]
      fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
        T::read(r).map(Self::new)
      }
    })*
  };
}

row_pointer!(alloc::sync::Arc<T>, alloc::rc::Rc<T>, alloc::boxed::Box<T>);

/// A [`TypedId`](crate::TypedId): the STORED id's columns, and nothing for the entity marker.
///
/// `E` reaches no column anywhere else in this crate and reaches none here — *storage and wire see
/// only `I`* is the type's own stated law, and a column is storage.
impl<I: Field, E> Field for crate::TypedId<I, E> {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    self.id_ref().write(w);
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    I::read(r).map(Self::new)
  }
}

/// The BSON pair, under the feature that supplies the types: each as its own raw bytes at its own
/// width, which is what both of them already are.
#[cfg(feature = "mongo")]
impl Field for bson::Uuid {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.fixed(&self.bytes());
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    Ok(Self::from_bytes(r.fixed::<16>()?))
  }
}

#[cfg(feature = "mongo")]
impl Field for bson::oid::ObjectId {
  #[inline]
  fn write(&self, w: &mut impl ColumnWriter) {
    w.fixed(&self.bytes());
  }

  #[inline]
  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    Ok(Self::from_bytes(r.fixed::<12>()?))
  }
}

/// The probe the audit below instantiates — a bound is resolved where a generic item is
/// INSTANTIATED, so the call never has to happen for the question to be asked.
fn crosses_into_any_engine<F: Field>() {}

/// One row demanded per member of the list — the audit's whole body.
macro_rules! audit_row {
  ($($ty:ty),* $(,)?) => {
    $(const _: fn() = crosses_into_any_engine::<$ty>;)*
  };
}

// THE VOCABULARY AUDIT: every member of `Id` has a row here, checked by the compiler.
//
// The obligation differs from `store::tantivy`'s shipped-parity audit and is stronger where it
// counts: that one says the shipped ENGINE pairs the shipped vocabulary, and this one says the
// vocabulary is crossable AT ALL, since a row here is the only row a member now needs. So a member
// admitted to `Id` tomorrow with no row in this module fails HERE, naming that member, rather than
// at whatever key first asks it to cross.
//
// The gated rows carry their gate in the list, so this audit is complete over the member set of the
// build it is compiled in rather than over `--all-features`'s.
crate::id::for_each_id_member!(audit_row);

// The five GENERIC rows, which no list of types can carry: each is an `impl` over a PARAMETER, so a
// witness leaf is the whole audit for them. Every one is bounded on what it holds, so the only thing
// such an impl can fail is EXISTING, and one instantiation settles that.
const _: () = {
  /// The entity a typed id addresses. It implements nothing, which is the point: `E` reaches no
  /// column, so this witness needs no faces at all.
  struct Witness;

  const _: fn() = crosses_into_any_engine::<alloc::sync::Arc<u64>>;
  const _: fn() = crosses_into_any_engine::<alloc::rc::Rc<u64>>;
  const _: fn() = crosses_into_any_engine::<alloc::boxed::Box<u64>>;
  const _: fn() = crosses_into_any_engine::<[u8; 12]>;
  const _: fn() = crosses_into_any_engine::<crate::TypedId<uuid::Uuid, Witness>>;
};

#[cfg(test)]
mod tests;