Skip to content

Commit

Permalink
refactor: simplify the NewMutex() method
Browse files Browse the repository at this point in the history
  • Loading branch information
dpeckett committed Feb 17, 2024
1 parent 762cea6 commit f96f831
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 15 deletions.
5 changes: 1 addition & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ if err != nil {
panic(err)
}

mu, err := objsync.NewMutex(p, bucket, key)
if err != nil {
panic(err)
}
mu := objsync.NewMutex(p, bucket, key)

fencingToken, err := mu.Lock(ctx, 5*time.Second)
if err != nil {
Expand Down
5 changes: 1 addition & 4 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ func main() {
}

// Create a mutex.
mu, err := objsync.NewMutex(p, bucket, key)
if err != nil {
panic(err)
}
mu := objsync.NewMutex(p, bucket, key)

// Lock the mutex.
fencingToken, err := mu.Lock(ctx, 5*time.Second)
Expand Down
5 changes: 3 additions & 2 deletions mutex.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,21 @@ type Mutex struct {
etag string
}

// The JSON content of the mutex object.
type mutexContent struct {
ID string `json:"id,omitempty"`
Expires *time.Time `json:"expires,omitempty"`
Fence int64 `json:"fence,omitempty"`
}

// NewMutex creates a new distributed mutex.
func NewMutex(p provider.Provider, bucket, key string) (*Mutex, error) {
func NewMutex(p provider.Provider, bucket, key string) *Mutex {
return &Mutex{
provider: p,
bucket: bucket,
key: key,
id: uuid.New().String(),
}, nil
}
}

// Lock acquires the mutex. It blocks until the mutex is available.
Expand Down
7 changes: 2 additions & 5 deletions mutex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ func TestMutex(t *testing.T) {
g, ctx := errgroup.WithContext(ctx)
for i := 0; i < 3; i++ {
g.Go(func() error {
mu, err := objsync.NewMutex(p, bucket, key)
if err != nil {
return err
}
mu := objsync.NewMutex(p, bucket, key)

for j := 0; j < 5; j++ {
fencingToken, err := mu.Lock(ctx, 5*time.Second)
Expand All @@ -61,7 +58,7 @@ func TestMutex(t *testing.T) {

// Verify the mutex is held by only one goroutine.
if n := atomic.AddInt32(&lockCounter, 1); n > 1 {
return fmt.Errorf("lock is held by %d goroutines (fencingToken: %d)", n, fencingToken)
return fmt.Errorf("lock is held by %d goroutines", n)
}

// Is the fencing token monotonically increasing?
Expand Down

0 comments on commit f96f831

Please sign in to comment.