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
//! **THE ROOT-KEY REGISTRY, ON THE WIRE** — K5 of the registry bureau: a client asks `registry
//! (family: "media") { state(key:) inflight(key:) counts { … } recent(n:) }`, and four flat
//! mutations turn the live dial and move a key by hand.
//!
//! ```text
//! Schema::build(<Root>Query::default(), RegistryMutationRoot::default(), EmptySubscription)
//!         .data(Arc::clone(&registries))                          // the application, once
//!         │
//!         ▼
//! ctx.data::<Arc<Registries>>()?  →  registries.dyn_for("media")  →  DynRegistry's own doors
//! ```
//!
//! # `registry(family:)` MOUNTS on the query root; the four mutations do NOT nest under one
//!
//! The brief's own shape is asymmetric and this face keeps it that way rather than smoothing it:
//! `registry(family:)` returns [`RegistryFamily`], a sub-object every READ goes through, while
//! `registryKnobs`, `retire`, `restore` and `reanalyze` are FLAT fields of [`RegistryMutationRoot`],
//! each taking its own `family` argument. A read asks *what is true of this family*, which is one
//! object's worth of questions; a write asks the framework to DO something, and four independent
//! acts nested under a shared parent would buy nothing a repeated argument does not already say.
//!
//! # WHY THE DISPATCH NEEDS NO PER-GRAPH CODEGEN AT ALL
//!
//! A graph's own root types are typed all the way down — `Registries::open::<Root>` — and a runtime
//! `family: String` cannot name one. The alternative this face takes is
//! [`crate::drive::DynRegistry`]: a family becomes reachable BY NAME the moment something calls
//! `Registries::expose::<Root>(family)` for it, independent of which graph, if any, mounts this
//! field — so `ingraph-codegen`'s own part is exactly ONE line, folding [`RegistryQueryRoot`] into
//! `<Root>Query`'s `MergedObject` beside the members a graph's own declarations project, and nothing
//! about a family's TYPE crosses the codegen boundary at all.
//!
//! # State is a LOWERCASE unit enum, and durations are humantime text BOTH WAYS
//!
//! [`RegistryState`] mirrors [`RootState`] with its data erased — `idle` `analyzing` `retiring`
//! `retired` `restoring`, on the wire-naming constitution's own law. Every duration this face
//! touches — `registryKnobs`'s five arguments, [`RegistryOptionsView`]'s four fields — crosses as
//! `humantime` text (`"300ms"`, `"1s"`), the SAME grammar [`RegistryOptions`]'s own document reads,
//! because a knob turned from a client is the SAME options-layer grain a `[registry]` section is —
//! see that type's own module note for the three-tier law this face's mutation is the third tier of.
//!
//! # READS are gentle on an unknown family; WRITES are not
//!
//! `registry(family: "nonexistent")` answers a live object whose every field reads the honest
//! nothing — [`idle`](RegistryState::Idle), zero counts, an empty `recent` — on
//! [`RegistryOptions`]'s own ruling that family names are OPEN and an unrecognised one is inert
//! rather than wrong. A MUTATION on an unexposed family is the opposite case: a person asked this
//! framework to retire, restore or re-tune something, and answering as though it happened would be a
//! lie a query's silence never tells. So every mutation here refuses by name where
//! [`Registries::dyn_for`] answers [`None`], and a `key` that does not even parse as the family's
//! own root type refuses the SAME way — on [`crate::drive::DynRegistry`]'s own reasoning, a key
//! nothing could be true of is a mistake worth surfacing on the write side and the honest `idle` on
//! the read side.

use core::time::Duration;
use std::sync::Arc;

use async_graphql::{Context, Enum, Error, Object, Result, SimpleObject};

use crate::drive::{
  DynRegistry, Registries, RegistryCounts as FamilyCounts, RegistryOptions, RegistryOverride,
  RetireOrigin, RootState,
};

#[cfg(test)]
mod tests;

/// How many entries [`RegistryFamily::recent`] answers when a client names none — generous enough
/// for an operator's glance, bounded enough that nobody asking "what's going on" walks a family's
/// whole table by accident.
const DEFAULT_RECENT: usize = 20;

/// `n` truncated up at zero and widened, on [`clippy::cast_sign_loss`]'s own reasoning: a client
/// asking for `-5` recent entries is asking for none, not for a wrapped huge number.
#[inline]
fn recent_limit(n: Option<i32>) -> usize {
  n.map_or(DEFAULT_RECENT, |n| {
    usize::try_from(n.max(0)).unwrap_or(usize::MAX)
  })
}

/// A count clamped into the wire's own width — [`u32::MAX`] rather than a silent wrap, for a family
/// so large the honest answer is "very many" rather than a number that lies.
#[inline]
fn wire_count(n: usize) -> u32 {
  u32::try_from(n).unwrap_or(u32::MAX)
}

/// `text` read as [`humantime`]'s own grammar — [`RegistryOptions`]'s module note: never a bare
/// number, always `"300ms"` / `"1s"` / `"2m"`.
fn parse_duration(field: &str, text: &str) -> Result<Duration> {
  humantime::parse_duration(text)
    .map_err(|error| Error::new(format!("{field}: not a duration: {text:?} ({error})")))
}

/// A duration rendered back out as the SAME grammar it was read in — `humantime::format_duration`,
/// both ways per the module note.
fn format_duration(duration: Duration) -> String {
  humantime::format_duration(duration).to_string()
}

/// **ONE ROOT KEY'S STATE, ON THE WIRE** — [`RootState`] with every payload erased, because a unit
/// enum is what a wire vocabulary this closed IS: five values, framework-owned, and no downstream
/// crate has anything to add to *where a key stands*.
///
/// Lowercase, per the wire-naming constitution: `idle` `analyzing` `retiring` `retired` `restoring`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Enum)]
#[graphql(rename_items = "lowercase")]
pub enum RegistryState {
  /// Nothing is stored for this key — see [`RootState::Idle`].
  Idle,
  /// Work is out and not yet answered — see [`RootState::Analyzing`].
  Analyzing,
  /// On its way out, answers still owed — see [`RootState::Retiring`].
  Retiring,
  /// Out — see [`RootState::Retired`].
  Retired,
  /// Coming back — see [`RootState::Restoring`].
  Restoring,
}

/// [`RootState`]'s own data erased to the tag alone — total, the same way the type it projects is.
impl From<RootState> for RegistryState {
  fn from(state: RootState) -> Self {
    match state {
      RootState::Idle => Self::Idle,
      RootState::Analyzing { .. } => Self::Analyzing,
      RootState::Retiring { .. } => Self::Retiring,
      RootState::Retired { .. } => Self::Retired,
      RootState::Restoring => Self::Restoring,
    }
  }
}

/// **WHO RETIRES A KEY, ON THE WIRE** — lowercase per the same law: `vanished` `user`.
///
/// TWO arms where [`RetireOrigin`] has three, and the missing one is deliberate.
/// [`Other`](RetireOrigin::Other) is a DEPLOYMENT's own reason, carried so a durable row can say why
/// rather than *some other reason* — and a wire enum is a closed vocabulary a client picks from, so
/// there is no word for it to pick. A client asking to retire a key is a person, which is
/// [`User`](RetireOrigin::User); the open arm reaches the registry from the deployment's own code
/// and from the rows a boot reads back.
///
/// The crossing is therefore ONE-WAY, and that is what the single [`From`] below says: every wire
/// origin is a framework origin, and not every framework origin is a wire one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Enum)]
#[graphql(rename_items = "lowercase")]
pub enum RegistryOrigin {
  /// The content went away on its own — see [`RetireOrigin::Vanished`].
  Vanished,
  /// A person stood it down — see [`RetireOrigin::User`].
  User,
}

impl From<RegistryOrigin> for RetireOrigin {
  fn from(origin: RegistryOrigin) -> Self {
    match origin {
      RegistryOrigin::Vanished => Self::Vanished,
      RegistryOrigin::User => Self::User,
    }
  }
}

/// **HOW MANY KEYS ONE FAMILY HOLDS**, broken down the way the brief's own shape asks:
/// `{ idle analyzing retiring retired }`.
///
/// `idle` is always `0` and can be nothing else — an idle key is the absence of an entry, on
/// [`RootState`]'s own reasoning, so there is no table this count could read one out of. It is
/// carried on the wire for symmetry with [`RegistryState`]'s own vocabulary rather than as a fact
/// anything here could answer differently.
///
/// The Rust name carries `View` because [`crate::RegistryCounts`] already names the framework's own
/// tally this projects from; the SDL name does not need the same caution, so it publishes as
/// `RegistryCounts`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, SimpleObject)]
#[graphql(name = "RegistryCounts")]
pub struct RegistryCountsView {
  /// Always `0` — see the type note.
  pub idle: u32,
  /// Keys [`Analyzing`](RootState::Analyzing).
  pub analyzing: u32,
  /// Keys [`Retiring`](RootState::Retiring).
  pub retiring: u32,
  /// Keys [`Retired`](RootState::Retired).
  pub retired: u32,
}

impl From<FamilyCounts> for RegistryCountsView {
  fn from(counts: FamilyCounts) -> Self {
    Self {
      idle: 0,
      analyzing: wire_count(counts.analyzing),
      retiring: wire_count(counts.retiring),
      retired: wire_count(counts.retired),
    }
  }
}

/// **ONE KEY, AS `recent` HANDS IT OUT**: its own text and where it stands.
#[derive(Debug, Clone, PartialEq, Eq, SimpleObject)]
pub struct RegistryEntry {
  /// The key's own wire spelling — [`core::fmt::Display`]'s, the same text a client would send back
  /// through `state(key:)` or `retire(key:)`.
  pub key: String,
  /// Where it stands.
  pub state: RegistryState,
}

/// **A FAMILY'S FIVE KNOBS, ON THE WIRE**: what `registryKnobs` hands back — the resolved value
/// after the fold, with no override table left to carry, exactly as
/// [`RegistryOptions::for_family`] hands one to a typed caller.
#[derive(Debug, Clone, PartialEq, Eq, SimpleObject)]
pub struct RegistryOptionsView {
  /// [`RegistryOptions::debounce`], as humantime text.
  pub debounce: String,
  /// [`RegistryOptions::batch_max_items`].
  pub batch_max_items: u32,
  /// [`RegistryOptions::batch_max_wait`], as humantime text.
  pub batch_max_wait: String,
  /// [`RegistryOptions::retire_drain`], as humantime text.
  pub retire_drain: String,
  /// [`RegistryOptions::settle`], as humantime text.
  pub settle: String,
}

impl From<RegistryOptions> for RegistryOptionsView {
  fn from(options: RegistryOptions) -> Self {
    Self {
      debounce: format_duration(options.debounce()),
      batch_max_items: wire_count(options.batch_max_items().get()),
      batch_max_wait: format_duration(options.batch_max_wait()),
      retire_drain: format_duration(options.retire_drain()),
      settle: format_duration(options.settle()),
    }
  }
}

/// **ONE FAMILY'S FACE**: what `registry(family:)` hands back, every field answered through
/// [`crate::drive::DynRegistry`] where the family has been [`expose`](Registries::expose)d, and the
/// honest nothing everywhere it has not — see the module note.
pub struct RegistryFamily {
  dyn_registry: Option<Arc<dyn DynRegistry>>,
}

#[Object]
impl RegistryFamily {
  /// Where `key` stands — [`idle`](RegistryState::Idle) for a key nothing is true of, AND for one
  /// this family's own root type cannot even parse, AND for a family nothing has exposed. All three
  /// are the same honest fact: nothing here is holding anything for it.
  async fn state(&self, key: String) -> RegistryState {
    self
      .dyn_registry
      .as_ref()
      .map_or(RootState::Idle, |registry| registry.state(&key))
      .into()
  }

  /// How much work is out for `key` — [`RootState::inflight`], read off the same state
  /// [`state`](Self::state) answers, so the two never disagree.
  async fn inflight(&self, key: String) -> u32 {
    self
      .dyn_registry
      .as_ref()
      .map_or(0, |registry| registry.state(&key).inflight())
  }

  /// This family's own tally.
  async fn counts(&self) -> RegistryCountsView {
    self
      .dyn_registry
      .as_ref()
      .map(|registry| registry.counts())
      .unwrap_or_default()
      .into()
  }

  /// Up to `n` keys this family is holding something for (default 20; a negative `n` asks for
  /// none) — see [`crate::drive::DynRegistry::recent`]'s own note on the order.
  async fn recent(&self, n: Option<i32>) -> Vec<RegistryEntry> {
    self
      .dyn_registry
      .as_ref()
      .map(|registry| registry.recent(recent_limit(n)))
      .unwrap_or_default()
      .into_iter()
      .map(|(key, state)| RegistryEntry {
        key: key.to_string(),
        state: state.into(),
      })
      .collect()
  }
}

/// **THE MOUNTABLE QUERY MEMBER**: one field, `registry(family:)`, folded into `<Root>Query`
/// beside a graph's own members by `ingraph-codegen`'s `graph::query` — or built into a schema
/// directly, exactly as [`SqlDoor`](crate::graphql::SqlDoor) is.
///
/// `Default` because [`async_graphql::MergedObject`] asks every member for one; the type carries no
/// state of its own; the schema's [`Context`] is where [`Arc<Registries>`] lives.
#[derive(Debug, Clone, Copy, Default)]
pub struct RegistryQueryRoot;

#[Object]
impl RegistryQueryRoot {
  // `cfg_attr(doc, doc = "…")` rather than a plain `///`, and for `OrderDirection`'s own reason
  // (`graphql/direction.rs`'s module note) rather than a general rule: THIS field, alone among
  // every one this module publishes, joins a `type Query` a GRAPH'S OWN emission also writes into —
  // `ingraph-codegen`'s `graph::query` folds it in beside a graph's own members, and every one of
  // those carries NO description by that emission's own ruling (`query.rs`: "no doc attribute, and
  // that is the emitted faces' rule reaching the root"). A description on this one field would be
  // the one root member that stands out for no reason a client could read off the schema, so it
  // matches its neighbours instead — reachable through `cargo doc`, absent from the SDL. Every
  // OTHER field in this file keeps its plain `///`, on `Point2`'s own precedent one primitive over:
  // those live in objects nothing else ever folds a member into, so a description there is only
  // ever read as what it is.
  //
  #[cfg_attr(
    doc,
    doc = "The registry face for `family` — the lowercase spelling of a root type, `media` for \
           `MediaId`."
  )]
  #[cfg_attr(doc, doc = "")]
  #[cfg_attr(
    doc,
    doc = "Total: an unrecognised family answers a live object whose fields all read the honest"
  )]
  #[cfg_attr(doc, doc = "nothing rather than a refusal — see the module note.")]
  async fn registry(&self, ctx: &Context<'_>, family: String) -> Result<RegistryFamily> {
    let registries = ctx.data::<Arc<Registries>>()?;
    Ok(RegistryFamily {
      dyn_registry: registries.dyn_for(&family),
    })
  }
}

/// **THE MUTATION ROOT**: `registryKnobs`, `retire`, `restore`, `reanalyze` — four flat fields, each
/// naming its own `family`. See the module note for why they do not nest the way the query side
/// does.
///
/// An application with no mutation of its own beyond this mounts it directly:
/// `Schema::build(<Root>Query::default(), RegistryMutationRoot::default(), EmptySubscription)`.
/// Nothing here folds it into a wider mutation root, because nothing else in this framework emits
/// one yet — see the module note.
///
/// Named `Mutation` on the wire — unlike [`RegistryQueryRoot`], which is always reached through a
/// `MergedObject` fold that discards a member's own SDL name, this type IS the mutation root in
/// every schema it serves today, so it takes the GraphQL convention's own name directly (via
/// `#[Object(name = "Mutation")]` on its own impl below) rather than publishing its Rust one.
#[derive(Debug, Clone, Copy, Default)]
pub struct RegistryMutationRoot;

impl RegistryMutationRoot {
  /// The one lookup every door here starts with: `family`, exposed, or the refusal a mutation gives
  /// where a query would answer the honest nothing instead — see the module note.
  fn dyn_for(ctx: &Context<'_>, family: &str) -> Result<Arc<dyn DynRegistry>> {
    let registries = ctx.data::<Arc<Registries>>()?;
    registries.dyn_for(family).ok_or_else(|| {
      Error::new(format!(
        "no family named {family:?} has been exposed to the registry face"
      ))
    })
  }
}

#[Object(name = "Mutation")]
impl RegistryMutationRoot {
  /// **TURN `family`'s LIVE DIAL**: fold whichever of the five knobs `debounce`, `batchMaxItems`,
  /// `batchMaxWait`, `retireDrain`, `settle` were named onto this family's own resolved options, and
  /// hand back the result — the options layer's REQUEST tier, the highest of its three; see
  /// [`RegistryOptions`]'s own module note.
  ///
  /// A knob left unnamed is UNCHANGED — this is a fold onto the value the family is already running,
  /// never a reset to the shipped defaults.
  #[expect(
    clippy::too_many_arguments,
    reason = "one argument per knob, and there are five of them"
  )]
  async fn registry_knobs(
    &self,
    ctx: &Context<'_>,
    family: String,
    debounce: Option<String>,
    batch_max_items: Option<u32>,
    batch_max_wait: Option<String>,
    retire_drain: Option<String>,
    settle: Option<String>,
  ) -> Result<RegistryOptionsView> {
    let registry = Self::dyn_for(ctx, &family)?;
    let mut over = RegistryOverride::new();
    if let Some(text) = debounce {
      over.set_debounce(Some(parse_duration("debounce", &text)?));
    }
    if let Some(items) = batch_max_items {
      let items = core::num::NonZeroUsize::new(items as usize)
        .ok_or_else(|| Error::new("batchMaxItems: must not be 0"))?;
      over.set_batch_max_items(Some(items));
    }
    if let Some(text) = batch_max_wait {
      over.set_batch_max_wait(Some(parse_duration("batchMaxWait", &text)?));
    }
    if let Some(text) = retire_drain {
      over.set_retire_drain(Some(parse_duration("retireDrain", &text)?));
    }
    if let Some(text) = settle {
      over.set_settle(Some(parse_duration("settle", &text)?));
    }
    registry.apply_knobs(&over);
    Ok(registry.options().into())
  }

  /// **RETIRE `key`** in `family`, on `origin`'s say-so — [`crate::drive::DynRegistry::retire`],
  /// through the family's own serialized per-key queue. Answers the state `key` landed in, which is
  /// [`Retiring`](RegistryState::Retiring) where work was out and [`Retired`](RegistryState::Retired)
  /// where none was.
  async fn retire(
    &self,
    ctx: &Context<'_>,
    family: String,
    key: String,
    origin: RegistryOrigin,
  ) -> Result<RegistryState> {
    let registry = Self::dyn_for(ctx, &family)?;
    registry
      .retire(&key, origin.into())
      .map(RegistryState::from)
      .map_err(|_| {
        Error::new(format!(
          "key {key:?} is not a valid id for family {family:?}"
        ))
      })
  }

  /// **BRING `key` BACK** in `family` — [`crate::drive::DynRegistry::restore`]. Answers the state it
  /// landed in, ordinarily [`Restoring`](RegistryState::Restoring).
  async fn restore(&self, ctx: &Context<'_>, family: String, key: String) -> Result<RegistryState> {
    let registry = Self::dyn_for(ctx, &family)?;
    registry
      .restore(&key)
      .map(RegistryState::from)
      .map_err(|_| {
        Error::new(format!(
          "key {key:?} is not a valid id for family {family:?}"
        ))
      })
  }

  /// **A PERSON'S OWN INTAKE** for `key` in `family` — the same transition a debounced burst earns,
  /// asked for by hand rather than waited for; see
  /// [`crate::drive::DynRegistry::reanalyze`].
  async fn reanalyze(
    &self,
    ctx: &Context<'_>,
    family: String,
    key: String,
  ) -> Result<RegistryState> {
    let registry = Self::dyn_for(ctx, &family)?;
    registry
      .reanalyze(&key)
      .map(RegistryState::from)
      .map_err(|_| {
        Error::new(format!(
          "key {key:?} is not a valid id for family {family:?}"
        ))
      })
  }
}