graph_d 1.3.2

A native graph database implementation in Rust with built-in JSON support and SQLite-like simplicity
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
//! Concurrency control for multi-threaded transactions.

use crate::error::{GraphError, Result};
use crate::graph::Id;
use crate::transaction::{Transaction, TransactionId};
use parking_lot::{Mutex, RwLock};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Lock types for different operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LockType {
    /// Shared read lock
    Read,
    /// Exclusive write lock
    Write,
}

/// Resource that can be locked (nodes, relationships, etc.).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LockableResource {
    /// Node with given ID
    Node(Id),
    /// Relationship with given ID
    Relationship(Id),
    /// Global graph structure
    Schema,
}

/// Lock information tracking.
#[derive(Debug, Clone)]
pub struct LockInfo {
    /// Unique identifier of the transaction holding this lock
    pub transaction_id: TransactionId,
    /// Type of lock (read or write)
    pub lock_type: LockType,
    /// Timestamp when the lock was acquired
    pub acquired_at: Instant,
    /// The resource that is locked
    pub resource: LockableResource,
}

/// Lock manager for coordinating concurrent access to graph resources.
pub struct LockManager {
    /// Currently held locks: resource -> set of lock info
    active_locks: Arc<RwLock<HashMap<LockableResource, Vec<LockInfo>>>>,
    /// Lock requests waiting for resources
    waiting_locks: Arc<Mutex<Vec<LockRequest>>>,
    /// Deadlock detection interval
    #[allow(dead_code)]
    deadlock_check_interval: Duration,
}

/// A lock request waiting to be granted.
#[derive(Debug, Clone)]
pub struct LockRequest {
    /// Unique identifier of the requesting transaction
    pub transaction_id: TransactionId,
    /// The resource being requested
    pub resource: LockableResource,
    /// Type of lock being requested (read or write)
    pub lock_type: LockType,
    /// Timestamp when the request was made
    pub requested_at: Instant,
}

impl LockManager {
    /// Create a new lock manager.
    pub fn new() -> Self {
        LockManager {
            active_locks: Arc::new(RwLock::new(HashMap::new())),
            waiting_locks: Arc::new(Mutex::new(Vec::new())),
            deadlock_check_interval: Duration::from_millis(100),
        }
    }

    /// Acquire a lock on a resource for a transaction.
    pub fn acquire_lock(
        &self,
        transaction_id: TransactionId,
        resource: LockableResource,
        lock_type: LockType,
        timeout: Option<Duration>,
    ) -> Result<bool> {
        let start_time = Instant::now();
        let timeout = timeout.unwrap_or(Duration::from_secs(30));

        loop {
            // Try to acquire the lock immediately
            if self.try_acquire_lock(transaction_id, resource, lock_type)? {
                return Ok(true);
            }

            // Check timeout
            if start_time.elapsed() > timeout {
                return Err(GraphError::Concurrency(format!(
                    "Lock acquisition timeout for transaction {transaction_id} on resource {resource:?}"
                )));
            }

            // Add to waiting queue
            self.add_to_waiting_queue(transaction_id, resource, lock_type);

            // Check for deadlocks
            if self.detect_deadlock(transaction_id)? {
                return Err(GraphError::Concurrency(format!(
                    "Deadlock detected involving transaction {transaction_id}"
                )));
            }

            // Wait a bit before retrying
            std::thread::sleep(Duration::from_millis(10));
        }
    }

    /// Try to acquire a lock immediately without waiting.
    fn try_acquire_lock(
        &self,
        transaction_id: TransactionId,
        resource: LockableResource,
        lock_type: LockType,
    ) -> Result<bool> {
        let mut locks = self.active_locks.write();
        let existing_locks = locks.get(&resource).cloned().unwrap_or_default();

        // Check if the lock can be acquired
        if self.can_acquire_lock(&existing_locks, lock_type) {
            let lock_info = LockInfo {
                transaction_id,
                lock_type,
                acquired_at: Instant::now(),
                resource,
            };

            locks.entry(resource).or_default().push(lock_info);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Check if a lock can be acquired given existing locks.
    fn can_acquire_lock(&self, existing_locks: &[LockInfo], requested_type: LockType) -> bool {
        if existing_locks.is_empty() {
            return true;
        }

        match requested_type {
            LockType::Read => {
                // Read locks can coexist with other read locks
                existing_locks
                    .iter()
                    .all(|lock| lock.lock_type == LockType::Read)
            }
            LockType::Write => {
                // Write locks are exclusive
                existing_locks.is_empty()
            }
        }
    }

    /// Add a lock request to the waiting queue.
    fn add_to_waiting_queue(
        &self,
        transaction_id: TransactionId,
        resource: LockableResource,
        lock_type: LockType,
    ) {
        let mut waiting = self.waiting_locks.lock();

        // Avoid duplicate requests
        if !waiting.iter().any(|req| {
            req.transaction_id == transaction_id
                && req.resource == resource
                && req.lock_type == lock_type
        }) {
            waiting.push(LockRequest {
                transaction_id,
                resource,
                lock_type,
                requested_at: Instant::now(),
            });
        }
    }

    /// Release all locks held by a transaction.
    pub fn release_all_locks(&self, transaction_id: TransactionId) -> Result<()> {
        let mut locks = self.active_locks.write();

        // Remove all locks held by this transaction
        for (_resource, lock_list) in locks.iter_mut() {
            lock_list.retain(|lock| lock.transaction_id != transaction_id);
        }

        // Remove empty entries
        locks.retain(|_resource, lock_list| !lock_list.is_empty());

        // Remove from waiting queue
        let mut waiting = self.waiting_locks.lock();
        waiting.retain(|req| req.transaction_id != transaction_id);

        Ok(())
    }

    /// Release a specific lock held by a transaction.
    pub fn release_lock(
        &self,
        transaction_id: TransactionId,
        resource: LockableResource,
    ) -> Result<()> {
        let mut locks = self.active_locks.write();

        if let Some(lock_list) = locks.get_mut(&resource) {
            lock_list.retain(|lock| {
                !(lock.transaction_id == transaction_id && lock.resource == resource)
            });

            if lock_list.is_empty() {
                locks.remove(&resource);
            }
        }

        Ok(())
    }

    /// Simple deadlock detection using wait-for graph.
    fn detect_deadlock(&self, transaction_id: TransactionId) -> Result<bool> {
        let locks = self.active_locks.read();
        let waiting = self.waiting_locks.lock();

        // Build wait-for graph
        let mut wait_for: HashMap<TransactionId, HashSet<TransactionId>> = HashMap::new();

        for request in waiting.iter() {
            if let Some(holders) = locks.get(&request.resource) {
                let waiting_tx = request.transaction_id;
                let holder_txs: HashSet<TransactionId> = holders
                    .iter()
                    .map(|lock| lock.transaction_id)
                    .filter(|&id| id != waiting_tx)
                    .collect();

                if !holder_txs.is_empty() {
                    wait_for.insert(waiting_tx, holder_txs);
                }
            }
        }

        // Check for cycles using DFS
        let mut visited = HashSet::new();
        let mut rec_stack = HashSet::new();

        self.has_cycle_dfs(transaction_id, &wait_for, &mut visited, &mut rec_stack)
    }

    /// DFS-based cycle detection.
    #[allow(clippy::only_used_in_recursion)]
    fn has_cycle_dfs(
        &self,
        node: TransactionId,
        graph: &HashMap<TransactionId, HashSet<TransactionId>>,
        visited: &mut HashSet<TransactionId>,
        rec_stack: &mut HashSet<TransactionId>,
    ) -> Result<bool> {
        visited.insert(node);
        rec_stack.insert(node);

        if let Some(neighbors) = graph.get(&node) {
            for &neighbor in neighbors {
                if !visited.contains(&neighbor) {
                    if self.has_cycle_dfs(neighbor, graph, visited, rec_stack)? {
                        return Ok(true);
                    }
                } else if rec_stack.contains(&neighbor) {
                    return Ok(true); // Cycle detected
                }
            }
        }

        rec_stack.remove(&node);
        Ok(false)
    }

    /// Get lock statistics for monitoring.
    pub fn get_lock_statistics(&self) -> LockStatistics {
        let locks = self.active_locks.read();
        let waiting = self.waiting_locks.lock();

        let total_active_locks = locks.values().map(|v| v.len()).sum();
        let waiting_requests = waiting.len();
        let locked_resources = locks.len();

        LockStatistics {
            total_active_locks,
            waiting_requests,
            locked_resources,
        }
    }
}

impl Default for LockManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Statistics about the current locking state.
#[derive(Debug, Clone)]
pub struct LockStatistics {
    /// Total number of locks currently held across all transactions
    pub total_active_locks: usize,
    /// Number of lock requests waiting to be granted
    pub waiting_requests: usize,
    /// Number of distinct resources that have at least one lock
    pub locked_resources: usize,
}

/// Enhanced transaction with concurrency control.
pub struct ConcurrentTransaction {
    /// Base transaction
    pub transaction: Transaction,
    /// Lock manager reference
    lock_manager: Arc<LockManager>,
    /// Locks held by this transaction
    held_locks: HashSet<LockableResource>,
}

impl ConcurrentTransaction {
    /// Create a new concurrent transaction.
    pub fn new(transaction: Transaction, lock_manager: Arc<LockManager>) -> Self {
        ConcurrentTransaction {
            transaction,
            lock_manager,
            held_locks: HashSet::new(),
        }
    }

    /// Acquire a read lock on a resource.
    pub fn read_lock(&mut self, resource: LockableResource) -> Result<()> {
        self.lock_manager.acquire_lock(
            self.transaction.id(),
            resource,
            LockType::Read,
            Some(Duration::from_secs(30)),
        )?;
        self.held_locks.insert(resource);
        Ok(())
    }

    /// Acquire a write lock on a resource.
    pub fn write_lock(&mut self, resource: LockableResource) -> Result<()> {
        self.lock_manager.acquire_lock(
            self.transaction.id(),
            resource,
            LockType::Write,
            Some(Duration::from_secs(30)),
        )?;
        self.held_locks.insert(resource);
        Ok(())
    }

    /// Commit the transaction and release all locks.
    pub fn commit(mut self) -> Result<()> {
        self.transaction.commit()?;
        self.lock_manager.release_all_locks(self.transaction.id())?;
        self.held_locks.clear();
        Ok(())
    }

    /// Rollback the transaction and release all locks.
    pub fn rollback(mut self) -> Result<()> {
        self.transaction.rollback()?;
        self.lock_manager.release_all_locks(self.transaction.id())?;
        self.held_locks.clear();
        Ok(())
    }

    /// Get the transaction ID.
    pub fn id(&self) -> TransactionId {
        self.transaction.id()
    }

    /// Check if the transaction is active.
    pub fn is_active(&self) -> bool {
        self.transaction.is_active()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::transaction::{IsolationLevel, TransactionManager};
    use std::time::Duration;

    #[test]
    fn test_lock_acquisition() {
        let lock_manager = LockManager::new();
        let tx_id = 1;
        let resource = LockableResource::Node(100);

        // Acquire read lock
        let result = lock_manager.acquire_lock(
            tx_id,
            resource,
            LockType::Read,
            Some(Duration::from_millis(100)),
        );
        assert!(result.is_ok());
        assert!(result.unwrap());

        // Acquire another read lock on same resource
        let result = lock_manager.acquire_lock(
            2,
            resource,
            LockType::Read,
            Some(Duration::from_millis(100)),
        );
        assert!(result.is_ok());
        assert!(result.unwrap());

        // Try to acquire write lock (should fail due to existing read locks)
        let result = lock_manager.acquire_lock(
            3,
            resource,
            LockType::Write,
            Some(Duration::from_millis(100)),
        );
        assert!(result.is_err());

        // Release locks
        lock_manager.release_all_locks(tx_id).unwrap();
        lock_manager.release_all_locks(2).unwrap();

        // Now write lock should succeed
        let result = lock_manager.acquire_lock(
            3,
            resource,
            LockType::Write,
            Some(Duration::from_millis(100)),
        );
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_concurrent_transaction() {
        let lock_manager = Arc::new(LockManager::new());
        let tx_manager = TransactionManager::new(IsolationLevel::ReadCommitted);

        let transaction = tx_manager.begin();
        let mut concurrent_tx = ConcurrentTransaction::new(transaction, lock_manager);

        let resource = LockableResource::Node(200);

        // Test locking
        assert!(concurrent_tx.read_lock(resource).is_ok());
        assert!(concurrent_tx
            .write_lock(LockableResource::Node(201))
            .is_ok());

        // Test commit
        assert!(concurrent_tx.commit().is_ok());
    }

    #[test]
    fn test_lock_statistics() {
        let lock_manager = LockManager::new();

        // Initially no locks
        let stats = lock_manager.get_lock_statistics();
        assert_eq!(stats.total_active_locks, 0);
        assert_eq!(stats.waiting_requests, 0);
        assert_eq!(stats.locked_resources, 0);

        // Acquire some locks
        lock_manager
            .acquire_lock(
                1,
                LockableResource::Node(100),
                LockType::Read,
                Some(Duration::from_millis(100)),
            )
            .unwrap();
        lock_manager
            .acquire_lock(
                2,
                LockableResource::Node(101),
                LockType::Write,
                Some(Duration::from_millis(100)),
            )
            .unwrap();

        let stats = lock_manager.get_lock_statistics();
        assert_eq!(stats.total_active_locks, 2);
        assert_eq!(stats.locked_resources, 2);
    }
}