ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
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
//! What a declaration's facts become: the impl a root reads it through.
//!
//! Read off the TOKENS, because that is what this layer can answer. Whether the facts are TRUE —
//! whether a declared channel opens an edge at the depth it names, whether a declared `changes`
//! makes the feeder check fire — is asserted where the emission can be run, in `ingraph`'s own
//! `tests/the_convergence.rs`.

use crate::{
  model::{
    ChangesFeed, ChannelOptions, DatabaseKind, FanIn, Kind, NodeKind, RecordModel, Subscription,
    Upstream, Upstreams,
  },
  tests::model,
};

/// One `upstream(…)` entry, as the front end would have settled it.
fn upstream(node: &str, channel: Option<ChannelOptions>, changes: Option<ChangesFeed>) -> Upstream {
  let node: syn::Path = syn::parse_str(node).expect("a path");
  let variant = node
    .segments
    .last()
    .expect("a path has a last segment")
    .ident
    .clone();
  Upstream {
    node,
    keyed: false,
    out: None,
    variant,
    channel,
    changes,
    notify: false,
  }
}

/// The emission with every space taken out — what a claim about a word is read off.
fn compact(model: &RecordModel) -> String {
  model.emit().to_string().split_whitespace().collect()
}

/// **EVERY DECLARED SOURCE IS ONE ROW**, in declaration order, carrying the words it was written
/// with — the upstream's own path, the depth its author shipped.
#[test]
fn the_sources_table_is_the_declarations_own_order() {
  let mut model = model("Captions", &["media_id"], "id");
  model.subscriptions = Some(Subscription {
    upstreams: vec![
      upstream("asr::Segment", Some(ChannelOptions::Bounded(512)), None),
      upstream("media::Ocr", Some(ChannelOptions::Unbounded), None),
      upstream("HttpFetch", None, None),
    ],
  });
  let emitted = compact(&model);

  assert!(
    emitted.contains("constUPSTREAMS:&'static[::ingraph::__private::drive::Upstream]=&["),
    "{emitted}"
  );
  let table = emitted
    .split("constUPSTREAMS:&'static[::ingraph::__private::drive::Upstream]=&[")
    .nth(1)
    .expect("the table");
  let first = table.find("asr::Segment").expect("the first entry");
  let second = table.find("media::Ocr").expect("the second entry");
  let third = table.find("HttpFetch").expect("the third entry");
  assert!(first < second && second < third, "{table}");

  assert!(
    table.contains(".channelled(::ingraph::__private::drive::ChannelOptions::Bounded(512usize))"),
    "the author's shipped depth rides the row: {table}"
  );
  assert!(
    table.contains(".channelled(::ingraph::__private::drive::ChannelOptions::Unbounded)"),
    "{table}"
  );
  assert!(
    table.contains("Upstream::of::<HttpFetch>(\"HttpFetch\")"),
    "a upstream with no words is the bare row: {table}"
  );
}

/// **THE `changes` WORD REACHES THE LAUNCH FLOOR** — S4b's L-1, closed at the emission. The word
/// was parsed, modelled and spent by the runtime; nothing carried a DECLARATION's listen arm into a
/// launch until this row.
#[test]
fn a_declared_changes_listener_states_its_feeder() {
  let mut model = model("Reaper", &[], "id");
  model.subscriptions = Some(Subscription {
    upstreams: vec![
      upstream(
        "media::Store",
        None,
        Some(ChangesFeed {
          database: DatabaseKind::Sqlite,
          external: false,
        }),
      ),
      upstream(
        "other::Store",
        None,
        Some(ChangesFeed {
          database: DatabaseKind::Sqlite,
          external: true,
        }),
      ),
    ],
  });
  let emitted = compact(&model);

  assert!(
    emitted.contains(
      ".listening(::ingraph::__private::drive::Listen::Changes(::ingraph::__private::drive::\
       Feeder::InGraph))"
    ),
    "a default `changes(<db>)` claims an in-graph feeder: {emitted}"
  );
  assert!(
    emitted.contains(
      ".listening(::ingraph::__private::drive::Listen::Changes(::ingraph::__private::drive::\
       Feeder::External))"
    ),
    "`external` declares the cross-process shape: {emitted}"
  );
}

/// The SINGLE-word form is one row, and a fusion's `upstream(…)` entries are rows too: three
/// spellings, one table, because the launch floor has one question.
#[test]
fn the_single_word_form_is_one_row() {
  let mut model = model("Titles", &[], "id");
  model.subscribe = Some(syn::parse_str("media::Frame").expect("a path"));
  let emitted = compact(&model);
  assert!(
    emitted.contains("Upstream::of::<media::Frame>(\"media::Frame\")"),
    "{emitted}"
  );
}

/// **THE EFFECT IS READ OFF THE KIND**, and so is the lane: a kind with a storage block lands
/// through one it owns, and an operator computes and lands nothing of its own.
#[test]
fn the_effect_and_the_lane_are_read_off_the_kind() {
  let stored = compact(&model("Scene", &[], "id"));
  assert!(
    stored.contains(
      "constEFFECT:::ingraph::__private::drive::Effect=::ingraph::__private::drive::Effect::Lands;"
    ),
    "{stored}"
  );
  assert!(stored.contains("constHOLDS_LANE:bool=true;"), "{stored}");

  let mut pure = model("Decode", &[], "id");
  pure.kind = NodeKind::Operator;
  let pure = compact(&pure);
  assert!(
    pure.contains(
      "constEFFECT:::ingraph::__private::drive::Effect=::ingraph::__private::drive::Effect::Pure;"
    ),
    "{pure}"
  );
  assert!(pure.contains("constHOLDS_LANE:bool=false;"), "{pure}");
}

/// **THE `options` WORD IS THE `Options` TYPE**, and its absence is the unit type rather than a gap:
/// a node with no knobs IS configured by `()`, which is what its constructor already spells.
#[test]
fn the_options_word_is_the_declared_type() {
  let mut named = model("Shout", &[], "id");
  named.options = Some(syn::parse_str("shout::Options").expect("a path"));
  assert!(
    compact(&named).contains("typeOptions=shout::Options;"),
    "{}",
    compact(&named)
  );

  let silent = compact(&model("Keep", &[], "id"));
  assert!(silent.contains("typeOptions=();"), "{silent}");
}

/// A node that subscribes to NOTHING states an empty table rather than no table: a head is a fact,
/// and the launch walk reads it the same way it reads every other node's.
#[test]
fn a_head_states_an_empty_table() {
  let emitted = compact(&model("Watch", &[], "id"));
  assert!(
    emitted.contains("constUPSTREAMS:&'static[::ingraph::__private::drive::Upstream]=&[];"),
    "{emitted}"
  );
}

/// The fusion spelling reaches the same table.
#[test]
fn a_fusions_upstreams_are_rows() {
  let mut model = model("Fused", &[], "id");
  model.upstreams = Some(Upstreams::Fanned(FanIn {
    kinds: vec![
      Kind {
        node: syn::parse_str("a::Left").expect("a path"),
        variant: syn::parse_str("Left").expect("an ident"),
      },
      Kind {
        node: syn::parse_str("a::Right").expect("a path"),
        variant: syn::parse_str("Right").expect("an ident"),
      },
    ],
  }));
  let emitted = compact(&model);
  assert!(emitted.contains("Upstream::of::<a::Left>"), "{emitted}");
  assert!(emitted.contains("Upstream::of::<a::Right>"), "{emitted}");
}

/// A compute node with the two face-axis words set as the front end would have settled them.
fn faced(name: &str, streaming: bool, asynchronous: bool) -> RecordModel {
  let mut model = model(name, &[], "id");
  model.kind = NodeKind::Operator;
  if streaming {
    model.streaming = Some(syn::parse_quote!(stream));
  }
  if asynchronous {
    model.asynchronous = Some(syn::parse_quote!(r#async));
  }
  model
}

/// The same, wearing the PAIR axis's THIRD value — the grammar refuses `autonomous` beside
/// `stream`, so this is its own fixture rather than a third flag on the one above.
fn autonomous(name: &str, asynchronous: bool) -> RecordModel {
  let mut model = model(name, &[], "id");
  model.kind = NodeKind::Operator;
  model.autonomous = Some(syn::parse_quote!(autonomous));
  if asynchronous {
    model.asynchronous = Some(syn::parse_quote!(r#async));
  }
  model
}

/// **THE FACE WORD IS THE `Pair` SEAT**, stated in as many words at BOTH arms — which is what a
/// seat with no default costs, and what stops a silent node from being one an author left wrong.
///
/// It was `const STREAMS: bool`, emitted at the `stream` arm only and defaulted in the trait at the
/// other. The design-law audit refused the shape: no const states a mode, and a defaulted one is
/// the member nothing checks against the body.
#[test]
fn the_face_word_is_the_pair_seat() {
  let streaming = compact(&faced("Demux", true, false));
  assert!(
    streaming.contains("typePair=::ingraph::__private::drive::Streaming;"),
    "{streaming}"
  );
  assert!(!streaming.contains("constSTREAMS"), "{streaming}");

  let buffered = compact(&faced("Describe", false, false));
  assert!(
    buffered.contains("typePair=::ingraph::__private::drive::Buffered;"),
    "{buffered}"
  );

  // THE THIRD VALUE, seated by the same one line — which is what a seat that is a TYPE buys and
  // what a two-valued const could not have taken at all.
  let owned = compact(&autonomous("Decode", false));
  assert!(
    owned.contains("typePair=::ingraph::__private::drive::Autonomous;"),
    "{owned}"
  );
}

/// **THE MODE SEAT IS ONE SEAT WHICHEVER KIND THE BODY WEARS.** The pair axis picks the kind and
/// `async` picks the half, so a streaming or autonomous declaration states `Block` and `Async` in
/// exactly the words a buffered one does — two axes, one seat apiece, and no third word for either.
#[test]
fn the_mode_seat_is_the_same_seat_on_both_pairs() {
  for streaming in [false, true] {
    let blocking = compact(&faced("Demux", streaming, false));
    assert!(
      blocking.contains("typeMode=::ingraph::__private::operator::Block;"),
      "{blocking}"
    );
    let awaited = compact(&faced("Demux", streaming, true));
    assert!(
      awaited.contains("typeMode=::ingraph::__private::operator::Async;"),
      "{awaited}"
    );
  }
  for asynchronous in [false, true] {
    let emitted = compact(&autonomous("Decode", asynchronous));
    let seat = if asynchronous { "Async" } else { "Block" };
    let spelled = format!("typeMode=::ingraph::__private::operator::{seat};");
    assert!(emitted.contains(&spelled), "{emitted}");
  }
}

/// **THE `attributed` WORD IS THE ATTRIBUTION SEAT**, and its absence is a seat too.
///
/// The parameter is what makes the attributed arm writable at all — the projection is over the
/// node's OUTPUT, which this emission cannot name — so the seat is a constructor and the walk
/// supplies the product. The silent arm answers `()` and ignores the parameter, which is what makes
/// the launch's install unconditional: the unit projection implements the seam for every payload
/// there is.
#[test]
fn the_attribution_word_is_the_projection_seat() {
  let mut model = faced("Keyframe", false, false);
  let silent = compact(&model);
  assert!(
    silent.contains("typeAttribution<__INGRAPH_OUT__>=();"),
    "{silent}"
  );
  // The record's OWN projection impl is emitted either way — having a root is a property of having
  // a key — so what the silence decides is the SEAT, and this is that distinction asserted.
  assert!(
    silent.contains("impl::ingraph::__private::drive::Attributes<Keyframe>"),
    "the projection is emitted whatever the node installs: {silent}"
  );
  assert!(
    !silent
      .contains("typeAttribution<__INGRAPH_OUT__>=::ingraph::__private::drive::RootProjection"),
    "a declaration that wrote no word installs nothing: {silent}"
  );

  model.attributed = true;
  let attributed = compact(&model);
  assert!(
    attributed.contains(
      "typeAttribution<__INGRAPH_OUT__>=::ingraph::__private::drive::RootProjection<\
       __INGRAPH_OUT__>;"
    ),
    "{attributed}"
  );
}

/// The word is on an AXIS OF ITS OWN: the pair, the mode and the kind say what a body IS, and this
/// says what the framework does with what the body EMITS. So every cell of the pair axis carries the
/// same one line, and none of them carries a second word for it.
#[test]
fn the_attribution_seat_is_the_same_seat_on_every_pair() {
  let spelled = "typeAttribution<__INGRAPH_OUT__>=::ingraph::__private::drive::RootProjection<\
                 __INGRAPH_OUT__>;";
  for streaming in [false, true] {
    for asynchronous in [false, true] {
      let mut model = faced("Demux", streaming, asynchronous);
      model.attributed = true;
      let emitted = compact(&model);
      assert!(emitted.contains(spelled), "{emitted}");
    }
  }
  let mut owned = autonomous("Decode", false);
  owned.attributed = true;
  let emitted = compact(&owned);
  assert!(emitted.contains(spelled), "{emitted}");
}

/// **THE FACE AUDIT NAMES THE CELL THE TWO WORDS SELECT.** A word is a claim about the body, and the
/// bound is what makes the claim checkable at the declaration rather than at whatever first tried to
/// mount the node.
///
/// A BARE declaration audits nothing, and that asymmetry is deliberate: a declaration is not
/// required to have an operator impl at all.
#[test]
fn the_face_audit_names_the_cell_the_words_select() {
  const ROSTER: [(bool, bool, &str); 3] = [
    (false, true, "AsyncOperator"),
    (true, false, "StreamOperator"),
    (true, true, "AsyncStreamOperator"),
  ];
  for (streaming, asynchronous, face) in ROSTER {
    let emitted = compact(&faced("Demux", streaming, asynchronous));
    let bound = format!("__INGRAPH_NODE__:::ingraph::__private::operator::{face}>");
    assert!(emitted.contains(&bound), "missing `{bound}` in: {emitted}");
  }

  // The third kind's two rows, on the same road: the word is a claim and the bound is what makes it
  // checkable at the declaration.
  for (asynchronous, face) in [
    (false, "AutonomousOperator"),
    (true, "AsyncAutonomousOperator"),
  ] {
    let emitted = compact(&autonomous("Decode", asynchronous));
    let bound = format!("__INGRAPH_NODE__:::ingraph::__private::operator::{face}>");
    assert!(emitted.contains(&bound), "missing `{bound}` in: {emitted}");
  }

  let bare = compact(&faced("Describe", false, false));
  assert!(!bare.contains("__ig_awaits"), "{bare}");
}

/// **THE `receipt` WORD EMITS THE SIBLING IMPL ON THE MESSAGE**, at the path the declaration wrote
/// and nowhere resolved: what an acked give of this message is answered with is a fact only this
/// declaration can state, and this is the statement.
///
/// The SELF TYPE is the assertion the re-key added. The impl used to sit on the consumer — *this
/// node hands back a `SceneId`* — and it sits on the thing GIVEN now, so every seat over one message
/// answers one declared question rather than each declaring its own.
///
/// The path is asserted VERBATIM, because verbatim is what makes the refusal land at the author's
/// own string — `LitStr::parse` respanned the tokens onto the literal, and an emission that rebuilt
/// the path from its segments would throw that away.
#[test]
fn the_receipt_word_states_the_type_this_message_is_answered_with() {
  let mut model = model("SceneOpen", &["media_id"], "id");
  model.receipt = Some(syn::parse_str("media::SceneId").expect("a path"));
  let emitted = compact(&model);

  assert!(
    emitted.contains("impl::ingraph::__private::operator::ReceiptsforSceneOpen{"),
    "the sibling impl is the message's own: {emitted}"
  );
  assert!(
    emitted.contains("typeReceipt=media::SceneId;"),
    "the author's path, verbatim: {emitted}"
  );
}

/// **SILENCE EMITS NOTHING**, which is the seat's whole reason for being a sibling rather than a
/// member of the facts trait.
///
/// A declaration that states no receipt gets no impl, no seat and no bound — so every message in
/// this tree that nobody waits on pays exactly what it paid before the word existed. The contrast
/// with `Options` is the assertion: that seat is filled with `()` on every silent declaration,
/// because it is a MEMBER and a member cannot be absent.
#[test]
fn a_declaration_that_declares_no_receipt_emits_no_seat() {
  let model = model("Scene", &["media_id"], "id");
  let emitted = compact(&model);

  assert!(
    !emitted.contains("::ingraph::__private::operator::Receipts"),
    "no word, no impl: {emitted}"
  );
  assert!(
    !emitted.contains("typeReceipt="),
    "no word, no seat: {emitted}"
  );
  assert!(
    emitted.contains("typeOptions=();"),
    "the MEMBER seat is filled even in silence, which is the contrast: {emitted}"
  );
}