fv-connect 0.1.0

FusionVault Conduit: read relational, file and REST sources into rows with mandatory access control pushed into the read, write results back with atomic promotion, and drive incremental base-ingest scans, changelogs and label normalisation checked against the published conformance vectors.
Documentation
//! Datasource row normalization, pinned to the contract's `normalize-row` conformance vectors.
//!
//! A raw curated source row carries security labels as ordinary columns (`classification_level`,
//! `compartments`, …); the binding's `label_columns` says which column feeds which taxonomy axis. This
//! turns that into a clean `_labels` map — once, at the source — so everything downstream (changelog,
//! merge, index, OSS filter) sees a clean row keyed by axis name.
//!
//! Multi-datasource CLAIMS project the row to the properties a source may emit: a source
//! physically cannot emit another source's properties, however its table is shaped — a capability
//! boundary at ingestion, not a hint. Row (T3) labels attach only for the PRIMARY source.

use std::collections::{BTreeMap, BTreeSet};

use fv_value::Value;

use crate::Row;

/// The normalization-relevant slice of a datasource binding (an object type's `datasource` block).
#[derive(Debug, Clone, Default)]
pub struct LabelBinding {
    /// axis → source label column.
    pub label_columns: BTreeMap<String, String>,
    /// axis → default label value (applied under `DEFAULT`).
    pub default_label: BTreeMap<String, Value>,
    /// `DENY` (absent axis stays absent — fail-closed) | `DEFAULT` (apply `default_label`).
    pub on_missing_label: String,
    /// The CLAIMS. Empty = the singular-sugar 'claims everything'.
    pub properties: Vec<String>,
    /// The binding's own operational columns — always pass the claims projection.
    pub correlation_token_column: Option<String>,
    pub source_updated_at_column: Option<String>,
    /// Row (T3) labels attach only for the primary source.
    pub primary: bool,
}

fn row_get<'a>(row: &'a Row, key: &str) -> Option<&'a Value> {
    row.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}

/// Split a raw source row into `{<business props>, rid, _labels?}`; strip the raw label columns,
/// project to the binding's claims, and fold the label columns into `_labels` by axis.
pub fn normalize_row(row: &Row, binding: &LabelBinding) -> Row {
    let label_cols: BTreeSet<&str> = binding.label_columns.values().map(String::as_str).collect();

    // Strip the raw label columns, preserving column order.
    let mut out: Row = row
        .iter()
        .filter(|(k, _)| !label_cols.contains(k.as_str()))
        .cloned()
        .collect();

    // Claims projection: rid + the binding's own operational columns always pass.
    if !binding.properties.is_empty() {
        let mut allowed: BTreeSet<&str> = binding.properties.iter().map(String::as_str).collect();
        allowed.insert("rid");
        if let Some(c) = &binding.correlation_token_column {
            allowed.insert(c.as_str());
        }
        if let Some(c) = &binding.source_updated_at_column {
            allowed.insert(c.as_str());
        }
        out.retain(|(k, _)| allowed.contains(k.as_str()));
    }

    // Fold label columns → `_labels` by axis. Present, non-null column wins; else DEFAULT applies the
    // default label; DENY leaves the axis absent (fail-closed downstream, the S10 gap).
    let default = binding.on_missing_label == "DEFAULT";
    let mut labels: BTreeMap<String, Value> = BTreeMap::new();
    for (axis, column) in &binding.label_columns {
        match row_get(row, column) {
            Some(v) if !matches!(v, Value::Null) => {
                labels.insert(axis.clone(), v.clone());
            }
            _ if default => {
                if let Some(default_val) = binding.default_label.get(axis) {
                    labels.insert(axis.clone(), default_val.clone());
                }
            }
            _ => {}
        }
    }

    // Also default axes that have a defaultLabel but no source column at all (DEFAULT policy).
    if default {
        for (axis, value) in &binding.default_label {
            labels.entry(axis.clone()).or_insert_with(|| value.clone());
        }
    }

    if !labels.is_empty() && binding.primary {
        out.push(("_labels".to_string(), Value::Obj(labels)));
    }
    out
}