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
//! The connection, read from both sides: what the schema shows a client, and what a client gets
//! back when it walks one.
//!
//! # The corpus is in memory and the CURSOR is the real one
//!
//! What this module proves is the WIRE loop — arguments in, edges and a cursor out, that cursor
//! handed back, the next page. Every piece of it on the framework's side is the shipped code: the
//! frame is [`Cursor`]'s own codec, the order it is minted under is a real
//! [`OrderTerm`](crate::OrderTerm) list, and the refusals are the ones a resolver raises. What is
//! stood in for is the STORE — a slice of titles rather than a table — because what a keyset page
//! does against a real engine is measured where the engine is, beside `query::sql::find`, and
//! repeating that here would be testing SQLite twice and the wire once.

use async_graphql::{EmptyMutation, EmptySubscription, InputType, Name, Object, Schema, Value};

use super::{Connection, PageArgument, PageError, PageRequest};
use crate::{
  Cursor, CursorValue, ErrorCode, FieldName, OrderDirection, OrderTerm, Orderings, SubjectPath,
  TermName, ToSubjectPath,
  query::{DEFAULT_PAGE_SIZE, Edge, MAX_PAGE_SIZE, Page},
};

/// Stands in for one emitted `<T>OrderBy`: one column, one direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::OneofObject)]
enum CueOrderBy {
  Title(OrderDirection),
}

impl ToSubjectPath for CueOrderBy {
  fn subject_path(&self) -> SubjectPath {
    const SUBJECT: SubjectPath = SubjectPath::new(&[TermName::new("title")]);
    SUBJECT
  }
}

/// The order every page here is minted under — a real term list, so the signature a cursor carries
/// is the one the engine would compute for it.
const ORDER: &[OrderTerm] = &[OrderTerm::new(
  TermName::new("title"),
  FieldName::new("title"),
  OrderDirection::Asc,
)];

/// Stands in for one emitted `<Row>Cursor`: the record's sum over its orderable columns, tagged by
/// column so a forged frame cannot move a value into another column's slot.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CueCursor {
  Title(String),
}

impl CursorValue for CueCursor {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::Title(title) => {
        out.push(0);
        title.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, rest) = bytes.split_first()?;
    match *tag {
      0 => String::read_cursor(rest).map(Self::Title),
      _ => None,
    }
  }
}

/// The RECORD — the domain value a page holds.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Cue {
  title: String,
}

/// The record's WIRE FACE, which is what a connection's node is. Two types rather than one, so the
/// crossing [`Page::into_connection`] takes is exercised rather than being the identity.
///
/// An `#[Object]` impl over the fields a declaration marked, which is the shape the emission writes
/// — never a blanket `SimpleObject` over everything the record holds. The GraphQL name is the
/// record's own, which is the two-axes rule: the Rust ident carries `Output` and the client sees
/// `Cue`.
struct CueOutput {
  title: String,
}

#[Object(name = "Cue")]
impl CueOutput {
  async fn title(&self) -> &str {
    &self.title
  }
}

/// The corpus, already in the order's own sequence.
const CUES: &[&str] = &["alpha", "beta", "delta", "epsilon", "gamma"];

/// One page of [`CUES`], resumed where the request says — the store's whole job, done over a slice.
fn page(request: &PageRequest<CueCursor>) -> Page<Cue, CueCursor> {
  let at = request.position().map(|cursor| {
    let values = cursor
      .resume(ORDER)
      .expect("the fixture mints every cursor under this order");
    match values[0].clone() {
      Some(CueCursor::Title(title)) => title,
      None => unreachable!("`title` is NOT NULL in this fixture"),
    }
  });
  let size = request.size() as usize;

  // The two walks are one rule read from either end: the direction the walk RAN answers exactly
  // (there was another row), and the other side answers *a position was given* — which is what
  // `Page`'s own note states and relay's own permitted approximation.
  let (rows, has_next, has_previous) = if request.is_forward() {
    let rest: Vec<&str> = CUES
      .iter()
      .copied()
      .filter(|title| at.as_deref().is_none_or(|at| *title > at))
      .collect();
    let has_previous = rest.len() != CUES.len();
    let has_next = rest.len() > size;
    (
      rest.into_iter().take(size).collect::<Vec<&str>>(),
      has_next,
      has_previous,
    )
  } else {
    let rest: Vec<&str> = CUES
      .iter()
      .copied()
      .filter(|title| at.as_deref().is_none_or(|at| *title < at))
      .collect();
    let has_next = rest.len() != CUES.len();
    let has_previous = rest.len() > size;
    let start = rest.len().saturating_sub(size);
    (rest[start..].to_vec(), has_next, has_previous)
  };

  let edges = rows
    .into_iter()
    .map(|title| {
      let cursor = Cursor::at(ORDER, vec![Some(CueCursor::Title(title.to_owned()))]);
      Edge::new(
        Cue {
          title: title.to_owned(),
        },
        cursor,
      )
    })
    .collect::<Vec<_>>();
  Page::new(edges, has_next, has_previous)
}

struct Query;

/// The resolver the emission will write, written by hand: the order door, relay's four arguments,
/// one call to build the page request and one to render the connection.
#[Object]
impl Query {
  async fn cues(
    &self,
    order_by: Option<Orderings<CueOrderBy>>,
    first: Option<u32>,
    last: Option<u32>,
    after: Option<String>,
    before: Option<String>,
  ) -> async_graphql::Result<Connection<CueOutput, CueCursor>> {
    // THE KEY DEFAULT, in the one line the emission will write: an absent argument normalises to
    // the empty order, which the emitted `complete` turns into the record's key ascending. This
    // fixture's store is already in that order, so `order` is read for its terms and not for its
    // presence — which is exactly the change: presence decides nothing any more.
    let order = order_by.unwrap_or_default();
    let _ = order.len();
    let request = PageRequest::of(first, last, after.as_deref(), before.as_deref())
      .map_err(|refusal| crate::refused(&refusal))?;
    page(&request).into_connection(|cue| async_graphql::Result::Ok(CueOutput { title: cue.title }))
  }
}

fn schema() -> Schema<Query, EmptyMutation, EmptySubscription> {
  Schema::new(Query, EmptyMutation, EmptySubscription)
}

/// The order `orderBy: []` decodes to — built through the wire door, which is the only party that
/// mints one from a client's list.
///
/// It is the same value [`Orderings::default`] hands back for an ABSENT argument, which is the key
/// default's whole claim, and the test below is where the two are compared rather than assumed.
fn written_order() -> Orderings<CueOrderBy> {
  InputType::parse(Some(Value::List(Vec::new()))).expect("an empty list is a written order")
}

/// The value at `path`, where a segment is a field name or a list index.
fn pick<'v>(value: &'v Value, path: &str) -> &'v Value {
  let mut at = value;
  for segment in path.split('.') {
    at = match at {
      Value::Object(fields) => fields
        .get(&Name::new(segment))
        .unwrap_or_else(|| panic!("`{segment}` of `{path}` is not in {value}")),
      Value::List(items) => {
        let index: usize = segment.parse().expect("a list is indexed by a number");
        items
          .get(index)
          .unwrap_or_else(|| panic!("`{segment}` of `{path}` is not in {value}"))
      }
      other => panic!("`{path}` runs past {other}"),
    };
  }
  at
}

fn text<'v>(value: &'v Value, path: &str) -> &'v str {
  match pick(value, path) {
    Value::String(text) => text,
    other => panic!("`{path}` is not a string: {other}"),
  }
}

fn flag(value: &Value, path: &str) -> bool {
  match pick(value, path) {
    Value::Boolean(flag) => *flag,
    other => panic!("`{path}` is not a boolean: {other}"),
  }
}

/// Execute `query` and hand back its data, or panic naming the errors.
async fn answered(query: &str) -> Value {
  let response = schema().execute(query).await;
  assert!(response.errors.is_empty(), "{:?}", response.errors);
  response.data
}

/// Execute `query` and hand back the first refusal's sentence and its code.
async fn refusal(query: &str) -> (String, Option<String>) {
  let response = schema().execute(query).await;
  let error = response
    .errors
    .first()
    .unwrap_or_else(|| panic!("this query is refused: {query}"))
    .clone();
  let code = error
    .extensions
    .as_ref()
    .and_then(|extensions| extensions.get(ErrorCode::EXTENSION))
    .and_then(|value| match value {
      Value::String(word) => Some(word.clone()),
      _ => None,
    });
  (error.message, code)
}

/// **The ruled shape, and nothing beside it.** `edges { node cursor }` and `pageInfo`, the
/// connection named after the node, the edge named after the node — and NO `nodes` field, which is
/// the one knob this framework closes on async-graphql's connection.
#[test]
fn the_connection_renders_the_ruled_shape() {
  let sdl = schema().sdl();
  let block = |head: &str| {
    let at = sdl
      .find(head)
      .unwrap_or_else(|| panic!("`{head}` is in the schema: {sdl}"));
    let rest = &sdl[at..];
    let end = rest.find("\n}").unwrap_or(rest.len());
    rest[..end].to_owned()
  };

  let connection = block("type CueConnection {");
  assert!(connection.contains("pageInfo: PageInfo!"), "{connection}");
  assert!(connection.contains("edges: [CueEdge!]!"), "{connection}");
  assert!(
    !connection.contains("nodes"),
    "the `nodes` shortcut is a word no ruling carries: {connection}"
  );

  let edge = block("type CueEdge {");
  assert!(edge.contains("node: Cue!"), "{edge}");
  assert!(edge.contains("cursor: String!"), "{edge}");

  let info = block("type PageInfo {");
  for field in [
    "hasPreviousPage: Boolean!",
    "hasNextPage: Boolean!",
    "startCursor: String",
    "endCursor: String",
  ] {
    assert!(info.contains(field), "`{field}` is missing from {info}");
  }
}

/// The FIELD's own arguments: the order door, and relay's four. `skip` is not among them — there is
/// no OFFSET lane on the wire, so the position the Rust builder carries has no argument here to be
/// refused.
#[test]
fn the_list_field_takes_the_order_door_and_relays_four() {
  let sdl = schema().sdl();
  let field = sdl
    .lines()
    .map(str::trim)
    .find(|line| line.starts_with("cues("))
    .unwrap_or_else(|| panic!("`cues` is a field of the schema: {sdl}"))
    .to_owned();
  assert_eq!(
    field,
    "cues(orderBy: [CueOrderBy!], first: Int, last: Int, after: String, before: String): \
     CueConnection!"
  );
  assert!(!field.contains("skip"), "{field}");
}

/// The WIRE LOOP: a first page, its `endCursor` handed straight back, the rows after it — and no
/// row served twice.
#[tokio::test]
async fn a_page_resumes_at_the_cursor_it_handed_out() {
  let data = answered(
    "{ cues(orderBy: [{title: ASC}], first: 2) { edges { node { title } cursor } \
     pageInfo { hasNextPage hasPreviousPage endCursor } } }",
  )
  .await;

  assert_eq!(text(&data, "cues.edges.0.node.title"), "alpha");
  assert_eq!(text(&data, "cues.edges.1.node.title"), "beta");
  assert!(flag(&data, "cues.pageInfo.hasNextPage"));
  assert!(!flag(&data, "cues.pageInfo.hasPreviousPage"));

  // The edge's own cursor and the page's `endCursor` are the SAME string — the engine minted it at
  // the boundary row and nothing re-derived it on the way out.
  let end = text(&data, "cues.pageInfo.endCursor").to_owned();
  assert_eq!(text(&data, "cues.edges.1.cursor"), end);
  assert_eq!(
    end,
    Cursor::at(ORDER, vec![Some(CueCursor::Title(String::from("beta")))]).encode(),
    "the string a client holds is the frame the boundary row's values encode to"
  );

  let data = answered(&format!(
    "{{ cues(orderBy: [{{title: ASC}}], first: 2, after: {end:?}) {{ edges {{ node {{ title }} }} \
     pageInfo {{ hasNextPage hasPreviousPage }} }} }}"
  ))
  .await;
  assert_eq!(text(&data, "cues.edges.0.node.title"), "delta");
  assert_eq!(text(&data, "cues.edges.1.node.title"), "epsilon");
  assert!(flag(&data, "cues.pageInfo.hasNextPage"));
  assert!(
    flag(&data, "cues.pageInfo.hasPreviousPage"),
    "a resumed page approximates the side it did not walk, which is relay's own permitted answer"
  );
}

/// The BACKWARD walk is the same machinery read from the far end — `last` with no `first` beside
/// it, and the page arrives in display order.
#[tokio::test]
async fn the_backward_walk_answers_in_display_order() {
  let data = answered(
    "{ cues(orderBy: [{title: ASC}], last: 2) { edges { node { title } } \
     pageInfo { hasPreviousPage } } }",
  )
  .await;
  assert_eq!(text(&data, "cues.edges.0.node.title"), "epsilon");
  assert_eq!(text(&data, "cues.edges.1.node.title"), "gamma");
  assert!(flag(&data, "cues.pageInfo.hasPreviousPage"));
}

/// **THE KEY DEFAULT.** A page whose query wrote no `orderBy` RUNS — on the record's key ascending,
/// which is the same order `orderBy: []` gets and the same one `complete` puts at the end of every
/// written order.
///
/// This supersedes the strict form, which refused the absent argument under `UNORDERED_PAGE` and
/// told a client to write `orderBy: []`. Two spellings of one query, one of them a refusal, is a
/// thing a client had to learn for no answer it could not already have — and the word left the wire
/// vocabulary with the refusal.
#[tokio::test]
async fn a_page_with_no_written_order_runs_on_the_key_default() {
  let defaulted = answered("{ cues(first: 2) { edges { node { title } } } }").await;
  assert_eq!(text(&defaulted, "cues.edges.0.node.title"), "alpha");
  assert_eq!(text(&defaulted, "cues.edges.1.node.title"), "beta");

  // A connection selected with NO argument at all is a page too, and it is served rather than
  // refused.
  let bare = answered("{ cues { edges { node { title } } pageInfo { hasNextPage } } }").await;
  assert_eq!(text(&bare, "cues.edges.0.node.title"), "alpha");

  // …and `orderBy: []` is the SAME query, which is the normalisation stated as an equality rather
  // than as a sentence.
  let empty = answered("{ cues(orderBy: [], first: 2) { edges { node { title } } } }").await;
  assert_eq!(empty, defaulted);
}

/// The normalisation, at the door it goes through: an ABSENT argument is
/// [`Orderings::default`], which holds exactly what `orderBy: []` decodes to.
#[test]
fn an_absent_order_normalises_to_the_empty_one() {
  // The argument comes from a value the compiler cannot fold to `None`, so what runs is the
  // normalisation a resolver performs and not a literal clippy would rather see written as
  // `Orderings::default()` outright.
  let argument: Option<Orderings<CueOrderBy>> = CUES.is_empty().then(written_order);
  let absent = argument.unwrap_or_default();
  assert!(absent.is_empty());
  assert_eq!(absent.len(), written_order().len());
  assert_eq!(absent.into_terms(), written_order().into_terms());
}

/// A page runs ONE way, which the builder says by giving `Paging<Forward>` and `Paging<Backward>`
/// no method in common. On the wire it is said in a sentence naming both arguments.
#[tokio::test]
async fn a_page_that_names_two_directions_is_refused() {
  let (message, code) =
    refusal("{ cues(orderBy: [{title: ASC}], first: 2, last: 2) { edges { node { title } } } }")
      .await;
  assert!(
    message.contains("`first` walks forward and `last` walks backward"),
    "{message}"
  );
  assert_eq!(code.as_deref(), Some("AMBIGUOUS_PAGE_DIRECTION"));

  let (message, code) = refusal(
    "{ cues(orderBy: [{title: ASC}], first: 2, before: \"x\") { edges { node { title } } } }",
  )
  .await;
  assert!(
    message.contains("`first` walks forward and `before` walks backward"),
    "{message}"
  );
  assert_eq!(code.as_deref(), Some("AMBIGUOUS_PAGE_DIRECTION"));
}

/// A cursor is a string the client had, so every byte of it is checked — and the refusal names the
/// argument that carried it.
#[tokio::test]
async fn a_cursor_that_is_not_one_is_refused() {
  let (message, code) = refusal(
    "{ cues(orderBy: [{title: ASC}], after: \"not a cursor\") { edges { node { title } } } }",
  )
  .await;
  assert!(message.contains("`after` is not a cursor"), "{message}");
  assert_eq!(code.as_deref(), Some("UNUSABLE_CURSOR"));
}

/// The direction partition is the BUILDER's: `first` and `after` reach and continue
/// `Paging<Forward>`, `last` and `before` reach and continue `Paging<Backward>`.
#[test]
fn the_arguments_partition_the_way_the_typestate_does() {
  assert!(PageArgument::First.is_forward());
  assert!(PageArgument::After.is_forward());
  assert!(!PageArgument::Last.is_forward());
  assert!(!PageArgument::Before.is_forward());
  assert_eq!(PageArgument::First.to_string(), "first");
  assert_eq!(PageArgument::Before.to_string(), "before");
}

/// Every combination the builder can spell is a page, and every one it cannot is refused — walked
/// as a table so no pair is left out.
#[test]
fn the_legal_combinations_are_the_ones_the_builder_can_spell() {
  let of = |first, last, after, before| PageRequest::<CueCursor>::of(first, last, after, before);

  for (first, last, after, before, legal) in [
    (None, None, None, None, true),
    (Some(2), None, None, None, true),
    (None, Some(2), None, None, true),
    (None, None, Some("x"), None, true),
    (None, None, None, Some("x"), true),
    (Some(2), None, Some("x"), None, true),
    (None, Some(2), None, Some("x"), true),
    (Some(2), Some(2), None, None, false),
    (Some(2), None, None, Some("x"), false),
    (None, Some(2), Some("x"), None, false),
    (None, None, Some("x"), Some("x"), false),
  ] {
    let answer = of(first, last, after, before);
    let spelled = !matches!(answer, Err(PageError::Directions { .. }));
    assert_eq!(
      spelled, legal,
      "first={first:?} last={last:?} after={after:?} before={before:?} → {answer:?}"
    );
  }
}

/// The size a client gets: what it asked for, defaulted where it asked for none and clamped at the
/// framework's ceiling — the same two constants the engine's builder spends.
#[test]
fn the_size_is_defaulted_and_clamped_where_the_engine_would() {
  let forward = |first| PageRequest::<CueCursor>::Forward { first, after: None };
  assert_eq!(forward(None).size(), DEFAULT_PAGE_SIZE);
  assert_eq!(forward(Some(7)).size(), 7);
  assert_eq!(forward(Some(u32::MAX)).size(), MAX_PAGE_SIZE);
  assert_eq!(
    PageRequest::<CueCursor>::Backward {
      last: Some(u32::MAX),
      before: None,
    }
    .size(),
    MAX_PAGE_SIZE
  );
}