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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! SHAREABLE RESOURCES: the capability a type declares, the citizenship a macro emits, and the
//! handle a unit reaches one through.
//!
//! A model context, an engine client, a tokenizer — the things a unit loads once and several units
//! want. The framework's answer has THREE layers, and each is written by a different party:
//!
//! | layer | written by | what it says |
//! |---|---|---|
//! | [`AsyncResource`] | the resource's AUTHOR, by hand | how to build one, and that it crosses threads |
//! | [`DeclaredResource`] | `#[ingraph::resource]` | this type is a citizen of the walk |
//! | [`ResourceCatalog`] | the graph ROOT's own fields | which resources this deployment has, under which mount, from which SOURCE |
//! | [`Plan::validate`](crate::Plan::validate) | the deployment | every DEMANDED resource was declared |
//!
//! Only the author knows how to load a model, so the contract is hand-implemented; only a
//! declaration can say a type is meant to be shared, so citizenship is a separate act; only the ROOT
//! holds the catalog, its fields being the declared set; and only a plan knows which units are
//! enabled, so the cross-check is a start-up one.
//!
//! # RESOURCES ARE THE ENGINES, and one row of that table moves for a BUILTIN
//!
//! A resource is where a deployment's engines live, so `#[ingraph::resource]` takes an optional
//! BUILTIN KIND WORD — `#[ingraph::resource(tantivy)] pub struct Ft;` — naming one of the
//! framework's own. For those, the first row above is the MACRO's rather than the author's:
//! [`AsyncResource`] is emitted, its [`Options`](AsyncResource::Options) projected off the engine's
//! own store, and the engine's base and faces are emitted delegating to it. Everything else in the
//! table is unchanged, and the word rides its engine's cargo feature.
//!
//! The vocabulary is CLOSED and short, because a kind word is a promise that the macro can write the
//! whole binding — which it can only keep for an engine this crate ships. The open half of the axis
//! is the bare form, which is the table exactly as it reads: hand-written contract, hand-written
//! faces, and no vocabulary to be admitted to.
//!
//! # THE MODE a declaration records
//!
//! An engine's verbs come in pairs, and which half a FOREIGN resource's hand-written impls are is a
//! fact nothing outside its own declaration can see. `#[ingraph::resource(async)]` is what records
//! it, and [`DeclaredResource::SYNC`] is where a binding reads it back — a builtin states it without
//! the author writing anything, the kind carrying that knowledge.
//!
//! # THE GOODBYE is a third opt-in, on the ROOT
//!
//! [`AsyncResource::goodbye`] is defaulted to a drop, so every resource already written keeps the
//! posture it had. What calls it is `#[ingraph(resource(teardown))]` on the field that mounts the
//! resource — the graph root's word, composing with either factory form — and nothing else does. A
//! library resource that knows how to close itself politely therefore does not join a graph's
//! shutdown chain by accident: the deployment that mounts it is the party that decides.
//!
//! # Sharing is a DOUBLE opt-in, and the bare field is the default
//!
//! A unit field written as the plain type is EXCLUSIVE: the unit owns it, the framework knows
//! nothing about it, and a `!Send` value is perfectly legal there because a resident constructs its
//! operator on the engine that will run it and never migrates it. Nothing about that changes here.
//!
//! Sharing is what needs both parties to say so. The resource's author declares the type shareable
//! ([`AsyncResource`] plus the macro), and the unit reaches for it BY TYPE — `model: Shared<Egemma>`.
//! The string label a share once needed is dead: the TYPE is the rendezvous.
//!
//! # Where the teeth are, and which refusal a reader gets
//!
//! | mistake | refusal | where |
//! |---|---|---|
//! | `Shared<T>` for a `T` that is no resource | `E0277`, naming the macro | the unit's FIELD |
//! | `#[ingraph::resource]` on a type with no [`AsyncResource`] impl | `E0277` | the DECLARATION |
//! | a resource type that is not `Send`/`Sync` | `E0277`, through the supertraits | the DECLARATION |
//! | a demanded resource nothing declared | [`Refusal::UndeclaredResource`](crate::Refusal) | START-UP, by name |
//! | a door the declaration did not name | [`LaunchError::Loading`](crate::LaunchError) | THE CREATE WALK, naming the declared source |
//!
//! The last one is a start-up refusal and not a compile one on purpose: [`AsyncResource`] is
//! hand-implemented, so a type CAN satisfy [`Shared`]'s bound without ever having joined the walk.
//! That gap is exactly what [`ResourceCatalog`] and the plan's cross-check close, and closing it in the
//! type system would mean making the capability unimplementable without the macro — which is the
//! opposite of how every other declaration in this crate can be hand-written.
//!
//! # The walk joins BESIDE the type walk rather than through it
//!
//! [`ResourceVisitor`] is its own trait, in this module, exactly as
//! [`transform::visit`](crate::TypeVisitor)'s note says a second kind must join: a per-family face
//! exists to reach ONE family's fact, so folding several into one trait makes the bound set the
//! union of every family's, paid by every visitor. [`TypeVisitor::next_type`](crate::TypeVisitor)'s
//! signature is untouched.

use core::future::Future;

use std::{collections::BTreeMap, convert::Infallible, sync::Arc};

use crate::{Resources, drive::Goodbye, name::borrowed_name};

borrowed_name! {
  /// A resource's name, as a type a message cannot be passed as.
  ///
  /// It is what the walk enumerates a citizen under and what a start-up refusal names, so a resource
  /// name is a key that gets COMPARED and PRINTED — [`NodeName`](crate::NodeName)'s position, one
  /// vocabulary over.
  ///
  /// It validates nothing, for [`NodeName`](crate::NodeName)'s reason: it is compared and printed,
  /// never quoted into a statement and never made into a path.
  pub struct ResourceName;
}

impl ResourceName {
  /// View `name` as a resource name.
  ///
  /// `const`, so a hand-written declaration can spell its resource names in constants.
  #[inline]
  #[must_use]
  pub const fn new(name: &str) -> &Self {
    Self::view(name)
  }

  /// The name `R` is enumerated and cross-checked under.
  ///
  /// # ONE authority, and that is the whole of why it is a function
  ///
  /// The declared set is collected off [`DeclaredResource::resource`] and the demanded set off
  /// [`ResourceDemand::of`], and the two must AGREE or the cross-check refuses a resource that is
  /// there. Both reach the name through this call, so there is no second author for it and no
  /// spelling for a declaration and a demand to disagree about.
  ///
  /// It is the compiler's own path for the type — `my_crate::Egemma` — which is what makes a
  /// start-up refusal name something a reader can find. Its exact spelling is
  /// [`core::any::type_name`]'s and is not promised across compilers; nothing here depends on that,
  /// because both sides are one compilation of one binary.
  ///
  /// # The key it is RULED to become, and the half that is still missing
  ///
  /// The design answer re-keys a resource to its MOUNT NAME, leaving the type path to diagnostics.
  /// The mount now EXISTS — a resource is a field of the graph root and [`ResourceCatalog`] carries the
  /// name it was written under — so the seat's stated precondition is met on the DECLARATION side.
  /// The demand side is what is not: [`ResourceDemand::of`] is minted inside a member's own
  /// declaration, which cannot see the root's field list and therefore cannot know the mount. So the
  /// two sides would key differently, and re-keying needs the type→mount join the root assembly
  /// brings. This stays the one call the key moves in when it does.
  #[inline]
  #[must_use]
  pub fn of<R: AsyncResource>() -> &'static Self {
    Self::view(core::any::type_name::<R>())
  }

  /// This name as a `str`.
  #[inline]
  #[must_use]
  pub const fn as_str(&self) -> &str {
    &self.0
  }
}

/// A type SEVERAL UNITS may hold at once — the capability contract, hand-implemented by the
/// resource's author.
///
/// # `Send + Sync` are the TEETH, and they are supertraits on purpose
///
/// A shared resource crosses residents, and residents are threads and tasks at once — so a type that
/// cannot cross is refused AT ITS DECLARATION, which is the earliest site there is, rather than at
/// whichever unit reached for it first. What the supertraits cannot promise is the other half:
/// `Sync` says a `&R` may be held by two threads, never that the PROTOCOL underneath is safe to
/// drive concurrently. That remains the author's asserted responsibility, and the declaration is
/// exactly the record of the assertion.
///
/// # `build` is ASYNC, and takes options the author shapes
///
/// Loading a model is I/O and compute, so construction is a future — the same async-factory posture
/// the rest of this crate's construction takes. [`Options`](Self::Options) is the AUTHOR's type
/// because only the author knows what one needs; the framework's job is to carry it to `build` once,
/// and to hand the built handle to every member that demanded it.
///
/// # Examples
///
/// ```
/// use ingraph::{Resources, AsyncResource, Shared};
///
/// struct Egemma {
///   dim: usize,
/// }
///
/// struct EgemmaOptions {
///   dim: usize,
/// }
///
/// impl AsyncResource for Egemma {
///   type Options = EgemmaOptions;
///   type Error = core::convert::Infallible;
///
///   async fn build(_ctx: &Resources, options: EgemmaOptions) -> Result<Self, Self::Error> {
///     Ok(Self { dim: options.dim })
///   }
/// }
///
/// // A handle is cloned, never rebuilt: one construction, N members.
/// let model = Shared::new(Egemma { dim: 768 });
/// let second = model.clone();
/// assert_eq!(second.dim, 768);
/// ```
#[diagnostic::on_unimplemented(
  message = "`{Self}` is not a shareable resource — only a declared one is reachable through \
             `Shared<…>`",
  label = "not a resource",
  note = "declare it with `#[ingraph::resource]` and write its `AsyncResource` impl; the `Send + Sync` \
          supertraits are the sharing teeth, and a bare field is the EXCLUSIVE default that needs \
          neither"
)]
pub trait AsyncResource: Send + Sync + Sized {
  /// What building one takes — the author's own type.
  ///
  /// Bound by nothing. What options must satisfy is the LAUNCH's question — how they are sourced,
  /// and what they deserialize from — and it is asked where the sourcing is written, which is not
  /// here.
  ///
  /// It is also where an ENGINE'S BUDGET lives, and the framework ships no second knob for one. A
  /// store is a resource, so a per-slot writer thread count or index arena is a field of the store
  /// author's own options — stated by the party that knows what the number means, in that engine's
  /// own units. A framework-global budget would have to be translated into each of them, and the
  /// translation would be this layer deciding a question no backend asked it.
  type Options;

  /// What a refused construction reports.
  ///
  /// Bound-free, per [`Operator::Error`](crate::Operator::Error)'s discipline: a resource reports in
  /// its own currency, and a caller bounds it where it must render or propagate one.
  type Error;

  /// Build one from `options` — ONCE per resource type, however many members demand it.
  ///
  /// The future is `Send` because construction happens wherever the launch runs, and it is spelled
  /// as `impl Future + Send` rather than as `async fn` so the bound is part of the contract instead
  /// of something each caller has to hope for.
  fn build(
    ctx: &Resources,
    options: Self::Options,
  ) -> impl Future<Output = Result<Self, Self::Error>> + Send;

  /// Say this resource's goodbye — a pool drained, a lock removed, a directory cleaned up after.
  ///
  /// The resource-side twin of [`Declared::goodbye`](crate::Declared::goodbye), and the DEFAULT is
  /// the same one: it DROPS, which is the shipped teardown for every value that enrols in no other.
  /// So this is additive for every resource already written — a type that has nothing to await says
  /// nothing here and pays nothing anywhere.
  ///
  /// # The WORD is what enrols it, not the impl
  ///
  /// Writing this override does not put the resource on the shutdown chain. The graph root's
  /// `#[ingraph(resource(teardown))]` does — the same rule the node side keeps, and for the same
  /// reason: whether a type happens to have something to say is not the same question as whether
  /// this deployment asked for it to be said. Without the word the resource is released by
  /// [`Drop`] as the launch's map goes, and this is never called.
  ///
  /// # It is reached only where the resource is the LAST handle
  ///
  /// The chain unseals through [`Shared::unseal`], so a resource an application still holds a clone
  /// of is never told to say anything: the release is skipped, the taps are told and the report
  /// carries the row. See [`Resources::release`](crate::Resources) for the whole of that posture.
  ///
  /// # It hands back a future, and that future is not `Send`
  ///
  /// [`build`](Self::build) promises `Send` because construction runs wherever the launch does; a
  /// goodbye is driven by the chain on one thread and needs no such promise. The asymmetry is the
  /// same one [`Declared::goodbye`](crate::Declared::goodbye) keeps, and it is what lets a resource
  /// whose goodbye reaches an FFI session say it at all.
  ///
  /// # Examples
  ///
  /// ```
  /// use ingraph::{Resources, BoxedError, Goodbye, AsyncResource};
  ///
  /// struct Pool {
  ///   open: usize,
  /// }
  ///
  /// impl AsyncResource for Pool {
  ///   type Options = usize;
  ///   type Error = core::convert::Infallible;
  ///
  ///   async fn build(_ctx: &Resources, open: usize) -> Result<Self, Self::Error> {
  ///     Ok(Self { open })
  ///   }
  ///
  ///   fn goodbye(self) -> Goodbye {
  ///     Box::pin(async move {
  ///       // Whatever draining takes — a flush, a connection closed politely.
  ///       assert_ne!(self.open, 0);
  ///       Ok::<(), BoxedError>(())
  ///     })
  ///   }
  /// }
  /// ```
  #[inline]
  fn goodbye(self) -> Goodbye {
    drop(self);
    Box::pin(core::future::ready(Ok(())))
  }
}

/// A resource's CITIZENSHIP: it is in the walk, so a plan can enumerate it and a demand can be
/// checked against it.
///
/// WHAT A RESOURCE HOLDS — the two storage seams a declaration's leg may point at.
///
/// # A closed pair, and it is closed by the seams rather than by taste
///
/// A leg points at a resource and the resource is verified against a KIND TRAIT
/// ([`holds_documents`](crate::store::holds_documents) / [`holds_coordinates`](crate::store::holds_coordinates)),
/// and there are exactly two of those because there are exactly two retrieving families. A third
/// arrives as a third seam, at which point this enum grows with it — which is the framework-owned
/// vocabulary case a unit enum is for, and not the extension point an application reaches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
pub enum ResourceKind {
  /// A full-text index — what a `searchable` election is written to.
  #[display("documents")]
  Documents,
  /// A vector index — what a `knn` election is written to.
  #[display("coordinates")]
  Coordinates,
}

/// THE KINDS ONE RESOURCE ANSWERS FOR — a SET, because a store may hold both.
///
/// # Why a set and not a [`ResourceKind`]
///
/// Nothing stops one connection-manager from holding a document index and a vector index: a
/// database with both a full-text and a vector extension is one store answering two seams, and the
/// two mount traits are independent impls on one type. A single-valued seat would make such a
/// resource unrepresentable, or would make it lie about half of itself — and the whole point of the
/// facet is that *kind-compatible* is a question a launch asks of a CANDIDATE LIST.
///
/// # It is a defaulted fact of the DECLARATION, and it defaults to EMPTY
///
/// [`DeclaredResource::KINDS`] carries it. A BUILTIN kind word states it without the author
/// writing anything, the word being the knowledge; a FOREIGN resource states it in one line, which
/// is the open seam's usual price — and the default is EMPTY rather than a guess, because a
/// resource that has not said what it holds must not silently become the sole default for a leg it
/// cannot serve. Saying nothing costs exactly the sole-default convenience and nothing else: a leg
/// that POINTS at such a resource is verified by the kind trait as it always was.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct ResourceKinds(u8);

impl ResourceKinds {
  const DOCUMENTS_BIT: u8 = 0b01;
  const COORDINATES_BIT: u8 = 0b10;

  /// A resource that has said nothing about what it holds — the default.
  pub const NONE: Self = Self(0);
  /// A full-text store.
  pub const DOCUMENTS: Self = Self(Self::DOCUMENTS_BIT);
  /// A vector store.
  pub const COORDINATES: Self = Self(Self::COORDINATES_BIT);

  /// Both — a store answering the two seams at once.
  #[must_use]
  pub const fn both() -> Self {
    Self(Self::DOCUMENTS_BIT | Self::COORDINATES_BIT)
  }

  /// This set with `kind` added — the `const` composer a declaration writes.
  #[must_use]
  pub const fn with(self, kind: ResourceKind) -> Self {
    Self(self.0 | Self::bit(kind))
  }

  /// Whether this resource answers for `kind`.
  #[must_use]
  pub const fn holds(self, kind: ResourceKind) -> bool {
    self.0 & Self::bit(kind) != 0
  }

  /// Whether the declaration said nothing at all.
  #[must_use]
  pub const fn is_empty(self) -> bool {
    self.0 == 0
  }

  const fn bit(kind: ResourceKind) -> u8 {
    match kind {
      ResourceKind::Documents => Self::DOCUMENTS_BIT,
      ResourceKind::Coordinates => Self::COORDINATES_BIT,
    }
  }
}

/// `#[ingraph::resource]` emits `impl DeclaredResource for …`, and the SUPERTRAIT is what makes the
/// declaration assert the contract: a type declared without a [`AsyncResource`] impl is `E0277` AT THE
/// DECLARATION rather than at the first unit that reached for it.
///
/// The supertrait is the WHOLE assert, and that is measured rather than assumed. A separate audit
/// call beside the impl — the shape [`refers_to`](crate::refers_to) and its neighbours take — was
/// written and then removed: it produced a SECOND error with the same sentence at the same span, so
/// what it added was a duplicate. `ingraph-derive/tests/refusals/` holds the message the one impl
/// gives.
///
/// # It is a marker, and [`resource`](Self::resource) has no second body to write
///
/// The name is derived from the type, in the one place [`ResourceName::of`] derives it, so a
/// citizen states nothing a demand could disagree with. Overriding it would be stating the same
/// thing again, differently — which is the one way the cross-check could ever refuse a resource
/// that is really there.
///
/// A hand-written `impl DeclaredResource for Egemma {}` is the same declaration spelled out, and it
/// is legal: every declaration in this crate can be hand-written, and the macro is the ergonomic
/// spelling rather than a gate.
#[diagnostic::on_unimplemented(
  message = "`{Self}` is a resource nothing DECLARED — the walk enumerates citizens, and this type \
             never joined",
  label = "not declared",
  note = "`#[ingraph::resource]` is what emits the citizenship"
)]
pub trait DeclaredResource: AsyncResource {
  /// THE MODE WORD, as the declaration recorded it: whether this resource's ENGINE FACES are the
  /// blocking ones.
  ///
  /// # What it is for, and why the declaration is where it lives
  ///
  /// A resource is an engine, and an engine's verbs come in pairs — `FulltextRead` beside
  /// `AsyncFulltextRead`, `VectorWrite` beside `AsyncVectorWrite`. Which half a resource wears is a
  /// fact NOTHING ELSE CAN SEE: a foreign resource's faces are hand-written in the author's own
  /// crate, and the election that binds one is expanded by a different macro in a different file. So
  /// the word rides the declaration — `#[ingraph::resource(async)]` — and this is where the
  /// expansion leaves it for the binding to read.
  ///
  /// The same two-clocks problem [`Declared::Mode`](crate::Declared::Mode) solves for a node, at the
  /// resource's own grain. A word that LIED is not a fact this seat can catch and is not meant to
  /// be: what catches it is the binding, which spells the face the word chose and gets `E0277`
  /// naming the trait the engine does not implement. Words CHOOSE; bounds PROVE.
  ///
  /// # `true` is the DEFAULT, and the default is what a bare declaration means
  ///
  /// A resource written with no word is on the BLOCKING face, exactly as a bare node declaration is.
  /// The seat is therefore defaulted rather than required, which is what keeps a HAND-WRITTEN
  /// `impl DeclaredResource for Egemma {}` — blessed by this trait's own note — a complete
  /// declaration: it says nothing about a mode and means the one a bare macro form means.
  ///
  /// A BUILTIN KIND WORD states it without the author writing anything, because the kind carries the
  /// knowledge: `#[ingraph::resource(tantivy)]` is `true` and cannot be otherwise, tantivy being a
  /// synchronous engine — which is why writing `resource(tantivy, async)` is refused at the word
  /// rather than believed.
  ///
  /// # A `bool` here and a TYPE where it is spent
  ///
  /// Stable Rust has no defaulted ASSOCIATED TYPE, and this seat must be defaulted or every
  /// hand-written declaration in every crate becomes a breaking change. So the fact is carried in
  /// the shape that can default, and lifted back into the type a bound selects on through the bridge
  /// the crate already ships for exactly this crossing:
  /// [`Selected<SYNC>`](crate::Selected) — `Selected<true>` is [`Block`](crate::Block) and
  /// `Selected<false>` is [`Async`](crate::Async). An emission naming a concrete resource writes
  /// `Selected<{ <Ft as DeclaredResource>::SYNC }>` and has the mode as a type.
  const SYNC: bool = true;

  /// WHAT THIS RESOURCE HOLDS — the facet a SOLE-DEFAULT binding is resolved against.
  ///
  /// # It is what makes *kind-compatible* a question a launch can ask
  ///
  /// A leg that names no resource is bound by 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. Both halves need the catalog to know a resource's kind, and nothing
  /// else in this crate does — a `DeclaredResource` bound cannot test whether the type also
  /// implements [`FulltextMount`](crate::FulltextMount), stable Rust having no way to ask.
  ///
  /// # DEFAULTED TO EMPTY, and the default is the conservative one
  ///
  /// [`SYNC`](Self::SYNC)'s reason exactly: the seat must default or every hand-written
  /// `impl DeclaredResource for Egemma {}` becomes a breaking change. What it defaults TO is the
  /// difference — a mode has an honest default and a kind does not, so a resource that has not said
  /// what it holds is simply not a candidate. It is never guessed at, and a leg that POINTS at it
  /// is verified by the kind trait as it always was.
  ///
  /// A BUILTIN KIND WORD states it: `#[ingraph::resource(tantivy)]` is
  /// [`ResourceKinds::DOCUMENTS`] and cannot be otherwise.
  const KINDS: ResourceKinds = ResourceKinds::NONE;

  /// The name this resource is enumerated and cross-checked under.
  ///
  /// Defaulted, and see the trait note for why nothing overrides it.
  #[inline]
  fn resource() -> &'static ResourceName {
    ResourceName::of::<Self>()
  }
}

/// WHERE one resource's options come from — the ONE source its declaration named.
///
/// # It is a vocabulary, and the vocabulary is CLOSED
///
/// A resource field of a graph root is written in exactly three spellings, and each names one door:
/// there is no fourth for a deployment to invent, so this is an enum rather than a seam. What is
/// open is the resource itself — its type, its options and its `build` are all the author's.
///
/// The `teardown` word is beside this vocabulary rather than in it, and that is what makes it
/// compose: `#[ingraph(resource(factory, teardown))]` names this same PREPARE door and adds the
/// goodbye, because where a resource's options come from and whether it has something to say on the
/// way out are unrelated questions. See [`AsyncResource::goodbye`], which is what the word enrols.
///
/// # THE SINGLE-SOURCE LAW
///
/// No precedence chain. The declaration names THE source, and every other door is CLOSED for that
/// resource and refuses loudly rather than quietly losing to one — a conflict dies at launch instead
/// of in production, which is the immutable-configuration doctrine's direct descendant. Varying a
/// resource between deployments is a different DOCUMENT, never a second door.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
pub enum ResourceSource {
  /// `#[ingraph(resource)]` — the deployment's own `[resources.<mount>]` document section.
  ///
  /// Absent from the document, the options run at their own [`Default`]; a type without one has
  /// said its knobs are mandatory, and the section is then the only place they can be written.
  ///
  /// The mount is not a payload here for the reason nothing in this crate is stated twice: the
  /// catalog already keys every resource by the name it is mounted under, and a copy inside the
  /// source word would be a second thing to keep true. A refusal that wants to spell
  /// `[resources.egemma]` reads the mount from [`ResourceCatalog::mount`].
  #[display("its own `[resources.…]` section of the deployment's document")]
  Section,
  /// `#[ingraph(resource(factory))]` — the PREPARE closure, the application's own hand.
  ///
  /// For options that close over something a document cannot hold: a runtime handle, an open
  /// connection, a value the process computed before it launched.
  #[display("the `prepare` closure the application hands the launch")]
  Prepare,
  /// `#[ingraph(resource(factory = "path::to::fn"))]` — a named function the create walk calls
  /// itself.
  ///
  /// The self-sufficient resource: options read from the environment or computed from a path need
  /// no `prepare` at all, so the declaration names the function and the walk spends it.
  #[display("the initialization function its declaration names")]
  Initializer,
}

impl ResourceSource {
  /// Whether this is the [`Prepare`](Self::Prepare) door — the one an application spends by hand.
  #[inline]
  #[must_use]
  pub const fn is_prepare(&self) -> bool {
    matches!(self, Self::Prepare)
  }
}

/// A visitor applied once per resource a deployment declares — the RESOURCE half of the walk.
///
/// Beside [`TypeVisitor`](crate::TypeVisitor) rather than inside it, per that trait's own note: a
/// per-family face exists to reach ONE family's fact, so folding this into `next_type` would make
/// every node visitor pay a resource bound it never spends.
///
/// # What a visitor may assume
///
/// [`DeclaredResource`], which [`next_resource`](Self::next_resource) declares — so a resource that
/// never took the macro cannot be walked at all, and the refusal lands where the WALK names it.
/// That is the citizenship bound doing at the walk what
/// [`Describe`](crate::Describe) does for a node.
///
/// # The MOUNT and the SOURCE ride with the type
///
/// A resource is a FIELD of the graph root, so its declaration states three things at once: the type,
/// the name it is mounted under, and which door its options come through. All three are the root's
/// facts and none of them can be read off the type alone — so the walk carries them rather than
/// making a visitor derive two of them from somewhere they are not written.
///
/// # Examples
///
/// ```
/// use ingraph::{Resources, DeclaredResource, AsyncResource, ResourceSource, ResourceVisitor, ResourceCatalog};
///
/// struct Egemma;
/// struct Whisper;
///
/// impl AsyncResource for Egemma {
///   type Options = ();
///   type Error = core::convert::Infallible;
///
///   async fn build(_ctx: &Resources, _: ()) -> Result<Self, Self::Error> {
///     Ok(Self)
///   }
/// }
///
/// impl AsyncResource for Whisper {
///   type Options = ();
///   type Error = core::convert::Infallible;
///
///   async fn build(_ctx: &Resources, _: ()) -> Result<Self, Self::Error> {
///     Ok(Self)
///   }
/// }
///
/// // What `#[ingraph::resource]` emits.
/// impl DeclaredResource for Egemma {}
/// impl DeclaredResource for Whisper {}
///
/// // What `#[ingraph::graph]` emits — one call per resource field, in declaration order.
/// let mut declared = ResourceCatalog::new();
/// declared
///   .next_resource::<Egemma>("egemma", ResourceSource::Section)
///   .unwrap();
/// declared
///   .next_resource::<Whisper>("whisper", ResourceSource::Prepare)
///   .unwrap();
///
/// assert_eq!(declared.len(), 2);
/// assert!(declared.declares(<Egemma as DeclaredResource>::resource()));
/// assert_eq!(
///   declared.source(<Whisper as DeclaredResource>::resource()),
///   Some(ResourceSource::Prepare)
/// );
/// ```
pub trait ResourceVisitor {
  /// This visitor's failure.
  ///
  /// Bound-free, per [`TypeVisitor::Error`](crate::TypeVisitor)'s discipline.
  type Error;

  /// Observe one declared resource — its type, the `mount` it is written under, and the `source`
  /// its declaration named.
  ///
  /// # Errors
  ///
  /// Whatever this visitor's per-resource work fails with. Returning `Err` ENDS the walk, which is
  /// what makes a refusal name the first resource it could not serve rather than a list.
  fn next_resource<R: DeclaredResource>(
    &mut self,
    mount: &'static str,
    source: ResourceSource,
  ) -> Result<(), Self::Error>;
}

/// THE ROOT CATALOG: every resource a deployment declares, under its mount, from its one source.
///
/// The graph root's fields ARE the declared set — nodes and resources in one namespace — so this is
/// what the root's own walk collects and what every later question is asked of: the validate walk
/// cross-checks a demand against it, and the create walk reads a resource's declared SOURCE out of
/// it before opening any door.
///
/// What it keeps is the FOUR facts a declaration states and nothing else — its name, its mount, its
/// source, and WHAT IT HOLDS. A resource's options and its built handle belong to the launch: the
/// options go through whichever door [`ResourceSource`] names, and the handle lives in the
/// [`Resources`](crate::Resources).
///
/// The fourth is the youngest and it is what the BINDING LAWS are resolved against: a leg that
/// names no resource takes the one kind-compatible resource a deployment declared, and zero or
/// several is a start-up refusal listing the candidates. See [`candidates`](Self::candidates) and
/// [`sole`](Self::sole).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ResourceCatalog {
  declared: BTreeMap<&'static str, (&'static str, ResourceSource, ResourceKinds)>,
}

impl ResourceCatalog {
  /// Nothing declared.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      declared: BTreeMap::new(),
    }
  }

  /// Declare `R` at `mount`, sourced from `source`, without driving a walk — the hand-written door,
  /// and what a test wires with.
  #[inline]
  #[must_use]
  pub fn with<R: DeclaredResource>(mut self, mount: &'static str, source: ResourceSource) -> Self {
    self
      .declared
      .insert(R::resource().as_str(), (mount, source, R::KINDS));
    self
  }

  /// Whether `resource` was declared.
  #[inline]
  #[must_use]
  pub fn declares(&self, resource: &ResourceName) -> bool {
    self.declared.contains_key(resource.as_str())
  }

  /// Where `resource`'s options come from — `None` for a resource nothing declared.
  #[inline]
  #[must_use]
  pub fn source(&self, resource: &ResourceName) -> Option<ResourceSource> {
    self
      .declared
      .get(resource.as_str())
      .map(|&(_, source, _)| source)
  }

  /// The name `resource` is mounted under on the root — `None` for a resource nothing declared.
  #[inline]
  #[must_use]
  pub fn mount(&self, resource: &ResourceName) -> Option<&'static str> {
    self
      .declared
      .get(resource.as_str())
      .map(|&(mount, _, _)| mount)
  }

  /// Every declared resource, in name order.
  #[inline]
  pub fn names(&self) -> impl Iterator<Item = &ResourceName> {
    self.declared.keys().copied().map(ResourceName::new)
  }

  /// WHAT `resource` holds, as its declaration stated it — `None` for a resource nothing declared.
  #[inline]
  #[must_use]
  pub fn kinds(&self, resource: &ResourceName) -> Option<ResourceKinds> {
    self
      .declared
      .get(resource.as_str())
      .map(|&(_, _, kinds)| kinds)
  }

  /// EVERY declared resource that can hold `kind`, in name order — the candidate list a
  /// SOLE-DEFAULT binding is resolved against, and the list a refusal prints.
  ///
  /// A resource whose declaration said nothing about what it holds is NOT a candidate; see
  /// [`DeclaredResource::KINDS`] for why the empty default is the conservative one.
  #[inline]
  pub fn candidates(&self, kind: ResourceKind) -> impl Iterator<Item = &'static ResourceName> {
    self
      .declared
      .iter()
      .filter(move |&(_, &(_, _, kinds))| kinds.holds(kind))
      .map(|(&name, _)| ResourceName::new(name))
  }

  /// THE SOLE-DEFAULT — the one resource that can hold `kind`, or [`None`] where the deployment
  /// declared zero of them or several.
  ///
  /// # The two absences are ONE answer here and TWO refusals above
  ///
  /// This says only *is the binding unambiguous*. WHICH way it failed — nothing to bind, or a
  /// choice this framework must not make on a deployment's behalf — is what the refusal words, and
  /// it words it out of [`candidates`](Self::candidates) rather than out of a second return shape.
  /// One question per method, and the caller that needs the list already has it.
  #[inline]
  #[must_use]
  pub fn sole(&self, kind: ResourceKind) -> Option<&'static ResourceName> {
    let mut candidates = self.candidates(kind);
    let first = candidates.next()?;
    candidates.next().is_none().then_some(first)
  }

  /// How many were declared.
  #[inline]
  #[must_use]
  pub fn len(&self) -> usize {
    self.declared.len()
  }

  /// Whether none was.
  #[inline]
  #[must_use]
  pub fn is_empty(&self) -> bool {
    self.declared.is_empty()
  }
}

impl ResourceVisitor for ResourceCatalog {
  type Error = Infallible;

  #[inline]
  fn next_resource<R: DeclaredResource>(
    &mut self,
    mount: &'static str,
    source: ResourceSource,
  ) -> Result<(), Self::Error> {
    self
      .declared
      .insert(R::resource().as_str(), (mount, source, R::KINDS));
    Ok(())
  }
}

/// ONE unit's demand for a resource — what a `Shared<R>` field says, as a plan records it.
///
/// It is minted from the TYPE and carries only the name, which is what keeps the demand recordable
/// for a resource that was never declared: that case is precisely the one the start-up cross-check
/// exists to refuse, so a door that could only be spelled for a citizen would make the refusal
/// unreachable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
#[display("{}", self.resource.as_str())]
pub struct ResourceDemand {
  resource: &'static ResourceName,
}

impl ResourceDemand {
  /// The demand a `Shared<R>` field states.
  #[inline]
  #[must_use]
  pub fn of<R: AsyncResource>() -> Self {
    Self {
      resource: ResourceName::of::<R>(),
    }
  }

  /// The resource demanded.
  #[inline]
  #[must_use]
  pub const fn resource(&self) -> &'static ResourceName {
    self.resource
  }
}

/// A handle to a resource SEVERAL units hold at once — one construction, N clones.
///
/// # The bound on the STRUCT is the admission gate
///
/// `R: AsyncResource` is written on the type itself and not only on its impls, and that is deliberate
/// rather than an over-application: the whole job of this wrapper is that a unit's FIELD refuses an
/// undeclared type, and a bound that lived on the methods would let `model: Shared<Vec<u8>>` compile
/// and fail somewhere else. The refusal carries [`AsyncResource`]'s own
/// [`on_unimplemented`](diagnostic::on_unimplemented) sentence, so the message names the fix at the
/// site that needs it.
///
/// # `Arc` and nothing else
///
/// Sharing is construction-sharing: the framework builds one value and clones the handle. It adds no
/// lock and no cell — whether the resource's own protocol is safe to drive concurrently is the
/// author's assertion, recorded by the declaration, and a lock this layer imposed would be this
/// layer answering a question it cannot see.
///
/// # Examples
///
/// ```
/// use ingraph::{Resources, AsyncResource, Shared};
///
/// struct Tokenizer(usize);
///
/// impl AsyncResource for Tokenizer {
///   type Options = usize;
///   type Error = core::convert::Infallible;
///
///   async fn build(_ctx: &Resources, vocab: usize) -> Result<Self, Self::Error> {
///     Ok(Self(vocab))
///   }
/// }
///
/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
/// let shared = Shared::<Tokenizer>::build(&Resources::new(), 32_000).await.unwrap();
/// let held_elsewhere = shared.clone();
/// assert_eq!(held_elsewhere.0, 32_000);
/// assert_eq!(shared.holders(), 2);
/// # });
/// ```
pub struct Shared<R: AsyncResource> {
  handle: Arc<R>,
}

impl<R: AsyncResource> Shared<R> {
  /// Share an already-built `resource`.
  #[inline]
  #[must_use]
  pub fn new(resource: R) -> Self {
    Self {
      handle: Arc::new(resource),
    }
  }

  /// Build one from `options` and share it — the construction slot, run ONCE per resource type.
  ///
  /// # Errors
  ///
  /// Whatever the resource's own [`build`](AsyncResource::build) refused with.
  #[inline]
  pub async fn build(ctx: &Resources, options: R::Options) -> Result<Self, R::Error> {
    R::build(ctx, options).await.map(Self::new)
  }

  /// The resource, borrowed.
  #[inline]
  #[must_use]
  pub fn get(&self) -> &R {
    &self.handle
  }

  /// How many handles are outstanding — the count that says construction happened once.
  #[inline]
  #[must_use]
  pub fn holders(&self) -> usize {
    Arc::strong_count(&self.handle)
  }

  /// UNSEAL the resource, where this is the LAST handle to it — `None` where it is not.
  ///
  /// The release the launch's resources-last step performs, and the reason it is a QUESTION: a
  /// resource is shared by construction, so the only honest way to get the value back is to ask
  /// whether anybody else still holds one. An application that kept a clone of its own gets `None`
  /// here, and what follows is a leak the report names rather than a wait nothing would end.
  ///
  /// Either way this handle is spent. Where the answer is `None` it was released as the question
  /// was asked, which is [`Arc::into_inner`]'s own contract: exactly one of several concurrent
  /// callers wins, so a resource whose last handles go at the same moment is torn down once rather
  /// than by neither of them.
  ///
  /// # Examples
  ///
  /// ```
  /// # use ingraph::Resources;
  /// # use ingraph::{AsyncResource, Shared};
  /// struct Pool;
  /// # impl AsyncResource for Pool {
  /// #   type Options = ();
  /// #   type Error = core::convert::Infallible;
  /// #   async fn build(_ctx: &Resources, _: ()) -> Result<Self, Self::Error> { Ok(Self) }
  /// # }
  /// let shared = Shared::new(Pool);
  /// let held_elsewhere = shared.clone();
  ///
  /// // Somebody else still holds one, so there is nothing to unseal.
  /// assert!(shared.unseal().is_none());
  ///
  /// // And once they have let go, the last handle answers.
  /// assert!(held_elsewhere.unseal().is_some());
  /// ```
  #[inline]
  #[must_use]
  pub fn unseal(self) -> Option<R> {
    Arc::into_inner(self.handle)
  }
}

impl<R: AsyncResource> Clone for Shared<R> {
  /// Hand-written so `R` need not be [`Clone`]: a handle is a handle, and cloning one is what
  /// SHARING is.
  #[inline]
  fn clone(&self) -> Self {
    Self {
      handle: Arc::clone(&self.handle),
    }
  }
}

impl<R: AsyncResource> core::ops::Deref for Shared<R> {
  type Target = R;

  #[inline]
  fn deref(&self) -> &R {
    &self.handle
  }
}

impl<R: AsyncResource> AsRef<R> for Shared<R> {
  #[inline]
  fn as_ref(&self) -> &R {
    &self.handle
  }
}

impl<R: AsyncResource> core::fmt::Debug for Shared<R> {
  /// The resource's NAME and the holder count, rather than the resource itself: a model context has
  /// no useful [`Debug`](core::fmt::Debug) and demanding one would bound every author's type for the
  /// benefit of this line. It is the arity answer [`Taps`](crate::Taps)' own `Debug` gives.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Shared")
      .field("resource", &ResourceName::of::<R>().as_str())
      .field("holders", &Arc::strong_count(&self.handle))
      .finish()
  }
}

#[cfg(test)]
mod tests;