use std::io::Write;
use crate::errors::{Error, Result};
pub const CODE_EDGE_SHAPES: &str = include_str!("../shapes/code-edges.ttl");
#[derive(Debug, Clone)]
pub struct Validation {
pub conforms: bool,
pub violations: Vec<String>,
}
pub fn validate(data_ttl: &str, shapes_ttl: &str) -> Result<Validation> {
use rudof_lib::formats::{DataFormat, InputSpec, ResultShaclValidationFormat, ShaclFormat};
use rudof_lib::{Rudof, RudofConfig};
let mut rudof = Rudof::new(RudofConfig::default());
rudof
.load_data()
.with_data(&[InputSpec::str(data_ttl)])
.with_data_format(&DataFormat::Turtle)
.execute()
.map_err(|e| Error::Promote(format!("promotion data is not valid Turtle: {e}")))?;
rudof
.load_shacl_shapes()
.with_shacl_schema(&InputSpec::str(shapes_ttl))
.with_shacl_schema_format(&ShaclFormat::Turtle)
.execute()
.map_err(|e| Error::Promote(format!("SHACL shapes did not load: {e}")))?;
rudof
.validate_shacl()
.execute()
.map_err(|e| Error::Promote(format!("SHACL validation failed to run: {e}")))?;
let mut buf: Vec<u8> = Vec::new();
rudof
.serialize_shacl_validation_results(&mut buf)
.with_result_shacl_validation_format(&ResultShaclValidationFormat::Turtle)
.execute()
.map_err(|e| Error::Promote(format!("could not read validation report: {e}")))?;
let report = String::from_utf8_lossy(&buf);
Ok(parse_report(&report))
}
fn parse_report(report: &str) -> Validation {
let conforms = report.contains("sh:conforms true") || report.contains("sh:conforms true");
let mut violations = Vec::new();
for line in report.lines() {
let l = line.trim();
if let Some(rest) = l.strip_prefix("sh:resultMessage") {
let msg = rest.trim().trim_end_matches(';').trim().trim_matches('"');
if !msg.is_empty() {
violations.push(msg.to_string());
}
}
}
if !conforms && violations.is_empty() {
violations.push("SHACL validation reported non-conformance (see report)".to_string());
}
Validation {
conforms,
violations,
}
}
fn quipu_auth_token() -> Option<String> {
normalize_token(std::env::var("QUIPU_AUTH_TOKEN").ok()).or_else(token_from_file)
}
fn token_from_file() -> Option<String> {
let path = std::env::var("QUIPU_AUTH_TOKEN_FILE")
.ok()
.filter(|p| !p.is_empty())
.or_else(|| {
std::env::var("HOME")
.ok()
.map(|h| format!("{h}/.config/quipu/token"))
})?;
normalize_token(
std::fs::read_to_string(path)
.ok()
.map(|s| s.trim().to_string()),
)
}
fn normalize_token(raw: Option<String>) -> Option<String> {
raw.filter(|t| !t.is_empty())
}
pub fn write_knot(endpoint: &str, turtle: &str, source: &str) -> Result<KnotResult> {
let url = format!("{}/knot", endpoint.trim_end_matches('/'));
let auth = quipu_auth_token();
let body =
serde_json::json!({ "turtle": turtle, "actor": "hank", "source": source }).to_string();
const ATTEMPTS: u32 = 3;
let mut resp = None;
let mut last_err = String::new();
for attempt in 1..=ATTEMPTS {
let mut req = ureq::post(&url).set("Content-Type", "application/json");
if let Some(token) = &auth {
req = req.set("Authorization", &format!("Bearer {token}"));
}
match req.send_string(&body) {
Ok(r) => {
resp = Some(r);
break;
}
Err(ureq::Error::Status(code, _)) if code < 500 => {
return Err(Error::Promote(format!("POST {url} failed: status {code}")));
}
Err(e) => {
last_err = e.to_string();
if attempt < ATTEMPTS {
std::thread::sleep(std::time::Duration::from_secs(2 * u64::from(attempt)));
}
}
}
}
let resp = resp.ok_or_else(|| {
Error::Promote(format!(
"POST {url} failed after {ATTEMPTS} attempts (transient errors retried): {last_err}"
))
})?;
let text = resp
.into_string()
.map_err(|e| Error::Promote(format!("could not read /knot response: {e}")))?;
if let Ok(refusal) = serde_json::from_str::<KnotRefusal>(&text) {
if !refusal.conforms {
let issues = refusal
.issues
.iter()
.map(|i| format!("{} {} on {}", i.component, i.message, i.focus_node))
.collect::<Vec<_>>()
.join("; ");
return Err(Error::Promote(format!(
"quipu refused the write (server-side SHACL, {} violation(s)): {issues}. \
hank's own shapes ACCEPTED this projection — the two shape sets have \
drifted; reconcile shapes/code-edges.ttl with quipu's stored registry.",
refusal.violations
)));
}
}
let parsed: KnotResult = serde_json::from_str(&text)
.map_err(|e| Error::Promote(format!("unexpected /knot response {text:?}: {e}")))?;
Ok(parsed)
}
#[derive(Debug, serde::Deserialize)]
struct KnotRefusal {
conforms: bool,
#[serde(default)]
violations: u64,
#[serde(default)]
issues: Vec<KnotIssue>,
}
#[derive(Debug, serde::Deserialize)]
struct KnotIssue {
#[serde(default)]
component: String,
#[serde(default)]
message: String,
#[serde(default)]
focus_node: String,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct KnotResult {
pub count: u64,
#[serde(default)]
pub tx_id: Option<u64>,
}
const CHUNK_LIMIT: usize = 1_500_000;
fn chunk_turtle(turtle: &str, limit: usize) -> Result<Vec<String>> {
if turtle.len() <= limit {
return Ok(vec![turtle.to_string()]);
}
let mut blocks = turtle.split("\n\n");
let header = blocks.next().unwrap_or_default();
let mut chunks = Vec::new();
let mut cur = String::from(header);
let push_piece = |cur: &mut String, chunks: &mut Vec<String>, piece: &str| -> Result<()> {
if header.len() + 2 + piece.len() > limit {
return Err(Error::Promote(format!(
"a single Turtle statement is {} bytes, over the {limit} byte chunk limit — cannot split below statement granularity",
piece.len()
)));
}
if cur.len() + 2 + piece.len() > limit {
chunks.push(std::mem::replace(cur, String::from(header)));
}
cur.push_str("\n\n");
cur.push_str(piece);
Ok(())
};
for block in blocks {
if block.trim().is_empty() {
continue;
}
if header.len() + 2 + block.len() <= limit {
push_piece(&mut cur, &mut chunks, block)?;
continue;
}
let mut piece = String::new();
for line in block.lines() {
if !piece.is_empty() {
piece.push('\n');
}
piece.push_str(line);
if line.trim_end().ends_with('.') && header.len() + 2 + piece.len() > limit / 2 {
push_piece(&mut cur, &mut chunks, &piece)?;
piece.clear();
}
}
if !piece.trim().is_empty() {
push_piece(&mut cur, &mut chunks, &piece)?;
}
}
if cur.len() > header.len() {
chunks.push(cur);
}
Ok(chunks)
}
#[derive(Debug, Clone)]
pub struct WriteSummary {
pub count: u64,
pub tx_ids: Vec<u64>,
pub chunks: usize,
}
pub fn promote(endpoint: &str, turtle: &str, source: &str) -> Result<Promotion> {
let v = validate(turtle, CODE_EDGE_SHAPES)?;
if !v.conforms {
return Ok(Promotion::Refused(v.violations));
}
let chunks = chunk_turtle(turtle, CHUNK_LIMIT)?;
let total = chunks.len();
let mut summary = WriteSummary {
count: 0,
tx_ids: Vec::new(),
chunks: total,
};
for (i, chunk) in chunks.iter().enumerate() {
let knot = write_knot(endpoint, chunk, source).map_err(|e| {
Error::Promote(format!(
"chunk {}/{total} failed after {} chunk(s) landed — re-running is safe (deterministic IRIs supersede): {e}",
i + 1,
i
))
})?;
summary.count += knot.count;
if let Some(t) = knot.tx_id {
summary.tx_ids.push(t);
}
}
Ok(Promotion::Wrote(summary))
}
#[derive(Debug)]
pub enum Promotion {
Wrote(WriteSummary),
Refused(Vec<String>),
}
impl Promotion {
pub fn report(&self, w: &mut impl Write) -> std::io::Result<bool> {
match self {
Promotion::Wrote(k) => {
let txs = match k.tx_ids.as_slice() {
[] => String::new(),
[one] => format!(" (tx {one})"),
[first, .., last] => format!(" (tx {first}..{last})"),
};
let chunked = if k.chunks > 1 {
format!(" in {} chunks", k.chunks)
} else {
String::new()
};
writeln!(w, " promoted: {} triples present{txs}{chunked}", k.count)?;
Ok(true)
}
Promotion::Refused(vs) => {
writeln!(
w,
" REFUSED — promotion did not pass SHACL, wrote nothing:"
)?;
for v in vs {
writeln!(w, " - {v}")?;
}
Ok(false)
}
}
}
}
#[cfg(test)]
#[path = "promote_test.rs"]
mod promote_test;