Initialize contracts experimental implementation and documentation
This commit is contained in:
commit
5cf638cc4b
6 changed files with 189 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/target/
|
||||
12
Cargo.toml
Normal file
12
Cargo.toml
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
[package]
|
||||
name = "archipelago-contracts"
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.90"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
regex = "1"
|
||||
yaml-rust2 = { version = "=0.10.4", default-features = false }
|
||||
jsonschema = { version = "=0.33.0", default-features = false }
|
||||
15
README.md
Normal file
15
README.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Archipelago contracts
|
||||
|
||||
Экспериментальные внутренние Rust-типы (D-062). Сериализация, схемы артефактов
|
||||
и получение content-derived snapshot identity здесь ещё не реализованы.
|
||||
|
||||
`layer` реализует строгий YAML/JSON parser и структурную проверку по замороженной
|
||||
схеме D-070, уникальность именованных элементов, ссылки checks и action DAG.
|
||||
CLI: `archipelago layer validate FILE`. Проверка не разрешает пакеты и не подтверждает
|
||||
adapter compatibility, source containment, effective ownership или readiness образа.
|
||||
Вход ограничен 4 MiB и вложенностью 64 — ограничения первой реализации.
|
||||
Схема включается из соседнего `rfc/schemas/layer-v1.schema.json`; её исходники
|
||||
должны входить в закреплённый source tree сборки CLI.
|
||||
|
||||
Новые компиляции и тесты — на `terra` по D-071. Исторические результаты superserv1
|
||||
не являются проверкой текущего парсера.
|
||||
3
rust-toolchain.toml
Normal file
3
rust-toolchain.toml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
[toolchain]
|
||||
channel = "1.90.0"
|
||||
profile = "minimal"
|
||||
139
src/layer.rs
Normal file
139
src/layer.rs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
//! Frozen Layer v1 parser and source-local validation, not package resolution.
|
||||
use serde_json::{Map, Value};
|
||||
use std::{collections::{BTreeMap, BTreeSet}, str::Chars};
|
||||
use yaml_rust2::{parser::{Event, Parser}, scanner::TScalarStyle};
|
||||
|
||||
type Result<T> = std::result::Result<T, String>;
|
||||
const SCHEMA: &str = include_str!("../../rfc/schemas/layer-v1.schema.json");
|
||||
|
||||
fn next(parser: &mut Parser<Chars<'_>>) -> Result<Event> {
|
||||
parser.next_token().map(|(event, _)| event).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn scalar(text: String, style: TScalarStyle) -> Result<Value> {
|
||||
if style == TScalarStyle::Plain {
|
||||
match text.as_str() {
|
||||
"true" => return Ok(Value::Bool(true)),
|
||||
"false" => return Ok(Value::Bool(false)),
|
||||
"null" => return Ok(Value::Null),
|
||||
_ => {}
|
||||
}
|
||||
// Parse JSON numbers only. YAML-specific spellings stay strings.
|
||||
static NUMBER: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(||
|
||||
regex::Regex::new(r"\A-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?\z").unwrap());
|
||||
if NUMBER.is_match(&text) {
|
||||
if text.contains(['.', 'e', 'E']) { return Err("Floats are forbidden".into()); }
|
||||
let integer: i64 = text.parse().map_err(|_| "Integer outside interoperable JSON range")?;
|
||||
if !(-9007199254740991..=9007199254740991).contains(&integer) {
|
||||
return Err("Integer outside interoperable JSON range".into());
|
||||
}
|
||||
return Ok(Value::from(integer));
|
||||
}
|
||||
}
|
||||
Ok(Value::String(text))
|
||||
}
|
||||
|
||||
fn node(parser: &mut Parser<Chars<'_>>, event: Event, depth: usize) -> Result<Value> {
|
||||
if depth > 64 { return Err("Manifest nesting exceeds implementation limit (64)".into()); }
|
||||
match event {
|
||||
Event::Scalar(text, style, 0, None) => scalar(text, style),
|
||||
Event::SequenceStart(0, None) => {
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
let event = next(parser)?;
|
||||
if event == Event::SequenceEnd { break; }
|
||||
items.push(node(parser, event, depth + 1)?);
|
||||
}
|
||||
Ok(Value::Array(items))
|
||||
}
|
||||
Event::MappingStart(0, None) => {
|
||||
let mut items = Map::new();
|
||||
loop {
|
||||
let event = next(parser)?;
|
||||
if event == Event::MappingEnd { break; }
|
||||
let key = node(parser, event, depth + 1)?;
|
||||
let key = key.as_str().ok_or("Mapping keys must be strings")?;
|
||||
if key == "<<" || items.contains_key(key) { return Err(format!("Merge or duplicate key: {key}")); }
|
||||
let event = next(parser)?;
|
||||
items.insert(key.into(), node(parser, event, depth + 1)?);
|
||||
}
|
||||
Ok(Value::Object(items))
|
||||
}
|
||||
_ => Err("Anchors, aliases, tags or unexpected YAML event".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Value> {
|
||||
if text.len() > 4 * 1024 * 1024 { return Err("Manifest exceeds implementation limit (4 MiB)".into()); }
|
||||
let mut parser = Parser::new_from_str(text);
|
||||
if next(&mut parser)? != Event::StreamStart || next(&mut parser)? != Event::DocumentStart {
|
||||
return Err("Exactly one nonempty YAML/JSON document is required".into());
|
||||
}
|
||||
let first = next(&mut parser)?;
|
||||
let value = node(&mut parser, first, 0)?;
|
||||
if next(&mut parser)? != Event::DocumentEnd || next(&mut parser)? != Event::StreamEnd {
|
||||
return Err("Exactly one document is required".into());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn entries(value: &Value) -> &[Value] {
|
||||
value.as_array().map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub fn validate(text: &str) -> Result<Value> {
|
||||
let data = parse(text)?;
|
||||
let schema: Value = serde_json::from_str(SCHEMA).map_err(|e| e.to_string())?;
|
||||
let validator = jsonschema::validator_for(&schema).map_err(|e| e.to_string())?;
|
||||
validator.validate(&data).map_err(|e| format!("{}: {e}", e.instance_path))?;
|
||||
let spec = &data["spec"];
|
||||
for (list, key) in [(&spec["packages"]["runtime"], "name"), (&spec["packages"]["build"], "name"),
|
||||
(&spec["actions"], "id"), (&spec["runtime"]["units"], "name"), (&spec["files"], "path")] {
|
||||
let mut seen = BTreeSet::new();
|
||||
for item in entries(list) {
|
||||
if !seen.insert(item[key].as_str().unwrap()) { return Err(format!("Duplicate {key}: {}", item[key])); }
|
||||
}
|
||||
}
|
||||
let actions: BTreeMap<_, _> = entries(&spec["actions"]).iter().map(|a| (a["id"].as_str().unwrap(), a)).collect();
|
||||
for field in ["boot_checks", "functional_checks"] {
|
||||
for name in entries(&spec["runtime"][field]) {
|
||||
if !actions.contains_key(name.as_str().unwrap()) { return Err(format!("Missing check action: {name}")); }
|
||||
}
|
||||
}
|
||||
// Iterative topological validation avoids recursion on authored action graphs.
|
||||
let mut completed = BTreeSet::new();
|
||||
while completed.len() < actions.len() {
|
||||
let previous = completed.len();
|
||||
for (name, action) in &actions {
|
||||
for predecessor in entries(&action["after"]) {
|
||||
actions.get(predecessor.as_str().unwrap()).ok_or("Missing predecessor action")?;
|
||||
}
|
||||
if entries(&action["after"]).iter().all(|v| completed.contains(v.as_str().unwrap())) {
|
||||
completed.insert(*name);
|
||||
}
|
||||
}
|
||||
if completed.len() == previous { return Err("Action cycle".into()); }
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn strict_scalar_and_mapping_contract() {
|
||||
for text in ["a: 1\na: 2", "a: &a x\nb: *a", "a: !!str x", "a: x\n---\nb: y",
|
||||
"a: 1.5", "a: 1e99999", "a: 9007199254740992", "a: 999999999999999999999999999",
|
||||
"a: -9007199254740992", "<<: {}", "true: x", "[a, b]: x", ""] {
|
||||
assert!(parse(text).is_err(), "accepted {text:?}");
|
||||
}
|
||||
let value = parse("yes: yes\nno: no\na: 0755\nb: 'true'\nc: true\nd: 9007199254740991").unwrap();
|
||||
assert_eq!(value["yes"], "yes");
|
||||
assert_eq!(value["no"], "no");
|
||||
assert_eq!(value["a"], "0755");
|
||||
assert_eq!(value["b"], "true");
|
||||
assert_eq!(value["c"], true);
|
||||
assert_eq!(value["d"], 9007199254740991_i64);
|
||||
}
|
||||
}
|
||||
19
src/lib.rs
Normal file
19
src/lib.rs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
//! Experimental internal types, not a serialized manifest or lockfile schema.
|
||||
//! Identity strings must come from a verified artifact adapter; this module does
|
||||
//! not derive snapshot identities or authenticate artifact metadata.
|
||||
|
||||
pub mod layer;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LayerKind {
|
||||
Core,
|
||||
Purpose,
|
||||
Overlay,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LayerInput {
|
||||
pub kind: LayerKind,
|
||||
pub snapshot_id: String,
|
||||
pub architecture: String,
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue