betex 0.35.0

Betfair / Prediction Market Exchange
Documentation
//! Shared helpers for the market close process.
//!
//! ## Close Process Overview
//!
//! When a market closes, all resting orders must be cancelled. To avoid
//! emitting unbounded events in a single transaction, the close process
//! uses **batched cancellation**:
//!
//! 1. `CloseMarket { reason }` starts the close, cancelling up to the configured batch budget
//! 2. Market transitions to `Closed` and starts a batched cancel process with
//!    [`BatchProcessState`](crate::book::common::types::BatchProcessState)
//! 3. `ContinueBatchProcess` commands process additional batches
//! 4. Final batch emits completion marker
//!
//! ## Cursor Semantics
//!
//! The `cursor_after` field in
//! [`BatchProcessState`](crate::book::common::types::BatchProcessState) and
//! [`BookEvent::OrderCancelled`]
//! tracks pagination through the order set:
//!
//! - `None` on the first batch (start from beginning)
//! - `Some(order_id)` indicates the last processed order
//! - Subsequent batches resume from orders greater than the cursor
//!
//! This cursor-based pagination ensures **idempotent recovery**: replaying
//! events that have already been applied is safe because the cursor prevents
//! re-processing orders.
//!
//! ## Recovery Guarantees
//!
//! The close process is designed for crash recovery:
//!
//! - **No double cancellation**: Orders before the cursor are skipped on replay
//! - **Deterministic ordering**: Orders are processed in BTreeMap order (by OrderId)
//! - **Progress tracking**: `chunks_done` and `processed_total` allow monitoring
//!
//! ## Event Budget
//!
//! The configured close batch budget controls how many order cancellations can
//! occur per batch. The minimum is [`MIN_CLOSE_BATCH_EVENTS`] (2) to ensure
//! at least the state-change event fits, and the maximum is
//! [`MAX_CLOSE_BATCH_EVENTS`] to keep individual batch payloads within a
//! practical operational bound. Typical values are 25-4096.

use crate::book::common::types::BookOrder;
use crate::types::OrderId;

// Account for MarketStateChanged + OrderCancelled(events-as-batch) events
pub const MIN_CLOSE_BATCH_EVENTS: u16 = 2;
pub const DEFAULT_CLOSE_BATCH_EVENTS: u16 = crate::config::DEFAULT_CLOSE_BATCH_MAX_EVENTS;
pub const MAX_CLOSE_BATCH_EVENTS: u16 = 4096;

pub const fn default_close_batch_events() -> u16 {
    DEFAULT_CLOSE_BATCH_EVENTS
}

#[inline]
pub(crate) fn set_close_batch_max_events(target: &mut u16, batch_max_events: u16) {
    *target = normalize_close_batch_events(batch_max_events);
}

#[inline]
pub fn is_valid_close_batch_events(batch_max_events: u16) -> bool {
    (MIN_CLOSE_BATCH_EVENTS..=MAX_CLOSE_BATCH_EVENTS).contains(&batch_max_events)
}

#[inline]
pub fn normalize_close_batch_events(batch_max_events: u16) -> u16 {
    batch_max_events.clamp(MIN_CLOSE_BATCH_EVENTS, MAX_CLOSE_BATCH_EVENTS)
}

#[inline]
pub fn is_live_order(o: &BookOrder) -> bool {
    matches!(
        o.info.state,
        crate::book::common::types::BookOrderState::ExecutableUnmatched
            | crate::book::common::types::BookOrderState::ExecutablePartiallyMatched
    )
}

pub fn count_live_orders<'a>(orders: impl Iterator<Item = (OrderId, &'a BookOrder)>) -> u64 {
    orders.filter(|(_, o)| is_live_order(o)).count() as u64
}