Skip to main content

tembra_core/
error.rs

1use std::fmt;
2
3/// Machine-readable failure categories shared by language adapters.
4#[derive(Clone, Copy, Debug, Eq, PartialEq)]
5pub enum Code {
6    Invalid,
7    Unavailable,
8    Released,
9    Gone,
10    Expired,
11    Cancelled,
12    Forbidden,
13    Conflict,
14    Unsupported,
15    Closed,
16    Exhausted,
17}
18
19impl Code {
20    /// Parses a known wire category without accepting an unknown category.
21    pub fn parse(value: &str) -> Option<Self> {
22        match value {
23            "invalid" => Some(Self::Invalid),
24            "unavailable" => Some(Self::Unavailable),
25            "released" => Some(Self::Released),
26            "gone" => Some(Self::Gone),
27            "expired" => Some(Self::Expired),
28            "cancelled" => Some(Self::Cancelled),
29            "forbidden" => Some(Self::Forbidden),
30            "conflict" => Some(Self::Conflict),
31            "unsupported" => Some(Self::Unsupported),
32            "closed" => Some(Self::Closed),
33            "exhausted" => Some(Self::Exhausted),
34            _ => None,
35        }
36    }
37
38    /// Return the stable wire name of this error field.
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::Invalid => "invalid",
42            Self::Unavailable => "unavailable",
43            Self::Released => "released",
44            Self::Gone => "gone",
45            Self::Expired => "expired",
46            Self::Cancelled => "cancelled",
47            Self::Forbidden => "forbidden",
48            Self::Conflict => "conflict",
49            Self::Unsupported => "unsupported",
50            Self::Closed => "closed",
51            Self::Exhausted => "exhausted",
52        }
53    }
54}
55
56/// Built-in failure reasons. Orbs may still supply their own reason strings at an adapter seam.
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub enum Reason {
59    ActivationBusy,
60    Address,
61    AlreadyCommitted,
62    AmbiguousScope,
63    ApiVersion,
64    Arguments,
65    Bigint,
66    ByteResult,
67    Call,
68    CleanupBusy,
69    Clock,
70    Context,
71    Deadline,
72    Dependency,
73    DependencyCycle,
74    DependencyService,
75    Disposing,
76    Driver,
77    Duplicate,
78    DuplicateContribution,
79    DuplicateService,
80    EffectResults,
81    EffectsRunning,
82    ExclusiveDependent,
83    Executor,
84    Orb,
85    OrbInstalled,
86    GateBusy,
87    GateOrb,
88    GateObject,
89    Hook,
90    HookDependency,
91    Hooks,
92    Host,
93    HostAddress,
94    HostResourceReload,
95    Identities,
96    Invocation,
97    Javascript,
98    Lifetime,
99    Linger,
100    LiveConsumer,
101    LiveReference,
102    LocalValue,
103    Memory,
104    Metadata,
105    MetadataSize,
106    Method,
107    MigrationGate,
108    MigrationRequired,
109    MigrationValue,
110    MissingHook,
111    MissingMethod,
112    NativeEffect,
113    NativeMethod,
114    NativeObject,
115    NativeService,
116    NotReady,
117    Object,
118    ObjectState,
119    ObservationSource,
120    ObservationAdmitted,
121    Operation,
122    OperationOwner,
123    Owner,
124    Payload,
125    Priority,
126    Program,
127    ProgramPhase,
128    ProgramRunning,
129    Reference,
130    ReloadAborted,
131    ReloadDeadline,
132    ReloadPreparing,
133    ReloadRunning,
134    ReloadTicket,
135    Requires,
136    Resource,
137    ResourceDependencies,
138    ResourceDependency,
139    ResourceHost,
140    ResourceState,
141    ResourceVersion,
142    Result,
143    RetainedVersions,
144    RevisionExhausted,
145    Root,
146    RustType,
147    Scope,
148    ScopeClosed,
149    ScopeOrb,
150    ScopeOwner,
151    ScopeResource,
152    Serialization,
153    Service,
154    State,
155    StateInitialized,
156    StateOwner,
157    StateRevision,
158    StateVersion,
159    Subscription,
160    SubscriptionBusy,
161    SubscriptionIdle,
162    SubscriptionQueue,
163    Superseded,
164    Task,
165    Telemetry,
166    UnknownService,
167    UpgradeConflict,
168    Value,
169}
170
171impl Reason {
172    /// Return the stable wire name of this error field.
173    pub const fn as_str(self) -> &'static str {
174        match self {
175            Self::ActivationBusy => "activation_busy",
176            Self::Address => "address",
177            Self::AlreadyCommitted => "already_committed",
178            Self::AmbiguousScope => "ambiguous_scope",
179            Self::ApiVersion => "api_version",
180            Self::Arguments => "arguments",
181            Self::Bigint => "bigint",
182            Self::ByteResult => "byte_result",
183            Self::Call => "call",
184            Self::CleanupBusy => "cleanup_busy",
185            Self::Clock => "clock",
186            Self::Context => "context",
187            Self::Deadline => "deadline",
188            Self::Dependency => "dependency",
189            Self::DependencyCycle => "dependency_cycle",
190            Self::DependencyService => "dependency_service",
191            Self::Disposing => "disposing",
192            Self::Driver => "driver",
193            Self::Duplicate => "duplicate",
194            Self::DuplicateContribution => "duplicate_contribution",
195            Self::DuplicateService => "duplicate_service",
196            Self::EffectResults => "effect_results",
197            Self::EffectsRunning => "effects_running",
198            Self::ExclusiveDependent => "exclusive_dependent",
199            Self::Executor => "executor",
200            Self::Orb => "orb",
201            Self::OrbInstalled => "orb_installed",
202            Self::GateBusy => "gate_busy",
203            Self::GateOrb => "gate_orb",
204            Self::GateObject => "gate_object",
205            Self::Hook => "hook",
206            Self::HookDependency => "hook_dependency",
207            Self::Hooks => "hooks",
208            Self::Host => "host",
209            Self::HostAddress => "host_address",
210            Self::HostResourceReload => "host_resource_reload",
211            Self::Identities => "identities",
212            Self::Invocation => "invocation",
213            Self::Javascript => "javascript",
214            Self::Lifetime => "lifetime",
215            Self::Linger => "linger",
216            Self::LiveConsumer => "live_consumer",
217            Self::LiveReference => "live_reference",
218            Self::LocalValue => "local_value",
219            Self::Memory => "memory",
220            Self::Metadata => "metadata",
221            Self::MetadataSize => "metadata_size",
222            Self::Method => "method",
223            Self::MigrationGate => "migration_gate",
224            Self::MigrationRequired => "migration_required",
225            Self::MigrationValue => "migration_value",
226            Self::MissingHook => "missing_hook",
227            Self::MissingMethod => "missing_method",
228            Self::NativeEffect => "native_effect",
229            Self::NativeMethod => "native_method",
230            Self::NativeObject => "native_object",
231            Self::NativeService => "native_service",
232            Self::NotReady => "not_ready",
233            Self::Object => "object",
234            Self::ObjectState => "object_state",
235            Self::ObservationSource => "observation_source",
236            Self::ObservationAdmitted => "observation_admitted",
237            Self::Operation => "operation",
238            Self::OperationOwner => "operation_owner",
239            Self::Owner => "owner",
240            Self::Payload => "payload",
241            Self::Priority => "priority",
242            Self::Program => "program",
243            Self::ProgramPhase => "program_phase",
244            Self::ProgramRunning => "program_running",
245            Self::Reference => "reference",
246            Self::ReloadAborted => "reload_aborted",
247            Self::ReloadDeadline => "reload_deadline",
248            Self::ReloadPreparing => "reload_preparing",
249            Self::ReloadRunning => "reload_running",
250            Self::ReloadTicket => "reload_ticket",
251            Self::Requires => "requires",
252            Self::Resource => "resource",
253            Self::ResourceDependencies => "resource_dependencies",
254            Self::ResourceDependency => "resource_dependency",
255            Self::ResourceHost => "resource_host",
256            Self::ResourceState => "resource_state",
257            Self::ResourceVersion => "resource_version",
258            Self::Result => "result",
259            Self::RetainedVersions => "retained_versions",
260            Self::RevisionExhausted => "revision_exhausted",
261            Self::Root => "root",
262            Self::RustType => "rust_type",
263            Self::Scope => "scope",
264            Self::ScopeClosed => "scope_closed",
265            Self::ScopeOrb => "scope_orb",
266            Self::ScopeOwner => "scope_owner",
267            Self::ScopeResource => "scope_resource",
268            Self::Serialization => "serialization",
269            Self::Service => "service",
270            Self::State => "state",
271            Self::StateInitialized => "state_initialized",
272            Self::StateOwner => "state_owner",
273            Self::StateRevision => "state_revision",
274            Self::StateVersion => "state_version",
275            Self::Subscription => "subscription",
276            Self::SubscriptionBusy => "subscription_busy",
277            Self::SubscriptionIdle => "subscription_idle",
278            Self::SubscriptionQueue => "subscription_queue",
279            Self::Superseded => "superseded",
280            Self::Task => "task",
281            Self::Telemetry => "telemetry",
282            Self::UnknownService => "unknown_service",
283            Self::UpgradeConflict => "upgrade_conflict",
284            Self::Value => "value",
285        }
286    }
287}
288
289impl From<Reason> for String {
290    /// Preserve a reason as an owned wire string.
291    fn from(reason: Reason) -> Self {
292        reason.as_str().into()
293    }
294}
295
296impl std::fmt::Display for Reason {
297    /// Write the error field in its stable textual form.
298    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299        f.write_str(self.as_str())
300    }
301}
302
303/// An operation failure. External effects performed by an adapter are not rolled back.
304#[derive(Clone, Debug, Eq, PartialEq)]
305pub struct Error {
306    pub code: Code,
307    pub reason: String,
308    pub message: String,
309}
310
311impl Error {
312    /// Create a structured error with an explicit code and reason.
313    pub fn new(code: Code, reason: impl Into<String>, message: impl Into<String>) -> Self {
314        Self {
315            code,
316            reason: reason.into(),
317            message: message.into(),
318        }
319    }
320
321    /// Create an invalid-input error with a specific reason.
322    pub fn invalid(reason: impl Into<String>, message: impl Into<String>) -> Self {
323        Self::new(Code::Invalid, reason, message)
324    }
325}
326
327impl fmt::Display for Error {
328    /// Format the error category, reason and message for diagnostics.
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        write!(
331            f,
332            "{}/{}: {}",
333            self.code.as_str(),
334            self.reason,
335            self.message
336        )
337    }
338}
339
340impl std::error::Error for Error {}
341pub type Result<T> = std::result::Result<T, Error>;