use ingraph_codegen::{journal::JournalModel, model::NodeKind};
use crate::{
attribute::{self, named, set_once},
errors::Errors,
value,
};
#[cfg(test)]
mod tests;
pub(crate) struct Journal {
pub(crate) host: syn::DeriveInput,
pub(crate) model: JournalModel,
}
pub(crate) fn parse(
input: &syn::DeriveInput,
arguments: &[syn::Attribute],
) -> syn::Result<Journal> {
let mut errors = Errors::default();
crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
let Options {
root,
persist,
krate,
krate_literal,
} = options(arguments, &mut errors);
marker(input, &mut errors);
let Some(root) = root else {
return Err(errors.seal(syn::Error::new_spanned(&input.ident, NO_ROOT)));
};
let krate = krate.unwrap_or_else(|| syn::parse_quote!(::ingraph));
let host = mounted(input, &root, &krate);
let kind = if persist.is_some() {
NodeKind::Record
} else {
NodeKind::Entity
};
let record = match crate::parse::parse(
&host,
&[canonical_options(krate_literal.as_ref(), persist.as_ref())],
kind,
) {
Ok(model) => model,
Err(refused) => return Err(errors.seal(refused)),
};
errors.into_result(Journal {
host,
model: JournalModel { record, root },
})
}
#[derive(Default)]
struct Options {
root: Option<syn::Type>,
persist: Option<proc_macro2::TokenStream>,
krate: Option<syn::Path>,
krate_literal: Option<syn::LitStr>,
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
let mut options = Options::default();
attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("root") {
match value::parse_literal::<syn::Type>(&meta, ROOT_TYPE) {
Ok(root) => set_once(
&mut options.root,
root,
&meta.path,
"`root` is declared more than once — one journal table is keyed by one root family",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("crate") {
match value::literal(&meta, CRATE_PATH)
.and_then(|spelled| Ok((spelled.parse::<syn::Path>()?, spelled)))
{
Ok((path, spelled)) => {
set_once(
&mut options.krate,
path,
&meta.path,
"`crate` is declared more than once — one declaration names one crate",
errors,
);
options.krate_literal.get_or_insert(spelled);
}
Err(e) => errors.push(syn::Error::new(e.span(), CRATE_PATH)),
}
return Ok(());
}
if meta.path.is_ident("persist") {
errors.push(named(&meta, PERSIST_UNWRAPPED.to_owned()));
attribute::skip_entry(&meta);
return Ok(());
}
if STORE_WORDS.contains(
&meta
.path
.get_ident()
.map(ToString::to_string)
.unwrap_or_default()
.as_str(),
) {
let word = meta.path.clone();
let inner = if attribute::has_block(&meta) {
let inner = attribute::verbatim(&meta)?;
quote::quote!(#word(#inner))
} else if attribute::has_value(&meta) {
let value: syn::LitStr = meta.value()?.parse()?;
quote::quote!(#word = #value)
} else {
quote::quote!(#word)
};
let forwarded = options
.persist
.get_or_insert_with(proc_macro2::TokenStream::new);
if !forwarded.is_empty() {
forwarded.extend(quote::quote!(,));
}
forwarded.extend(inner);
return Ok(());
}
for (word, instead) in FIXED {
if meta.path.is_ident(word) {
errors.push(named(&meta, format!("`{word}` decides something a CANONICAL journal has already decided: {instead}. {HAND_PATH}")));
return Ok(());
}
}
for (word, noun) in STORES {
if meta.path.is_ident(word) {
errors.push(named(
&meta,
format!(
"a journal holds ROWS — its store words name where they land, and {noun} is its OWN \
node: declare it with the `{word}` macro, on a type whose `upstream(…)` names this \
journal. ONE NODE HOLDS ONE STORAGE, so the MACRO IS the storage declaration"
),
));
return Ok(());
}
}
errors.push(attribute::unknown(
&meta,
UNKNOWN,
&["root", "crate"]
.into_iter()
.chain(STORE_WORDS.iter().copied())
.collect::<Vec<_>>(),
));
Ok(())
});
options
}
const FIXED: [(&str, &str); 6] = [
(
"lineage",
"the path is the `root` column, which `root = \"…\"` already names",
),
(
"key",
"the key is `(root, node)`, which `key = lineage ⊕ id` already spells over those two columns",
),
(
"graphql",
"the wire face rides the four canonical columns, so there is no field for a block to name",
),
(
"implements",
"an interface's contract is a promise about COLUMNS, and a journal's four are the framework's \
rather than a declaration's to agree with",
),
(
"subscribe",
"a journal is written by the drive layer through `JournalRow`, so its inputs are observations \
rather than an upstream node's messages",
),
(
"upstream",
"a journal is written by the drive layer through `JournalRow`, so its inputs are observations \
rather than an upstream node's messages",
),
];
const STORES: [(&str, &str); 3] = [
("fulltext", "a full-text index"),
("vector", "an embedding index"),
("blob", "an artifact family"),
];
const HAND_PATH: &str = "A journal whose columns, key or wire face are its own is the HAND path, \
which this word does not replace: declare an ordinary \
`#[ingraph::record(…)]` with whatever columns you want and implement \
`JournalRow` on it. The macro is sugar over that contract, so the two are \
one seam to every writer";
const UNKNOWN: &str = "unknown `ingraph` journal attribute — a journal takes `root = \"…\"`, its \
STORE WORDS (`sqlite`, `postgres`, `mysql`, `mongo`, with `table = \"…\"` \
and `rename = \"…\"` beside them) and `crate = \"…\"`, and nothing else: \
its four columns (`root`, `node`, `station`, `at`) and its `(root, node)` \
key are the word's own, which is what CANONICAL means";
const STORE_WORDS: [&str; 6] = ["sqlite", "postgres", "mysql", "mongo", "table", "rename"];
const PERSIST_UNWRAPPED: &str = "`persist(…)` is gone — a journal names its stores BARE, so write \
`#[ingraph::journal(root = \"…\", sqlite)]` and keep every word \
that was inside each database's own block. Storage is the essence \
of a thing that holds rows, and an essence does not wrap";
const ROOT_TYPE: &str = "`root = \"…\"` names the chain root this journal is keyed by, as a type in \
a string literal";
const CRATE_PATH: &str =
"`#[ingraph::journal(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal";
const NO_ROOT: &str = "a journal needs `root = \"…\"` — there is ONE journal table per ROOT FAMILY, \
and the word is what says which family: \
`#[ingraph::journal(root = \"media::MediaId\", sqlite)]`. The type \
is spelled as a path in a string, which is this grammar's rule for every type \
it names";
fn marker(input: &syn::DeriveInput, errors: &mut Errors) {
if !input.generics.params.is_empty() {
errors.push(syn::Error::new_spanned(
&input.generics.params,
"a journal takes no generic parameter — the record it mounts is CONCRETE, because a key \
column's type is read straight off the declaration, and `root = \"…\"` is how this one's is \
named",
));
}
match &input.data {
syn::Data::Struct(data) if matches!(data.fields, syn::Fields::Unit) => {}
syn::Data::Struct(_) => errors.push(syn::Error::new_spanned(
&input.ident,
format!(
"a journal's host is a MARKER — write `struct {name};` and nothing inside it. The four \
canonical columns (`root`, `node`, `station`, `at`) are this word's own mint, so a field \
written here would be a second author for a shape that is already decided. {HAND_PATH}",
name = input.ident,
),
)),
syn::Data::Enum(_) | syn::Data::Union(_) => errors.push(syn::Error::new_spanned(
&input.ident,
"a journal's host is a marker STRUCT — `#[ingraph::journal(…)]` mounts a RECORD, and a record \
is a struct. There is nothing here for a variant or a union field to be",
)),
}
}
fn mounted(input: &syn::DeriveInput, root: &syn::Type, krate: &syn::Path) -> syn::DeriveInput {
let mut host = input.clone();
host.attrs.retain(|attr| !attr.path().is_ident("ingraph"));
host.data = syn::Data::Struct(syn::DataStruct {
struct_token: syn::token::Struct::default(),
fields: syn::Fields::Named(ingraph_codegen::journal::columns(root, krate)),
semi_token: None,
});
host
}
fn canonical_options(
krate: Option<&syn::LitStr>,
persist: Option<&proc_macro2::TokenStream>,
) -> syn::Attribute {
let krate = krate.map(|spelled| quote::quote!(, crate = #spelled));
let persist = persist.map(|inner| quote::quote!(, #inner));
syn::parse_quote!(#[ingraph(lineage(fields(root)) #krate #persist)])
}