hibana 0.6.2

Const-projected Affine Multiparty Session Types for choreography-first Rust protocols
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Topology operations and state tracking.
//!
//! Implements topology transaction helpers and per-lane pending topology state.

use core::{cell::UnsafeCell, marker::PhantomData};

use super::error::TopologyError;
use crate::control::{
    automaton::{distributed::TopologyAck, txn::InAcked},
    types::{AtMostOnceCommit, Generation, Lane, NoCrossLaneAliasing, One, SessionId},
};

/// Invariant marker for local topology transactions evaluated inside a rendezvous.
///
/// Guarantees that lane ownership is unique (no cross-lane aliasing) and that
/// commits happen at most once per transaction.
pub(super) struct LocalTopologyInvariant;

impl NoCrossLaneAliasing for LocalTopologyInvariant {}
impl AtMostOnceCommit for LocalTopologyInvariant {}

/// Pending topology state tracked per lane.
pub(super) struct PendingTopology {
    sid: SessionId,
    lane: Lane,
    previous_generation: Option<Generation>,
    target: Generation,
    lease_state: TopologyLeaseState,
    state: Option<InAcked<LocalTopologyInvariant, One>>,
    fences: Option<(u32, u32)>,
    expected_ack: Option<TopologyAck>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum TopologyLeaseState {
    SourcePrepared,
    DestinationPrepared,
    DestinationCommitted,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TopologySessionState {
    SourcePending { lane: Lane },
    DestinationPending { lane: Lane },
    DestinationAttachReady { lane: Lane },
}

impl PendingTopology {
    pub(super) fn source_prepare(
        sid: SessionId,
        lane: Lane,
        previous_generation: Option<Generation>,
        target: Generation,
        state: InAcked<LocalTopologyInvariant, One>,
        fences: Option<(u32, u32)>,
        expected_ack: TopologyAck,
    ) -> Self {
        Self {
            sid,
            lane,
            previous_generation,
            target,
            lease_state: TopologyLeaseState::SourcePrepared,
            state: Some(state),
            fences,
            expected_ack: Some(expected_ack),
        }
    }

    pub(super) fn destination_prepare(
        sid: SessionId,
        lane: Lane,
        previous_generation: Option<Generation>,
        target: Generation,
        state: InAcked<LocalTopologyInvariant, One>,
        fences: Option<(u32, u32)>,
    ) -> Self {
        Self {
            sid,
            lane,
            previous_generation,
            target,
            lease_state: TopologyLeaseState::DestinationPrepared,
            state: Some(state),
            fences,
            expected_ack: None,
        }
    }

    #[inline]
    pub(super) fn lane(&self) -> Lane {
        self.lane
    }

    #[inline]
    pub(super) const fn expected_ack(&self) -> Option<TopologyAck> {
        self.expected_ack
    }

    #[inline]
    pub(super) const fn session_state(&self) -> TopologySessionState {
        match self.lease_state {
            TopologyLeaseState::SourcePrepared => {
                TopologySessionState::SourcePending { lane: self.lane }
            }
            TopologyLeaseState::DestinationPrepared => {
                TopologySessionState::DestinationPending { lane: self.lane }
            }
            TopologyLeaseState::DestinationCommitted => {
                TopologySessionState::DestinationAttachReady { lane: self.lane }
            }
        }
    }

    #[inline]
    pub(super) const fn is_attach_ready(&self) -> bool {
        matches!(self.lease_state, TopologyLeaseState::DestinationCommitted)
    }

    #[inline]
    #[allow(clippy::type_complexity)]
    pub(super) fn into_parts(
        self,
    ) -> (
        SessionId,
        Lane,
        Option<Generation>,
        Generation,
        TopologyLeaseState,
        Option<InAcked<LocalTopologyInvariant, One>>,
        Option<(u32, u32)>,
        Option<TopologyAck>,
    ) {
        (
            self.sid,
            self.lane,
            self.previous_generation,
            self.target,
            self.lease_state,
            self.state,
            self.fences,
            self.expected_ack,
        )
    }
}

impl core::fmt::Debug for PendingTopology {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PendingTopology")
            .field("sid", &self.sid)
            .field("lane", &self.lane)
            .field("previous_generation", &self.previous_generation)
            .field("target", &self.target)
            .field("lease_state", &self.lease_state)
            .finish()
    }
}

/// Local topology state table (per-lane).
///
/// Tracks pending topology operations within a single Rendezvous instance.
pub(super) struct TopologyStateTable {
    lane_base: u32,
    lane_slots: u16,
    lanes: UnsafeCell<*mut Option<PendingTopology>>,
    _no_send_sync: PhantomData<*mut ()>,
}

impl Default for TopologyStateTable {
    fn default() -> Self {
        Self::empty()
    }
}

impl TopologyStateTable {
    pub(super) const fn empty() -> Self {
        Self {
            lane_base: 0,
            lane_slots: 0,
            lanes: UnsafeCell::new(core::ptr::null_mut()),
            _no_send_sync: PhantomData,
        }
    }

    pub(super) unsafe fn init_empty(dst: *mut Self) {
        unsafe {
            core::ptr::addr_of_mut!((*dst).lane_base).write(0);
            core::ptr::addr_of_mut!((*dst).lane_slots).write(0);
            core::ptr::addr_of_mut!((*dst).lanes).write(UnsafeCell::new(core::ptr::null_mut()));
            core::ptr::addr_of_mut!((*dst)._no_send_sync).write(PhantomData);
        }
    }

    #[inline]
    pub(super) const fn storage_align() -> usize {
        core::mem::align_of::<Option<PendingTopology>>()
    }

    #[inline]
    pub(super) const fn storage_bytes(lane_slots: usize) -> usize {
        lane_slots.saturating_mul(core::mem::size_of::<Option<PendingTopology>>())
    }

    pub(super) unsafe fn bind_from_storage(
        &mut self,
        storage: *mut u8,
        lane_base: u32,
        lane_slots: usize,
    ) {
        let lanes = storage.cast::<Option<PendingTopology>>();
        let mut idx = 0usize;
        while idx < lane_slots {
            unsafe {
                lanes.add(idx).write(None);
            }
            idx += 1;
        }
        self.lane_base = lane_base;
        self.lane_slots = lane_slots as u16;
        *self.lanes.get_mut() = lanes;
    }

    pub(super) unsafe fn rebind_from_storage_preserving(
        &mut self,
        storage: *mut u8,
        lane_base: u32,
        lane_slots: usize,
    ) {
        let old_base = self.lane_base;
        let old_slots = self.lane_slots as usize;
        let old_lanes = self.lanes_ptr();
        let lanes = storage.cast::<Option<PendingTopology>>();
        let mut idx = 0usize;
        while idx < lane_slots {
            unsafe {
                lanes.add(idx).write(None);
            }
            idx += 1;
        }
        let mut old_idx = 0usize;
        while old_idx < old_slots {
            let lane = old_base + old_idx as u32;
            if lane >= lane_base {
                let new_idx = (lane - lane_base) as usize;
                if new_idx < lane_slots {
                    unsafe {
                        lanes.add(new_idx).write((*old_lanes.add(old_idx)).take());
                    }
                }
            }
            old_idx += 1;
        }
        self.lane_base = lane_base;
        self.lane_slots = lane_slots as u16;
        *self.lanes.get_mut() = lanes;
    }

    #[inline]
    pub(super) fn is_bound(&self) -> bool {
        !self.lanes_ptr().is_null()
    }

    #[inline]
    pub(super) const fn lane_slots(&self) -> usize {
        self.lane_slots as usize
    }

    #[inline]
    pub(super) fn storage_ptr(&self) -> *mut u8 {
        self.lanes_ptr().cast::<u8>()
    }

    #[inline]
    pub(super) const fn storage_bytes_current(&self) -> usize {
        Self::storage_bytes(self.lane_slots as usize)
    }

    #[inline]
    fn lanes_ptr(&self) -> *mut Option<PendingTopology> {
        unsafe { *self.lanes.get() }
    }

    #[inline]
    fn lane_slot(&self, lane: Lane) -> Option<usize> {
        let lane_raw = lane.raw();
        if lane_raw < self.lane_base {
            return None;
        }
        let slot = (lane_raw - self.lane_base) as usize;
        (slot < self.lane_slots as usize).then_some(slot)
    }

    pub(super) fn pending_lane_for_sid(&self, sid: SessionId) -> Option<Lane> {
        let slots = self.lanes_ptr();
        if slots.is_null() {
            return None;
        }

        let mut idx = 0usize;
        while idx < self.lane_slots as usize {
            unsafe {
                if let Some(pending) = (&*slots.add(idx)).as_ref()
                    && pending.sid == sid
                {
                    return Some(pending.lane());
                }
            }
            idx += 1;
        }

        None
    }

    pub(super) fn take_pending_for_sid(&self, sid: SessionId) -> Option<PendingTopology> {
        let lane = self.pending_lane_for_sid(sid)?;
        self.take(lane)
    }

    pub(super) fn session_state(&self, sid: SessionId) -> Option<TopologySessionState> {
        let slots = self.lanes_ptr();
        if slots.is_null() {
            return None;
        }

        let mut idx = 0usize;
        while idx < self.lane_slots as usize {
            unsafe {
                let Some(pending) = (&*slots.add(idx)).as_ref() else {
                    idx += 1;
                    continue;
                };
                if pending.sid == sid {
                    return Some(pending.session_state());
                }
            }
            idx += 1;
        }

        None
    }

    /// Begin a topology operation.
    pub(super) fn begin(&self, lane: Lane, pending: PendingTopology) -> Result<(), TopologyError> {
        let slots = self.lanes_ptr();
        let Some(idx) = self.lane_slot(lane) else {
            return Err(TopologyError::PendingTableFull);
        };
        if let Some(existing_lane) = self.pending_lane_for_sid(pending.sid) {
            return Err(TopologyError::InProgress {
                lane: existing_lane,
            });
        }
        unsafe {
            let slot = &mut *slots.add(idx);
            if slot.is_some() {
                return Err(TopologyError::InProgress { lane });
            }
            *slot = Some(pending);
            Ok(())
        }
    }

    /// Take (consume) pending topology state.
    pub(super) fn take(&self, lane: Lane) -> Option<PendingTopology> {
        let slots = self.lanes_ptr();
        let idx = self.lane_slot(lane)?;
        unsafe { (*slots.add(idx)).take() }
    }

    /// Validate that the given lane still owns a pending topology transition for `sid`.
    pub(super) fn preflight_commit(&self, lane: Lane, sid: SessionId) -> Result<(), TopologyError> {
        let slots = self.lanes_ptr();
        let Some(idx) = self.lane_slot(lane) else {
            return Err(TopologyError::NoPending { lane });
        };
        unsafe {
            match (&*slots.add(idx)).as_ref() {
                Some(pending)
                    if pending.sid == sid
                        && matches!(
                            pending.lease_state,
                            TopologyLeaseState::DestinationPrepared
                        ) =>
                {
                    Ok(())
                }
                Some(pending) if pending.sid == sid => Err(TopologyError::InProgress { lane }),
                Some(pending) => Err(TopologyError::UnknownSession { sid: pending.sid }),
                None => Err(TopologyError::NoPending { lane }),
            }
        }
    }

    pub(super) fn prepared_destination_generation(
        &self,
        lane: Lane,
        sid: SessionId,
    ) -> Result<(Option<Generation>, Generation), TopologyError> {
        let slots = self.lanes_ptr();
        let Some(idx) = self.lane_slot(lane) else {
            return Err(TopologyError::NoPending { lane });
        };
        unsafe {
            match (&*slots.add(idx)).as_ref() {
                Some(pending)
                    if pending.sid == sid
                        && matches!(
                            pending.lease_state,
                            TopologyLeaseState::DestinationPrepared
                        ) =>
                {
                    Ok((pending.previous_generation, pending.target))
                }
                Some(pending) if pending.sid == sid => Err(TopologyError::InProgress { lane }),
                Some(pending) => Err(TopologyError::UnknownSession { sid: pending.sid }),
                None => Err(TopologyError::NoPending { lane }),
            }
        }
    }

    /// Return the expected distributed-topology ACK for a pending session.
    pub(super) fn expected_ack_for_session(
        &self,
        sid: SessionId,
    ) -> Result<TopologyAck, TopologyError> {
        let slots = self.lanes_ptr();
        if slots.is_null() {
            return Err(TopologyError::UnknownSession { sid });
        }

        let mut idx = 0usize;
        while idx < self.lane_slots as usize {
            unsafe {
                let Some(pending) = (&*slots.add(idx)).as_ref() else {
                    idx += 1;
                    continue;
                };
                if pending.sid != sid {
                    idx += 1;
                    continue;
                }
                return pending.expected_ack().ok_or(TopologyError::NoPending {
                    lane: pending.lane(),
                });
            }
        }

        Err(TopologyError::UnknownSession { sid })
    }

    /// Reset lane (clear pending topology state).
    pub(super) fn reset_lane(&self, lane: Lane) {
        let slots = self.lanes_ptr();
        let Some(idx) = self.lane_slot(lane) else {
            return;
        };
        unsafe {
            *slots.add(idx) = None;
        }
    }

    pub(super) fn finalize_destination(
        &self,
        lane: Lane,
        sid: SessionId,
    ) -> Result<(), TopologyError> {
        let slots = self.lanes_ptr();
        let Some(idx) = self.lane_slot(lane) else {
            return Err(TopologyError::NoPending { lane });
        };
        unsafe {
            let slot = &mut *slots.add(idx);
            match slot {
                Some(pending)
                    if pending.sid == sid
                        && matches!(
                            pending.lease_state,
                            TopologyLeaseState::DestinationPrepared
                        ) =>
                {
                    pending.lease_state = TopologyLeaseState::DestinationCommitted;
                    pending.state = None;
                    Ok(())
                }
                Some(pending) if pending.sid == sid => Err(TopologyError::InProgress { lane }),
                Some(pending) => Err(TopologyError::UnknownSession { sid: pending.sid }),
                None => Err(TopologyError::NoPending { lane }),
            }
        }
    }

    pub(super) fn attach_ready_sid(&self, lane: Lane) -> Option<SessionId> {
        let slots = self.lanes_ptr();
        let idx = self.lane_slot(lane)?;
        unsafe {
            match (&*slots.add(idx)).as_ref() {
                Some(pending) if pending.is_attach_ready() => Some(pending.sid),
                _ => None,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::TopologyStateTable;
    use crate::{
        control::types::{Lane, SessionId},
        rendezvous::error::TopologyError,
    };

    #[test]
    fn topology_state_table_unbound_reads_as_empty() {
        let table = TopologyStateTable::empty();
        let lane = Lane::new(0);
        let sid = SessionId::new(7);

        assert!(!table.is_bound());
        assert!(table.take(lane).is_none());
        assert_eq!(
            table.preflight_commit(lane, sid),
            Err(TopologyError::NoPending { lane })
        );
        table.reset_lane(lane);
    }
}