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
use core::marker::PhantomData;

use super::*;

/// The QUANTIFIED collection filter — two operators over a collection column, generic over the
/// element type `T`: `any` asks whether SOME element satisfies a whole element predicate, and
/// `count` asks about the collection's LENGTH. There is no third.
///
/// # What it is FOR: an element with no honest LITERAL form
///
/// [`ListFilter`] and [`SetFilter`] each carry seven slots holding the element itself — six whole
/// collection operands and `has_element` — and putting an element on the wire is what their faces
/// ask [`ToGraphqlInput`](crate::ToGraphqlInput) for. That bound is the right one there and it is a
/// CONSEQUENCE rather than a convention: an operator whose operand is an element cannot be published
/// without publishing the element's literal form.
///
/// A great many element types have no such form that is worth publishing. A detection pair
/// `(code, score)` is the case this kind was cut for: `score` is a float, so
///
/// - **`hasElement` is a lie**. Membership is exact equality, and exact equality against a float
///   operand a client typed is false for every row that is not bit-identical. The operator would
///   compile, render, execute, and answer *no rows* to a question the caller believed they had
///   asked.
/// - **the four ordering operators are unstatable**. `gt` compares two whole collections
///   element-wise and lexicographically, so `gt: [{code: "cat", score: 0.4}]` asks whether this
///   detection list sorts after that one under an order composed of a string's and a float's. There
///   is no reading of that a client can act on, and none this crate could document.
/// - **`eq` and `ne` are the same shape of unusable**. Whole-collection equality over a float-bearing
///   element is exact equality per element, so it inherits `hasElement`'s falseness and multiplies it
///   by the collection's length.
///
/// So the narrow kind is not a subset taken for economy. **A schema publishes only the words it can
/// answer honestly**, and the seven that leave are the seven that could not be.
///
/// # Two KINDS and two NAMES, never one name with a conditional field list
///
/// A `Vec<Detection>` column reaches `DetectionQuantifiedFilter` and a `Vec<String>` column reaches
/// `StringListFilter`; the two are different input objects with different field lists under different
/// names. That is the NAMING CONSTITUTION's own rule — one wire name pins one vocabulary — and it is
/// why this is a type rather than a `ListFilter` whose face drops fields when the element cannot
/// cross. A face that varied its field list by a bound would publish a schema whose shape a client
/// could not predict from the name, and two clients reading `SomethingListFilter` would be reading
/// two different objects.
///
/// It is also the split [`ListFilter`] and [`SetFilter`] already are, and for a related reason: a
/// marker deciding which OPERATORS exist is a second kind rather than a rendering of one.
///
/// # `T` is carried and never held, and that is what the wire face proves
///
/// The element type appears in no slot — it is [`PhantomData`] — so this kind's face asks NOTHING of
/// it. Not [`ToGraphqlInput`](crate::ToGraphqlInput), not [`InputType`](async_graphql::InputType),
/// not [`Send`], not [`Sync`]: read the `where` clause on the [`InputType`](async_graphql::InputType)
/// row below and the only bound there is `VF`'s. **That is the whole deliverable**, stated by the
/// compiler rather than by this paragraph.
///
/// It is carried all the same, for the reason `VF` has a DEFAULT: `QuantifiedFilter<Detection>` is a
/// whole spelling and resolves the element's own filter through the same marker chain
/// `ListFilter<Detection>` resolves it through. Dropping `T` would make every spelling name the
/// element's FILTER — `QuantifiedFilter<DetectionFilter>` — which reads, beside `ListFilter<Detection>`,
/// as a collection of `DetectionFilter`. The parameter list is part of the family law, and a kind
/// that swaps into a collection seat should swap in one word.
///
/// # `VF` is the ELEMENT's filter, and it is what `any` asks with
///
/// [`ListFilter`]'s parameter, in every respect — the same default, reached through
/// `<<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter`, and a DEFAULT rather than a bound so
/// that an element with no reading at all is still filterable by naming `VF` outright. See it.
///
/// The element's filter is where the element's honest questions live. A detection's own filter names
/// its fields — `code` as an enumeration, `score` as a range — so the narrow collection kind loses
/// nothing a caller could have asked: `any: { score: { gte: 0.8 } }` is the question `hasElement`
/// pretended to be able to ask, and it is answerable.
///
/// # `any` on an EMPTY inner filter is a predicate, and `count` on an empty one is not
///
/// Carried word for word from [`ListFilter::is_empty`], because it is the same two slots and the
/// same quantifier: `∃x ∈ S. true` is `S ≠ ∅`, which is a predicate and not the absence of one,
/// while asking no question about one number excludes no row. The two slots this kind has are exactly
/// the two the wide kinds treat unlike each other, so the reading had to travel with them.
///
/// # There is no `try_map`, and the absence is total rather than partial
///
/// [`ListFilter::try_map`] converts every ELEMENT operand and passes `any` and `count` through
/// untouched. Seven of its nine slots hold elements and this kind has none of them, so the method
/// here would convert nothing and return `Self` under another name. What a nested filter's operands
/// need is its own crossing, exactly as it is one kind over.
///
/// # Examples
///
/// The two operators, and the emptiness reading that separates them:
///
/// ```
/// use ingraph::{GraphqlFilter, QuantifiedFilter, ScalarFilter};
///
/// // A quantified filter over a `Vec<i64>` column, asked in the element's own vocabulary.
/// let some_big = QuantifiedFilter::<i64>::new().with_any(ScalarFilter::new().with_gt(1_000));
/// assert!(!some_big.is_empty());
///
/// // `∃x. true` is *this collection has an element*, so a present `any` is never empty.
/// let non_empty = QuantifiedFilter::<i64>::new().with_any(ScalarFilter::new());
/// assert!(!non_empty.is_empty());
///
/// // A present `count` holding an unasked question is, because nothing quantifies it.
/// let unasked = QuantifiedFilter::<i64>::new().with_count(ScalarFilter::new());
/// assert!(unasked.is_empty());
/// ```
///
/// The seven whole-collection operators are absent from the TYPE, so asking one is a compile error
/// at the call site rather than a refusal at a crossing — the posture [`SetFilter`]'s missing
/// ordering operators already take:
///
/// ```compile_fail,E0599
/// let _ = ingraph::QuantifiedFilter::<i64>::new().with_has_element(1i64);
/// ```
///
/// The positive twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far
/// enough to see it fail and never checks why, so the pair shares its call shape and one half has to
/// be positive:
///
/// ```
/// use ingraph::{QuantifiedFilter, ScalarFilter};
///
/// let _ = QuantifiedFilter::<i64>::new().with_any(ScalarFilter::new().with_eq(1i64));
/// ```
pub struct QuantifiedFilter<T, VF = <<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter> {
  pub(crate) any: Option<VF>,
  pub(crate) count: Option<ScalarFilter<usize>>,
  // `fn() -> T` (not a bare parameter) so the element contributes no auto-trait or variance
  // obligation: this filter is `Send`/`Sync` on `VF` alone, which is what makes the element's
  // absence from every bound below real rather than nominal.
  pub(crate) element: PhantomData<fn() -> T>,
}

impl<T, VF> QuantifiedFilter<T, VF> {
  /// The empty filter — no operator set.
  #[inline]
  pub const fn new() -> Self {
    Self {
      any: None,
      count: None,
      element: PhantomData,
    }
  }

  /// True while NO operator slot is set — so a lowering would emit nothing for this field.
  ///
  /// Inherent, not the backend traits' provided `is_empty`, for [`ListFilter::is_empty`]'s reason:
  /// "is anything set" is a property of the FILTER, identical on every backend, and asking it should
  /// not make a caller name a dialect.
  ///
  /// A present `any` holding an EMPTY element filter is not empty and a present `count` holding an
  /// empty scalar filter IS, which is the QUANTIFIER law this kind's two slots are the whole of —
  /// see [`ListFilter::is_empty`], where it is stated over the same pair.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.any.is_none()
      && match &self.count {
        Some(count) => count.is_empty(),
        None => true,
      }
  }

  opt_accessor!(any: VF => with_any, set_any, maybe_any, update_any);
  opt_accessor!(
    count: ScalarFilter<usize> => with_count, set_count, maybe_count, update_count
  );
}

impl<T, VF> Default for QuantifiedFilter<T, VF> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

impl<T, VF> GraphqlFilter for QuantifiedFilter<T, VF> {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

// Hand-written, where the wide collection kinds derive all three: a derive would put `T: Debug` /
// `Clone` / `PartialEq` on the ELEMENT, which this kind holds only as `PhantomData<fn() -> T>` and
// asks nothing of anywhere else. `BytesFilter`'s reading marker is written out for the same reason
// one file over; here the parameter is an ordinary type that usually answers all three, which is
// what makes the derive's bound invisible rather than harmless — an element type kept out of every
// other bound must not re-enter through a `#[derive]`.
impl<T, VF: core::fmt::Debug> core::fmt::Debug for QuantifiedFilter<T, VF> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("QuantifiedFilter")
      .field("any", &self.any)
      .field("count", &self.count)
      .finish()
  }
}

impl<T, VF: Clone> Clone for QuantifiedFilter<T, VF> {
  fn clone(&self) -> Self {
    Self {
      any: self.any.clone(),
      count: self.count.clone(),
      element: PhantomData,
    }
  }
}

impl<T, VF: PartialEq> PartialEq for QuantifiedFilter<T, VF> {
  fn eq(&self, other: &Self) -> bool {
    self.any == other.any && self.count == other.count
  }
}

/// The WIRE FACE, written over the two PARAMETERS — [`ListFilter`](super::ListFilter)'s row, for the
/// narrow shape.
///
/// # The `where` clause is the deliverable
///
/// The wide collections ask `T: ToGraphqlInput`, `<T as ToGraphqlInput>::Input: InputType` and
/// `T: Send + Sync`, and every one of those three is spent by a slot holding an ELEMENT. This kind
/// holds none, so it asks for none: **`VF: InputType` is the whole clause**, and an element type with
/// no wire form at all reaches a schema through it.
///
/// `T` is not even asked for [`Send`] and [`Sync`], which
/// [`InputType`](async_graphql::InputType)'s own supertraits would otherwise reach through a slot.
/// `PhantomData<fn() -> T>` is both for every `T` — a function pointer carries no obligation to its
/// return type — which is what the field's own note is about.
///
/// # The NAME comes from the element's FILTER, as the wide collections' names do
///
/// `<Element>QuantifiedFilter`, assembled from `VF::type_name()` with the family suffix taken off —
/// see [`operand_of`](super::operand_of) for why the ELEMENT's own name cannot serve and why the
/// filter's is injective where the element's is not. So a detection's filter named `DetectionFilter`
/// gives `DetectionQuantifiedFilter`, and the wide kind over the same element would be
/// `DetectionListFilter`: two vocabularies, two names, which is the rule this kind exists under.
///
/// `ScalarFilter<usize>` needs no bound of its own: `count` is a cardinality, so it is one registered
/// input object for every element type there is.
#[cfg(feature = "async-graphql")]
impl<T, VF> async_graphql::InputType for QuantifiedFilter<T, VF>
where
  VF: async_graphql::InputType,
{
  type RawValueType = Self;

  fn type_name() -> ::std::borrow::Cow<'static, str> {
    let element = VF::type_name();
    ::std::borrow::Cow::Owned(::std::format!(
      "{}QuantifiedFilter",
      super::operand_of(&element)
    ))
  }

  fn create_type_info(registry: &mut async_graphql::registry::Registry) -> ::std::string::String {
    registry.create_input_type::<Self, _>(
      async_graphql::registry::MetaTypeId::InputObject,
      |registry| async_graphql::registry::MetaType::InputObject {
        name: ::std::borrow::Cow::into_owned(Self::type_name()),
        description: ::std::option::Option::None,
        input_fields: <Self as crate::NullableFace>::bare_fields(registry),
        visible: ::std::option::Option::None,
        inaccessible: false,
        tags: ::std::vec::Vec::new(),
        rust_typename: ::std::option::Option::Some(::std::any::type_name::<Self>()),
        oneof: false,
        directive_invocations: ::std::vec::Vec::new(),
      },
    )
  }

  fn parse(
    value: ::std::option::Option<async_graphql::Value>,
  ) -> async_graphql::InputValueResult<Self> {
    if let ::std::option::Option::Some(async_graphql::Value::Object(object)) = value {
      ::std::result::Result::Ok(Self {
        any: super::parse_slot::<_, Self>(&object, "any")?,
        count: super::parse_slot::<_, Self>(&object, "count")?,
        element: PhantomData,
      })
    } else {
      ::std::result::Result::Err(async_graphql::InputValueError::expected_type(
        value.unwrap_or_default(),
      ))
    }
  }

  fn to_value(&self) -> async_graphql::Value {
    async_graphql::Value::Object(<Self as crate::NullableFace>::bare_values(self))
  }

  #[inline]
  fn as_raw_value(&self) -> ::std::option::Option<&Self::RawValueType> {
    ::std::option::Option::Some(self)
  }
}

#[cfg(feature = "async-graphql")]
impl<T, VF> async_graphql::InputObjectType for QuantifiedFilter<T, VF> where
  VF: async_graphql::InputType
{
}

/// The NULLABLE row, fed from the same face for the reason every kind's is: nullability is a TYPE
/// here, so a face with no [`NullableFace`](crate::NullableFace) row leaves the wrapper unspellable
/// over it.
///
/// The two slots are rendered by `__ingraph_filter_value_map!` DIRECTLY, where the wide collections
/// each need a function: that macro writes each slot through its own type's
/// [`InputType`](async_graphql::InputType), and the wide kinds' element slots hold a DOMAIN value
/// whose whole point is that it may have no such impl. Both slots here hold a FILTER, and a filter's
/// face is what this row is written beside.
#[cfg(feature = "async-graphql")]
impl<T, VF> crate::NullableFace for QuantifiedFilter<T, VF>
where
  VF: async_graphql::InputType,
{
  fn bare_fields(
    registry: &mut async_graphql::registry::Registry,
  ) -> async_graphql::indexmap::IndexMap<
    ::std::string::String,
    async_graphql::registry::MetaInputValue,
  > {
    __ingraph_filter_input_fields!(
      registry,
      "any" : ::core::option::Option<VF>,
      "count" : ::core::option::Option<ScalarFilter<usize>>,
    )
  }

  fn bare_values(
    &self,
  ) -> async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value> {
    __ingraph_filter_value_map!(self, "any": any, "count": count)
  }
}