#![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, EnumCase, FieldDeclaration, InterfaceDescriptor, MAX_SAFE_INTEGER,
MIN_SAFE_INTEGER, OperationDeclaration, ParameterDeclaration, ReturnDeclaration,
TypeDeclaration, TypeExpr, UnionCase, ValidationError, Value,
};
pub trait WipType: Sized {
fn type_expr() -> TypeExpr;
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>);
fn encode(self) -> Result<Value, CodecError>;
fn decode(value: Value) -> Result<Self, CodecError>;
}
pub trait InterfaceDefinition {
fn descriptor() -> InterfaceDescriptor;
}
pub trait InterfaceImplementation<T>: InterfaceDefinition {
fn dispatch(
implementation: &T,
operation: &str,
arguments: BTreeMap<String, Value>,
) -> Result<Value, DispatchError>;
}
pub type OperationResult<T> = Result<T, HostError>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EffectGuarantee {
NotCommitted,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostErrorKind {
Internal,
ResourceLimitExceeded,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostError {
kind: HostErrorKind,
effect_guarantee: EffectGuarantee,
message: String,
}
impl HostError {
#[must_use]
pub fn internal(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
Self::new(HostErrorKind::Internal, effect_guarantee, message)
}
#[must_use]
pub fn resource_limit(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
Self::new(
HostErrorKind::ResourceLimitExceeded,
effect_guarantee,
message,
)
}
fn new(
kind: HostErrorKind,
effect_guarantee: EffectGuarantee,
message: impl Into<String>,
) -> Self {
Self {
kind,
effect_guarantee,
message: bounded_diagnostic(message.into()),
}
}
#[must_use]
pub fn kind(&self) -> HostErrorKind {
self.kind
}
#[must_use]
pub fn effect_guarantee(&self) -> EffectGuarantee {
self.effect_guarantee
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
const MAX_DIAGNOSTIC_BYTES: usize = 512;
fn bounded_diagnostic(mut message: String) -> String {
if message.len() <= MAX_DIAGNOSTIC_BYTES {
return message;
}
let mut end = MAX_DIAGNOSTIC_BYTES;
while !message.is_char_boundary(end) {
end -= 1;
}
message.truncate(end);
message
}
impl Display for HostError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl Error for HostError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodecError {
path: Vec<String>,
message: String,
}
impl CodecError {
#[must_use]
pub fn new(message: impl Into<String>) -> Self {
Self {
path: Vec::new(),
message: message.into(),
}
}
#[must_use]
pub fn expected(expected: &str, actual: &Value) -> Self {
Self::new(format!("expected {expected}, found {:?}", actual.kind()))
}
#[must_use]
pub fn at(mut self, segment: impl Into<String>) -> Self {
self.path.insert(0, segment.into());
self
}
#[must_use]
pub fn path(&self) -> &[String] {
&self.path
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl Display for CodecError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
if self.path.is_empty() {
write!(formatter, "WIP codec error: {}", self.message)
} else {
write!(
formatter,
"WIP codec error at {}: {}",
self.path.join("."),
self.message
)
}
}
}
impl Error for CodecError {}
#[derive(Debug)]
pub enum DispatchError {
UnknownOperation(String),
InvalidArguments(wip_protocol::ValidationError),
Decode(CodecError),
Host(HostError),
Panic,
Encode(CodecError),
InvalidResult(wip_protocol::ValidationError),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DispatchPhase {
BeforeInvocation,
AfterInvocation,
}
impl DispatchError {
#[must_use]
pub fn phase(&self) -> DispatchPhase {
match self {
Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => {
DispatchPhase::BeforeInvocation
}
Self::Host(_) | Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
DispatchPhase::AfterInvocation
}
}
}
#[must_use]
pub fn effect_guarantee(&self) -> Option<EffectGuarantee> {
match self {
Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => None,
Self::Host(error) => Some(error.effect_guarantee()),
Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
Some(EffectGuarantee::Unknown)
}
}
}
}
impl Display for DispatchError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownOperation(operation) => {
write!(formatter, "unknown operation `{operation}`")
}
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
Self::Host(error) => write!(formatter, "host operation failed: {error}"),
Self::Panic => formatter.write_str("operation implementation panicked"),
Self::Encode(error) => write!(formatter, "result encoding failed: {error}"),
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
}
}
}
impl Error for DispatchError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::UnknownOperation(_) | Self::Panic => None,
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
Self::Decode(error) | Self::Encode(error) => Some(error),
Self::Host(error) => Some(error),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Bytes(pub Vec<u8>);
impl From<Vec<u8>> for Bytes {
fn from(value: Vec<u8>) -> Self {
Self(value)
}
}
impl From<Bytes> for Vec<u8> {
fn from(value: Bytes) -> Self {
value.0
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Entry(String);
impl Entry {
pub fn new(path: impl Into<String>) -> Result<Self, CodecError> {
let path = path.into();
validate_entry_path(&path)?;
Ok(Self(path))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[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)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct JsonMember {
pub name: String,
pub value: JsonValue,
}
#[derive(Debug, Clone, PartialEq)]
pub enum JsonValue {
Null,
Boolean(bool),
Integer(i64),
Number(f64),
String(String),
Array(Vec<JsonValue>),
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 {
fn type_expr() -> TypeExpr {
TypeExpr::Boolean
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
Ok(Value::Boolean(self))
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::Boolean(value) => Ok(value),
other => Err(CodecError::expected("boolean", &other)),
}
}
}
macro_rules! integer_codec {
($($ty:ty),+ $(,)?) => {
$(
impl WipType for $ty {
fn type_expr() -> TypeExpr {
TypeExpr::Integer
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
let value = i64::try_from(self).map_err(|_| {
CodecError::new("integer is outside the protocol i64 range")
})?;
ensure_safe_integer(value)?;
Ok(Value::Integer(value))
}
fn decode(value: Value) -> Result<Self, CodecError> {
let Value::Integer(value) = value else {
return Err(CodecError::expected("integer", &value));
};
ensure_safe_integer(value)?;
Self::try_from(value).map_err(|_| {
CodecError::new(concat!("integer does not fit Rust `", stringify!($ty), "`"))
})
}
}
)+
};
}
integer_codec!(
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
);
fn ensure_safe_integer(value: i64) -> Result<(), CodecError> {
if (MIN_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&value) {
Ok(())
} else {
Err(CodecError::new(format!(
"integer {value} is outside the JavaScript-lossless protocol range"
)))
}
}
impl WipType for f64 {
fn type_expr() -> TypeExpr {
TypeExpr::Number
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
ensure_finite(self)?;
Ok(Value::Number(self))
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::Number(value) => {
ensure_finite(value)?;
Ok(value)
}
other => Err(CodecError::expected("number", &other)),
}
}
}
impl WipType for f32 {
fn type_expr() -> TypeExpr {
TypeExpr::Number
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
let value = f64::from(self);
ensure_finite(value)?;
Ok(Value::Number(value))
}
fn decode(value: Value) -> Result<Self, CodecError> {
let value = f64::decode(value)?;
let narrowed = value as Self;
if narrowed.is_finite() {
Ok(narrowed)
} else {
Err(CodecError::new("number does not fit finite Rust `f32`"))
}
}
}
fn ensure_finite(value: f64) -> Result<(), CodecError> {
if value.is_finite() {
Ok(())
} else {
Err(CodecError::new("protocol numbers must be finite"))
}
}
impl WipType for String {
fn type_expr() -> TypeExpr {
TypeExpr::String
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
Ok(Value::String(self))
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::String(value) => Ok(value),
other => Err(CodecError::expected("string", &other)),
}
}
}
impl WipType for Bytes {
fn type_expr() -> TypeExpr {
TypeExpr::Bytes
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
Ok(Value::Bytes(self.0))
}
fn decode(value: Value) -> Result<Self, CodecError> {
match value {
Value::Bytes(value) => Ok(Self(value)),
other => Err(CodecError::expected("bytes", &other)),
}
}
}
impl WipType for JsonValue {
fn type_expr() -> TypeExpr {
TypeExpr::Json
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
encode_json(self)
}
fn decode(value: Value) -> Result<Self, CodecError> {
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));
}
}
Ok(Value::Record(fields))
}
}
}
fn decode_json(value: Value) -> Result<JsonValue, CodecError> {
match value {
Value::Unit => Ok(JsonValue::Null),
Value::Boolean(value) => Ok(JsonValue::Boolean(value)),
Value::Integer(value) => {
ensure_safe_integer(value)?;
Ok(JsonValue::Integer(value))
}
Value::Number(value) => {
ensure_finite(value)?;
Ok(JsonValue::Number(value))
}
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 {
items: Box::new(T::type_expr()),
}
}
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
T::collect_declarations(declarations);
}
fn encode(self) -> Result<Value, CodecError> {
self.into_iter()
.enumerate()
.map(|(index, value)| value.encode().map_err(|error| error.at(index.to_string())))
.collect::<Result<Vec<_>, _>>()
.map(Value::List)
}
fn decode(value: Value) -> Result<Self, CodecError> {
let Value::List(values) = value else {
return Err(CodecError::expected("list", &value));
};
values
.into_iter()
.enumerate()
.map(|(index, value)| T::decode(value).map_err(|error| error.at(index.to_string())))
.collect()
}
}
impl WipType for Entry {
fn type_expr() -> TypeExpr {
TypeExpr::Entry
}
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
fn encode(self) -> Result<Value, CodecError> {
validate_entry_path(&self.0)?;
Ok(Value::String(self.0))
}
fn decode(value: Value) -> Result<Self, CodecError> {
let Value::String(path) = value else {
return Err(CodecError::expected("entry path string", &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}")))
}
#[doc(hidden)]
pub mod __private {
use std::collections::BTreeMap;
use wip_protocol::{InterfaceDescriptor, TypeDeclaration, ValidationError, Value};
use crate::{CodecError, Documentation, WipType};
pub fn documentation(summary: &str, details: Option<&str>) -> Option<Documentation> {
if summary.is_empty() && details.is_none() {
None
} else {
Some(Documentation {
summary: summary.into(),
details: details.map(str::to_owned),
})
}
}
pub fn register_declaration(
declarations: &mut Vec<TypeDeclaration>,
declaration: TypeDeclaration,
) -> bool {
if declarations.iter().any(|existing| existing == &declaration) {
false
} else {
declarations.push(declaration);
true
}
}
pub fn validate_arguments(
descriptor: &InterfaceDescriptor,
operation: &str,
arguments: &BTreeMap<String, Value>,
) -> Result<(), ValidationError> {
descriptor.validate_arguments(operation, arguments)
}
pub fn decode_type_mismatch(expected: &str, actual: Value) -> CodecError {
CodecError::expected(expected, &actual)
}
pub fn decode_unknown_variant(type_name: &str, variant: String) -> CodecError {
CodecError::new(format!(
"unknown variant `{variant}` for WIP type `{type_name}`"
))
.at(variant)
}
pub struct RecordDecoder {
fields: BTreeMap<String, Value>,
}
impl RecordDecoder {
pub fn new(fields: BTreeMap<String, Value>) -> Self {
Self { fields }
}
pub fn required<T: WipType>(&mut self, name: &str) -> Result<T, CodecError> {
let value = self.take(name).ok_or_else(|| {
CodecError::new(format!("missing required field `{name}`")).at(name)
})?;
T::decode(value).map_err(|error| error.at(name))
}
pub fn optional<T: WipType>(&mut self, name: &str) -> Result<Option<T>, CodecError> {
self.take(name)
.map(T::decode)
.transpose()
.map_err(|error| error.at(name))
}
pub fn finish(self) -> Result<(), CodecError> {
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> {
self.fields.remove(name)
}
}
}