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
use crate::Context;
use core::time::Duration;

use std::{
  sync::{Arc, Mutex},
  thread,
  time::Instant,
};

use super::{
  super::{
    Ack, Answer, Delivery, Item, ItemId, Lifecycle, Payload, RecordingTap, Resident, Station, Taps,
    ack_channel, channel,
  },
  Attributes,
};
use crate::{Arrival, Emitter, Failure, NodeName, Operator, drive::Drives};

/// What a hand-wired hook records — the three columns a journal row is keyed and read by.
type Rows = Arc<Mutex<Vec<(u64, String, Station)>>>;

/// A media root, as a declared key's first column spells it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct MediaId(u64);

/// A record whose declared key is lineage-shaped: the media it descends from, then its own index.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Keyframe {
  media: MediaId,
  index: u32,
}

/// The hook a node wires by hand — the projection its emitted wrapper would supply, and somewhere
/// for the attributed observations to go.
struct Wired {
  rows: Rows,
}

impl Attributes<Keyframe> for Wired {
  type Root = MediaId;

  fn root(&self, record: &Keyframe) -> MediaId {
    // The whole of what a projection is: a field access on the record's declared key.
    record.media
  }

  fn observe(&self, root: &MediaId, worker: &NodeName, arrival: &Arrival) {
    self.rows.lock().expect("the rows").push((
      root.0,
      worker.as_str().to_owned(),
      arrival.station(),
    ));
  }
}

/// Addresses a frame into the media it came from — the shape an emitted wrapper has.
struct Framing;

impl Operator for Framing {
  type Error = core::convert::Infallible;
  type In = (u64, u32);
  type Out = Keyframe;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<Keyframe>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let (media, index) = item.into_value();
      emitter.emit(Keyframe {
        media: MediaId(media),
        index,
      });
    }
    Ok(())
  }
}

#[test]
fn a_wired_projection_reads_the_root_off_the_declared_key() {
  let rows: Rows = Arc::new(Mutex::new(Vec::new()));
  let wired = Wired { rows: rows.clone() };
  let keyframe = Keyframe {
    media: MediaId(7),
    index: 3,
  };
  assert_eq!(wired.root(&keyframe), MediaId(7));

  let arrival = Lifecycle::<()>::Persisted(()).arrive();
  wired.observe(&MediaId(7), NodeName::new("thumbs"), &arrival);
  assert_eq!(
    *rows.lock().expect("the rows"),
    [(7, "thumbs".to_owned(), Station::Persisted)]
  );
}

#[test]
fn the_absent_attribution_records_nothing_and_refuses_nothing() {
  // A node with nothing wired is legal, and what it costs is that its observations stay
  // counter-grade: a tap still sees the station, and no row can be keyed by a root.
  let arrival = Lifecycle::<()>::Processed(()).arrive();
  let nothing = ();
  let keyframe = Keyframe {
    media: MediaId(1),
    index: 0,
  };
  assert_eq!(Attributes::<Keyframe>::root(&nothing, &keyframe), ());
  Attributes::<Keyframe>::observe(&nothing, &(), NodeName::new("decode"), &arrival);
}

/// Answer the delivery waiting on `inbox`, as `worker`, with `lifecycle`, and say which keys it
/// released.
fn answer(
  downstream: &super::super::Inbox<ItemId, Keyframe>,
  worker: &str,
  released: bool,
  lifecycle: Lifecycle<()>,
) {
  let deadline = Instant::now() + Duration::from_secs(5);
  loop {
    match downstream.park(Duration::from_millis(5)) {
      Some(super::super::Wake::Delivered(delivery)) => {
        let (payload, ack) = delivery.into_parts();
        let ack = ack.expect("a delivery off the wire carries its custody token");
        let keys = if released {
          payload.keys().copied().collect()
        } else {
          std::collections::HashSet::new()
        };
        ack.send(Ack::new(keys, worker, lifecycle));
        return;
      }
      Some(super::super::Wake::Sweep | super::super::Wake::Tick(_)) => {
        assert!(Instant::now() < deadline, "no delivery arrived");
      }
      None => panic!("the sender is gone"),
    }
  }
}

#[test]
fn an_answer_comes_back_attributed_to_the_root_the_unit_projected() {
  // The seam driven by the LOOP rather than called directly: the node projects where it fans out,
  // the answer arrives keyed by a transport id the consumer has never heard of, and the two are
  // rejoined here — which is the whole of what the diagnostic half is.
  //
  // Two medias, and the second answer is a FAILURE. A failed delivery releases nothing, so a
  // pairing built out of released keys alone would record the first row and lose the second — and
  // the second is the badge-red one a reader is looking for.
  let rows: Rows = Arc::new(Mutex::new(Vec::new()));
  let tap = Arc::new(RecordingTap::new());
  let (feed, inbox) = channel::<ItemId, (u64, u32)>(8);
  let (out, downstream) = channel::<ItemId, Keyframe>(8);
  let resident = Resident::new("thumbs", Framing, inbox)
    .publish(out)
    .with_taps(Taps::new().with(tap.clone()))
    .attributing(Wired { rows: rows.clone() })
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  // The receivers are held to the end of the walk: dropping one would hang the delivery up, which
  // is a different path from the one this walk is about.
  let _held: Vec<_> = [(0u64, 11u64, 0u32), (1, 22, 5)]
    .into_iter()
    .map(|(seq, media, index)| {
      let (ack, answers) = ack_channel();
      feed
        .deliver(Delivery::new(
          Payload::One(Item::new(ItemId::new(seq), (media, index))),
          ack,
        ))
        .expect("the resident is listening");
      answers
    })
    .collect();

  answer(&downstream, "storer", true, Lifecycle::Persisted(()));
  answer(
    &downstream,
    "storer",
    false,
    Lifecycle::Failed(Failure::new(std::io::Error::other("the disk"))),
  );

  let deadline = Instant::now() + Duration::from_secs(5);
  while rows.lock().expect("the rows").len() < 2 && Instant::now() < deadline {
    thread::sleep(Duration::from_millis(5));
  }
  drop(feed);
  drop(downstream);
  engine.join().expect("the engine thread");

  let mut seen = rows.lock().expect("the rows").clone();
  seen.sort_by_key(|(root, _, _)| *root);
  assert_eq!(
    seen,
    [
      (11, "storer".to_owned(), Station::Persisted),
      // Attributed, released nothing, and named by the node that failed rather than by the one that
      // sent the frame.
      (22, "storer".to_owned(), Station::Failed),
    ]
  );
  assert_eq!(tap.len(), 2, "the counter-grade tap sees the same two");
}

#[test]
fn a_unit_with_no_projection_wired_still_runs_and_records_nothing() {
  // The legality of the absence, driven the same way. Every station a tap sees is the same; what
  // does not exist is a root to key a row by.
  let tap = Arc::new(RecordingTap::new());
  let (feed, inbox) = channel::<ItemId, (u64, u32)>(8);
  let (out, downstream) = channel::<ItemId, Keyframe>(8);
  let resident = Resident::new("thumbs", Framing, inbox)
    .publish(out)
    .with_taps(Taps::new().with(tap.clone()))
    .with_sweep(Duration::from_millis(5));
  let engine = thread::spawn(move || {
    let mut resident = resident;
    resident.run()
  });

  let (ack, answers) = ack_channel();
  feed
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), (11u64, 0u32))),
      ack,
    ))
    .expect("the resident is listening");
  assert!(matches!(
    answers.take(),
    Answer::Waiting | Answer::Settled(_)
  ));

  answer(&downstream, "storer", true, Lifecycle::Persisted(()));
  let deadline = Instant::now() + Duration::from_secs(5);
  while tap.is_empty() && Instant::now() < deadline {
    thread::sleep(Duration::from_millis(5));
  }
  drop(feed);
  drop(downstream);
  engine.join().expect("the engine thread");

  assert_eq!(tap.seen(), [("storer".to_owned(), Station::Persisted)]);
}

/// The DIAGNOSTIC half: the bounded queue, what a full one drops, and the writer that drains it.
mod queued {
  use core::time::Duration;

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

  use super::{
    super::{
      super::{AsyncLands, Commit, Lifecycle},
      Attributes, JournalRow, JournalTap, JournalWriter, journal_queue,
    },
    Keyframe, MediaId, Rows, Wired,
  };
  use crate::{Arrival, NodeName, Station};

  /// The deployment's own row: `(media, node)` and where it got to.
  #[derive(Debug, Clone, PartialEq, Eq)]
  struct Journal {
    media: u64,
    unit: String,
    station: Station,
  }

  impl JournalRow<MediaId> for Journal {
    fn of(root: &MediaId, node: &NodeName, arrival: &Arrival, _at: SystemTime) -> Self {
      Self {
        media: root.0,
        unit: node.as_str().to_owned(),
        station: arrival.station(),
      }
    }
  }

  /// A KEYED store: one entry per `(media, node)`, replaced.
  ///
  /// The keying is the whole reason a dropped observation is harmless, so a lane that appended would
  /// be testing something else.
  #[derive(Debug, Clone, Default)]
  struct Kept {
    rows: Arc<Mutex<BTreeMap<(u64, String), Station>>>,
  }

  impl AsyncLands<Journal> for Kept {
    type Error = core::convert::Infallible;

    async fn land(&mut self, items: &[Journal]) -> Commit<Self::Error> {
      let mut rows = self.rows.lock().expect("the rows");
      for row in items {
        rows.insert((row.media, row.unit.clone()), row.station);
      }
      Commit::all()
    }
  }

  #[test]
  fn a_full_queue_drops_the_oldest_and_keeps_the_newest() {
    // "The last run" is what the row says, so of two observations about one `(root, node)` the
    // later one is the one worth keeping. Dropping the NEWEST would leave the record permanently
    // stale; dropping the oldest leaves it merely behind.
    let (queue, drain) = journal_queue::<u8>(2);
    assert!(queue.offer(1));
    assert!(queue.offer(2));
    assert_eq!(queue.len(), 2);
    assert!(queue.offer(3), "a full queue still takes the row");
    assert_eq!(queue.len(), 2, "bounded, and it stayed bounded");

    let batch = drain
      .take(Duration::from_millis(50))
      .expect("the queue is open");
    assert_eq!(batch, [2, 3], "1 went, 3 arrived");
  }

  #[test]
  fn a_dropped_observation_is_harmless_because_the_next_one_overwrites_the_row() {
    // The claim the whole best-effort posture rests on, measured. A queue of ONE with nobody
    // draining loses every observation but the last, and the last is the one the record needs: the
    // row a reader ends up with is the same row a queue that lost nothing would have left.
    let (queue, drain) = journal_queue::<Journal>(1);
    let tap: JournalTap<Keyframe, MediaId, Journal> = JournalTap::new(|frame| frame.media, queue);
    let frame = Keyframe {
      media: MediaId(7),
      index: 0,
    };
    assert_eq!(tap.root(&frame), MediaId(7));

    for lifecycle in [
      Lifecycle::<()>::Processed(()),
      Lifecycle::<()>::Failed(crate::Failure::new(std::io::Error::other("a wobble"))),
      Lifecycle::<()>::Persisted(()),
    ] {
      tap.observe(&MediaId(7), NodeName::new("thumbs"), &lifecycle.arrive());
    }

    let kept = Kept::default();
    let mut writer =
      JournalWriter::new(drain, kept.clone()).with_patience(Duration::from_millis(5));
    drop(tap);
    let report = writer.run();

    assert_eq!(report.written(), 1, "two of the three were dropped");
    assert_eq!(report.refused(), 0);
    // And the row is the LAST state, which is what a dropped observation costs nothing against.
    assert_eq!(
      kept
        .rows
        .lock()
        .expect("the rows")
        .get(&(7, "thumbs".to_owned())),
      Some(&Station::Persisted)
    );
  }

  #[test]
  fn a_burst_of_observations_becomes_one_write() {
    // The batching is why the diagnostic half is queued rather than written where it is produced:
    // three nodes answering about three medias in one breath is ONE round trip.
    let (queue, drain) = journal_queue::<Journal>(64);
    let tap: JournalTap<Keyframe, MediaId, Journal> = JournalTap::new(|frame| frame.media, queue);
    for media in 1..=3u64 {
      tap.observe(
        &MediaId(media),
        NodeName::new("thumbs"),
        &Lifecycle::<()>::Persisted(()).arrive(),
      );
    }
    drop(tap);

    let kept = Kept::default();
    let mut writer =
      JournalWriter::new(drain, kept.clone()).with_patience(Duration::from_millis(5));
    let report = writer.run();
    assert_eq!(report.batches(), 1, "one write, not three");
    assert_eq!(report.written(), 3);
    assert_eq!(kept.rows.lock().expect("the rows").len(), 3);
  }

  #[test]
  fn the_writer_runs_on_a_thread_of_its_own_and_stops_when_the_queue_holders_go() {
    // The seam's own liveness: a writer parks on its queue, wakes when a row arrives, and ends when
    // the last holder of the queue is dropped. Nothing about it can reach back into a resident.
    let (queue, drain) = journal_queue::<Journal>(8);
    let kept = Kept::default();
    let mut writer =
      JournalWriter::new(drain, kept.clone()).with_patience(Duration::from_millis(5));
    let engine = thread::spawn(move || writer.run());

    let tap: JournalTap<Keyframe, MediaId, Journal> = JournalTap::new(|frame| frame.media, queue);
    tap.observe(
      &MediaId(9),
      NodeName::new("thumbs"),
      &Lifecycle::<()>::Persisted(()).arrive(),
    );
    drop(tap);

    let report = engine.join().expect("the writer thread");
    assert_eq!(report.written(), 1);
    assert_eq!(
      kept
        .rows
        .lock()
        .expect("the rows")
        .get(&(9, "thumbs".to_owned())),
      Some(&Station::Persisted)
    );
  }

  #[test]
  fn the_shipped_composition_answers_what_a_hand_wired_hook_answers() {
    // The seam is OPEN: the shipped composition and a hand-written hook are two implementations of
    // one trait, and a deployment that wants its own destination writes the second without touching
    // anything the loop does.
    let rows: Rows = Arc::new(Mutex::new(Vec::new()));
    let wired = Wired { rows };
    let (queue, _drain) = journal_queue::<Journal>(4);
    let shipped: JournalTap<Keyframe, MediaId, Journal> =
      JournalTap::new(|frame| frame.media, queue);
    let frame = Keyframe {
      media: MediaId(4),
      index: 1,
    };
    // One projection, two implementations of the seam that carries it.
    assert_eq!(wired.root(&frame), shipped.root(&frame));
  }
}