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
//! Control-plane error types.
//!
//! `CpError` is the internal control-plane failure catalogue. Public attach
//! failures use [`AttachError`], which records the public attach operation
//! callsite so protocol integrations can propagate attach errors with `?`
//! without adding wrapper context at every call site.

use core::{fmt, panic::Location};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ErrorLocation {
    location: &'static Location<'static>,
}

impl ErrorLocation {
    #[inline]
    #[track_caller]
    pub(crate) fn caller() -> Self {
        Self {
            location: Location::caller(),
        }
    }

    #[inline]
    const fn file(self) -> &'static str {
        self.location.file()
    }

    #[inline]
    const fn line(self) -> u32 {
        self.location.line()
    }

    #[inline]
    const fn column(self) -> u32 {
        self.location.column()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AttachOp {
    Internal,
    AddRendezvous,
    Enter,
}

/// Errors raised while attaching cursor endpoints to the control cluster.
///
/// Attach failures are public evidence for rendezvous/endpoint setup. They are
/// intentionally separate from endpoint progress errors so `?` can preserve the
/// failing boundary without a wide crate-level error enum.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct AttachError {
    op: AttachOp,
    location: ErrorLocation,
    kind: AttachErrorKind,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AttachErrorKind {
    Control(CpError),
    Rendezvous(crate::rendezvous::error::RendezvousError),
}

impl fmt::Debug for AttachError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AttachError")
            .field("operation", &self.operation())
            .field("file", &self.file())
            .field("line", &self.line())
            .field("column", &self.column())
            .field("kind", &self.kind)
            .finish()
    }
}

impl AttachError {
    #[inline]
    #[track_caller]
    pub(crate) fn control(error: CpError) -> Self {
        Self {
            op: AttachOp::Internal,
            location: ErrorLocation::caller(),
            kind: AttachErrorKind::Control(error),
        }
    }

    #[inline]
    #[track_caller]
    pub(crate) fn rendezvous(error: crate::rendezvous::error::RendezvousError) -> Self {
        Self {
            op: AttachOp::Internal,
            location: ErrorLocation::caller(),
            kind: AttachErrorKind::Rendezvous(error),
        }
    }

    #[inline]
    pub(crate) const fn with_operation(mut self, op: AttachOp, location: ErrorLocation) -> Self {
        self.op = op;
        self.location = location;
        self
    }

    #[inline]
    pub(crate) const fn control_cause(&self) -> Option<CpError> {
        match self.kind {
            AttachErrorKind::Control(error) => Some(error),
            AttachErrorKind::Rendezvous(_) => None,
        }
    }

    #[inline]
    pub const fn operation(&self) -> &'static str {
        match self.op {
            AttachOp::Internal => "attach",
            AttachOp::AddRendezvous => "add_rendezvous",
            AttachOp::Enter => "enter",
        }
    }

    #[inline]
    pub const fn file(&self) -> &'static str {
        self.location.file()
    }

    #[inline]
    pub const fn line(&self) -> u32 {
        self.location.line()
    }

    #[inline]
    pub const fn column(&self) -> u32 {
        self.location.column()
    }
}

impl From<CpError> for AttachError {
    #[inline]
    #[track_caller]
    fn from(err: CpError) -> Self {
        Self::control(err)
    }
}

impl From<crate::rendezvous::error::RendezvousError> for AttachError {
    #[inline]
    #[track_caller]
    fn from(err: crate::rendezvous::error::RendezvousError) -> Self {
        Self::rendezvous(err)
    }
}

/// Unified control-plane error type.
///
/// All control-plane operations (topology, delegation, abort, state snapshot,
/// state restore, and transaction commit) return errors of this type, enabling
/// uniform error handling and tap integration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CpError {
    /// Topology-related errors.
    Topology(TopologyError),

    /// Abort-related errors.
    Abort(AbortError),

    /// State snapshot-related errors.
    StateSnapshot(StateSnapshotError),

    /// State restore-related errors.
    StateRestore(StateRestoreError),

    /// Transaction commit-related errors.
    TxCommit(TxCommitError),

    /// Transaction abort-related errors.
    TxAbort(TxAbortError),

    /// Delegation-related errors
    Delegation(DelegationError),

    /// Rendezvous ID mismatch (distributed operations)
    RendezvousMismatch { expected: u16, actual: u16 },

    /// Requested rendezvous was not registered in this control cluster.
    RendezvousMissing { id: u16 },

    /// Rendezvous exists but is currently protected by an affine lease.
    RendezvousBusy { id: u16 },

    /// Replay detection (duplicate operation)
    ReplayDetected { operation: u8, nonce: u32 },

    /// Generation ordering violation
    GenerationViolation { expected: u16, actual: u16 },

    /// Resource exhaustion in a specific control-plane storage area.
    ResourceExhausted { resource: ResourceScope },

    /// Capability check failed (operation not permitted for this lane).
    Authorisation { operation: u8 },

    /// Effect not supported by the target control plane.
    UnsupportedEffect(u8),

    /// Program label exceeds the rendezvous label universe.
    LabelOutOfUniverse { max: u8, actual: u8 },

    /// Policy VM requested that the operation be aborted.
    PolicyAbort { reason: u16 },

    /// Resource kind mismatch in typed token pipeline.
    ResourceMismatch { expected: u8, actual: u8 },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResourceScope {
    Generic,
    SessionKit,
    RendezvousSlot,
    ResolverTable,
    PolicyTable,
    ProgramImage,
    RoleImage,
    EndpointResidentBudget,
    RouteTable,
    LoopTable,
    CapTable,
    EndpointLease,
    EndpointBounds,
    EndpointMark,
    EndpointPin,
    EndpointHeader,
    ControlLaneStorage,
}

impl ResourceScope {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Generic => "generic",
            Self::SessionKit => "session-kit",
            Self::RendezvousSlot => "rendezvous-slot",
            Self::ResolverTable => "resolver-table",
            Self::PolicyTable => "policy-table",
            Self::ProgramImage => "program-image",
            Self::RoleImage => "role-image",
            Self::EndpointResidentBudget => "endpoint-resident-budget",
            Self::RouteTable => "route-table",
            Self::LoopTable => "loop-table",
            Self::CapTable => "cap-table",
            Self::EndpointLease => "endpoint-lease",
            Self::EndpointBounds => "endpoint-bounds",
            Self::EndpointMark => "endpoint-mark",
            Self::EndpointPin => "endpoint-pin",
            Self::EndpointHeader => "endpoint-header",
            Self::ControlLaneStorage => "control-lane-storage",
        }
    }
}

impl CpError {
    #[inline]
    pub const fn resource_exhausted(resource: ResourceScope) -> Self {
        Self::ResourceExhausted { resource }
    }
}

/// Topology operation errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TopologyError {
    /// Invalid session ID
    InvalidSession,

    /// Invalid lane ID
    InvalidLane,

    /// Session not in topology-transitionable state
    InvalidState,

    /// Generation mismatch
    GenerationMismatch,

    /// Distributed topology transition: ACK timeout
    AckTimeout,

    /// Distributed topology transition: commit failed
    CommitFailed,

    /// Lane out of range
    LaneOutOfRange,

    /// Lane mismatch
    LaneMismatch,

    /// Topology transition already in progress
    InProgress,

    /// No pending topology transition
    NoPending,

    /// Stale generation
    StaleGeneration,

    /// Generation overflow
    GenerationOverflow,

    /// Invalid initial generation
    InvalidInitial,

    /// Rendezvous ID mismatch
    RendezvousIdMismatch,

    /// Sequence number mismatch
    SeqnoMismatch,

    /// Pending topology table full
    PendingTableFull,
}

impl From<crate::rendezvous::error::TopologyError> for TopologyError {
    fn from(err: crate::rendezvous::error::TopologyError) -> Self {
        match err {
            crate::rendezvous::error::TopologyError::LaneOutOfRange { .. } => {
                TopologyError::LaneOutOfRange
            }
            crate::rendezvous::error::TopologyError::UnknownSession { .. } => {
                TopologyError::InvalidSession
            }
            crate::rendezvous::error::TopologyError::LaneMismatch { .. } => {
                TopologyError::LaneMismatch
            }
            crate::rendezvous::error::TopologyError::InProgress { .. } => TopologyError::InProgress,
            crate::rendezvous::error::TopologyError::NoPending { .. } => TopologyError::NoPending,
            crate::rendezvous::error::TopologyError::StaleGeneration { .. } => {
                TopologyError::StaleGeneration
            }
            crate::rendezvous::error::TopologyError::GenerationOverflow { .. } => {
                TopologyError::GenerationOverflow
            }
            crate::rendezvous::error::TopologyError::InvalidInitial { .. } => {
                TopologyError::InvalidInitial
            }
            crate::rendezvous::error::TopologyError::RemoteRendezvousMismatch { .. }
            | crate::rendezvous::error::TopologyError::RendezvousIdMismatch { .. } => {
                TopologyError::RendezvousIdMismatch
            }
            crate::rendezvous::error::TopologyError::SeqnoMismatch { .. } => {
                TopologyError::SeqnoMismatch
            }
            crate::rendezvous::error::TopologyError::PendingTableFull => {
                TopologyError::PendingTableFull
            }
        }
    }
}

/// Abort errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AbortError {
    /// Session not found
    SessionNotFound,

    /// Generation mismatch in ACK
    GenerationMismatch,
}

/// State snapshot errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateSnapshotError {
    /// Session not found
    SessionNotFound,
}

/// State restore errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateRestoreError {
    /// Session not found
    SessionNotFound,

    /// State snapshot epoch not found
    EpochNotFound,

    /// Epoch mismatch (not aligned)
    EpochMismatch,

    /// State snapshot already finalized by a prior restore or commit
    AlreadyFinalized,
}

/// Transaction commit errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TxCommitError {
    /// Session not found
    SessionNotFound,

    /// No state snapshot available to commit
    NoStateSnapshot,

    /// State snapshot already finalized by a prior restore or commit
    AlreadyFinalized,

    /// Provided generation does not match the recorded state snapshot
    GenerationMismatch,
}

/// Transaction abort errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TxAbortError {
    /// Session not found
    SessionNotFound,

    /// No state snapshot available to abort back to
    NoStateSnapshot,

    /// State snapshot already finalized by a prior restore, abort, or commit
    AlreadyFinalized,

    /// Provided generation does not match the recorded state snapshot
    GenerationMismatch,
}

/// Delegation errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DelegationError {
    /// Invalid capability token
    InvalidToken,

    /// Capability exhausted (one-shot)
    Exhausted,

    /// Shot discipline violation
    ShotMismatch,
}

impl core::fmt::Display for CpError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Topology(e) => write!(f, "Topology error: {:?}", e),
            Self::Abort(e) => write!(f, "Abort error: {:?}", e),
            Self::StateSnapshot(e) => write!(f, "StateSnapshot error: {:?}", e),
            Self::StateRestore(e) => write!(f, "StateRestore error: {:?}", e),
            Self::TxCommit(e) => write!(f, "TxCommit error: {:?}", e),
            Self::TxAbort(e) => write!(f, "TxAbort error: {:?}", e),
            Self::Delegation(e) => write!(f, "Delegation error: {:?}", e),
            Self::RendezvousMismatch { expected, actual } => {
                write!(
                    f,
                    "Rendezvous ID mismatch: expected {}, got {}",
                    expected, actual
                )
            }
            Self::RendezvousMissing { id } => {
                write!(f, "Rendezvous {} is not registered", id)
            }
            Self::RendezvousBusy { id } => {
                write!(f, "Rendezvous {} is already leased", id)
            }
            Self::ReplayDetected { operation, nonce } => {
                write!(
                    f,
                    "Replay detected: operation {}, nonce {}",
                    operation, nonce
                )
            }
            Self::GenerationViolation { expected, actual } => {
                write!(
                    f,
                    "Generation ordering violation: expected {}, got {}",
                    expected, actual
                )
            }
            Self::ResourceExhausted { resource } => {
                write!(f, "Resource exhausted: {}", resource.as_str())
            }
            Self::Authorisation { operation } => {
                write!(f, "Operation not authorised: {}", operation)
            }
            Self::UnsupportedEffect(op) => write!(f, "Unsupported effect: {}", op),
            Self::LabelOutOfUniverse { max, actual } => write!(
                f,
                "Program label {} exceeds rendezvous label universe {}",
                actual, max
            ),
            Self::PolicyAbort { reason } => write!(f, "Policy abort requested (reason {})", reason),
            Self::ResourceMismatch { expected, actual } => {
                write!(
                    f,
                    "Resource kind mismatch: expected tag {}, got {}",
                    expected, actual
                )
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for CpError {}

// Conversions for ergonomic error propagation
impl From<TopologyError> for CpError {
    fn from(e: TopologyError) -> Self {
        Self::Topology(e)
    }
}

impl From<AbortError> for CpError {
    fn from(e: AbortError) -> Self {
        Self::Abort(e)
    }
}

impl From<StateSnapshotError> for CpError {
    fn from(e: StateSnapshotError) -> Self {
        Self::StateSnapshot(e)
    }
}

impl From<StateRestoreError> for CpError {
    fn from(e: StateRestoreError) -> Self {
        Self::StateRestore(e)
    }
}

impl From<TxCommitError> for CpError {
    fn from(e: TxCommitError) -> Self {
        Self::TxCommit(e)
    }
}

impl From<TxAbortError> for CpError {
    fn from(e: TxAbortError) -> Self {
        Self::TxAbort(e)
    }
}

impl From<DelegationError> for CpError {
    fn from(e: DelegationError) -> Self {
        Self::Delegation(e)
    }
}

// Tests use `format!` which requires `alloc`/`std`. Gate them behind `std` so
// that rust-analyzer (no_std default) doesn't flag errors, while CI runs them
// under `--all-features` (which enables `std`).
#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;

    #[test]
    fn test_error_conversions() {
        let topology_err: CpError = TopologyError::InvalidSession.into();
        assert!(matches!(topology_err, CpError::Topology(_)));

        let abort_err: CpError = AbortError::SessionNotFound.into();
        assert!(matches!(abort_err, CpError::Abort(_)));
    }

    #[test]
    fn test_error_display() {
        let err = CpError::RendezvousMismatch {
            expected: 1,
            actual: 2,
        };
        let s = format!("{}", err);
        assert!(s.contains("expected 1"));
        assert!(s.contains("got 2"));
    }
}