ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The JOURNAL declaration's emission: the canonical record, and the row contract over it.
//!
//! ```ignore
//! #[ingraph::journal(root = "MediaId", sqlite)]
//! pub struct VideoJournal;
//! ```
//!
//! # It emits a RECORD, and that is the whole design
//!
//! What the word mounts is not a second kind of thing. [`columns`] mints the four the organ is
//! keyed and read by, the front end hands them to the ORDINARY record pass under
//! [`NodeKind::Record`](crate::model::NodeKind::Record), and this model emits that record's own
//! expansion plus one impl. So a mounted journal has the `*Key` type, the accessor family, the
//! per-database row, the comparison lowering, the order-by vocabulary and the cursor that every
//! declared record has — because it IS one — and a deployment queries its run state exactly as it
//! queries anything else it declared.
//!
//! The one thing added is [`JournalModel::row`]: `impl JournalRow<Root>`, which is the same trait
//! the HAND path implements by hand. The macro is sugar over that contract and never a replacement,
//! so the two paths meet at one seam and a writer cannot tell them apart.
//!
//! # The four columns, and why each is the one it is
//!
//! | column | type | why |
//! |---|---|---|
//! | `root` | the type `root = "…"` named | one journal table per ROOT FAMILY, and the root is that family |
//! | `node` | `String` | `NodeName`'s storable face, which is what the hand corpus already stores |
//! | `station` | `String` | `Station`'s, for the same reason — the framework's own stable word |
//! | `at` | `Timestamp` | the framework's own instant: feature-free, and stored on every backend |
//!
//! `root` is the LINEAGE and `node` is the ID, so `key = lineage ⊕ id` spells `(root, node)` with
//! nothing declared for it — and the keyed replace that makes an entry the LAST STATE is the
//! ordinary write of that key. That is the organ's semantics arriving from the record law rather
//! than from anything written here.
//!
//! `root`'s CITIZENSHIP is not checked here and is not left unchecked: it is a key column of an
//! ordinary record, so a type no backend can store is the storability audit's own refusal, at the
//! declaration that named it.
//!
//! # `SystemTime` → `Timestamp`: the crossing PANICS, and the alternative is a durable lie
//!
//! [`JournalRow::of`](../../ingraph/trait.JournalRow.html) is handed a `SystemTime` and the `at`
//! column is a `Timestamp`, whose range is jiff's ±9999 years. The conversion is `TryFrom` rather
//! than `From` on purpose — `ingraph::Timestamp`'s own note says why: *a saturating `From` would
//! substitute an instant for the one a caller handed over*.
//!
//! The signature this emission has to satisfy returns `Self` and cannot report a refusal, so the
//! two available postures are to substitute an instant or to stop. It stops. A journal row is
//! DURABLE and is read as *when this node got there*, so a substituted instant is a row asserting a
//! moment that never happened — and what reaches this crossing is a system clock wrong by thousands
//! of years rather than a value worth rounding. The panic names the fact and carries jiff's own
//! refusal; a deployment that would rather keep the row writes the HAND path, whose `of` is its own
//! and may say whatever it likes about an instant it cannot hold.

use quote::quote;

use crate::model::RecordModel;

#[cfg(test)]
mod tests;

/// A validated journal declaration, ready to emit.
///
/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a
/// manifest front end later reach the same emitter.
#[derive(Debug, Clone)]
pub struct JournalModel {
  /// The canonical record this journal IS — the four columns of [`columns`], parsed by the ordinary
  /// record pass, so everything a declared record emits is emitted here too.
  pub record: RecordModel,
  /// The chain root the journal is keyed by — the type `root = "…"` named, and the `Root` parameter
  /// of the emitted [`JournalRow`](../../ingraph/trait.JournalRow.html) impl.
  pub root: syn::Type,
}

impl JournalModel {
  /// The record's own expansion, and the row contract over it.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let record = self.record.emit();
    let row = row(&self.record.krate, &self.record.record, &self.root);
    quote! {
      #record
      #row
    }
  }
}

/// `impl JournalRow<Root>` — the four things the framework knows, mapped onto the four columns.
///
/// A free function over the three tokens it spends rather than a method, so the claim about what it
/// writes is readable without assembling a whole record model to make it.
///
/// Every path is rooted through the shelf, as every emitted framework path is, and every trait item
/// is reached in qualified form: an expansion lands in a namespace whose `From` and whose `TryFrom`
/// are not necessarily the ones this code means.
pub(crate) fn row(
  krate: &syn::Path,
  name: &syn::Ident,
  root: &syn::Type,
) -> proc_macro2::TokenStream {
  let drive = quote!(#krate::__private::drive);
  let instant = quote!(#krate::__private::primitives::Timestamp);
  quote! {
    impl #drive::JournalRow<#root> for #name {
      fn of(
        root: &#root,
        node: &#drive::NodeName,
        arrival: &#drive::Arrival,
        at: ::std::time::SystemTime,
      ) -> Self {
        Self {
          root: ::core::clone::Clone::clone(root),
          node: ::std::string::String::from(#drive::NodeName::as_str(node)),
          station: ::std::string::String::from(
            #drive::Station::as_str(&#drive::Arrival::station(arrival)),
          ),
          // The crossing that cannot report — see the module note for why it stops rather than
          // substituting an instant nobody observed.
          at: match <#instant as ::core::convert::TryFrom<::std::time::SystemTime>>::try_from(at) {
            ::core::result::Result::Ok(instant) => instant,
            ::core::result::Result::Err(refused) => ::core::panic!(
              "a journal row's `at` is outside the range `ingraph::Timestamp` can hold, so this \
               row cannot be written: {}. The instant a journal keeps is durable and is read as \
               when the node got there, so substituting one would record a moment that never \
               happened — this is a clock wrong by thousands of years rather than a value to round",
              refused,
            ),
          },
        }
      }
    }
  }
}

/// The four canonical columns, minted whole — the ONE authority for a mounted journal's shape.
///
/// Handed back as a declaration's own field list, markers and all, because that is what the record
/// pass reads: the front end swaps them into the host it was given and every rule downstream is the
/// rule that was already there. Nothing about the shape is decided twice.
///
/// The four columns are the SAME four whether or not the journal named a store, which is the
/// participation inversion read from the mint's side.
///
/// The `root` column used to carry a bare `#[ingraph(persist)]` and the other three used to carry
/// one beside their own word, both only where a storage block had been written — because the marker
/// was what put a column in the row. Data fields ARE the row now, so a marker that says so is a word
/// nobody reads, and the branch that wrote it is gone with it. WHICH RUNG the mount lands on is the
/// front end's, decided from the store words and spent as the node kind it parses under; nothing
/// about the column list depends on it.
///
/// The KEY-side columns (`root` and `node`) carry no family label and cannot: a label on a key
/// column is refused by the record grammar, the key's own crossing being decided by its type.
#[must_use]
pub fn columns(root: &syn::Type, krate: &syn::Path) -> syn::FieldsNamed {
  syn::parse_quote!({
    /// The chain ROOT this entry is about — one journal table per root family, and this is the
    /// family. The key's first column.
    root: #root,

    /// The NODE that did the work, as the framework's own stable word for it. The key's last
    /// column, so `(root, node)` is the whole address and an entry is replaced in place.
    #[ingraph(id)]
    node: ::std::string::String,

    /// Where the node GOT TO — the station of the observation this entry was built from.
    #[ingraph(string)]
    station: ::std::string::String,

    /// WHEN, as the framework's own instant.
    #[ingraph(scalar)]
    at: #krate::__private::primitives::Timestamp,
  })
}