fix: align interface macros with canonical values
This commit is contained in:
+207
-99
@@ -30,18 +30,18 @@
|
||||
//!
|
||||
//! | Rust type | Protocol type/value |
|
||||
//! | --- | --- |
|
||||
//! | `()` as an operation result | no return declaration / no value |
|
||||
//! | `()` | `Unit` |
|
||||
//! | `bool` | `Boolean` |
|
||||
//! | signed and unsigned integer primitives | JavaScript-lossless `Integer` |
|
||||
//! | `f32`, `f64` | finite `Number` |
|
||||
//! | `String` | `String` |
|
||||
//! | [`Bytes`] | `Bytes` |
|
||||
//! | [`wip_protocol::JsonValue`] | `Json` |
|
||||
//! | [`Entry<K, V>`] | `Entry<K, V>` |
|
||||
//! | [`JsonValue`] | schema-neutral `Json` value tree |
|
||||
//! | [`Entry`] | canonical absolute Worldspace path (`Entry`) |
|
||||
//! | `Vec<T>` | `List<T>` |
|
||||
//! | a named-field struct deriving [`WipType`] | named record |
|
||||
//! | an all-unit enum deriving [`WipType`] | named enum |
|
||||
//! | an all-newtype enum deriving [`WipType`] | named tagged union |
|
||||
//! | an enum mixing unit and single-payload cases deriving [`WipType`] | named union |
|
||||
//!
|
||||
//! `Option<T>` is supported only directly as a record field or operation
|
||||
//! parameter. It means omission, not a null value. A domain failure belongs in
|
||||
@@ -49,33 +49,44 @@
|
||||
//! [`HostError`] is reserved for host/runtime failure, so the required
|
||||
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
||||
//!
|
||||
//! # Migration to canonical values
|
||||
//!
|
||||
//! Earlier releases exposed `Entry<K, V>` and semantic `Value::Json`,
|
||||
//! `Value::Entry`, `Value::Enum`, and `Value::Union` variants. Those forms are
|
||||
//! intentionally gone: [`Entry`] is now one validated absolute Worldspace path,
|
||||
//! while JSON, enum, and union meaning comes only from the descriptor. Codecs
|
||||
//! exchange only raw [`Value`] strings, records, lists, and primitives. Unit
|
||||
//! operation results now cross the boundary as [`Value::Unit`] rather than an
|
||||
//! absent value.
|
||||
//!
|
||||
//! # Supported interface syntax
|
||||
//!
|
||||
//! An interface is a public, non-generic trait whose operations use exactly
|
||||
//! `&self`, simple named owned parameters, and an explicit
|
||||
//! `OperationResult<T>`. `WipType` derives support named-field structs,
|
||||
//! all-unit enums, and all-single-payload enums.
|
||||
//! all-unit enums as protocol enums, and enums made from any mix of unit and
|
||||
//! single-payload cases as protocol unions.
|
||||
//!
|
||||
//! The macros reject trait inheritance and associated items; const, async,
|
||||
//! unsafe, extern, variadic, generic, default-bodied, or non-`&self` methods;
|
||||
//! borrowed values and custom lifetimes; tuple, unit, or generic structs;
|
||||
//! mixed or named-field enum variants; explicit discriminants; Rust unions;
|
||||
//! unsupported named-field or multi-field enum variants; explicit discriminants; Rust unions;
|
||||
//! and `Option` anywhere except a direct DTO field or operation parameter.
|
||||
//! Unsupported inputs produce source-located compile errors rather than
|
||||
//! generating a partial interface.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
pub use wip_interface_macros::{WipType, interface};
|
||||
pub use wip_protocol;
|
||||
pub use wip_protocol::{
|
||||
Documentation, EnumDeclaration, EnumVariantDeclaration, FieldDeclaration, InterfaceDescriptor,
|
||||
JsonMember, JsonValue, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NamedValue, OperationDeclaration,
|
||||
ParameterDeclaration, RecordDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr,
|
||||
UnionDeclaration, UnionVariantDeclaration, ValidationError, Value,
|
||||
Documentation, EnumCase, FieldDeclaration, InterfaceDescriptor, MAX_SAFE_INTEGER,
|
||||
MIN_SAFE_INTEGER, OperationDeclaration, ParameterDeclaration, ReturnDeclaration,
|
||||
TypeDeclaration, TypeExpr, UnionCase, ValidationError, Value,
|
||||
};
|
||||
|
||||
/// Converts one Rust application type to and from its protocol representation.
|
||||
@@ -118,8 +129,8 @@ pub trait InterfaceImplementation<T>: InterfaceDefinition {
|
||||
fn dispatch(
|
||||
implementation: &T,
|
||||
operation: &str,
|
||||
arguments: Vec<NamedValue>,
|
||||
) -> Result<Option<Value>, DispatchError>;
|
||||
arguments: BTreeMap<String, Value>,
|
||||
) -> Result<Value, DispatchError>;
|
||||
}
|
||||
|
||||
/// Result convention required for generated interface operations.
|
||||
@@ -281,13 +292,101 @@ impl From<Bytes> for Vec<u8> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed protocol key/value entry.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Entry<K, V> {
|
||||
/// Entry key.
|
||||
pub key: K,
|
||||
/// Entry value.
|
||||
pub value: V,
|
||||
/// A canonical absolute path to an entry in the current Worldspace.
|
||||
///
|
||||
/// This replaces the pre-canonical `Entry<K, V>` key/value pair. Construct an
|
||||
/// entry from a path such as `/articles/1`; application data associated with
|
||||
/// that entry belongs in an ordinary record alongside this value.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Entry(String);
|
||||
|
||||
impl Entry {
|
||||
/// Validates and creates an entry path.
|
||||
pub fn new(path: impl Into<String>) -> Result<Self, CodecError> {
|
||||
let path = path.into();
|
||||
validate_entry_path(&path)?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
|
||||
/// Returns the canonical absolute Worldspace path.
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Consumes the entry and returns its path.
|
||||
#[must_use]
|
||||
pub fn into_string(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Entry {
|
||||
type Error = CodecError;
|
||||
|
||||
fn try_from(path: String) -> Result<Self, Self::Error> {
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for Entry {
|
||||
type Err = CodecError;
|
||||
|
||||
fn from_str(path: &str) -> Result<Self, Self::Err> {
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// One member in a [`JsonValue::Object`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct JsonMember {
|
||||
/// Member name.
|
||||
pub name: String,
|
||||
/// Member value.
|
||||
pub value: JsonValue,
|
||||
}
|
||||
|
||||
/// JSON data represented independently of any application schema.
|
||||
///
|
||||
/// Its codec uses the ordinary schema-neutral [`Value`] variants. JSON null is
|
||||
/// [`Value::Unit`], arrays are [`Value::List`], and objects are
|
||||
/// [`Value::Record`]. Protocol bytes have no JSON representation and decoding
|
||||
/// a tree containing [`Value::Bytes`] is rejected.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum JsonValue {
|
||||
/// JSON null.
|
||||
Null,
|
||||
/// A JSON boolean.
|
||||
Boolean(bool),
|
||||
/// An interoperable integral JSON number.
|
||||
Integer(i64),
|
||||
/// A finite non-integral JSON number.
|
||||
Number(f64),
|
||||
/// A JSON string.
|
||||
String(String),
|
||||
/// A JSON array.
|
||||
Array(Vec<JsonValue>),
|
||||
/// A JSON object. Duplicate member names are rejected while encoding.
|
||||
Object(Vec<JsonMember>),
|
||||
}
|
||||
|
||||
impl WipType for () {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Unit
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Unit)
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Unit => Ok(()),
|
||||
other => Err(CodecError::expected("unit", &other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WipType for bool {
|
||||
@@ -456,52 +555,87 @@ impl WipType for JsonValue {
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
validate_json(&self)?;
|
||||
Ok(Value::Json(self))
|
||||
encode_json(self)
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Json(value) => {
|
||||
validate_json(&value)?;
|
||||
Ok(value)
|
||||
decode_json(value)
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_json(value: JsonValue) -> Result<Value, CodecError> {
|
||||
match value {
|
||||
JsonValue::Null => Ok(Value::Unit),
|
||||
JsonValue::Boolean(value) => Ok(Value::Boolean(value)),
|
||||
JsonValue::Integer(value) => {
|
||||
ensure_safe_integer(value)?;
|
||||
Ok(Value::Integer(value))
|
||||
}
|
||||
JsonValue::Number(value) => {
|
||||
ensure_finite(value)?;
|
||||
Ok(Value::Number(value))
|
||||
}
|
||||
JsonValue::String(value) => Ok(Value::String(value)),
|
||||
JsonValue::Array(values) => values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| encode_json(value).map_err(|error| error.at(index.to_string())))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(Value::List),
|
||||
JsonValue::Object(members) => {
|
||||
let mut fields = BTreeMap::new();
|
||||
for member in members {
|
||||
let name = member.name;
|
||||
let value = encode_json(member.value).map_err(|error| error.at(name.clone()))?;
|
||||
if fields.insert(name.clone(), value).is_some() {
|
||||
return Err(CodecError::new(format!("duplicate JSON member `{name}`")).at(name));
|
||||
}
|
||||
}
|
||||
other => Err(CodecError::expected("json", &other)),
|
||||
Ok(Value::Record(fields))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_json(value: &JsonValue) -> Result<(), CodecError> {
|
||||
fn decode_json(value: Value) -> Result<JsonValue, CodecError> {
|
||||
match value {
|
||||
JsonValue::Integer(value) => ensure_safe_integer(*value),
|
||||
JsonValue::Number(value) => ensure_finite(*value),
|
||||
JsonValue::Array(values) => {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
validate_json(value).map_err(|error| error.at(index.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
Value::Unit => Ok(JsonValue::Null),
|
||||
Value::Boolean(value) => Ok(JsonValue::Boolean(value)),
|
||||
Value::Integer(value) => {
|
||||
ensure_safe_integer(value)?;
|
||||
Ok(JsonValue::Integer(value))
|
||||
}
|
||||
JsonValue::Object(members) => {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for member in members {
|
||||
if !names.insert(member.name.as_str()) {
|
||||
return Err(CodecError::new(format!(
|
||||
"duplicate JSON member `{}`",
|
||||
member.name
|
||||
))
|
||||
.at(member.name.clone()));
|
||||
}
|
||||
validate_json(&member.value).map_err(|error| error.at(member.name.clone()))?;
|
||||
}
|
||||
Ok(())
|
||||
Value::Number(value) => {
|
||||
ensure_finite(value)?;
|
||||
Ok(JsonValue::Number(value))
|
||||
}
|
||||
JsonValue::Null | JsonValue::Boolean(_) | JsonValue::String(_) => Ok(()),
|
||||
Value::String(value) => Ok(JsonValue::String(value)),
|
||||
Value::Bytes(_) => Err(CodecError::new("bytes are not valid inside JSON")),
|
||||
Value::List(values) => values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| decode_json(value).map_err(|error| error.at(index.to_string())))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(JsonValue::Array),
|
||||
Value::Record(fields) => fields
|
||||
.into_iter()
|
||||
.map(|(name, value)| {
|
||||
decode_json(value)
|
||||
.map(|value| JsonMember {
|
||||
name: name.clone(),
|
||||
value,
|
||||
})
|
||||
.map_err(|error| error.at(name))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(JsonValue::Object),
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: WipType> WipType for Vec<T> {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::List(Box::new(T::type_expr()))
|
||||
TypeExpr::List {
|
||||
items: Box::new(T::type_expr()),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
||||
@@ -528,37 +662,31 @@ impl<T: WipType> WipType for Vec<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: WipType, V: WipType> WipType for Entry<K, V> {
|
||||
impl WipType for Entry {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Entry {
|
||||
key: Box::new(K::type_expr()),
|
||||
value: Box::new(V::type_expr()),
|
||||
}
|
||||
TypeExpr::Entry
|
||||
}
|
||||
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
||||
K::collect_declarations(declarations);
|
||||
V::collect_declarations(declarations);
|
||||
}
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Entry {
|
||||
key: Box::new(self.key.encode().map_err(|error| error.at("key"))?),
|
||||
value: Box::new(self.value.encode().map_err(|error| error.at("value"))?),
|
||||
})
|
||||
validate_entry_path(&self.0)?;
|
||||
Ok(Value::String(self.0))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
let Value::Entry { key, value } = value else {
|
||||
return Err(CodecError::expected("entry", &value));
|
||||
let Value::String(path) = value else {
|
||||
return Err(CodecError::expected("entry path string", &value));
|
||||
};
|
||||
Ok(Self {
|
||||
key: K::decode(*key).map_err(|error| error.at("key"))?,
|
||||
value: V::decode(*value).map_err(|error| error.at("value"))?,
|
||||
})
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_entry_path(path: &str) -> Result<(), CodecError> {
|
||||
wip_protocol::validate_path(path)
|
||||
.map_err(|error| CodecError::new(format!("invalid canonical Worldspace path: {error}")))
|
||||
}
|
||||
|
||||
/// Implementation details used by code emitted from the facade's macros.
|
||||
///
|
||||
/// These APIs are public only because macro expansions execute in the
|
||||
@@ -566,12 +694,9 @@ impl<K: WipType, V: WipType> WipType for Entry<K, V> {
|
||||
/// and are not intended for direct use.
|
||||
#[doc(hidden)]
|
||||
pub mod __private {
|
||||
use std::collections::HashSet;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_protocol::{
|
||||
InterfaceDescriptor, NamedValue, ObjectId, OperationCall, OperationTarget, TypeDeclaration,
|
||||
ValidationError, Value,
|
||||
};
|
||||
use wip_protocol::{InterfaceDescriptor, TypeDeclaration, ValidationError, Value};
|
||||
|
||||
use crate::{CodecError, Documentation, WipType};
|
||||
|
||||
@@ -606,16 +731,9 @@ pub mod __private {
|
||||
pub fn validate_arguments(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
operation: &str,
|
||||
arguments: &[NamedValue],
|
||||
arguments: &BTreeMap<String, Value>,
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate_call(&OperationCall {
|
||||
target: OperationTarget {
|
||||
object: ObjectId("<typed-dispatch>".into()),
|
||||
interface: descriptor.name.clone(),
|
||||
operation: operation.into(),
|
||||
},
|
||||
arguments: arguments.to_vec(),
|
||||
})
|
||||
descriptor.validate_arguments(operation, arguments)
|
||||
}
|
||||
|
||||
/// Builds a codec error for a generated structural mismatch.
|
||||
@@ -633,21 +751,13 @@ pub mod __private {
|
||||
|
||||
/// Decoder for a protocol record or operation's named argument collection.
|
||||
pub struct RecordDecoder {
|
||||
fields: Vec<NamedValue>,
|
||||
fields: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
impl RecordDecoder {
|
||||
/// Starts decoding record fields or named operation arguments and
|
||||
/// rejects duplicate names.
|
||||
pub fn new(fields: Vec<NamedValue>) -> Result<Self, CodecError> {
|
||||
let mut seen = HashSet::new();
|
||||
for field in &fields {
|
||||
if !seen.insert(field.name.clone()) {
|
||||
return Err(CodecError::new(format!("duplicate field `{}`", field.name))
|
||||
.at(field.name.clone()));
|
||||
}
|
||||
}
|
||||
Ok(Self { fields })
|
||||
/// Starts decoding record fields or named operation arguments.
|
||||
pub fn new(fields: BTreeMap<String, Value>) -> Self {
|
||||
Self { fields }
|
||||
}
|
||||
|
||||
/// Decodes a required field.
|
||||
@@ -668,17 +778,15 @@ pub mod __private {
|
||||
|
||||
/// Rejects any fields that were not consumed by generated code.
|
||||
pub fn finish(self) -> Result<(), CodecError> {
|
||||
if let Some(field) = self.fields.first() {
|
||||
Err(CodecError::new(format!("unknown field `{}`", field.name))
|
||||
.at(field.name.clone()))
|
||||
if let Some(name) = self.fields.keys().next() {
|
||||
Err(CodecError::new(format!("unknown field `{name}`")).at(name.clone()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, name: &str) -> Option<Value> {
|
||||
let index = self.fields.iter().position(|field| field.name == name)?;
|
||||
Some(self.fields.remove(index).value)
|
||||
self.fields.remove(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use wip_interface::wip_protocol::{
|
||||
EnumDeclaration, JsonMember, JsonValue, NamedValue, RecordDeclaration, TypeDeclaration,
|
||||
TypeExpr, UnionDeclaration, Value,
|
||||
};
|
||||
use wip_interface::{Bytes, Entry, WipType};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_interface::wip_protocol::{TypeExpr, UNION_CASE_FIELD, UNION_VALUE_FIELD, Value};
|
||||
use wip_interface::{Bytes, Entry, JsonMember, JsonValue, WipType};
|
||||
|
||||
/// A request record.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
@@ -11,8 +10,8 @@ struct Request {
|
||||
title: String,
|
||||
/// Optional priority.
|
||||
priority: Option<i32>,
|
||||
/// Related entries.
|
||||
related: Vec<Entry<String, bool>>,
|
||||
/// Related Worldspace entries.
|
||||
related: Vec<Entry>,
|
||||
/// Opaque bytes.
|
||||
body: Bytes,
|
||||
/// Arbitrary metadata.
|
||||
@@ -38,33 +37,53 @@ struct Receipt {
|
||||
/// Application-level publication outcome.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
enum PublishOutcome {
|
||||
/// Work has not completed and carries no payload.
|
||||
Pending,
|
||||
/// Application success.
|
||||
Published(Receipt),
|
||||
/// Domain rejection, not a host failure.
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
fn field<'a>(record: &'a BTreeMap<String, Value>, name: &str) -> &'a Value {
|
||||
record
|
||||
.get(name)
|
||||
.unwrap_or_else(|| panic!("missing `{name}`"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_values_round_trip() {
|
||||
fn primitive_unit_record_list_entry_and_json_values_round_trip() {
|
||||
assert_eq!(().encode().unwrap(), Value::Unit);
|
||||
assert_eq!(<()>::decode(Value::Unit).unwrap(), ());
|
||||
assert_eq!(<()>::type_expr(), TypeExpr::Unit);
|
||||
|
||||
let request = Request {
|
||||
title: "hello".into(),
|
||||
priority: None,
|
||||
related: vec![Entry {
|
||||
key: "/articles/1".into(),
|
||||
value: true,
|
||||
}],
|
||||
related: vec![Entry::new("/articles/1").unwrap()],
|
||||
body: Bytes(vec![1, 2, 3]),
|
||||
metadata: JsonValue::Object(vec![JsonMember {
|
||||
name: "source".into(),
|
||||
value: JsonValue::String("test".into()),
|
||||
value: JsonValue::Array(vec![JsonValue::String("test".into()), JsonValue::Null]),
|
||||
}]),
|
||||
};
|
||||
|
||||
let encoded = request.clone().encode().unwrap();
|
||||
let Value::Record(fields) = &encoded else {
|
||||
panic!("record derive must encode a protocol record")
|
||||
panic!("record derive must encode a raw protocol record")
|
||||
};
|
||||
assert!(fields.iter().all(|field| field.name != "priority"));
|
||||
assert!(!fields.contains_key("priority"));
|
||||
assert_eq!(
|
||||
field(fields, "related"),
|
||||
&Value::List(vec![Value::String("/articles/1".into())])
|
||||
);
|
||||
assert_eq!(
|
||||
field(fields, "metadata"),
|
||||
&Value::Record(BTreeMap::from([(
|
||||
"source".into(),
|
||||
Value::List(vec![Value::String("test".into()), Value::Unit]),
|
||||
)]))
|
||||
);
|
||||
assert_eq!(Request::decode(encoded).unwrap(), request);
|
||||
|
||||
let number = 42.5_f64;
|
||||
@@ -77,92 +96,136 @@ fn supported_values_round_trip() {
|
||||
f32::decode(narrow_number.encode().unwrap()).unwrap(),
|
||||
narrow_number
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enums_are_strings_and_unions_are_discriminated_records() {
|
||||
for color in [Color::Red, Color::Blue] {
|
||||
let encoded = color.clone().encode().unwrap();
|
||||
let decoded = Color::decode(encoded).unwrap();
|
||||
assert_eq!(decoded, color);
|
||||
assert!(matches!(encoded, Value::String(_)));
|
||||
assert_eq!(Color::decode(encoded).unwrap(), color);
|
||||
}
|
||||
|
||||
let pending = PublishOutcome::Pending.encode().unwrap();
|
||||
assert_eq!(
|
||||
pending,
|
||||
Value::Record(BTreeMap::from([(
|
||||
UNION_CASE_FIELD.into(),
|
||||
Value::String("Pending".into()),
|
||||
)]))
|
||||
);
|
||||
|
||||
let published = PublishOutcome::Published(Receipt { number: 7 })
|
||||
.encode()
|
||||
.unwrap();
|
||||
let Value::Record(fields) = &published else {
|
||||
panic!("union must encode as a record")
|
||||
};
|
||||
assert_eq!(
|
||||
fields.get(UNION_CASE_FIELD),
|
||||
Some(&Value::String("Published".into()))
|
||||
);
|
||||
assert!(matches!(
|
||||
fields.get(UNION_VALUE_FIELD),
|
||||
Some(Value::Record(_))
|
||||
));
|
||||
|
||||
for outcome in [
|
||||
PublishOutcome::Pending,
|
||||
PublishOutcome::Published(Receipt { number: 7 }),
|
||||
PublishOutcome::Rejected("policy".into()),
|
||||
] {
|
||||
let encoded = outcome.clone().encode().unwrap();
|
||||
let decoded = PublishOutcome::decode(encoded).unwrap();
|
||||
assert_eq!(decoded, outcome);
|
||||
assert_eq!(PublishOutcome::decode(encoded).unwrap(), outcome);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_declarations_include_docs_optionality_and_dependencies() {
|
||||
fn derived_declarations_use_canonical_named_type_expressions() {
|
||||
let mut declarations = Vec::new();
|
||||
Request::collect_declarations(&mut declarations);
|
||||
Color::collect_declarations(&mut declarations);
|
||||
PublishOutcome::collect_declarations(&mut declarations);
|
||||
|
||||
let TypeDeclaration::Record(RecordDeclaration {
|
||||
documentation,
|
||||
fields,
|
||||
..
|
||||
}) = &declarations[0]
|
||||
else {
|
||||
let request = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name == "Request")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
request.documentation.as_ref().unwrap().summary,
|
||||
"A request record."
|
||||
);
|
||||
let TypeExpr::Record { fields } = &request.definition else {
|
||||
panic!("Request must be a record declaration")
|
||||
};
|
||||
assert_eq!(documentation.as_ref().unwrap().summary, "A request record.");
|
||||
assert_eq!(
|
||||
fields[0].documentation.as_ref().unwrap().summary,
|
||||
"Required title."
|
||||
);
|
||||
assert!(!fields[0].optional);
|
||||
assert!(fields[1].optional);
|
||||
assert_eq!(fields[1].ty, TypeExpr::Integer);
|
||||
assert!(fields[0].required);
|
||||
assert!(!fields[1].required);
|
||||
assert_eq!(fields[1].r#type, TypeExpr::Integer);
|
||||
assert_eq!(
|
||||
fields[2].ty,
|
||||
TypeExpr::List(Box::new(TypeExpr::Entry {
|
||||
key: Box::new(TypeExpr::String),
|
||||
value: Box::new(TypeExpr::Boolean),
|
||||
}))
|
||||
fields[2].r#type,
|
||||
TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Entry),
|
||||
}
|
||||
);
|
||||
|
||||
let color = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name() == "Color")
|
||||
.find(|declaration| declaration.name == "Color")
|
||||
.unwrap();
|
||||
let TypeDeclaration::Enum(EnumDeclaration { variants, .. }) = color else {
|
||||
let TypeExpr::Enum { cases } = &color.definition else {
|
||||
panic!("Color must be an enum declaration")
|
||||
};
|
||||
assert_eq!(
|
||||
variants[0].documentation.as_ref().unwrap().summary,
|
||||
cases[0].documentation.as_ref().unwrap().summary,
|
||||
"Warm red."
|
||||
);
|
||||
|
||||
let outcome = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name() == "PublishOutcome")
|
||||
.find(|declaration| declaration.name == "PublishOutcome")
|
||||
.unwrap();
|
||||
let TypeDeclaration::Union(UnionDeclaration { variants, .. }) = outcome else {
|
||||
let TypeExpr::Union { cases } = &outcome.definition else {
|
||||
panic!("PublishOutcome must be a union declaration")
|
||||
};
|
||||
assert_eq!(variants[0].ty, TypeExpr::Named("Receipt".into()));
|
||||
assert_eq!(cases[0].payload, None);
|
||||
assert_eq!(
|
||||
cases[1].payload,
|
||||
Some(TypeExpr::Named {
|
||||
name: "Receipt".into(),
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
declarations
|
||||
.iter()
|
||||
.any(|declaration| declaration.name() == "Receipt")
|
||||
.any(|declaration| declaration.name == "Receipt")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codecs_reject_invalid_boundaries() {
|
||||
fn codecs_reject_invalid_boundaries_and_json_bytes() {
|
||||
assert!(i64::MAX.encode().is_err());
|
||||
assert!(f64::NAN.encode().is_err());
|
||||
assert!(Request::decode(Value::Record(vec![])).is_err());
|
||||
assert!(Request::decode(Value::Record(BTreeMap::new())).is_err());
|
||||
assert!(
|
||||
Request::decode(Value::Record(vec![NamedValue {
|
||||
name: "unknown".into(),
|
||||
value: Value::String("value".into()),
|
||||
}]))
|
||||
Request::decode(Value::Record(BTreeMap::from([(
|
||||
"unknown".into(),
|
||||
Value::String("value".into()),
|
||||
)])))
|
||||
.is_err()
|
||||
);
|
||||
assert!(Color::decode(Value::String("Green".into())).is_err());
|
||||
assert!(Entry::new("articles/1").is_err());
|
||||
assert!(Entry::decode(Value::String("/articles/../1".into())).is_err());
|
||||
assert!(JsonValue::decode(Value::Bytes(vec![1])).is_err());
|
||||
assert!(
|
||||
JsonValue::decode(Value::Record(BTreeMap::from([(
|
||||
"nested".into(),
|
||||
Value::List(vec![Value::Bytes(vec![1])]),
|
||||
)])))
|
||||
.is_err()
|
||||
);
|
||||
assert!(Color::decode(Value::Enum("Green".into())).is_err());
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use wip_interface::wip_protocol::{NamedValue, TypeDeclaration, TypeExpr, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_interface::wip_protocol::{INTERFACE_FORMAT_V1, TypeExpr, Value};
|
||||
use wip_interface::{DispatchError, HostError, OperationResult, WipType, interface};
|
||||
|
||||
/// Publication request.
|
||||
@@ -36,7 +38,7 @@ pub trait Catalog {
|
||||
note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome>;
|
||||
|
||||
/// Checks connectivity without returning an application value.
|
||||
/// Checks connectivity without returning application data.
|
||||
fn ping(&self) -> OperationResult<()>;
|
||||
|
||||
/// Demonstrates a host/runtime failure.
|
||||
@@ -88,36 +90,29 @@ impl Catalog for RejectingCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
fn named(name: &str, value: Value) -> NamedValue {
|
||||
NamedValue {
|
||||
name: name.into(),
|
||||
value,
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_arguments(with_note: bool) -> Vec<NamedValue> {
|
||||
let mut arguments = vec![named(
|
||||
"request",
|
||||
fn publish_arguments(with_note: bool) -> BTreeMap<String, Value> {
|
||||
let mut arguments = BTreeMap::from([(
|
||||
"request".into(),
|
||||
PublishRequest {
|
||||
title: "example".into(),
|
||||
}
|
||||
.encode()
|
||||
.unwrap(),
|
||||
)];
|
||||
)]);
|
||||
if with_note {
|
||||
arguments.push(named("note", Value::String("audit".into())));
|
||||
arguments.insert("note".into(), Value::String("audit".into()));
|
||||
}
|
||||
arguments
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_is_generated_only_from_the_trait_declaration() {
|
||||
fn descriptor_is_canonical_and_generated_only_from_the_trait_declaration() {
|
||||
let first = CatalogDefinition::descriptor();
|
||||
let second = CatalogDefinition::descriptor();
|
||||
assert_eq!(first, second);
|
||||
first.validate().unwrap();
|
||||
|
||||
assert_eq!(first.name, "Catalog");
|
||||
assert_eq!(first.format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(
|
||||
first.documentation.as_ref().unwrap().summary,
|
||||
"Catalog editing capability."
|
||||
@@ -139,81 +134,82 @@ fn descriptor_is_generated_only_from_the_trait_declaration() {
|
||||
.summary,
|
||||
"Item to publish."
|
||||
);
|
||||
assert!(!publish.parameters[0].optional);
|
||||
assert!(publish.parameters[1].optional);
|
||||
assert!(publish.parameters[0].required);
|
||||
assert!(!publish.parameters[1].required);
|
||||
assert_eq!(
|
||||
publish
|
||||
.returns
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.documentation
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.summary,
|
||||
publish.returns.documentation.as_ref().unwrap().summary,
|
||||
"The application publication outcome."
|
||||
);
|
||||
assert_eq!(
|
||||
publish.returns.as_ref().unwrap().ty,
|
||||
TypeExpr::Named("PublishOutcome".into())
|
||||
publish.returns.r#type,
|
||||
TypeExpr::Named {
|
||||
name: "PublishOutcome".into(),
|
||||
}
|
||||
);
|
||||
assert!(first.operations[1].returns.is_none());
|
||||
assert_eq!(first.operations[1].returns.r#type, TypeExpr::Unit);
|
||||
assert!(
|
||||
first
|
||||
.declarations
|
||||
.types
|
||||
.iter()
|
||||
.any(|declaration| matches!(declaration, TypeDeclaration::Record(_)))
|
||||
.any(|declaration| matches!(declaration.definition, TypeExpr::Record { .. }))
|
||||
);
|
||||
assert!(
|
||||
first
|
||||
.declarations
|
||||
.types
|
||||
.iter()
|
||||
.any(|declaration| matches!(declaration, TypeDeclaration::Union(_)))
|
||||
.any(|declaration| matches!(declaration.definition, TypeExpr::Union { .. }))
|
||||
);
|
||||
|
||||
// Both implementation types satisfy the same generated dispatch boundary;
|
||||
// neither can affect the descriptor shape.
|
||||
// Both implementation types satisfy one immutable generated definition;
|
||||
// implementation selection cannot contribute fields to the descriptor.
|
||||
fn accepts_definition<T: Catalog>(_: &T) {}
|
||||
accepts_definition(&AcceptingCatalog);
|
||||
accepts_definition(&RejectingCatalog);
|
||||
assert_eq!(CatalogDefinition::descriptor(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_argument_decoder_and_result_encoder_round_trip() {
|
||||
fn generated_argument_decoder_and_result_encoder_use_raw_values() {
|
||||
let decoded = CatalogPublishArguments::decode(publish_arguments(false)).unwrap();
|
||||
assert_eq!(decoded.request.title, "example");
|
||||
assert_eq!(decoded.note, None);
|
||||
|
||||
let encoded = CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into()))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let encoded =
|
||||
CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into())).unwrap();
|
||||
assert_eq!(
|
||||
PublishOutcome::decode(encoded).unwrap(),
|
||||
PublishOutcome::Rejected("domain".into())
|
||||
);
|
||||
assert_eq!(
|
||||
CatalogPingArguments::encode_result(()).unwrap(),
|
||||
Value::Unit
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
|
||||
let value = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let value =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true)).unwrap();
|
||||
assert_eq!(
|
||||
PublishOutcome::decode(value).unwrap(),
|
||||
PublishOutcome::Published(true)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", vec![]).unwrap(),
|
||||
None
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", BTreeMap::new()).unwrap(),
|
||||
Value::Unit
|
||||
);
|
||||
|
||||
let invalid = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", vec![]).unwrap_err();
|
||||
let invalid =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(invalid, DispatchError::InvalidArguments(_)));
|
||||
|
||||
let host = CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", vec![]).unwrap_err();
|
||||
let host =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(host, DispatchError::Host(error) if error.message() == "backend unavailable"));
|
||||
|
||||
let unknown = CatalogDefinition::dispatch(&AcceptingCatalog, "missing", vec![]).unwrap_err();
|
||||
let unknown =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "missing", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(unknown, DispatchError::UnknownOperation(name) if name == "missing"));
|
||||
}
|
||||
|
||||
@@ -245,12 +241,12 @@ fn distinct_operation_names_always_generate_distinct_public_items() {
|
||||
assert_eq!(descriptor.operations[0].name, "item");
|
||||
assert_eq!(descriptor.operations[1].name, "item_");
|
||||
|
||||
let first = DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", vec![])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let second = DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", vec![])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let first =
|
||||
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", BTreeMap::new())
|
||||
.unwrap();
|
||||
let second =
|
||||
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", BTreeMap::new())
|
||||
.unwrap();
|
||||
assert_eq!(first, Value::String("item".into()));
|
||||
assert_eq!(second, Value::String("item_".into()));
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
enum MixedEnum {
|
||||
enum UnsupportedEnum {
|
||||
Empty,
|
||||
Payload(String),
|
||||
Payload { value: String },
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
error: a `WipType` enum must contain either only unit variants or only single-field tuple variants; mixed and named-field variants are unsupported
|
||||
--> tests/ui/mixed_enum.rs:4:1
|
||||
error: a `WipType` enum must contain unit variants and/or single-field tuple variants; named-field and multi-field variants are unsupported
|
||||
--> tests/ui/mixed_enum.rs:6:5
|
||||
|
|
||||
4 | enum MixedEnum {
|
||||
| ^^^^
|
||||
6 | Payload { value: String },
|
||||
| ^^^^^^^
|
||||
|
||||
@@ -4,16 +4,11 @@ error[E0277]: the trait bound `(std::string::String, std::string::String): WipTy
|
||||
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||
|
|
||||
= help: the following other types implement trait `WipType`:
|
||||
JsonValue
|
||||
Vec<T>
|
||||
bool
|
||||
f32
|
||||
f64
|
||||
i128
|
||||
i16
|
||||
i32
|
||||
and $N others
|
||||
help: the trait `WipType` is implemented for `()`
|
||||
--> src/lib.rs
|
||||
|
|
||||
| impl WipType for () {
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
|
||||
--> tests/ui/unsupported_type.rs:5:26
|
||||
@@ -24,16 +19,11 @@ error[E0277]: the trait bound `(std::string::String, std::string::String): WipTy
|
||||
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||
|
|
||||
= help: the following other types implement trait `WipType`:
|
||||
JsonValue
|
||||
Vec<T>
|
||||
bool
|
||||
f32
|
||||
f64
|
||||
i128
|
||||
i16
|
||||
i32
|
||||
and $N others
|
||||
help: the trait `WipType` is implemented for `()`
|
||||
--> src/lib.rs
|
||||
|
|
||||
| impl WipType for () {
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
note: required by a bound in `wip_interface::__private::RecordDecoder::required`
|
||||
--> src/lib.rs
|
||||
|
|
||||
|
||||
Reference in New Issue
Block a user