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
use core::error::Error;

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

use jiff::SignedDuration;

use crate::{AsyncTeardown, Resources, Shutdown, Taps};

use super::{App, Farewell};

/// What the stop machinery did, in the order it did it — the one record every claim here reads.
type Record = Arc<Mutex<Vec<&'static str>>>;

fn record() -> Record {
  Arc::new(Mutex::new(Vec::new()))
}

fn seen(record: &Record) -> Vec<&'static str> {
  record.lock().expect("the stop's record").clone()
}

/// A goodbye that writes its own name down when it is said.
struct Says {
  name: &'static str,
  record: Record,
}

impl AsyncTeardown for Says {
  async fn teardown(self) -> Result<(), Box<dyn Error + Send + Sync>> {
    self
      .record
      .lock()
      .expect("the stop's record")
      .push(self.name);
    Ok(())
  }
}

fn goodbye(name: &'static str, record: &Record) -> Farewell {
  Farewell::new(
    name,
    Says {
      name,
      record: Arc::clone(record),
    },
  )
}

/// A started source, which writes its name down when it is STOPPED — a source being stopped by
/// dropping what starting it gave back.
struct Admitting {
  name: &'static str,
  record: Record,
}

impl Drop for Admitting {
  fn drop(&mut self) {
    self
      .record
      .lock()
      .expect("the stop's record")
      .push(self.name);
  }
}

fn source(name: &'static str, record: &Record) -> Box<dyn core::any::Any + Send> {
  Box::new(Admitting {
    name,
    record: Arc::clone(record),
  })
}

/// A world with no bodies and no edges: what is under test here is the STOP, and a graph would only
/// be a second thing able to fail.
///
/// No mounted ORIGIN and no bodies of EITHER engine — the three empty vectors between the sources
/// and the goodbyes are the origins' stop lines, the threads and the tasks.
fn world(
  shutdown: Shutdown,
  sources: Vec<Box<dyn core::any::Any + Send>>,
  teardowns: Vec<Farewell>,
) -> App<()> {
  App::new(
    std::sync::Arc::new(Resources::new()),
    shutdown,
    Taps::new(),
    std::sync::Arc::new(crate::Registries::default()),
    Vec::new(),
    sources,
    Vec::new(),
    Vec::new(),
    Vec::new(),
    teardowns,
    std::collections::HashMap::new(),
    std::collections::HashMap::new(),
    std::collections::HashMap::new(),
  )
}

#[test]
fn a_world_that_has_already_settled_stops_cleanly_and_says_its_goodbyes() {
  let record = record();
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  let scenes = shutdown.register("scenes");
  decode.settle();
  scenes.settle();

  let stopped = world(
    shutdown,
    Vec::new(),
    vec![goodbye("pool", &record), goodbye("device", &record)],
  )
  .shutdown(None);

  assert_eq!(stopped.settled(), 2);
  assert_eq!(stopped.unsettled().len(), 0);
  assert!(!stopped.overran());
  assert!(stopped.is_clean());
  assert_eq!(
    seen(&record),
    ["device", "pool"],
    "last enrolled, first to say goodbye"
  );
}

#[test]
fn the_sources_stop_before_anything_is_waited_for_and_last_started_first() {
  let record = record();
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  // The party settles only once the intake has stopped, which is what puts the two facts in one
  // order: whatever this list holds happened before the wait could end.
  let stopping = Arc::clone(&record);
  let hand = thread::spawn(move || {
    while stopping.lock().expect("the stop's record").len() < 2 {
      thread::yield_now();
    }
    decode.settle();
  });

  let stopped = world(
    shutdown,
    vec![source("intake", &record), source("clock", &record)],
    vec![goodbye("pool", &record)],
  )
  .shutdown(None);

  hand.join().expect("the party's own thread");
  assert!(stopped.is_clean());
  assert_eq!(
    seen(&record),
    ["clock", "intake", "pool"],
    "intake stops last-started-first, and only then is anybody told goodbye"
  );
}

#[test]
fn a_deadline_that_runs_out_names_who_did_not_answer_and_says_no_goodbye() {
  let record = record();
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  let scenes = shutdown.register("scenes");
  scenes.settle();

  let began = Instant::now();
  let stopped = world(shutdown, Vec::new(), vec![goodbye("pool", &record)])
    .shutdown(Some(SignedDuration::from_millis(30)));

  assert!(began.elapsed() >= Duration::from_millis(30), "it waited");
  assert!(stopped.overran());
  assert_eq!(stopped.settled(), 1);
  let unanswered: Vec<&str> = stopped.unsettled().map(|name| name.as_str()).collect();
  assert_eq!(unanswered, ["decode"]);
  assert!(!stopped.is_clean());

  assert_eq!(stopped.untorn().len(), 1, "the goodbye is named as un-torn");
  assert_eq!(stopped.untorn()[0].name().as_str(), "pool");
  assert!(stopped.untorn()[0].error().is_none(), "it was never said");
  assert!(
    seen(&record).is_empty(),
    "a store is not flushed while the node writing to it is still running"
  );
  drop(decode);
}

#[test]
fn a_deadline_that_passed_before_it_was_given_waits_for_nothing() {
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");

  let began = Instant::now();
  let stopped =
    world(shutdown, Vec::new(), Vec::new()).shutdown(Some(SignedDuration::from_millis(-500)));

  assert!(began.elapsed() < Duration::from_millis(400));
  assert!(stopped.overran());
  assert_eq!(stopped.settled(), 0);
  drop(decode);
}

#[test]
fn an_abort_stops_now_and_reports_whoever_had_already_answered() {
  let record = record();
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  let scenes = shutdown.register("scenes");
  scenes.settle();

  let began = Instant::now();
  let stopped = world(
    shutdown,
    vec![source("intake", &record)],
    vec![goodbye("pool", &record)],
  )
  .abort();

  assert!(
    began.elapsed() < Duration::from_millis(500),
    "it did not wait"
  );
  assert!(!stopped.overran(), "no deadline ran out — none was given");
  assert_eq!(stopped.settled(), 1);
  let unanswered: Vec<&str> = stopped.unsettled().map(|name| name.as_str()).collect();
  assert_eq!(unanswered, ["decode"]);
  assert_eq!(
    seen(&record),
    ["intake"],
    "the intake still stopped, and no goodbye was said"
  );
  assert_eq!(stopped.untorn().len(), 1);
  drop(decode);
}

#[test]
fn an_abort_of_a_settled_world_still_says_no_goodbye() {
  let record = record();
  let mut shutdown = Shutdown::new();
  shutdown.register("decode").settle();

  let stopped = world(shutdown, Vec::new(), vec![goodbye("pool", &record)]).abort();

  assert_eq!(stopped.settled(), 1);
  assert!(
    seen(&record).is_empty(),
    "a stop that would not wait for its nodes does not wait for their stores"
  );
  assert_eq!(stopped.untorn().len(), 1);
}

#[test]
fn until_stopped_parks_until_the_world_ends_of_itself() {
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  let hand = thread::spawn(move || {
    thread::sleep(Duration::from_millis(20));
    decode.settle();
  });

  let running = world(shutdown, Vec::new(), Vec::new());
  let began = Instant::now();
  running.until_stopped();

  assert!(began.elapsed() >= Duration::from_millis(20));
  hand.join().expect("the party's own thread");
  // The value survives the park, so the report is still to be had.
  let stopped = running.shutdown(None);
  assert_eq!(stopped.settled(), 1);
  assert!(stopped.is_clean());
}

#[test]
fn an_empty_deployment_is_stopped_the_moment_it_is_asked() {
  let running = world(Shutdown::new(), Vec::new(), Vec::new());
  running.until_stopped();
  let stopped = running.shutdown(None);

  assert_eq!(stopped.settled(), 0);
  assert!(stopped.is_clean());
  assert_eq!(stopped.to_string(), "stopped: 0 settled");
}

#[test]
fn the_report_reads_as_rows_under_a_summary() {
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  let stopped = world(shutdown, Vec::new(), Vec::new()).abort();

  let rendered = stopped.to_string();
  assert!(rendered.starts_with("stopped: 0 settled"));
  assert!(rendered.contains("`decode` did not answer"));
  drop(decode);
}

/// THE EXIT SOURCE'S OWN ROW — [`App::halt_on`], and the park it ends.
///
/// A world with ONE party that never settles, so `until_stopped` would wait forever on the
/// registry's own account: whatever ends the wait here can only be the registration.
mod halt_on {
  use super::{App, Record, Resources, Shutdown, Taps, record, seen};

  use crate::conduit;

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

  /// A world holding ONE unsettled party, so nothing but a halt source can end the park.
  fn parked() -> (App<()>, crate::Enrolled) {
    let mut shutdown = Shutdown::new();
    let party = shutdown.register("decode");
    let app = App::new(
      Arc::new(Resources::new()),
      shutdown,
      Taps::new(),
      Arc::new(crate::Registries::default()),
      Vec::new(),
      Vec::new(),
      Vec::new(),
      Vec::new(),
      Vec::new(),
      Vec::new(),
      std::collections::HashMap::new(),
      std::collections::HashMap::new(),
      std::collections::HashMap::new(),
    );
    (app, party)
  }

  /// Run `until_stopped` on a thread of its own and answer whether it returned inside `patience`.
  fn woken(app: App<()>, patience: Duration, record: &Record) -> bool {
    let written = Arc::clone(record);
    let hand = thread::spawn(move || {
      app.until_stopped();
      written.lock().expect("the halt's record").push("woken");
      app.halted()
    });
    let end = Instant::now() + patience;
    while Instant::now() < end && !hand.is_finished() {
      thread::yield_now();
    }
    assert!(hand.is_finished(), "the park never returned");
    hand.join().expect("the parked thread")
  }

  #[test]
  fn a_registered_source_that_speaks_wakes_the_park() {
    let record = record();
    let (mut app, party) = parked();
    let (fired, source) = conduit::bounded::<()>(1);
    app.halt_on(source);

    assert!(!app.halted(), "nothing has been said yet");
    fired.send(()).expect("the watcher is listening");

    assert!(woken(app, Duration::from_secs(5), &record));
    assert_eq!(seen(&record), ["woken"]);
    // The party never settled, so the wait ended on the REGISTRATION and on nothing else.
    drop(party);
  }

  #[test]
  fn a_registered_source_that_hangs_up_is_the_same_news() {
    let record = record();
    let (mut app, party) = parked();
    let (fired, source) = conduit::bounded::<()>(1);
    app.halt_on(source);

    // The handler vanished without a word, which is a handler that will never speak — see the
    // door's own note.
    drop(fired);

    assert!(woken(app, Duration::from_secs(5), &record));
    drop(party);
  }

  #[test]
  fn two_sources_are_two_registrations_and_either_one_wakes_the_park() {
    let record = record();
    let (mut app, party) = parked();
    let (_signals, from_signals) = conduit::bounded::<()>(1);
    let (supervisor, from_supervisor) = conduit::bounded::<()>(1);
    app.halt_on(from_signals);
    app.halt_on(from_supervisor);

    // Only the SECOND speaks, and the park still ends: each registration watches its own line.
    supervisor.send(()).expect("the watcher is listening");

    assert!(woken(app, Duration::from_secs(5), &record));
    drop(party);
  }

  #[test]
  fn a_source_that_fired_before_the_park_is_not_waited_past() {
    let record = record();
    let (mut app, party) = parked();
    let (fired, source) = conduit::bounded::<()>(1);
    app.halt_on(source);
    fired.send(()).expect("the watcher is listening");

    // The latch is read BEFORE the park, so a source that spoke while the caller was still setting
    // up does not leave `until_stopped` waiting on a bell that has already rung.
    while !app.halted() {
      thread::yield_now();
    }
    assert!(woken(app, Duration::from_secs(5), &record));
    drop(party);
  }

  #[test]
  fn the_ordinary_park_still_ends_when_every_party_finishes() {
    let record = record();
    let (mut app, party) = parked();
    let (_fired, source) = conduit::bounded::<()>(1);
    app.halt_on(source);

    // NOTHING is said on the line; the registry's own account is what ends this wait, and
    // `halted` says which of the two endings it was.
    party.settle();

    assert!(
      !woken(app, Duration::from_secs(5), &record),
      "the world ended of itself, so no exit source had fired"
    );
  }
}