diff --git a/docs/odcs/field-mapping.md b/docs/odcs/field-mapping.md index 1b1de13a..417885fc 100644 --- a/docs/odcs/field-mapping.md +++ b/docs/odcs/field-mapping.md @@ -33,7 +33,7 @@ | `name` | string | required | _(none at top level)_ | — | — | **Restructured** | [Fundamentals](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/fundamentals/) / [Schema](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/schema/) | ODCS has no single `name` field at the contract level. The equivalent contract identity is expressed via `dataProduct` (Fundamentals) plus `schema[].name` (the dataset name). On export CG `name` should populate **both** `dataProduct` and `schema[0].name`. On import, `schema[0].name` wins. **Round-trip risk.** | | `description` | string (optional) | optional | `description.purpose` | string (inside object) | O | **Restructured** | [Fundamentals](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/fundamentals/) | ODCS `description` is an object with sub-keys `purpose`, `limitations`, `usage`. CG's flat string maps to `description.purpose`. On import, CG should concatenate any present sub-keys with a delimiter. | | `compliance_mode` | bool (default false) | optional | _(none)_ | — | — | **No equivalent** | — | RFC-004 per-version enforcement flag. No ODCS home. Must be exported as `x-contractgate-compliance-mode`. | -| `ontology` | Ontology object | required | `schema` (array) | array | R | **Restructured** | [Schema](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/schema/) | CG flattens all field definitions under a single `ontology.entities[]` list. ODCS nests field definitions inside one or more `schema[]` dataset objects (tables, topics). On export, all CG entities are placed under a single synthesised `schema[0]`. On import, only `schema[0].properties[]` is processed unless explicitly extended. | +| `ontology` | Ontology object | required | `schema` (array) | array | R | **Restructured** | [Schema](https://bitol-io.github.io/open-data-contract-standard/v3.1.0/schema/) | CG flattens all field definitions under a single `ontology.entities[]` list. ODCS nests field definitions inside one or more `schema[]` dataset objects (tables, topics). On export, all CG entities are placed under a single synthesised `schema[0]`. On import, one schema object is processed: the first, or the one named by `schema_object` (`--schema-object` on the CLI). The others are listed in a note. | | `glossary` | GlossaryEntry[] (default []) | optional | _(none as top-level block)_ | — | — | **No equivalent** | — | ODCS has no dedicated glossary section. Per-field semantic data is distributed across `schema[].properties[].description`, `.businessName`, and `.authoritativeDefinitions`. Full glossary must be preserved as `x-contractgate-glossary`. See gap-analysis.md §CG-GAP-003. | | `metrics` | MetricDefinition[] (default []) | optional | _(none as top-level block)_ | — | — | **No equivalent** | — | ODCS has no formula-metrics section. Closest available landing zones are `schema[].quality[]` (for threshold rules) and `slaProperties[]` (for SLO-style bounds). Formula metrics have no structural home. Full block must be preserved as `x-contractgate-metrics`. See gap-analysis.md §CG-GAP-004. | diff --git a/docs/odcs/using-odcs-directly.md b/docs/odcs/using-odcs-directly.md index 5157ebe1..ab39117c 100644 --- a/docs/odcs/using-odcs-directly.md +++ b/docs/odcs/using-odcs-directly.md @@ -44,11 +44,37 @@ To shape synthetic values on a number or integer property, add a custom property `type` is `uniform`, `normal`, `lognormal` (`mean` and `sd` of the underlying normal) or `exponential` (`rate`). Details: [synthetic data reference](../synthetic-data-reference.md#value-distributions). A bad value is an import error that names the property. +## Choosing a schema object + +An ODCS file can describe several tables or topics in `schema[]`. A +DataContractGate contract covers one of them. The first is used unless you pick +one by `name` (`physicalName` and `id` also match): + +```sh +contractgate validate --schema-object customers contracts/shop.odcs.yaml +contractgate synth --schema-object customers contracts/shop.odcs.yaml +``` + +`--schema-object` is on `validate`, `synth`, `test` and `enforce`. The API takes +`schema_object` on `POST /contracts/synth` (with `yaml_content`) and on +`POST /contracts/import`. An unknown name is an error that lists the names in +the file. A native contract ignores it. + +The note that lists the ignored objects (and any composite key or relationships +note) is printed by the CLI and returned as `notes` in the JSON response of +`POST /contracts/synth` and `POST /contracts/import`. `notes` is left out when +there is nothing to say. To cover several objects, import each one as its own +contract. + ## What does not map -- Only `schema[0]` is read. Other schema objects are reported as a note - (`contractgate validate` prints it) and skipped. -- `relationships` and foreign keys, composite primary key uniqueness. +- One schema object is read per contract (see below). The others are skipped + and listed in a note. +- `relationships` and foreign keys. A contract validates one object's events + and has no lookup into another, so these are not enforced. A note says so. +- Uniqueness of a composite primary key. Each key column is made required, but + uniqueness rules cover one field, so the combination is not checked. A note + says so. - Dataset-level `quality` (for example `rowCount`), `sql` and `custom` quality checks from other engines. - `servers`, `team`, `roles`, `slaProperties`, `support`, `price`, diff --git a/docs/synthetic-data-reference.md b/docs/synthetic-data-reference.md index 02accf4f..c98033a4 100644 --- a/docs/synthetic-data-reference.md +++ b/docs/synthetic-data-reference.md @@ -194,4 +194,5 @@ It takes the same options as the Rust CLI plus `--contract-id`, `--version`, `-- ## ODCS input `contractgate synth` and `POST /contracts/synth` accept an ODCS v3.x document -with no `ontology`. See [`odcs/using-odcs-directly.md`](odcs/using-odcs-directly.md). +with no `ontology`. Pass `--schema-object NAME` (or `schema_object` in the API) to pick one object of a multi-object file; the response lists unmapped content in `notes`. +See [`odcs/using-odcs-directly.md`](odcs/using-odcs-directly.md). diff --git a/src/cli/commands/enforce.rs b/src/cli/commands/enforce.rs index 86f80758..ed9042d1 100644 --- a/src/cli/commands/enforce.rs +++ b/src/cli/commands/enforce.rs @@ -38,6 +38,11 @@ pub struct EnforceArgs { #[arg(long, env = "CG_KAFKA_BROKER", value_name = "HOST:PORT")] pub broker: Option, + /// For an ODCS file with several `schema` objects: the one to use, by + /// name (default: the first). + #[arg(long, value_name = "NAME")] + pub schema_object: Option, + /// Kafka topic to consume. #[arg(long, value_name = "TOPIC")] pub topic: Option, @@ -74,7 +79,7 @@ pub struct EnforceArgs { pub fn run(args: &EnforceArgs) -> anyhow::Result { // Load and compile the contract. - let (contract_name, compiled) = load_contract(&args.contract)?; + let (contract_name, compiled) = load_contract(&args.contract, args.schema_object.as_deref())?; // Collect events to validate. let events = collect_events(args)?; @@ -130,7 +135,10 @@ pub fn run(args: &EnforceArgs) -> anyhow::Result { // Helpers // --------------------------------------------------------------------------- -fn load_contract(spec: &str) -> anyhow::Result<(String, CompiledContract)> { +fn load_contract( + spec: &str, + schema_object: Option<&str>, +) -> anyhow::Result<(String, CompiledContract)> { if spec.starts_with("id:") { anyhow::bail!( "contract ID lookup (id:uuid) is a Phase 2 feature; \ @@ -139,8 +147,9 @@ fn load_contract(spec: &str) -> anyhow::Result<(String, CompiledContract)> { } let yaml = std::fs::read_to_string(spec).map_err(|e| anyhow::anyhow!("cannot read {spec}: {e}"))?; - let contract: Contract = crate::odcs::parse_contract_yaml(&yaml) - .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; + let (contract, _notes): (Contract, Vec) = + crate::odcs::parse_contract_yaml_with(&yaml, schema_object) + .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; let name = contract.name.clone(); let compiled = CompiledContract::compile(contract) .map_err(|e| anyhow::anyhow!("contract compile failed: {e}"))?; diff --git a/src/cli/commands/synth.rs b/src/cli/commands/synth.rs index eba0e022..f6dc990a 100644 --- a/src/cli/commands/synth.rs +++ b/src/cli/commands/synth.rs @@ -50,6 +50,11 @@ pub struct SynthArgs { /// Write to this file instead of stdout. #[arg(long, short = 'o', value_name = "FILE")] pub out: Option, + + /// For an ODCS file with several `schema` objects: the one to use, by + /// name (default: the first). + #[arg(long, value_name = "NAME")] + pub schema_object: Option, } #[derive(Debug, Clone, Copy, clap::ValueEnum)] @@ -66,13 +71,13 @@ pub fn run(args: &SynthArgs) -> Result { return Ok(2); } }; - if let Ok((_, notes)) = crate::odcs::normalize_contract_yaml(&yaml) { - for n in notes { - eprintln!("note: {n}"); + let compiled = match synth::compile_yaml_with(&yaml, args.schema_object.as_deref()) { + Ok((c, notes)) => { + for n in notes { + eprintln!("note: {n}"); + } + c } - } - let compiled = match synth::compile_yaml(&yaml) { - Ok(c) => c, Err(e) => { eprintln!("error: {}", e.message); return Ok(2); diff --git a/src/cli/commands/test.rs b/src/cli/commands/test.rs index a6a67354..2347931b 100644 --- a/src/cli/commands/test.rs +++ b/src/cli/commands/test.rs @@ -46,6 +46,11 @@ pub struct TestArgs { /// Summary line only; suppress per-violation detail. #[arg(long)] pub quiet: bool, + + /// For an ODCS file with several `schema` objects: the one to use, by + /// name (default: the first). + #[arg(long, value_name = "NAME")] + pub schema_object: Option, } #[derive(Debug, Clone, clap::ValueEnum)] @@ -90,11 +95,12 @@ struct Summary { pub fn run(args: &TestArgs) -> anyhow::Result { // --- Load + compile contract (exit 2 on failure) ---------------------- - let (contract_name, compiled) = load_contract(&args.contract).map_err(|e| { - eprintln!("error: {e:#}"); - // We can't return i32 from map_err; we propagate and handle at call site. - e - })?; + let (contract_name, compiled) = load_contract(&args.contract, args.schema_object.as_deref()) + .map_err(|e| { + eprintln!("error: {e:#}"); + // We can't return i32 from map_err; we propagate and handle at call site. + e + })?; // --- Read records (exit 2 on top-level parse failure) ----------------- let records = read_records(&args.data).map_err(|e| { @@ -216,11 +222,15 @@ impl Format { } } -fn load_contract(path: &PathBuf) -> anyhow::Result<(String, CompiledContract)> { +fn load_contract( + path: &PathBuf, + schema_object: Option<&str>, +) -> anyhow::Result<(String, CompiledContract)> { let yaml = std::fs::read_to_string(path) .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", path.display()))?; - let contract: Contract = crate::odcs::parse_contract_yaml(&yaml) - .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; + let (contract, _notes): (Contract, Vec) = + crate::odcs::parse_contract_yaml_with(&yaml, schema_object) + .map_err(|e| anyhow::anyhow!("invalid contract YAML: {e}"))?; let name = contract.name.clone(); let compiled = CompiledContract::compile(contract) .map_err(|e| anyhow::anyhow!("contract compile failed: {e}"))?; diff --git a/src/cli/commands/validate.rs b/src/cli/commands/validate.rs index fba95467..12fd6300 100644 --- a/src/cli/commands/validate.rs +++ b/src/cli/commands/validate.rs @@ -16,6 +16,11 @@ pub struct ValidateArgs { /// Emit machine-readable JSON output. #[arg(long)] pub json: bool, + + /// For an ODCS file with several `schema` objects: the one to use, by + /// name (default: the first). + #[arg(long, value_name = "NAME")] + pub schema_object: Option, } #[derive(Serialize)] @@ -57,7 +62,7 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result { let mut any_failure = false; for path in &files { - let result = validate_file(path); + let result = validate_file(path, args.schema_object.as_deref()); match result { Ok(notes) => { let name = path.display().to_string(); @@ -99,11 +104,11 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result { /// Native or ODCS v3.x YAML. Returns notes for anything in an ODCS document /// that did not map. -fn validate_file(path: &Path) -> Result> { +fn validate_file(path: &Path, schema_object: Option<&str>) -> Result> { let src = std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("cannot read file: {e}"))?; let (contract, notes): (Contract, Vec) = - crate::odcs::parse_contract_yaml_with_notes(&src) + crate::odcs::parse_contract_yaml_with(&src, schema_object) .map_err(|e| anyhow::anyhow!("YAML parse error: {e}"))?; CompiledContract::compile(contract).map_err(|e| anyhow::anyhow!("compile error: {e}"))?; Ok(notes) diff --git a/src/contract.rs b/src/contract.rs index 66173ceb..fd1b0823 100644 --- a/src/contract.rs +++ b/src/contract.rs @@ -1331,6 +1331,11 @@ pub struct VersionResponse { pub import_source: ImportSource, /// When `true`, human review is required before promotion to stable. pub requires_review: bool, + /// Import notes: ODCS content that did not map (ignored schema objects, + /// composite key, relationships). Only set by `POST /contracts/import`, + /// and omitted from the JSON when empty. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub notes: Vec, } impl From<&ContractVersion> for VersionResponse { @@ -1348,6 +1353,7 @@ impl From<&ContractVersion> for VersionResponse { egress_leakage_mode: v.egress_leakage_mode, import_source: v.import_source, requires_review: v.requires_review, + notes: Vec::new(), } } } diff --git a/src/main.rs b/src/main.rs index 87862ea8..fd946ba3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -970,7 +970,8 @@ async fn import_odcs_handler( .await .map_err(|e| AppError::BadRequest(e.to_string()))?; - let result = odcs::import_odcs(&body.odcs_yaml).map_err(AppError::BadRequest)?; + let result = odcs::import_odcs_with(&body.odcs_yaml, body.schema_object.as_deref()) + .map_err(AppError::BadRequest)?; // Name override from request body wins over the ODCS-parsed name. let name_in_yaml: Contract = serde_yaml::from_str(&result.yaml_content) @@ -1011,7 +1012,9 @@ async fn import_odcs_handler( state.self_hosted, ) .await?; - return Ok((StatusCode::CREATED, Json(VersionResponse::from(&cv)))); + let mut resp = VersionResponse::from(&cv); + resp.notes = result.warnings; + return Ok((StatusCode::CREATED, Json(resp))); } // No target: a new identity needs an org (NOT NULL column). @@ -1059,7 +1062,9 @@ async fn import_odcs_handler( ) .await?; - Ok((StatusCode::CREATED, Json(VersionResponse::from(&cv)))) + let mut resp = VersionResponse::from(&cv); + resp.notes = result.warnings; + Ok((StatusCode::CREATED, Json(resp))) } /// `GET /contracts/:id/versions/:version/export` — return the contract version diff --git a/src/odcs.rs b/src/odcs.rs index d1447a6a..1ae3db02 100644 --- a/src/odcs.rs +++ b/src/odcs.rs @@ -704,6 +704,14 @@ fn description_text(v: Option<&Value>) -> Option { /// transforms, glossary, metrics, and dataset-level rules (`rowCount`) are /// not recoverable — the caller sets `requires_review = true` (D-002). pub fn import_odcs(yaml: &str) -> Result { + import_odcs_with(yaml, None) +} + +/// [`import_odcs`] for a document whose `schema` has several objects: +/// `schema_object` picks one by `name` (or `physicalName`, or `id`); the +/// first object is used when it is `None`. A DataContractGate export (lossless +/// import) is a single contract, so the choice does not apply to it. +pub fn import_odcs_with(yaml: &str, schema_object: Option<&str>) -> Result { let doc: Value = serde_yaml::from_str(yaml).map_err(|e| format!("invalid ODCS YAML: {e}"))?; let mapping = doc @@ -736,9 +744,17 @@ pub fn import_odcs(yaml: &str) -> Result { }; if root_extension(mapping, "x-contractgate-version").is_some() { - import_mode_a(mapping, version) + let mut r = import_mode_a(mapping, version)?; + if schema_object.is_some() { + r.warnings.push( + "schema_object ignored: this document is a DataContractGate export, \ + which carries one contract" + .to_string(), + ); + } + Ok(r) } else { - import_mode_b(mapping, version) + import_mode_b(mapping, version, schema_object) } } @@ -797,10 +813,20 @@ fn looks_like_odcs(yaml: &str) -> bool { pub fn normalize_contract_yaml( yaml: &str, ) -> Result<(std::borrow::Cow<'_, str>, Vec), String> { + normalize_contract_yaml_with(yaml, None) +} + +/// [`normalize_contract_yaml`] with a `schema_object` choice for ODCS +/// documents that have several schema objects (see [`import_odcs_with`]). +/// Ignored for native YAML. +pub fn normalize_contract_yaml_with<'a>( + yaml: &'a str, + schema_object: Option<&str>, +) -> Result<(std::borrow::Cow<'a, str>, Vec), String> { if !looks_like_odcs(yaml) { return Ok((std::borrow::Cow::Borrowed(yaml), Vec::new())); } - let r = import_odcs(yaml).map_err(|e| format!("ODCS import: {e}"))?; + let r = import_odcs_with(yaml, schema_object).map_err(|e| format!("ODCS import: {e}"))?; Ok((std::borrow::Cow::Owned(r.yaml_content), r.warnings)) } @@ -811,7 +837,15 @@ pub fn parse_contract_yaml(yaml: &str) -> Result { /// Like [`parse_contract_yaml`], also returning ODCS import notes. pub fn parse_contract_yaml_with_notes(yaml: &str) -> Result<(Contract, Vec), String> { - let (native, notes) = normalize_contract_yaml(yaml)?; + parse_contract_yaml_with(yaml, None) +} + +/// [`parse_contract_yaml_with_notes`] with a `schema_object` choice. +pub fn parse_contract_yaml_with( + yaml: &str, + schema_object: Option<&str>, +) -> Result<(Contract, Vec), String> { + let (native, notes) = normalize_contract_yaml_with(yaml, schema_object)?; let contract: Contract = serde_yaml::from_str(&native).map_err(|e| e.to_string())?; Ok((contract, notes)) } @@ -877,7 +911,11 @@ fn import_mode_a(doc: &Mapping, version: String) -> Result // ── Mode B (stripped / foreign ODCS) ───────────────────────────────────────── -fn import_mode_b(doc: &Mapping, version: String) -> Result { +fn import_mode_b( + doc: &Mapping, + version: String, + schema_object: Option<&str>, +) -> Result { let schema_seq = doc .get("schema") .and_then(|v| v.as_sequence()) @@ -887,14 +925,41 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result .to_string() })?; + let object_name = |v: &Value| -> String { + v.as_mapping() + .and_then(|m| m.get("name")) + .and_then(|n| n.as_str()) + .unwrap_or("?") + .to_string() + }; + // Which schema object: by name, physicalName or id when asked, else the first. + let idx = match schema_object { + None => 0, + Some(want) => schema_seq + .iter() + .position(|o| { + o.as_mapping().is_some_and(|m| { + ["name", "physicalName", "id"] + .iter() + .any(|k| m.get(*k).and_then(|v| v.as_str()) == Some(want)) + }) + }) + .ok_or_else(|| { + let names: Vec = schema_seq.iter().map(object_name).collect(); + format!( + "schema object '{want}' not found; this document has: {}", + names.join(", ") + ) + })?, + }; let schema0 = schema_seq - .first() + .get(idx) .and_then(|v| v.as_mapping()) .ok_or_else(|| { "ODCS 'schema' array is empty or its first entry is not a mapping".to_string() })?; - // Contract name: dataProduct › schema[0].name › root name (the order + // Contract name: dataProduct › schema object name › root name (the order // existing imports already use). let name = doc .get("dataProduct") @@ -914,8 +979,8 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result .filter(|p| !p.is_empty()) .ok_or_else(|| { format!( - "ODCS schema[0] ('{}') has no properties; nothing to validate. \ - Add schema[0].properties[] with a name and logicalType per field", + "ODCS schema[{idx}] ('{}') has no properties; nothing to validate. \ + Add schema[{idx}].properties[] with a name and logicalType per field", schema0.get("name").and_then(|v| v.as_str()).unwrap_or("?") ) })?; @@ -928,23 +993,46 @@ fn import_mode_b(doc: &Mapping, version: String) -> Result .get("name") .and_then(|v| v.as_str()) .unwrap_or("schema[0]"); - let skipped: Vec<&str> = schema_seq + let skipped: Vec = schema_seq .iter() - .skip(1) - .map(|s| { - s.as_mapping() - .and_then(|m| m.get("name")) - .and_then(|v| v.as_str()) - .unwrap_or("?") - }) + .enumerate() + .filter(|(i, _)| *i != idx) + .map(|(_, o)| object_name(o)) .collect(); warnings.push(format!( - "ODCS schema has {} objects; imported '{}' (schema[0]) and ignored: {}", + "ODCS schema has {} objects; imported '{}' (schema[{}]) and ignored: {}. \ + Pick another with schema_object (--schema-object on the CLI)", schema_seq.len(), used, + idx, skipped.join(", ") )); } + let key_cols: Vec<&str> = props + .iter() + .filter_map(|p| p.as_mapping()) + .filter(|m| m.get("primaryKey").and_then(|v| v.as_bool()) == Some(true)) + .filter_map(|m| m.get("name").and_then(|v| v.as_str())) + .collect(); + if key_cols.len() > 1 { + warnings.push(format!( + "composite primary key ({}): each column is required, but uniqueness of the \ + combination is not enforced (uniqueness rules cover one field)", + key_cols.join(", ") + )); + } + let has_relationships = schema0.contains_key("relationships") + || props + .iter() + .filter_map(|p| p.as_mapping()) + .any(|m| m.contains_key("relationships")); + if has_relationships { + warnings.push( + "relationships (foreign keys) are not enforced: a contract validates one object's \ + events and has no lookup into another" + .to_string(), + ); + } let compliance_mode = root_extension(doc, "x-contractgate-compliance-mode") .and_then(|v| v.as_bool()) @@ -1317,6 +1405,10 @@ fn odcs_prop_to_field(m: &Mapping, full_name: &str) -> Result, /// Optional contract identity name override. When absent, the importer /// reads `dataProduct` (or `schema[0].name`) from the ODCS document. #[serde(default)] diff --git a/src/synth.rs b/src/synth.rs index a20b4596..049f824d 100644 --- a/src/synth.rs +++ b/src/synth.rs @@ -201,10 +201,23 @@ pub fn generate( /// Parse and compile contract YAML, mapping failures to a `contract` rule error. pub fn compile_yaml(yaml: &str) -> Result { - let contract: Contract = crate::odcs::parse_contract_yaml(yaml) - .map_err(|e| SynthError::new("contract", None, format!("invalid contract YAML: {e}")))?; - CompiledContract::compile(contract) - .map_err(|e| SynthError::new("contract", None, format!("contract does not compile: {e}"))) + compile_yaml_with(yaml, None).map(|(c, _)| c) +} + +/// [`compile_yaml`] for ODCS documents with several `schema` objects: +/// `schema_object` picks one by name. Also returns the ODCS import notes. +pub fn compile_yaml_with( + yaml: &str, + schema_object: Option<&str>, +) -> Result<(CompiledContract, Vec), SynthError> { + let (contract, notes): (Contract, Vec) = + crate::odcs::parse_contract_yaml_with(yaml, schema_object).map_err(|e| { + SynthError::new("contract", None, format!("invalid contract YAML: {e}")) + })?; + let compiled = CompiledContract::compile(contract).map_err(|e| { + SynthError::new("contract", None, format!("contract does not compile: {e}")) + })?; + Ok((compiled, notes)) } // --------------------------------------------------------------------------- diff --git a/src/synth_handler.rs b/src/synth_handler.rs index e9580eab..3154a622 100644 --- a/src/synth_handler.rs +++ b/src/synth_handler.rs @@ -49,6 +49,10 @@ pub struct SynthRequest { /// `envelope_payload` (RFC-118). 400 when the contract has none. #[serde(default)] pub envelope: bool, + /// For `yaml_content` in ODCS with several `schema` objects: which one to + /// use, by name. The first when omitted. + #[serde(default)] + pub schema_object: Option, } fn default_rows() -> usize { @@ -104,6 +108,7 @@ pub async fn synth_handler( None => chrono::Utc::now(), }; let want_envelope = req.envelope; + let schema_object = req.schema_object.clone(); let seed = req.seed.unwrap_or_else(rand::random); let opts = SynthOptions { rows: req.rows, @@ -115,7 +120,7 @@ pub async fn synth_handler( let started = std::time::Instant::now(); // CPU-bound; keep it off the async reactor. let result = tokio::task::spawn_blocking(move || { - let compiled = synth::compile_yaml(&yaml)?; + let (compiled, notes) = synth::compile_yaml_with(&yaml, schema_object.as_deref())?; let name = compiled.contract.name.clone(); let version = compiled.contract.version.clone(); let out = synth::generate(&compiled, &opts)?; @@ -128,13 +133,13 @@ pub async fn synth_handler( } else { None }; - Ok::<_, synth::SynthError>((name, version, out, payload)) + Ok::<_, synth::SynthError>((name, version, out, payload, notes)) }) .await .map_err(|e| AppError::Internal(format!("synth task failed: {e}")))?; match result { - Ok((name, version, out, payload)) => { + Ok((name, version, out, payload, notes)) => { let count = out.rows.len() + out.invalid_rows.len(); let rows: Value = match out.mode { SynthMode::Valid => Value::Array(out.rows), @@ -155,6 +160,9 @@ pub async fn synth_handler( if let Some(p) = payload { body["envelope_payload"] = p; } + if !notes.is_empty() { + body["notes"] = json!(notes); + } Ok(Json(body).into_response()) } Err(e) => { @@ -205,6 +213,7 @@ pub fn merge_openapi(paths: &mut serde_json::Map) { "mode": {"type": "string", "enum": ["valid", "invalid"], "default": "valid"}, "seed": {"type": "integer", "minimum": 0}, "anchor_time": {"type": "string", "format": "date-time", "description": "Time freshness rules are measured from. Now when omitted. Set it with seed for rows that repeat exactly."}, + "schema_object": {"type": "string", "description": "For ODCS yaml_content with several schema objects: the one to use, by name. The first when omitted."}, "envelope": {"type": "boolean", "default": false, "description": "Also return the rows wrapped in the contract's envelope as envelope_payload. 400 no_envelope when the contract has none."} }}}}}, "responses": { @@ -215,6 +224,7 @@ pub fn merge_openapi(paths: &mut serde_json::Map) { "seed": {"type": "integer"}, "anchor_time": {"type": "string", "format": "date-time"}, "envelope_payload": {"type": "object", "description": "Present when envelope=true: the records wrapped in the contract's envelope."}, + "notes": {"type": "array", "items": {"type": "string"}, "description": "ODCS content that did not map (ignored schema objects, composite key, relationships). Omitted when empty."}, "row_count": {"type": "integer"}, "rows": {"type": "array", "description": "valid: records. invalid: {record, broken_rule: {field, rule, metric?, violation_kind, message, constraint?}}.", "items": {"type": "object"}}, "skipped_rules": {"type": "array", "items": {"type": "object", "properties": {"field": {"type": "string"}, "rule": {"type": "string"}, "reason": {"type": "string"}}}}, @@ -265,6 +275,36 @@ mod tests { assert!(row["id"].as_str().unwrap().starts_with('A')); } + const ODCS_MULTI: &str = "apiVersion: v3.1.0\nkind: DataContract\nversion: 1.0.0\nschema:\n - name: a\n properties:\n - name: x\n logicalType: integer\n required: true\n - name: b\n properties:\n - name: y\n logicalType: string\n required: true\n"; + + #[tokio::test] + async fn odcs_schema_object_selects_and_notes_are_returned() { + let r = server() + .post("/contracts/synth") + .json(&json!({"yaml_content": ODCS_MULTI, "rows": 3, "seed": 1})) + .await; + assert_eq!(r.status_code(), StatusCode::OK); + let b = r.json::(); + assert!(b["rows"][0]["x"].is_number()); + assert!(b["notes"][0].as_str().unwrap().contains("ignored: b")); + let r = server() + .post("/contracts/synth") + .json(&json!({"yaml_content": ODCS_MULTI, "rows": 3, "seed": 1, "schema_object": "b"})) + .await; + let b = r.json::(); + assert!(b["rows"][0]["y"].is_string()); + assert!(b["notes"][0].as_str().unwrap().contains("ignored: a")); + let r = server() + .post("/contracts/synth") + .json(&json!({"yaml_content": ODCS_MULTI, "schema_object": "zzz"})) + .await; + assert_eq!(r.status_code(), StatusCode::UNPROCESSABLE_ENTITY); + assert!(r.json::()["message"] + .as_str() + .unwrap() + .contains("'zzz' not found")); + } + #[tokio::test] async fn inline_invalid_rows_are_labeled() { let r = server() diff --git a/src/v1_ingest.rs b/src/v1_ingest.rs index 2d258b0d..893b580d 100644 --- a/src/v1_ingest.rs +++ b/src/v1_ingest.rs @@ -625,7 +625,7 @@ fn extra_openapi_paths(paths: &mut serde_json::Map) { paths.insert("/contracts/import/dbt".into(), json!({"post": {"operationId": "import_dbt", "summary": "Import a dbt model contract as a DataContractGate draft", "description": "RFC-120. Body is dbt schema.yml (`dbt_yaml`) plus optional `model`, `name_override`, and `target_contract_id`. Creates a native draft, or a new version on a contract the caller owns. Mirrors POST /contracts/import (ODCS).", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["dbt_yaml"], "properties": {"dbt_yaml": {"type": "string"}, "model": {"type": "string"}, "name_override": {"type": "string"}, "target_contract_id": {"type": "string", "format": "uuid"}, "contract_id": {"type": "string", "format": "uuid"}}}}}}, "responses": {"201": {"description": "Created version"}, "400": {"description": "Invalid dbt YAML or missing model"}, "401": {"description": "Missing or invalid credentials"}, "402": {"description": "Free plan cap"}, "404": {"description": "Target contract not found"}, "409": {"description": "A contract with this name already exists"}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/versions/{version}/export/dbt".into(), json!({"get": {"operationId": "export_dbt", "summary": "Export a version as a dbt model contract", "description": "RFC-120. Writes schema.yml with config.contract.enforced, portable data_type values, not_null/unique/check constraints, and accepted_values tests. Rules dbt model contracts cannot express are stored in meta.contractgate for a lossless round-trip.", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}, {"name": "version", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "model", "in": "query", "required": false, "schema": {"type": "string"}, "description": "dbt model name; defaults to the contract's name"}], "responses": {"200": {"description": "dbt schema.yml", "content": {"application/yaml": {"schema": {"type": "string"}}}}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract or version not found"}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/export".into(), json!({"post": {"operationId": "export_fork_data", "summary": "Export a forked public-catalog contract's data", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}, {"name": "format", "in": "query", "required": false, "schema": {"type": "string", "enum": ["csv", "parquet"], "default": "csv"}}], "responses": {"200": {"description": "Exported data (CSV)"}, "400": {"description": "Unsupported format (parquet is not implemented yet)"}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract not found"}}, "security": [{"ApiKeyAuth": []}]}})); - paths.insert("/contracts/import".into(), json!({"post": {"operationId": "import_odcs", "summary": "Import an ODCS v3.1 document as a draft version", "description": "With target_contract_id (or its alias contract_id) the document is imported as a new draft version on that contract, which must be owned by the caller. Without a target, a new contract is created, unless the caller already owns a live contract with that name (409; pass target_contract_id).", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["odcs_yaml"], "properties": {"odcs_yaml": {"type": "string"}, "name_override": {"type": ["string", "null"]}, "target_contract_id": {"type": ["string", "null"], "format": "uuid"}, "contract_id": {"type": ["string", "null"], "format": "uuid", "description": "Alias of target_contract_id"}}}}}}, "responses": {"201": {"description": "Draft version created"}, "400": {"description": "Invalid ODCS document, or target_contract_id and contract_id disagree"}, "401": {"description": "Missing or invalid credentials"}, "403": {"description": "Collaborator grant on the target (owner required)"}, "404": {"description": "Target contract not found or not owned by the caller's org"}, "409": {"description": "Version (or an equivalent, e.g. 1.0 vs 1.0.0) already exists on the target, or a live contract with this name exists and no target was given"}}, "security": [{"ApiKeyAuth": []}]}})); + paths.insert("/contracts/import".into(), json!({"post": {"operationId": "import_odcs", "summary": "Import an ODCS v3.1 document as a draft version", "description": "With target_contract_id (or its alias contract_id) the document is imported as a new draft version on that contract, which must be owned by the caller. Without a target, a new contract is created, unless the caller already owns a live contract with that name (409; pass target_contract_id).", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["odcs_yaml"], "properties": {"odcs_yaml": {"type": "string"}, "schema_object": {"type": ["string", "null"], "description": "For an ODCS document with several schema objects: the one to import, by name. The first when omitted. Unmapped content is listed in the response's notes array."}, "name_override": {"type": ["string", "null"]}, "target_contract_id": {"type": ["string", "null"], "format": "uuid"}, "contract_id": {"type": ["string", "null"], "format": "uuid", "description": "Alias of target_contract_id"}}}}}}, "responses": {"201": {"description": "Draft version created. A notes array lists ODCS content that did not map (ignored schema objects, composite key uniqueness, relationships)."}, "400": {"description": "Invalid ODCS document, schema_object not found, or target_contract_id and contract_id disagree"}, "401": {"description": "Missing or invalid credentials"}, "403": {"description": "Collaborator grant on the target (owner required)"}, "404": {"description": "Target contract not found or not owned by the caller's org"}, "409": {"description": "Version (or an equivalent, e.g. 1.0 vs 1.0.0) already exists on the target, or a live contract with this name exists and no target was given"}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/kafka-ingress".into(), json!({"get": {"operationId": "get_kafka_ingress", "summary": "Kafka ingress config (owner)", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}], "responses": {"200": {"description": "Config (no secret)"}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract not found or not owned by the caller's org"}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/kafka-ingress/enable".into(), json!({"post": {"operationId": "enable_kafka_ingress", "summary": "Enable Kafka ingress (owner, Enterprise; available on request)", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}], "responses": {"200": {"description": "Already enabled"}, "201": {"description": "Enabled; secret shown once"}, "400": {"description": "Kafka ingress unavailable on this deployment (KAFKA_ENABLED=false)"}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract not found or not owned by the caller's org"}, "403": {"description": "Collaborator grant (owner required), or org below Enterprise: \"Kafka/Kinesis streaming ingress requires the Enterprise plan (available on request)\""}}, "security": [{"ApiKeyAuth": []}]}})); paths.insert("/contracts/{id}/kafka-ingress/disable".into(), json!({"delete": {"operationId": "disable_kafka_ingress", "summary": "Disable Kafka ingress (owner, any plan)", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid"}}], "responses": {"204": {"description": "Disabled; credentials revoked"}, "401": {"description": "Missing or invalid credentials"}, "404": {"description": "Contract not found or not owned by the caller's org"}}, "security": [{"ApiKeyAuth": []}]}})); diff --git a/tests/cli_test_dryrun.rs b/tests/cli_test_dryrun.rs index e707dc2c..1eb4a00d 100644 --- a/tests/cli_test_dryrun.rs +++ b/tests/cli_test_dryrun.rs @@ -24,6 +24,7 @@ fn args(data: &str) -> TestArgs { format: Format::Human, fail_fast: false, quiet: false, + schema_object: None, } } @@ -34,6 +35,7 @@ fn args_json(data: &str) -> TestArgs { format: Format::Json, fail_fast: false, quiet: false, + schema_object: None, } } @@ -114,6 +116,7 @@ fn bad_contract_yaml_returns_err() { format: Format::Human, fail_fast: false, quiet: false, + schema_object: None, }; // run() returns Err for load/compile failures (caller maps to exit 2). assert!(run(&bad_args).is_err(), "bad contract YAML → Err"); @@ -127,6 +130,7 @@ fn missing_data_file_returns_err() { format: Format::Human, fail_fast: false, quiet: false, + schema_object: None, }; assert!(run(&bad_args).is_err(), "missing data file → Err"); } @@ -149,6 +153,7 @@ fn fail_fast_exits_1_on_first_failing_record() { format: Format::Human, fail_fast: true, quiet: true, + schema_object: None, }; let code = run(&ff_args).expect("run"); assert_eq!(code, 1); @@ -165,6 +170,7 @@ fn quiet_mode_does_not_panic() { format: Format::Human, fail_fast: false, quiet: true, + schema_object: None, }; let code = run(&quiet_args).expect("run"); assert_eq!(code, 1); diff --git a/tests/cli_validate.rs b/tests/cli_validate.rs index 1d7e4a5d..154959e1 100644 --- a/tests/cli_validate.rs +++ b/tests/cli_validate.rs @@ -24,6 +24,7 @@ fn args_for_dir(dir: PathBuf) -> ValidateArgs { ValidateArgs { dir: Some(dir), json: false, + schema_object: None, } } @@ -31,6 +32,7 @@ fn args_for_dir_json(dir: PathBuf) -> ValidateArgs { ValidateArgs { dir: Some(dir), json: true, + schema_object: None, } } diff --git a/tests/odcs_compat.rs b/tests/odcs_compat.rs index 3da98925..e40c9912 100644 --- a/tests/odcs_compat.rs +++ b/tests/odcs_compat.rs @@ -79,8 +79,10 @@ fn official_full_example_parses_and_synths() { Some("Views built on top of the seller tables.") ); // schema[0] only; the second object is reported, not silently dropped. - assert_eq!(notes.len(), 1, "{notes:?}"); + // It also notes the relationships it does not enforce. + assert_eq!(notes.len(), 2, "{notes:?}"); assert!(notes[0].contains("receivers"), "{notes:?}"); + assert!(notes[1].contains("relationships"), "{notes:?}"); let cc = c .ontology .entities @@ -219,6 +221,7 @@ fn validate_command_accepts_odcs_directory() { let args = ValidateArgs { dir: Some(tmp.path().to_path_buf()), json: false, + schema_object: None, }; assert_eq!(run(&args, &CliConfig::default()).unwrap(), 0); } @@ -240,3 +243,16 @@ fn json_style_odcs_is_detected() { let c = parse_contract_yaml(y).expect("parses"); assert_eq!(c.ontology.entities.len(), 1); } + +#[test] +fn official_full_example_second_object_by_name() { + let (c, notes) = + contractgate::odcs::parse_contract_yaml_with(FULL, Some("receivers")).expect("parses"); + assert!(notes[0].contains("imported 'receivers'"), "{notes:?}"); + assert!(!c.ontology.entities.is_empty()); + assert!(c + .ontology + .entities + .iter() + .all(|f| f.name != "rcvr_cntry_code")); +} diff --git a/tests/odcs_schema_object.rs b/tests/odcs_schema_object.rs new file mode 100644 index 00000000..85efc030 --- /dev/null +++ b/tests/odcs_schema_object.rs @@ -0,0 +1,147 @@ +//! ODCS documents with several `schema` objects: pick one by name, and +//! surface what did not map (ignored objects, composite key, relationships). + +use contractgate::odcs::{import_odcs_with, parse_contract_yaml_with}; +use contractgate::synth::{self, SynthMode, SynthOptions}; +use contractgate::validation::validate; + +const MULTI: &str = r#" +apiVersion: v3.1.0 +kind: DataContract +version: 1.0.0 +dataProduct: shop +schema: + - name: orders + properties: + - name: order_id + logicalType: string + primaryKey: true + required: true + - name: line_no + logicalType: integer + primaryKey: true + required: true + - name: customer_id + logicalType: string + relationships: + - to: customers.customer_id + - name: customers + physicalName: tbl_customers + properties: + - name: customer_id + logicalType: string + required: true + - name: age + logicalType: integer + logicalTypeOptions: + minimum: 18 + maximum: 99 +"#; + +fn field_names(yaml: &str, obj: Option<&str>) -> Vec { + let (c, _) = parse_contract_yaml_with(yaml, obj).expect("parses"); + c.ontology.entities.into_iter().map(|f| f.name).collect() +} + +#[test] +fn default_is_first_object_and_note_names_the_rest_and_the_flag() { + assert_eq!( + field_names(MULTI, None), + ["order_id", "line_no", "customer_id"] + ); + let r = import_odcs_with(MULTI, None).unwrap(); + let n = r + .warnings + .iter() + .find(|w| w.contains("objects")) + .expect("multi-object note"); + assert!(n.contains("imported 'orders'"), "{n}"); + assert!(n.contains("customers"), "{n}"); + assert!(n.contains("schema_object"), "{n}"); +} + +#[test] +fn schema_object_selects_by_name_physical_name_and_id() { + assert_eq!( + field_names(MULTI, Some("customers")), + ["customer_id", "age"] + ); + assert_eq!( + field_names(MULTI, Some("tbl_customers")), + ["customer_id", "age"] + ); + let r = import_odcs_with(MULTI, Some("customers")).unwrap(); + let n = r.warnings.iter().find(|w| w.contains("objects")).unwrap(); + assert!(n.contains("imported 'customers' (schema[1])"), "{n}"); + assert!(n.contains("ignored: orders"), "{n}"); +} + +#[test] +fn unknown_schema_object_lists_the_available_names() { + let Err(e) = import_odcs_with(MULTI, Some("nope")) else { + panic!("expected error") + }; + assert!(e.contains("'nope' not found"), "{e}"); + assert!(e.contains("orders, customers"), "{e}"); +} + +#[test] +fn composite_key_and_relationships_are_noted_not_enforced() { + let r = import_odcs_with(MULTI, None).unwrap(); + assert!( + r.warnings + .iter() + .any(|w| w.contains("composite primary key (order_id, line_no)")), + "{:?}", + r.warnings + ); + assert!( + r.warnings.iter().any(|w| w.contains("relationships")), + "{:?}", + r.warnings + ); + // The second object has neither. + let r2 = import_odcs_with(MULTI, Some("customers")).unwrap(); + assert!(!r2.warnings.iter().any(|w| w.contains("composite"))); + assert!(!r2.warnings.iter().any(|w| w.contains("relationships"))); +} + +#[test] +fn single_column_key_gets_no_composite_note() { + let y = "apiVersion: v3.1.0\nkind: DataContract\nversion: 1.0.0\nschema:\n - name: t\n properties:\n - name: id\n logicalType: string\n primaryKey: true\n"; + let r = import_odcs_with(y, None).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +#[test] +fn selected_object_synths_valid_rows() { + let (c, _) = parse_contract_yaml_with(MULTI, Some("customers")).unwrap(); + let compiled = contractgate::validation::CompiledContract::compile(c).unwrap(); + let out = synth::generate( + &compiled, + &SynthOptions { + rows: 50, + mode: SynthMode::Valid, + seed: 1, + now_unix: 1_780_000_000, + }, + ) + .unwrap(); + let mut seen = 0; + for row in &out.rows { + assert!(validate(&compiled, row).passed, "{row}"); + if let Some(age) = row.get("age").and_then(|v| v.as_i64()) { + assert!((18..=99).contains(&age)); + seen += 1; + } + } + assert!(seen > 0, "optional field never generated"); +} + +#[test] +fn schema_object_is_ignored_for_native_yaml() { + let y = "version: \"1\"\nname: t\nontology:\n entities:\n - name: id\n type: string\n"; + let (c, notes) = parse_contract_yaml_with(y, Some("whatever")).unwrap(); + assert_eq!(c.name, "t"); + assert!(notes.is_empty()); +}