Skip to content

Commit

Permalink
Merge pull request #3 from pamburus/feature/try-lock
Browse files Browse the repository at this point in the history
new: TryLock
  • Loading branch information
ssgreg committed Oct 1, 2019
2 parents b90daa1 + 21753b9 commit 5668d21
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
4 changes: 4 additions & 0 deletions discard_vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@ func (v *discardVault) Lock(context.Context, Tx) error {
return nil
}

func (v *discardVault) TryLock(context.Context, Tx) (bool, error) {
return true, nil
}

func (v *discardVault) Unlock(Tx) {
}
1 change: 1 addition & 0 deletions stl.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,6 @@ type Builder interface {
// the specified transaction.
type Vault interface {
Lock(context.Context, Tx) error
TryLock(context.Context, Tx) (bool, error)
Unlock(Tx)
}
24 changes: 24 additions & 0 deletions stl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,3 +372,27 @@ func TestMergeTx(t *testing.T) {
require.ElementsMatch(t, expectedExs, tx.ListExclusive())
require.ElementsMatch(t, expectedShs, tx.ListShared())
}

func TestTryLock(t *testing.T) {
v := NewVault()
tx1 := NewStacked().Shared("resource1").ToTx()
ok, err := v.TryLock(context.Background(), tx1)
require.NoError(t, err)
require.True(t, ok)
defer v.Unlock(tx1)

tx2 := NewStacked().Exclusive("resource1").ToTx()
ok, err = v.TryLock(context.Background(), tx2)
require.NoError(t, err)
require.False(t, ok)
}

func TestDiscardVault(t *testing.T) {
v := NewDiscardVault()
err := v.Lock(context.Background(), nil)
require.NoError(t, err)
v.Unlock(nil)
ok, err := v.TryLock(context.Background(), nil)
require.NoError(t, err)
require.True(t, ok)
}
5 changes: 5 additions & 0 deletions vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ func (v *vault) Lock(ctx context.Context, tx Tx) error {
}
}

// TryLock tries to lock the resources according to specified Tx.
func (v *vault) TryLock(ctx context.Context, tx Tx) (bool, error) {
return v.tryLock(tx) == nil, nil
}

// Unlock unlocks the resources according to specified Tx.
func (v *vault) Unlock(tx Tx) {
v.mu.Lock()
Expand Down

0 comments on commit 5668d21

Please sign in to comment.