summaryrefslogtreecommitdiff
path: root/internal/filelock/filelock.go
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2026-04-13 08:09:33 +0300
committerPaul Buetow <paul@buetow.org>2026-04-13 08:10:16 +0300
commitf2dd8d8a515c1a2a220836231ad1a671a5e9b73d (patch)
tree5b19585afb01b60d03d24a96b57bc7b986ea4cc0 /internal/filelock/filelock.go
parent56002ff942de1bfb0ce467ec37a692b8c4ca01e9 (diff)
ask: serialize concurrent CLI with repo lock and stale PID recovery
Add advisory lock under .git/hexai-ask.lock around Taskwarrior execution, with metadata (PID and process basename) and Linux /proc comm checks to remove orphan lock files when the recorded holder is gone or not ask. Extract internal/filelock for shared flock helpers; stats uses it too. Made-with: Cursor
Diffstat (limited to 'internal/filelock/filelock.go')
-rw-r--r--internal/filelock/filelock.go45
1 files changed, 45 insertions, 0 deletions
diff --git a/internal/filelock/filelock.go b/internal/filelock/filelock.go
new file mode 100644
index 0000000..192c3ca
--- /dev/null
+++ b/internal/filelock/filelock.go
@@ -0,0 +1,45 @@
+// Package filelock provides advisory exclusive locks on open files.
+package filelock
+
+import (
+ "context"
+ "errors"
+ "os"
+ "time"
+)
+
+// ErrWouldBlock indicates a non-blocking lock attempt could not acquire the lock.
+var ErrWouldBlock = errors.New("filelock: would block")
+
+// TryExclusive attempts a non-blocking exclusive advisory lock on f.
+func TryExclusive(f *os.File) error {
+ return tryLockExclusive(f.Fd())
+}
+
+// UnlockExclusive releases the advisory lock held on f.
+func UnlockExclusive(f *os.File) error {
+ return unlockExclusive(f.Fd())
+}
+
+// AcquireExclusive spins with TryExclusive until the lock is acquired, ctx is done, or a non-would-block error occurs.
+func AcquireExclusive(ctx context.Context, f *os.File) (func() error, error) {
+ fd := f.Fd()
+ retryTimer := time.NewTimer(5 * time.Millisecond)
+ defer retryTimer.Stop()
+ for {
+ err := tryLockExclusive(fd)
+ if err == nil {
+ return func() error { return unlockExclusive(fd) }, nil
+ }
+ if errors.Is(err, ErrWouldBlock) {
+ retryTimer.Reset(5 * time.Millisecond)
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-retryTimer.C:
+ }
+ continue
+ }
+ return nil, err
+ }
+}