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 FlowLimit {
209 current: usize,
210 max: u32,
211 },
212 SpawnDenied(String),
214 SpawnRateExceeded,
215 ParentCapRevoked,
216 MissingSpawnRight,
217 NameTaken {
219 name: String,
220 },
221 ThreadSpawnFailed(String),
223 Attestation(crate::AttestError),
225 VmInit(String),
228}
229
230impl fmt::Display for SpawnError {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 match self {
233 SpawnError::BadFunction { index, table_size } => {
234 write!(
235 f,
236 "spawn: function index {index} out of range (table size {table_size})"
237 )
238 }
239 SpawnError::VerifyFailed(err) => write!(f, "chunk verification failed: {err}"),
240 SpawnError::InvalidCapability => {
241 write!(f, "spawn: argument capability is unknown or not held")
242 }
243 SpawnError::Unavailable => write!(f, "spawn: runtime table unavailable"),
244 SpawnError::FlowIdExhausted => {
245 write!(f, "spawn: flow id space exhausted (counter wrapped)")
246 }
247 SpawnError::FlowLimit { current, max } => {
248 write!(f, "spawn: live flow limit reached ({current}/{max})")
249 }
250 SpawnError::SpawnDenied(msg) => write!(f, "spawn: {msg}"),
251 SpawnError::SpawnRateExceeded => write!(f, "spawn: spawn rate exceeded"),
252 SpawnError::ParentCapRevoked => write!(f, "spawn: parent capability revoked"),
253 SpawnError::MissingSpawnRight => write!(f, "spawn: parent lacks SPAWN right"),
254 SpawnError::NameTaken { name } => {
255 write!(f, "spawn: registry name {name:?} already taken")
256 }
257 SpawnError::ThreadSpawnFailed(msg) => {
258 write!(f, "failed to spawn runtime thread: {msg}")
259 }
260 SpawnError::Attestation(err) => write!(f, "attestation failed: {err}"),
261 SpawnError::VmInit(msg) => write!(f, "vm init failed: {msg}"),
262 }
263 }
264}
265
266impl std::error::Error for SpawnError {}
267
268impl From<crate::vm::Fault> for SpawnError {
269 fn from(fault: crate::vm::Fault) -> Self {
270 match fault {
271 crate::vm::Fault::BadFunction { index, table_size } => {
272 SpawnError::BadFunction { index, table_size }
273 }
274 other => SpawnError::VmInit(other.to_string()),
275 }
276 }
277}