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