Skip to main content

backbone_bucket/domain/entity/
file_lock.ext.rs

1//! The extension of `file_lock.rs` (hand-written; ADR-0031).
2
3#[allow(unused_imports)]
4use super::*;
5
6impl FileLock {
7
8    // ==========================================================
9    // DDD Entity Methods
10    // ==========================================================
11
12    /// Check if lock is still valid (active status and not yet expired)
13    pub fn is_valid(&self) -> bool {
14        self.status == LockStatus::Active && !self.is_expired()
15    }
16
17    /// Check if lock has expired (expires_at is at or before the current time)
18    pub fn is_expired(&self) -> bool {
19        self.expires_at <= Utc::now()
20    }
21
22    /// Check if lock belongs to the given user
23    pub fn is_owned_by(&self, user_id: Uuid) -> bool {
24        self.user_id == user_id
25    }
26
27    /// Check if lock can be refreshed (must be currently valid)
28    pub fn can_refresh(&self) -> bool {
29        self.is_valid()
30    }
31
32    /// Refresh lock expiry time by extending it by the given duration
33    pub fn refresh(&mut self, duration: Duration) -> Result<(), LockError> {
34        if !self.can_refresh() {
35            return Err(LockError::ValidationFailed(
36                "Cannot refresh lock: lock is not active or has expired".to_string(),
37            ));
38        }
39
40        let now = Utc::now();
41        self.expires_at = now + duration;
42        self.refreshed_at = Some(now);
43        self.metadata.touch();
44
45        Ok(())
46    }
47
48    /// Get remaining time until expiry. Returns zero duration if already expired.
49    pub fn time_remaining(&self) -> Duration {
50        let remaining = self.expires_at - Utc::now();
51        if remaining < Duration::zero() {
52            Duration::zero()
53        } else {
54            remaining
55        }
56    }
57
58    /// Check all business invariants
59    pub fn check_invariants(&self) -> Result<(), Vec<&'static str>> {
60        let mut errors = Vec::new();
61
62        // Invariant 1: expires_at must be after locked_at
63        if self.expires_at <= self.locked_at {
64            errors.push("expires_at must be after locked_at");
65        }
66
67        // Invariant 2: if status is Active, it must not be expired
68        if self.status == LockStatus::Active && self.is_expired() {
69            errors.push("active lock must not be expired (expires_at must be in the future)");
70        }
71
72        if errors.is_empty() { Ok(()) } else { Err(errors) }
73    }
74}