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