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
//! The frame, the string, and every refusal a client's cursor can earn.
//!
//! Two things are pinned here that nothing else can pin. The first is the frame's BYTES: a cursor
//! outlives the process that minted it, so a changed layout is a deployment refusing every
//! outstanding page rather than a compile error. The second is the SUM TYPE — the shape a
//! heterogeneous order's values take — written by hand, because that is what a record's expansion
//! will emit and this is where the seam is shown to carry one.

/// The COMPOSITE subject's own corpus — a term of several COLUMNS and one SLOT, and the pair
/// checked on the way back. Its own file because what it measures is the split between the two, and
/// the sum below is over a scalar order.
mod composite;

use super::{
  ArityMismatch, Cursor, CursorError, CursorValue, OrderMismatch, OrderSignature, OrderTerm,
  TermName, text,
};
use crate::{FieldName, OrderDirection};

/// The identities of the order these tests page over.
const CREATED: &TermName = TermName::new("created_at");
const TITLE: &TermName = TermName::new("title");
const ID: &TermName = TermName::new("id");

/// A record's orderable values, as ONE type — the sum a heterogeneous order needs and a record's
/// expansion emits.
///
/// It carries a TAG of its own, which the frame does not supply: the frame delimits a slot and says
/// nothing about what is in it, so a sum over several column types is the party that knows which
/// arm it wrote. That keeps the framing in one place and the vocabulary in the record's.
#[derive(Debug, Clone, PartialEq)]
enum MediaValue {
  Created(i64),
  Title(String),
  Id(uuid::Uuid),
}

/// The arms' tags. One byte, and a byte outside the set is refused rather than read as an arm.
const CREATED_TAG: u8 = 0;
const TITLE_TAG: u8 = 1;
const ID_TAG: u8 = 2;

impl CursorValue for MediaValue {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Created(value) => {
        out.push(CREATED_TAG);
        value.write_cursor(out);
      }
      Self::Title(value) => {
        out.push(TITLE_TAG);
        value.write_cursor(out);
      }
      Self::Id(value) => {
        out.push(ID_TAG);
        value.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, rest) = bytes.split_first()?;
    match *tag {
      CREATED_TAG => i64::read_cursor(rest).map(Self::Created),
      TITLE_TAG => String::read_cursor(rest).map(Self::Title),
      ID_TAG => uuid::Uuid::read_cursor(rest).map(Self::Id),
      _ => None,
    }
  }
}

/// A uuid whose bytes are visible in an assertion.
const KEY: uuid::Uuid = uuid::Uuid::from_bytes([0xab; 16]);

/// `created_at DESC, title ASC, id ASC` — a written order with its key tail, over one nullable
/// column.
fn order() -> [OrderTerm; 3] {
  [
    OrderTerm::new(CREATED, FieldName::new("created_at"), OrderDirection::Desc),
    OrderTerm::nullable(TITLE, FieldName::new("title"), OrderDirection::Asc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ]
}

/// The boundary row: a timestamp, a title, and the key.
fn boundary() -> Cursor<MediaValue> {
  Cursor::at(
    &order(),
    [
      Some(MediaValue::Created(1_700_000_000)),
      Some(MediaValue::Title("a red car".to_owned())),
      Some(MediaValue::Id(KEY)),
    ],
  )
}

/// A cursor is minted UNDER an order, so its signature is that order's and there is no second way
/// to give it one.
#[test]
fn a_cursor_carries_the_signature_of_the_order_it_was_minted_under() {
  assert_eq!(boundary().signature(), OrderSignature::of(&order()));
  assert_eq!(boundary().values().len(), order().len());
}

/// The whole trip: typed in, one string out, the same typed values back.
#[test]
fn a_cursor_round_trips_through_its_opaque_string() {
  let cursor = boundary();
  let text = cursor.encode();

  assert_eq!(Cursor::<MediaValue>::decode(&text), Ok(cursor));
}

/// **The frame's bytes, pinned.** A cursor outlives its process, so this is the assertion that
/// stands between a layout change and a deployment refusing every page a client is holding.
///
/// The layout it reads: one version byte, the signature's eight big-endian bytes, then per slot a
/// presence byte and — for a value — four big-endian length bytes and the value's own.
#[test]
fn the_frame_is_a_version_a_signature_and_one_length_prefixed_slot_per_term() {
  let cursor = Cursor::at(
    &order(),
    [
      Some(MediaValue::Created(1)),
      None,
      Some(MediaValue::Id(KEY)),
    ],
  );
  let frame = text::decode(&cursor.encode()).expect("what `encode` wrote is base64url");

  let mut expected = vec![1u8];
  expected.extend_from_slice(&OrderSignature::of(&order()).to_blob());
  // `created_at`: present, a tag byte and eight big-endian bytes.
  expected.extend_from_slice(&[1, 0, 0, 0, 9, CREATED_TAG]);
  expected.extend_from_slice(&1i64.to_be_bytes());
  // `title`: SQL NULL — the presence byte alone, and no length to read.
  expected.push(0);
  // `id`: present, a tag byte and sixteen.
  expected.extend_from_slice(&[1, 0, 0, 0, 17, ID_TAG]);
  expected.extend_from_slice(KEY.as_bytes());

  assert_eq!(frame, expected);
}

/// A `NULL` sort value is a POSITION rather than a missing field, so the frame spells it — and it
/// comes back as one.
#[test]
fn a_null_slot_round_trips_as_a_null_slot() {
  let cursor = Cursor::at(
    &order(),
    [
      Some(MediaValue::Created(1)),
      None,
      Some(MediaValue::Id(KEY)),
    ],
  );

  let decoded =
    Cursor::<MediaValue>::decode(&cursor.encode()).expect("this cursor was just minted");
  assert_eq!(decoded.values()[1], None);
  assert_eq!(decoded, cursor);
}

/// **The refusal the signature exists for.** A cursor minted under one order and replayed against
/// another is refused BEFORE any SQL renders — where a server that ignored it would serve a page
/// computed by comparing values against columns they were never read from.
#[test]
fn a_cursor_replayed_under_another_order_is_refused() {
  let other = [
    OrderTerm::new(TITLE, FieldName::new("title"), OrderDirection::Asc),
    OrderTerm::nullable(CREATED, FieldName::new("created_at"), OrderDirection::Desc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ];

  assert_eq!(
    boundary().resume(&other),
    Err(CursorError::Order(OrderMismatch::new(
      OrderSignature::of(&order()),
      OrderSignature::of(&other),
    )))
  );
  assert_eq!(boundary().resume(&order()).map(<[_]>::len), Ok(3));
}

/// The same order with a RENAMED column is the same order, so the cursor resumes — the rename
/// measurement, reaching the refusal that would otherwise fire on it.
#[test]
fn a_rename_does_not_refuse_an_outstanding_cursor() {
  let renamed = [
    OrderTerm::new(CREATED, FieldName::new("created"), OrderDirection::Desc),
    OrderTerm::nullable(TITLE, FieldName::new("name"), OrderDirection::Asc),
    OrderTerm::new(ID, FieldName::new("pk"), OrderDirection::Asc),
  ];

  assert!(boundary().resume(&renamed).is_ok());
}

/// A tuple of the wrong width leaves a column comparing against nothing, so the width is checked
/// against the order rather than trusted.
///
/// It is a separate refusal from the signature's on purpose: a cursor can carry the right order and
/// the wrong number of values only by being tampered with, and saying which of the two happened is
/// what makes the two distinguishable in a log.
#[test]
fn a_tuple_that_is_not_as_wide_as_the_order_is_refused() {
  let short = Cursor::at(&order(), [Some(MediaValue::Created(1))]);

  assert_eq!(
    short.resume(&order()),
    Err(CursorError::Arity(ArityMismatch::new(1, 3)))
  );
}

/// A `NULL` at a `NOT NULL` term is refused: the column cannot hold one, so no row is on the other
/// side of that boundary and the comparison the expansion would render asks about a value that
/// cannot exist.
#[test]
fn a_null_at_a_not_null_term_is_refused() {
  let cursor = Cursor::at(
    &order(),
    [
      None,
      Some(MediaValue::Title("a red car".to_owned())),
      Some(MediaValue::Id(KEY)),
    ],
  );

  assert_eq!(cursor.resume(&order()), Err(CursorError::Null(CREATED)));
}

/// A string that is not base64url is refused at the alphabet, before anything is read as a frame.
#[test]
fn a_string_that_is_not_the_opaque_spelling_is_refused() {
  assert_eq!(
    Cursor::<MediaValue>::decode("not a cursor"),
    Err(CursorError::Alphabet)
  );
}

/// A version byte this build does not know is a cursor from the FUTURE — an ordinary thing during a
/// rollout, and an ordinary refusal that names the version rather than reading the frame anyway.
#[test]
fn a_version_this_build_does_not_know_is_refused() {
  let mut frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");
  frame[0] = 2;

  assert_eq!(
    Cursor::<MediaValue>::decode(&text::encode(&frame)),
    Err(CursorError::Version(2))
  );
}

/// A frame that ends inside a field is refused rather than read as far as it goes — and the claimed
/// length is used to SPLIT bytes that are already here, so an enormous one is a refusal rather than
/// an allocation.
#[test]
fn a_truncated_frame_is_refused() {
  let frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");

  assert_eq!(
    Cursor::<MediaValue>::decode(&text::encode(&[])),
    Err(CursorError::Truncated),
    "a frame with no version byte"
  );
  assert_eq!(
    Cursor::<MediaValue>::decode(&text::encode(&frame[..5])),
    Err(CursorError::Truncated),
    "a frame whose signature is cut short"
  );
  assert_eq!(
    Cursor::<MediaValue>::decode(&text::encode(&frame[..12])),
    Err(CursorError::Truncated),
    "a frame whose first slot's length is cut short"
  );
  assert_eq!(
    Cursor::<MediaValue>::decode(&text::encode(&frame[..frame.len() - 1])),
    Err(CursorError::Truncated),
    "a frame whose last slot's value is cut short"
  );

  let mut enormous = frame.clone();
  enormous[10..14].copy_from_slice(&u32::MAX.to_be_bytes());
  assert_eq!(
    Cursor::<MediaValue>::decode(&text::encode(&enormous)),
    Err(CursorError::Truncated),
    "a length no frame this size could hold"
  );
}

/// A presence byte that is neither of the two is a frame this build cannot read, and reading it as
/// either would be reading a slot that was never written.
#[test]
fn a_presence_byte_that_is_neither_is_refused() {
  let mut frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");
  frame[9] = 2;

  assert_eq!(
    Cursor::<MediaValue>::decode(&text::encode(&frame)),
    Err(CursorError::Truncated)
  );
}

/// A slot whose bytes are not a value of the cursor's type is refused AT ITS OWN POSITION, so a
/// caller reading the error knows which column the client's string went wrong at.
#[test]
fn a_slot_that_is_not_a_value_of_this_type_is_refused_at_its_position() {
  let mut frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");
  // The second slot's tag byte: `created_at` occupies 1 presence + 4 length + 9 value bytes from
  // offset 9, so the next slot's tag is at 9 + 14 + 5.
  let tag = 9 + 14 + 5;
  frame[tag] = 9;

  assert_eq!(
    Cursor::<MediaValue>::decode(&text::encode(&frame)),
    Err(CursorError::Value(1))
  );
}

/// Every refusal says what it says in one sentence, because a teaching refusal that a client sees
/// is the whole of what it gets.
#[test]
fn the_refusals_say_which_one_they_are() {
  assert_eq!(
    CursorError::Order(OrderMismatch::new(
      OrderSignature::of(&order()),
      OrderSignature::of(&[])
    ))
    .to_string(),
    "this cursor was minted under another order (0x0a6c8216b482e628, replayed against \
     0xcbf29ce484222325)"
  );
  assert_eq!(
    CursorError::Arity(ArityMismatch::new(1, 3)).to_string(),
    "this cursor carries 1 values and the order has 3 terms"
  );
  assert_eq!(
    CursorError::Null(CREATED).to_string(),
    "this cursor is null at `created_at`, which is NOT NULL"
  );
  assert_eq!(
    CursorError::Version(2).to_string(),
    "this cursor is version 2 and this build reads version 1"
  );
  assert_eq!(
    CursorError::Value(1).to_string(),
    "this cursor's value 1 is not a value of that column"
  );
  assert_eq!(
    CursorError::Alphabet.to_string(),
    "this cursor is not base64url"
  );
  assert_eq!(
    CursorError::Truncated.to_string(),
    "this cursor's frame ends inside a field"
  );
}

/// **The COLLECTION slot: one slot of the SAME frame, whose bytes have inner structure.**
///
/// Fork A (i)'s whole content, pinned as bytes. The version stays `1`, the slot grammar stays
/// `presence | length | bytes`, and everything the list adds is INSIDE those bytes — so a build that
/// grew a frame-level tag or bumped the version would refuse every outstanding page, which is what
/// this stands between.
mod collection {
  use super::{Cursor, CursorError, CursorValue, OrderSignature, OrderTerm, TermName, text};
  use crate::{FieldName, OrderDirection};

  const TAGS: &TermName = TermName::new("tags");
  const ID: &TermName = TermName::new("id");

  /// The tag bytes of the sum below, in the emitted shape: one byte naming the column.
  const TAGS_TAG: u8 = 0;
  const ID_TAG: u8 = 1;

  /// A record whose `tags` column is a collection and whose id is the tail — the sum a record with
  /// an array-stored collection emits.
  #[derive(Debug, Clone, PartialEq)]
  enum Slot {
    Tags(Vec<String>),
    Id(i64),
  }

  impl CursorValue for Slot {
    fn write_cursor(&self, out: &mut Vec<u8>) {
      match self {
        Self::Tags(value) => {
          out.push(TAGS_TAG);
          value.write_cursor(out);
        }
        Self::Id(value) => {
          out.push(ID_TAG);
          value.write_cursor(out);
        }
      }
    }

    fn read_cursor(bytes: &[u8]) -> Option<Self> {
      let (tag, rest) = bytes.split_first()?;
      match *tag {
        TAGS_TAG => <Vec<String> as CursorValue>::read_cursor(rest).map(Self::Tags),
        ID_TAG => <i64 as CursorValue>::read_cursor(rest).map(Self::Id),
        _ => None,
      }
    }
  }

  /// `tags ASC, id ASC` — the collection term with the key tail that makes it total.
  fn order() -> [OrderTerm; 2] {
    [
      OrderTerm::array(TAGS, FieldName::new("tags"), OrderDirection::Asc),
      OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
    ]
  }

  /// A boundary at `["hdr", "sdr"]` and `id = 7`.
  fn boundary() -> Cursor<Slot> {
    Cursor::at(
      &order(),
      [
        Some(Slot::Tags(vec!["hdr".to_owned(), "sdr".to_owned()])),
        Some(Slot::Id(7)),
      ],
    )
  }

  /// **The bytes.** Version `1`, the signature, then two ordinary slots — and the first one's bytes
  /// are the sum's tag, the element COUNT, and the two length-prefixed elements.
  ///
  /// The slot's own four-byte length covers all of it, which is what *inner framing* means: the
  /// outer walk reads this slot exactly as it reads the `i64` beside it and never learns that one of
  /// them holds a list.
  #[test]
  fn a_collection_slot_is_one_slot_whose_bytes_carry_the_count_and_the_elements() {
    let frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");

    let mut expected = vec![1u8];
    expected.extend_from_slice(&OrderSignature::of(&order()).to_blob());
    // `tags`: present, and 1 tag byte + 4 count bytes + 2 × (4 length bytes + 3) = 19.
    expected.extend_from_slice(&[1, 0, 0, 0, 19, TAGS_TAG]);
    expected.extend_from_slice(&2u32.to_be_bytes());
    expected.extend_from_slice(&3u32.to_be_bytes());
    expected.extend_from_slice(b"hdr");
    expected.extend_from_slice(&3u32.to_be_bytes());
    expected.extend_from_slice(b"sdr");
    // `id`: present, a tag byte and eight — the ordinary slot beside it, unchanged.
    expected.extend_from_slice(&[1, 0, 0, 0, 9, ID_TAG]);
    expected.extend_from_slice(&7i64.to_be_bytes());

    assert_eq!(frame, expected);
    assert_eq!(frame[0], 1, "the frame version does not move for a list");
  }

  /// The EMPTY list is a PRESENT slot holding four zero bytes — a collection has no null state, so
  /// the least boundary is a value and never the absence the presence byte spells.
  #[test]
  fn an_empty_collection_is_a_present_slot_and_not_an_absent_one() {
    let cursor = Cursor::at(&order(), [Some(Slot::Tags(Vec::new())), Some(Slot::Id(1))]);
    let frame = text::decode(&cursor.encode()).expect("what `encode` wrote is base64url");

    assert_eq!(
      frame[9..14],
      [1, 0, 0, 0, 5],
      "PRESENT, and five bytes: the sum's tag and the count"
    );
    assert_eq!(frame[14..19], [TAGS_TAG, 0, 0, 0, 0]);
    assert_eq!(Cursor::<Slot>::decode(&cursor.encode()), Ok(cursor));
  }

  /// The whole trip, list and all — including an element that is itself empty, which the per-element
  /// length is what makes distinguishable from no element at all.
  #[test]
  fn a_collection_boundary_round_trips_through_its_opaque_string() {
    let cursor = Cursor::at(
      &order(),
      [
        Some(Slot::Tags(vec![
          "hdr".to_owned(),
          String::new(),
          "médià".to_owned(),
        ])),
        Some(Slot::Id(-1)),
      ],
    );

    assert_eq!(Cursor::<Slot>::decode(&cursor.encode()), Ok(cursor));
  }

  /// **A malformed INNER frame refuses in the existing per-slot family, at the slot's own
  /// position.** That is fork A (i)'s other half: no new error variant, because the frame gained no
  /// new field to be wrong in.
  ///
  /// Each mutation below leaves the OUTER frame perfectly walkable — the slot's own length is
  /// untouched — so what refuses is the list's own reading and nothing else.
  #[test]
  fn a_malformed_inner_frame_is_refused_as_a_value_at_its_slot() {
    let encoded = boundary().encode();
    let frame = text::decode(&encoded).expect("what `encode` wrote is base64url");
    // The inner count sits after the version, the signature, the presence byte, the four-byte slot
    // length and the sum's own tag.
    let count = 1 + 8 + 1 + 4 + 1;
    assert_eq!(frame[count..count + 4], [0, 0, 0, 2]);

    let overstated = {
      let mut frame = frame.clone();
      frame[count + 3] = 3;
      frame
    };
    assert_eq!(
      Cursor::<Slot>::decode(&text::encode(&overstated)),
      Err(CursorError::Value(0)),
      "a count larger than the elements behind it"
    );

    let understated = {
      let mut frame = frame.clone();
      frame[count + 3] = 1;
      frame
    };
    assert_eq!(
      Cursor::<Slot>::decode(&text::encode(&understated)),
      Err(CursorError::Value(0)),
      "…and one smaller, which leaves bytes no element owns"
    );

    let short = {
      let mut frame = frame.clone();
      // The FIRST element claims four bytes where three follow it, inside a slot whose own length
      // still covers everything.
      frame[count + 7] = 4;
      frame
    };
    assert_eq!(
      Cursor::<Slot>::decode(&text::encode(&short)),
      Err(CursorError::Value(0)),
      "an element length longer than the bytes behind it"
    );

    let invalid = {
      let mut frame = frame.clone();
      // A lone continuation byte in the first element: the framing is right and the ELEMENT's own
      // domain check is what refuses.
      frame[count + 8] = 0x80;
      frame
    };
    assert_eq!(
      Cursor::<Slot>::decode(&text::encode(&invalid)),
      Err(CursorError::Value(0)),
      "and an element the element's own row refuses"
    );

    // The unmutated frame decodes, so every refusal above is the mutation's and not the walk's.
    assert!(Cursor::<Slot>::decode(&encoded).is_ok());
  }
}