use std::sync::OnceLock;
use indexmap::IndexMap;
use memstead_schema::{
CrossMemRelationshipEntry, FieldType, RelationshipDef, RelationshipMode, Schema, Serialization,
TypeDefinition,
};
use regex::Regex;
use crate::entity::MetadataValue;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelationshipHint {
pub name: String,
pub when_to_use: Option<String>,
}
impl std::fmt::Display for RelationshipHint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.name)
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ValidationError {
#[error("unknown section '{key}' for type '{entity_type}'")]
UnknownSection {
key: String,
entity_type: String,
declared: Vec<String>,
suggestion: Option<String>,
},
#[error("unknown metadata field '{key}' for type '{entity_type}'")]
UnknownMetadata {
key: String,
entity_type: String,
declared: Vec<String>,
suggestion: Option<String>,
},
#[error("invalid value '{value}' for field '{field}' on type '{entity_type}'")]
InvalidEnumValue {
field: String,
value: String,
allowed: Vec<String>,
field_description: Option<String>,
suggestion: Option<String>,
type_write_rules: Vec<String>,
entity_type: String,
},
#[error("cannot change read-only field '{field}' via update")]
ReadOnlyField { field: String },
#[error("section '{section}' is not updatable for type '{entity_type}'")]
SectionNotUpdatable {
section: String,
entity_type: String,
},
#[error("invalid relationship type '{input}'")]
InvalidRelationshipType {
input: String,
allowed: Vec<RelationshipHint>,
suggestion: Option<String>,
},
#[error(
"relationship '{rel_type}' from type '{from_type}' to type '{to_type}' violates declared shape"
)]
InvalidRelationshipShape {
rel_type: String,
from_type: String,
to_type: String,
allowed_source_types: Vec<String>,
allowed_target_types: Vec<String>,
suggestion: Option<RelationshipHint>,
},
#[error(
"section '{section}' content contains an embedded reserved (`# ` / `## `) heading line '{embedded_heading}' — \
the compose-then-reparse pipeline would split the value at that heading; use `### ` or \
deeper for sub-headings"
)]
SectionContentInvalid {
section: String,
embedded_heading: String,
},
#[error(
"section '{section}' carries heading '{heading}', which type '{entity_type}' does not \
declare and which has no body under it. The catch-all keeps absorbed content but skips \
empty content, so this heading would be dropped by the write. Give it a body, or \
remove the heading."
)]
EmptyUndeclaredHeading {
section: String,
heading: String,
entity_type: String,
},
#[error(
"section '{section}' ends inside an unterminated `{fence}` code fence — every section \
heading written after it would be swallowed into this body and read back as empty. \
Close the fence with a line of `{fence}`."
)]
UnterminatedFence { section: String, fence: String },
#[error(
"section '{section}' content contains a disallowed control character U+{codepoint:04X} \
at byte offset {byte_offset} — only tab and newline are permitted in section bodies"
)]
SectionContentControlByte {
section: String,
control_char: char,
codepoint: u32,
byte_offset: usize,
},
#[error(
"invalid value '{value}' for field '{field}' on type '{entity_type}' — expected {expected_type}"
)]
InvalidFieldValue {
field: String,
value: String,
expected_type: String,
expected_format: Option<String>,
field_description: Option<String>,
entity_type: String,
},
}
impl ValidationError {
pub fn code(&self) -> &'static str {
match self {
ValidationError::UnknownSection { .. } => "UNKNOWN_SECTION",
ValidationError::UnknownMetadata { .. } => "UNKNOWN_METADATA_FIELD",
ValidationError::InvalidEnumValue { .. } => "INVALID_ENUM_VALUE",
ValidationError::ReadOnlyField { .. } => "READ_ONLY_FIELD",
ValidationError::SectionNotUpdatable { .. } => "SECTION_NOT_UPDATABLE",
ValidationError::InvalidRelationshipType { .. } => "INVALID_REL_TYPE",
ValidationError::InvalidRelationshipShape { .. } => "INVALID_REL_SHAPE",
ValidationError::EmptyUndeclaredHeading { .. } => "EMPTY_UNDECLARED_HEADING",
ValidationError::UnterminatedFence { .. } => "UNTERMINATED_FENCE",
ValidationError::SectionContentInvalid { .. } => "SECTION_CONTENT_INVALID",
ValidationError::SectionContentControlByte { .. } => "SECTION_CONTENT_INVALID",
ValidationError::InvalidFieldValue { .. } => "INVALID_FIELD_VALUE",
}
}
pub fn details(&self) -> serde_json::Value {
match self {
ValidationError::UnknownSection {
key,
entity_type,
declared,
suggestion,
} => serde_json::json!({
"key": key,
"entity_type": entity_type,
"declared": declared,
"suggestion": suggestion,
}),
ValidationError::UnknownMetadata {
key,
entity_type,
declared,
suggestion,
} => serde_json::json!({
"key": key,
"entity_type": entity_type,
"declared": declared,
"suggestion": suggestion,
}),
ValidationError::InvalidEnumValue {
field,
value,
allowed,
field_description,
suggestion,
type_write_rules,
entity_type,
} => serde_json::json!({
"field": field,
"value": value,
"allowed": allowed,
"field_description": field_description,
"suggestion": suggestion,
"type_write_rules": type_write_rules,
"entity_type": entity_type,
}),
ValidationError::ReadOnlyField { field } => serde_json::json!({
"field": field,
}),
ValidationError::SectionNotUpdatable {
section,
entity_type,
} => serde_json::json!({
"section": section,
"entity_type": entity_type,
}),
ValidationError::InvalidRelationshipType {
input,
allowed,
suggestion,
} => {
let allowed_json: Vec<serde_json::Value> = allowed
.iter()
.map(|h| {
serde_json::json!({
"name": h.name,
"when_to_use": h.when_to_use,
})
})
.collect();
serde_json::json!({
"input": input,
"allowed": allowed_json,
"suggestion": suggestion,
})
}
ValidationError::InvalidRelationshipShape {
rel_type,
from_type,
to_type,
allowed_source_types,
allowed_target_types,
suggestion,
} => {
let suggestion_json = suggestion.as_ref().map(|h| {
serde_json::json!({
"name": h.name,
"when_to_use": h.when_to_use,
})
});
let mut details = serde_json::Map::new();
details.insert(
"rel_type".into(),
serde_json::Value::String(rel_type.clone()),
);
details.insert(
"from_type".into(),
serde_json::Value::String(from_type.clone()),
);
details.insert("to_type".into(), serde_json::Value::String(to_type.clone()));
if !allowed_source_types.is_empty() {
details.insert(
"allowed_source_types".into(),
serde_json::json!(allowed_source_types),
);
}
if !allowed_target_types.is_empty() {
details.insert(
"allowed_target_types".into(),
serde_json::json!(allowed_target_types),
);
}
details.insert("suggestion".into(), serde_json::json!(suggestion_json));
serde_json::Value::Object(details)
}
ValidationError::UnterminatedFence { section, fence } => serde_json::json!({
"section": section,
"fence": fence,
"expected": format!(
"close the fence with a line of `{fence}`, or remove the opener"
),
}),
ValidationError::EmptyUndeclaredHeading {
section,
heading,
entity_type,
} => serde_json::json!({
"section": section,
"heading": heading,
"entity_type": entity_type,
"expected": "give the heading a body, or remove it: the catch-all keeps \
absorbed content but skips empty content",
}),
ValidationError::SectionContentInvalid {
section,
embedded_heading,
} => serde_json::json!({
"section": section,
"embedded_heading": embedded_heading,
}),
ValidationError::SectionContentControlByte {
section,
control_char,
codepoint,
byte_offset,
} => serde_json::json!({
"section": section,
"control_char": control_char.to_string(),
"codepoint": codepoint,
"byte_offset": byte_offset,
}),
ValidationError::InvalidFieldValue {
field,
value,
expected_type,
expected_format,
field_description,
entity_type,
} => serde_json::json!({
"field": field,
"value": value,
"expected_type": expected_type,
"expected_format": expected_format,
"field_description": field_description,
"entity_type": entity_type,
}),
}
}
pub fn prose_render(&self) -> String {
match self {
ValidationError::UnknownSection {
key,
entity_type,
declared,
suggestion,
} => {
let declared_inline = if declared.is_empty() {
"(none)".to_string()
} else {
declared.join(", ")
};
let suggestion_clause = suggestion
.as_deref()
.map(|s| format!(" Did you mean '{s}'?"))
.unwrap_or_default();
format!(
"unknown section '{key}' for type '{entity_type}' — declared sections: {declared_inline}.{suggestion_clause}"
)
}
ValidationError::UnknownMetadata {
key,
entity_type,
declared,
suggestion,
} => {
let declared_inline = if declared.is_empty() {
"(none)".to_string()
} else {
declared.join(", ")
};
let suggestion_clause = suggestion
.as_deref()
.map(|s| format!(" Did you mean '{s}'?"))
.unwrap_or_default();
format!(
"unknown metadata field '{key}' for type '{entity_type}' — declared fields: {declared_inline}.{suggestion_clause}"
)
}
ValidationError::InvalidEnumValue {
field,
value,
allowed,
field_description,
suggestion,
type_write_rules,
entity_type,
} => {
let allowed_inline = if allowed.is_empty() {
"(none)".to_string()
} else {
allowed.join(", ")
};
let desc_clause = field_description
.as_deref()
.map(|d| format!(" Field purpose: {d}."))
.unwrap_or_default();
let suggestion_clause = suggestion
.as_deref()
.map(|s| format!(" Did you mean '{s}'?"))
.unwrap_or_default();
let rules_clause = if type_write_rules.is_empty() {
String::new()
} else {
format!(" Type-level write_rules: {}.", type_write_rules.join("; "))
};
format!(
"invalid value '{value}' for field '{field}' on type '{entity_type}' — allowed: {allowed_inline}.{desc_clause}{suggestion_clause}{rules_clause}"
)
}
ValidationError::ReadOnlyField { field } => {
format!("cannot change read-only field '{field}' via update")
}
ValidationError::SectionNotUpdatable {
section,
entity_type,
} => format!("section '{section}' is not updatable for type '{entity_type}'"),
ValidationError::InvalidRelationshipType {
input,
allowed,
suggestion,
} => {
let allowed_inline = if allowed.is_empty() {
"(none)".to_string()
} else {
allowed
.iter()
.map(|h| h.name.clone())
.collect::<Vec<_>>()
.join(", ")
};
let suggestion_clause = suggestion
.as_deref()
.map(|s| format!(" Did you mean '{s}'?"))
.unwrap_or_default();
format!(
"invalid relationship type '{input}' — must be one of the schema's declared types: {allowed_inline}.{suggestion_clause}"
)
}
ValidationError::InvalidRelationshipShape {
rel_type,
from_type,
to_type,
allowed_source_types,
allowed_target_types,
suggestion,
} => {
let sources_inline = if allowed_source_types.is_empty() {
"any".to_string()
} else {
allowed_source_types.join(", ")
};
let targets_inline = if allowed_target_types.is_empty() {
"any".to_string()
} else {
allowed_target_types.join(", ")
};
let suggestion_clause = suggestion
.as_ref()
.map(|h| format!(" Suggested rel-type: '{}'.", h.name))
.unwrap_or_default();
format!(
"relationship '{rel_type}' from type '{from_type}' to type '{to_type}' violates declared shape — allowed sources: {sources_inline}; allowed targets: {targets_inline}.{suggestion_clause}"
)
}
ValidationError::EmptyUndeclaredHeading {
section,
heading,
entity_type,
} => format!(
"section '{section}' carries heading '{heading}', which type '{entity_type}' does \
not declare and which has no body under it. An undeclared heading WITH content \
is kept byte-verbatim in the catch-all; an empty one is skipped, so this write \
would drop it. Give the heading a body, or remove it."
),
ValidationError::UnterminatedFence { section, fence } => format!(
"section '{section}' ends inside an unterminated `{fence}` code fence. In \
CommonMark an open fence runs to the end of the text, so every section heading \
written after this one would land inside the fence, be masked, and be read back \
as part of THIS section's body: the sections after it would render empty and \
the entity would still read as healthy. Close the fence with a line of \
`{fence}`, or remove the opener."
),
ValidationError::SectionContentInvalid {
section,
embedded_heading,
} => format!(
"section '{section}' content contains an embedded reserved (`# ` / `## `) heading line '{embedded_heading}' — use `### ` or deeper for sub-headings"
),
ValidationError::SectionContentControlByte {
section,
codepoint,
byte_offset,
..
} => format!(
"section '{section}' content contains a disallowed control character U+{codepoint:04X} at byte offset {byte_offset} — \
only tab (U+0009) and newline (U+000A) are permitted in section bodies. Remove the control character: it would break \
the diffable-markdown invariant (a NUL makes git treat the file as binary and text tooling truncates at it)."
),
ValidationError::InvalidFieldValue {
field,
value,
expected_type,
expected_format,
field_description,
entity_type,
} => {
let format_clause = expected_format
.as_deref()
.map(|f| format!(" Expected format: {f}."))
.unwrap_or_default();
let desc_clause = field_description
.as_deref()
.map(|d| format!(" Field purpose: {d}."))
.unwrap_or_default();
format!(
"invalid value '{value}' for field '{field}' on type '{entity_type}' — \
not a valid {expected_type}.{format_clause}{desc_clause}"
)
}
}
}
}
pub const READ_ONLY_METADATA_KEYS: &[&str] = &["mem", "id", "type"];
pub fn validate_reserved_metadata_key(key: &str) -> Result<(), ValidationError> {
if READ_ONLY_METADATA_KEYS.contains(&key) || key.starts_with('_') {
return Err(ValidationError::ReadOnlyField {
field: key.to_string(),
});
}
Ok(())
}
pub fn validate_writable_metadata_key(
key: &str,
schema: &TypeDefinition,
) -> Result<(), ValidationError> {
validate_reserved_metadata_key(key)?;
if let Some(field) = schema.metadata_field(key)
&& (field.init_timestamp || field.auto_timestamp)
{
return Err(ValidationError::ReadOnlyField {
field: key.to_string(),
});
}
Ok(())
}
pub fn validate_unsettable_metadata_key(
key: &str,
schema: &TypeDefinition,
) -> Result<(), ValidationError> {
if let Some(field) = schema.metadata_field(key)
&& (field.init_timestamp || field.auto_timestamp)
{
return Err(ValidationError::ReadOnlyField {
field: key.to_string(),
});
}
Ok(())
}
pub fn validate_updatable_section(
section: &str,
schema: &TypeDefinition,
) -> Result<(), ValidationError> {
if section == "relationships" {
return Err(ValidationError::SectionNotUpdatable {
section: section.to_string(),
entity_type: schema.name.clone(),
});
}
if !schema.updatable_fields.is_empty() && !schema.updatable_fields.iter().any(|f| f == section)
{
return Err(ValidationError::SectionNotUpdatable {
section: section.to_string(),
entity_type: schema.name.clone(),
});
}
Ok(())
}
#[derive(Debug, Clone)]
pub struct MissingRequiredSection {
pub entity_type: String,
pub key: String,
pub heading: String,
pub write_rules: Vec<String>,
}
#[derive(Debug, Clone, Copy)]
pub struct CatchAllContext<'a> {
pub key: &'a str,
pub entity_type: &'a str,
pub declared_headings: &'a [&'a str],
}
pub fn catch_all_context<'a>(
type_def: &'a memstead_schema::TypeDefinition,
buf: &'a mut Vec<&'a str>,
) -> Option<CatchAllContext<'a>> {
let key = type_def.catch_all_section()?.key.as_str();
buf.extend(type_def.sections.iter().map(|s| s.heading.as_str()));
Some(CatchAllContext {
key,
entity_type: type_def.name.as_str(),
declared_headings: buf,
})
}
fn heading_body_is_empty(body: &str, heading_line: &str) -> bool {
let mut lines = body.lines().skip_while(|l| *l != heading_line);
lines.next();
for line in lines {
if line.starts_with("## ") {
return true;
}
if !line.trim().is_empty() {
return false;
}
}
true
}
pub fn validate_section_content<'a>(
sections: impl Iterator<Item = (&'a str, &'a str)>,
catch_all: Option<CatchAllContext<'_>>,
) -> Result<(), ValidationError> {
for (key, value) in sections {
if let Some((byte_offset, ch)) = value
.char_indices()
.find(|(_, c)| c.is_control() && *c != '\t' && *c != '\n')
{
return Err(ValidationError::SectionContentControlByte {
section: key.to_string(),
control_char: ch,
codepoint: ch as u32,
byte_offset,
});
}
if let Some(fence) = crate::markdown::closing_fence_if_unterminated(value.trim()) {
return Err(ValidationError::UnterminatedFence {
section: key.to_string(),
fence,
});
}
let stored = value.trim();
let masked = crate::markdown::mask_code_blocks(stored);
for (line, masked_line) in stored.lines().zip(masked.lines()) {
let is_h2 = masked_line.starts_with("## ") && masked_line.len() > 3;
let is_h1 = masked_line.starts_with("# ") && masked_line.len() > 2;
if is_h2
&& catch_all.is_some_and(|c| {
c.key == key && !c.declared_headings.contains(&&masked_line[3..])
})
{
if heading_body_is_empty(stored, line) {
return Err(ValidationError::EmptyUndeclaredHeading {
section: key.to_string(),
heading: masked_line[3..].to_string(),
entity_type: catch_all
.map(|c| c.entity_type.to_string())
.unwrap_or_default(),
});
}
continue;
}
if is_h2 || is_h1 {
return Err(ValidationError::SectionContentInvalid {
section: key.to_string(),
embedded_heading: line.to_string(),
});
}
}
}
Ok(())
}
pub fn validate_section_keys<'a>(
provided: impl Iterator<Item = &'a str>,
schema: &TypeDefinition,
) -> Result<(), ValidationError> {
let mut declared: Vec<String> = schema.sections.iter().map(|s| s.key.clone()).collect();
declared.sort();
let declared_set: std::collections::HashSet<&str> =
schema.sections.iter().map(|s| s.key.as_str()).collect();
let catch_all_key = schema.catch_all_section().map(|s| s.key.clone());
for key in provided {
if key == "relationships" {
continue;
}
if declared_set.contains(key) {
continue;
}
let suggestion = schema
.suggest_section(key)
.or_else(|| catch_all_key.clone());
return Err(ValidationError::UnknownSection {
key: key.to_string(),
entity_type: schema.name.clone(),
declared: declared.clone(),
suggestion,
});
}
Ok(())
}
pub fn parse_metadata_value(
key: &str,
value: &str,
schema: &TypeDefinition,
) -> Result<MetadataValue, ValidationError> {
let Some(field_def) = schema.metadata_field(key) else {
let mut declared: Vec<String> = schema
.metadata_fields
.iter()
.map(|f| f.key.clone())
.collect();
declared.sort();
return Err(ValidationError::UnknownMetadata {
key: key.to_string(),
entity_type: schema.name.clone(),
declared,
suggestion: schema.suggest_metadata_field(key),
});
};
if let Some(ref allowed) = field_def.enum_values
&& !allowed.iter().any(|v| v == value)
{
let suggestion = nearest_str_match(value, allowed);
return Err(ValidationError::InvalidEnumValue {
field: key.to_string(),
value: value.to_string(),
allowed: allowed.clone(),
field_description: Some(field_def.description.clone()),
suggestion,
type_write_rules: schema.write_rules.clone(),
entity_type: schema.name.clone(),
});
}
if let Some(pattern) = field_def.value_pattern.as_ref()
&& let Ok(re) = regex::Regex::new(&format!("^(?:{pattern})$"))
{
let members: Vec<&str> = if field_def.serialization == Serialization::CsvArray {
value.split(',').map(str::trim).collect()
} else {
vec![value]
};
if let Some(bad) = members.iter().find(|m| !re.is_match(m)) {
return Err(ValidationError::InvalidFieldValue {
field: key.to_string(),
value: (*bad).to_string(),
expected_type: "String".to_string(),
expected_format: Some(format!("matching the pattern `{pattern}`")),
field_description: Some(field_def.description.clone()),
entity_type: schema.name.clone(),
});
}
}
Ok(match field_def.field_type {
FieldType::Boolean => MetadataValue::Bool(value == "true" || value == "1"),
FieldType::Number => {
if let Ok(n) = value.parse::<i64>() {
MetadataValue::Integer(n)
} else if let Ok(f) = value.parse::<f64>() {
MetadataValue::Float(f)
} else {
return Err(ValidationError::InvalidFieldValue {
field: key.to_string(),
value: value.to_string(),
expected_type: "Number".to_string(),
expected_format: Some("an integer or decimal number".to_string()),
field_description: Some(field_def.description.clone()),
entity_type: schema.name.clone(),
});
}
}
FieldType::Date => {
if !is_date_shaped(value) {
return Err(ValidationError::InvalidFieldValue {
field: key.to_string(),
value: value.to_string(),
expected_type: "Date".to_string(),
expected_format: Some("YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ".to_string()),
field_description: Some(field_def.description.clone()),
entity_type: schema.name.clone(),
});
}
MetadataValue::String(value.to_string())
}
_ => MetadataValue::String(value.to_string()),
})
}
pub fn is_date_shaped(s: &str) -> bool {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?$").unwrap())
.is_match(s)
}
#[derive(Debug, Clone)]
pub struct MissingRequiredField {
pub entity_type: String,
pub key: String,
pub description: String,
pub enum_values: Vec<String>,
}
pub fn missing_required_fields(
schema: &TypeDefinition,
supplied: &IndexMap<String, String>,
) -> Vec<MissingRequiredField> {
schema
.metadata_fields
.iter()
.filter(|f| {
!READ_ONLY_METADATA_KEYS.contains(&f.key.as_str())
&& f.is_required()
&& f.default_value.is_none()
&& !f.init_timestamp
&& !f.auto_timestamp
&& !supplied.contains_key(f.key.as_str())
})
.map(|f| MissingRequiredField {
entity_type: schema.name.clone(),
key: f.key.clone(),
description: f.description.clone(),
enum_values: f.enum_values.clone().unwrap_or_default(),
})
.collect()
}
pub fn missing_required_sections(
schema: &TypeDefinition,
sections: &IndexMap<String, String>,
) -> Vec<MissingRequiredSection> {
schema
.required_sections()
.filter_map(|sec| {
let is_empty = sections
.get(sec.key.as_str())
.is_none_or(|c| c.trim().is_empty());
is_empty.then(|| MissingRequiredSection {
entity_type: schema.name.clone(),
key: sec.key.clone(),
heading: sec.heading.clone(),
write_rules: sec.write_rules.clone(),
})
})
.collect()
}
#[derive(Debug, Clone)]
pub enum RelationshipCheck {
Ok,
OpenWarning(String),
}
pub fn validate_rel_type(
rel_type: &str,
schema: &Schema,
) -> Result<RelationshipCheck, ValidationError> {
if schema.relationship_known(rel_type) {
return Ok(RelationshipCheck::Ok);
}
match schema.mode() {
RelationshipMode::Strict => {
let allowed = declared_relationship_hints(schema);
let candidate_names: Vec<String> = allowed.iter().map(|h| h.name.clone()).collect();
let suggestion = nearest_str_match(rel_type, &candidate_names);
Err(ValidationError::InvalidRelationshipType {
input: rel_type.to_string(),
allowed,
suggestion,
})
}
RelationshipMode::Open => {
let declared: Vec<String> = declared_relationship_hints(schema)
.into_iter()
.map(|h| h.name)
.collect();
let suggestion = schema
.suggest_relationship(rel_type)
.map(|s| format!(" Did you mean '{s}'?"))
.unwrap_or_default();
let (schema_name, schema_version) = schema.id();
Ok(RelationshipCheck::OpenWarning(format!(
"relationship '{rel_type}' is not declared in schema \
'{schema_name}@{schema_version}' (mode: open). \
Accepted with default weight. Declared: [{}].{suggestion}",
declared.join(", "),
)))
}
}
}
pub fn validate_rel_shape(
rel_type: &str,
from_type: &str,
to_type: Option<&str>,
schema: &Schema,
) -> Result<(), ValidationError> {
let Some(def) = schema.relationship_def(rel_type) else {
return Ok(());
};
let source_ok = def.source_types.is_empty() || def.source_types.iter().any(|t| t == from_type);
let target_ok = def.target_types.is_empty()
|| to_type.is_none_or(|t| def.target_types.iter().any(|d| d == t));
if source_ok && target_ok {
return Ok(());
}
let to_for_err = to_type.unwrap_or("<unknown>").to_string();
let suggestion = suggest_shape_admitting(from_type, to_type, schema);
Err(ValidationError::InvalidRelationshipShape {
rel_type: rel_type.to_string(),
from_type: from_type.to_string(),
to_type: to_for_err,
allowed_source_types: def.source_types.clone(),
allowed_target_types: def.target_types.clone(),
suggestion,
})
}
#[derive(Debug, Clone)]
pub enum CrossMemRelCheck {
Ok,
EdgeNotDeclared,
Invalid(ValidationError),
}
pub fn validate_cross_mem_edge(
rel_type: &str,
from_type: &str,
to_type: Option<&str>,
source_schema: &Schema,
target_schema_ref: &memstead_schema::SchemaRef,
) -> CrossMemRelCheck {
let entries = source_schema.cross_mem_entries(&target_schema_ref.name);
if entries.is_empty() {
return CrossMemRelCheck::EdgeNotDeclared;
}
let Some(def) = entries
.iter()
.find_map(|entry| entry.definitions.iter().find(|d| d.name == rel_type))
else {
if !entries.iter().any(|e| e.to_schema != "*") {
return CrossMemRelCheck::EdgeNotDeclared;
}
let allowed: Vec<RelationshipHint> = cross_mem_entries_hints(&entries);
let candidate_names: Vec<String> = allowed.iter().map(|h| h.name.clone()).collect();
let suggestion = nearest_str_match(rel_type, &candidate_names);
return CrossMemRelCheck::Invalid(ValidationError::InvalidRelationshipType {
input: rel_type.to_string(),
allowed,
suggestion,
});
};
let source_ok = def.source_types.is_empty() || def.source_types.iter().any(|t| t == from_type);
let target_ok = def.target_types.is_empty()
|| to_type.is_none_or(|t| def.target_types.iter().any(|d| d == t));
if source_ok && target_ok {
return CrossMemRelCheck::Ok;
}
let to_for_err = to_type.unwrap_or("<unknown>").to_string();
let suggestion = entries
.iter()
.find_map(|entry| cross_mem_suggest_shape(entry, from_type, to_type));
CrossMemRelCheck::Invalid(ValidationError::InvalidRelationshipShape {
rel_type: rel_type.to_string(),
from_type: from_type.to_string(),
to_type: to_for_err,
allowed_source_types: def.source_types.clone(),
allowed_target_types: def.target_types.clone(),
suggestion,
})
}
fn cross_mem_entries_hints(entries: &[&CrossMemRelationshipEntry]) -> Vec<RelationshipHint> {
let mut out: Vec<RelationshipHint> = Vec::new();
for entry in entries {
for hint in cross_mem_entry_hints(entry) {
if !out.iter().any(|h| h.name == hint.name) {
out.push(hint);
}
}
}
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
fn cross_mem_entry_hints(entry: &CrossMemRelationshipEntry) -> Vec<RelationshipHint> {
let mut out: Vec<RelationshipHint> = entry
.definitions
.iter()
.filter(|d| d.name != "_default")
.map(|d| RelationshipHint {
name: d.name.clone(),
when_to_use: d.when_to_use.clone(),
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
fn cross_mem_suggest_shape(
entry: &CrossMemRelationshipEntry,
from_type: &str,
to_type: Option<&str>,
) -> Option<RelationshipHint> {
entry
.definitions
.iter()
.filter(|d| d.name != "_default")
.find(|d| cross_mem_def_admits(d, from_type, to_type))
.map(|d| RelationshipHint {
name: d.name.clone(),
when_to_use: d.when_to_use.clone(),
})
}
fn cross_mem_def_admits(d: &RelationshipDef, from_type: &str, to_type: Option<&str>) -> bool {
let src_ok = d.source_types.is_empty() || d.source_types.iter().any(|t| t == from_type);
let tgt_ok =
d.target_types.is_empty() || to_type.is_none_or(|t| d.target_types.iter().any(|x| x == t));
src_ok && tgt_ok
}
fn suggest_shape_admitting(
from_type: &str,
to_type: Option<&str>,
schema: &Schema,
) -> Option<RelationshipHint> {
schema
.manifest
.relationships
.definitions
.iter()
.filter(|d| d.name != "_default")
.find(|d| {
let src_ok = d.source_types.is_empty() || d.source_types.iter().any(|t| t == from_type);
let tgt_ok = d.target_types.is_empty()
|| to_type.is_none_or(|t| d.target_types.iter().any(|x| x == t));
src_ok && tgt_ok
})
.map(|d| RelationshipHint {
name: d.name.clone(),
when_to_use: d.when_to_use.clone(),
})
}
fn declared_relationship_hints(schema: &Schema) -> Vec<RelationshipHint> {
let mut out: Vec<RelationshipHint> = schema
.manifest
.relationships
.definitions
.iter()
.filter(|d| d.name != "_default")
.map(|d| RelationshipHint {
name: d.name.clone(),
when_to_use: d.when_to_use.clone(),
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
fn nearest_str_match(needle: &str, candidates: &[String]) -> Option<String> {
let noise_floor = (needle.chars().count() / 2).max(1);
let mut best: Option<(usize, String)> = None;
for cand in candidates {
let d = strsim::levenshtein(needle, cand);
if d == 0 || d > noise_floor {
continue;
}
match &best {
Some((bd, _)) if *bd <= d => {}
_ => best = Some((d, cand.clone())),
}
}
best.map(|(_, name)| name)
}
#[cfg(test)]
mod tests;