|
| 1 | +//! Distributed deadlock detection via call-edge tracking. |
| 2 | +//! |
| 3 | +//! When database A calls a reducer on database B, the edge A -> B is registered |
| 4 | +//! with the control DB. If inserting the edge creates a cycle in the call graph, |
| 5 | +//! the call that created the cycle is cancelled. |
| 6 | +//! |
| 7 | +//! The [`CallEdgeTracker`] trait provides the interface. Standalone uses a no-op |
| 8 | +//! implementation; cloud implements cycle detection via the control DB. |
| 9 | +
|
| 10 | +use spacetimedb_lib::Identity; |
| 11 | + |
| 12 | +/// Error returned when registering a call edge would create a cycle. |
| 13 | +#[derive(Debug)] |
| 14 | +pub struct CycleDetected; |
| 15 | + |
| 16 | +impl std::fmt::Display for CycleDetected { |
| 17 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 18 | + write!(f, "distributed deadlock detected: call would create a cycle") |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +impl std::error::Error for CycleDetected {} |
| 23 | + |
| 24 | +/// Tracks cross-database call edges for distributed deadlock detection. |
| 25 | +/// |
| 26 | +/// Methods are blocking (not async) because they are called from the database |
| 27 | +/// thread, which must not enter an async runtime. |
| 28 | +pub trait CallEdgeTracker: Send + Sync { |
| 29 | + /// Register that `caller` is about to call a reducer on `target`. |
| 30 | + /// |
| 31 | + /// Returns `Err(CycleDetected)` if the edge would create a cycle in the |
| 32 | + /// call graph (i.e. `target` is already waiting, directly or transitively, |
| 33 | + /// for `caller`). |
| 34 | + fn register_edge(&self, caller: Identity, target: Identity) -> Result<(), CycleDetected>; |
| 35 | + |
| 36 | + /// Remove the edge after the call completes (success or failure). |
| 37 | + fn unregister_edge(&self, caller: Identity, target: Identity); |
| 38 | + |
| 39 | + /// Check whether a pending call from `caller` to `target` has been |
| 40 | + /// asynchronously cancelled (e.g. because a cycle was detected after |
| 41 | + /// the edge was registered). |
| 42 | + fn is_cancelled(&self, caller: Identity, target: Identity) -> bool; |
| 43 | +} |
| 44 | + |
| 45 | +/// No-op implementation for standalone (single-node) deployments. |
| 46 | +/// |
| 47 | +/// Always succeeds, never detects cycles. Distributed deadlocks are not |
| 48 | +/// possible when the control DB is not involved. |
| 49 | +pub struct NoopCallEdgeTracker; |
| 50 | + |
| 51 | +impl CallEdgeTracker for NoopCallEdgeTracker { |
| 52 | + fn register_edge(&self, _caller: Identity, _target: Identity) -> Result<(), CycleDetected> { |
| 53 | + Ok(()) |
| 54 | + } |
| 55 | + |
| 56 | + fn unregister_edge(&self, _caller: Identity, _target: Identity) {} |
| 57 | + |
| 58 | + fn is_cancelled(&self, _caller: Identity, _target: Identity) -> bool { |
| 59 | + false |
| 60 | + } |
| 61 | +} |
0 commit comments