hibana 0.5.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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! Lease-first control core.
//!
//! This module replaces ad-hoc interior mutability with an explicit, RAII-based
//! leasing API. `ControlCore::lease::<Spec>()` is the single entry point for
//! touching rendezvous state; everything else must be expressed as a typed
//! automaton that consumes the lease.
//!
//! The design goals are:
//! - **No hidden mutable access** — leases carry unique borrows, eliminating
//!   `UnsafeCell` gymnastics and raw pointers.
//! - **Facet-driven typing** — the lease exposes only the facets declared by
//!   the `RendezvousSpec`. Unsupported operations are a compile-time error.
//! - **Affine lifecycle** — leases release themselves on drop, and cannot be
//!   cloned or duplicated.
//! - **Const-friendly control** — the control layer stays allocation free and
//!   is ready for `no_std`.

use core::{marker::PhantomData, ptr, ptr::NonNull};

use crate::control::types::{Lane, RendezvousId, SessionId};
use crate::rendezvous::core::Rendezvous;
use crate::{
    control::lease::map::ArrayMap,
    runtime::{config::Clock, consts::LabelUniverse},
    transport::Transport,
};

/// Fixed-size control core that owns rendezvous instances.
///
/// `ControlCore` is parameterised by the transport, label universe, clock and
/// epoch table used by the rendezvous layer. The `MAX_RV` const parameter fixes
/// the maximum number of rendezvous that can be registered in `no_alloc`
/// environments.
pub(crate) struct ControlCore<
    'cfg,
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
    const MAX_RV: usize,
> {
    entries: ArrayMap<RendezvousId, RendezvousEntry<'cfg, T, U, C, E>, MAX_RV>,
}

impl<'cfg, T, U, C, E, const MAX_RV: usize> Default for ControlCore<'cfg, T, U, C, E, MAX_RV>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<'cfg, T, U, C, E, const MAX_RV: usize> ControlCore<'cfg, T, U, C, E, MAX_RV>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
    /// Construct an empty control core.
    pub(crate) const fn new() -> Self {
        Self {
            entries: ArrayMap::new(),
        }
    }

    /// Initialize an empty control core in place without constructing the full
    /// fixed-capacity storage on the caller's stack first.
    ///
    /// # Safety
    /// `dst` must point to valid, writable memory for `Self`.
    pub(crate) unsafe fn init_empty(dst: *mut Self) {
        unsafe {
            ArrayMap::init_empty(core::ptr::addr_of_mut!((*dst).entries));
        }
    }

    /// Returns true if the rendezvous identifier is present, regardless of activity.
    #[cfg(test)]
    pub(crate) fn is_registered(&self, id: &RendezvousId) -> bool {
        self.entries.contains_key(id)
    }

    /// Borrow a rendezvous by shared reference when no lease is active.
    pub(crate) fn get(&self, id: &RendezvousId) -> Option<&Rendezvous<'cfg, 'cfg, T, U, C, E>> {
        self.entries
            .get(id)
            .and_then(|entry| entry.rendezvous_ref())
    }

    /// Borrow a rendezvous by mutable reference when no lease is active.
    pub(crate) fn get_mut(
        &mut self,
        id: &RendezvousId,
    ) -> Option<&mut Rendezvous<'cfg, 'cfg, T, U, C, E>> {
        self.entries
            .get_mut(id)
            .and_then(|entry| entry.rendezvous_mut())
    }

    /// Borrow a rendezvous mutably, preserving the distinction between an
    /// absent rendezvous and an active affine lease.
    pub(crate) fn get_mut_checked(
        &mut self,
        id: &RendezvousId,
    ) -> Result<&mut Rendezvous<'cfg, 'cfg, T, U, C, E>, LeaseError> {
        let slot = self
            .entries
            .get_mut(id)
            .ok_or(LeaseError::UnknownRendezvous(*id))?;
        if slot.is_active() {
            return Err(LeaseError::AlreadyLeased(*id));
        }
        Ok(slot.rendezvous())
    }

    /// Obtain a lease for the rendezvous identified by `rv_id`.
    ///
    /// The lease carries a type parameter `Spec` that determines which facets
    /// of the rendezvous state may be accessed.
    pub(crate) fn lease<'lease, Spec>(
        &'lease mut self,
        rv_id: RendezvousId,
    ) -> Result<RendezvousLease<'lease, 'cfg, T, U, C, E, Spec>, LeaseError>
    where
        Spec: RendezvousSpec<T, U, C, E>,
        'cfg: 'lease,
    {
        let slot = self
            .entries
            .get_mut(&rv_id)
            .ok_or(LeaseError::UnknownRendezvous(rv_id))?;
        if slot.is_active() {
            return Err(LeaseError::AlreadyLeased(rv_id));
        }
        slot.mark_active();
        Ok(RendezvousLease::new(slot))
    }
}

impl<'cfg, T, U, C, const MAX_RV: usize>
    ControlCore<'cfg, T, U, C, crate::control::cap::mint::EpochTbl, MAX_RV>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
{
    fn next_available_rendezvous_id(&self) -> Option<RendezvousId> {
        let mut raw = 1u16;
        loop {
            let id = RendezvousId::new(raw);
            if !self.entries.contains_key(&id) {
                return Some(id);
            }
            raw = raw.wrapping_add(1);
            if raw == 0 {
                return None;
            }
        }
    }

    /// Register a local rendezvous by constructing it directly inside the
    /// fixed-capacity owner slot instead of materialising a large stack value on
    /// the caller stack first.
    #[cfg(test)]
    pub(crate) fn register_local_from_config(
        &mut self,
        config: crate::runtime::config::Config<'cfg, U, C>,
        transport: T,
        endpoint_slots: usize,
    ) -> Result<RendezvousId, RegisterRendezvousError> {
        if self.entries.is_full() {
            return Err(RegisterRendezvousError::CapacityExceeded);
        }
        let id = self
            .next_available_rendezvous_id()
            .ok_or(RegisterRendezvousError::CapacityExceeded)?;

        self.entries
            .try_push_with(RegisterRendezvousError::CapacityExceeded, |slot| unsafe {
                let entry = slot.as_mut_ptr();
                core::ptr::addr_of_mut!((*entry).0).write(id);
                RendezvousEntry::init_from_config(
                    core::ptr::addr_of_mut!((*entry).1),
                    id,
                    config,
                    transport,
                    endpoint_slots,
                )
            })?;
        Ok(id)
    }

    pub(crate) fn register_local_from_config_auto(
        &mut self,
        config: crate::runtime::config::Config<'cfg, U, C>,
        transport: T,
    ) -> Result<RendezvousId, RegisterRendezvousError> {
        if self.entries.is_full() {
            return Err(RegisterRendezvousError::CapacityExceeded);
        }
        let endpoint_slots = config.endpoint_slots;
        let id = self
            .next_available_rendezvous_id()
            .ok_or(RegisterRendezvousError::CapacityExceeded)?;
        self.entries
            .try_push_with(RegisterRendezvousError::CapacityExceeded, |slot| unsafe {
                let entry = slot.as_mut_ptr();
                core::ptr::addr_of_mut!((*entry).0).write(id);
                RendezvousEntry::init_from_config_auto(
                    core::ptr::addr_of_mut!((*entry).1),
                    id,
                    config,
                    transport,
                    endpoint_slots,
                )
            })?;
        Ok(id)
    }
}

/// Failure modes for rendezvous registration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RegisterRendezvousError {
    /// Attempted to register more rendezvous than the fixed capacity allows.
    CapacityExceeded,
    /// Borrowed runtime storage cannot fit the rendezvous resident header.
    StorageExhausted,
}

/// Leasing failures.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LeaseError {
    /// No rendezvous with the requested identifier exists.
    UnknownRendezvous(RendezvousId),
    /// The rendezvous is currently leased and cannot be borrowed again.
    AlreadyLeased(RendezvousId),
}

/// Internal rendezvous slot used by [`ControlCore`].
struct RendezvousEntry<'cfg, T, U, C, E>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
    rendezvous: NonNull<Rendezvous<'cfg, 'cfg, T, U, C, E>>,
    active: bool,
    _marker: PhantomData<&'cfg mut Rendezvous<'cfg, 'cfg, T, U, C, E>>,
}

impl<'cfg, T, U, C, E> RendezvousEntry<'cfg, T, U, C, E>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
    fn is_active(&self) -> bool {
        self.active
    }

    fn mark_active(&mut self) {
        self.active = true;
    }

    fn clear_active(&mut self) {
        self.active = false;
    }

    fn rendezvous_ref(&self) -> Option<&Rendezvous<'cfg, 'cfg, T, U, C, E>> {
        if self.active {
            None
        } else {
            Some(unsafe { self.rendezvous.as_ref() })
        }
    }

    fn rendezvous_mut(&mut self) -> Option<&mut Rendezvous<'cfg, 'cfg, T, U, C, E>> {
        if self.active {
            None
        } else {
            Some(unsafe { self.rendezvous.as_mut() })
        }
    }

    fn rendezvous(&mut self) -> &mut Rendezvous<'cfg, 'cfg, T, U, C, E> {
        unsafe { self.rendezvous.as_mut() }
    }
}

impl<'cfg, T, U, C> RendezvousEntry<'cfg, T, U, C, crate::control::cap::mint::EpochTbl>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
{
    #[cfg(test)]
    unsafe fn init_from_config(
        dst: *mut Self,
        rv_id: RendezvousId,
        config: crate::runtime::config::Config<'cfg, U, C>,
        transport: T,
        endpoint_slots: usize,
    ) -> Result<(), RegisterRendezvousError> {
        let rendezvous = unsafe {
            Rendezvous::init_in_slab(rv_id, config, transport, endpoint_slots)
                .ok_or(RegisterRendezvousError::StorageExhausted)?
        };
        unsafe {
            core::ptr::addr_of_mut!((*dst).rendezvous).write(NonNull::new_unchecked(rendezvous));
            core::ptr::addr_of_mut!((*dst).active).write(false);
            core::ptr::addr_of_mut!((*dst)._marker).write(PhantomData);
        }
        Ok(())
    }

    unsafe fn init_from_config_auto(
        dst: *mut Self,
        rv_id: RendezvousId,
        config: crate::runtime::config::Config<'cfg, U, C>,
        transport: T,
        endpoint_slots: usize,
    ) -> Result<(), RegisterRendezvousError> {
        let rendezvous = unsafe {
            Rendezvous::init_in_slab_auto(rv_id, config, transport, endpoint_slots)
                .ok_or(RegisterRendezvousError::StorageExhausted)?
        };
        unsafe {
            core::ptr::addr_of_mut!((*dst).rendezvous).write(NonNull::new_unchecked(rendezvous));
            core::ptr::addr_of_mut!((*dst).active).write(false);
            core::ptr::addr_of_mut!((*dst)._marker).write(PhantomData);
        }
        Ok(())
    }
}

impl<'cfg, T, U, C, E> Drop for RendezvousEntry<'cfg, T, U, C, E>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
    fn drop(&mut self) {
        unsafe {
            ptr::drop_in_place(self.rendezvous.as_ptr());
        }
    }
}

/// RAII lease over a rendezvous slot.
///
/// The lease is affine: it cannot be cloned, and dropping it automatically marks
/// the underlying rendezvous as available again. Access to rendezvous facets is
/// mediated through the `Spec` type parameter.
pub(crate) struct RendezvousLease<
    'lease,
    'cfg,
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
    Spec,
> where
    Spec: RendezvousSpec<T, U, C, E>,
    'cfg: 'lease,
{
    slot: Option<&'lease mut RendezvousEntry<'cfg, T, U, C, E>>,
    _spec: PhantomData<Spec>,
}

impl<'lease, 'cfg, T, U, C, E, Spec> RendezvousLease<'lease, 'cfg, T, U, C, E, Spec>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
    Spec: RendezvousSpec<T, U, C, E>,
    'cfg: 'lease,
{
    fn new(slot: &'lease mut RendezvousEntry<'cfg, T, U, C, E>) -> Self {
        Self {
            slot: Some(slot),
            _spec: PhantomData,
        }
    }

    #[inline]
    fn entry_mut(&mut self) -> &mut RendezvousEntry<'cfg, T, U, C, E> {
        self.slot
            .as_mut()
            .expect("rendezvous lease has already been consumed")
    }

    #[inline]
    pub(crate) fn with_rendezvous<R>(
        &mut self,
        f: impl FnOnce(&mut Rendezvous<'cfg, 'cfg, T, U, C, E>) -> R,
    ) -> R {
        let entry = self.entry_mut();
        f(entry.rendezvous())
    }

    /// Obtain an observation lease for the underlying rendezvous.
    pub(crate) fn observe(&mut self) -> LeaseObserve<'_, 'cfg> {
        let tap = self.with_rendezvous(|rv| rv.tap() as *const crate::observe::core::TapRing<'cfg>);
        LeaseObserve::new(tap)
    }
}

impl<'lease, 'cfg, T, U, C, E> RendezvousLease<'lease, 'cfg, T, U, C, E, FullSpec>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
    'cfg: 'lease,
{
    #[inline]
    pub(crate) fn brand(&mut self) -> crate::control::brand::Guard<'cfg> {
        self.with_rendezvous(|rv| rv.brand())
    }

    #[inline]
    pub(crate) fn emit_lane_acquire(
        &mut self,
        timestamp: u32,
        rv_id: crate::control::types::RendezvousId,
        sid: SessionId,
        lane: Lane,
    ) {
        let observe = self.observe();
        observe.emit(crate::observe::events::LaneAcquire::new(
            timestamp,
            rv_id.raw() as u32,
            sid.raw(),
            lane.raw() as u16,
        ));
    }

    #[inline]
    pub(crate) fn release_lane_with_tap(&mut self, lane: Lane) -> bool {
        self.with_rendezvous(|rv| {
            if let Some(sid) = rv.release_lane(lane) {
                rv.emit_lane_release(sid, lane);
                true
            } else {
                false
            }
        })
    }
}

impl<'lease, 'cfg, T, U, C, E, Spec> Drop for RendezvousLease<'lease, 'cfg, T, U, C, E, Spec>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
    Spec: RendezvousSpec<T, U, C, E>,
    'cfg: 'lease,
{
    fn drop(&mut self) {
        if let Some(slot) = self.slot.take() {
            slot.clear_active();
        }
    }
}

/// Trait implemented by rendezvous lease specifications.
///
/// A spec declares a set of facets accessible through a lease. Simple specs may
/// return a mutable reference to the rendezvous itself, while more focused specs
/// can expose narrow capability objects.
pub(crate) trait RendezvousSpec<T, U, C, E>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
}

/// Default spec exposing full mutable access to the rendezvous.
pub(crate) struct FullSpec;

/// Spec that exposes only topology operations.
pub(crate) struct TopologySpec;

impl<T, U, C, E> RendezvousSpec<T, U, C, E> for TopologySpec
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
}

/// Lease-backed access to rendezvous observation events.
#[derive(Clone, Copy)]
pub(crate) struct LeaseObserve<'lease, 'cfg> {
    tap: *const crate::observe::core::TapRing<'cfg>,
    _marker: PhantomData<&'lease crate::observe::core::TapRing<'cfg>>,
}

impl<'lease, 'cfg> LeaseObserve<'lease, 'cfg> {
    #[inline]
    pub(crate) const fn new(tap: *const crate::observe::core::TapRing<'cfg>) -> Self {
        Self {
            tap,
            _marker: PhantomData,
        }
    }

    #[inline]
    fn ring(&self) -> &crate::observe::core::TapRing<'cfg> {
        unsafe { &*self.tap }
    }

    /// Emit an already constructed tap event.
    #[inline]
    pub(crate) fn emit(&self, event: crate::observe::core::TapEvent) {
        crate::observe::core::emit(self.ring(), event);
    }
}

impl<T, U, C, E> RendezvousSpec<T, U, C, E> for FullSpec
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
}

/// Control automaton executed against a rendezvous lease.
pub(crate) trait ControlAutomaton<T, U, C, E>
where
    T: Transport,
    U: LabelUniverse,
    C: Clock,
    E: crate::control::cap::mint::EpochTable,
{
    /// Lease specialisation required by the automaton.
    type Spec: RendezvousSpec<T, U, C, E>;
    /// Initial input value.
    type Seed;
    /// Result produced on success.
    type Output;
    /// Error reported on failure.
    type Error;
    /// LeaseGraph specialisation used when the automaton requires cross-rendezvous
    /// coordination. Automatons that do not depend on additional graph state can
    /// provide a degenerate spec.
    type GraphSpec: LeaseSpec;

    /// Execute the automaton using a LeaseGraph for ownership tracking.
    fn run_with_graph<'lease, 'cfg, 'graph>(
        graph: &'graph mut LeaseGraph<'graph, Self::GraphSpec>,
        lease: &mut RendezvousLease<'lease, 'cfg, T, U, C, E, Self::Spec>,
        seed: Self::Seed,
    ) -> ControlStep<Self::Output, Self::Error>
    where
        'cfg: 'lease;
}

/// Result of running a control automaton step.
pub(crate) enum ControlStep<O, E> {
    /// Automaton finished successfully.
    Complete(O),
    /// Automaton failed.
    Abort(E),
}

use crate::control::lease::graph::{LeaseGraph, LeaseGraphError, LeaseSpec};

/// Error when running a LeaseGraph-enabled automaton.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DelegationDriveError<E> {
    /// Failed to obtain a rendezvous lease.
    Lease(LeaseError),
    /// LeaseGraph operation failed.
    Graph(LeaseGraphError),
    /// The automaton aborted.
    Automaton(E),
}

#[cfg(test)]
mod automaton_tests {
    use super::*;
    use crate::control::lease::graph::LeaseFacet;
    use crate::control::types::RendezvousId;
    use core::mem::MaybeUninit;

    #[derive(Clone, Copy, Default)]
    struct TestFacet;

    #[derive(Clone, Copy)]
    struct TestContext {
        value: u32,
    }

    impl LeaseFacet for TestFacet {
        type Context<'ctx> = TestContext;

        fn on_commit<'ctx>(&self, _context: &mut Self::Context<'ctx>) {}

        fn on_rollback<'ctx>(&self, _context: &mut Self::Context<'ctx>) {}
    }

    struct RvLeaseSpec;
    impl LeaseSpec for RvLeaseSpec {
        type NodeId = RendezvousId;
        type Facet = TestFacet;
        type ChildStorage = crate::control::lease::graph::InlineLeaseChildStorage<RendezvousId, 3>;
        type NodeStorage<'graph>
            = crate::control::lease::graph::InlineLeaseNodeStorage<'graph, Self, 4>
        where
            Self: 'graph;
        const MAX_NODES: usize = 4;
        const MAX_CHILDREN: usize = 3;
    }

    #[test]
    fn test_lease_graph_operations() {
        let root_id = RendezvousId::new(1);
        let child_id = RendezvousId::new(2);

        let mut graph_storage = MaybeUninit::<LeaseGraph<'_, RvLeaseSpec>>::uninit();
        let mut graph = unsafe {
            LeaseGraph::<RvLeaseSpec>::init_new(
                graph_storage.as_mut_ptr(),
                root_id,
                TestFacet,
                TestContext { value: 10 },
            );
            graph_storage.assume_init()
        };
        graph
            .add_child(root_id, child_id, TestFacet, TestContext { value: 20 })
            .unwrap();

        let sum = graph.handle_mut(root_id).unwrap().with(|_, ctx| ctx.value)
            + graph.handle_mut(child_id).unwrap().with(|_, ctx| ctx.value);
        assert_eq!(sum, 30);

        graph.commit();
    }
}