1use std::fmt;
16use std::sync::atomic::{AtomicU64, Ordering};
17
18static FAULTS: AtomicU64 = AtomicU64::new(0);
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum RuntimeError {
24 PoisonedLock(&'static str),
27 Abandoned(&'static str),
36 AlreadyCollected(&'static str),
45 EntropyFailed(crate::entropy::EntropyError),
47 ReservedCapId,
49 CapIdCollision,
51 CannotFinalizeHostFlow,
53 FlowIdExhausted,
55 DuplicateFlowId,
57 LinkIdExhausted,
59 MonitorIdExhausted,
61}
62
63impl fmt::Display for RuntimeError {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match self {
66 RuntimeError::PoisonedLock(where_) => {
67 write!(f, "runtime mutex poisoned at {where_}")
68 }
69 RuntimeError::Abandoned(where_) => {
70 write!(
71 f,
72 "{where_}: flow was destroyed before producing an outcome"
73 )
74 }
75 RuntimeError::AlreadyCollected(where_) => {
76 write!(f, "{where_}: outcome was already collected")
77 }
78 RuntimeError::EntropyFailed(err) => {
79 write!(f, "capability CSPRNG unavailable: {err}")
80 }
81 RuntimeError::ReservedCapId => {
82 write!(f, "capability id draw was the reserved zero")
83 }
84 RuntimeError::CapIdCollision => {
85 write!(f, "could not allocate a unique capability id")
86 }
87 RuntimeError::CannotFinalizeHostFlow => {
88 write!(f, "cannot finalize reserved host flow")
89 }
90 RuntimeError::FlowIdExhausted => {
91 write!(f, "flow id space exhausted (counter wrapped)")
92 }
93 RuntimeError::DuplicateFlowId => {
94 write!(f, "directory already has this flow id")
95 }
96 RuntimeError::LinkIdExhausted => {
97 write!(f, "link id space exhausted (counter wrapped)")
98 }
99 RuntimeError::MonitorIdExhausted => {
100 write!(f, "monitor id space exhausted (counter wrapped)")
101 }
102 }
103 }
104}
105
106impl std::error::Error for RuntimeError {
107 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
108 match self {
109 RuntimeError::EntropyFailed(err) => Some(err),
110 _ => None,
111 }
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq)]
121pub enum LifecycleError {
122 NoSuchFlow(super::process::FlowId),
123 InvalidCapability,
124 InvalidMonitor,
125 InvalidLink,
126 NotOwner,
127 AlreadyRegistered,
128 AlreadyLinked,
129 EmptyName,
130 SelfRelation,
131 Unavailable,
132 LinkLimitReached {
134 limit: u32,
135 },
136 MonitorLimitReached {
138 limit: u32,
139 },
140 RegistryLimitReached {
142 limit: u32,
143 },
144}
145
146impl fmt::Display for LifecycleError {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 match self {
149 Self::NoSuchFlow(id) => write!(f, "no live flow {id}"),
150 Self::InvalidCapability => write!(f, "unknown or revoked capability"),
151 Self::InvalidMonitor => write!(f, "unknown monitor"),
152 Self::InvalidLink => write!(f, "unknown link"),
153 Self::NotOwner => write!(f, "caller does not own this relation"),
154 Self::AlreadyRegistered => write!(f, "registry name already taken"),
155 Self::AlreadyLinked => write!(f, "flows are already linked"),
156 Self::EmptyName => write!(f, "registry name must be non-empty"),
157 Self::SelfRelation => write!(f, "cannot link or monitor a flow to itself"),
158 Self::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
159 Self::LinkLimitReached { limit } => {
160 write!(f, "link limit reached ({limit})")
161 }
162 Self::MonitorLimitReached { limit } => {
163 write!(f, "monitor limit reached ({limit})")
164 }
165 Self::RegistryLimitReached { limit } => {
166 write!(f, "registry name limit reached ({limit})")
167 }
168 }
169 }
170}
171
172impl std::error::Error for LifecycleError {}
173
174#[cold]
176pub fn report_fault(err: RuntimeError) {
177 FAULTS.fetch_add(1, Ordering::Relaxed);
178 eprintln!("byteflow: {err} — fail-closed");
179}
180
181pub fn fault_count() -> u64 {
183 FAULTS.load(Ordering::Relaxed)
184}
185
186#[derive(Debug, Clone, PartialEq, Eq)]
193pub enum SpawnError {
194 BadFunction {
196 index: u32,
197 table_size: u32,
198 },
199 VerifyFailed(crate::bytecode::VerifyError),
201 InvalidCapability,
203 Unavailable,
205 FlowIdExhausted,
207 RequestIdsExhausted,
209 FlowLimit {
211 current: usize,
212 max: u32,
213 },
214 SpawnDenied(String),
216 SpawnRateExceeded,
217 ParentCapRevoked,
218 MissingSpawnRight,
219 NameTaken {
221 name: String,
222 },
223 ThreadSpawnFailed(String),
225 Attestation(crate::AttestError),
227 VmInit(String),
230}
231
232impl fmt::Display for SpawnError {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 match self {
235 SpawnError::BadFunction { index, table_size } => {
236 write!(
237 f,
238 "spawn: function index {index} out of range (table size {table_size})"
239 )
240 }
241 SpawnError::VerifyFailed(err) => write!(f, "chunk verification failed: {err}"),
242 SpawnError::InvalidCapability => {
243 write!(f, "spawn: argument capability is unknown or not held")
244 }
245 SpawnError::Unavailable => write!(f, "spawn: runtime table unavailable"),
246 SpawnError::FlowIdExhausted => {
247 write!(f, "spawn: flow id space exhausted (counter wrapped)")
248 }
249 SpawnError::RequestIdsExhausted => {
250 write!(f, "spawn: host request ids exhausted")
251 }
252 SpawnError::FlowLimit { current, max } => {
253 write!(f, "spawn: live flow limit reached ({current}/{max})")
254 }
255 SpawnError::SpawnDenied(msg) => write!(f, "spawn: {msg}"),
256 SpawnError::SpawnRateExceeded => write!(f, "spawn: spawn rate exceeded"),
257 SpawnError::ParentCapRevoked => write!(f, "spawn: parent capability revoked"),
258 SpawnError::MissingSpawnRight => write!(f, "spawn: parent lacks SPAWN right"),
259 SpawnError::NameTaken { name } => {
260 write!(f, "spawn: registry name {name:?} already taken")
261 }
262 SpawnError::ThreadSpawnFailed(msg) => {
263 write!(f, "failed to spawn runtime thread: {msg}")
264 }
265 SpawnError::Attestation(err) => write!(f, "attestation failed: {err}"),
266 SpawnError::VmInit(msg) => write!(f, "vm init failed: {msg}"),
267 }
268 }
269}
270
271impl std::error::Error for SpawnError {}
272
273impl From<crate::vm::Fault> for SpawnError {
274 fn from(fault: crate::vm::Fault) -> Self {
275 match fault {
276 crate::vm::Fault::BadFunction { index, table_size } => {
277 SpawnError::BadFunction { index, table_size }
278 }
279 other => SpawnError::VmInit(other.to_string()),
280 }
281 }
282}