Repository navigation
lock state file writes #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e568d7f
add file locking to prevent concurrent stack file edits
skarim 211e563
lock failure exit code
skarim 37e32a5
only lock for writes
skarim 629ea06
non-blocking saves for non-critical writes
skarim d5bb33e
additional lock file test
skarim fc4528b
protect against time of check vs use race condition
skarim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| package stack | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "os" | ||
| "path/filepath" | ||
| "time" | ||
| ) | ||
|
|
||
| const lockFileName = "gh-stack.lock" | ||
|
|
||
| // LockError is returned when the stack file lock cannot be acquired. | ||
| // Callers can check for this with errors.As to distinguish lock failures | ||
| // from other errors. | ||
| type LockError struct { | ||
| Err error | ||
| } | ||
|
|
||
| func (e *LockError) Error() string { return e.Err.Error() } | ||
| func (e *LockError) Unwrap() error { return e.Err } | ||
|
skarim marked this conversation as resolved.
Resolved
|
||
|
|
||
| // LockTimeout is how long Lock() will wait for the exclusive lock before | ||
| // giving up. With the lock held only during file writes (milliseconds), | ||
| // this timeout primarily guards against stuck or orphaned lock files. | ||
|
skarim marked this conversation as resolved.
Resolved
|
||
| const LockTimeout = 5 * time.Second | ||
|
|
||
| // lockRetryInterval is the sleep between non-blocking lock attempts. | ||
| const lockRetryInterval = 100 * time.Millisecond | ||
|
|
||
| // FileLock provides an exclusive advisory lock on the stack file to prevent | ||
| // concurrent Load-Modify-Save races between multiple gh-stack processes. | ||
| type FileLock struct { | ||
| f *os.File | ||
| } | ||
|
|
||
| // Lock acquires an exclusive lock on the stack file in the given git directory. | ||
| // It retries with a non-blocking attempt every 100ms for up to LockTimeout. | ||
| // | ||
| // Most callers should not use Lock directly — stack.Save() acquires the lock | ||
| // automatically. Use Lock only when you need to hold the lock across multiple | ||
| // operations (e.g. Load-Modify-Save as an atomic unit). | ||
|
skarim marked this conversation as resolved.
Resolved
|
||
| func Lock(gitDir string) (*FileLock, error) { | ||
| path := filepath.Join(gitDir, lockFileName) | ||
| f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("opening lock file: %w", err) | ||
| } | ||
|
|
||
| deadline := time.Now().Add(LockTimeout) | ||
| for { | ||
| err := tryLockFile(f) | ||
| if err == nil { | ||
| return &FileLock{f: f}, nil | ||
| } | ||
| if time.Now().After(deadline) { | ||
| f.Close() | ||
| return nil, fmt.Errorf("timed out waiting for stack lock after %s — another gh-stack process may be running", LockTimeout) | ||
| } | ||
| time.Sleep(lockRetryInterval) | ||
| } | ||
|
skarim marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| // Unlock releases the lock. The lock file is intentionally left on disk to | ||
| // avoid a race where another process opens the same path, blocks on flock, | ||
| // then wakes up holding a lock on an unlinked inode while a third process | ||
| // creates a new file and locks a different inode. | ||
| func (l *FileLock) Unlock() { | ||
| if l == nil || l.f == nil { | ||
| return | ||
| } | ||
| unlockFile(l.f) | ||
| l.f.Close() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| package stack | ||
|
|
||
| import ( | ||
| "sync" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestLock_Basic(t *testing.T) { | ||
| dir := t.TempDir() | ||
|
|
||
| lock, err := Lock(dir) | ||
| require.NoError(t, err) | ||
| require.NotNil(t, lock) | ||
|
|
||
| lock.Unlock() | ||
| } | ||
|
|
||
| func TestLock_NilUnlockSafe(t *testing.T) { | ||
| // Unlock on nil should not panic. | ||
| var lock *FileLock | ||
| lock.Unlock() | ||
| } | ||
|
|
||
| func TestLock_BlocksUntilReleased(t *testing.T) { | ||
| dir := t.TempDir() | ||
|
|
||
| lock1, err := Lock(dir) | ||
| require.NoError(t, err) | ||
|
|
||
| acquired := make(chan struct{}) | ||
| go func() { | ||
| lock2, err := Lock(dir) | ||
| require.NoError(t, err) | ||
| close(acquired) | ||
| lock2.Unlock() | ||
| }() | ||
|
skarim marked this conversation as resolved.
Resolved
|
||
|
|
||
| // lock2 should be blocked while lock1 is held. | ||
| select { | ||
| case <-acquired: | ||
| t.Fatal("lock2 acquired while lock1 was still held") | ||
| case <-time.After(300 * time.Millisecond): | ||
| // expected — lock2 is waiting | ||
| } | ||
|
|
||
| lock1.Unlock() | ||
|
|
||
| // After releasing lock1, lock2 should acquire promptly. | ||
| select { | ||
| case <-acquired: | ||
| // success | ||
| case <-time.After(5 * time.Second): | ||
| t.Fatal("lock2 did not acquire after lock1 was released") | ||
| } | ||
| } | ||
|
|
||
| func TestLock_SerializesConcurrentAccess(t *testing.T) { | ||
| dir := t.TempDir() | ||
|
|
||
| // Write an initial stack file with 0 stacks. | ||
| sf := &StackFile{SchemaVersion: 1, Stacks: []Stack{}} | ||
| require.NoError(t, Save(dir, sf)) | ||
|
|
||
| // Run 10 concurrent goroutines, each adding a stack under lock. | ||
| // Uses Lock + Load + SaveLocked for atomic read-modify-write. | ||
| var wg sync.WaitGroup | ||
| for i := 0; i < 10; i++ { | ||
| wg.Add(1) | ||
| go func(idx int) { | ||
| defer wg.Done() | ||
|
|
||
| lock, err := Lock(dir) | ||
| require.NoError(t, err) | ||
| defer lock.Unlock() | ||
|
|
||
| loaded, err := Load(dir) | ||
| require.NoError(t, err) | ||
|
|
||
| loaded.AddStack(makeStack("main", "branch")) | ||
| require.NoError(t, SaveLocked(dir, loaded)) | ||
| }(i) | ||
| } | ||
| wg.Wait() | ||
|
skarim marked this conversation as resolved.
Resolved
|
||
|
|
||
| // All 10 stacks should be present — no lost updates. | ||
| final, err := Load(dir) | ||
| require.NoError(t, err) | ||
| assert.Len(t, final.Stacks, 10, "all concurrent writes should be preserved") | ||
| } | ||
|
|
||
| func TestLock_FileLeftOnDisk(t *testing.T) { | ||
| dir := t.TempDir() | ||
|
|
||
| lock, err := Lock(dir) | ||
| require.NoError(t, err) | ||
| lock.Unlock() | ||
|
|
||
| // Lock file should still exist after unlock (no os.Remove race). | ||
| lock2, err := Lock(dir) | ||
| require.NoError(t, err, "should be able to re-lock after unlock") | ||
| lock2.Unlock() | ||
| } | ||
|
skarim marked this conversation as resolved.
Resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| //go:build !windows | ||
|
|
||
| package stack | ||
|
|
||
| import ( | ||
| "os" | ||
| "syscall" | ||
| ) | ||
|
|
||
| // tryLockFile attempts a non-blocking exclusive lock. | ||
| // Returns nil on success, or an error if the lock is held by another process. | ||
| func tryLockFile(f *os.File) error { | ||
| return syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) | ||
| } | ||
|
|
||
| func unlockFile(f *os.File) { | ||
| _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| //go:build windows | ||
|
|
||
| package stack | ||
|
|
||
| import ( | ||
| "os" | ||
|
|
||
| "golang.org/x/sys/windows" | ||
| ) | ||
|
|
||
| // tryLockFile attempts a non-blocking exclusive lock. | ||
| // Returns nil on success, or an error if the lock is held by another process. | ||
| func tryLockFile(f *os.File) error { | ||
| ol := new(windows.Overlapped) | ||
| return windows.LockFileEx( | ||
| windows.Handle(f.Fd()), | ||
| windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, | ||
| 0, // reserved | ||
| 1, // lock 1 byte | ||
| 0, // high word | ||
| ol, | ||
| ) | ||
| } | ||
|
|
||
| func unlockFile(f *os.File) { | ||
| ol := new(windows.Overlapped) | ||
| _ = windows.UnlockFileEx( | ||
| windows.Handle(f.Fd()), | ||
| 0, 1, 0, ol, | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.