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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! The RELAY CONNECTION: what a page looks like on the wire, and the arguments a client asks for
//! one with.
//!
//! ```text
//! medias(orderBy: [{title: ASC}], first: 20, after: "…") {
//!   edges { node { title }  cursor }
//!   pageInfo { hasNextPage  hasPreviousPage  startCursor  endCursor }
//! }
//! ```
//!
//! # The connection is async-graphql's own, at the parameters the design fixed
//!
//! [`Connection`] is an ALIAS rather than a type of this crate's, and that is the whole of what this
//! module decides about the shape: the library already renders `edges { node cursor }` and
//! `pageInfo`, names the object `<Node>Connection` and mints `<Node>Edge` beside it, so a second
//! implementation would be a second relay to keep correct. What the alias pins is the two knobs the
//! library leaves open:
//!
//! - the CURSOR is [`Cursor<V>`](crate::Cursor) — the engine's own typed keyset position, which
//!   [`CursorType`] renders as the one opaque string a client holds. Never an offset: a connection
//!   whose cursor was a row number would let a client page a moving table by counting, which is the
//!   lane this framework refuses on both sides of the wire.
//! - `nodes` is OFF. The design ruled `edges { node cursor }` and `pageInfo`, and the library's
//!   optional `nodes` shortcut is a word no ruling carries; a field a client can see is a promise,
//!   and this one can be added later without breaking anyone.
//!
//! The library leaves a THIRD knob open — what the SDL calls the page and one edge — and that one
//! the alias FORWARDS rather than pins, because unlike the cursor and unlike `nodes` the answer is
//! per DECLARATION rather than per framework: two records in one schema may reasonably disagree. So
//! both parameters are open, each carrying the library's own default for a hand-written caller, and
//! what a declaration's page is called is decided where a declaration can be read — in
//! `emit::queries`, whose naming tower is the plural, `graphql(plural = "…")` over it and
//! `graphql(connection(rename = "…"), edge(rename = "…"))` on top.
//!
//! # THE KEY DEFAULT: an absent `orderBy` is the key ascending
//!
//! A wire list or page that writes no `orderBy` runs on **the record's key, ascending** — the same
//! order `orderBy: []` gets, and the same one `<T>OrderBy::complete` puts at the end of every
//! written order. The two are one query: absent normalises to empty, and empty completes into the
//! key.
//!
//! It is a DOCUMENTED default rather than a silent one, and it is the only default that could be:
//! the key is unique, so the order is total, so a page in it neither skips nor repeats a row. A
//! default that were merely *some* order would be the wrong kind of convenience — a client that
//! paged it would get a plausible answer with rows missing.
//!
//! This SUPERSEDES the strict form, where an absent argument was refused and a client had to write
//! `orderBy: []` to say *the address order*. 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.
//!
//! What is NOT superseded is the ENGINE's rule, and the difference is the layers'. In Rust, `first`,
//! `last`, `after` and `before` exist on the ordered builder state and nowhere else, so a page over
//! the unordered lane is a method that does not exist — see `query::sql::find`'s own table. That
//! stands: a Rust caller that reached the page lane WROTE `.order(…)`, and the framework does not
//! choose an order for a party that has a compiler telling it to.
//!
//! # The teaching refusals: what the Rust builder says with a MISSING METHOD
//!
//! The two that remain are the DIRECTION pairs, and each is one arrow of the typestate written out
//! as a sentence — GraphQL having no cross-argument constraint to state it with:
//!
//! | the Rust query | why it does not compile | the wire's answer |
//! |---|---|---|
//! | `find(…).order(&[]).first(20).last(5)` | `Paging<Forward>` has no `last` | [`PageError::Directions`] |
//! | `find(…).order(&[]).first(20).before(c)` | `Paging<Forward>` has no `before` | the same |
//!
//! # `skip` has no argument here at all
//!
//! There is no OFFSET lane on the wire, matching the engine's own refusal of one — so the fourth
//! position the Rust builder carries has nothing to be refused, because nothing can ask for it. The
//! typed refusal for an oversized offset stays where the offset is bound.

use core::fmt::Display;

use async_graphql::{
  OutputType,
  connection::{
    Connection as RelayConnection, ConnectionNameType, CursorType, DefaultConnectionName,
    DefaultEdgeName, DisableNodesField, Edge as RelayEdge, EdgeNameType, EmptyFields,
  },
};

use super::{ErrorCode, ToErrorCode};
use crate::{
  Cursor, CursorError, CursorValue,
  query::{DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, Page},
};

#[cfg(test)]
mod raised_tests;
#[cfg(test)]
mod tests;

/// One page of `N`, resumed by the engine's own keyset cursor.
///
/// The NODE comes first because it is the half a reader is asking about: `Connection<MediaOutput,
/// MediaSqliteCursor>` says what a client receives, then how it resumes. async-graphql's own
/// parameter order is the other way round, and this alias is the one place the two meet.
///
/// # The two NAME parameters, and why they are last and defaulted
///
/// `C` and `D` are the SDL names of the page object and of one edge — async-graphql's
/// [`ConnectionNameType`] and [`EdgeNameType`] hooks, which the library resolves by calling
/// `type_name::<N>()` rather than by any Rust name. They sit LAST and each carries its default, so
/// `Connection<N, V>` is the same type it was and every call site that writes two parameters is
/// untouched: the knob is a pure widening, which is the law this crate applies to every argument and
/// type parameter it adds.
///
/// The DEFAULTS are the Relay Cursor Connections specification's own vocabulary — `<Node>Connection`
/// and `<Node>Edge` — and they are what a HAND-WRITTEN `Connection<N, V>` still publishes, this
/// alias being a widening that moved nothing.
///
/// **A DECLARATION's page does not reach them**, and that is not this alias's decision: the emitted
/// legs close both parameters in every case, on markers the expansion mints, because the user's
/// ruling of 2026-08-13 put the page's name on the record's PLURAL — `ReelsConnection`, not
/// `ReelConnection` — and the library's default renders over the node's own type name, which is the
/// singular. `emit::queries`'s own note carries the tower those markers resolve, its three tiers and
/// what leaving the specification's shape costs a client's tooling.
pub type Connection<N, V, C = DefaultConnectionName, D = DefaultEdgeName> =
  RelayConnection<Cursor<V>, N, EmptyFields, EmptyFields, C, D, DisableNodesField>;

/// The cursor as a client holds it: one opaque base64url string, checked back into typed values.
///
/// The framework's own frame rather than relay's `OpaqueCursor`, which is a serde round-trip over
/// whatever the node's id happens to be. What a page resumes at here is the ordering TUPLE under the
/// SIGNATURE of the order it was minted in, so a cursor replayed against another order is refused by
/// name instead of comparing values against columns nobody named.
impl<V> CursorType for Cursor<V>
where
  V: CursorValue,
{
  type Error = CursorError;

  #[inline]
  fn decode_cursor(text: &str) -> Result<Self, Self::Error> {
    Self::decode(text)
  }

  #[inline]
  fn encode_cursor(&self) -> String {
    self.encode()
  }
}

/// One of the four pagination arguments a client may write.
///
/// A closed vocabulary rather than the strings themselves, for the reason every name in this crate
/// is a type: a refusal names the argument a client wrote, and an argument name that could be any
/// `&str` is one a refusal could be built with a typo in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PageArgument {
  /// `first` — how many rows, walking forward.
  First,
  /// `last` — how many rows, walking backward.
  Last,
  /// `after` — the position a forward walk resumes past.
  After,
  /// `before` — the position a backward walk resumes short of.
  Before,
}

impl PageArgument {
  /// This argument as a client spells it.
  ///
  /// camelCase is not reached: all four are one word, which is why relay's names survive every
  /// naming convention unchanged.
  #[inline]
  #[must_use]
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::First => "first",
      Self::Last => "last",
      Self::After => "after",
      Self::Before => "before",
    }
  }

  /// Whether this argument describes a FORWARD walk.
  ///
  /// The partition the direction refusal is built on, and it is the builder's own: `first` and
  /// `after` are the two methods `Paging<Forward>` is reached and continued through, `last` and
  /// `before` are `Paging<Backward>`'s.
  #[inline]
  #[must_use]
  pub const fn is_forward(self) -> bool {
    matches!(self, Self::First | Self::After)
  }
}

impl Display for PageArgument {
  #[inline]
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str(self.as_str())
  }
}

/// Why these arguments describe no page.
///
/// A sum whose arms carry their own facts, as [`CursorError`] is: the two refuse two different
/// things and a client fixes each of them differently, which is why each arm answers with a code of
/// its own.
///
/// # The arm that LEFT, and what took its place
///
/// `Unordered` stood here and refused a page whose query wrote no `orderBy`. The key default
/// superseded it: an absent argument is now the record's key ascending, which is a total order, so
/// there is nothing left to refuse. A refusal that cannot be raised needs no variant — the rule
/// [`SqlWriteError`](crate::query::sql::SqlWriteError) is three variants rather than seven under —
/// and `UNORDERED_PAGE` left the wire vocabulary with it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageError {
  /// Two arguments named two directions, and a page runs one way.
  Directions {
    /// The forward argument that was written.
    forward: PageArgument,
    /// The backward one written beside it.
    backward: PageArgument,
  },
  /// A cursor a client handed back is not one this build can read.
  ///
  /// Only the FRAME is read here. Whether the cursor belongs to the order it is being replayed
  /// against is the engine's own question, asked where the page is rendered.
  Cursor {
    /// Which argument carried it.
    argument: PageArgument,
    /// What the frame refused with.
    cause: CursorError,
  },
}

impl Display for PageError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Directions { forward, backward } => write!(
        f,
        "`{forward}` walks forward and `{backward}` walks backward, and a page runs one way — keep \
         the arguments of one direction"
      ),
      Self::Cursor { argument, cause } => write!(f, "`{argument}` is not a cursor: {cause}"),
    }
  }
}

impl core::error::Error for PageError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Directions { .. } => None,
      Self::Cursor { cause, .. } => Some(cause),
    }
  }
}

/// One word per ARM, because the two ask a client for two different fixes — drop an argument, drop
/// a cursor. A single word over both would tell a client that its query is wrong and nothing about
/// how.
impl ToErrorCode for PageError {
  #[inline]
  fn error_code(&self) -> ErrorCode {
    match self {
      Self::Directions { .. } => ErrorCode::AmbiguousPageDirection,
      Self::Cursor { .. } => ErrorCode::UnusableCursor,
    }
  }
}

/// The page a client's arguments describe: which way it walks, how wide, and where it resumes.
///
/// It is built by [`of`](Self::of) and nowhere else, so every value of this type has already passed
/// the refusals — the arrangement [`Orderings`](crate::Orderings) takes one door over, and for the
/// same reason: a check somebody remembers to run is a check somebody forgets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PageRequest<V> {
  /// The order as written, read from the start or from a position inside it.
  Forward {
    /// How many rows, or the framework's default where the client named none.
    first: Option<u32>,
    /// The row to resume past.
    after: Option<Cursor<V>>,
  },
  /// The same order read from the far end.
  Backward {
    /// How many rows, or the framework's default where the client named none.
    last: Option<u32>,
    /// The row to resume short of.
    before: Option<Cursor<V>>,
  },
}

impl<V> PageRequest<V>
where
  V: CursorValue,
{
  /// The page these arguments describe, or why they describe none.
  ///
  /// # The ORDER is not among them, and that is the key default
  ///
  /// This took `order: Option<&Orderings<T>>` ([`Orderings`](crate::Orderings)) and refused a page
  /// whose query wrote none. It decided
  /// exactly that one thing, and the key default decided it the other way: an absent `orderBy` is
  /// the record's key ascending, `orderBy: []` normalises to the same, and a resolver reaches both
  /// through `Orderings::default` and the emitted `complete`. So the argument answers no question
  /// this type asks, and a parameter read for nothing is a parameter a caller has to guess the
  /// meaning of.
  ///
  /// A page is the four RELAY arguments: which way it walks, how wide, and where it resumes. The
  /// order is a second axis, and it now crosses on its own.
  ///
  /// The cursors are DECODED here, so a resolver that holds a `PageRequest` holds values rather
  /// than strings and there is no second place for the frame to be checked.
  ///
  /// # Errors
  ///
  /// [`PageError::Directions`] where the arguments name both walks; [`PageError::Cursor`] where a
  /// cursor's frame will not read.
  pub fn of(
    first: Option<u32>,
    last: Option<u32>,
    after: Option<&str>,
    before: Option<&str>,
  ) -> Result<Self, PageError> {
    let written = [
      first.map(|_| PageArgument::First),
      last.map(|_| PageArgument::Last),
      after.map(|_| PageArgument::After),
      before.map(|_| PageArgument::Before),
    ];
    // The typestate's own partition, read off the arguments that were actually written: one from
    // each side is a page asked to run two ways, which `Paging<Forward>` and `Paging<Backward>`
    // make unspellable by having no method in common.
    let side = |forward: bool| {
      written
        .into_iter()
        .flatten()
        .find(|argument| argument.is_forward() == forward)
    };
    if let (Some(forward), Some(backward)) = (side(true), side(false)) {
      return Err(PageError::Directions { forward, backward });
    }
    let decode = |argument, text: Option<&str>| {
      text
        .map(Cursor::<V>::decode)
        .transpose()
        .map_err(|cause| PageError::Cursor { argument, cause })
    };
    if last.is_some() || before.is_some() {
      return Ok(Self::Backward {
        last,
        before: decode(PageArgument::Before, before)?,
      });
    }
    Ok(Self::Forward {
      first,
      after: decode(PageArgument::After, after)?,
    })
  }
}

impl<V> PageRequest<V> {
  /// How many rows this page will hold — what the client asked for, defaulted and clamped.
  ///
  /// The same two constants the engine's builder spends, so a resolver reading this and the page
  /// that runs cannot disagree: [`DEFAULT_PAGE_SIZE`] where no size was named, and
  /// [`MAX_PAGE_SIZE`] as the ceiling every ask is narrowed to. Relay lets a server return fewer
  /// edges than were asked for, which is what makes the clamp a legal answer rather than a refusal.
  #[inline]
  #[must_use]
  pub const fn size(&self) -> u32 {
    let asked = match self {
      Self::Forward { first: size, .. } | Self::Backward { last: size, .. } => *size,
    };
    match asked {
      Some(asked) if asked > MAX_PAGE_SIZE => MAX_PAGE_SIZE,
      Some(asked) => asked,
      None => DEFAULT_PAGE_SIZE,
    }
  }

  /// Whether this page walks the order as written.
  #[inline]
  #[must_use]
  pub const fn is_forward(&self) -> bool {
    matches!(self, Self::Forward { .. })
  }

  /// The position this page resumes at, where the client gave one.
  #[inline]
  #[must_use]
  pub fn position(&self) -> Option<&Cursor<V>> {
    match self {
      Self::Forward { after: at, .. } | Self::Backward { before: at, .. } => at.as_ref(),
    }
  }
}

impl<R, V> Page<R, V>
where
  V: CursorValue,
{
  /// This page as the connection a client receives, each record crossed into its wire face by
  /// `node`.
  ///
  /// The crossing is the CALLER's, and it is fallible for the reason the read lane's own is: a
  /// record reaches its output face through the conversions a declaration wrote, and one of them
  /// may refuse. Nothing is assembled before it does — an edge is minted only for a record that
  /// crossed.
  ///
  /// The cursors travel unchanged. They were minted by the engine at the rows this page holds, so
  /// the string a client resumes with is the one the boundary row produced and never a re-derivation
  /// of it.
  ///
  /// # The NAME parameters are inferred from the RETURN position
  ///
  /// `C` and `D` are never written at a call site: the caller states the connection it wants back —
  /// the emitted list leg does so in its own signature — and the two names follow from that. Both
  /// carry the specification's defaults on the alias, so a caller that names neither gets
  /// `<Node>Connection` / `<Node>Edge`, which is what every call site written before the knob
  /// existed already asked for.
  ///
  /// # Errors
  ///
  /// Whatever `node` refuses with, at the first record that does not cross.
  pub fn into_connection<N, E, C, D>(
    self,
    mut node: impl FnMut(R) -> Result<N, E>,
  ) -> Result<Connection<N, V, C, D>, E>
  where
    N: OutputType,
    V: Send + Sync,
    C: ConnectionNameType,
    D: EdgeNameType,
  {
    let (has_next, has_previous) = (self.has_next_page(), self.has_previous_page());
    let mut connection = Connection::new(has_previous, has_next);
    for edge in self.into_edges() {
      let (record, cursor) = edge.into_parts();
      connection.edges.push(RelayEdge::new(cursor, node(record)?));
    }
    Ok(connection)
  }

  /// The same page, where the nodes were raised SOMEWHERE ELSE and arrive already in the page's own
  /// order.
  ///
  /// # Why an interface cannot use the map above
  ///
  /// A record's row becomes its wire object by a pure conversion, one row at a time — which is what
  /// [`into_connection`](Self::into_connection)'s `FnMut` is. An interface's row is a PROJECTION:
  /// the shared columns, a discriminant and an address, and the object a client asked for lives in
  /// the member's own table. So the crossing is a GATHER — one statement per member, `async`, and
  /// batched — and neither of those two words fits a synchronous per-row closure.
  ///
  /// So the caller does the gather, scatters each member's answers back to the positions the page
  /// asked for them at, and hands the result here. The cursors travel unchanged, as they do above:
  /// they were minted by the engine at the rows this page holds.
  ///
  /// # A slot the gather did not fill is REPORTED
  ///
  /// `Option` per slot, and a `None` is a refusal rather than a shorter page. It should be
  /// unreachable — the emitted lane asks every discriminant the projection can carry, and the
  /// hydration itself refuses a member's gather that came back short — so what this guards is the
  /// class of bug rather than a state a correct caller reaches. A page that silently loses rows is
  /// a page whose `hasNextPage` is a lie, which is the same judgement the hydration's own coherence
  /// refusal is made on.
  ///
  /// # Errors
  ///
  /// [`UnraisedPage`] where any slot arrived empty, naming how many of how many.
  pub fn into_connection_of<N, C, D>(
    self,
    nodes: Vec<Option<N>>,
  ) -> Result<Connection<N, V, C, D>, UnraisedPage>
  where
    N: OutputType,
    V: Send + Sync,
    C: ConnectionNameType,
    D: EdgeNameType,
  {
    let (has_next, has_previous) = (self.has_next_page(), self.has_previous_page());
    let edges = self.into_edges();
    let of = edges.len();
    let missing = nodes.iter().filter(|node| node.is_none()).count() + of.abs_diff(nodes.len());
    if missing > 0 {
      return Err(UnraisedPage { missing, of });
    }
    let mut connection = Connection::new(has_previous, has_next);
    for (edge, node) in edges.into_vec().into_iter().zip(nodes) {
      let (_, cursor) = edge.into_parts();
      // `flatten`'s own answer, reached by a `let else` rather than an unwrap: the count above has
      // already refused every empty slot, so this arm is unreachable — and it is written as an arm
      // instead of a panic because an emitted resolver has no business carrying one.
      let Some(node) = node else {
        return Err(UnraisedPage { missing: 1, of });
      };
      connection.edges.push(RelayEdge::new(cursor, node));
    }
    Ok(connection)
  }
}

/// A page whose nodes were raised elsewhere and did not all come back.
///
/// Carried as a type rather than a sentence because it crosses a resolver boundary: the emitted
/// interface lane maps it through `refused_row`, which attaches
/// [`UnreadableRow`](ErrorCode::UnreadableRow) — the row read fine and did not become what a client
/// asked for, which is exactly this.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnraisedPage {
  /// How many slots arrived empty.
  missing: usize,
  /// How many rows the page held.
  of: usize,
}

impl UnraisedPage {
  /// How many slots arrived empty.
  #[inline]
  #[must_use]
  pub const fn missing(&self) -> usize {
    self.missing
  }

  /// How many rows the page held.
  #[inline]
  #[must_use]
  pub const fn of(&self) -> usize {
    self.of
  }
}

impl Display for UnraisedPage {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "{} of {} rows on this page were never raised onto the wire — the gather that fills them \
       answered for fewer addresses than the page asked about",
      self.missing, self.of
    )
  }
}

impl std::error::Error for UnraisedPage {}