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
use std::{collections::HashSet, sync::Arc};

use super::super::{
  Ack, Answer, Custody, Delivery, Item, ItemId, Lifecycle, NodeName, Observation, Payload, Station,
  Unreceipted, ack_channel,
};
use crate::{LifecycleTap, Skip, SkipReason};

fn one(seq: u64) -> Payload<u8> {
  Payload::One(Item::new(ItemId::new(seq), seq as u8))
}

fn batch(seqs: &[u64]) -> Payload<u8> {
  Payload::Batch(
    seqs
      .iter()
      .map(|&seq| Item::new(ItemId::new(seq), seq as u8))
      .collect(),
  )
}

#[test]
fn a_single_item_payload_is_one_item_and_allocates_no_vec() {
  let payload = one(7);
  assert_eq!(payload.len(), 1);
  assert!(!payload.is_empty());
  assert_eq!(
    payload.keys().copied().collect::<Vec<_>>(),
    [ItemId::new(7)]
  );
  // The owning walk over `One` is the single slot, not a `Vec` walk — the `size_hint` is the
  // observable form of that, since a `Vec::IntoIter` would report the same numbers by a different
  // route only if a `Vec` had been built.
  let mut walk = payload.into_iter();
  assert_eq!(walk.size_hint(), (1, Some(1)));
  assert_eq!(walk.next().map(Item::into_parts), Some((ItemId::new(7), 7)));
  assert_eq!(walk.size_hint(), (0, Some(0)));
  assert!(walk.next().is_none());
}

#[test]
fn a_batch_keeps_send_order_through_the_walk() {
  let payload = batch(&[3, 1, 2]);
  assert_eq!(payload.len(), 3);
  assert_eq!(
    payload.keys().copied().collect::<Vec<_>>(),
    [ItemId::new(3), ItemId::new(1), ItemId::new(2)]
  );
  assert_eq!(
    payload.into_iter().map(|i| *i.key()).collect::<Vec<_>>(),
    [ItemId::new(3), ItemId::new(1), ItemId::new(2)]
  );
}

#[test]
fn an_empty_batch_is_empty() {
  let payload: Payload<u8> = Payload::Batch(Vec::new());
  assert_eq!(payload.len(), 0);
  assert!(payload.is_empty());
}

#[test]
fn a_delivery_splits_into_its_payload_and_its_oneshot() {
  let (ack, answers) = ack_channel::<ItemId>();
  let delivery = Delivery::new(one(1), ack);
  assert_eq!(delivery.payload().len(), 1);
  let (payload, ack) = delivery.into_parts();
  let ack = ack.expect("a delivery off the wire carries its custody token");
  assert_eq!(payload.len(), 1);
  assert!(ack.send(Ack::<ItemId, ()>::holding(
    "consumer",
    Lifecycle::Processed(())
  )));
  assert!(answers.take().is_settled());
}

#[test]
fn a_delivery_in_custody_carries_the_message_and_not_the_promise() {
  // The shape a driver hands an operator: the obligation was opened for the whole inbound delivery
  // before the walk began, so the item's own delivery has no token to answer on and the walk is
  // what the operator gets.
  let delivery = Delivery::in_custody(batch(&[1, 2, 3]));
  assert_eq!(delivery.payload().len(), 3);
  let values: Vec<u8> = delivery.into_items().map(Item::into_value).collect();
  assert_eq!(values, [1, 2, 3]);

  let delivery = Delivery::in_custody(one(7));
  assert!(delivery.into_parts().1.is_none(), "nothing to answer on");
}

#[test]
fn an_ack_that_holds_releases_nothing() {
  let ack = Ack::<ItemId, ()>::holding("consumer", Lifecycle::Processed(()));
  assert!(ack.released().is_empty());
  assert_eq!(ack.lifecycle().station(), Station::Processed);
}

#[test]
fn releasing_names_exactly_what_it_was_given() {
  let ack = Ack::<ItemId, ()>::holding("consumer", Lifecycle::Processed(()))
    .releasing(ItemId::new(1))
    .releasing(ItemId::new(3));
  let released: HashSet<ItemId> = ack.released().clone();
  assert_eq!(released.len(), 2);
  assert!(released.contains(&ItemId::new(1)));
  assert!(!released.contains(&ItemId::new(2)));
}

#[test]
fn an_ack_built_from_a_set_keeps_it_verbatim() {
  let set: HashSet<ItemId> = (0..4).map(ItemId::new).collect();
  let ack = Ack::new(set.clone(), "consumer", Lifecycle::Persisted(9u32));
  assert_eq!(ack.released(), &set);
  assert_eq!(*ack.lifecycle().unwrap_persisted_ref(), 9);
}

#[test]
fn the_oneshot_answers_once_and_the_receiver_reads_the_split_halves() {
  let (ack, answers) = ack_channel::<ItemId>();
  assert!(answers.take().is_waiting());
  let sent = Ack::holding("consumer", Lifecycle::Persisted(())).releasing(ItemId::new(4));
  assert!(ack.send(sent));
  let Answer::Settled(settled) = answers.take() else {
    panic!("the answer was sent");
  };
  assert_eq!(settled.released().len(), 1);
  assert_eq!(settled.observation().station(), Some(Station::Persisted));
  let (released, worker, observation, message, receipts) = settled.into_parts();
  assert!(released.contains(&ItemId::new(4)));
  assert_eq!(worker, "consumer");
  assert_eq!(observation.station(), Some(Station::Persisted));
  // An ordinary arrival carries no fate, so the extra-message slot a terminal fills is empty here.
  assert!(message.is_none());
  // And nothing receipted, so the answer's own slot is ABSENT — not an empty map but no map at all,
  // which is what every consumer written before this slot existed carries.
  assert!(receipts.is_none());
}

#[test]
fn a_dropped_oneshot_reads_as_hung_up_and_never_as_an_answer() {
  let (ack, answers) = ack_channel::<ItemId>();
  drop(ack);
  assert!(answers.take().is_hung_up());
}

#[test]
fn a_sender_whose_receiver_is_gone_reports_that_it_was_not_heard() {
  let (ack, answers) = ack_channel::<ItemId>();
  drop(answers);
  assert!(!ack.send(Ack::<ItemId, ()>::holding(
    "consumer",
    Lifecycle::Processed(())
  )));
}

#[test]
fn the_info_type_is_erased_at_the_oneshot_and_asked_for_back_at_the_tap() {
  // Two consumers of one edge, each naming its OWN info type. A transport typed in the info could
  // hold one of them; erasing at the boundary is what lets both cross and both be recovered.
  #[derive(Debug, PartialEq)]
  struct Bytes(usize);
  #[derive(Debug, PartialEq)]
  struct Rows(&'static str);

  fn answer<I: core::any::Any + Send + Sync>(info: I) -> Observation {
    let (ack, answers) = ack_channel::<ItemId>();
    assert!(ack.send(Ack::<ItemId, I>::holding(
      "consumer",
      Lifecycle::Persisted(info)
    )));
    let Answer::Settled(settled) = answers.take() else {
      panic!("the answer was sent");
    };
    settled.into_parts().2
  }

  let bytes = answer(Bytes(4096));
  assert_eq!(bytes.info::<Bytes>(), Some(&Bytes(4096)));
  assert_eq!(bytes.info::<Rows>(), None);

  let rows = answer(Rows("scene"));
  assert_eq!(rows.info::<Rows>(), Some(&Rows("scene")));
  assert_eq!(rows.info::<usize>(), None);
}

#[test]
fn a_refusal_crosses_whole_and_a_failure_crosses_erased() {
  let (ack, answers) = ack_channel::<ItemId>();
  let skip = Skip::new(SkipReason::custom("oversize")).about("scene#3");
  assert!(ack.send(Ack::<ItemId, ()>::holding(
    "consumer",
    Lifecycle::Skipped(skip)
  )));
  let Answer::Settled(settled) = answers.take() else {
    panic!("the answer was sent");
  };
  let observation = settled.into_parts().2;
  assert_eq!(observation.station(), Some(Station::Skipped));
  let skip = observation.skip().expect("a skipped station carries one");
  assert_eq!(skip.reason().as_str(), "oversize");
  assert_eq!(skip.content(), Some("scene#3"));
  assert!(observation.failure().is_none());
}

// One tap, several nodes, several info types — the shape the erasure exists for.
#[derive(Default)]
struct Counting {
  stations: std::sync::Mutex<Vec<(String, Station, Option<usize>)>>,
}

impl LifecycleTap for Counting {
  fn observe(&self, node: &NodeName, observation: &Observation) {
    let Some(arrival) = observation.arrival() else {
      return;
    };
    self.stations.lock().expect("the tap's lock").push((
      node.as_str().to_owned(),
      arrival.station(),
      arrival.info::<usize>().copied(),
    ));
  }
}

#[test]
fn one_tap_observes_units_carrying_different_info_types() {
  let tap = Arc::new(Counting::default());
  let taps = crate::Taps::new().with(tap.clone());

  for (node, observation) in [
    ("decode", Lifecycle::<usize>::Processed(12).erase()),
    (
      "store",
      Lifecycle::<&'static str>::Persisted("rows").erase(),
    ),
  ] {
    <crate::Taps as LifecycleTap>::observe(&taps, NodeName::new(node), &observation);
  }

  let seen = tap.stations.lock().expect("the tap's lock").clone();
  assert_eq!(
    seen,
    vec![
      ("decode".to_owned(), Station::Processed, Some(12)),
      // The second node's info is not a `usize`, so the tap asks and is told no — which is the
      // honest answer, and not an error.
      ("store".to_owned(), Station::Persisted, None),
    ]
  );
}

#[test]
fn a_delivery_can_be_answered_by_a_consumer_that_never_reads_the_payload() {
  // The obligation is the oneshot, not the data: a consumer that decides on the keys alone is a
  // legal consumer, which is what makes a storage co-subscriber expressible later.
  let (ack, answers) = ack_channel::<ItemId>();
  let delivery = Delivery::new(batch(&[1, 2, 3]), ack);
  let (payload, ack): (_, Option<Custody<ItemId>>) = delivery.into_parts();
  let ack = ack.expect("a delivery off the wire carries its custody token");
  let released: HashSet<ItemId> = payload.keys().copied().collect();
  assert!(ack.send(Ack::new(released, "consumer", Lifecycle::Persisted(()))));
  let Answer::Settled(settled) = answers.take() else {
    panic!("answered");
  };
  assert_eq!(settled.released().len(), 3);
}

/// A durable id, standing where a seat's own key type would: the whole point of the receipt is that
/// only the consumer knew this number, so the test's producer must have no way to compute it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SceneId(u64);

/// A DECLARED MESSAGE, standing in for the impl a `receipt = "…"` word emits — hand-written here,
/// because the seat is a public trait and a message is not obliged to be generated to fill it.
///
/// The self type is the MESSAGE and not the consumer: a receipt answers the item that was GIVEN, so
/// every seat over one message answers one declared question rather than each declaring its own.
struct SceneOpen;

impl crate::Receipts for SceneOpen {
  type Receipt = SceneId;
}

#[test]
fn an_ack_carries_a_typed_receipt_per_item_and_the_producer_reads_it_back() {
  let (ack, answers) = ack_channel::<ItemId>();
  let delivery = Delivery::new(batch(&[1, 2]), ack);
  let (payload, custody) = delivery.into_parts();
  let custody = custody.expect("a delivery off the wire carries its custody token");
  let released: HashSet<ItemId> = payload.keys().copied().collect();

  // The consumer answers BOTH items and receipts about one of them — which is the ordinary shape:
  // a receipt is per item and an item that has nothing to say says nothing.
  assert!(custody.send(
    Ack::new(released, "seat", Lifecycle::Persisted(())).receipting(ItemId::new(1), SceneId(4242))
  ));

  let Answer::Settled(mut settled) = answers.take() else {
    panic!("answered");
  };
  assert_eq!(settled.released().len(), 2);
  assert!(settled.has_receipt(&ItemId::new(1)));
  assert_eq!(
    settled.receipt::<SceneId>(&ItemId::new(1)),
    Ok(&SceneId(4242))
  );
  // The item that stated nothing is SILENT and not an error path: the ack arrived, and what it did
  // not carry is the value.
  assert_eq!(
    settled.receipt::<SceneId>(&ItemId::new(2)),
    Err(Unreceipted::Silent)
  );
  // A wrong type is its own arm, and a refused take leaves the receipt where it was.
  assert_eq!(
    settled.take_receipt::<String>(&ItemId::new(1)),
    Err(Unreceipted::Mismatched)
  );
  assert_eq!(
    settled.take_receipt::<SceneId>(&ItemId::new(1)),
    Ok(SceneId(4242))
  );
  // Taken once, and once only — the value MOVED out.
  assert_eq!(
    settled.take_receipt::<SceneId>(&ItemId::new(1)),
    Err(Unreceipted::Silent)
  );
}

#[test]
fn a_receipt_does_not_release_and_a_release_does_not_receipt() {
  // The two facts are independent at the transport, which is what lets a consumer that computed an
  // answer but could not make it durable state the answer and still hold the key.
  let (ack, answers) = ack_channel::<ItemId>();
  let delivery = Delivery::new(one(9), ack);
  let (_payload, custody) = delivery.into_parts();
  let custody = custody.expect("token");
  assert!(
    custody.send(
      Ack::<ItemId, ()>::holding(
        "seat",
        Lifecycle::Failed(crate::Failure::new(std::io::Error::other(
          "the store would not take it"
        )))
      )
      .receipting(ItemId::new(9), SceneId(1))
    )
  );

  let Answer::Settled(settled) = answers.take() else {
    panic!("answered");
  };
  assert!(
    settled.released().is_empty(),
    "a receipt released a key nothing said to release"
  );
  assert_eq!(settled.receipt::<SceneId>(&ItemId::new(9)), Ok(&SceneId(1)));
  assert_eq!(settled.observation().station(), Some(Station::Failed));
}

#[test]
fn a_fate_carries_no_receipt_because_no_consumer_saw_it() {
  let (ack, answers) = ack_channel::<ItemId>();
  let released: HashSet<ItemId> = [ItemId::new(3)].into_iter().collect();
  assert!(ack.fate(
    released,
    "gate",
    crate::Fate::GivenUp {
      attempt: 3,
      failure: None,
      message: (),
    }
  ));
  let Answer::Settled(settled) = answers.take() else {
    panic!("answered");
  };
  assert!(!settled.has_receipt(&ItemId::new(3)));
  assert_eq!(
    settled.receipt::<SceneId>(&ItemId::new(3)),
    Err(Unreceipted::Silent)
  );
}

#[test]
fn an_obligation_carries_its_receipts_through_to_the_settle() {
  // `Owed` is where a driver parks a receipt between the item that stated it and the ack that is sent
  // once for the whole delivery — and under a chained mode, a whole pass later.
  let (ack, answers) = ack_channel::<ItemId>();
  let delivery = Delivery::new(batch(&[5, 6]), ack);
  let (payload, custody) = delivery.into_parts();
  let mut owed = super::super::Owed::open(payload.keys().copied(), custody);
  // The DECLARED door, which is what a seat over a message carrying a `receipt` word reaches for:
  // the same slot and the same box, with the type read off `<SceneOpen as Receipts>::Receipt`
  // instead of written here.
  owed.receipt_of::<SceneOpen>(ItemId::new(5), SceneId(55));
  owed.release(ItemId::new(5));
  owed.release(ItemId::new(6));
  assert!(owed.settle("seat", Lifecycle::Persisted(())));

  let Answer::Settled(settled) = answers.take() else {
    panic!("answered");
  };
  assert_eq!(
    settled.receipt::<SceneId>(&ItemId::new(5)),
    Ok(&SceneId(55))
  );
  assert_eq!(
    settled.receipt::<SceneId>(&ItemId::new(6)),
    Err(Unreceipted::Silent)
  );
}

#[test]
fn a_joined_custody_answers_on_each_member_and_carries_no_composed_receipt() {
  // A joined answer is owed to SEVERAL senders on several tokens, and one boxed value cannot be
  // split between them — so the composed answer's own receipt slot is dropped by name, and what each
  // member sends is the receipt its OWN obligation collected.
  let (ack, answers) = ack_channel::<ItemId>();
  let delivery = Delivery::new(one(1), ack);
  let (payload, custody) = delivery.into_parts();
  let owing = super::super::Owing::open(payload.keys().copied(), custody);
  let composed = Custody::joined(ItemId::new(70), vec![owing.share(ItemId::new(1))]);
  assert!(
    composed.send(
      Ack::new(
        [ItemId::new(70)].into_iter().collect(),
        "join",
        Lifecycle::Processed(())
      )
      .receipting(ItemId::new(70), SceneId(7))
    )
  );

  let Answer::Settled(settled) = answers.take() else {
    panic!("the member's own token was answered");
  };
  assert!(settled.released().contains(&ItemId::new(1)));
  assert!(
    !settled.has_receipt(&ItemId::new(70)),
    "the composed answer's receipt reached a member's token"
  );
}

#[test]
fn a_waiting_door_and_a_polling_door_read_one_oneshot() {
  // `take` is the WINDOW's poll and `settled` is the acked give's wait, and both are the same
  // oneshot — so a hung-up token is `HungUp` at either door and never a hang at this one.
  let (ack, answers) = ack_channel::<ItemId>();
  assert!(answers.take().is_waiting());
  drop(ack);
  assert_eq!(
    answers
      .settled_within(core::time::Duration::from_secs(5))
      .err(),
    Some(super::Unsettled::HungUp)
  );

  let (ack, answers) = ack_channel::<ItemId>();
  // A budget that elapses is its own arm, and it says nothing about the consumer.
  assert_eq!(
    answers
      .settled_within(core::time::Duration::from_millis(50))
      .err(),
    Some(super::Unsettled::TimedOut)
  );
  drop(ack);
}