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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! The carriers, read from both ends: what a client may write, what comes back, and the two values
//! in the whole 128-bit domain that would overflow a buffer one byte short.

use async_graphql::{ScalarType, Value};

use super::{Digits, HexBytes, I128, U128};

/// The rendered text of one value, whichever carrier holds it.
fn rendered<T: ScalarType>(value: T) -> String {
  match value.to_value() {
    Value::String(text) => text,
    other => panic!("a carrier renders as a string: {other}"),
  }
}

/// The refusal one value is read with, or `None` where it parses.
///
/// The sentence is taken through `into_server_error`, which is the one door onto it:
/// `InputValueError` carries its message privately and implements no `Display` — a positioned server
/// error is what async-graphql turns one into on the way to a client, so this is the text a client
/// actually reads.
fn refusal<T: ScalarType + async_graphql::InputType>(value: Value) -> Option<String> {
  <T as ScalarType>::parse(value).err().map(|error| {
    error
      .into_server_error(async_graphql::parser::Pos::default())
      .message
  })
}

/// The buffer's WIDTH, at the two values that decide it: `u128::MAX` is 39 digits and `i128::MIN` is
/// 39 digits under a sign, so a `[u8; 39]` would panic on exactly one of the four ends below and a
/// `[u8; 40]` holds all of them.
#[test]
fn the_stack_buffer_holds_both_extremes() {
  assert_eq!(Digits::unsigned(u128::MAX).as_str().len(), 39);
  assert_eq!(Digits::signed(i128::MIN).as_str().len(), 40);
  assert_eq!(Digits::unsigned(0).as_str(), "0");
  assert_eq!(Digits::signed(0).as_str(), "0");
  assert_eq!(Digits::signed(-1).as_str(), "-1");
  assert_eq!(
    Digits::unsigned(u128::MAX).as_str(),
    "340282366920938463463374607431768211455"
  );
  // The magnitude comes from `unsigned_abs`, so the one value whose negation is not an `i128`
  // renders rather than overflowing.
  assert_eq!(
    Digits::signed(i128::MIN).as_str(),
    "-170141183460469231731687303715884105728"
  );
  assert_eq!(
    Digits::signed(i128::MAX).as_str(),
    "170141183460469231731687303715884105727"
  );
}

/// Every value round-trips through WHICHEVER form it takes, and the DIGITS are read at every
/// magnitude beside it — the encode fork and the liberal decode, at the ends where a JSON number
/// would already have lost bits.
#[test]
fn a_128_bit_integer_round_trips_through_whichever_form_it_takes() {
  for value in [0, 1, u128::from(u64::MAX) + 1, u128::MAX] {
    let wire = U128::from(value).to_value();
    assert_eq!(
      U128::parse(wire.clone()).expect("its own rendering parses"),
      U128::from(value),
      "{wire}"
    );
    // …and the string form is read at EVERY magnitude, whichever form the value came back in.
    let text = U128::from(value).to_string();
    assert_eq!(
      U128::parse(Value::String(text.clone())).expect("the digits parse at any magnitude"),
      U128::from(value),
      "{text}"
    );
  }
  for value in [0, -1, i128::from(i64::MIN) - 1, i128::MIN, i128::MAX] {
    let wire = I128::from(value).to_value();
    assert_eq!(
      I128::parse(wire.clone()).expect("its own rendering parses"),
      I128::from(value),
      "{wire}"
    );
    let text = I128::from(value).to_string();
    assert_eq!(
      I128::parse(Value::String(text.clone())).expect("the digits parse at any magnitude"),
      I128::from(value),
      "{text}"
    );
  }

  // `Display` renders the same text, through the same buffer and without the `Value` allocation —
  // read at the two ends, which are the values that DO cross as text.
  assert_eq!(
    U128::from(u128::MAX).to_string(),
    rendered(U128::from(u128::MAX))
  );
  assert_eq!(
    I128::from(i128::MIN).to_string(),
    rendered(I128::from(i128::MIN))
  );
}

/// A leading `+` is accepted and does not come back, which is `i128::from_str`'s own grammar rather
/// than a rule this carrier added.
#[test]
fn a_leading_plus_is_read_and_not_rendered() {
  let parsed = I128::parse(Value::String(String::from("+7"))).expect("a signed literal");
  assert_eq!(parsed, I128::from(7));
  // SEVEN is inside the safe range, so what comes back is the NUMBER — and the digits it is spelled
  // with carry no sign either way.
  assert_eq!(parsed.to_value(), Value::Number(7.into()));
  assert_eq!(parsed.to_string(), "7");
}

/// A JSON number is READ wherever it is whole and inside the scalar's own range, and refused where
/// it is not — the hybrid law's decode half, which is liberal at every magnitude.
///
/// It replaces the posture that preceded it, and the replacement is the ruling rather than a
/// loosening: refusing a number outright made a client that had never sent a large value pay for a
/// bound it would never reach. What protects the value is the ENCODE side, which never hands back a
/// number a double cannot carry.
#[test]
fn a_json_number_is_read_at_a_128_bit_width_when_it_is_whole_and_in_range() {
  assert_eq!(
    U128::parse(Value::Number(7.into())).expect("a whole number in range"),
    U128::from(7),
  );
  assert_eq!(
    I128::parse(Value::Number((-7).into())).expect("a whole number in range"),
    I128::from(-7),
  );
  assert!(U128::is_valid(&Value::Number(7.into())));

  // A NEGATIVE against the unsigned width, and a FRACTION against either: neither is a value of the
  // scalar, so both are refused rather than wrapped or rounded.
  let negative = refusal::<U128>(Value::Number((-1).into())).expect("-1 is not a `u128`");
  assert!(negative.contains("`u128`"), "{negative}");
  assert!(negative.contains("WHOLE value"), "{negative}");
  let fraction = refusal::<I128>(Value::Number(
    async_graphql::Number::from_f64(1.5).expect("1.5 is a JSON number"),
  ))
  .expect("1.5 is not an integer");
  assert!(fraction.contains("DECIMAL TEXT"), "{fraction}");

  // …and a value that is NEITHER form is still refused as the wrong type.
  assert!(refusal::<U128>(Value::Boolean(true)).is_some());
  assert!(!U128::is_valid(&Value::Boolean(true)));
}

/// The three refusals, each naming what a client can act on — and the two overflow ones naming the
/// BOUND, which is the one fact a client cannot discover by trying.
#[test]
fn a_refused_operand_is_told_what_the_form_and_the_range_are() {
  let past = refusal::<U128>(Value::String(String::from(
    "340282366920938463463374607431768211456",
  )))
  .expect("one past the ceiling");
  assert!(past.contains("outside `u128`'s range"), "{past}");
  assert!(
    past.contains("340282366920938463463374607431768211455"),
    "{past}"
  );

  let under = refusal::<I128>(Value::String(String::from(
    "-170141183460469231731687303715884105729",
  )))
  .expect("one past the floor");
  assert!(
    under.contains("-170141183460469231731687303715884105728"),
    "{under}"
  );

  let empty = refusal::<U128>(Value::String(String::new())).expect("an empty string");
  assert!(empty.contains("empty"), "{empty}");

  let words = refusal::<U128>(Value::String(String::from("twelve"))).expect("not digits");
  assert!(words.contains("DECIMAL TEXT"), "{words}");
  // A NEGATIVE operand against the unsigned carrier lands here too, which is the honest answer: it
  // is not an unsigned integer, and the sentence says what the range is.
  assert!(refusal::<U128>(Value::String(String::from("-1"))).is_some());
}

/// `is_valid` runs the SAME parser `parse` does, so a document that validates is a document that
/// parses — async-graphql's default answers `true` for every value, which would ship a validator
/// admitting what its own parser rejects.
#[test]
fn validity_and_parsing_are_one_question() {
  for text in ["0", "340282366920938463463374607431768211455"] {
    let value = Value::String(String::from(text));
    assert!(U128::is_valid(&value), "{text}");
    assert!(U128::parse(value).is_ok(), "{text}");
  }
  for text in [
    "",
    "-1",
    "twelve",
    "340282366920938463463374607431768211456",
  ] {
    let value = Value::String(String::from(text));
    assert!(!U128::is_valid(&value), "{text}");
    assert!(U128::parse(value).is_err(), "{text}");
  }
  assert!(HexBytes::is_valid(&Value::String(String::from("89504e47"))));
  assert!(!HexBytes::is_valid(&Value::String(String::from("89504e4"))));
}

/// A blob crosses as an EVEN number of hex digits and comes back lowercase and unprefixed — so
/// `parse(render(b)) == b`, while `render(parse(t))` is the canonical spelling of `t` rather than
/// `t`.
#[test]
fn a_blob_round_trips_through_lowercase_hex() {
  let png = vec![0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
  let carrier = HexBytes::from(png.clone());
  assert_eq!(rendered(carrier.clone()), "89504e470d0a1a0a");
  assert_eq!(carrier.to_string(), "89504e470d0a1a0a");
  assert_eq!(
    HexBytes::parse(Value::String(String::from("89504e470d0a1a0a")))
      .expect("its own rendering parses"),
    carrier
  );

  // Uppercase and a `0x` prefix are accepted on the way in and normalised on the way out.
  for text in [
    "89504E470D0A1A0A",
    "0x89504e470d0a1a0a",
    "0X89504E470D0A1A0A",
  ] {
    let parsed = HexBytes::parse(Value::String(String::from(text))).expect(text);
    assert_eq!(parsed.get(), &png, "{text}");
    assert_eq!(rendered(parsed), "89504e470d0a1a0a", "{text}");
  }

  // The EMPTY string is the empty blob, and it is a value rather than a refusal: a zero-length blob
  // is a thing a column can hold, so `eq: ""` is a question with an answer.
  let empty = HexBytes::parse(Value::String(String::new())).expect("the empty blob");
  assert!(empty.get().is_empty());
  assert_eq!(rendered(empty), "");
}

/// An ODD digit count is refused, and so is a digit that is not one — the two ways a hex string is
/// not a byte string, both told in a sentence naming the form.
#[test]
fn half_a_byte_is_not_a_byte_string() {
  for text in ["89504e4", "89504e4g", "0x8", "not hex"] {
    let refused = refusal::<HexBytes>(Value::String(String::from(text))).expect(text);
    assert!(refused.contains("EVEN number of hex digits"), "{refused}");
  }
  assert!(refusal::<HexBytes>(Value::Number(7.into())).is_some());
}

/// The carrier is exactly its operand with a wire face attached: both conversions are total, and
/// neither loses anything.
#[test]
fn a_carrier_converts_both_ways() {
  assert_eq!(u128::from(U128::from(u128::MAX)), u128::MAX);
  assert_eq!(i128::from(I128::from(i128::MIN)), i128::MIN);
  assert_eq!(
    Vec::<u8>::from(HexBytes::from(vec![1, 2, 3])),
    vec![1, 2, 3]
  );
  assert_eq!(*U128::from(7).get(), 7);
  assert_eq!(U128::from(7).into_inner(), 7);
}

/// **EVERY ADDRESS ROUND-TRIPS THROUGH ITS OWN CANONICAL TEXT**, at both versions and at both
/// untagged unions — `parse(render(a)) == a`, which is the fixed point the family's whole grammar
/// argument rests on.
///
/// Read through the CARRIERS rather than through `std`'s own `Display`/`FromStr` pair, because what
/// is claimed is about the SCALARS: a row that rendered through one spelling and parsed through
/// another would pass a test written against the standard library and fail on the wire.
#[test]
fn an_address_round_trips_through_its_canonical_text() {
  use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};

  use super::{
    NetIpAddr, NetIpv4Addr, NetIpv6Addr, NetSocketAddr, NetSocketAddrV4, NetSocketAddrV6,
  };

  macro_rules! round_trips {
    ($carrier:ident($value:expr) => $text:literal) => {{
      let carrier = $carrier::from($value);
      assert_eq!(rendered(carrier.clone()), $text);
      assert_eq!(
        $carrier::parse(Value::String(String::from($text))).expect("its own rendering parses"),
        carrier,
        $text
      );
    }};
  }

  round_trips!(NetIpv4Addr(Ipv4Addr::new(192, 0, 2, 1)) => "192.0.2.1");
  round_trips!(NetIpv4Addr(Ipv4Addr::UNSPECIFIED) => "0.0.0.0");
  round_trips!(NetIpv4Addr(Ipv4Addr::BROADCAST) => "255.255.255.255");
  round_trips!(NetIpv6Addr(Ipv6Addr::LOCALHOST) => "::1");
  round_trips!(NetIpv6Addr(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)) => "2001:db8::1");
  round_trips!(NetIpAddr(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1))) => "192.0.2.1");
  round_trips!(NetIpAddr(IpAddr::V6(Ipv6Addr::LOCALHOST)) => "::1");
  round_trips!(NetSocketAddrV4(SocketAddrV4::new(Ipv4Addr::new(192, 0, 2, 1), 443)) => "192.0.2.1:443");
  round_trips!(NetSocketAddrV6(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 443, 0, 0)) => "[::1]:443");
  round_trips!(NetSocketAddr(SocketAddr::from(([192, 0, 2, 1], 443))) => "192.0.2.1:443");
  round_trips!(NetSocketAddr(SocketAddr::from((Ipv6Addr::LOCALHOST, 443))) => "[::1]:443");
}

/// **RFC 5952 IS THE RENDERED FORM AND RFC 4291 IS THE READ ONE** — every spelling is accepted and
/// exactly one comes back, so `render(parse(t))` is the CANONICAL spelling of `t` rather than `t`.
///
/// The same promise the byte households make about hex, at the one family where the normalisation
/// does real work: an IPv6 address has a combinatorial number of legal spellings, and a client that
/// compared two of them as strings would be comparing spellings rather than addresses.
#[test]
fn an_ipv6_address_comes_back_in_exactly_one_spelling() {
  use super::NetIpv6Addr;

  for text in [
    "2001:0DB8:0000:0000:0000:0000:0000:0001",
    "2001:db8:0:0:0:0:0:1",
    "2001:db8::0:1",
    "2001:DB8::1",
  ] {
    let parsed = NetIpv6Addr::parse(Value::String(String::from(text))).expect(text);
    assert_eq!(rendered(parsed), "2001:db8::1", "{text}");
  }

  // The IPv4-MAPPED tail keeps its dotted form, which is RFC 5952's own exception rather than an
  // inconsistency: `::ffff:c000:201` and `::ffff:192.0.2.1` are one address and the second is the
  // canonical spelling of it.
  let mapped =
    NetIpv6Addr::parse(Value::String(String::from("::ffff:c000:201"))).expect("a mapped address");
  assert_eq!(rendered(mapped), "::ffff:192.0.2.1");
}

/// A spelling outside the grammar is REFUSED and never guessed at, and the sentence names the scalar
/// that refused and the form a repair takes — the two facts a client can act on.
///
/// The LEADING ZERO case is the one worth having on the record: `01.2.3.4` is a real address in some
/// resolvers (octal) and a different one in others (decimal), so reading it at all would be this
/// crate choosing a host on a client's behalf. The standard library refuses it and so does this row.
#[test]
fn a_malformed_address_is_refused_by_name() {
  use super::{NetIpv4Addr, NetIpv6Addr, NetSocketAddr};

  let refused = refusal::<NetIpv4Addr>(Value::String(String::from("01.2.3.4")))
    .expect("a leading zero is not an address");
  assert!(refused.contains("`Ipv4Addr`"), "{refused}");
  assert!(refused.contains("DOTTED QUAD"), "{refused}");
  assert!(
    refused.contains("REFUSED and never guessed at"),
    "{refused}"
  );

  for text in ["192.0.2.256", "192.0.2", "192.0.2.1 ", "", "::1"] {
    assert!(
      refusal::<NetIpv4Addr>(Value::String(String::from(text))).is_some(),
      "{text}"
    );
  }
  for text in ["2001:db8::1::2", "gggg::1", "192.0.2.1"] {
    assert!(
      refusal::<NetIpv6Addr>(Value::String(String::from(text))).is_some(),
      "{text}"
    );
  }
  // A socket address with NO PORT is not one, and is refused rather than defaulted to zero.
  let portless = refusal::<NetSocketAddr>(Value::String(String::from("192.0.2.1")))
    .expect("an address with no port is not a socket address");
  assert!(portless.contains("`SocketAddr`"), "{portless}");

  // A wire value that is not a STRING is the wrong type rather than a badly spelled address — there
  // is no number leg here for a packed integer to arrive through.
  assert!(refusal::<NetIpv4Addr>(Value::Number(7.into())).is_some());
  assert!(!NetIpv4Addr::is_valid(&Value::Number(7.into())));
}

/// `is_valid` runs the SAME parser `parse` does across the address family too — see
/// [`validity_and_parsing_are_one_question`], whose claim this is at the second grammar.
#[test]
fn address_validity_and_parsing_are_one_question() {
  use super::{NetIpAddr, NetIpv4Addr};

  for text in ["192.0.2.1", "0.0.0.0"] {
    let value = Value::String(String::from(text));
    assert!(NetIpv4Addr::is_valid(&value), "{text}");
    assert!(NetIpv4Addr::parse(value).is_ok(), "{text}");
  }
  for text in ["01.2.3.4", "", "::1", "192.0.2.1:443"] {
    let value = Value::String(String::from(text));
    assert!(!NetIpv4Addr::is_valid(&value), "{text}");
    assert!(NetIpv4Addr::parse(value).is_err(), "{text}");
  }
  // The UNTAGGED union reads both versions, which is the whole of what it is for.
  for text in ["192.0.2.1", "2001:db8::1"] {
    let value = Value::String(String::from(text));
    assert!(NetIpAddr::is_valid(&value), "{text}");
    assert!(NetIpAddr::parse(value).is_ok(), "{text}");
  }
}

/// **THE PATTERN CROSSES VERBATIM AND CANONICALISES NOTHING**, which is where this scalar parts from
/// every other parsed-text row in the file.
///
/// A uuid folds four spellings into one and an IPv6 address folds many into RFC 5952. A pattern
/// folds none: `(?i)a` and `[aA]` accept exactly the same strings and are two different values, so
/// what comes back is the text that went in, character for character. Asserted at a pattern with
/// whitespace, a flag group and an escape, because those are the three things a canonicaliser would
/// have been tempted by.
#[cfg(feature = "regex")]
#[test]
fn a_pattern_comes_back_exactly_as_it_was_written() {
  use super::RegexPattern;

  for pattern in [
    "^[a-z]+(?:-[0-9]+)?$",
    "(?i)README\\.md",
    "(?x) a  b ",
    "\\p{Greek}+",
    "",
  ] {
    let parsed = RegexPattern::parse(Value::String(String::from(pattern)))
      .unwrap_or_else(|_| panic!("`{pattern}` compiles"));
    assert_eq!(
      rendered(parsed),
      pattern,
      "`{pattern}` is returned verbatim"
    );
  }
}

/// A pattern that does not compile is refused, and the refusal carries the ENGINE's own sentence —
/// the span, the quote and the rule — because that is the only thing a client writing a pattern can
/// act on.
#[cfg(feature = "regex")]
#[test]
fn a_pattern_that_does_not_compile_is_refused_with_the_engine_s_own_sentence() {
  use super::RegexPattern;

  let refused = refusal::<RegexPattern>(Value::String(String::from("a(b")))
    .expect("an unclosed group is not a pattern");
  assert!(
    refused.contains("is not `Regex` text"),
    "the refusal names the scalar: {refused}"
  );
  assert!(
    refused.contains("COMPILED on the way in"),
    "the refusal says what the crossing does: {refused}"
  );
  assert!(
    refused.contains("unclosed group"),
    "the refusal carries the engine's own diagnosis: {refused}"
  );

  // A BACKREFERENCE is the dialect's own refusal rather than a syntax error, and it is the one a
  // client migrating from PCRE meets first — so it is pinned here beside the syntax case.
  let unsupported = refusal::<RegexPattern>(Value::String(String::from(r"(a)\1")))
    .expect("this engine has no backreference");
  assert!(
    unsupported.contains("backreferences"),
    "the dialect's own refusal reaches the client: {unsupported}"
  );

  // A JSON number is the WRONG TYPE rather than a badly written pattern — the same fork every row
  // in this file takes.
  let wrong = refusal::<RegexPattern>(Value::Number(7.into())).expect("a number is not a pattern");
  assert!(
    wrong.contains("Expected input type \"Regex\""),
    "a number is refused as the wrong type: {wrong}"
  );
}

/// Validity and parsing are ONE question here as everywhere, and here they are one EXPENSIVE
/// question: `is_valid` compiles the pattern and throws the automaton away, which is the price of
/// never admitting a document the parse then refuses.
#[cfg(feature = "regex")]
#[test]
fn validating_a_pattern_is_compiling_it() {
  use super::RegexPattern;

  for (pattern, valid) in [("^ok$", true), ("a(b", false), (r"(a)\1", false)] {
    let value = Value::String(String::from(pattern));
    assert_eq!(RegexPattern::is_valid(&value), valid, "{pattern}");
    assert_eq!(
      RegexPattern::parse(value).is_ok(),
      valid,
      "{pattern} parses exactly when it validates"
    );
  }
}

/// The carrier converts both ways and holds the operand it was built from — the `bare` derive arm's
/// row, proved the way the full arm's is one test up.
#[cfg(feature = "regex")]
#[test]
fn a_pattern_carrier_converts_both_ways() {
  use super::RegexPattern;

  let compiled = regex::Regex::new("^a+$").expect("a pattern");
  let carried = RegexPattern::from(compiled);
  assert_eq!(carried.get().as_str(), "^a+$");
  assert_eq!(
    regex::Regex::from(carried.clone()).as_str(),
    "^a+$",
    "and back out again"
  );
  assert_eq!(carried.into_inner().as_str(), "^a+$");
}