liminal-server 0.4.1

Standalone server for the liminal messaging bus
Documentation
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Durable four-class binding-fate occurrence routing.
//!
//! Every Died, Detached, Ordinary, and Recovered row enters this router before
//! its protocol transition can surrender an observer-progress projection.  The
//! in-memory table is reconstructed exclusively from durable row tags during
//! cold replay; it is active-occurrence state, not a history-linear index.

use std::collections::BTreeMap;

use liminal_protocol::wire::{BindingEpoch, ParticipantId};

use super::log::{
    StoredDetached, StoredDied, StoredFinalizerPresentation, StoredOperation,
    StoredOrdinaryTerminalSource, StoredRecoveredPresentation, StoredSpecificFateIntent,
    StoredTerminalDisposition,
};
use super::state::{ConversationAuthority, StateError};

/// Exact identity shared by the four binding-fate classes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct FateOccurrenceKey {
    pub(super) conversation_id: u64,
    pub(super) participant_id: ParticipantId,
    pub(super) binding_epoch: BindingEpoch,
}

/// Closed binding-fate class used in typed conflict diagnostics.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum FateOccurrenceClass {
    Died,
    Detached,
    Ordinary,
    Recovered,
}

/// Durable owner of the occurrence's sole observer presentation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum FatePresentationOwner {
    Died,
    Detached,
    Recovered,
    Finalizer,
}

/// Durable source and explicit presentation mode selected for one finalizer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct PendingFinalizerRoute {
    pub(super) pending_source_sequence: u64,
    pub(super) presentation: StoredFinalizerPresentation,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ExpectedSpecificFate {
    Ordinary,
    Recovered,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PrimaryFate {
    Died {
        source_sequence: u64,
        committed: bool,
        expected_specific: Option<ExpectedSpecificFate>,
    },
    Detached {
        source_sequence: u64,
        committed: bool,
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct FateOccurrenceState {
    primary: PrimaryFate,
    specific: Option<FateOccurrenceClass>,
    presentation_owner: Option<FatePresentationOwner>,
    recovered_reservation: Option<u64>,
    reservation_consumed: bool,
}

/// One typed refusal emitted before observer mutation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum FateOccurrenceConflict {
    #[error("binding-fate occurrence already has a primary {existing:?} row; refused {incoming:?}")]
    PrimaryClass {
        existing: FateOccurrenceClass,
        incoming: FateOccurrenceClass,
    },
    #[error("binding-fate specific row has no earlier Died occurrence")]
    MissingDied,
    #[error("binding-fate specific row does not consume its exact lower Died source")]
    DiedSource,
    #[error("binding-fate specific row class disagrees with the Died intent")]
    SpecificClass,
    #[error("binding-fate occurrence already consumed a specific row")]
    DuplicateSpecific,
    #[error("binding-fate occurrence epoch disagrees with its Died source")]
    BindingEpoch,
    #[error("binding-fate presentation tag disagrees with durable occurrence ownership")]
    PresentationOwner,
    #[error("pending finalizer has no matching pending Died or Detached occurrence")]
    FinalizerSource,
    #[error("Recovered finalizer reservation is missing, wrong, or already consumed")]
    RecoveredReservation,
}

/// Active occurrence table rebuilt from the validated durable stream.
#[derive(Debug, Default)]
pub(super) struct FateOccurrenceRouter {
    occurrences: BTreeMap<FateOccurrenceKey, FateOccurrenceState>,
}

impl FateOccurrenceRouter {
    pub(super) const fn new() -> Self {
        Self {
            occurrences: BTreeMap::new(),
        }
    }

    pub(super) fn route(
        &mut self,
        conversation_id: u64,
        operation: &StoredOperation,
        source_sequence: u64,
    ) -> Result<(), FateOccurrenceConflict> {
        match operation {
            StoredOperation::Died { row } => self.route_died(conversation_id, row, source_sequence),
            StoredOperation::Detached { row } => {
                self.route_detached(conversation_id, row, source_sequence)
            }
            StoredOperation::Ordinary { row, .. } => {
                let died_source_sequence = match row.terminal_source {
                    StoredOrdinaryTerminalSource::DiedCommitted {
                        died_source_sequence,
                    }
                    | StoredOrdinaryTerminalSource::PendingDiedFinalized {
                        died_source_sequence,
                        ..
                    } => died_source_sequence,
                };
                self.route_specific(
                    FateOccurrenceKey {
                        conversation_id,
                        participant_id: row.participant_id,
                        binding_epoch: row
                            .last_dead_binding_epoch
                            .to_epoch()
                            .map_err(|_| FateOccurrenceConflict::BindingEpoch)?,
                    },
                    died_source_sequence,
                    source_sequence,
                    FateOccurrenceClass::Ordinary,
                    None,
                )
            }
            StoredOperation::Recovered { row, .. } => self.route_specific(
                FateOccurrenceKey {
                    conversation_id,
                    participant_id: row.participant_id,
                    binding_epoch: row
                        .last_dead_binding_epoch
                        .to_epoch()
                        .map_err(|_| FateOccurrenceConflict::BindingEpoch)?,
                },
                row.died_source_sequence,
                source_sequence,
                FateOccurrenceClass::Recovered,
                Some(row.presentation),
            ),
            _ => Ok(()),
        }
    }

    fn route_died(
        &mut self,
        conversation_id: u64,
        row: &StoredDied,
        source_sequence: u64,
    ) -> Result<(), FateOccurrenceConflict> {
        let key = FateOccurrenceKey {
            conversation_id,
            participant_id: row.participant_id,
            binding_epoch: row
                .binding_epoch
                .to_epoch()
                .map_err(|_| FateOccurrenceConflict::BindingEpoch)?,
        };
        let expected_specific = row.specific_fate_intent.map(|intent| match intent {
            StoredSpecificFateIntent::Ordinary { .. } => ExpectedSpecificFate::Ordinary,
            StoredSpecificFateIntent::Recovered { .. } => ExpectedSpecificFate::Recovered,
        });
        let committed = matches!(row.disposition, StoredTerminalDisposition::Committed { .. });
        self.insert_primary(
            key,
            FateOccurrenceState {
                primary: PrimaryFate::Died {
                    source_sequence,
                    committed,
                    expected_specific,
                },
                specific: None,
                presentation_owner: committed.then_some(FatePresentationOwner::Died),
                recovered_reservation: None,
                reservation_consumed: false,
            },
            FateOccurrenceClass::Died,
        )
    }

    fn route_detached(
        &mut self,
        conversation_id: u64,
        row: &StoredDetached,
        source_sequence: u64,
    ) -> Result<(), FateOccurrenceConflict> {
        let key = FateOccurrenceKey {
            conversation_id,
            participant_id: row.participant_id,
            binding_epoch: row
                .binding_epoch
                .to_epoch()
                .map_err(|_| FateOccurrenceConflict::BindingEpoch)?,
        };
        let committed = matches!(row.disposition, StoredTerminalDisposition::Committed { .. });
        self.insert_primary(
            key,
            FateOccurrenceState {
                primary: PrimaryFate::Detached {
                    source_sequence,
                    committed,
                },
                specific: None,
                presentation_owner: committed.then_some(FatePresentationOwner::Detached),
                recovered_reservation: None,
                reservation_consumed: false,
            },
            FateOccurrenceClass::Detached,
        )
    }

    fn insert_primary(
        &mut self,
        key: FateOccurrenceKey,
        state: FateOccurrenceState,
        incoming: FateOccurrenceClass,
    ) -> Result<(), FateOccurrenceConflict> {
        if let Some(existing) = self.occurrences.insert(key, state) {
            self.occurrences.insert(key, existing);
            return Err(FateOccurrenceConflict::PrimaryClass {
                existing: primary_class(existing.primary),
                incoming,
            });
        }
        Ok(())
    }

    /// Selects and consumes the one durable presentation mode before a real
    /// Leave or fenced-Attached finalizer can construct an observer projection.
    pub(super) fn select_finalizer(
        &mut self,
        key: FateOccurrenceKey,
    ) -> Result<PendingFinalizerRoute, FateOccurrenceConflict> {
        let state = self
            .occurrences
            .get_mut(&key)
            .ok_or(FateOccurrenceConflict::FinalizerSource)?;
        let (pending_source_sequence, pending) = match state.primary {
            PrimaryFate::Died {
                source_sequence,
                committed,
                ..
            }
            | PrimaryFate::Detached {
                source_sequence,
                committed,
            } => (source_sequence, !committed),
        };
        if !pending {
            return Err(FateOccurrenceConflict::FinalizerSource);
        }
        let presentation = if let Some(recovered_source_sequence) = state.recovered_reservation {
            if state.reservation_consumed
                || state.presentation_owner != Some(FatePresentationOwner::Recovered)
            {
                return Err(FateOccurrenceConflict::RecoveredReservation);
            }
            state.reservation_consumed = true;
            StoredFinalizerPresentation::ConsumeRecoveredReservation {
                recovered_source_sequence,
            }
        } else {
            if state.presentation_owner.is_some() {
                return Err(FateOccurrenceConflict::PresentationOwner);
            }
            state.presentation_owner = Some(FatePresentationOwner::Finalizer);
            StoredFinalizerPresentation::PresentEnclosing
        };
        Ok(PendingFinalizerRoute {
            pending_source_sequence,
            presentation,
        })
    }

    fn route_specific(
        &mut self,
        key: FateOccurrenceKey,
        died_source_sequence: u64,
        source_sequence: u64,
        class: FateOccurrenceClass,
        recovered_presentation: Option<StoredRecoveredPresentation>,
    ) -> Result<(), FateOccurrenceConflict> {
        let state = self
            .occurrences
            .get_mut(&key)
            .ok_or(FateOccurrenceConflict::MissingDied)?;
        let PrimaryFate::Died {
            source_sequence: expected_source,
            committed,
            expected_specific,
        } = state.primary
        else {
            return Err(FateOccurrenceConflict::PrimaryClass {
                existing: FateOccurrenceClass::Detached,
                incoming: class,
            });
        };
        if died_source_sequence != expected_source || died_source_sequence >= source_sequence {
            return Err(FateOccurrenceConflict::DiedSource);
        }
        let expected_class = match expected_specific {
            Some(ExpectedSpecificFate::Ordinary) => FateOccurrenceClass::Ordinary,
            Some(ExpectedSpecificFate::Recovered) => FateOccurrenceClass::Recovered,
            None => return Err(FateOccurrenceConflict::SpecificClass),
        };
        if expected_class != class {
            return Err(FateOccurrenceConflict::SpecificClass);
        }
        if state.specific.is_some() {
            return Err(FateOccurrenceConflict::DuplicateSpecific);
        }
        match (class, committed, recovered_presentation) {
            (
                FateOccurrenceClass::Recovered,
                true,
                Some(StoredRecoveredPresentation::DiedCommittedOwns),
            )
            | (FateOccurrenceClass::Ordinary, _, None) => {}
            (
                FateOccurrenceClass::Recovered,
                false,
                Some(StoredRecoveredPresentation::RecoveredOwnsAndReservesFinalizer),
            ) => {
                if state.presentation_owner.is_some() {
                    return Err(FateOccurrenceConflict::PresentationOwner);
                }
                state.presentation_owner = Some(FatePresentationOwner::Recovered);
                state.recovered_reservation = Some(source_sequence);
            }
            _ => return Err(FateOccurrenceConflict::PresentationOwner),
        }
        state.specific = Some(class);
        Ok(())
    }

    #[cfg(test)]
    pub(super) fn state(&self, key: FateOccurrenceKey) -> Option<FateOccurrenceState> {
        self.occurrences.get(&key).copied()
    }
}

const fn primary_class(primary: PrimaryFate) -> FateOccurrenceClass {
    match primary {
        PrimaryFate::Died { .. } => FateOccurrenceClass::Died,
        PrimaryFate::Detached { .. } => FateOccurrenceClass::Detached,
    }
}

impl FateOccurrenceState {
    #[cfg(test)]
    pub(super) const fn presentation_owner(self) -> Option<FatePresentationOwner> {
        self.presentation_owner
    }

    #[cfg(test)]
    pub(super) const fn reservation(self) -> Option<(u64, bool)> {
        match self.recovered_reservation {
            Some(source) => Some((source, self.reservation_consumed)),
            None => None,
        }
    }
}

impl ConversationAuthority {
    /// Routes one durable fate candidate before any observer-progress mutation.
    pub(super) fn route_fate_occurrence(
        &mut self,
        operation: &StoredOperation,
        source_sequence: u64,
    ) -> Result<(), StateError> {
        self.fate_occurrences
            .route(self.conversation_id, operation, source_sequence)
            .map_err(StateError::from)
    }
}