ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! WHAT THE LAUNCH WORD MINTS — the node beside the declaration, its facts, its reach into the
//! mount, and the two shapes that mint nothing at all.
//!
//! Beside [`habitats`](super::habitats) rather than inside it, on this directory's own precedent:
//! one file per thing being proved. WHETHER the word is accepted is `ingraph-derive`'s
//! `index/subscribe_word.rs`; whether the emitted node actually fills a corpus is `ingraph`'s
//! `tests/subscriber_fulltext_road.rs`.
//!
//! # The claim these tests exist for
//!
//! Subscription is ADDITIVE, and additive is a claim about the expansion rather than a promise in a
//! doc comment: a declaration that wrote no word must emit exactly what it emitted before the word
//! existed. So the first test below reads the two expansions against each other rather than
//! asserting about either alone — the only shape in which *nothing else moved* is checkable.

use super::{Dedup, IndexGraphql, IndexModel, Projected, Upstream};
use crate::{
  engine::{Engine, FieldEngines},
  model::{Column, GraphqlKind, NodeKind, Projection},
  prefix::EmissionPrefix,
};

fn ident(name: &str) -> syn::Ident {
  syn::Ident::new(name, proc_macro2::Span::call_site())
}

fn column(name: &str, ty: &str) -> Column {
  Column {
    name: ident(name),
    source: ident(name),
    ty: syn::parse_str(ty).expect("a type"),
    project: Projection::Borrowed,
  }
}

fn projected(field: &str, ty: &str) -> Projected {
  Projected {
    field: ident(field),
    from: ident(field),
    ty: syn::parse_str(ty).expect("a type"),
  }
}

/// One `tantivy` leg, pointing wherever `resource` says — or nowhere, which is the portable case.
fn leg(word: &str, resource: Option<syn::Path>) -> Engine {
  Engine {
    resource,
    ..Engine::bare(ident(word))
  }
}

/// A full-text declaration over `fields`, each field carrying its own legs, wearing the word or not.
fn document(subscribe: bool, fields: Vec<(&str, Vec<Engine>)>) -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    index: ident("Media"),
    kind: NodeKind::Fulltext,
    vis: syn::Visibility::Public(syn::token::Pub::default()),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(asr::Segment),
      projections: fields
        .iter()
        .map(|(name, _)| projected(name, "String"))
        .collect(),
    },
    dedup: Dedup::Hash,
    embeddings: Vec::new(),
    labelled: Vec::new(),
    searchable: fields.iter().map(|(name, _)| ident(name)).collect(),
    engines: fields
      .iter()
      .map(|(name, engines)| FieldEngines {
        field: ident(name),
        engines: engines.clone(),
        fanout: false,
      })
      .collect(),
    fields: fields
      .iter()
      .map(|(name, _)| column(name, "String"))
      .collect(),
  }
}

/// The ONE-LEG declaration every test but the grouping one is written over.
fn pointed(subscribe: bool) -> IndexModel {
  document(
    subscribe,
    vec![(
      "body",
      vec![leg("lexical", Some(syn::parse_quote!(app::Ft)))],
    )],
  )
}

/// The whole expansion with the spaces taken out — what a claim about a CALL is read off.
fn tight(model: &IndexModel) -> String {
  model.emit().to_string().replace(' ', "")
}

/// **SUBSCRIPTION IS ADDITIVE, AND THIS IS THE ONLY SHAPE IN WHICH THAT IS CHECKABLE.** The bare
/// expansion is a PREFIX of nothing and a subset of everything: every token the wordless declaration
/// emits is emitted by the wearing one too, and what the word adds is the node.
///
/// Read as a containment rather than as two assertions about lengths, because *nothing else moved*
/// is what a deployment on the hand road is owed and a count would not see a reordering.
#[test]
fn the_word_adds_a_node_and_moves_nothing_else() {
  let bare = tight(&pointed(false));
  let wearing = tight(&pointed(true));

  assert!(
    !bare.contains("structMediaIndexer"),
    "a declaration that wrote no word minted a node: {bare}",
  );
  assert!(
    wearing.contains("structMediaIndexer"),
    "the word minted no node: {wearing}",
  );
  assert!(
    wearing.len() > bare.len(),
    "the wearing expansion is not larger than the bare one",
  );
  for fragment in [
    "FulltextRoadforMediaBodyLexical",
    "HabitatsforMedia",
    "pubstructMediaBodyLexical",
  ] {
    assert!(
      bare.contains(fragment) && wearing.contains(fragment),
      "`{fragment}` is not in both expansions",
    );
  }
}

/// **THE FACTS THE LAUNCH READS** — the edge from `upstream(…)`, the mount from the leg, and the two
/// rows that say this node lands rather than computes.
#[test]
fn the_node_states_its_edge_its_mount_and_its_landing() {
  let emitted = tight(&pointed(true));
  assert!(
    emitted.contains("Upstream::of::<asr::Segment>(\"asr::Segment\")"),
    "{emitted}",
  );
  assert!(
    emitted.contains("ResourceDemand::of::<app::Ft>"),
    "the node demanded no mount: {emitted}",
  );
  assert!(emitted.contains("constHOLDS_LANE:bool=true"), "{emitted}");
  assert!(emitted.contains("Effect::Lands"), "{emitted}");
}

/// **THE BODY IS AWAITED, AND ITS PRODUCT IS THE DOCUMENT.** The write face queues through a future,
/// so the node wears the awaited mode and the awaited operator — a blocking body here would be the
/// fiction the dual-mode law refuses.
#[test]
fn the_node_wears_the_awaited_face_and_emits_the_declaration() {
  let emitted = tight(&pointed(true));
  assert!(
    emitted.contains("operator::AsyncOperatorforMediaIndexer"),
    "{emitted}",
  );
  assert!(
    emitted.contains("typeIn=asr::Segment;typeOut=Media;"),
    "{emitted}"
  );
  assert!(
    emitted.contains("store::IndexRefusal;"),
    "the node refuses in some type other than the seam's: {emitted}",
  );
}

/// **ONE FIELD PER RESOURCE, NOT PER LEG.** Two elections pointing at ONE store share one mount, and
/// a second field holding a second `Shared` of the same type would be a `Shared` this node built
/// twice.
#[test]
fn two_legs_at_one_resource_hold_one_mount() {
  let emitted = tight(&document(
    true,
    vec![
      (
        "title",
        vec![leg("lexical", Some(syn::parse_quote!(app::Ft)))],
      ),
      (
        "body",
        vec![leg("lexical", Some(syn::parse_quote!(app::Ft)))],
      ),
    ],
  ));
  assert!(emitted.contains("__ingraph_mount_0"), "{emitted}");
  assert!(
    !emitted.contains("__ingraph_mount_1"),
    "one resource grew two mounts: {emitted}",
  );
  // BOTH corpora are still written — the mount is shared, the slots are not.
  for corpus in [
    "MediaTitleLexicalas::ingraph",
    "MediaBodyLexicalas::ingraph",
  ] {
    assert!(
      emitted.contains(corpus),
      "`{corpus}` is not written: {emitted}"
    );
  }
}

/// **TWO RESOURCES ARE TWO MOUNTS**, in the order the declaration wrote them.
#[test]
fn two_resources_are_two_mounts() {
  let emitted = tight(&document(
    true,
    vec![
      (
        "title",
        vec![leg("lexical", Some(syn::parse_quote!(app::Ft)))],
      ),
      (
        "body",
        vec![leg("replica", Some(syn::parse_quote!(app::Other)))],
      ),
    ],
  ));
  assert!(emitted.contains("__ingraph_mount_0"), "{emitted}");
  assert!(emitted.contains("__ingraph_mount_1"), "{emitted}");
  assert!(
    emitted.contains("ResourceDemand::of::<app::Ft>"),
    "{emitted}"
  );
  assert!(
    emitted.contains("ResourceDemand::of::<app::Other>"),
    "{emitted}",
  );
}

/// **A DECLARATION WHOSE LEGS POINT NOWHERE MINTS NO NODE**, and that is the honest answer rather
/// than a refusal: an unpointed leg is legal and means the deployment says where instead, so there
/// is no store for a subscriber to open and nothing for it to demand.
#[test]
fn an_unpointed_declaration_mints_no_node_even_wearing_the_word() {
  let emitted = tight(&document(true, vec![("body", vec![leg("lexical", None)])]));
  assert!(
    !emitted.contains("structMediaIndexer"),
    "a subscriber was minted for a declaration with nowhere to write: {emitted}",
  );
}

/// **THE OTHER TWO KINDS MINT NOTHING**, whatever the model says — the front end refuses the word
/// there, and this is the emitter's own half of that so a hand-built model cannot reach the road.
#[test]
fn a_kind_without_the_road_mints_no_node() {
  for kind in [NodeKind::Vector, NodeKind::Blob] {
    let model = IndexModel {
      prefix: EmissionPrefix::default(),
      kind,
      ..pointed(true)
    };
    assert!(
      !model.subscriber().to_string().contains("MediaIndexer"),
      "{kind:?} reached the subscriber road",
    );
  }
}