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
//! THE TOWER DOOR: where an emitted search resolver finds the assembled question road its bound
//! tower walks, and the knobs a launch named for it.
//!
//! ```text
//! Schema::build(root, …)
//!   .data(Shared::<Lance>::new(lance))                       // WHERE the members are read
//!   │
//!   TowerDoor::<ClipText>::installed(|| ClipText { … })?      // THE ROAD one question walks
//!     .with_step_options(ClipTextStepOptions::new()…)         // …and the knobs it runs under
//!     .with_budget(WalkBudget::new(clock, budget))            // …and how long it may take
//!     .install(builder)
//!         │
//!         ▼
//! installed_road::<ClipText>(ctx, "shotsClipSearchKeys")
//!     →  (ClipText, Option<&ClipTextStepOptions>, Option<&WalkBudget>)
//!     →  walk_within(seat, asked, tower, ClipText::run(&mut steps, q, opts, asked)).await
//! ```
//!
//! # WHY THIS CITIZEN EXISTS AT ALL: the walk's arity does not cross the expansion wall
//!
//! A tower's `walk` is an inherent fn taking ONE `&mut` PER STEP, and a search recipe's expansion has
//! never seen the steps — so the call a resolver would have to write was not spellable, and until
//! this door landed no resolver wrote one. Two things close that: the uniform
//! [`AssembledTower::run`](crate::AssembledTower::run), whose arity is fixed, and this citizen, which
//! is where the VALUE that run is handed comes from.
//!
//! # IT HOLDS A MINT, and that is the per-read minting pin being spent
//!
//! `Serves::serve` takes `&mut self` and [`Context::data`](async_graphql::Context::data) lends `&T`,
//! so a shared citizen cannot answer a walk. [`search_slot`](super::search_slot) meets the same wall
//! and answers it the same way — *mint per read* — and the towers chapter recorded the pin in as
//! many words: a step that needs exclusivity is minted per read rather than shared across concurrent
//! reads.
//!
//! So what a deployment installs is not the steps but the FUNCTION THAT BUILDS THEM, and every read
//! gets its own exclusive value with no lock and no guard held across an `await`. The trade is
//! deliberate and it is the open one: whether a step is a fresh allocation or a cheap handle cloned
//! out of an [`Arc`] is the DEPLOYMENT's to decide inside its own closure, where it knows what its
//! steps hold. A framework that demanded `Clone` of the whole steps struct would have decided it for
//! every tower, and a tower holding one exclusive resource could not have joined at all.
//!
//! # THE GATE RUNS AT INSTALL, which is what makes it a boot refusal
//!
//! [`TowerDoor::installed`] mints once and reads the result against the declaration through
//! [`AssembledTower::check`](crate::AssembledTower::check). A declared word whose seat is empty
//! refuses THERE — at the line a deployment wrote, before a schema is built and before a question is
//! asked. That is [`LaneFan::check`](crate::LaneFan::check)'s own posture and its own reason: the
//! failure it prevents is silent, and a search that quietly answers the unwidened result reads months
//! later as *our search is bad*.
//!
//! The constructor therefore answers a [`Result`] where [`FoldDoor::installed`](super::FoldDoor) —
//! whose shape this citizen otherwise follows verbatim — answers a value. The difference is what each
//! one can be missing: a deployment that installs no fold is content with the election's own, and a
//! deployment whose assembly contradicts its declaration is not content with anything.
//!
//! # ONE DOOR PER TOWER, which is the grain the recipe already names
//!
//! The key is the TOWER TYPE — the very path a recipe's `tower(text(type = "crate::ClipText"))`
//! wrote — so `Context::data` is a `TypeId` lookup and the parameter IS the routing. Two recipes
//! binding one tower share one road; two towers are two doors and no lookup can reach the wrong one.
//!
//! # THE BUDGET SEAT IS BESIDE THE MINT, and the grain is the reason
//!
//! *How long may this walk take* is a fact about ONE TOWER's road, and this is the one act a
//! deployment performs for one tower — so tier two's protective number is named here, exactly where
//! tier two's preference numbers already are. It is deliberately NOT a row of `<Tower>StepOptions`:
//! that object carries one row per STEP and a budget bounds the whole walk, so a row of it would
//! have had to pick a step to belong to. See [`WalkBudget`](crate::WalkBudget) for why the number
//! and the clock that measures it arrive as one value.

use core::{any::type_name, fmt, marker::PhantomData};

use std::sync::Arc;

use crate::retrieve::{AssembledTower, SeatsUnfilled, WalkBudget};

#[cfg(all(test, feature = "async-graphql"))]
mod tests;

/// **THE ASSEMBLED QUESTION ROAD** a schema's bound towers are walked over — one per tower a schema
/// serves, and REQUIRED wherever a recipe bound one.
///
/// # `T` is the TOWER and no value of it is held
///
/// `TowerDoor<ClipText>`. What the door holds is a way to build `<ClipText as SearchTower>::Steps`
/// and the `<ClipText as DeclaredTower>::StepOptions` a launch named — both projections off the
/// tower,
/// which is what lets a deployment spell a name its recipe already wrote rather than a name this
/// module would have had to invent.
pub struct TowerDoor<T: AssembledTower> {
  /// What builds one exclusive road — called once per read, and once more at the gate.
  mint: Arc<dyn Fn() -> T::Steps + Send + Sync>,
  /// TIER TWO — the step-keyed knobs this deployment named once, at launch, or [`None`] where it
  /// named none.
  step_options: Option<T::StepOptions>,
  /// TIER TWO's PROTECTIVE number, and the clock that measures it — [`None`] where this deployment
  /// named none, under which a walk takes as long as it takes.
  budget: Option<WalkBudget>,
  /// The tower this door is branded for, held as the crate's marker spelling: nothing, and every
  /// auto trait left independent of `T` itself.
  tower: PhantomData<fn(&T)>,
}

impl<T> TowerDoor<T>
where
  T: AssembledTower,
{
  /// **INSTALL THE ROAD `mint` BUILDS** — the one act a deployment performs for a tower, and the
  /// gate.
  ///
  /// ```ignore
  /// let door = TowerDoor::<ClipText>::installed(|| ClipText {
  ///   widen: Expansion::new().with_expander(Box::new(Synonyms::from(table))),
  ///   fan: LaneFan::new(CORPUS).with_router(ScriptWeightedFan::new(CORPUS)),
  ///   read: lane.clone(),
  /// })?;
  /// ```
  ///
  /// The closure is called ONCE HERE, and the value it built is what the gate reads: a deployment
  /// whose words and instances disagree is told so at this line rather than at a question.
  ///
  /// # `Fn` rather than `FnOnce`, and the difference is the whole shape
  ///
  /// One road per read means the closure is called again for every question this schema answers, so
  /// it captures what it needs by value and hands out a fresh road each time. A deployment whose
  /// steps are cheap handles writes `move || Road { arm: arm.clone(), … }`; one whose step opens
  /// something writes the open.
  ///
  /// # Errors
  ///
  /// [`SeatsUnfilled`], naming every declared word the assembly left with an empty seat.
  pub fn installed<F>(mint: F) -> Result<Self, SeatsUnfilled>
  where
    F: Fn() -> T::Steps + Send + Sync + 'static,
  {
    T::check(&mint())?;
    Ok(Self {
      mint: Arc::new(mint),
      step_options: None,
      budget: None,
      tower: PhantomData,
    })
  }

  /// **TIER TWO** — the STEP-KEYED knobs every question walking this road runs under, named once at
  /// launch.
  ///
  /// The three-tier law's middle writing: the declaration's own constants stand where this names
  /// nothing, and a request's own numbers compose OVER these where a request can reach them — which
  /// is [`DeclaredTower::SearchOptions`](crate::DeclaredTower::SearchOptions), the other clock, named
  /// per question rather than here. See the law at [`route_depth`](crate::route_depth) for which
  /// knobs may be reached from which tier.
  #[must_use]
  #[inline]
  pub fn with_step_options(mut self, step_options: T::StepOptions) -> Self {
    self.set_step_options(Some(step_options));
    self
  }

  /// [`with_step_options`](Self::with_step_options), in place — INCLUDING back to nothing.
  ///
  /// It takes an [`Option`] where the consuming form takes the value, on
  /// [`Flow::set_limit`](crate::Flow::set_limit)'s law: a holder narrowing a door it was handed needs
  /// *this deployment names nothing* to stay sayable after construction.
  #[inline]
  pub fn set_step_options(&mut self, step_options: Option<T::StepOptions>) -> &mut Self {
    self.step_options = step_options;
    self
  }

  /// The step-keyed knobs this deployment named, or [`None`] where it named none — under which every
  /// step runs at its own floor.
  #[inline]
  #[must_use]
  pub const fn step_options(&self) -> Option<&T::StepOptions> {
    self.step_options.as_ref()
  }

  /// **TIER TWO's PROTECTIVE NUMBER** — how long every question walking this road may take, and the
  /// clock that measures it, named once at launch.
  ///
  /// ```ignore
  /// let door = TowerDoor::<ClipText>::installed(|| ClipText { … })?
  ///   .with_budget(WalkBudget::new(
  ///     TokioClock,
  ///     SearchBudget::new().with_walk(SignedDuration::from_secs(30)),
  ///   ));
  /// ```
  ///
  /// A request may TIGHTEN this and can never raise it — [`tightened_budget`](crate::tightened_budget)
  /// is that arithmetic and [`walk_within`](crate::walk_within) is where it is spent. A door that
  /// names nothing is informed openness rather than a gap: the walk takes as long as it takes, which
  /// is what every road did before this seat existed.
  ///
  /// # A BLOCKING TOWER HAS NO BUDGET SEAT, and this line is where it is told so
  ///
  /// [`DeclaredTower::ALL_SYNC`](crate::DeclaredTower::ALL_SYNC) is a `const`, so a tower whose every
  /// step is served by a blocking face is refused HERE, at compile time, in either direction. Its
  /// [`run`](crate::AssembledTower::run) has no suspension point in it — the walk completes inside
  /// the first poll — so a clock raced against it can never win, and a seat that accepted the number
  /// anyway would be a budget that looks like it binds and does not. That is the one failure this
  /// whole seat exists to foreclose, so it is foreclosed at the line a deployment wrote rather than
  /// discovered at a question. A blocking tower that wants a wall puts one inside its own step, where
  /// there is a thread to interrupt.
  ///
  /// ```compile_fail
  /// use core::{convert::Infallible, future::Future, pin::Pin, time::Duration};
  ///
  /// use ingraph::{
  ///   AssembledTower, DeclaredTower, SearchBudget, SearchTower, TowerDoor, WalkBudget, WalkClock,
  /// };
  ///
  /// struct Blocking;
  ///
  /// impl SearchTower for Blocking {
  ///   type Question = String;
  ///   type Answer = String;
  ///   type Steps = ();
  /// }
  ///
  /// // NO `ALL_SYNC` WORD, so the default stands: every step is served by a blocking face.
  /// impl DeclaredTower for Blocking {
  ///   type StepOptions = ();
  ///   type SearchOptions = ();
  /// }
  ///
  /// impl AssembledTower for Blocking {
  ///   type Refusal = Infallible;
  ///
  ///   async fn run(
  ///     _steps: &mut (),
  ///     question: String,
  ///     _options: Option<&()>,
  ///     _asked: Option<()>,
  ///   ) -> Result<String, Infallible> {
  ///     Ok(question)
  ///   }
  /// }
  ///
  /// struct Spent;
  ///
  /// impl WalkClock for Spent {
  ///   fn elapsed<'a>(&'a self, _budget: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
  ///     Box::pin(core::future::ready(()))
  ///   }
  /// }
  ///
  /// let door = TowerDoor::<Blocking>::installed(|| ())
  ///   .expect("this tower declares nothing that could be missing")
  ///   .with_budget(WalkBudget::new(Spent, SearchBudget::new()));
  /// ```
  #[must_use]
  #[inline]
  pub fn with_budget(mut self, budget: WalkBudget) -> Self {
    self.set_budget(Some(budget));
    self
  }

  /// [`with_budget`](Self::with_budget), in place — INCLUDING back to nothing, and under the same
  /// compile-time refusal for a blocking tower.
  ///
  /// It takes an [`Option`] where the consuming form takes the value, on
  /// [`Flow::set_limit`](crate::Flow::set_limit)'s law: a holder narrowing a door it was handed needs
  /// *this deployment names nothing* to stay sayable after construction.
  #[inline]
  pub fn set_budget(&mut self, budget: Option<WalkBudget>) -> &mut Self {
    const {
      assert!(
        !T::ALL_SYNC,
        "a blocking tower's walk has no suspension point, so a budget on it could never bite — put \
         the wall inside the step that blocks",
      );
    }
    self.budget = budget;
    self
  }

  /// The walk budget this deployment named, or [`None`] where it named none — under which a walk
  /// takes as long as it takes.
  #[inline]
  #[must_use]
  pub const fn budget(&self) -> Option<&WalkBudget> {
    self.budget.as_ref()
  }

  /// **ONE EXCLUSIVE ROAD**, built for one read.
  ///
  /// What [`installed_road`] hands a resolver, and what a hand-written caller takes when it wants
  /// the walk rather than the run.
  #[must_use]
  pub fn mint(&self) -> T::Steps {
    (self.mint)()
  }
}

/// Written out because a closure carries no [`Debug`](core::fmt::Debug). What a reader wants from
/// this line is WHICH tower's road it is and WHETHER a launch named knobs for it — the mint itself
/// has no name to print, which is the erased handle's own honesty one seam over.
impl<T> fmt::Debug for TowerDoor<T>
where
  T: AssembledTower,
{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("TowerDoor")
      .field("tower", &type_name::<T>())
      .field("step_options", &self.step_options.is_some())
      .field("budget", &self.budget)
      .finish()
  }
}

/// The bounds are the CITIZEN's and never the road's, which is the narrowest honest set:
/// [`Context::data`](async_graphql::Context::data) keys on [`Any`](core::any::Any) and lends `&T`, so
/// what has to be `Send + Sync + 'static` is this DOOR — the mint behind its [`Arc`], and the
/// step-keyed options beside it. The STEPS a mint hands out are asked for neither, because they are built inside one
/// read and never shared across two; whether the FUTURE holding them is `Send` is the resolver's own
/// question, answered where that future is built.
#[cfg(feature = "async-graphql")]
impl<T> TowerDoor<T>
where
  T: AssembledTower + 'static,
  T::Steps: 'static,
  T::StepOptions: Send + Sync + 'static,
{
  /// **PUT THIS DOOR ON A SCHEMA BEING BUILT** — [`FoldDoor::install`](super::FoldDoor)'s act, one
  /// layer up.
  ///
  /// ```ignore
  /// let schema = TowerDoor::<ClipText>::installed(|| ClipText { … })?
  ///   .install(Schema::build(MediaQuery::default(), EmptyMutation, EmptySubscription))
  ///   .data(Shared::<Lance>::new(lance))
  ///   .finish();
  /// ```
  ///
  /// A named act rather than a bare `.data(door)`, and the reason is the KEYING: a schema serving
  /// two towers calls this twice and each resolver reaches the road its own recipe named.
  #[must_use]
  pub fn install<Q, M, S>(
    self,
    builder: async_graphql::SchemaBuilder<Q, M, S>,
  ) -> async_graphql::SchemaBuilder<Q, M, S>
  where
    Q: async_graphql::ObjectType + 'static,
    M: async_graphql::ObjectType + 'static,
    S: async_graphql::SubscriptionType + 'static,
  {
    builder.data(self)
  }
}

/// The refusal a resolver reads when the deployment installed no road for the tower its recipe
/// bound.
///
/// A sentence of this seam's own rather than the library's, for
/// [`search_slot`](super::search_slot)'s reason: async-graphql's message would name the citizen type
/// and stop. What a deployment reading this one is told is WHICH FIELD went looking and for WHICH
/// TOWER — and those two are what turn *a citizen is missing* into *this install line is missing*.
#[cfg(feature = "async-graphql")]
fn unassembled<T>(word: &str) -> async_graphql::Error {
  async_graphql::Error::new(format!(
    "`{word}` walks the `{tower}` tower, and no road for it is installed on this schema. A \
     deployment assembles it once and hands it over: \
     `::ingraph::TowerDoor::<{tower}>::installed(|| /* the steps */)?.install(builder)`",
    tower = type_name::<T>(),
  ))
}

/// **THE ONE DEMAND A DRESSED RECIPE MAKES OF A BOUND TOWER'S REQUEST FACE** — that it can be asked
/// for through a schema.
///
/// A recipe that named a GraphQL backend publishes its bound tower's
/// [`SearchOptions`](crate::DeclaredTower::SearchOptions) as an `options` argument, so that type has
/// to cross. This is that crossing named: BLANKET over every `InputType`, so it adds no obligation
/// to anybody and asks for nothing async-graphql does not already answer — what it buys is the
/// SENTENCE. Without it a `()`-faced tower earns async-graphql's own *the trait bound `(): InputType`
/// is not satisfied*, at a span a recipe's author cannot act on and naming a type they never wrote.
///
/// # It lands at the RECIPE and never at the tower
///
/// A tower walked from Rust alone owes this nothing, which is why the demand is not a bound on the
/// [`SearchOptions`](crate::DeclaredTower::SearchOptions) seat itself. The dressing is what needs a
/// wire face, so the dressing is where the refusal fires — spanned at the `type = "…"` word that
/// bound the tower.
#[cfg(feature = "async-graphql")]
#[diagnostic::on_unimplemented(
  message = "`{Self}` cannot be asked for through a schema",
  label = "no request face",
  note = "a DRESSED recipe publishes its bound tower's `DeclaredTower::SearchOptions` as the \
          `options` argument, so that type needs an async-graphql `InputType`. \
          `#[ingraph::tower]` mints one; a hand-written tower names the framework's budget-only \
          citizen — `type SearchOptions = ::ingraph::SearchBudget;`"
)]
pub trait SearchOptionsFace: async_graphql::InputType {}

/// Every `InputType` is one, which is what makes this a SENTENCE rather than a second obligation.
#[cfg(feature = "async-graphql")]
impl<T> SearchOptionsFace for T where T: async_graphql::InputType {}

/// **WHAT ONE LOOKUP HANDS BACK** — the steps minted for this read, the knobs they run under, and
/// the wall they run inside.
///
/// A name rather than the triple spelled at the seat, because the triple is what a reader has to
/// hold: three projections and two lifetimes read as punctuation, and the sentence *this is the road*
/// is what the signature is for. It is a TUPLE and not a struct on the emission's own account — an
/// emitted resolver destructures it in one `let`, and three accessor calls would be three more paths
/// for a macro to spell.
#[cfg(feature = "async-graphql")]
pub type InstalledRoad<'ctx, T> = (
  <T as crate::retrieve::SearchTower>::Steps,
  Option<&'ctx <T as crate::retrieve::DeclaredTower>::StepOptions>,
  Option<&'ctx WalkBudget>,
);

/// **THE ROAD ONE QUESTION WALKS** — an exclusive set of steps minted for this read, beside the
/// knobs the deployment named and the budget it may take.
///
/// # All THREE halves come out of ONE lookup, for [`search_slot`](super::search_slot)'s reason
///
/// The steps, the knobs they run under and the wall they run inside are facts about ONE installed
/// door, and a resolver that took them from three lookups could take them from three doors. So the
/// triple is what this answers, exactly as the search road's own front door answers its handle
/// beside the manager that handle reaches back through.
///
/// # It REFUSES rather than answering [`None`], unlike [`installed_fold`](super::installed_fold)
///
/// A missing fold door is a deployment content with the election's own fold, which is the ordinary
/// case. A missing tower door is a recipe whose question has no producer at all — there is no
/// fallback for this crate to reach for, because what the tower does is the application's and this
/// module has never seen it. So the absence is a mistake and it is named as one.
///
/// # Errors
///
/// Where no [`TowerDoor<T>`] is installed on the schema.
#[cfg(feature = "async-graphql")]
pub fn installed_road<'ctx, T>(
  ctx: &'ctx async_graphql::Context<'_>,
  word: &str,
) -> async_graphql::Result<InstalledRoad<'ctx, T>>
where
  T: AssembledTower + 'static,
  T::Steps: 'static,
  T::StepOptions: Send + Sync + 'static,
{
  let door =
    async_graphql::Context::data_opt::<TowerDoor<T>>(ctx).ok_or_else(|| unassembled::<T>(word))?;
  Ok((door.mint(), door.step_options(), door.budget()))
}