libgrite-git 0.5.3

Git WAL, sync, and snapshot operations for grite
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
//! Lock manager for git ref-based locks
//!
//! Locks are stored as git refs at `refs/grite/locks/<resource_hash>`.
//! Each ref points to a commit containing a blob with the lock JSON.

use std::path::Path;

use git2::{Repository, Signature};
use libgrite_core::{resource_hash, Lock, LockCheckResult, LockPolicy, DEFAULT_LOCK_TTL_MS};

use crate::GitError;

/// Internal error for lock acquire fast-path
enum LockAcquireError {
    /// Ref already exists
    Exists,
    /// Git error
    Git(GitError),
}

/// Statistics from lock garbage collection
#[derive(Debug, Clone, Default)]
pub struct LockGcStats {
    /// Number of expired locks removed
    pub removed: usize,
    /// Number of active locks kept
    pub kept: usize,
}

/// Manager for git ref-based locks
pub struct LockManager {
    repo: Repository,
}

impl LockManager {
    /// Open a lock manager for the given git directory
    pub fn open(git_dir: &Path) -> Result<Self, GitError> {
        let repo = Repository::open(git_dir)?;
        Ok(Self { repo })
    }

    /// Acquire a lock on a resource
    ///
    /// Returns the lock if acquired, or an error if a conflicting lock exists
    pub fn acquire(
        &self,
        resource: &str,
        owner: &str,
        ttl_ms: Option<u64>,
    ) -> Result<Lock, GitError> {
        let ttl = ttl_ms.unwrap_or(DEFAULT_LOCK_TTL_MS);
        let ref_name = lock_ref_name(resource);
        let lock = Lock::new(owner.to_string(), resource.to_string(), ttl);

        // Try atomic create-if-not-exists (fast path)
        match self.try_create_lock(&ref_name, &lock) {
            Ok(()) => Ok(lock),
            Err(LockAcquireError::Exists) => {
                // Slow path: read existing, handle expired / owned-by-us
                if let Some(existing) = self.read_lock(resource)? {
                    if !existing.is_expired() {
                        if existing.owner == owner {
                            // Already owned by this actor - return as-is
                            Ok(existing)
                        } else {
                            let expires_in_ms = existing.time_remaining_ms();
                            Err(GitError::LockConflict {
                                resource: resource.to_string(),
                                owner: existing.owner,
                                expires_in_ms,
                            })
                        }
                    } else {
                        // Lock is expired - delete and retry
                        self.delete_ref(&ref_name)?;
                        match self.try_create_lock(&ref_name, &lock) {
                            Ok(()) => Ok(lock),
                            Err(LockAcquireError::Exists) => {
                                if let Some(other) = self.read_lock(resource)? {
                                    if !other.is_expired() {
                                        return Err(GitError::LockConflict {
                                            resource: resource.to_string(),
                                            owner: other.owner.clone(),
                                            expires_in_ms: other.time_remaining_ms(),
                                        });
                                    }
                                }
                                Err(GitError::LockConflict {
                                    resource: resource.to_string(),
                                    owner: "unknown".to_string(),
                                    expires_in_ms: 0,
                                })
                            }
                            Err(LockAcquireError::Git(e)) => Err(e),
                        }
                    }
                } else {
                    // Race: lock was deleted between read and delete
                    match self.try_create_lock(&ref_name, &lock) {
                        Ok(()) => Ok(lock),
                        Err(LockAcquireError::Exists) => {
                            if let Some(other) = self.read_lock(resource)? {
                                if !other.is_expired() {
                                    return Err(GitError::LockConflict {
                                        resource: resource.to_string(),
                                        owner: other.owner.clone(),
                                        expires_in_ms: other.time_remaining_ms(),
                                    });
                                }
                            }
                            Err(GitError::LockConflict {
                                resource: resource.to_string(),
                                owner: "unknown".to_string(),
                                expires_in_ms: 0,
                            })
                        }
                        Err(LockAcquireError::Git(e)) => Err(e),
                    }
                }
            }
            Err(LockAcquireError::Git(e)) => Err(e),
        }
    }

    /// Release a lock
    pub fn release(&self, resource: &str, owner: &str) -> Result<(), GitError> {
        let ref_name = lock_ref_name(resource);

        // Verify ownership
        if let Some(existing) = self.read_lock(resource)? {
            if existing.owner != owner && !existing.is_expired() {
                return Err(GitError::LockNotOwned {
                    resource: resource.to_string(),
                    owner: existing.owner,
                });
            }
        }

        // Delete the ref
        self.delete_ref(&ref_name)?;

        Ok(())
    }

    /// Renew a lock's expiration
    pub fn renew(
        &self,
        resource: &str,
        owner: &str,
        ttl_ms: Option<u64>,
    ) -> Result<Lock, GitError> {
        let ttl = ttl_ms.unwrap_or(DEFAULT_LOCK_TTL_MS);
        let ref_name = lock_ref_name(resource);

        // Verify ownership
        if let Some(mut existing) = self.read_lock(resource)? {
            if existing.owner != owner {
                return Err(GitError::LockNotOwned {
                    resource: resource.to_string(),
                    owner: existing.owner,
                });
            }

            // Renew the lock
            existing.renew(ttl);
            self.write_lock(&ref_name, &existing)?;
            return Ok(existing);
        }

        // Lock doesn't exist, acquire it
        self.acquire(resource, owner, Some(ttl))
    }

    /// Read a lock by resource
    pub fn read_lock(&self, resource: &str) -> Result<Option<Lock>, GitError> {
        let ref_name = lock_ref_name(resource);
        self.read_lock_ref(&ref_name)
    }

    /// List all locks
    pub fn list_locks(&self) -> Result<Vec<Lock>, GitError> {
        let mut locks = Vec::new();

        // Iterate over refs/grite/locks/*
        let refs = self.repo.references_glob("refs/grite/locks/*")?;
        for ref_result in refs {
            let reference = ref_result?;
            if let Some(lock) = self.read_lock_from_ref(&reference)? {
                locks.push(lock);
            }
        }

        Ok(locks)
    }

    /// Check for conflicts with a resource
    pub fn check_conflicts(
        &self,
        resource: &str,
        current_owner: &str,
        policy: LockPolicy,
    ) -> Result<LockCheckResult, GitError> {
        if policy == LockPolicy::Off {
            return Ok(LockCheckResult::Clear);
        }

        let locks = self.list_locks()?;
        let conflicts: Vec<Lock> = locks
            .into_iter()
            .filter(|lock| {
                !lock.is_expired() && lock.owner != current_owner && lock.conflicts_with(resource)
            })
            .collect();

        if conflicts.is_empty() {
            Ok(LockCheckResult::Clear)
        } else if policy == LockPolicy::Warn {
            Ok(LockCheckResult::Warning(conflicts))
        } else {
            Ok(LockCheckResult::Blocked(conflicts))
        }
    }

    /// Garbage collect expired locks
    pub fn gc(&self) -> Result<LockGcStats, GitError> {
        let mut stats = LockGcStats::default();

        let refs: Vec<_> = self
            .repo
            .references_glob("refs/grite/locks/*")?
            .collect::<Result<Vec<_>, _>>()?;

        for reference in refs {
            if let Some(lock) = self.read_lock_from_ref(&reference)? {
                if lock.is_expired() {
                    if let Some(name) = reference.name() {
                        self.delete_ref(name)?;
                        stats.removed += 1;
                    }
                } else {
                    stats.kept += 1;
                }
            }
        }

        Ok(stats)
    }

    /// Read lock from a ref
    fn read_lock_ref(&self, ref_name: &str) -> Result<Option<Lock>, GitError> {
        let reference = match self.repo.find_reference(ref_name) {
            Ok(r) => r,
            Err(e) if e.code() == git2::ErrorCode::NotFound => return Ok(None),
            Err(e) => return Err(e.into()),
        };

        self.read_lock_from_ref(&reference)
    }

    /// Read lock from a reference object
    fn read_lock_from_ref(&self, reference: &git2::Reference) -> Result<Option<Lock>, GitError> {
        let commit = reference.peel_to_commit()?;
        let tree = commit.tree()?;

        // Lock is stored in a file called "lock.json" in the tree
        let entry = match tree.get_name("lock.json") {
            Some(e) => e,
            None => return Ok(None),
        };

        let blob = self.repo.find_blob(entry.id())?;
        let content =
            std::str::from_utf8(blob.content()).map_err(|e| GitError::ParseError(e.to_string()))?;

        let lock: Lock =
            serde_json::from_str(content).map_err(|e| GitError::ParseError(e.to_string()))?;

        Ok(Some(lock))
    }

    /// Try to create a lock ref atomically (fail if it already exists).
    fn try_create_lock(&self, ref_name: &str, lock: &Lock) -> Result<(), LockAcquireError> {
        let commit_oid = self
            .write_lock_commit(lock)
            .map_err(LockAcquireError::Git)?;
        match self
            .repo
            .reference(ref_name, commit_oid, false, "lock acquire")
        {
            Ok(_) => Ok(()),
            Err(e) if e.code() == git2::ErrorCode::Exists => Err(LockAcquireError::Exists),
            Err(e) => Err(LockAcquireError::Git(e.into())),
        }
    }

    /// Create the commit for a lock and return its OID (does not update any ref).
    fn write_lock_commit(&self, lock: &Lock) -> Result<git2::Oid, GitError> {
        let json =
            serde_json::to_string_pretty(lock).map_err(|e| GitError::ParseError(e.to_string()))?;

        // Create blob
        let blob_id = self.repo.blob(json.as_bytes())?;

        // Create tree with lock.json
        let mut tree_builder = self.repo.treebuilder(None)?;
        tree_builder.insert("lock.json", blob_id, 0o100644)?;
        let tree_id = tree_builder.write()?;
        let tree = self.repo.find_tree(tree_id)?;

        // Create commit
        let sig = Signature::now("grite", "grit@localhost")?;
        let message = format!("Lock: {}", lock.resource);

        let parent = self
            .repo
            .find_reference(&lock_ref_name(&lock.resource))
            .ok()
            .and_then(|r| r.peel_to_commit().ok());

        let parents: Vec<&git2::Commit> = parent.iter().collect();

        let commit_oid = self
            .repo
            .commit(None, &sig, &sig, &message, &tree, &parents)?;

        Ok(commit_oid)
    }

    /// Write lock to a ref (overwrites existing).
    fn write_lock(&self, ref_name: &str, lock: &Lock) -> Result<(), GitError> {
        let commit_oid = self.write_lock_commit(lock)?;
        self.repo
            .reference(ref_name, commit_oid, true, "lock update")?;
        Ok(())
    }

    /// Delete a ref
    fn delete_ref(&self, ref_name: &str) -> Result<(), GitError> {
        match self.repo.find_reference(ref_name) {
            Ok(mut reference) => {
                reference.delete()?;
                Ok(())
            }
            Err(e) if e.code() == git2::ErrorCode::NotFound => Ok(()),
            Err(e) => Err(e.into()),
        }
    }
}

/// Get the ref name for a lock resource
fn lock_ref_name(resource: &str) -> String {
    format!("refs/grite/locks/{}", resource_hash(resource))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    fn setup_repo() -> tempfile::TempDir {
        let dir = tempdir().unwrap();
        let repo = Repository::init(dir.path()).unwrap();

        // Create initial commit
        let sig = Signature::now("test", "test@test.com").unwrap();
        let tree_id = repo.treebuilder(None).unwrap().write().unwrap();
        {
            let tree = repo.find_tree(tree_id).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "Initial", &tree, &[])
                .unwrap();
        }

        dir
    }

    #[test]
    fn test_acquire_and_release() {
        let dir = setup_repo();
        let manager = LockManager::open(dir.path()).unwrap();

        // Acquire lock
        let lock = manager
            .acquire("repo:global", "actor1", Some(60000))
            .unwrap();
        assert_eq!(lock.owner, "actor1");
        assert_eq!(lock.resource, "repo:global");
        assert!(!lock.is_expired());

        // Verify lock exists
        let read_lock = manager.read_lock("repo:global").unwrap().unwrap();
        assert_eq!(read_lock.owner, "actor1");

        // Release lock
        manager.release("repo:global", "actor1").unwrap();

        // Verify lock is gone
        let read_lock = manager.read_lock("repo:global").unwrap();
        assert!(read_lock.is_none());
    }

    #[test]
    fn test_acquire_conflict() {
        let dir = setup_repo();
        let manager = LockManager::open(dir.path()).unwrap();

        // Acquire lock as actor1
        manager
            .acquire("repo:global", "actor1", Some(60000))
            .unwrap();

        // Try to acquire as actor2 - should fail
        let result = manager.acquire("repo:global", "actor2", Some(60000));
        assert!(result.is_err());
    }

    #[test]
    fn test_renew_lock() {
        let dir = setup_repo();
        let manager = LockManager::open(dir.path()).unwrap();

        // Acquire lock
        let lock1 = manager
            .acquire("issue:abc123", "actor1", Some(1000))
            .unwrap();
        let expires1 = lock1.expires_unix_ms;

        // Wait a tiny bit
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Renew lock
        let lock2 = manager
            .renew("issue:abc123", "actor1", Some(60000))
            .unwrap();
        assert!(lock2.expires_unix_ms > expires1);
    }

    #[test]
    fn test_list_locks() {
        let dir = setup_repo();
        let manager = LockManager::open(dir.path()).unwrap();

        // Acquire multiple locks
        manager
            .acquire("repo:global", "actor1", Some(60000))
            .unwrap();
        manager
            .acquire("issue:abc123", "actor2", Some(60000))
            .unwrap();

        // List locks
        let locks = manager.list_locks().unwrap();
        assert_eq!(locks.len(), 2);
    }

    #[test]
    fn test_gc_expired() {
        let dir = setup_repo();
        let manager = LockManager::open(dir.path()).unwrap();

        // Acquire lock with very short TTL
        manager.acquire("issue:abc123", "actor1", Some(1)).unwrap();

        // Wait for it to expire
        std::thread::sleep(std::time::Duration::from_millis(10));

        // GC should remove it
        let stats = manager.gc().unwrap();
        assert_eq!(stats.removed, 1);
        assert_eq!(stats.kept, 0);

        // Verify lock is gone
        let locks = manager.list_locks().unwrap();
        assert!(locks.is_empty());
    }

    #[test]
    fn test_check_conflicts() {
        let dir = setup_repo();
        let manager = LockManager::open(dir.path()).unwrap();

        // Acquire repo lock
        manager
            .acquire("repo:global", "actor1", Some(60000))
            .unwrap();

        // Check conflicts for actor2
        let result = manager
            .check_conflicts("issue:abc123", "actor2", LockPolicy::Warn)
            .unwrap();
        assert!(matches!(result, LockCheckResult::Warning(_)));

        let result = manager
            .check_conflicts("issue:abc123", "actor2", LockPolicy::Require)
            .unwrap();
        assert!(matches!(result, LockCheckResult::Blocked(_)));

        // No conflict for actor1 (owner)
        let result = manager
            .check_conflicts("issue:abc123", "actor1", LockPolicy::Require)
            .unwrap();
        assert!(matches!(result, LockCheckResult::Clear));
    }
}