ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What a declaration's clocks become: the vocabulary, the two translations, and the schedule.
//!
//! Read off the EMISSION rather than off the model, because what an author writes against is the
//! emitted text — a variant that is named right in the model and spelled wrong in the tokens is a
//! bug this suite exists to see.

use quote::format_ident;

use crate::{
  model::{PollBody, PollCadence, PollEntry, PollMode, Polls, RecordModel, default_due_name},
  tests::{emission, enum_named, model},
};

/// A node with one clock of each cadence, in that order — the shape the emission exists for.
fn swept() -> RecordModel {
  let mut model = model("Reaper", &["media_id"], "id");
  model.polls = Some(Polls {
    entries: vec![
      entry(
        "orphans",
        PollCadence::Every(core::time::Duration::new(600, 0)),
      ),
      entry(
        "sweep_stale",
        PollCadence::Calendar {
          expression: "0 3 * * *".to_owned(),
          zone: None,
        },
      ),
      entry(
        "compact",
        PollCadence::Calendar {
          expression: "*/15 * * * *".to_owned(),
          zone: Some("America/New_York".to_owned()),
        },
      ),
    ],
  });
  model
}

/// One entry, as the front end would have settled it — the variant included, since that is the front
/// end's to decide and this suite's to read back.
fn entry(name: &str, cadence: PollCadence) -> PollEntry {
  use heck::ToUpperCamelCase as _;

  let variant = format_ident!("{}", name.to_upper_camel_case());
  PollEntry {
    name: format_ident!("{name}"),
    variant,
    cadence,
    grants: None,
    body: PollBody::Light,
    mode: PollMode::AsyncInline,
    concurrent: false,
  }
}

/// The emission, as one string with its spaces gone — for the assertions about generated bodies,
/// where the tokens matter and their layout does not.
///
/// It flattens the INSIDE of string literals too, so an assertion about a cron expression reads the
/// emission through [`written`] instead.
fn tight(model: &RecordModel) -> String {
  model.emit().to_string().replace(' ', "")
}

/// The emission with its spacing left alone — for the assertions about the TEXT a declaration wrote,
/// which a flattening would edit.
fn written(model: &RecordModel) -> String {
  model.emit().to_string()
}

/// ONE variant per entry, named by the word the entry minted, in declaration order.
#[test]
fn the_vocabulary_is_one_variant_per_entry_in_order() {
  let model = swept();
  let file = emission(&model);
  let due = enum_named(&file, &default_due_name(&model.record).to_string());
  assert_eq!(
    due
      .variants
      .iter()
      .map(|variant| variant.ident.to_string())
      .collect::<Vec<_>>(),
    ["Orphans", "SweepStale", "Compact"],
  );
  // A vocabulary and not a payload: a tick moves no message, so no variant carries one.
  assert!(due.variants.iter().all(|variant| variant.fields.is_empty()));
}

/// A node with no `poll(…)` word emits no vocabulary at all — the collision rule must not report a
/// name no expansion writes.
#[test]
fn a_node_with_no_clock_emits_no_vocabulary() {
  let model = model("Plain", &["media_id"], "id");
  let file = emission(&model);
  let due = default_due_name(&model.record).to_string();
  assert!(
    !file.items.iter().any(|item| matches!(
      item,
      syn::Item::Enum(item) if item.ident == due
    )),
    "`{due}` is not emitted for a node with no clock"
  );
}

/// ONE clock still gets the vocabulary, where a fan-in of one collapses to its message type: a
/// tick's identity is a position at every arity, so there is no bare type to fall back to.
#[test]
fn one_clock_still_gets_a_vocabulary() {
  let mut model = model("Compactor", &["media_id"], "id");
  model.polls = Some(Polls {
    entries: vec![entry(
      "compact",
      PollCadence::Every(core::time::Duration::new(3_600, 0)),
    )],
  });
  let file = emission(&model);
  let due = enum_named(&file, &default_due_name(&model.record).to_string());
  assert_eq!(due.variants.len(), 1);
  assert!(tight(&model).contains("constCOUNT:usize=1usize"));
}

/// The two translations are inverses, and the numbers in them are declaration order.
#[test]
fn position_and_name_translate_both_ways() {
  let emitted = tight(&swept());
  assert!(emitted.contains("constCOUNT:usize=3usize"), "{emitted}");

  // Position → name, and one arm past the end that answers `None` rather than a variant.
  for (index, variant) in ["Orphans", "SweepStale", "Compact"].iter().enumerate() {
    assert!(
      emitted.contains(&format!(
        "{index}usize=>::core::option::Option::Some(Self::{variant})"
      )),
      "position {index} translates to `{variant}`: {emitted}"
    );
  }
  assert!(
    emitted.contains("_=>::core::option::Option::None"),
    "{emitted}"
  );

  // Name → position.
  for (index, variant) in ["Orphans", "SweepStale", "Compact"].iter().enumerate() {
    assert!(
      emitted.contains(&format!("Self::{variant}=>{index}usize")),
      "`{variant}` translates to position {index}: {emitted}"
    );
  }
}

/// The schedule is built in declaration order, each entry through the door its cadence names.
#[test]
fn the_schedule_carries_every_cadence_in_order() {
  let model = swept();

  // The three DOORS, one per cadence shape — an interval, a calendar in the system's zone, and a
  // calendar in a named one.
  let emitted = tight(&model);
  assert!(
    emitted.contains("schedule.every(::core::time::Duration::new(600u64,0u32))"),
    "{emitted}"
  );
  assert!(emitted.contains("schedule.cron("), "{emitted}");
  assert!(emitted.contains("schedule.cron_in("), "{emitted}");

  // The EXPRESSIONS, verbatim and in declaration order — read off the unflattened emission, since
  // what a declaration wrote inside a string is exactly what a flattening would edit.
  let written = written(&model);
  let opened = written
    .find("fn schedule")
    .expect("the schedule door is emitted");
  let body = &written[opened..];
  let interval = body.find("600u64").expect("the interval entry");
  let bare = body
    .find(r#""0 3 * * *""#)
    .expect("the calendar entry with no zone");
  let zoned = body
    .find(r#""*/15 * * * *""#)
    .expect("the calendar entry with a zone");
  assert!(
    body.contains(r#""America/New_York""#),
    "the zone rides its entry: {body}"
  );
  assert!(interval < bare && bare < zoned, "declaration order: {body}");
}

/// The door answers a `Result` at every arity, including a node whose every clock is an interval —
/// the signature must not change shape when a declaration swaps one word for another.
#[test]
fn the_schedule_door_is_fallible_even_with_no_calendar() {
  let mut model = model("Compactor", &["media_id"], "id");
  model.polls = Some(Polls {
    entries: vec![entry(
      "compact",
      PollCadence::Every(core::time::Duration::new(3_600, 500)),
    )],
  });
  let emitted = tight(&model);
  assert!(
    emitted.contains("fnschedule()->::core::result::Result<"),
    "{emitted}"
  );
  // And the sub-second half of an interval survives the crossing.
  assert!(
    emitted.contains("every(::core::time::Duration::new(3600u64,500u32))"),
    "{emitted}"
  );
}