Skip to main content

ranvier_runtime/
distributed.rs

1use async_trait::async_trait;
2use std::fmt;
3
4/// Errors that can occur during distributed state operations.
5#[derive(Debug)]
6pub enum DistributedError {
7    StoreError(String),
8    LockError(String),
9    NotFound(String),
10}
11
12impl fmt::Display for DistributedError {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        match self {
15            Self::StoreError(e) => write!(f, "Store error: {}", e),
16            Self::LockError(e) => write!(f, "Lock error: {}", e),
17            Self::NotFound(e) => write!(f, "Not found: {}", e),
18        }
19    }
20}
21
22impl std::error::Error for DistributedError {}
23
24/// An abstraction for a distributed key-value store.
25#[async_trait]
26pub trait DistributedStore: Send + Sync {
27    /// Retrieve a value from the store.
28    async fn get(&self, domain: &str, key: &str) -> Result<Option<Vec<u8>>, DistributedError>;
29    
30    /// Set a value in the store, optionally with a time-to-live (in seconds).
31    async fn set(
32        &self,
33        domain: &str,
34        key: &str,
35        value: &[u8],
36        ttl_sec: Option<u64>,
37    ) -> Result<(), DistributedError>;
38    
39    /// Delete a value from the store.
40    async fn delete(&self, domain: &str, key: &str) -> Result<(), DistributedError>;
41}
42
43/// Options to attempt to acquire a distributed lock.
44#[derive(Debug, Clone)]
45pub struct LockOptions {
46    /// Time-to-live for the lock in milliseconds.
47    pub ttl_ms: u64,
48    /// Number of attempts to acquire the lock.
49    pub retry_count: u32,
50    /// Delay between retry attempts in milliseconds.
51    pub retry_delay_ms: u64,
52}
53
54impl Default for LockOptions {
55    fn default() -> Self {
56        Self {
57            ttl_ms: 10_000,
58            retry_count: 5,
59            retry_delay_ms: 200,
60        }
61    }
62}
63
64/// Representation of an acquired lock.
65#[derive(Debug, Clone)]
66pub struct Guard {
67    /// The unique resource identifier for this lock.
68    pub resource_key: String,
69    /// The specific token given to the lock owner.
70    pub token: String,
71}
72
73/// An abstraction for acquiring and releasing distributed locks.
74#[async_trait]
75pub trait DistributedLock: Send + Sync {
76    /// Attempt to acquire a distributed lock on a resource.
77    async fn acquire(
78        &self,
79        resource_key: &str,
80        options: LockOptions,
81    ) -> Result<Guard, DistributedError>;
82    
83    /// Release the acquired lock.
84    async fn release(&self, guard: Guard) -> Result<(), DistributedError>;
85    
86    /// Extend the TTL of the currently held lock.
87    async fn extend(&self, guard: &Guard, additional_ttl_ms: u64) -> Result<(), DistributedError>;
88}