feat: model operation outcome guarantees
This commit is contained in:
@@ -46,8 +46,10 @@
|
||||
//! `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
|
||||
//! an application return enum/union and is returned as `Ok(value)`.
|
||||
//! [`HostError`] is reserved for host/runtime failure, so the required
|
||||
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
||||
//! [`HostError`] is reserved for host/runtime failure and requires an explicit
|
||||
//! [`HostErrorKind`] plus [`EffectGuarantee`]. The required [`OperationResult`]
|
||||
//! convention therefore keeps domain failures separate from runtime failures and
|
||||
//! makes outcome uncertainty visible to Host dispatch.
|
||||
//!
|
||||
//! # Migration to canonical values
|
||||
//!
|
||||
@@ -139,29 +141,107 @@ pub trait InterfaceImplementation<T>: InterfaceDefinition {
|
||||
/// `Err(HostError)` means the host or runtime could not perform the operation.
|
||||
pub type OperationResult<T> = Result<T, HostError>;
|
||||
|
||||
/// A host/runtime failure, kept separate from the operation's application
|
||||
/// Whether an operation failure proves that no effects were committed.
|
||||
///
|
||||
/// This guarantee is consumed by Host dispatch when choosing a protocol failure:
|
||||
/// only [`NotCommitted`](Self::NotCommitted) failures may become `Internal` or
|
||||
/// `ResourceLimitExceeded`; [`Unknown`](Self::Unknown) failures must become
|
||||
/// `OperationOutcomeUnknown`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EffectGuarantee {
|
||||
/// The operation was not invoked, or every effect was rolled back.
|
||||
NotCommitted,
|
||||
/// The operation may have committed effects.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Host/runtime failure category used when effects are known not to be committed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HostErrorKind {
|
||||
/// The Host or backend encountered an internal failure.
|
||||
Internal,
|
||||
/// A cancellation, deadline, or bounded resource limit was exceeded.
|
||||
ResourceLimitExceeded,
|
||||
}
|
||||
|
||||
/// A typed host/runtime failure, kept separate from the operation's application
|
||||
/// return type.
|
||||
///
|
||||
/// The effect guarantee is mandatory. Host runtimes must ignore the diagnostic
|
||||
/// when producing a wire response; it is bounded here for local observability but
|
||||
/// can still contain backend-private information.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HostError {
|
||||
kind: HostErrorKind,
|
||||
effect_guarantee: EffectGuarantee,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl HostError {
|
||||
/// Creates a host failure with a human-readable diagnostic.
|
||||
/// Creates an internal Host failure with an explicit effect guarantee.
|
||||
#[must_use]
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
pub fn internal(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
|
||||
Self::new(HostErrorKind::Internal, effect_guarantee, message)
|
||||
}
|
||||
|
||||
/// Creates a resource-limit Host failure with an explicit effect guarantee.
|
||||
#[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 {
|
||||
message: message.into(),
|
||||
kind,
|
||||
effect_guarantee,
|
||||
message: bounded_diagnostic(message.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the diagnostic message.
|
||||
/// Returns the typed Host failure category.
|
||||
#[must_use]
|
||||
pub fn kind(&self) -> HostErrorKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
/// Returns the operation-effect guarantee attached by the implementation.
|
||||
#[must_use]
|
||||
pub fn effect_guarantee(&self) -> EffectGuarantee {
|
||||
self.effect_guarantee
|
||||
}
|
||||
|
||||
/// Returns the bounded local diagnostic message.
|
||||
///
|
||||
/// Host runtimes must not place this value in protocol responses because it
|
||||
/// can contain backend paths, credentials, or other private details.
|
||||
#[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)
|
||||
@@ -241,12 +321,59 @@ pub enum DispatchError {
|
||||
Decode(CodecError),
|
||||
/// The implementation reported a host/runtime failure.
|
||||
Host(HostError),
|
||||
/// The implementation panicked after invocation began.
|
||||
///
|
||||
/// Panic payloads are deliberately discarded because they can contain
|
||||
/// backend-private diagnostics.
|
||||
Panic,
|
||||
/// The Rust result could not be encoded.
|
||||
Encode(CodecError),
|
||||
/// The encoded result did not match the generated declaration.
|
||||
InvalidResult(wip_protocol::ValidationError),
|
||||
}
|
||||
|
||||
/// Whether generated dispatch failed before or after typed implementation
|
||||
/// invocation began.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DispatchPhase {
|
||||
/// Typed implementation code was not invoked.
|
||||
BeforeInvocation,
|
||||
/// Typed implementation invocation began, so effects require an explicit
|
||||
/// non-commit or rollback guarantee.
|
||||
AfterInvocation,
|
||||
}
|
||||
|
||||
impl DispatchError {
|
||||
/// Returns the execution phase in which this dispatch failure occurred.
|
||||
#[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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a post-invocation effect guarantee when the implementation
|
||||
/// supplied one.
|
||||
///
|
||||
/// Panic, encode, and result-validation failures default to `Unknown` until
|
||||
/// a provider confirms rollback. Pre-invocation failures return `None`.
|
||||
#[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 {
|
||||
@@ -256,6 +383,7 @@ impl Display for DispatchError {
|
||||
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}"),
|
||||
}
|
||||
@@ -265,7 +393,7 @@ impl Display for DispatchError {
|
||||
impl Error for DispatchError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::UnknownOperation(_) => None,
|
||||
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),
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_interface::wip_protocol::{INTERFACE_FORMAT_V1, TypeExpr, Value};
|
||||
use wip_interface::{DispatchError, HostError, OperationResult, WipType, interface};
|
||||
use wip_interface::{
|
||||
DispatchError, DispatchPhase, EffectGuarantee, HostError, HostErrorKind, OperationResult,
|
||||
WipType, interface,
|
||||
};
|
||||
|
||||
/// Publication request.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
@@ -66,7 +69,10 @@ impl Catalog for AcceptingCatalog {
|
||||
}
|
||||
|
||||
fn host_value(&self) -> OperationResult<String> {
|
||||
Err(HostError::new("backend unavailable"))
|
||||
Err(HostError::internal(
|
||||
"backend unavailable",
|
||||
EffectGuarantee::Unknown,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +96,26 @@ impl Catalog for RejectingCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
struct PanickingCatalog;
|
||||
|
||||
impl Catalog for PanickingCatalog {
|
||||
fn publish(
|
||||
&self,
|
||||
_request: PublishRequest,
|
||||
_note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
|
||||
fn ping(&self) -> OperationResult<()> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
|
||||
fn host_value(&self) -> OperationResult<String> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_arguments(with_note: bool) -> BTreeMap<String, Value> {
|
||||
let mut arguments = BTreeMap::from([(
|
||||
"request".into(),
|
||||
@@ -203,16 +229,41 @@ fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
|
||||
let invalid =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(invalid, DispatchError::InvalidArguments(_)));
|
||||
assert_eq!(invalid.phase(), DispatchPhase::BeforeInvocation);
|
||||
assert_eq!(invalid.effect_guarantee(), None);
|
||||
|
||||
let host =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(host, DispatchError::Host(error) if error.message() == "backend unavailable"));
|
||||
assert!(
|
||||
matches!(&host, DispatchError::Host(error) if error.message() == "backend unavailable")
|
||||
);
|
||||
assert_eq!(host.phase(), DispatchPhase::AfterInvocation);
|
||||
assert_eq!(host.effect_guarantee(), Some(EffectGuarantee::Unknown));
|
||||
|
||||
let panic =
|
||||
CatalogDefinition::dispatch(&PanickingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(panic, DispatchError::Panic));
|
||||
assert_eq!(panic.phase(), DispatchPhase::AfterInvocation);
|
||||
assert_eq!(panic.effect_guarantee(), Some(EffectGuarantee::Unknown));
|
||||
assert!(!panic.to_string().contains("private panic payload"));
|
||||
|
||||
let unknown =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "missing", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(unknown, DispatchError::UnknownOperation(name) if name == "missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_errors_require_a_typed_kind_and_effect_guarantee() {
|
||||
let internal = HostError::internal("x".repeat(4_096), EffectGuarantee::NotCommitted);
|
||||
assert_eq!(internal.kind(), HostErrorKind::Internal);
|
||||
assert_eq!(internal.effect_guarantee(), EffectGuarantee::NotCommitted);
|
||||
assert!(internal.message().len() <= 512);
|
||||
|
||||
let resource = HostError::resource_limit("deadline", EffectGuarantee::Unknown);
|
||||
assert_eq!(resource.kind(), HostErrorKind::ResourceLimitExceeded);
|
||||
assert_eq!(resource.effect_guarantee(), EffectGuarantee::Unknown);
|
||||
}
|
||||
|
||||
/// Operations whose distinct source names normalize to the same PascalCase.
|
||||
#[interface]
|
||||
pub trait DistinctOperations {
|
||||
|
||||
Reference in New Issue
Block a user