Skip to main content

bornera_core/connection/
core.rs

1//! Aggregate deterministic ownership of policy and complete outbound frames.
2
3use core::{cell::Cell, num::NonZeroUsize};
4
5use calandria::{Moment, RetainedBytes};
6
7use crate::{
8    ConnectionCoreInvariant, ConnectionEpoch, ConnectionId, ConnectionLimits, ConnectionMachine,
9    ConnectionSnapshot, ConnectionTransition, EffectId, EndpointId, FrameCommitError,
10    FrameCommitFailure, FrameMeasure, IdentitySeeds, LaneId, OperationId, OperationOptions,
11    OperationPermit, OrderedVerified, ReserveError, WriteFrame, WriteSlice,
12};
13
14use super::journal::RecoveryJournal;
15use crate::write::WriteQueue;
16
17/// Sole deterministic mutation owner for one exact connection epoch.
18#[derive(Debug)]
19pub struct ConnectionCore<F> {
20    pub(super) machine: ConnectionMachine,
21    pub(super) writes: WriteQueue<F>,
22    pub(super) journal: RecoveryJournal<F>,
23    pub(super) poisoned: Cell<Option<ConnectionCoreInvariant>>,
24}
25
26impl<F: WriteFrame> ConnectionCore<F> {
27    /// Creates a live fixed-epoch owner with session-only admission.
28    pub fn new(
29        endpoint: EndpointId,
30        lane: LaneId,
31        connection: ConnectionId,
32        epoch: ConnectionEpoch,
33        limits: ConnectionLimits,
34    ) -> Self {
35        Self {
36            machine: ConnectionMachine::new(endpoint, lane, connection, epoch, limits),
37            writes: WriteQueue::new(epoch, limits.write_queue_limits()),
38            journal: RecoveryJournal::new(limits.max_operations(), limits.max_write_frames()),
39            poisoned: Cell::new(None),
40        }
41    }
42
43    /// Creates a fixed epoch with deterministic identity seeds.
44    pub fn with_identity_seeds(
45        endpoint: EndpointId,
46        lane: LaneId,
47        connection: ConnectionId,
48        epoch: ConnectionEpoch,
49        limits: ConnectionLimits,
50        seeds: IdentitySeeds,
51    ) -> Self {
52        Self {
53            machine: ConnectionMachine::with_identity_seeds(
54                endpoint, lane, connection, epoch, limits, seeds,
55            ),
56            writes: WriteQueue::new(epoch, limits.write_queue_limits()),
57            journal: RecoveryJournal::new(limits.max_operations(), limits.max_write_frames()),
58            poisoned: Cell::new(None),
59        }
60    }
61
62    /// Atomically reserves all operation resources before frame preparation.
63    pub fn reserve(
64        &mut self,
65        now: Moment,
66        options: OperationOptions,
67    ) -> Result<OperationPermit, ReserveError> {
68        if self
69            .ensure_healthy()
70            .and_then(|()| self.verify_ownership_on_hot_path())
71            .is_err()
72        {
73            return Err(ReserveError::OwnerPoisoned);
74        }
75        self.machine.reserve(now, options)
76    }
77
78    /// Atomically transfers an affine permit and exact complete frame.
79    pub fn commit(
80        &mut self,
81        permit: OperationPermit,
82        frame: F,
83    ) -> Result<(OperationId, ConnectionTransition), FrameCommitError<F>> {
84        if self
85            .ensure_healthy()
86            .and_then(|()| self.verify_ownership_on_hot_path())
87            .is_err()
88        {
89            return Err(FrameCommitError::new(
90                FrameCommitFailure::Policy(crate::CommitErrorKind::OwnerPoisoned),
91                permit,
92                frame,
93            ));
94        }
95        let measure = FrameMeasure::capture(&frame);
96        if let Some(kind) = self
97            .machine
98            .commit_failure(&permit, measure.retained_bytes())
99        {
100            return Err(FrameCommitError::new(
101                FrameCommitFailure::Policy(kind),
102                permit,
103                frame,
104            ));
105        }
106        if let Err(error) = self.writes.admit(
107            permit.epoch,
108            permit.operation,
109            permit.effect,
110            measure,
111            frame,
112        ) {
113            return Err(FrameCommitError::new(
114                FrameCommitFailure::Writer(error.failure()),
115                permit,
116                error.into_frame(),
117            ));
118        }
119        Ok(self.machine.commit_permit(permit, measure.retained_bytes()))
120    }
121
122    /// Borrows at most `maximum` bytes from the exact FIFO write front.
123    pub fn front_write(
124        &self,
125        maximum: NonZeroUsize,
126    ) -> Result<Option<WriteSlice<'_>>, crate::ConnectionCoreError> {
127        if let Some(invariant) = self.poisoned.get() {
128            return Err(crate::ConnectionCoreError::Poisoned(invariant));
129        }
130        if self.machine.ledger.borrow().poisoned() {
131            let invariant = ConnectionCoreInvariant::ReservationAccounting;
132            self.poisoned.set(Some(invariant));
133            return Err(crate::ConnectionCoreError::Invariant(invariant));
134        }
135        self.writes.front(maximum).map_err(|violation| {
136            let invariant = ConnectionCoreInvariant::FrameContractViolation(violation);
137            if self.poisoned.get().is_none() {
138                self.poisoned.set(Some(invariant));
139            }
140            crate::ConnectionCoreError::Invariant(invariant)
141        })
142    }
143
144    /// Returns the exact epoch permanently owned by this aggregate.
145    pub const fn epoch(&self) -> ConnectionEpoch {
146        self.machine.epoch()
147    }
148
149    /// Returns current deterministic policy state.
150    pub fn snapshot(&self) -> ConnectionSnapshot {
151        self.machine.snapshot()
152    }
153
154    /// Returns immutable ordered-matching state.
155    pub const fn matching(&self) -> &OrderedVerified {
156        self.machine.matching()
157    }
158
159    /// Returns read-only access to the underlying policy state for diagnostics.
160    pub const fn policy(&self) -> &ConnectionMachine {
161        &self.machine
162    }
163
164    /// Returns complete frames still awaiting transport completion.
165    pub fn queued_write_frames(&self) -> usize {
166        self.writes.queued_frames()
167    }
168
169    /// Returns whether the FIFO front can complete without transport progress.
170    pub fn front_write_is_empty(&self) -> bool {
171        self.writes.front_is_empty()
172    }
173
174    /// Returns the internal write identity retained for an accepted operation.
175    pub fn write_effect(&self, operation: OperationId) -> Option<EffectId> {
176        self.writes.effect_for(operation)
177    }
178
179    /// Returns bytes retained by complete outbound frames.
180    pub const fn buffered_write_retained_bytes(&self) -> RetainedBytes {
181        self.writes.retained_bytes()
182    }
183}