Struct FallibleCommandBuffer

pub struct FallibleCommandBuffer<W, E> { /* private fields */ }
Expand description

A bounded FIFO queue of fallible deferred mutations.

This opt-in sibling leaves CommandBuffer and its normal-return accounting unchanged. IDs are caller-supplied correlation labels, not handles: all u64 values are valid, and duplicate IDs are allowed. Assign distinct IDs when the consumer needs to distinguish individual requests. No deduplication occurs.

Storage grows lazily on accepted pushes and is retained after application or clear. The capacity bounds command count, not payload/error sizes or execution time. Applying does not allocate queue/report storage; closures, error callbacks and destructors remain caller-controlled.

Commands can partially mutate before returning an error. They are removed before invocation and are never automatically retried, even on failure. Dropping the queue drops pending payloads without invoking their commands.

§Deferred inventory requests

Flush at an explicit simulation boundary. A capacity rejection returns the unboxed closure; only that never-executed request is safe to enqueue again without reasoning about partial application.

use ferravex_engine::commands::{
    CommandFailure, CommandFailurePolicy, FallibleCommandBuffer,
};

let mut commands = FallibleCommandBuffer::new(2);
let spend = |stock: &mut u32| {
    *stock = stock.checked_sub(3).ok_or("insufficient stock")?;
    Ok(())
};
assert!(commands.push(10, spend).is_ok());
assert!(commands.push(11, spend).is_ok());
let refill = commands.push(12, |stock| { *stock += 5; Ok(()) }).err().unwrap();
assert!(commands.is_full());
assert_eq!((commands.capacity(), commands.remaining_capacity()), (2, 0));
let mut stock = 4;
let mut failure = None;
let report = commands.apply_report(&mut stock, 2, CommandFailurePolicy::StopOnError,
    |error| failure = Some(error));
assert_eq!((report.started, report.applied, report.failed, report.remaining), (2, 1, 1, 0));
assert_eq!(failure, Some(CommandFailure { id: 11, error: "insufficient stock" }));
assert_eq!(stock, 1);
assert!(commands.is_empty());
assert!(commands.push(12, refill).is_ok());
let report = commands.apply_report(&mut stock, 1, CommandFailurePolicy::Continue,
    |_| panic!("refill cannot fail"));
assert_eq!((report.applied, stock), (1, 6));
assert_eq!(commands.metrics().failed, 1);
assert_eq!(commands.reset_metrics().accepted, 3);
assert_eq!(commands.metrics().started, 0);
assert!(commands.push(13, spend).is_ok());
commands.clear(); // A restart discards stale requests without spending stock.
assert_eq!((commands.len(), commands.metrics().discarded, stock), (0, 1, 6));

Implementations§

§

impl<W, E> FallibleCommandBuffer<W, E>

pub fn new(capacity: usize) -> FallibleCommandBuffer<W, E>

Creates an empty queue. Zero capacity is valid and rejects every push.

pub fn push<F>(&mut self, id: u64, command: F) -> Result<(), F>
where F: FnOnce(&mut W) -> Result<(), E> + 'static,

Queues a command with a caller-supplied ID, or returns it unchanged if full.

Rejection does not box, invoke or drop the closure. A rejected closure can be pushed again when space is available; it then joins the tail. IDs are preserved verbatim, including duplicates, and never affect execution order.

pub fn apply_report( &mut self, world: &mut W, limit: usize, policy: CommandFailurePolicy, on_error: impl FnMut(CommandFailure<E>), ) -> FallibleCommandApplyOutcome

Invokes at most limit oldest commands, reporting every error as it occurs.

Both successful and failed invocations consume budget. A zero limit runs neither commands nor on_error. Errors move to on_error in FIFO order, even under CommandFailurePolicy::StopOnError; the queue retains no error collection. Unexecuted commands stay queued in their original order. Under the stop policy, failed == 1 means this call stopped on an error, including when that error was the last command or used the last budget unit. A later explicit apply resumes with the tail, never the failed command.

§Panics

Command and error-callback panics propagate under either policy. The current command is consumed, mutations remain, and the untouched tail stays queued. started is incremented before invocation; applied or failed is incremented on normal return, before on_error. A command panic does not become an E. The host must assess world validity before resuming.

§A prepared system’s explicit flush

Propagate the original command ID and error through a named flush. The schedule suppresses its downstream consumers when the flush returns Err.

use ferravex_engine::commands::{
    CommandFailure, CommandFailurePolicy, FallibleCommandBuffer,
};
use ferravex_engine::systems::{SystemControl, SystemSchedule};

struct Simulation {
    stock: u32,
    commands: FallibleCommandBuffer<u32, &'static str>,
}
let mut schedule = SystemSchedule::<Simulation, CommandFailure<&'static str>>::default();
schedule.register_flush("inventory-flush", |sim| {
    let mut failure = None;
    let report = sim.commands.apply_report(
        &mut sim.stock, 8, CommandFailurePolicy::StopOnError,
        |error| failure = Some(error));
    if let Some(error) = failure { return Err(error); }
    // A successful but incomplete flush also suppresses dependent consumers.
    Ok(if report.remaining == 0 { SystemControl::Continue } else { SystemControl::Stop })
}).unwrap();
schedule.register("observe", |sim| {
    assert_eq!(sim.stock, 1);
    Ok(SystemControl::Continue)
}).unwrap();
schedule.before_checked("inventory-flush", "observe").unwrap();
schedule.prepare().unwrap();
let mut sim = Simulation { stock: 3, commands: FallibleCommandBuffer::new(1) };
assert!(sim.commands.push(42, |stock| {
    *stock = stock.checked_sub(2).ok_or("insufficient stock")?;
    Ok(())
}).is_ok());
assert_eq!(schedule.run(&mut sim).unwrap().invoked, 2);

pub fn len(&self) -> usize

Number of pending commands.

pub fn is_empty(&self) -> bool

Whether no commands are queued.

pub fn capacity(&self) -> usize

Maximum queued command count, independent of backing storage capacity.

pub fn remaining_capacity(&self) -> usize

Number of additional commands that fit before pushes are rejected.

pub fn is_full(&self) -> bool

Whether pushes will be rejected. True for a zero-capacity queue.

pub fn metrics(&self) -> FallibleCommandBufferMetrics

Copies metrics without consuming commands or inspecting closure payloads.

pub fn reset_metrics(&mut self) -> FallibleCommandBufferMetrics

Returns prior metrics and starts a new observation interval. Pending commands and IDs remain intact; the high-water mark starts at len.

pub fn clear(&mut self)

Drops all pending commands without invoking them, retaining storage/metrics.

Each command is removed and counted before dropping its payload. If a destructor panics, the panic propagates and the untouched tail stays queued. This discards stale work on restart; it does not reset the caller’s world.

Auto Trait Implementations§

§

impl<W, E> Freeze for FallibleCommandBuffer<W, E>

§

impl<W, E> !RefUnwindSafe for FallibleCommandBuffer<W, E>

§

impl<W, E> !Send for FallibleCommandBuffer<W, E>

§

impl<W, E> !Sync for FallibleCommandBuffer<W, E>

§

impl<W, E> Unpin for FallibleCommandBuffer<W, E>

§

impl<W, E> !UnwindSafe for FallibleCommandBuffer<W, E>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.