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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! **LAYER TWO** — the initialization walk: after the resources are built and their stores opened,
//! every declaration's HOME in every target it points at is MADE, and only then does the graph
//! serve.
//!
//! ```text
//! layer one   AsyncResource::build ─► Store::open                      the mounts exist
//!                     │
//! layer two   per declaration × per target it points at:
//!                     │   Initialize::initializer(mount) ─► the AUTHOR'S factory visitor
//!                     │   visitor.next_type::<Declaration>()          ─► its blueprint, made
//!                     ▼
//! the barrier  every walk finished ─► nodes built ─► wired ─► ignited ─► SERVING
//! ```
//!
//! # THE COMPLETENESS LAW
//!
//! One node's fields may need initializing on BOTH sides at once — a `title` elected into a
//! synchronous tantivy mount, an `embedding` into a remote vector store that answers with a future,
//! a `persist` into a SQL database. So the walk is driven per (declaration × target), each target on
//! ITS OWN FACE, and the union of those steps is what covers a mixed node completely. No step is
//! skipped for being on the other side, and the whole set finishes before anything is wired — a
//! launch that served first would have a request reach a corpus that does not exist yet.
//!
//! A refusal anywhere in it is a REFUSED LAUNCH ([`LaunchError::Initializing`]), raised inside the
//! create walk's own fallible phase so that everything already built says its goodbyes on the way
//! out — the pre-ignition unwind, unchanged.
//!
//! # MOUNTED IS VISITED, and it is UNCONDITIONAL
//!
//! A target a declaration POINTS AT is a target this deployment mounts, and every mount is built at
//! launch and shown its declarations — a write mount and a read-only one alike. The distinction the
//! walk used to draw between them is retired, because it was never a distinction the deployment
//! could keep: what makes a mount a WRITE mount is a node that lands into it, and what makes one a
//! WIRE mount is a resolver holding a [`Shared<R>`](crate::Shared) that the graph cannot see at all.
//! A search door is exactly as much of a holder as a landing node is, so a launch that built only
//! what the graph could see left the read path opening a corpus that was never made.
//!
//! [`Habitats::TARGETS`] is how the fact travels: a declaration names its targets in a `const`, an
//! emitted launch states them on the [`Plan`](super::Plan) before the validate walk, and they join
//! the enabled nodes' own demands in the one set the create walk builds from. Which leaves exactly
//! ONE laziness, and it is the honest one — a resource NOTHING points at and NO enabled node
//! demands is neither built nor walked, so a catalog's unused models stay unloaded.
//!
//! The read-only half of that is not a formality, and [`Initialize`] says what an honest body for it
//! does: open the table, keep the handle, verify the schema is the one this deployment was compiled
//! against.
//!
//! # WHO knows what, and why the steps are per DECLARATION rather than per resource
//!
//! Which targets a declaration's legs point at is written in the DECLARATION — `lexical(resource =
//! "crate::Ft")` — and a graph root cannot see it: the root holds a list of member types and a list
//! of resource types, and the PAIRING between them is a fact of neither list. A root-side loop over
//! `resources × members` would therefore demand that every mounted target be a habitat for every
//! member, which is false of every mixed deployment there is — a full-text mount is no home for a
//! vector declaration.
//!
//! So the step is emitted where the pairing is known, on the declaration, through [`Habitats`]; and
//! the ROOT drives one call per fused member. **One visitor per target even so** — the walk's own
//! shape — because [`Creation`](super::Creation) keeps the visitors it builds and hands each
//! declaration the one that target already had. A slot maker therefore sees every declaration that
//! lives in its mount, in member order, exactly as a walk over one list would have shown it.
//!
//! # And the corpora that named NO target
//!
//! [`Habitats::UNBOUND`] is the other half of the same list: a leg that wrote no `resource = "…"`
//! has no type for a step to name, and what binds it is the deployment's own catalog — exactly one
//! kind-compatible resource declared and the leg takes it, zero or several and the launch refuses
//! listing the candidates. The root reads this const off each member and states it on the
//! [`Plan`](super::Plan) before the validate walk, which is what makes the sole-default law
//! reachable from an emitted launch rather than only from a hand-wired one.

use core::{any::Any, future::Future};

use smol_bytes::Utf8Bytes;

use super::{Creation, LaunchError, SlotBinding};
use crate::{
  Async, AsyncResource, AsyncTypeVisitor, Block, Describe, Habitat, ResourceDemand, ResourceKind,
  ResourceName, Shared, SlotName, TypeVisitor,
};

/// ONE CORPUS a declaration owns whose leg named NO resource — the row a launch resolves by the
/// SOLE-DEFAULT law.
///
/// [`SlotBinding`](super::SlotBinding)'s `const`-constructible twin. The launch floor's own type
/// holds an owned name because the walk builds one per plan; this one is written INSIDE a
/// declaration's expansion, where every part is `&'static` and the whole list is an item — so a
/// declaration states its unbound corpora once, at compile time, and nothing is assembled per boot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UnboundCorpus {
  slot: &'static SlotName,
  kind: ResourceKind,
}

impl UnboundCorpus {
  /// The corpus `slot`, which needs a resource holding `kind`.
  #[inline]
  #[must_use]
  pub const fn new(slot: &'static SlotName, kind: ResourceKind) -> Self {
    Self { slot, kind }
  }

  /// The corpus, by its durable name.
  #[inline]
  #[must_use]
  pub const fn slot(&self) -> &'static SlotName {
    self.slot
  }

  /// What it needs a resource to hold.
  #[inline]
  #[must_use]
  pub const fn kind(&self) -> ResourceKind {
    self.kind
  }
}

impl From<&UnboundCorpus> for SlotBinding {
  /// The launch floor's own row, minted from the declaration's `const` — `from_static`, the name
  /// under it already being the byte string a store will be given.
  #[inline]
  fn from(corpus: &UnboundCorpus) -> Self {
    Self::new(
      Utf8Bytes::from_static(corpus.slot().as_ref()),
      corpus.kind(),
    )
  }
}

/// **LAYER TWO, on the DECLARATION** — every home this declaration owns, in every target its legs
/// point at, and every corpus of its whose leg pointed at nothing.
///
/// # Who implements it
///
/// `#[ingraph::fulltext(…)]`, `#[ingraph::vector(…)]` and their siblings, from the `resource = "…"`
/// paths their elections wrote. A declaration whose legs all point at nothing implements it with an
/// empty [`make`](Self::make), an empty [`TARGETS`](Self::TARGETS) and a full
/// [`UNBOUND`](Self::UNBOUND); a declaration with no elections at all takes all three defaults and
/// is a no-op on every half.
///
/// # Every member DEFAULTS, and that is what keeps a hand-written declaration whole
///
/// The trait is read by a graph root's emitted launch, once per fused member. A member that has
/// nothing to say about any of the three says nothing, exactly as
/// [`DeclaredResource`](crate::DeclaredResource)'s two seats default — and for the same reason: a
/// seat that must be filled makes every declaration written before it a breaking change.
pub trait Habitats {
  /// Every corpus this declaration owns whose leg named NO resource.
  ///
  /// Empty is the ordinary state: a leg that WROTE `resource = "…"` is bound at the word, and its
  /// kind is verified there. This states the other case, and the launch resolves it against the
  /// deployment's own catalog.
  const UNBOUND: &'static [UnboundCorpus] = &[];

  /// Every TARGET this declaration's legs point at — the mounts a launch owes this declaration,
  /// whether or not any node in the arrangement writes into them.
  ///
  /// # It is the WIRE mount's only voice
  ///
  /// A resource is built for whoever holds a [`Shared<R>`](crate::Shared), and the plan can see one
  /// kind of holder: a node with such a field. The other kind is a search resolver, which is handed
  /// its mount by the application after the launch and is invisible to every list the launch reads.
  /// So a deployment that only READS a corpus had nothing to say — and this is what it says: the
  /// declaration that owns the corpus names the target, once, at compile time.
  ///
  /// An emitted launch turns each row into a demand on the [`Plan`](super::Plan) before the validate
  /// walk, beside the [`UNBOUND`](Self::UNBOUND) rows it states there. The two are the same list
  /// split by one question — a leg that named a target is a row here, and a leg that named none is a
  /// row there — so nothing is in both and nothing is in neither.
  ///
  /// A `fn` pointer rather than the value, for
  /// [`Declared::DEMANDS`](super::Declared::DEMANDS)' reason: [`ResourceDemand::of`] reads the
  /// compiler's own path for the type, which is not a `const` operation.
  const TARGETS: &'static [fn() -> ResourceDemand] = &[];

  /// MAKE every home this declaration owns — one step per target its legs point at, each driven on
  /// that target's own face.
  ///
  /// Defaulted to nothing, so a declaration that elects into no resource costs a launch one
  /// already-resolved future.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Initializing`], naming the resource whose walk refused. The step stops there:
  /// homes are MADE rather than collected, so the ones after a refusal would be built in a world the
  /// failed one did not finish.
  #[inline]
  fn make(creation: &mut Creation<'_>) -> impl Future<Output = Result<(), LaunchError>> {
    let _ = creation;
    core::future::ready(Ok(()))
  }
}

/// **LAYER TWO's BLOCKING FACE, on the RESOURCE** — the factory visitor this mount's homes are made
/// by.
///
/// # It is the AUTHOR'S MACHINE
///
/// A slot maker holds its own connection and its own per-slot values, so the framework builds
/// nothing here: it asks the resource for one and shows it types. `#[ingraph::resource(<word>)]`
/// names the shipped machine for a builtin engine — [`TantivySlotMaker`](crate::TantivySlotMaker) —
/// and a foreign resource's author names theirs, which is the same open seam the mount faces are on.
///
/// # The DB is the RESOURCE and not the engine
///
/// [`Visitor`](Self::Visitor) is pinned to `TypeVisitor<Db = Self>`, so a maker built for one mount
/// is shown only the declarations that describe themselves in THAT mount. Two deployments' tantivy
/// stores are two resource types and therefore two habitats, which is what keeps a second mount
/// addressable at all.
///
/// # THE THREE HONEST BODIES
///
/// Every mounted target implements this, and the walk shows every one of them its declarations —
/// there is no word, no marker and no seat that opts a resource out. What differs between targets is
/// what the machine DOES when it is shown one, and in practice it is one of three things:
///
/// | body | the target it is honest for |
/// |---|---|
/// | **noop** — [`MakesNothing`] | the store creates its own homes on first use: an index directory that appears at the first write, a collection a driver opens on demand, a bucket the object store mints when something lands in it |
/// | **open-or-create** | the walk makes what is not there and reopens what is — the shipped [`TantivySlotMaker`](crate::TantivySlotMaker), whose `Index::open_or_create` is idempotent by construction |
/// | **read-side open and verify** | a mount this deployment only READS: open the table, keep the handle warm, and check that the schema in front of it is the one these declarations were compiled against |
///
/// The third row is the one a read-only deployment is owed. *Nothing is written here* is not the same
/// sentence as *nothing is to be done here*: a replica still has a table to open, a handle to keep
/// and a schema that can have drifted, and the launch is the only moment at which finding that out is
/// still cheap. A target whose credentials are read-only is the author's own branch inside the body —
/// open where the deployment reads, create where it writes — and not a question the framework asks.
///
/// # Forgetting it is `E0277`, which is harder teeth than a marker
///
/// The seat is mandatory: a resource a declaration points at and that implements neither this nor
/// [`AsyncInitialize`] does not compile, at the launch, naming the trait it lacks. A marker meaning
/// *this one needs nothing* would have had the opposite property — silence would be the default and a
/// forgotten one would be indistinguishable from a deliberate one — so the noop is a BODY that
/// somebody wrote, and the compiler is what makes sure somebody did.
pub trait Initialize: Habitat + AsyncResource + Sized {
  /// The machine that makes this mount's homes.
  ///
  /// `'static` because the launch KEEPS it: one visitor per target, shown every declaration that
  /// lives there, held in the create walk's own bag between steps.
  type Visitor: TypeVisitor<Db = Self> + Send + Sync + 'static;

  /// Build one, over the mount this launch opened.
  ///
  /// `Shared<Self>` rather than a borrow, because the visitor outlives the call that made it: it is
  /// handed the next declaration in the same walk. The handle is an `Arc` clone and costs nothing.
  fn initializer(mount: Shared<Self>) -> Self::Visitor;
}

/// **LAYER TWO's AWAITED FACE** — [`Initialize`]'s twin, for a mount whose creates answer with a
/// future.
///
/// The dual-mode law at this grain: a resource implements one of the two, or BOTH where its machine
/// genuinely has two faces, and nothing bridges them by blanket. Which one a launch drives is the
/// resource's own `#[ingraph::resource(async)]` word, read back through
/// [`DeclaredResource::SYNC`](crate::DeclaredResource::SYNC) at the emission that spells the call.
pub trait AsyncInitialize: Habitat + AsyncResource + Sized {
  /// The machine that makes this mount's homes, awaited.
  type Visitor: AsyncTypeVisitor<Db = Self> + Send + Sync + 'static;

  /// Build one, over the mount this launch opened.
  fn initializer(mount: Shared<Self>) -> Self::Visitor;
}

/// **THE NOOP BODY** — the machine a target names when it has nothing to make.
///
/// # It is a BODY and not a marker
///
/// Naming it does not take this mount out of the walk. Layer two visits every mounted target
/// unconditionally, and a mount whose machine is this one is shown every declaration that lives in
/// it exactly as any other is — it simply answers each of them by doing nothing. There is no seat
/// anywhere that means *skip me*, and this is not one wearing a different hat.
///
/// # What it is honest for
///
/// A store that creates its own homes on first use: an index directory that appears at the first
/// write, a collection a driver opens on demand, a bucket the object store mints when something
/// lands in it. For such a target *nothing to make ahead of time* is a real answer rather than a
/// gap, and this is that answer in one line instead of a hand-written visitor whose body is `Ok(())`.
///
/// It is the FIRST of [`Initialize`]'s three honest bodies and the one to reach for LAST: a mount
/// this deployment only reads still has a table to open and a schema to check, and a noop there is
/// silence rather than honesty. What the order of layer two buys even here is the moment: the walk
/// runs before the first construction, so a target that later grows an eager step gains it without
/// any caller changing shape.
///
/// # It wears BOTH faces, and that is not the blanket the pair refuses
///
/// One type, two impls, the SAME `Db` — so a resource of either mode names it and neither face is
/// invented for the other. The blanket the visitor pair refuses is over every `V`, which would
/// collide with a machine that wears the two faces for two DIFFERENT targets; a concrete type
/// stating both is exactly what that freedom is for.
///
/// # Examples
///
/// ```
/// use ingraph::{Resources, Habitat, Initialize, MakesNothing, Shared, SlotSpec};
/// # use ingraph::AsyncResource;
///
/// pub struct Qdrant;
/// # impl AsyncResource for Qdrant {
/// #   type Options = ();
/// #   type Error = core::convert::Infallible;
/// #   async fn build(_ctx: &Resources, _: ()) -> Result<Self, Self::Error> { Ok(Self) }
/// # }
///
/// impl Habitat for Qdrant {
///   type Blueprint = &'static [SlotSpec];
/// }
///
/// impl Initialize for Qdrant {
///   type Visitor = MakesNothing<Self>;
///
///   fn initializer(_mount: Shared<Self>) -> Self::Visitor {
///     MakesNothing::new()
///   }
/// }
/// ```
pub struct MakesNothing<R> {
  target: core::marker::PhantomData<fn() -> R>,
}

impl<R> MakesNothing<R> {
  /// The machine.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      target: core::marker::PhantomData,
    }
  }
}

impl<R> Default for MakesNothing<R> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

impl<R> core::fmt::Debug for MakesNothing<R> {
  /// Written rather than derived, so the target needs no `Debug` of its own — the same trade every
  /// `PhantomData`-carrying type in this crate makes.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str("MakesNothing")
  }
}

impl<R> Clone for MakesNothing<R> {
  /// `*self` and not `Self::new()`, which is the CANONICAL body for a `Copy` type: the two are the
  /// same bytes here, and the canonical one is what keeps `clone` and the implicit copy from being
  /// two roads that could ever disagree.
  #[inline]
  fn clone(&self) -> Self {
    *self
  }
}

impl<R> Copy for MakesNothing<R> {}

impl<R: Habitat> TypeVisitor for MakesNothing<R> {
  type Db = R;
  /// It cannot fail, and the type says so rather than a `Result` a caller has to read.
  type Error = core::convert::Infallible;

  #[inline]
  fn next_type<E: Describe<R>>(&mut self) -> Result<(), Self::Error> {
    Ok(())
  }
}

impl<R: Habitat> AsyncTypeVisitor for MakesNothing<R> {
  type Db = R;
  type Error = core::convert::Infallible;

  #[inline]
  fn next_type<E: Describe<R>>(&mut self) -> impl Future<Output = Result<(), Self::Error>> {
    core::future::ready(Ok(()))
  }
}

/// **THE MODE-DISPATCHED DRIVER** — what an emitted launch names once per (declaration × target),
/// whichever face that target wears.
///
/// # `M` is the resource's MODE, as a type
///
/// `Selected<{ <R as DeclaredResource>::SYNC }>` — [`Block`] or [`Async`], the same crossing every
/// other mode-selecting emission in this crate makes. The call is spelled at a CONCRETE resource, so
/// the const is nameable there; nothing generic ever has to evaluate it.
///
/// # Two impls, and a resource may take both
///
/// One per mode, so they cannot overlap, and each closes over the face its mode names. A resource
/// implementing [`Initialize`] AND [`AsyncInitialize`] gets both rows and stays addressable on
/// either — the two-face freedom, at the resource's grain.
///
/// # Nothing implements this by hand
///
/// It is the framework's bridge between the two author faces and one call shape. What an author
/// writes is [`Initialize`] or [`AsyncInitialize`], one associated type and one line.
pub trait Initializes<M>: Habitat + Sized {
  /// The machine, whichever face this mode names.
  type Visitor: Send + Sync + 'static;

  /// Its refusal — the visitor's own error, in the visitor's own currency.
  type Error;

  /// Build one over `mount`.
  fn initializer(mount: Shared<Self>) -> Self::Visitor
  where
    Self: AsyncResource;

  /// SHOW the visitor one declaration, and make what it describes.
  ///
  /// Awaited on both faces: the blocking one answers a `Result` already computed, with
  /// [`ready`](core::future::ready) around it, which is the one direction the dual-mode law admits.
  /// The reverse — a `block_on` around an awaited create — is the fiction it refuses, and no row
  /// here writes one.
  fn show<T: Describe<Self>>(
    visitor: &mut Self::Visitor,
  ) -> impl Future<Output = Result<(), Self::Error>>;
}

impl<R: Initialize> Initializes<Block> for R {
  type Visitor = <R as Initialize>::Visitor;
  type Error = <<R as Initialize>::Visitor as TypeVisitor>::Error;

  #[inline]
  fn initializer(mount: Shared<Self>) -> Self::Visitor {
    <R as Initialize>::initializer(mount)
  }

  #[inline]
  fn show<T: Describe<Self>>(
    visitor: &mut Self::Visitor,
  ) -> impl Future<Output = Result<(), Self::Error>> {
    core::future::ready(TypeVisitor::next_type::<T>(visitor))
  }
}

impl<R: AsyncInitialize> Initializes<Async> for R {
  type Visitor = <R as AsyncInitialize>::Visitor;
  type Error = <<R as AsyncInitialize>::Visitor as AsyncTypeVisitor>::Error;

  #[inline]
  fn initializer(mount: Shared<Self>) -> Self::Visitor {
    <R as AsyncInitialize>::initializer(mount)
  }

  #[inline]
  fn show<T: Describe<Self>>(
    visitor: &mut Self::Visitor,
  ) -> impl Future<Output = Result<(), Self::Error>> {
    AsyncTypeVisitor::next_type::<T>(visitor)
  }
}

/// **A TARGET A DECLARATION POINTS AT THAT THIS DEPLOYMENT NEVER BUILT** — layer two's own refusal,
/// and the sentence that replaced a silent skip.
///
/// # The two deployments that reach it
///
/// A root that MOUNTS the target reaches it only through the application's own hand: a
/// `#[ingraph(resource(factory))]` field's options are `prepare`'s to hand over, and a `prepare` that
/// did not build this one leaves the walk with nothing to make homes in. Everything else the root
/// declares is built by the launch itself, from the demand the declaration's own
/// [`TARGETS`](Habitats::TARGETS) row states.
///
/// A root that does NOT mount it reaches it by having a member whose leg points somewhere the
/// deployment never declared — the resource axis' own gap, which nothing before the launch can catch:
/// the leg names a TYPE and the catalog is a list of FIELDS, and the two only meet here.
///
/// Either way the fix is a declaration or a call, which is why the sentence names both.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
#[display(
  "this deployment never built it — a declaration's leg points at it, so the launch owes it a \
   mount: declare it as a `#[ingraph(resource)]` field of the graph root, or build it in the \
   `prepare` closure where its declaration wrote `factory`"
)]
pub struct UnbuiltTargetError {
  target: &'static ResourceName,
}

impl UnbuiltTargetError {
  /// The refusal a pointed but unbuilt `R` earns.
  #[inline]
  #[must_use]
  fn of<R: AsyncResource>() -> Self {
    Self {
      target: ResourceName::of::<R>(),
    }
  }

  /// The target that was never built.
  #[inline]
  #[must_use]
  pub const fn target(&self) -> &'static ResourceName {
    self.target
  }
}

impl core::error::Error for UnbuiltTargetError {}

/// The VISITOR BAG the create walk keeps between layer-two steps — one machine per target, keyed by
/// the machine's own type.
///
/// Keyed by the VISITOR and not by the resource, and the difference is the two-face freedom: a
/// resource wearing both faces has two machines, and one key per resource would hand a blocking step
/// the awaited one and fail the downcast. A visitor names its own `Db`, so its type is already the
/// finer key.
#[derive(Default)]
pub(super) struct Makers {
  built: std::collections::HashMap<core::any::TypeId, Box<dyn Any + Send + Sync>>,
}

impl Makers {
  /// The machine for `V`, built by `make` on first ask and handed back as itself thereafter.
  pub(super) fn entry<V: Send + Sync + 'static>(&mut self, make: impl FnOnce() -> V) -> &mut V {
    self
      .built
      .entry(core::any::TypeId::of::<V>())
      .or_insert_with(|| Box::new(make()))
      .downcast_mut::<V>()
      // The map is keyed by `TypeId::of::<V>()` and written only here, so the value under a key IS
      // a `V`. A `downcast_mut` that could answer otherwise would mean the key and the value were
      // written by two different parties, which the private field is what prevents.
      .expect("a machine is stored under its own type")
  }
}

impl core::fmt::Debug for Makers {
  /// How many machines, and never what they hold: a slot maker is the AUTHOR's type, so deriving
  /// here would put a `Debug` bound on every one of them for the benefit of this line.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Makers")
      .field("built", &self.built.len())
      .finish()
  }
}

impl Creation<'_> {
  /// **ONE LAYER-TWO STEP**: make every home `T` owns in the target `R`.
  ///
  /// The whole of what an emitted [`Habitats::make`] body is, one line per pointed target. `M` is
  /// `R`'s own mode, lifted from its declaration through [`Selected`](crate::Selected) at the
  /// concrete call.
  ///
  /// # A POINTED TARGET IS ALWAYS WALKED
  ///
  /// This step is spelled for a target a declaration POINTS AT, and pointing at one is what makes
  /// this deployment mount it — so by the time the walk reaches here the mount exists, put there by
  /// the resource step from the demand [`Habitats::TARGETS`] stated on the plan. There is no
  /// arm for *nobody asked for this one*: the deployment asked by naming it.
  ///
  /// What used to be here was that arm, and it was the wrong shape twice over. A read-only mount got
  /// no corpora made, because no node in the graph wrote into it — and the first search then opened
  /// an index that did not exist instead of refusing. And an unbuilt mount was reported as a
  /// SUCCESS, which is the one thing a launch may not say about work it did not do.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Initializing`], naming `R`: where the visitor refused, or where the target this
  /// declaration points at was never built at all — see [`UnbuiltTargetError`] for the two
  /// deployments that reach it.
  pub async fn habitat<R, M, T>(&mut self) -> Result<(), LaunchError>
  where
    R: AsyncResource + Initializes<M> + 'static,
    <R as Initializes<M>>::Error: core::error::Error + Send + Sync + 'static,
    T: Describe<R>,
  {
    let Some(mount) = self.built::<R>() else {
      return Err(LaunchError::initializing::<R, _>(
        UnbuiltTargetError::of::<R>(),
      ));
    };
    let visitor = self
      .makers()
      .entry::<<R as Initializes<M>>::Visitor>(|| <R as Initializes<M>>::initializer(mount));
    <R as Initializes<M>>::show::<T>(visitor)
      .await
      .map_err(LaunchError::initializing::<R, _>)
  }
}

#[cfg(test)]
mod tests;