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
//! The language house's wire faces, behind the `async-graphql` feature.
//!
//! Every subtag type crosses as a SCALAR and as the SAME scalar in both seats — the shape a value
//! that is ONE WORD has. There is no operand newtype beside any of them and no input object
//! restating one, because neither is publishing an object a scalar of the same name would collide
//! with.
//!
//! ```text
//! scalar Language
//! ```
//!
//! # WIDE IN, STRICT OUT — and the wide half is the type's, not this module's
//!
//! A door here reads a JSON string and hands it to the type's own `new`, so the spellings it
//! admits are exactly the ones that type documents and there is no second grammar to keep in step.
//! What this layer adds is the JSON shape: a string, and the refusal a client gets for anything
//! else.
//!
//! **A NUMBER is refused on every one of them**, which is worth a sentence because one of the three
//! subtag grammars is digits. `419` is a region subtag and `Region`'s door reads it — from the
//! STRING `"419"`. A JSON number has no leading zeros, so `001` — the M.49 code for *World* — could
//! not survive the round trip as one, and admitting `419` while refusing `001` would be a door
//! whose grammar depended on which area a client asked about.

use async_graphql::{InputValueError, InputValueResult, Object, Scalar, ScalarType, Value};

use super::{DetectedLanguage, Language, LanguageId, LanguageIdOperand, Region, ScriptSubtag};

#[cfg(test)]
mod tests;

/// Generate one subtag type's SCALAR DOOR — the JSON shape, and nothing about the subtag grammar.
///
/// The three bodies are the same three bodies: read a string, hand it to the type's own `new`,
/// refuse everything else, and write back the canonical text. Writing them out three times would be
/// three chances for one of them to admit a JSON shape the others do not.
///
/// **The DESCRIPTION is passed in and not generated**, which is the whole reason this takes a doc
/// block rather than deriving one. async-graphql publishes the doc comment as the scalar's SDL
/// description, so it is the sentence a client reads to learn what the operand is — the one part of
/// a door that cannot be shared, and the one a reader of this module comes for.
macro_rules! subtag_scalar {
  ($(#[$description:meta])* $subtag:ident, $name:literal, $error:ident) => {
    $(#[$description])*
    // The GraphQL name is SPELLED rather than derived from the Rust one, as `SoundEventCode`'s is:
    // a wire name is a schema commitment, and a Rust rename is not a schema change.
    #[Scalar(name = $name)]
    impl ScalarType for $subtag {
      fn parse(value: Value) -> InputValueResult<Self> {
        match &value {
          Value::String(text) => Self::new(text).map_err(InputValueError::custom),
          _ => Err(InputValueError::expected_type(value.clone())),
        }
      }

      /// The SOLE notion of validity, shared with [`parse`](ScalarType::parse) so that a query which
      /// validates is a query which parses. async-graphql's default answers `true` for every value,
      /// so a scalar narrowing in `parse` alone ships a validator admitting what its own parser
      /// rejects — and the refusal then lands at execution rather than at validation, where a client
      /// is looking.
      ///
      /// What sharing it costs is the SENTENCE: validation runs before any resolver and reads a
      /// `bool`, so a client sending a bad operand is told the type its value could not become and
      /// not which rule it broke. The
      #[doc = concat!("[`", stringify!($error), "`](super::", stringify!($error), ")")]
      /// sentences are what a caller holding a value gets.
      #[inline]
      fn is_valid(value: &Value) -> bool {
        match value {
          Value::String(text) => Self::new(text).is_ok(),
          _ => false,
        }
      }

      /// STRICT OUT: the canonical subtag, whichever spelling came in.
      #[inline]
      fn to_value(&self) -> Value {
        Value::String(String::from(self.as_str()))
      }
    }
  };
}

subtag_scalar! {
  /// A BCP 47 primary language subtag, read WIDE and written back canonical: `"de"`, `"DE"`, `"ger"`
  /// (an mkv's ISO 639-2/B) and `"deu"` (an mp4's 639-2/T) are one operand, and it is written back
  /// as `de`.
  ///
  /// `"iw"` is `he`, `"in"` is `id` — the registry's `Preferred-Value` column, applied at the door.
  ///
  /// `"und"` is an ordinary value meaning *undetermined*, and it is NOT the way to say a track has
  /// no language: an absent language is `null`, and the difference is between a muxer that looked
  /// and could not tell and a muxer that never looked.
  ///
  /// A subtag the registry does not carry is ACCEPTED — the structure is what is checked here, and a
  /// vendored registry is a snapshot. What is refused is a string that is not a subtag's SHAPE:
  /// `zh_CN` for its underscore, `e` for its length, `日本語` for its characters.
  Language, "Language", ParseLanguageError
}

subtag_scalar! {
  /// An ISO 15924 script subtag, read WIDE and written back in the registry's Titlecase: `"Latn"`,
  /// `"latn"` and `"LATN"` are one operand, and it is written back as `Latn`.
  ///
  /// EXACTLY four letters. There is no shorter or longer form of a script code, so `"Lat"` and
  /// `"Latin"` are both refused.
  ///
  /// **`"Hans"` and `"Hant"` are two different operands and nothing folds them together.** Simplified
  /// and traditional Han are different writing systems, and which one a track declared is a fact
  /// about the track; what a SEARCH across them should do belongs to a retrieval layer with a query
  /// and a corpus to weigh, not to a scalar's door.
  ///
  /// `"Zxxx"` (*unwritten*) and `"Zzzz"` (*uncoded*) are ordinary values, and neither is the way to
  /// say a track declared no script: that is `null`.
  ScriptSubtag, "ScriptSubtag", ParseScriptSubtagError
}

subtag_scalar! {
  /// A region subtag, read WIDE and written back in the registry's own spelling: `"DE"`, `"de"` and
  /// `"dE"` are one operand and come back as `DE`.
  ///
  /// TWO grammars, because BCP 47 gives a region two: an ISO 3166-1 country code of two letters, or
  /// a UN M.49 area code of three digits — `"419"` is *Latin America and the Caribbean*, `"001"` is
  /// *World*. Both arrive as STRINGS. A JSON number is refused, and the leading zeros are why:
  /// `001` could not survive the round trip as one, and a door that took `419` while refusing `001`
  /// would have a grammar that depended on which area a client asked about.
  ///
  /// `"BU"` is `MM` — the registry's `Preferred-Value` column, applied at the door. `"SU"` stays
  /// `SU`: it is deprecated and the registry names no successor, the USSR having become several.
  ///
  /// `"ZZ"` is an ordinary value. The registry calls it *Private use*; a muxer writes it meaning
  /// *no region*. Either way it is not the way to say a track declared none, which is `null`.
  Region, "Region", ParseRegionError
}

/// A whole BCP 47 language tag, read WIDE and written back canonical: `"zh_Hans_CN"`, `"ZH-hans-cn"`
/// and `"zh-Hans-CN"` are one operand, and it comes back as `zh-Hans-CN`.
///
/// Each subtag goes through its own type's door, so every fold those documents applies here too:
/// `"ger-Latn-de"` is `de` — the alpha-3 fold on the language, the suppression removing a script
/// German already implies, and the case fold on the region.
///
/// `"i-klingon"` is `tlh` and `"zh-guoyu"` is `cmn`: the registry's grandfathered table, applied to
/// the whole tag before it is taken apart.
///
/// Everything past the region — variants, extensions, the private-use sequence — is carried
/// VERBATIM and is part of the identity. `"en-US-x-Foo"` and `"en-US-x-foo"` are two operands.
///
/// A tag whose subtags are structurally sound but unregistered is ACCEPTED, as each subtag type
/// accepts one of its own. What is refused is a shape: `"i-default"` for its one-letter primary
/// subtag, `"en--US"` for its empty subtag, `"zh-Hans-XYZ"` for a region that is neither two letters
/// nor three digits.
///
/// The SAME text a client reads back from a `LanguageId`'s `tag` field is what this operand takes,
/// which is what makes the pair a round trip.
// A named operand rather than the object's own name, for the reason `TimebaseOperand` carries:
// GraphQL keeps objects and input types in one namespace, and `LanguageId` is an object.
#[Scalar(name = "LanguageIdOperand")]
impl ScalarType for LanguageIdOperand {
  fn parse(value: Value) -> InputValueResult<Self> {
    match &value {
      Value::String(text) => super::LanguageId::new(text)
        .map(Self::new)
        .map_err(InputValueError::custom),
      _ => Err(InputValueError::expected_type(value.clone())),
    }
  }

  /// The SOLE notion of validity, shared with [`parse`](ScalarType::parse) — see the subtag doors,
  /// where the argument is the same one.
  #[inline]
  fn is_valid(value: &Value) -> bool {
    match value {
      Value::String(text) => super::LanguageId::new(text).is_ok(),
      _ => false,
    }
  }

  /// STRICT OUT: the canonical tag, whichever spelling came in.
  #[inline]
  fn to_value(&self) -> Value {
    Value::String(self.get().to_string())
  }
}

/// One whole language identity — the tag a track declared, taken apart into the seats a query can
/// reach.
///
/// FIVE fields where four columns are stored, and the extra one is the RENDERING: `tag` is what the
/// four seats spell together, and it is what a client sends back as a `LanguageIdOperand`. Publishing
/// it is what makes the pair a round trip — a value a client can read but not send back would be a
/// filter half the vocabulary cannot use.
#[Object]
impl LanguageId {
  /// The canonical tag — `de`, `zh-Hans`, `en-US-x-lorem`. The form a filter operand takes.
  #[doc(hidden)]
  #[graphql(name = "tag")]
  async fn __async_graphql_tag__(&self) -> String {
    self.to_string()
  }

  /// The primary language subtag, which every identity has.
  #[doc(hidden)]
  #[graphql(name = "language")]
  async fn __async_graphql_language__(&self) -> Language {
    self.language().clone()
  }

  /// The script, where one was declared and the language does not already imply it. Null for `en`,
  /// which implies Latin — and null for `en-Latn`, which said the same thing twice.
  #[doc(hidden)]
  #[graphql(name = "script")]
  async fn __async_graphql_script__(&self) -> Option<ScriptSubtag> {
    self.script().cloned()
  }

  /// The region, where one was declared; null otherwise.
  #[doc(hidden)]
  #[graphql(name = "region")]
  async fn __async_graphql_region__(&self) -> Option<Region> {
    self.region().cloned()
  }

  /// Everything past the region — variants, extensions and the private-use sequence — verbatim, or
  /// null where the tag has none. Not parsed and not case-folded: it is carried as the file spelled
  /// it.
  #[doc(hidden)]
  #[graphql(name = "rest")]
  async fn __async_graphql_rest__(&self) -> Option<String> {
    self.rest().map(|rest| String::from(rest.as_str()))
  }
}

/// One detected language: the identity a detector decided on, and how confident it was.
///
/// The identity's fields are FLATTENED here rather than nested behind a `language` object, so
/// reading a detection's tag costs no extra selection set — the shape `SoundEventDetection` takes,
/// for the same reason. The confidence sits beside them.
#[Object]
impl DetectedLanguage {
  /// The detected tag — `de`, `zh-Hans`. The form a filter operand takes.
  #[doc(hidden)]
  #[graphql(name = "tag")]
  async fn __async_graphql_tag__(&self) -> String {
    self.language().to_string()
  }

  /// How confident the detector was, in `[0.0, 1.0]`.
  // `f32`, the width's own roster scalar, reached through the confidence's OUTPUT crossing: the
  // `Score` scalar is retired, and the interval it stated is `Score::new`'s promise, said to a
  // client in the line above rather than in a scalar's name.
  #[doc(hidden)]
  #[graphql(name = "confidence")]
  async fn __async_graphql_confidence__(&self) -> crate::F32 {
    <crate::Score as crate::ToGraphqlOutput>::to_graphql_output(&self.confidence())
  }

  /// The detected primary language subtag.
  #[doc(hidden)]
  #[graphql(name = "language")]
  async fn __async_graphql_language__(&self) -> Language {
    self.language().language().clone()
  }

  /// The detected script, where the detector named one and the language does not imply it. Null for
  /// a detector that emits bare language codes, which is most of them today.
  #[doc(hidden)]
  #[graphql(name = "script")]
  async fn __async_graphql_script__(&self) -> Option<ScriptSubtag> {
    self.language().script().cloned()
  }

  /// The detected region, where the detector named one; null otherwise.
  #[doc(hidden)]
  #[graphql(name = "region")]
  async fn __async_graphql_region__(&self) -> Option<Region> {
    self.language().region().cloned()
  }

  /// Everything past the region, verbatim, or null where the tag has none.
  #[doc(hidden)]
  #[graphql(name = "rest")]
  async fn __async_graphql_rest__(&self) -> Option<String> {
    self
      .language()
      .rest()
      .map(|rest| String::from(rest.as_str()))
  }
}