ingraph_codegen/resource.rs
1//! The RESOURCE declaration's emission: citizenship, the mode the declaration recorded, and — where
2//! a BUILTIN KIND WORD was written — the engine the macro mints and the impls that delegate to it.
3//!
4//! ```ignore
5//! #[ingraph::resource] pub struct Egemma { model: EgemmaModel } // FOREIGN: hand impls
6//! #[ingraph::resource(async)] pub struct MyRemote(RemoteQdrant); // FOREIGN, awaited faces
7//! #[ingraph::resource(tantivy)] pub struct Ft; // BUILTIN: the macro mints
8//! ```
9//!
10//! # THE FOREIGN FORM emits ONE ITEM, and the item is two refusals
11//!
12//! `impl DeclaredResource for Egemma { … }` — the CITIZENSHIP, which the walk enumerates. The trait's
13//! SUPERTRAIT is what makes the same line an assert: `DeclaredResource: AsyncResource`, so a declaration
14//! with no `AsyncResource` impl is `E0277` AT THE DECLARATION; and `AsyncResource: Send + Sync`, so a type
15//! that cannot cross threads is refused at the same site, which is the earliest one there is.
16//!
17//! Its BODY is the mode the declaration recorded — `const SYNC` — and that is the whole of what the
18//! `async` word buys here. The faces themselves stay the author's own hand: this is the OPEN SEAM,
19//! and a macro that wrote an engine impl for a type it has never seen would be closing it.
20//!
21//! # A SECOND audit was written and removed, and the measurement is why
22//!
23//! Every other emission in this crate states a bound it wants a reader to meet as a sentence
24//! through an audit CALL in an anonymous `const` —
25//! [`stores_rows`](../../ingraph/fn.stores_rows.html)'s shape. One was written here, and the
26//! measurement is that rustc reports the missing contract at the DECLARATION's own type name
27//! either way, with the `on_unimplemented` note either way — so the audit produced a second error
28//! saying exactly what the first one said. It is gone, and the note is what stops it being
29//! rediscovered.
30//!
31//! # THE BUILTIN FORM is the same declaration with the engine filled in
32//!
33//! A kind word names one of the framework's own engines, so everything the foreign author writes by
34//! hand is known here and is written for them: the declaration is re-emitted CARRYING the engine (a
35//! kind word takes a declaration with no fields, precisely so the macro owns the one it mints), the
36//! `AsyncResource` impl opens it, and the base plus the two faces of the engine's OWN MODE delegate to
37//! it. No face of the other mode is emitted, because the kind word carries the mode knowledge and a
38//! second face would be this crate claiming a posture the engine does not have.
39//!
40//! It rides the engine's own cargo gate, and the shut half carries the author's declaration back
41//! beside a `compile_error!` — see [`ResourceKind::gate`].
42//!
43//! # No accessor family, and that is the tier rather than an omission
44//!
45//! A record's expansion hands its fields out; a resource's does not. A resource is reached through
46//! [`Shared<R>`](../../ingraph/struct.Shared.html), which derefs to the type itself, so what a
47//! member can do with one is whatever the AUTHOR's own inherent impl offers. Emitting accessors
48//! would put this crate's naming convention on a type whose whole surface is somebody else's.
49//!
50//! The BUILTIN form has two inherent items anyway, and the line is exactly the one above: the macro
51//! MINTED that engine, so the two doors onto it are this crate's to name — see
52//! [`ResourceKind::emit`].
53
54use crate::prefix::EmissionPrefix;
55use quote::{format_ident, quote};
56
57#[cfg(test)]
58mod kind_tests;
59#[cfg(test)]
60mod tests;
61
62/// WHICH FACE a resource's engine impls wear — the `async` word, as a closed vocabulary.
63///
64/// [`Block`](../../ingraph/struct.Block.html) / [`Async`](../../ingraph/struct.Async.html) at the
65/// declaration's grain, and one word of the same lexicon `source(async)`, `handler(async)` and
66/// `operator(async)` are written in. What it reaches is one `const SYNC` on the emitted citizenship,
67/// which the ELECTION's emission reads to decide which of an engine's two face pairs to bind.
68///
69/// An enum rather than a `bool` for the reason every closed vocabulary in this crate is one: the two
70/// ends have names, and a field called `sync` reads as an answer to a question nobody asked at the
71/// declaration.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
73pub enum ResourceMode {
74 /// The BLOCKING face — a bare declaration, and every builtin whose engine answers without a
75 /// future.
76 #[default]
77 Block,
78 /// The AWAITED face — what the `async` word buys.
79 Async,
80}
81
82impl ResourceMode {
83 /// Whether this mode's verbs answer without a future — the `bool` the emitted `SYNC` carries.
84 #[inline]
85 #[must_use]
86 pub const fn sync(self) -> bool {
87 matches!(self, Self::Block)
88 }
89}
90
91/// A BUILTIN ENGINE a resource declaration may name in one word — the CLOSED framework vocabulary.
92///
93/// # Closed, and short, and both on purpose
94///
95/// A kind word is a promise that this crate can write the whole engine binding, which it can only
96/// keep for an engine it SHIPS. So the vocabulary holds exactly the engines in the tree, and it
97/// holds them by NAME rather than by family: `tantivy` is a word because
98/// `store::tantivy` is an engine; `lance` is not, because nothing in this tree implements one, and a
99/// word whose emission has no target is a promise made to a reader who then cannot cash it. The
100/// OPEN half of the axis is the bare form, which needs no vocabulary at all.
101///
102/// # It is the ONE home of the word list
103///
104/// The grammar refuses an unknown kind word by naming the known ones, and the emitter writes what
105/// each one means. Both read [`WORDS`](Self::WORDS) and [`from_word`](Self::from_word) here, so a
106/// word cannot be spellable in one and unknown in the other.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum ResourceKind {
109 /// `tantivy` — the shipped full-text engine: a `TantivyStore` connection-manager, its per-slot
110 /// `TantivyFulltext` handle, and a corpus per resource.
111 Tantivy,
112}
113
114impl ResourceKind {
115 /// Every builtin kind word, in the order a refusal lists them.
116 pub const WORDS: &'static [&'static str] = &["tantivy"];
117
118 /// The kind `word` names — `None` for a word this vocabulary does not hold.
119 #[inline]
120 #[must_use]
121 pub fn from_word(word: &str) -> Option<Self> {
122 match word {
123 "tantivy" => Some(Self::Tantivy),
124 _ => None,
125 }
126 }
127
128 /// The word that names this kind.
129 #[inline]
130 #[must_use]
131 pub const fn word(self) -> &'static str {
132 match self {
133 Self::Tantivy => "tantivy",
134 }
135 }
136
137 /// THE MODE THE KIND CARRIES, which is why a kind word takes no `async` beside it.
138 ///
139 /// Tantivy is a SYNCHRONOUS engine — the shipped face does its work inline and the async twin is
140 /// the blocking body with `ready` around it — so a resource of this kind wears the blocking faces,
141 /// and nothing an author writes can make that untrue. This is what the word *carries its own mode*
142 /// means, and what makes `resource(tantivy, async)` a refusal rather than a preference.
143 #[inline]
144 #[must_use]
145 pub const fn mode(self) -> ResourceMode {
146 match self {
147 Self::Tantivy => ResourceMode::Block,
148 }
149 }
150
151 /// WHAT A RESOURCE OF THIS KIND HOLDS — the facet the SOLE-DEFAULT binding is resolved against.
152 ///
153 /// The word carries it for the reason it carries the mode: `tantivy` IS a full-text store, and an
154 /// author who wrote the word has already said so. A FOREIGN resource states it by hand — one
155 /// line, the open seam's usual price — and says nothing by default, which costs exactly the
156 /// sole-default convenience.
157 #[must_use]
158 pub fn kinds(self) -> proc_macro2::TokenStream {
159 match self {
160 Self::Tantivy => quote!(DOCUMENTS),
161 }
162 }
163
164 /// WHAT A HOME LOOKS LIKE in a resource of this kind — the [`Habitat`] blueprint the word carries.
165 ///
166 /// The word knows the kind and the kind knows the vocabulary: `tantivy` holds documents, so a
167 /// declaration's home in one is the CORPORA it owns there. A foreign resource states it by hand,
168 /// which is one line and the open seam's usual price.
169 ///
170 /// [`Habitat`]: ../../ingraph/trait.Habitat.html
171 #[must_use]
172 pub fn blueprint(self, krate: &syn::Path) -> proc_macro2::TokenStream {
173 match self {
174 Self::Tantivy => {
175 let schema = crate::emit::framework(krate, &["transform"], "SlotSchema");
176 quote!(&'static [#schema])
177 }
178 }
179 }
180
181 /// THE FACTORY VISITOR a resource of this kind makes its homes with — LAYER TWO's machine, and the
182 /// face its own MODE names.
183 ///
184 /// A builtin's machine is the framework's, because the framework wrote the engine: the word that
185 /// mints the store mints the maker for it too. The pair is `(the author face to implement, the
186 /// visitor type)`, and which face is [`mode`](Self::mode)'s answer — a blocking engine's maker is
187 /// a [`TypeVisitor`] and an awaited one's is its twin, with no bridge between them.
188 ///
189 /// [`TypeVisitor`]: ../../ingraph/trait.TypeVisitor.html
190 #[must_use]
191 pub fn maker(self, krate: &syn::Path, name: &syn::Ident) -> proc_macro2::TokenStream {
192 match self {
193 Self::Tantivy => {
194 let habitat = crate::emit::framework(krate, &["transform"], "Habitat");
195 let initialize = crate::emit::framework(krate, &["drive"], "Initialize");
196 let shared = crate::emit::framework(krate, &["resource"], "Shared");
197 let maker = crate::emit::framework(krate, &["store"], "TantivySlotMaker");
198 let blueprint = self.blueprint(krate);
199 quote! {
200 impl #habitat for #name {
201 /// The corpora a declaration owns in THIS mount — one blueprint per election that
202 /// points here, each carrying its durable name, its columns and the `stored` posture
203 /// the declaration chose.
204 type Blueprint = #blueprint;
205 }
206
207 impl #initialize for #name {
208 /// The shipped slot maker, over this mount — the BLOCKING face, because opening a
209 /// tantivy index is two syscalls and no await.
210 type Visitor = #maker<Self>;
211
212 #[inline]
213 fn initializer(mount: #shared<Self>) -> Self::Visitor {
214 #maker::new(mount)
215 }
216 }
217 }
218 }
219 }
220 }
221
222 /// The two halves of the cargo gate this kind's emission rides — the OPEN one and its complement.
223 ///
224 /// The emission names types a build without the feature does not have, so it cannot be written
225 /// unconditionally, and a `#[cfg(feature = …)]` inside an expansion asks the DECLARING crate for a
226 /// feature it has never heard of. The gate pair is the crate's own answer to exactly that, and this
227 /// is which pair a kind spends.
228 #[inline]
229 #[must_use]
230 pub const fn gate(self) -> (&'static str, &'static str) {
231 match self {
232 Self::Tantivy => ("if_tantivy", "if_no_tantivy"),
233 }
234 }
235
236 /// What a build WITHOUT this engine is told, at the declaration that asked for it.
237 ///
238 /// It names the feature and the manifest, because that is the whole fix. The alternative — letting
239 /// the shut gate swallow the emission — leaves a reader an `AsyncResource` they never wrote and were
240 /// never going to write.
241 #[must_use]
242 pub fn absent(self) -> String {
243 format!(
244 "`#[ingraph::resource({word})]` needs `ingraph`'s `{word}` feature — the kind word emits this \
245 engine's own impls, and a build without the engine has no types for them to name. Add \
246 `features = [\"{word}\"]` to the `ingraph` dependency, or drop the word and write the \
247 resource's impls by hand (the foreign form).",
248 word = self.word()
249 )
250 }
251
252 /// The FIELD a kind word injects into the declaration — the engine the macro mints.
253 ///
254 /// The whole reason a resource macro is an ATTRIBUTE one: a builtin resource's author writes
255 /// `pub struct Ft;` and the engine underneath it is this crate's business, so the declaration the
256 /// compiler sees is not the declaration the author wrote. It is named the way every injected field
257 /// here is — a spelling nothing outside the emission writes — and it is PRIVATE, because the two
258 /// doors onto it are emitted beside it and are what a caller reaches.
259 #[must_use]
260 pub fn engine_field(self, krate: &syn::Path, prefix: &EmissionPrefix) -> syn::Field {
261 use syn::parse::Parser as _;
262
263 let ty: syn::Type = match self {
264 Self::Tantivy => syn::parse_quote!(#krate::__private::store::TantivyStore),
265 };
266 let name = engine_field(prefix);
267 syn::Field::parse_named
268 .parse2(quote!(#name: #ty))
269 .expect("a named field")
270 }
271
272 /// Everything this kind emits for the declaration `name`, under the crate `krate`.
273 ///
274 /// Three impls and one inherent block, and every one of them delegates:
275 ///
276 /// | item | what it says |
277 /// |---|---|
278 /// | `impl AsyncResource` | the store's own construction — `Options` and `Error` are the store's, and `build` is its open |
279 /// | `impl DeclaredResource` | the citizenship, carrying the mode the KIND knows |
280 /// | `impl FulltextEngine` | THE BASE: eight seats and the three address-lifecycle functions, projected off the store's per-slot handle |
281 /// | `impl FulltextStore` | THE PER-SLOT FACTORY — the mode's own face, and the door every corpus is opened through |
282 /// | `impl FulltextMount` | THE MODE-BLIND FACE over that factory, plus the manager it lends — what a WIRE DOOR names |
283 /// | `impl Habitat` | WHAT A HOME LOOKS LIKE here — the corpora a declaration owns in this mount |
284 /// | `impl Initialize` | LAYER TWO's machine: the shipped slot maker, on the face this kind's mode names |
285 /// | `impl <Type>` | `connection()` — the one fact a caller needs to bundle a `Connected` |
286 ///
287 /// # A RESOURCE IS A STORE, and it is NOT a corpus
288 ///
289 /// This is the grain the whole emission turns on. A resource is the MOUNT — a connection-manager
290 /// opened once, holding whatever pool or index root the deployment configured — and a SLOT is one
291 /// corpus inside it, named by the ELECTION that writes it: `<index>__<field>__<label>`, which is
292 /// `node × election` and is what boot slot-shape validation checks. Two elections pointing at ONE
293 /// resource are therefore TWO corpora with two universes of BM25 statistics, which is the whole
294 /// reason the grain is where it is: `docfreq` over `numdocs` and the average document length are
295 /// INDEX-WIDE, so a title and a body sharing a corpus would move each other's scores.
296 ///
297 /// An earlier draft named ONE corpus per resource, after the declaration's own snake name. That
298 /// read the resource as the corpus and left a deployment no way to hold two elections in one mount
299 /// without merging their statistics. The two-`TypeId` story — two same-kind resources being two
300 /// types and two `Shared<R>` lookups — is untouched and is what it always was: the answer for
301 /// genuinely TWO STORES, not the answer for two corpora.
302 ///
303 /// # The BASE is projections and nothing else, which is what makes delegation honest
304 ///
305 /// Every seat is written as `<TantivyFulltext as FulltextEngine>::…` rather than as the concrete
306 /// type it resolves to. So the day the engine changes one of them, this expansion changes with it
307 /// and no declaration has to be re-emitted against a copy that drifted. The three lifecycle
308 /// functions are ASSOCIATED ones, which is why the base needs no value at all to delegate.
309 ///
310 /// The base is also SLOT-BLIND — eight type seats and three address functions, not one of which
311 /// names a corpus — which is exactly why it can sit on the mount. It is [`the kind trait`]: a leg
312 /// writing `resource = "crate::Ft"` is verified by projecting through it, so a vector election
313 /// pointed at a full-text resource is `E0277` at the path its author wrote.
314 ///
315 /// # NO READ AND NO WRITE FACE, and the slot grain is why
316 ///
317 /// `FulltextRead::search` and `FulltextWrite::upsert` carry no slot parameter — the per-slot
318 /// HANDLE is what carries it, minted at the corpus name. A face on the mount would therefore have
319 /// to bake ONE corpus name into itself, which is the reading this emission just refused. So the
320 /// mount wears the FACTORY and the handle it mints wears the faces, and the two are never confused
321 /// because they are two types.
322 ///
323 /// # The mode's FIRST TRUE SPEND is which factory face is written
324 ///
325 /// [`mode`](Self::mode) picks `FulltextStore` for a blocking store and `AsyncFulltextStore` for an
326 /// awaited one. The pair differs in exactly one verb — `open` — because the per-slot factory is
327 /// synchronous and infallible on both faces, so `open` is the whole of what a mode can change
328 /// here. Tantivy's open is two syscalls and no await, so a `tantivy` resource is written on the
329 /// BLOCKING face; the transitional posture that bound the awaited face regardless ends at this
330 /// line.
331 ///
332 /// # …and the MOUNT is where that spend stops leaking outward
333 ///
334 /// Face selection happens AT THIS EMISSION and nowhere downstream, which is the whole reason
335 /// `FulltextMount` exists: a wire door is expanded at an ELECTION, in a crate that can see the
336 /// resource's path and not its mode, so a door written over either store face would serve half
337 /// the resources there are. The two templates here — `FulltextStore` at `Block`,
338 /// `AsyncFulltextStore` at `Async` — both close into one mode-blind seam, and the selection is
339 /// therefore paid once by the party that knows the answer.
340 ///
341 /// # The one inherent door, and why it is not the accessor family the module refuses
342 ///
343 /// `connection()` hands out the manager THIS MACRO opened. That is a fact about the field the
344 /// macro injected, not about anything the author wrote — so naming it here is this crate naming
345 /// its own mint, which is the opposite of putting a convention on somebody else's surface. A
346 /// caller needs it to bundle a [`Connected`](../../ingraph/struct.Connected.html), the connection
347 /// being the borrow every verb takes back.
348 #[must_use]
349 pub fn emit(
350 self,
351 krate: &syn::Path,
352 name: &syn::Ident,
353 prefix: &EmissionPrefix,
354 ) -> proc_macro2::TokenStream {
355 let engine = match self {
356 Self::Tantivy => tantivy(krate, name, self.mode(), prefix),
357 };
358 // LAYER TWO rides beside the engine and is written per KIND for the same reason the engine is:
359 // the word knows what a home looks like here and which machine makes one, so the two lines a
360 // foreign author writes by hand are written for a builtin.
361 let maker = self.maker(krate, name);
362 quote! {
363 #engine
364 #maker
365 }
366 }
367}
368
369/// A validated resource declaration, ready to emit.
370///
371/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a
372/// manifest front end later reach the same emitter.
373#[derive(Debug, Clone)]
374pub struct ResourceModel {
375 /// The EMISSION NAMESPACE this declaration's minted names wear.
376 ///
377 /// [`EmissionPrefix::INGRAPH`] for everything `ingraph`'s own front ends build, and a domain
378 /// framework's own mark for a model `mediagraph-codegen` or its successors build — see
379 /// [`crate::prefix`] for what the seat covers and why it is a field rather than a constant.
380 pub prefix: EmissionPrefix,
381 /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
382 /// another.
383 pub krate: syn::Path,
384 /// The declared type — what the citizenship is emitted for.
385 pub name: syn::Ident,
386 /// The BUILTIN ENGINE this declaration named in one word — `None` for the FOREIGN form, which is
387 /// the open seam and emits no engine impl at all.
388 pub kind: Option<ResourceKind>,
389 /// WHICH FACE this resource's engine impls wear.
390 ///
391 /// The `async` word where the declaration is foreign, and the KIND's own answer where it is not —
392 /// which is why the two are refused together: a builtin's mode is knowledge the word carries, and
393 /// a second opinion beside it could only disagree.
394 pub mode: ResourceMode,
395}
396
397impl ResourceModel {
398 /// The field a BUILTIN kind word injects into the host — `None` for the foreign form, whose
399 /// declaration is echoed exactly as written.
400 #[must_use]
401 pub fn carried_engine(&self) -> Option<syn::Field> {
402 self
403 .kind
404 .map(|kind| kind.engine_field(&self.krate, &self.prefix))
405 }
406
407 /// The IMPLS — the citizenship, and whatever a kind word adds beside it.
408 ///
409 /// The host is not here: an attribute macro replaces the item it sits on, and assembling the two is
410 /// [`expand`](Self::expand)'s job because only the caller holds the declaration. This is what a
411 /// reader asserts against.
412 #[must_use]
413 pub fn emit(&self) -> proc_macro2::TokenStream {
414 let krate = &self.krate;
415 let name = &self.name;
416 let sync = self.mode.sync();
417 // WHAT THE DECLARATION HOLDS. A builtin kind word answers it; the foreign form answers NOTHING
418 // and takes the trait's empty default, which is the conservative half of the sole-default law —
419 // a resource that has not said what it holds must not become the sole candidate for a leg it
420 // cannot serve.
421 let kinds = self.kind.map(|kind| {
422 let held = kind.kinds();
423 quote! {
424 const KINDS: #krate::__private::resource::ResourceKinds =
425 #krate::__private::resource::ResourceKinds::#held;
426 }
427 });
428 let citizenship = quote! {
429 impl #krate::__private::resource::DeclaredResource for #name {
430 const SYNC: bool = #sync;
431 #kinds
432 }
433 };
434 match self.kind {
435 None => citizenship,
436 Some(kind) => {
437 let engine = kind.emit(krate, name, &self.prefix);
438 quote! {
439 #citizenship
440 #engine
441 }
442 }
443 }
444 }
445
446 /// THE WHOLE EXPANSION — the declaration and the impls, assembled under whichever gate the
447 /// declaration's kind rides.
448 ///
449 /// `plain` is the author's own host, re-emitted; `carrying` is that host with
450 /// [`carried_engine`](Self::carried_engine) appended. THE HOST IS EMITTED WHETHER OR NOT the
451 /// declaration was accepted and whichever half of a gate survives, for the reason every attribute
452 /// macro in this family states: the macro replaces the item it sits on, so an expansion that
453 /// dropped the host would delete the type and bury its own message under every mention of it.
454 ///
455 /// The FOREIGN form has no gate and no injection, so it is the two token streams' concatenation and
456 /// nothing more — the semantics it has always had.
457 #[must_use]
458 pub fn expand(
459 &self,
460 plain: &proc_macro2::TokenStream,
461 carrying: &proc_macro2::TokenStream,
462 ) -> proc_macro2::TokenStream {
463 let emitted = self.emit();
464 let Some(kind) = self.kind else {
465 return quote! {
466 #plain
467 #emitted
468 };
469 };
470 let krate = &self.krate;
471 let (open, shut) = kind.gate();
472 let (open, shut) = (format_ident!("{open}"), format_ident!("{shut}"));
473 let absent = kind.absent();
474 quote! {
475 #krate::__private::gate::#open! {
476 #carrying
477 #emitted
478 }
479 #krate::__private::gate::#shut! {
480 #plain
481 ::core::compile_error!(#absent);
482 }
483 }
484 }
485}
486
487/// The name the injected engine is written under — a spelling nothing outside this module writes.
488///
489/// One function, so the field the injection APPENDS and the field the emitted bodies READ cannot be
490/// given two spellings. It is private for the reason the doors beside it are public: what a caller
491/// reaches is `connection()` and `SLOT`, and the field itself is the expansion's own business.
492fn engine_field(prefix: &EmissionPrefix) -> syn::Ident {
493 prefix.framed_ident("engine")
494}
495
496/// The `tantivy` kind word's whole emission — see [`ResourceKind::emit`] for what each item says.
497///
498/// Written as one function rather than as four, because the four share every path they name and the
499/// alternative is threading a dozen `syn::Path`s between them.
500///
501/// `mode` is READ rather than assumed: it names the construction face, and a kind whose store opens
502/// through a future would spell the awaited one at this same line. Passing it in is what makes the
503/// choice a spend of [`ResourceKind::mode`] instead of a constant this function happens to agree
504/// with.
505fn tantivy(
506 krate: &syn::Path,
507 name: &syn::Ident,
508 mode: ResourceMode,
509 prefix: &EmissionPrefix,
510) -> proc_macro2::TokenStream {
511 let engine = engine_field(prefix);
512
513 let store = quote!(#krate::__private::store::TantivyStore);
514 let handle = quote!(#krate::__private::store::TantivyFulltext);
515 let construction = match mode {
516 ResourceMode::Block => quote!(#krate::__private::store::FulltextStore),
517 ResourceMode::Async => quote!(#krate::__private::store::AsyncFulltextStore),
518 };
519 let base = quote!(#krate::__private::store::FulltextEngine);
520 let mount = quote!(#krate::__private::store::FulltextMount);
521 let bytes = quote!(#krate::__private::store::Utf8Bytes);
522 // THE RESOURCE CONTRACT's `build`, which asks for a future whichever face the store opens on —
523 // so it DELEGATES to the factory below rather than opening the store a second time, and the two
524 // modes differ only in what stands between them.
525 //
526 // A BLOCKING open answers a `Result`, so the awaited construction is that `Result` with `ready`
527 // around it: a wrapper over a value already computed, which is the one shape the dual-mode law
528 // admits. The reverse — a `block_on` around an awaited open — is the fiction it refuses, and no
529 // arm here writes one; the awaited face already answers a future and is forwarded untouched.
530 let opened = match mode {
531 ResourceMode::Block => quote! {
532 ::core::future::ready(<Self as #construction>::open(options))
533 },
534 ResourceMode::Async => quote!(<Self as #construction>::open(options)),
535 };
536 // THE FACTORY'S OWN `open`, whose SHAPE is the one thing the two store faces differ in: the
537 // blocking face answers a `Result` and the awaited one answers a future. Written out per mode
538 // rather than shared, because a shared body would have to pick one shape and wrap the other.
539 let open = match mode {
540 ResourceMode::Block => quote! {
541 /// Open the manager ONCE, on this thread — the store's own blocking open, with the mount
542 /// wrapped around what it returns.
543 #[inline]
544 fn open(options: Self::Options) -> ::core::result::Result<Self, Self::Error> {
545 <#store as #construction>::open(options).map(|#engine| Self { #engine })
546 }
547 },
548 ResourceMode::Async => quote! {
549 /// Open the manager ONCE — the store's own awaited open, with the mount wrapped around what
550 /// it resolves to.
551 #[inline]
552 fn open(
553 options: Self::Options,
554 ) -> impl ::core::future::Future<Output = ::core::result::Result<Self, Self::Error>>
555 + ::core::marker::Send {
556 async move {
557 <#store as #construction>::open(options)
558 .await
559 .map(|#engine| Self { #engine })
560 }
561 }
562 },
563 };
564
565 quote! {
566 impl #name {
567 /// The connection-manager this resource opened, borrowed — what a call's
568 /// `Connected` carries.
569 ///
570 /// One manager, opened once by `build` and held for the resource's life. It is handed out
571 /// rather than kept private because every verb reached through this mount takes it back: a
572 /// read reaches its slot's reader through it, and a write is queued into a writer taken on it.
573 #[inline]
574 #[must_use]
575 pub fn connection(&self) -> &#store {
576 &self.#engine
577 }
578 }
579
580 impl #krate::__private::resource::AsyncResource for #name {
581 /// The STORE's own construction input, projected rather than restated: whatever the store
582 /// takes to open is what this resource's `[resources.…]` section carries.
583 type Options = <#store as #construction>::Options;
584 /// The store's own refusal, for the same reason.
585 type Error = <#store as #construction>::Error;
586
587 /// One construction, reached through the FACTORY beside it: `build` is the resource tier's
588 /// name for the same act, so it delegates rather than opening the store a second time.
589 ///
590 /// The `ctx` seat is UNSPENT here and that is the honest state: what a store mount opens with
591 /// is its own options, and a resource that wants a resource built before it reads it through
592 /// this seat by hand rather than through an emission that cannot know which.
593 #[inline]
594 fn build(
595 _ctx: &#krate::__private::drive::Resources,
596 options: Self::Options,
597 ) -> impl ::core::future::Future<Output = ::core::result::Result<Self, Self::Error>>
598 + ::core::marker::Send {
599 #opened
600 }
601 }
602
603 impl #construction for #name {
604 /// The three seats are the STORE's, projected — a mount that restated any of them would be a
605 /// second copy to keep true.
606 type Options = <#store as #construction>::Options;
607 type Error = <#store as #construction>::Error;
608 /// THE PER-SLOT HANDLE — stateless, minted per corpus, and the type that wears the read and
609 /// write faces this mount deliberately does not.
610 type Handle = <#store as #construction>::Handle;
611
612 #open
613
614 /// ONE CORPUS of this mount, by name.
615 ///
616 /// The name is the ELECTION's — `<index>__<field>__<label>`, minted by the declaration that
617 /// writes the slot — and it arrives as a parameter for exactly that reason: a mount holds as
618 /// many corpora as elections point at it, and baking one name in here is the reading this
619 /// emission refuses. Sync and infallible, per the seam's own contract: a stateless handle
620 /// needs no I/O to mint.
621 #[inline]
622 fn fulltext(&self, slot: impl ::core::convert::Into<#bytes>) -> Self::Handle {
623 <#store as #construction>::fulltext(&self.#engine, slot)
624 }
625 }
626
627 impl #mount for #name {
628 /// The factory's own handle, projected — the mount seam adds no third opinion about what a
629 /// corpus of this store is.
630 type Handle = <Self as #construction>::Handle;
631
632 /// ONE CORPUS, by the election's durable name — the factory above, under the name a WIRE
633 /// DOOR can spell.
634 ///
635 /// The seam exists because a door cannot name the factory: which of the two store faces this
636 /// resource wears is decided by its MODE, and an election that points here is expanded
637 /// without that knowledge. So the mode is spent HERE, where the declaration knows it, and
638 /// every door downstream names one trait.
639 #[inline]
640 fn corpus(&self, slot: impl ::core::convert::Into<#bytes>) -> Self::Handle {
641 <Self as #construction>::fulltext(self, slot)
642 }
643
644 /// The manager, borrowed — what a `Connected` against any corpus of this mount carries.
645 #[inline]
646 fn connection(&self) -> &<Self::Handle as #base>::Connection {
647 &self.#engine
648 }
649 }
650
651 impl #base for #name {
652 type Options = <#handle as #base>::Options;
653 type SearchOptions = <#handle as #base>::SearchOptions;
654 type Error = <#handle as #base>::Error;
655 type Score = <#handle as #base>::Score;
656 type Address = <#handle as #base>::Address;
657 type Connection = <#handle as #base>::Connection;
658 type WriteBuffer = <#handle as #base>::WriteBuffer;
659 type ReadBuffer = <#handle as #base>::ReadBuffer;
660
661 #[inline]
662 fn buffer() -> Self::WriteBuffer {
663 <#handle as #base>::buffer()
664 }
665
666 #[inline]
667 fn finalize(buf: Self::WriteBuffer) -> Self::Address {
668 <#handle as #base>::finalize(buf)
669 }
670
671 #[inline]
672 fn open(address: Self::Address) -> Self::ReadBuffer {
673 <#handle as #base>::open(address)
674 }
675 }
676
677 }
678}