43 lines
861 B
Go
43 lines
861 B
Go
package application
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"enkly/pkg/authsupport"
|
|
)
|
|
|
|
// throttle replaces Handlers.throttle (see the same helper in the iam
|
|
// service's application package for the full doc comment — identical
|
|
// behavior, duplicated rather than shared because it's five lines and
|
|
// not worth a dependency between two bounded contexts).
|
|
func throttle(ctx context.Context, l *authsupport.Limiter, keys ...string) bool {
|
|
var wait time.Duration
|
|
for _, k := range keys {
|
|
if d := l.Delay(k); d > wait {
|
|
wait = d
|
|
}
|
|
}
|
|
if !sleepCtx(ctx, wait) {
|
|
return false
|
|
}
|
|
for _, k := range keys {
|
|
l.RecordFailure(k)
|
|
}
|
|
return true
|
|
}
|
|
|
|
func sleepCtx(ctx context.Context, d time.Duration) bool {
|
|
if d <= 0 {
|
|
return ctx.Err() == nil
|
|
}
|
|
t := time.NewTimer(d)
|
|
defer t.Stop()
|
|
select {
|
|
case <-t.C:
|
|
return true
|
|
case <-ctx.Done():
|
|
return false
|
|
}
|
|
}
|