From f96f831b611eb07c2f2a86a055607cd11b2cba57 Mon Sep 17 00:00:00 2001 From: Damian Peckett Date: Sat, 17 Feb 2024 11:57:22 +0100 Subject: [PATCH] refactor: simplify the NewMutex() method --- README.md | 5 +---- examples/main.go | 5 +---- mutex.go | 5 +++-- mutex_test.go | 7 ++----- 4 files changed, 7 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 62971b1..af76930 100644 --- a/README.md +++ b/README.md @@ -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 { diff --git a/examples/main.go b/examples/main.go index 26e8f9d..0ff3530 100644 --- a/examples/main.go +++ b/examples/main.go @@ -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) diff --git a/mutex.go b/mutex.go index c0c9f8b..2ef72ce 100644 --- a/mutex.go +++ b/mutex.go @@ -30,6 +30,7 @@ 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"` @@ -37,13 +38,13 @@ type mutexContent struct { } // 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. diff --git a/mutex_test.go b/mutex_test.go index db80a38..91edbbc 100644 --- a/mutex_test.go +++ b/mutex_test.go @@ -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) @@ -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?