Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/odcs/field-mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Expand Down
32 changes: 29 additions & 3 deletions docs/odcs/using-odcs-directly.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
3 changes: 2 additions & 1 deletion docs/synthetic-data-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
17 changes: 13 additions & 4 deletions src/cli/commands/enforce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ pub struct EnforceArgs {
#[arg(long, env = "CG_KAFKA_BROKER", value_name = "HOST:PORT")]
pub broker: Option<String>,

/// 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<String>,

/// Kafka topic to consume.
#[arg(long, value_name = "TOPIC")]
pub topic: Option<String>,
Expand Down Expand Up @@ -74,7 +79,7 @@ pub struct EnforceArgs {

pub fn run(args: &EnforceArgs) -> anyhow::Result<i32> {
// 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)?;
Expand Down Expand Up @@ -130,7 +135,10 @@ pub fn run(args: &EnforceArgs) -> anyhow::Result<i32> {
// 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; \
Expand All @@ -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<String>) =
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}"))?;
Expand Down
17 changes: 11 additions & 6 deletions src/cli/commands/synth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ pub struct SynthArgs {
/// Write to this file instead of stdout.
#[arg(long, short = 'o', value_name = "FILE")]
pub out: Option<PathBuf>,

/// 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<String>,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
Expand All @@ -66,13 +71,13 @@ pub fn run(args: &SynthArgs) -> Result<i32> {
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);
Expand Down
26 changes: 18 additions & 8 deletions src/cli/commands/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
}

#[derive(Debug, Clone, clap::ValueEnum)]
Expand Down Expand Up @@ -90,11 +95,12 @@ struct Summary {

pub fn run(args: &TestArgs) -> anyhow::Result<i32> {
// --- 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| {
Expand Down Expand Up @@ -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<String>) =
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}"))?;
Expand Down
11 changes: 8 additions & 3 deletions src/cli/commands/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
}

#[derive(Serialize)]
Expand Down Expand Up @@ -57,7 +62,7 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result<i32> {
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();
Expand Down Expand Up @@ -99,11 +104,11 @@ pub fn run(args: &ValidateArgs, cfg: &CliConfig) -> Result<i32> {

/// Native or ODCS v3.x YAML. Returns notes for anything in an ODCS document
/// that did not map.
fn validate_file(path: &Path) -> Result<Vec<String>> {
fn validate_file(path: &Path, schema_object: Option<&str>) -> Result<Vec<String>> {
let src =
std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("cannot read file: {e}"))?;
let (contract, notes): (Contract, Vec<String>) =
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)
Expand Down
6 changes: 6 additions & 0 deletions src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
}

impl From<&ContractVersion> for VersionResponse {
Expand All @@ -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(),
}
}
}
Expand Down
11 changes: 8 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading