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
use crate::{
  Context, Delivery, Feed, Fin, Item, ItemId, Payload, ReasonName, Stopper, Wanted, feed,
  operator::{Emission, Emitter, Operator, Skip, SkipLabel, SkipReason, StreamOperator, subscribe},
  shutdown_signal,
};

// Producer: emits a keyframe image.
struct Scenes;
impl Operator for Scenes {
  type In = ();
  type Out = &'static str;
  type Error = core::convert::Infallible;
  fn accept(
    &mut self,
    _ctx: &Context,
    _delivery: Delivery<Self::In>,
    _emitter: &mut Emitter<Self::Out>,
  ) -> Result<(), Self::Error> {
    Ok(())
  }
}

// Enricher: consumes exactly the producer's output.
struct Vlm;
impl Operator for Vlm {
  type In = &'static str;
  type Out = String;
  type Error = core::convert::Infallible;
  fn accept(
    &mut self,
    _ctx: &Context,
    _delivery: Delivery<Self::In>,
    _emitter: &mut Emitter<Self::Out>,
  ) -> Result<(), Self::Error> {
    Ok(())
  }
}

// A filter: keeps even numbers, skips odd ones — an operator whose one `accept` call both emits
// and skips, standing in for the shape an app-level test drives through the public read alone.
struct FilterEvens;
impl Operator for FilterEvens {
  type In = u32;
  type Out = u32;
  type Error = core::convert::Infallible;
  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<Self::Out>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let value = item.into_value();
      if value % 2 == 0 {
        emitter.emit(value);
      } else {
        emitter.skip(SkipReason::Filtered);
      }
    }
    Ok(())
  }
}

#[test]
fn subscribe_wires_matching_output_to_input() {
  // Compiles because Vlm::Input == Scenes::Output.
  subscribe(&Scenes, &Vlm);
}

#[test]
fn context_buffers_emissions_in_order() {
  let mut emitter = Emitter::<u32>::new();
  emitter.emit(1);
  emitter.skip(SkipReason::Filtered);
  emitter.emit(2);
  let out: Vec<Emission<u32>> = emitter.drain();
  assert_eq!(out.len(), 3);
  assert!(out[0].is_emit());
  assert!(out[1].is_skip());
  assert!(out[2].is_emit());
  assert_eq!(*out[0].unwrap_emit_ref(), 1);
  assert_eq!(*out[2].unwrap_emit_ref(), 2);
}

#[test]
fn the_public_read_asserts_without_a_side_door() {
  // findit-studio/ingraph#348's own shape: build `Emitter::new().wanting(…)`, drive an `accept`,
  // read back items AND a skip — zero per-operator side doors. `emissions`/`into_emissions` are
  // what makes this possible from OUTSIDE the crate, since `drain` (used above) stays
  // `pub(crate)`.
  let mut emitter = Emitter::<u32>::new().wanting(Wanted::sole(true));
  let delivery = Delivery::in_custody(Payload::Batch(vec![
    Item::new(ItemId::new(0), 4),
    Item::new(ItemId::new(1), 7),
  ]));
  FilterEvens
    .accept(&Context::new("filter-evens"), delivery, &mut emitter)
    .unwrap();

  // The borrow half: assert without consuming the organ.
  let seen = emitter.emissions();
  assert_eq!(seen.len(), 2);
  assert!(seen[0].is_emit());
  assert_eq!(*seen[0].unwrap_emit_ref(), 4);
  assert!(seen[1].is_skip());
  assert!(seen[1].unwrap_skip_ref().reason().is_filtered());

  // The owned half: the public counterpart of the driver's own `drain`, same buffer.
  let out = emitter.into_emissions();
  assert_eq!(out.len(), 2);
  assert!(out[0].is_emit());
  assert!(out[1].is_skip());
}

#[test]
fn skip_reason_names_are_stable() {
  assert_eq!(SkipReason::Filtered.as_str(), "filtered");
  assert_eq!(SkipReason::NoConsumers.as_str(), "no_consumers");
  assert_eq!(SkipReason::ServiceInactive.as_str(), "service_inactive");
  assert_eq!(SkipReason::NoConsumers.to_string(), "no_consumers");
}

#[test]
fn custom_skip_reason_round_trips() {
  // The Custom escape is lossless: as_str returns the operator-authored label
  // verbatim, and Display routes through as_str.
  let r = SkipReason::custom("late_frame");
  assert!(r.is_custom());
  assert_eq!(r.as_str(), "late_frame");
  assert_eq!(r.to_string(), "late_frame");
}

// One operator's own refusal vocabulary — the shape every app writes, standing in for the two
// sides of the round-trip (the operator that encodes, the tap that decodes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Refusal {
  Oversize,
  Unreadable,
}

impl SkipLabel for Refusal {
  fn label(&self) -> &'static ReasonName {
    match self {
      Self::Oversize => ReasonName::new("oversize"),
      Self::Unreadable => ReasonName::new("unreadable"),
    }
  }

  fn from_label(label: &ReasonName) -> Option<Self> {
    match label.as_ref() {
      "oversize" => Some(Self::Oversize),
      "unreadable" => Some(Self::Unreadable),
      _ => None,
    }
  }
}

// A SECOND vocabulary, deliberately disjoint from Refusal: one tap observes operators carrying
// different reason enums, which is why the wire form is erased.
#[derive(Debug, PartialEq, Eq)]
enum Verdict {
  Stale,
}

impl SkipLabel for Verdict {
  fn label(&self) -> &'static ReasonName {
    ReasonName::new("stale")
  }

  fn from_label(label: &ReasonName) -> Option<Self> {
    (label.as_ref() == "stale").then_some(Self::Stale)
  }
}

#[test]
fn a_typed_reason_survives_the_erased_wire_form() {
  // The law: encode ∘ decode is the identity on the operator's own vocabulary.
  for reason in [Refusal::Oversize, Refusal::Unreadable] {
    let wire = SkipReason::encode(&reason);
    assert!(wire.is_custom());
    assert_eq!(wire.as_str(), reason.label().as_ref());
    assert_eq!(wire.decode::<Refusal>(), Some(reason));
  }
}

#[test]
fn a_label_outside_the_vocabulary_decodes_to_none() {
  // Another operator's reason, a built-in, and a bare hand-written label all decode to None
  // rather than to a wrong variant — the property that makes decoding safe at a tap that
  // observes the whole graph.
  assert_eq!(
    SkipReason::encode(&Verdict::Stale).decode::<Refusal>(),
    None
  );
  assert_eq!(SkipReason::Filtered.decode::<Refusal>(), None);
  assert_eq!(SkipReason::custom("oversized").decode::<Refusal>(), None);
  // ...and the reverse direction, so neither vocabulary can claim the other's.
  assert_eq!(
    SkipReason::encode(&Refusal::Oversize).decode::<Verdict>(),
    None
  );
}

#[test]
fn a_skip_composes_its_two_independent_facts() {
  // The reason and the content are orthogonal, so each is opt-in and neither multiplies the
  // emission verbs: a bare reason still buffers through `From`, and `about` adds the answer to
  // "which item?" without touching the reason.
  let bare = Skip::new(SkipReason::Filtered);
  assert!(bare.reason().is_filtered());
  assert_eq!(bare.content(), None);

  let named = Skip::new(SkipReason::encode(&Refusal::Oversize)).about("chapter-9.md");
  assert_eq!(named.reason().decode::<Refusal>(), Some(Refusal::Oversize));
  assert_eq!(named.content(), Some("chapter-9.md"));

  let mut emitter = Emitter::<u32>::new();
  emitter.skip(SkipReason::Filtered);
  emitter.skip(named.clone());
  let out = emitter.drain();
  assert_eq!(*out[0].unwrap_skip_ref(), bare);
  assert_eq!(*out[1].unwrap_skip_ref(), named);
}

// ---- The STREAMING face -------------------------------------------------------------------
//
// Driven BY HAND throughout, which is the honest state as well as the shape: no lane spawns a
// `StreamOperator` yet, so a test builds the three seats itself — a feed pair, a stop pair, a
// delivery — and reads the answer at the DRAIN. That is the external-assertion shape the buffered
// face's own tests use, one seat over: nothing per-operator is opened to make a run readable.

/// One delivery carrying one document — the shape every case below runs over.
fn one(text: &str) -> Delivery<String> {
  Delivery::in_custody(Payload::One(Item::new(ItemId::new(0), text.to_owned())))
}

// A chunker: one document becomes as many windows as it has room for. THE FACE-SELECTION LAW's own
// example — the fan-out grows with the input's length, so a buffered `accept` would hold every
// window of a 2 GB document before the driver drained one.
struct Windows {
  width: usize,
}

impl StreamOperator for Windows {
  type In = String;
  type Out = String;
  type Error = core::convert::Infallible;

  fn run(
    &mut self,
    ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    for item in delivery.into_items() {
      for window in item.into_value().into_bytes().chunks(self.width) {
        if ctx.shutdown().is_shutdown() {
          return Ok(Fin::Stopped);
        }
        if feed
          .give(String::from_utf8_lossy(window).into_owned())
          .is_err()
        {
          return Ok(Fin::Stopped);
        }
      }
    }
    Ok(Fin::Spent)
  }
}

// The same chunker, hearing the framework MID-RUN: it holds the framework's own half of the stop
// line and says the stop after `announce_after` windows. That is the one way a single-threaded test
// can put the announcement where a running deployment would — INSIDE the run rather than before it —
// and it keeps the case deterministic, which a second thread would not.
struct StoppedMidway {
  announce_after: usize,
  stopper: Stopper,
}

impl StreamOperator for StoppedMidway {
  type In = String;
  type Out = String;
  type Error = core::convert::Infallible;

  fn run(
    &mut self,
    ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    let mut given = 0;
    for item in delivery.into_items() {
      for window in item.into_value().into_bytes() {
        if ctx.shutdown().is_shutdown() {
          return Ok(Fin::Stopped);
        }
        if feed.give((window as char).to_string()).is_err() {
          return Ok(Fin::Stopped);
        }
        given += 1;
        if given == self.announce_after {
          self.stopper.announce();
        }
      }
    }
    Ok(Fin::Spent)
  }
}

/// A run that DIED — it neither finished nor was stopped. Carries how far it got, which is the
/// failure scene the ruling puts on the author's own error rather than on an ending arm.
#[derive(Debug, PartialEq, Eq)]
struct Torn {
  after: usize,
}

// A chunker that tears at a fixed window: the `Err` case, and the one that proves the already-given
// products stand.
struct Tearing {
  after: usize,
}

impl StreamOperator for Tearing {
  type In = String;
  type Out = String;
  type Error = Torn;

  fn run(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    feed: Feed<Self::Out>,
  ) -> Result<Fin, Self::Error> {
    let mut given = 0;
    for item in delivery.into_items() {
      for window in item.into_value().into_bytes() {
        if given == self.after {
          return Err(Torn { after: given });
        }
        if feed.give((window as char).to_string()).is_err() {
          return Ok(Fin::Stopped);
        }
        given += 1;
      }
    }
    Ok(Fin::Spent)
  }
}

#[test]
fn a_stream_run_reaches_the_drain_and_ends_spent() {
  // The whole shape a hand-driven case needs: the two mints, one delivery, one `run`, and the
  // items read off the FAR END. `Fin::Spent` is the origin layer's own word, reused verbatim —
  // read here as "this delivery streamed to its end".
  let (given, yielded) = feed::<String>(16);
  let (_stopper, stop) = shutdown_signal();
  let ctx = Context::new("windows").halting(stop);

  assert_eq!(
    Windows { width: 3 }.run(&ctx, one("abcdefg"), given),
    Ok(Fin::Spent)
  );
  assert_eq!(yielded.drain().collect::<Vec<_>>(), ["abc", "def", "g"]);
}

#[test]
fn the_line_closes_when_the_run_returns() {
  // The `Feed` is taken BY VALUE, so it is dropped with the run and the drain sees the end of one
  // delivery's stream without being told about it separately. That is what makes a per-delivery
  // life readable at the far end at all.
  let (given, yielded) = feed::<String>(16);
  let (_stopper, stop) = shutdown_signal();
  let ctx = Context::new("windows").halting(stop);

  assert!(!yielded.is_disconnected());
  assert_eq!(
    Windows { width: 7 }.run(&ctx, one("abcdefg"), given),
    Ok(Fin::Spent)
  );
  assert!(yielded.is_disconnected());
  assert_eq!(yielded.take(), Some("abcdefg".to_owned()));
  assert_eq!(yielded.take(), None);
}

#[test]
fn a_stop_heard_mid_run_ends_stopped_with_the_prefix_standing() {
  // The stop is said after two windows and read on the third pass. The run answers `Fin::Stopped`
  // — the second of the two endings, not an error — and the two windows it had already given are
  // AT THE DRAIN: a wound-down run's outputs are outputs.
  let (given, yielded) = feed::<String>(16);
  let (stopper, stop) = shutdown_signal();
  let ctx = Context::new("windows").halting(stop);

  let mut unit = StoppedMidway {
    announce_after: 2,
    stopper,
  };
  assert_eq!(unit.run(&ctx, one("abcdefg"), given), Ok(Fin::Stopped));
  assert_eq!(yielded.drain().collect::<Vec<_>>(), ["a", "b"]);
}

#[test]
fn an_err_dead_letters_the_delivery_and_the_given_products_stand() {
  // `Err` is the WHOLE DELIVERY's dead-letter, and the ruling's second clause is what this holds:
  // everything already given crossed the feed before the failure and is valid independently of it.
  // Nothing recalls it, and the failure scene rides the author's own error rather than an ending
  // arm — which is why `Fin` could stay two-armed.
  let (given, yielded) = feed::<String>(16);
  let (_stopper, stop) = shutdown_signal();
  let ctx = Context::new("windows").halting(stop);

  assert_eq!(
    Tearing { after: 3 }.run(&ctx, one("abcdefg"), given),
    Err(Torn { after: 3 })
  );
  assert_eq!(yielded.drain().collect::<Vec<_>>(), ["a", "b", "c"]);
}

#[test]
fn the_wait_for_room_is_what_carries_a_wide_stream_down_a_narrow_line() {
  // BACKPRESSURE IS THE CONTRACT: a capacity-ONE feed and seven windows, and the run finishes only
  // because `give` WAITED for room each time. A door that refused instead of waiting would have
  // ended this run at the second window with `Fin::Stopped` and five windows unsent.
  let (given, yielded) = feed::<String>(1);
  let (_stopper, stop) = shutdown_signal();
  let ctx = Context::new("windows").halting(stop);
  let streamed = std::thread::spawn(move || Windows { width: 1 }.run(&ctx, one("abcdefg"), given));

  let mut taken = Vec::new();
  while let Some(window) = yielded.take() {
    taken.push(window);
  }

  assert_eq!(streamed.join().unwrap(), Ok(Fin::Spent));
  assert_eq!(taken, ["a", "b", "c", "d", "e", "f", "g"]);
}

#[test]
fn decode_reads_the_whole_reason_not_just_the_custom_payload() {
  // `decode` goes through `as_str`, so a vocabulary that CHOOSES to model a built-in spelling
  // gets it — the built-ins are not a walled-off half of the label space.
  enum Everything {
    Filtered,
  }
  impl SkipLabel for Everything {
    fn label(&self) -> &'static ReasonName {
      ReasonName::new("filtered")
    }
    fn from_label(label: &ReasonName) -> Option<Self> {
      (label.as_ref() == "filtered").then_some(Self::Filtered)
    }
  }
  assert!(SkipReason::Filtered.decode::<Everything>().is_some());
  assert!(SkipReason::NoConsumers.decode::<Everything>().is_none());
}