Skip to main content

bornera_core/connection/
progress.rs

1//! Aggregate application of inputs, replies, and exact write progress.
2
3use crate::write::{WriteBoundary, WriteProgress};
4use crate::{
5    ConnectionCore, ConnectionCoreError, ConnectionCoreInvariant, ConnectionInput, ConnectionPhase,
6    ConnectionTransition, Delivery, EffectId, InboundReply, InputDisposition, OperationPhase,
7    WriteFrame,
8};
9
10impl<F: WriteFrame> ConnectionCore<F> {
11    /// Applies one epoch-fenced command, timer, or transport observation.
12    pub fn apply(
13        &mut self,
14        input: ConnectionInput,
15    ) -> Result<ConnectionTransition, ConnectionCoreError> {
16        self.ensure_healthy()?;
17        self.verify_ownership_on_hot_path()?;
18        self.prepare_input_journal(input)?;
19        let transition = self.machine.apply(input);
20        let result = self.reconcile(transition);
21        match result {
22            Ok(transition) => {
23                self.ensure_healthy()?;
24                self.journal.clear();
25                Ok(transition)
26            }
27            Err(error) => Err(error),
28        }
29    }
30
31    /// Applies one complete opaque reply through the same aggregate owner.
32    pub fn apply_reply<R>(
33        &mut self,
34        reply: InboundReply<R>,
35    ) -> Result<ConnectionTransition<R>, ConnectionCoreError> {
36        self.ensure_healthy()?;
37        self.verify_ownership_on_hot_path()?;
38        self.prepare_reply_journal(&reply)?;
39        let transition = self.machine.apply_reply(reply);
40        let result = self.reconcile(transition);
41        match result {
42            Ok(transition) => {
43                self.ensure_healthy()?;
44                self.journal.clear();
45                Ok(transition)
46            }
47            Err(error) => Err(error),
48        }
49    }
50
51    /// Applies exact transport progress to both frame and policy ownership.
52    pub fn advance_write(
53        &mut self,
54        epoch: crate::ConnectionEpoch,
55        effect: EffectId,
56        written: usize,
57    ) -> Result<ConnectionTransition, ConnectionCoreError> {
58        self.ensure_healthy()?;
59        // The writer and policy both validate the exact FIFO operation/effect
60        // below, so partial progress needs no whole-epoch ownership snapshot.
61        self.begin_write_recovery_journal();
62        let progress = match self.writes.advance(epoch, effect, written) {
63            Ok(progress) => progress,
64            Err(
65                crate::WriteProgressError::RetainedAccountingUnderflow { .. }
66                | crate::WriteProgressError::ProgressAccountingOverflow { .. },
67            ) => {
68                return self.poison(ConnectionCoreInvariant::WriteAccounting);
69            }
70            Err(crate::WriteProgressError::ExceedsRemaining { written, remaining }) => {
71                return self
72                    .poison(ConnectionCoreInvariant::WriteProgressContract { written, remaining });
73            }
74            Err(source) => {
75                self.journal.clear();
76                return Err(ConnectionCoreError::Write(source));
77            }
78        };
79        let (operation, boundary, complete) = match progress {
80            WriteProgress::Pending {
81                operation,
82                boundary,
83                ..
84            } => (operation, boundary, false),
85            WriteProgress::Complete {
86                operation,
87                effect,
88                frame,
89                measure,
90                boundary,
91                delivery,
92            } => {
93                let written = measure.wire_bytes();
94                if !self.journal.retain_write(crate::DiscardedWrite {
95                    operation,
96                    effect,
97                    frame,
98                    measure,
99                    written,
100                    delivery,
101                }) {
102                    return self.poison(ConnectionCoreInvariant::RecoveryJournalCapacity);
103                }
104                let Some((wire_index, record)) = self.machine.matching.get_indexed(operation)
105                else {
106                    return self
107                        .poison(ConnectionCoreInvariant::UnexpectedWrite { operation, effect });
108                };
109                if !self.journal.retain_operation(record, wire_index) {
110                    return self.poison(ConnectionCoreInvariant::RecoveryJournalCapacity);
111                }
112                (operation, boundary, true)
113            }
114        };
115        let mut combined = ConnectionTransition::new(InputDisposition::Applied);
116        if boundary == WriteBoundary::Crossed {
117            let transition = self.machine.write_started(epoch, operation, effect);
118            self.absorb_write_transition(&mut combined, transition, operation, effect)?;
119        }
120        if complete {
121            let transition = self.machine.write_completed(epoch, operation, effect);
122            self.absorb_write_transition(&mut combined, transition, operation, effect)?;
123        }
124        self.ensure_healthy()?;
125        self.journal.clear();
126        Ok(combined)
127    }
128
129    fn prepare_input_journal(&mut self, input: ConnectionInput) -> Result<(), ConnectionCoreError> {
130        match input {
131            ConnectionInput::CloseRequested { epoch, .. }
132            | ConnectionInput::ReplyMalformed { epoch }
133                if epoch == self.machine.epoch && self.machine.phase == ConnectionPhase::Live =>
134            {
135                self.begin_recovery_journal()
136            }
137            ConnectionInput::Cancel { epoch, operation }
138                if epoch == self.machine.epoch
139                    && self
140                        .machine
141                        .matching
142                        .get(operation)
143                        .is_some_and(|record| record.phase != OperationPhase::Terminal) =>
144            {
145                self.begin_operation_recovery_journal(operation)
146            }
147            ConnectionInput::DeadlineElapsed {
148                epoch,
149                operation,
150                now,
151            } if epoch == self.machine.epoch => {
152                let Some(record) = self.machine.matching.get(operation).copied() else {
153                    return Ok(());
154                };
155                if !record.deadline.is_elapsed_at(now) {
156                    return Ok(());
157                }
158                if record.delivery == Delivery::PossiblySent {
159                    self.begin_recovery_journal()
160                } else {
161                    self.begin_operation_recovery_journal(operation)
162                }
163            }
164            _ => Ok(()),
165        }
166    }
167
168    fn prepare_reply_journal<R>(
169        &mut self,
170        reply: &InboundReply<R>,
171    ) -> Result<(), ConnectionCoreError> {
172        if reply.epoch != self.machine.epoch || self.machine.phase != ConnectionPhase::Live {
173            return Ok(());
174        }
175        let Some(front) = self.machine.matching.front().copied() else {
176            return self.begin_recovery_journal();
177        };
178        let valid_phase = matches!(
179            front.phase,
180            OperationPhase::AwaitingReply | OperationPhase::Terminal
181        ) && !front.write_held;
182        let expected = front.reservation.match_key;
183        if !valid_phase || reply.key != expected {
184            self.begin_recovery_journal()
185        } else {
186            self.begin_operation_recovery_journal(front.id)
187        }
188    }
189}