feat(example): restore virtual workspace conformance
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "wip-public-api-example"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Public-only end-to-end conformance consumer for the WIP Rust APIs"
|
||||
license = "MIT OR Apache-2.0"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
wip-host = { path = "../wip-host" }
|
||||
wip-interface = { path = "../wip-interface" }
|
||||
wip-protocol = { path = "../wip-protocol" }
|
||||
@@ -0,0 +1,508 @@
|
||||
//! Public-only conformance consumer for the WIP Rust crates.
|
||||
//!
|
||||
//! # Architectural boundary
|
||||
//!
|
||||
//! This package is an ordinary application consumer. Its direct dependencies are
|
||||
//! the public `wip-protocol`, `wip-interface`, and `wip-host` crates; it neither
|
||||
//! imports workspace-private modules nor depends on `wip-interface-macros`.
|
||||
//! `wip-protocol` owns transport-independent DTOs and schema-neutral values,
|
||||
//! while this package owns its application DTOs and interface traits. The
|
||||
//! request-scoped implementation, backend handle, authorization policy, and
|
||||
//! publication wiring remain host-private. A transport binding would translate
|
||||
//! its own wire routes and envelopes to the protocol call DTOs; no HTTP type is
|
||||
//! part of an application trait or interface descriptor.
|
||||
//!
|
||||
//! # Breaking migration exercised here
|
||||
//!
|
||||
//! The canonical API targets operations by `target.path` rather than a mandatory
|
||||
//! object identifier. Object `ref` and object/interface validators are separate,
|
||||
//! optional observation fields. Interface references are opaque values observed
|
||||
//! separately from descriptors, and descriptors contain neither a Rust trait
|
||||
//! name nor an opaque-reference `name` field. Application records, enums,
|
||||
//! unions, entry paths, and JSON all encode through the schema-neutral [`Value`]
|
||||
//! variants: entries and enums are strings, unions are discriminator records,
|
||||
//! and JSON recursively uses ordinary records/lists/primitives. The former
|
||||
//! `Entry<K, V>` and semantic `Value::Entry`, `Value::Enum`, `Value::Union`, and
|
||||
//! `Value::Json` forms are intentionally unsupported.
|
||||
//!
|
||||
//! # Supported authoring subset
|
||||
//!
|
||||
//! Public, non-generic traits use immutable `&self` receivers, owned named
|
||||
//! parameters, and explicit `wip::OperationResult<T>` returns. Derived DTOs are
|
||||
//! named-field records, all-unit enums, or unions with unit and single-payload
|
||||
//! cases. A direct `Option<T>` means field/argument omission, never protocol
|
||||
//! null. See `wip-interface` for the complete rejected-syntax list.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::io;
|
||||
|
||||
use wip_host::{
|
||||
CallErrorKind, CallRequest, InterfaceRef, InterfaceRegistry, InterfaceTarget, ObjectProvider,
|
||||
PublishedObject, RegisteredInterface, Target, Validator, WipObject,
|
||||
};
|
||||
use wip_interface as wip;
|
||||
use wip_interface::WipType;
|
||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, Value};
|
||||
|
||||
const OBJECT_PATH: &str = "/article-service";
|
||||
const OBJECT_VALIDATOR: &[u8] = b"object-v1";
|
||||
const CATALOG_VALIDATOR: &[u8] = b"catalog-v1";
|
||||
|
||||
/// Publication visibility represented as a protocol enum string.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
|
||||
pub enum Visibility {
|
||||
/// Visible to every authorized caller.
|
||||
Public,
|
||||
/// Visible only inside the application domain.
|
||||
Private,
|
||||
}
|
||||
|
||||
/// An application-owned request DTO mapped to a protocol record.
|
||||
#[derive(Debug, Clone, PartialEq, wip::WipType)]
|
||||
pub struct PublishRequest {
|
||||
/// Title of the article to publish.
|
||||
pub title: String,
|
||||
/// Optional article body; omission is distinct from JSON null.
|
||||
pub body: Option<String>,
|
||||
/// Canonical Worldspace path to the source entry.
|
||||
pub source: wip::Entry,
|
||||
/// Application enum represented by a schema-neutral string.
|
||||
pub visibility: Visibility,
|
||||
/// Schema-opaque JSON represented by ordinary protocol values.
|
||||
pub metadata: wip::JsonValue,
|
||||
}
|
||||
|
||||
/// The application domain result of a publication attempt.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
|
||||
pub enum PublishOutcome {
|
||||
/// Publication succeeded and returned its application identifier.
|
||||
Published(String),
|
||||
/// An application policy rejected the publication.
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
/// Article publication operations.
|
||||
#[wip::interface]
|
||||
pub trait Catalog {
|
||||
/// Publishes an article or reports an application-domain rejection.
|
||||
///
|
||||
/// # Returns
|
||||
/// The typed application outcome.
|
||||
fn publish(
|
||||
&self,
|
||||
/// Application publication request.
|
||||
request: PublishRequest,
|
||||
) -> wip::OperationResult<PublishOutcome>;
|
||||
|
||||
/// Returns the catalog-qualified status.
|
||||
fn status(&self) -> wip::OperationResult<String>;
|
||||
|
||||
/// Demonstrates a host/backend failure rather than a domain result.
|
||||
fn backend_status(&self) -> wip::OperationResult<String>;
|
||||
|
||||
/// Demonstrates denial after every structural precondition succeeds.
|
||||
fn restricted_status(&self) -> wip::OperationResult<String>;
|
||||
}
|
||||
|
||||
/// Audit operations exposed by the same object.
|
||||
#[wip::interface]
|
||||
pub trait Audit {
|
||||
/// Returns the audit-qualified status.
|
||||
fn status(&self) -> wip::OperationResult<String>;
|
||||
}
|
||||
|
||||
/// A registered but deliberately unexposed interface.
|
||||
#[wip::interface]
|
||||
pub trait Diagnostics {
|
||||
/// Returns host-private diagnostics when explicitly exposed.
|
||||
fn diagnostics(&self) -> wip::OperationResult<String>;
|
||||
}
|
||||
|
||||
/// Observable outcomes from the complete public-API scenario.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DemoReport {
|
||||
/// Path-segment name from the canonical object projection.
|
||||
pub object_name: String,
|
||||
/// Optional object identity, distinct from the resolution path.
|
||||
pub object_reference: Option<String>,
|
||||
/// Optional object-state validator.
|
||||
pub object_validator: Option<Vec<u8>>,
|
||||
/// Opaque interface references published by the object, in exposure order.
|
||||
pub published_interfaces: Vec<String>,
|
||||
/// Opaque reference assigned to the catalog descriptor.
|
||||
pub catalog_interface_reference: String,
|
||||
/// Opaque reference assigned to the audit descriptor.
|
||||
pub audit_interface_reference: String,
|
||||
/// Descriptor format observed separately for the catalog reference.
|
||||
pub catalog_descriptor_format: String,
|
||||
/// Descriptor format observed separately for the audit reference.
|
||||
pub audit_descriptor_format: String,
|
||||
/// Typed successful application result decoded from a validated [`Value`].
|
||||
pub published: PublishOutcome,
|
||||
/// Typed application-domain rejection decoded from a validated [`Value`].
|
||||
pub rejected: PublishOutcome,
|
||||
/// Result of the catalog-qualified `status` operation.
|
||||
pub catalog_status: String,
|
||||
/// Result of the audit-qualified `status` operation.
|
||||
pub audit_status: String,
|
||||
/// Stable failure kind produced by the deliberate host/backend failure.
|
||||
pub host_failure: CallErrorKind,
|
||||
/// A protocol-level failure built from the host failure.
|
||||
pub protocol_failure: ProtocolError,
|
||||
/// Authorization failure after a fully qualified valid request.
|
||||
pub permission_failure: ProtocolErrorCode,
|
||||
/// Recovery signal for a stale object validator.
|
||||
pub validator_failure: ProtocolErrorCode,
|
||||
/// Failure for a known but unexposed interface reference.
|
||||
pub interface_mismatch: ProtocolErrorCode,
|
||||
/// Failure for an unknown interface observation reference.
|
||||
pub interface_not_found: ProtocolErrorCode,
|
||||
/// First failure for a request with an invalid path and later invalid fields.
|
||||
pub precedence_failure: ProtocolErrorCode,
|
||||
}
|
||||
|
||||
/// Runs the complete end-to-end conformance example.
|
||||
///
|
||||
/// The provider resolves the current object from a Worldspace path for each
|
||||
/// call. Interface observations remain separate from object projection, and all
|
||||
/// successful calls carry independent object and interface validators.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if registration, observation, path resolution, dispatch, or
|
||||
/// application-value decoding fails unexpectedly.
|
||||
pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let catalog = registry.register(CatalogDefinition, Some(Validator::new(CATALOG_VALIDATOR)))?;
|
||||
let audit = registry.register(AuditDefinition, None)?;
|
||||
let diagnostics = registry.register(DiagnosticsDefinition, None)?;
|
||||
let provider = ApplicationProvider {
|
||||
catalog: catalog.clone(),
|
||||
audit: audit.clone(),
|
||||
};
|
||||
|
||||
let object = provider.fetch(OBJECT_PATH)?;
|
||||
let catalog_observation = registry.fetch_interface(
|
||||
object
|
||||
.interfaces
|
||||
.first()
|
||||
.ok_or_else(|| io::Error::other("catalog interface was not published"))?,
|
||||
)?;
|
||||
let audit_observation = registry.fetch_interface(
|
||||
object
|
||||
.interfaces
|
||||
.get(1)
|
||||
.ok_or_else(|| io::Error::other("audit interface was not published"))?,
|
||||
)?;
|
||||
|
||||
let published = dispatch_publish(
|
||||
&provider,
|
||||
catalog.reference(),
|
||||
PublishRequest {
|
||||
title: "Public APIs".into(),
|
||||
body: Some("protocol values in, validated values out".into()),
|
||||
source: wip::Entry::new("/drafts/public-apis")?,
|
||||
visibility: Visibility::Public,
|
||||
metadata: wip::JsonValue::Object(vec![wip::JsonMember {
|
||||
name: "reviewed".into(),
|
||||
value: wip::JsonValue::Boolean(true),
|
||||
}]),
|
||||
},
|
||||
)?;
|
||||
let rejected = dispatch_publish(
|
||||
&provider,
|
||||
catalog.reference(),
|
||||
PublishRequest {
|
||||
title: String::new(),
|
||||
body: None,
|
||||
source: wip::Entry::new("/drafts/untitled")?,
|
||||
visibility: Visibility::Private,
|
||||
metadata: wip::JsonValue::Null,
|
||||
},
|
||||
)?;
|
||||
let catalog_status = dispatch_string(
|
||||
&provider,
|
||||
request(
|
||||
OBJECT_PATH,
|
||||
catalog.reference(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"status",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)?;
|
||||
let audit_status = dispatch_string(
|
||||
&provider,
|
||||
request(
|
||||
OBJECT_PATH,
|
||||
audit.reference(),
|
||||
None,
|
||||
"status",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)?;
|
||||
|
||||
let host_error = provider
|
||||
.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
catalog.reference(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"backend_status",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.expect_err("backend_status must model a host failure");
|
||||
ensure_kind(&host_error, CallErrorKind::Implementation)?;
|
||||
let protocol_failure = host_error.protocol_error();
|
||||
|
||||
let permission_failure = provider
|
||||
.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
catalog.reference(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"restricted_status",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.expect_err("restricted_status must be denied")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
let validator_failure = provider
|
||||
.call_operation(CallRequest {
|
||||
target: Target {
|
||||
path: OBJECT_PATH.into(),
|
||||
validator: Some(b"stale-object".to_vec()),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: diagnostics.reference().as_str().to_owned(),
|
||||
validator: Some(b"stale-interface".to_vec()),
|
||||
},
|
||||
operation: "missing".into(),
|
||||
arguments: BTreeMap::from([("unknown".into(), Value::Unit)]),
|
||||
})
|
||||
.expect_err("the stale object validator must fail first")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
let interface_mismatch = provider
|
||||
.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
diagnostics.reference(),
|
||||
None,
|
||||
"diagnostics",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.expect_err("registered but unexposed interface must not dispatch")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
let interface_not_found = registry
|
||||
.fetch_interface("missing-interface")
|
||||
.expect_err("unknown interface references must not resolve")
|
||||
.code;
|
||||
|
||||
let precedence_failure = provider
|
||||
.call_operation(CallRequest {
|
||||
target: Target {
|
||||
path: "relative/path".into(),
|
||||
validator: Some(b"stale-object".to_vec()),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: diagnostics.reference().as_str().to_owned(),
|
||||
validator: Some(b"stale-interface".to_vec()),
|
||||
},
|
||||
operation: "missing".into(),
|
||||
arguments: BTreeMap::from([("unknown".into(), Value::Unit)]),
|
||||
})
|
||||
.expect_err("invalid path must have canonical precedence")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
Ok(DemoReport {
|
||||
object_name: object.name,
|
||||
object_reference: object.r#ref,
|
||||
object_validator: object.validator,
|
||||
published_interfaces: object.interfaces,
|
||||
catalog_interface_reference: catalog.reference().as_str().to_owned(),
|
||||
audit_interface_reference: audit.reference().as_str().to_owned(),
|
||||
catalog_descriptor_format: catalog_observation.descriptor.format,
|
||||
audit_descriptor_format: audit_observation.descriptor.format,
|
||||
published,
|
||||
rejected,
|
||||
catalog_status,
|
||||
audit_status,
|
||||
host_failure: host_error.kind(),
|
||||
protocol_failure,
|
||||
permission_failure,
|
||||
validator_failure,
|
||||
interface_mismatch,
|
||||
interface_not_found,
|
||||
precedence_failure,
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_kind(error: &wip_host::CallError, expected: CallErrorKind) -> Result<(), io::Error> {
|
||||
if error.kind() == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other(format!(
|
||||
"unexpected host failure kind: {:?}",
|
||||
error.kind()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_publish(
|
||||
provider: &ApplicationProvider,
|
||||
catalog: &InterfaceRef,
|
||||
request_value: PublishRequest,
|
||||
) -> Result<PublishOutcome, Box<dyn Error>> {
|
||||
let encoded_request = request_value.encode()?;
|
||||
let result = provider.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
catalog,
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"publish",
|
||||
BTreeMap::from([("request".into(), encoded_request)]),
|
||||
))?;
|
||||
Ok(PublishOutcome::decode(result.result)?)
|
||||
}
|
||||
|
||||
fn dispatch_string(
|
||||
provider: &ApplicationProvider,
|
||||
request: CallRequest,
|
||||
) -> Result<String, Box<dyn Error>> {
|
||||
let result = provider.call_operation(request)?;
|
||||
Ok(String::decode(result.result)?)
|
||||
}
|
||||
|
||||
fn request(
|
||||
path: &str,
|
||||
interface: &InterfaceRef,
|
||||
interface_validator: Option<&[u8]>,
|
||||
operation: &str,
|
||||
arguments: BTreeMap<String, Value>,
|
||||
) -> CallRequest {
|
||||
CallRequest {
|
||||
target: Target {
|
||||
path: path.into(),
|
||||
validator: Some(OBJECT_VALIDATOR.to_vec()),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: interface.as_str().to_owned(),
|
||||
validator: interface_validator.map(<[u8]>::to_vec),
|
||||
},
|
||||
operation: operation.into(),
|
||||
arguments,
|
||||
}
|
||||
}
|
||||
|
||||
struct ApplicationProvider {
|
||||
catalog: RegisteredInterface<CatalogDefinition>,
|
||||
audit: RegisteredInterface<AuditDefinition>,
|
||||
}
|
||||
|
||||
impl ObjectProvider for ApplicationProvider {
|
||||
type Object = ApplicationService;
|
||||
|
||||
fn with_object<R>(
|
||||
&self,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||
) -> Option<R> {
|
||||
if path != OBJECT_PATH {
|
||||
return None;
|
||||
}
|
||||
let publication = PublishedObject::new(ApplicationService::new())
|
||||
.expose(&self.catalog)
|
||||
.expect("ApplicationService implements Catalog")
|
||||
.expose(&self.audit)
|
||||
.expect("ApplicationService implements Audit");
|
||||
Some(operation(&publication))
|
||||
}
|
||||
|
||||
fn authorize(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &ApplicationService,
|
||||
_: &InterfaceRef,
|
||||
operation: &str,
|
||||
) -> bool {
|
||||
operation != "restricted_status"
|
||||
}
|
||||
}
|
||||
|
||||
struct ApplicationService {
|
||||
object_validator: Validator,
|
||||
backend_connection: String,
|
||||
}
|
||||
|
||||
impl ApplicationService {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
object_validator: Validator::new(OBJECT_VALIDATOR),
|
||||
backend_connection: "private://article-database".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WipObject for ApplicationService {
|
||||
fn name(&self) -> &str {
|
||||
"article-service"
|
||||
}
|
||||
|
||||
fn description(&self) -> Option<&str> {
|
||||
Some("Article publication service")
|
||||
}
|
||||
|
||||
fn reference(&self) -> Option<&str> {
|
||||
Some("article-service-instance")
|
||||
}
|
||||
|
||||
fn validator(&self) -> Option<&Validator> {
|
||||
Some(&self.object_validator)
|
||||
}
|
||||
|
||||
fn requires_validator(&self, _: &InterfaceRef, _: &str) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Catalog for ApplicationService {
|
||||
fn publish(&self, request: PublishRequest) -> wip::OperationResult<PublishOutcome> {
|
||||
if request.title.trim().is_empty() {
|
||||
Ok(PublishOutcome::Rejected("a title is required".into()))
|
||||
} else {
|
||||
Ok(PublishOutcome::Published("article-1".into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn status(&self) -> wip::OperationResult<String> {
|
||||
Ok("catalog-ready".into())
|
||||
}
|
||||
|
||||
fn backend_status(&self) -> wip::OperationResult<String> {
|
||||
if self.backend_connection.starts_with("private://") {
|
||||
Err(wip::HostError::new("backend unavailable"))
|
||||
} else {
|
||||
Ok("backend-ready".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn restricted_status(&self) -> wip::OperationResult<String> {
|
||||
Ok("authorization hook should prevent this call".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Audit for ApplicationService {
|
||||
fn status(&self) -> wip::OperationResult<String> {
|
||||
Ok("audit-ready".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Diagnostics for ApplicationService {
|
||||
fn diagnostics(&self) -> wip::OperationResult<String> {
|
||||
Ok("host-private".into())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use std::error::Error;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let report = wip_public_api_example::run()?;
|
||||
println!(
|
||||
"published {} interfaces; catalog={}, audit={}; domain={:?}; host={:?}",
|
||||
report.published_interfaces.len(),
|
||||
report.catalog_status,
|
||||
report.audit_status,
|
||||
report.rejected,
|
||||
report.host_failure,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_host::CallErrorKind;
|
||||
use wip_interface::{Entry, JsonMember, JsonValue, WipType};
|
||||
use wip_protocol::{INTERFACE_FORMAT_V1, InterfaceDescriptor, Object, ProtocolErrorCode, Value};
|
||||
use wip_public_api_example::{CatalogDefinition, PublishOutcome, PublishRequest, Visibility, run};
|
||||
|
||||
#[test]
|
||||
fn public_crates_support_the_complete_qualified_end_to_end_scenario() {
|
||||
let report = run().unwrap();
|
||||
|
||||
assert_eq!(report.object_name, "article-service");
|
||||
assert_eq!(
|
||||
report.object_reference.as_deref(),
|
||||
Some("article-service-instance")
|
||||
);
|
||||
assert_eq!(
|
||||
report.object_validator.as_deref(),
|
||||
Some(b"object-v1".as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
report.published_interfaces,
|
||||
[
|
||||
report.catalog_interface_reference.clone(),
|
||||
report.audit_interface_reference.clone(),
|
||||
],
|
||||
"interfaces must retain explicit publication order"
|
||||
);
|
||||
assert_ne!(
|
||||
report.catalog_interface_reference, report.audit_interface_reference,
|
||||
"interfaces form an ordered set of distinct opaque references"
|
||||
);
|
||||
assert_eq!(report.catalog_descriptor_format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(report.audit_descriptor_format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(
|
||||
report.published,
|
||||
PublishOutcome::Published("article-1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
report.rejected,
|
||||
PublishOutcome::Rejected("a title is required".into())
|
||||
);
|
||||
assert_eq!(report.catalog_status, "catalog-ready");
|
||||
assert_eq!(report.audit_status, "audit-ready");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_host_permission_and_validator_failures_remain_distinct() {
|
||||
let report = run().unwrap();
|
||||
|
||||
assert!(matches!(report.rejected, PublishOutcome::Rejected(_)));
|
||||
assert_eq!(report.host_failure, CallErrorKind::Implementation);
|
||||
assert_eq!(report.protocol_failure.code, ProtocolErrorCode::Internal);
|
||||
assert_eq!(
|
||||
report.permission_failure,
|
||||
ProtocolErrorCode::PermissionDenied
|
||||
);
|
||||
assert_eq!(
|
||||
report.validator_failure,
|
||||
ProtocolErrorCode::ValidatorMismatch,
|
||||
"validator recovery signals must not collapse to InvalidRequest"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_mismatch_is_not_interface_not_found() {
|
||||
let report = run().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
report.interface_mismatch,
|
||||
ProtocolErrorCode::InterfaceMismatch
|
||||
);
|
||||
assert_eq!(
|
||||
report.interface_not_found,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
assert_ne!(report.interface_mismatch, report.interface_not_found);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_path_keeps_canonical_failure_precedence() {
|
||||
let report = run().unwrap();
|
||||
|
||||
assert_eq!(report.precedence_failure, ProtocolErrorCode::InvalidRequest);
|
||||
assert_ne!(report.precedence_failure, report.validator_failure);
|
||||
assert_ne!(report.precedence_failure, report.interface_mismatch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_fields_keep_path_context_and_optional_ref_separate() {
|
||||
// Listing every field makes this test fail to compile if a mandatory
|
||||
// ObjectId is reintroduced into the canonical object DTO.
|
||||
let object = Object {
|
||||
name: "article".into(),
|
||||
description: None,
|
||||
interfaces: vec!["catalog-ref".into(), "audit-ref".into()],
|
||||
r#ref: None,
|
||||
validator: None,
|
||||
};
|
||||
|
||||
object.validate_at_path("/library/article").unwrap();
|
||||
assert_eq!(object.name, "article");
|
||||
assert_eq!(object.r#ref, None);
|
||||
assert_eq!(object.interfaces, ["catalog-ref", "audit-ref"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_reference_is_observed_separately_from_descriptor_fields() {
|
||||
// An exact destructuring pattern is compile-time coverage that the
|
||||
// descriptor has no trait-name or opaque-reference `name` field.
|
||||
let InterfaceDescriptor {
|
||||
format,
|
||||
documentation,
|
||||
types,
|
||||
operations,
|
||||
} = CatalogDefinition::descriptor();
|
||||
|
||||
assert_eq!(format, INTERFACE_FORMAT_V1);
|
||||
assert!(documentation.is_some());
|
||||
assert!(!types.is_empty());
|
||||
assert_eq!(
|
||||
operations
|
||||
.iter()
|
||||
.map(|operation| operation.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["publish", "status", "backend_status", "restricted_status"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_record_enum_union_entry_and_json_use_schema_neutral_values() {
|
||||
let request = PublishRequest {
|
||||
title: "Canonical values".into(),
|
||||
body: None,
|
||||
source: Entry::new("/drafts/canonical-values").unwrap(),
|
||||
visibility: Visibility::Public,
|
||||
metadata: JsonValue::Object(vec![
|
||||
JsonMember {
|
||||
name: "tags".into(),
|
||||
value: JsonValue::Array(vec![JsonValue::String("wip".into()), JsonValue::Null]),
|
||||
},
|
||||
JsonMember {
|
||||
name: "ready".into(),
|
||||
value: JsonValue::Boolean(true),
|
||||
},
|
||||
]),
|
||||
};
|
||||
|
||||
let encoded = request.encode().unwrap();
|
||||
assert_schema_neutral(&encoded);
|
||||
let Value::Record(fields) = encoded else {
|
||||
panic!("derived DTO record must use Value::Record")
|
||||
};
|
||||
assert_eq!(
|
||||
fields.get("title"),
|
||||
Some(&Value::String("Canonical values".into()))
|
||||
);
|
||||
assert!(!fields.contains_key("body"));
|
||||
assert_eq!(
|
||||
fields.get("source"),
|
||||
Some(&Value::String("/drafts/canonical-values".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
fields.get("visibility"),
|
||||
Some(&Value::String("Public".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
fields.get("metadata"),
|
||||
Some(&Value::Record(BTreeMap::from([
|
||||
("ready".into(), Value::Boolean(true)),
|
||||
(
|
||||
"tags".into(),
|
||||
Value::List(vec![Value::String("wip".into()), Value::Unit])
|
||||
),
|
||||
])))
|
||||
);
|
||||
|
||||
let outcome = PublishOutcome::Rejected("policy".into()).encode().unwrap();
|
||||
assert_schema_neutral(&outcome);
|
||||
assert_eq!(
|
||||
outcome,
|
||||
Value::Record(BTreeMap::from([
|
||||
("$case".into(), Value::String("Rejected".into())),
|
||||
("value".into(), Value::String("policy".into())),
|
||||
]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_is_a_validated_canonical_absolute_path_string() {
|
||||
let entry = Entry::new("/articles/one").unwrap();
|
||||
assert_eq!(
|
||||
entry.encode().unwrap(),
|
||||
Value::String("/articles/one".into())
|
||||
);
|
||||
|
||||
for invalid in [
|
||||
"articles/one",
|
||||
"/articles/",
|
||||
"/articles//one",
|
||||
"/articles/./one",
|
||||
"/articles/../one",
|
||||
] {
|
||||
assert!(
|
||||
Entry::new(invalid).is_err(),
|
||||
"accepted invalid path {invalid}"
|
||||
);
|
||||
assert!(
|
||||
Entry::decode(Value::String(invalid.into())).is_err(),
|
||||
"decoded invalid path {invalid}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_schema_neutral(value: &Value) {
|
||||
// This exhaustive match is a compile-time regression guard: reintroducing
|
||||
// semantic Entry/Enum/Union/Json variants makes the consumer non-exhaustive.
|
||||
match value {
|
||||
Value::Unit
|
||||
| Value::Boolean(_)
|
||||
| Value::Integer(_)
|
||||
| Value::Number(_)
|
||||
| Value::String(_)
|
||||
| Value::Bytes(_) => {}
|
||||
Value::Record(fields) => {
|
||||
for value in fields.values() {
|
||||
assert_schema_neutral(value);
|
||||
}
|
||||
}
|
||||
Value::List(values) => {
|
||||
for value in values {
|
||||
assert_schema_neutral(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user