1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//! 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` command starts the close, cancelling up to `batch_max_events` orders
//! 2. Market transitions to `Closed` and starts a batched cancel process with [`CloseProcessState`]
//! 3. `ContinueCloseMarket` commands process additional batches
//! 4. Final batch emits completion marker
//!
//! ## Cursor Semantics
//!
//! The `cursor_after` field in [`CloseProcessState`] 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 `cancelled_total` allow monitoring
//!
//! ## Event Budget
//!
//! The `batch_max_events` parameter 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. Typical values are 1000-4096.
use crateBookOrder;
use crateOrderId;
// Account for MarketStateChanged + OrderCancelled(events-as-batch) events
pub const MIN_CLOSE_BATCH_EVENTS: u16 = 2;
pub const DEFAULT_CLOSE_BATCH_EVENTS: u16 = 4096;
/// Encode the close batch size into the market-state-change reason so the close process can be
/// initialized deterministically during event application (no command-time mutation).