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
//! [`Label`]: the WORD a classifier put on something, validated for the one thing a word cannot be.

use core::{fmt, str::FromStr};

use smol_bytes::Utf8Bytes;

use crate::{
  ColumnKind, CursorValue, DefaultMarker, StringFilterMarker, StringMarker, TextFilter, TextWire,
  column::column_eq,
};

#[cfg(test)]
mod tests;

/// **A CLASSIFICATION'S WORD** — what a detector, a classifier or a tagger says a thing IS.
///
/// A [`Utf8Bytes`] underneath, and a different type for the reason every newtype in
/// [`primitives`](crate::primitives) is one: it carries an INVARIANT its representation cannot
/// state. A label is a word somebody said, and *nothing at all* is not one — so [`new`](Self::new)
/// is the only way in and it refuses the empty case.
///
/// # THE ENGINE OWNS NORMALISATION, AND THIS TYPE OWNS EXISTENCE
///
/// **This type does not fold case, and it never will.** The division is the producer's, stated in
/// `avanalyze`'s own contract: *the engine lowercases and trims image-classification labels but
/// passes animal labels through verbatim, and uses the literal `"person"` for human subjects — the
/// label vocabulary is Apple's, not this crate's*. One producer therefore emits `cat` and `Golden
/// Retriever` from the same run, deliberately, and a type that lowercased them both would be a type
/// overruling the engine about a vocabulary the engine owns.
///
/// So `Cat` and `cat` are TWO labels here. A caller that wants them to be one asks with
/// `containsNocase` or `eqNocase`'s neighbours on [`TextFilter`], which is where a case question
/// belongs: a QUERY's, asked per query, rather than a value's, decided once for everybody at a
/// constructor.
///
/// # WHAT IS REFUSED, and it is one rule
///
/// A label that is empty, **or that is nothing but whitespace**. The second clause is the first one
/// read honestly: `"   "` is a string a producer sent by accident, it names nothing, and admitting
/// it would put a row in a table whose label no query can ever match and no reader can ever see.
///
/// **The whitespace is a PREDICATE and never a transform.** `Label::new("  cat  ")` succeeds and
/// holds `"  cat  "` — the six characters it was handed, byte for byte. That is the division above
/// kept where it would have been easiest to bend: trimming is normalisation, normalisation is the
/// engine's, and this crate has no trim-at-a-constructor anywhere else either. What the trim decides
/// is *whether there is a word here*, not *what the word is*.
///
/// It follows that a value this crate wrote reads back byte for byte at every door — the decode, the
/// cursor and the document all re-enter [`new`](Self::new), and a constructor that rewrites nothing
/// admits exactly what it was given.
///
/// # NO VOCABULARY, and that is the ruling rather than an omission
///
/// A label is an OPEN word. Every model ships its own roster — Apple's image classifier, a
/// zero-shot tagger, a barcode symbology reader — the rosters disagree, and none of them is a
/// standard this crate could hold a table of. So there is no enum here and none is coming: an
/// `#[ingraph::enumerate]` vocabulary over a model's output would be a closed surface over an open
/// world, which is the one shape this framework does not build. See
/// [`lang`](crate::primitives::lang), where the opposite case is argued — a language IS a standard,
/// so it IS a type family.
///
/// # Examples
///
/// ```
/// use ingraph::Label;
///
/// assert_eq!(Label::new("golden retriever").unwrap().as_str(), "golden retriever");
///
/// // Case is the ENGINE's, so two spellings are two labels.
/// assert_ne!(Label::new("Cat").unwrap(), Label::new("cat").unwrap());
///
/// // The whitespace decides whether there is a word, and never what the word is.
/// assert!(Label::new("").is_err());
/// assert!(Label::new("   ").is_err());
/// assert_eq!(Label::new("  cat  ").unwrap().as_str(), "  cat  ");
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Label(Utf8Bytes);

impl Label {
  /// Construct a label, or refuse a value that is not one.
  ///
  /// Takes anything the crate's text carrier is built from — a `&str`, a [`String`], a
  /// [`Utf8Bytes`] already in hand — so a caller holding an owned word hands it over rather than
  /// copying it, and `Label::new(Utf8Bytes::from_static("person"))` is the door a compile-time word
  /// takes with no allocation at all.
  ///
  /// # Errors
  ///
  /// [`EmptyLabel`] where the text is empty or holds nothing but whitespace. It is the only refusal
  /// this type has — see the type's note, where the case question is answered.
  pub fn new(text: impl Into<Utf8Bytes>) -> Result<Self, EmptyLabel> {
    let text = text.into();

    if text.as_str().trim().is_empty() {
      return Err(EmptyLabel);
    }

    Ok(Self(text))
  }

  /// The word, as text.
  #[inline]
  #[must_use]
  pub fn as_str(&self) -> &str {
    self.0.as_str()
  }

  /// The word, as the carrier it is held in.
  #[inline]
  #[must_use]
  pub fn into_inner(self) -> Utf8Bytes {
    self.0
  }
}

/// The word itself, with nothing around it.
impl fmt::Display for Label {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(self.as_str())
  }
}

/// The word QUOTED, under the type's own name — which is what makes a whitespace-carrying label
/// visible in a test failure instead of vanishing into the alignment.
impl fmt::Debug for Label {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "Label({:?})", self.as_str())
  }
}

impl FromStr for Label {
  type Err = EmptyLabel;

  #[inline]
  fn from_str(text: &str) -> Result<Self, Self::Err> {
    Self::new(text)
  }
}

impl AsRef<str> for Label {
  #[inline]
  fn as_ref(&self) -> &str {
    self.as_str()
  }
}

/// The label, as the carrier it holds.
///
/// ONE direction, which is the type's whole subject: `From<Utf8Bytes> for Label` would say that any
/// text IS a label, and the empty string is the counter-example this newtype exists to keep out of a
/// row. Minting one is [`Label::new`], where the caller meets the refusal.
impl From<Label> for Utf8Bytes {
  #[inline]
  fn from(label: Label) -> Self {
    label.into_inner()
  }
}

/// What gives `String: TryFrom<Label>` through std's blanket, which is the crossing a `TEXT`
/// column's comparison makes — and it makes it with `Error = Infallible`, a label being valid text
/// by construction.
impl From<Label> for String {
  #[inline]
  fn from(label: Label) -> Self {
    Self::from(label.as_str())
  }
}

/// **What a label refuses a value with** — one sentence, at the four doors that mint one from the
/// outside: a caller's constructor, a stored column, a cursor a client handed back, and a wire
/// operand.
///
/// It carries no value, which is [`OutsideTheUnitInterval`](crate::OutsideTheUnitInterval)'s own
/// shape and its reason: what is wrong is a property of the text the caller already has in hand, and
/// a copy of nothing would be a second spelling of an empty string. The COLUMN's name arrives with
/// the [`sqlx::Error::ColumnDecode`] this is wrapped in, and a wire operand travels back to a client
/// in async-graphql's own error context.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EmptyLabel;

impl fmt::Display for EmptyLabel {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str("a label is a word: it holds at least one character that is not whitespace")
  }
}

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

/// **ONE column**, which is the default — stated rather than inherited, because the two composites
/// in this house read their own widths off this row and a reader auditing them should find the
/// answer here rather than the absence of one.
impl ColumnKind for Label {}

// A label is the same as a label when its bytes are, byte for byte — no case fold, no trim: the
// engine owns normalisation and this type owns only whether a word is there at all.
column_eq! { Label }

/// **THE STORED WORD is text's**, in every dialect that has one.
///
/// Delegated to [`String`] rather than named, for the reason the bind below is: a label IS its text,
/// so the column is a text column and the dialect's own word for one is the only answer. The
/// delegation carries the ADMISSION with it — a label is declarable exactly where text is, which is
/// everywhere.
///
/// The non-emptiness is kept by the DECODE rather than by the schema; no dialect here has a `CHECK`
/// this crate emits. See the assemble row below, which refuses.
impl<Db> crate::StoredAs<Db> for Label
where
  String: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = <String as crate::StoredAs<Db>>::WORDS;
}

/// **ONE BIND OUT** — the word, as text.
///
/// An OWNED [`String`] rather than the borrowed `&str` the slot already holds, and the reason is
/// [`sqlx::QueryBuilder`]'s own lifetime rather than a preference: `push_bind` requires its value to
/// outlive the builder's `'args`, which this trait's signature leaves unrelated to `&self`, so a
/// borrow of `self` cannot satisfy it. That is the same copy every text newtype in
/// [`primitives`](crate::primitives) pays at this seat.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for Label
where
  Db: sqlx::Database,
  String: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <String as crate::Carrier<Db>>::push_bind(&String::from(self.as_str()), qb);
  }
}

/// **AND THE WORD BACK IN**, through the constructor rather than around it.
///
/// A database is exactly the place that can hand back a value this type says cannot exist — a
/// hand-written `UPDATE`, a restore, a column shared with something else — so the read refuses
/// rather than substituting a placeholder. That is [`Count`](crate::Count)'s posture at its own
/// column and every subtag's at theirs: loudly, at the row that held it, never a value quietly
/// minted around the hole.
#[cfg(feature = "sqlx")]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for Label
where
  String: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let stored: String = <String as crate::Assemble<'a, R>>::assemble(row, under)?;

    Self::new(stored).map_err(|refused| sqlx::Error::Decode(Box::new(refused)))
  }
}

/// **THE KEYSET POSITION**: the word's UTF-8 bytes, which is byte for byte what [`Utf8Bytes`]' own
/// row writes — so a label column and a text column page past the same cursor.
///
/// No framing is added, and none may be: a cursor slot is already length-delimited by the layer
/// above, so a row for a variable-width value writes the value and nothing else. The read
/// RE-VALIDATES because a cursor is a string a CLIENT hands back — a forged empty position is
/// refused rather than turned into a label whose type says it cannot exist.
impl CursorValue for Label {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(self.as_str().as_bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Self::new(Utf8Bytes::try_from(bytes).ok()?).ok()
  }
}

/// **THE DOCUMENT'S FORM: a BSON `String`** — the same text the `TEXT` column above binds, at the
/// one BSON type that holds it.
///
/// A label is ONE WORD, so there is nothing here of a composite's key-set question. This row is the
/// FILTER OPERAND's form and not a serde row, which is the posture every storage type this crate
/// ships takes — see [`Timestamp`](crate::Timestamp)'s, where the `E0277` a bare column earns at a
/// declaration is named.
#[cfg(feature = "mongo")]
impl crate::MongoCarrier for Label {
  #[inline]
  fn to_bson(&self) -> bson::Bson {
    bson::Bson::String(String::from(self.as_str()))
  }
}

/// **THE READ: the same word, back through the door** — [`MongoCarrier`](crate::MongoCarrier)'s
/// mirror.
///
/// A `string` field is exactly as untrusted as the `TEXT` column [`Assemble`](crate::Assemble) above
/// reads: nothing stops a document holding `""`, one written before this type existed, or one
/// written by hand for a test. So the read goes through [`Label::new`] rather than wrapping the
/// bytes.
#[cfg(feature = "mongo")]
impl crate::query::mongo::MongoExtract for Label {
  const BSON: &'static str = "string";

  fn extract(value: Option<&bson::Bson>) -> Result<Self, crate::query::mongo::MongoTypeError> {
    match value {
      Some(bson::Bson::String(text)) => Self::new(text.as_str()).map_err(|_refused| {
        crate::query::mongo::MongoTypeError::Range(
          "this field holds a string that is empty or nothing but whitespace, which is no label",
        )
      }),
      Some(other) => Err(crate::query::mongo::MongoTypeError::wrong_type(
        Self::BSON,
        crate::query::mongo::alias(other),
      )),
      None => Err(crate::query::mongo::MongoTypeError::Absent),
    }
  }
}

/// **The TEXT reading**, which is what an open vocabulary earns.
///
/// A label takes the twenty-slot [`TextFilter`] rather than the eight-slot
/// [`ScalarFilter`](crate::ScalarFilter) the [`lang`](crate::primitives::lang) subtags take, and the
/// difference is what the two words ARE. A subtag is one token of a closed grammar, so *does it
/// start with* is a question about spelling rather than about meaning. A label is FREE TEXT from a
/// model's own roster — `golden retriever`, `traffic light`, `person` — so `contains: "retriever"`
/// is a real question a real client asks, and the `nocase` half of every affix slot is where the
/// case this type refuses to fold gets asked about instead.
///
/// The lexical ORDERING slots come with the kind and they are honest here: text has a byte order,
/// [`Utf8Bytes`] publishes a filter carrying `gt`/`gte`/`lt`/`lte` over exactly that order, and the
/// non-emptiness rule disturbs none of it. A label column is an ORDER SUBJECT in the same breath —
/// see the [`CursorValue`] row above, which is what a page walks.
impl StringFilterMarker for Label {
  type Filter = TextFilter<Label, LabelWire>;
}

/// The interpretation a [`Label`] field is read under — the TEXT family's, which is what puts
/// `Option<Label>` on the `isNull` road rather than on a collection's.
impl DefaultMarker for Label {
  type Marker = StringMarker<Label>;
}

/// How a label crosses when the framework's own text filter holds it — the reading that gives
/// `TextFilter<Label, LabelWire>` a face.
///
/// A marker carrying the wire NAME beside the operand, which is the shape every registered text
/// filter here takes: `TextFilter<S, I>`'s second parameter is what its input object is called, so a
/// filter over a label is named by a TYPE rather than by a table only this crate could extend. It is
/// the surface a declaring crate joins through, and this house is the framework's own worked example
/// of doing so with a validated newtype.
///
/// **The carrier is [`String`] and the crossing is FALLIBLE**, which is the whole difference from
/// the [`lang`](crate::primitives::lang) subtags' [`ScalarWire`](crate::ScalarWire) rows: those
/// types ARE their own GraphQL scalars, so a refusal happens at the scalar's door and the crossing
/// is [`Infallible`](core::convert::Infallible). A label publishes NO scalar of its own — see the
/// module note, where the retirement that decided it is cited — so this row is the door, and
/// `{ eq: "" }` meets [`EmptyLabel`] here.
pub enum LabelWire {}

impl TextWire<Label> for LabelWire {
  const NAME: &'static str = "LabelFilter";

  type Carrier = String;
  type Error = EmptyLabel;

  #[inline]
  fn cross(carrier: String) -> Result<Label, Self::Error> {
    Label::new(carrier)
  }

  #[inline]
  fn carry(operand: &Label) -> String {
    String::from(operand.as_str())
  }
}

/// **THE CROSSING IN — a label arrives as the roster's own `String`**, and the non-emptiness is kept
/// HERE.
///
/// No `#[Scalar]` of its own, and the absence is [`NormCoord`](crate::NormCoord)'s ruling one house
/// over rather than an omission: a named scalar has to say something the roster does not, and what a
/// `Label` scalar would have said is NON-EMPTY — a constructor's promise rather than a grammar,
/// which a client can act on nowhere. So a label column and a plain text column publish one SDL
/// scalar, the rule reaches a reader through the FIELD's documentation, and every operand reaches it
/// through [`Label::new`], which this row calls.
#[cfg(feature = "async-graphql")]
impl crate::ToGraphqlInput for Label {
  type Input = String;
  type Error = EmptyLabel;

  #[inline]
  fn cross(input: String) -> Result<Self, EmptyLabel> {
    Self::new(input)
  }

  #[inline]
  fn carry(operand: &Self) -> String {
    String::from(operand.as_str())
  }
}

/// **AND OUT**, mirroring the row above so the two directions cannot come to disagree.
///
/// A BORROW of the text rather than of the value, which is [`Utf8Bytes`]' own bargain at this seat:
/// the label has no scalar to be returned as, so what a field yields is the string it holds.
#[cfg(feature = "async-graphql")]
impl crate::ToGraphqlOutput for Label {
  type Output<'a> = &'a str;

  #[inline]
  fn to_graphql_output(marked: &Self) -> &str {
    marked.as_str()
  }
}