Skip to content

Commit 8dce106

Browse files
committed
Replace ctxLock with simple channel operations
This was a lot of documentation and untested logic for what seems like a fairly simple pattern. At the very least, I want to try it this way and see if I dislike it 5 more years from now.
1 parent 277d1be commit 8dce106

File tree

1 file changed

+5
-44
lines changed

1 file changed

+5
-44
lines changed

internal/slack/token.go

Lines changed: 5 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"errors"
66
"fmt"
77
"os"
8-
"sync"
98
"time"
109

1110
"github.com/aws/aws-sdk-go-v2/aws"
@@ -71,16 +70,18 @@ func StaticToken(token string) TokenProvider {
7170
// token value for the provided TTL.
7271
func AWSParameter(name string, ttl time.Duration) TokenProvider {
7372
var (
74-
mu ctxLock
73+
lock = make(chan struct{}, 1)
7574
token string
7675
expiry time.Time
7776
)
7877

7978
return func(ctx context.Context) (string, error) {
80-
if !mu.LockWithContext(ctx) {
79+
select {
80+
case lock <- struct{}{}:
81+
defer func() { <-lock }()
82+
case <-ctx.Done():
8183
return "", ctx.Err()
8284
}
83-
defer mu.Unlock()
8485

8586
if time.Now().Before(expiry) {
8687
return token, nil
@@ -104,43 +105,3 @@ func AWSParameter(name string, ttl time.Duration) TokenProvider {
104105
return token, nil
105106
}
106107
}
107-
108-
// ctxLock is a mutual exclusion lock that allows clients to cancel a pending
109-
// lock operation with a context. The zero value is an unlocked lock.
110-
type ctxLock struct {
111-
init sync.Once
112-
ch chan struct{} // buffered, size 1
113-
}
114-
115-
// LockWithContext attempts to lock l. If the lock is already in use, the
116-
// calling goroutine blocks until l is available or ctx is canceled. The return
117-
// value indicates whether the lock was actually acquired; if false, ctx was
118-
// canceled before the lock was acquired, and the caller must not unlock l or
119-
// violate any invariant that l protects.
120-
func (l *ctxLock) LockWithContext(ctx context.Context) bool {
121-
l.ensureInit()
122-
select {
123-
case <-l.ch:
124-
return true
125-
case <-ctx.Done():
126-
return false
127-
}
128-
}
129-
130-
// Unlock unlocks l.
131-
func (l *ctxLock) Unlock() {
132-
l.ensureInit()
133-
select {
134-
case l.ch <- struct{}{}:
135-
return
136-
default:
137-
panic("unlock of unlocked ctxLock")
138-
}
139-
}
140-
141-
func (l *ctxLock) ensureInit() {
142-
l.init.Do(func() {
143-
l.ch = make(chan struct{}, 1)
144-
l.ch <- struct{}{}
145-
})
146-
}

0 commit comments

Comments
 (0)