Throttling with bug
This commit is contained in:
56
throttling/rateLimit.go
Normal file
56
throttling/rateLimit.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package throttling
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const rateLimit = time.Second * 3 // a call each 3 second
|
||||
|
||||
// Client is an interface that calls something with a payload.
|
||||
type Client interface {
|
||||
Call(*Payload)
|
||||
}
|
||||
|
||||
// Payload is some payload a Client would send in a call.
|
||||
type Payload struct {
|
||||
ClientResult string
|
||||
W http.ResponseWriter
|
||||
R *http.Request
|
||||
}
|
||||
|
||||
// CallFunction allows burst rate limiting client calls with the
|
||||
// payloads.
|
||||
func CallFunction(ctx context.Context, client Client, payload *Payload, throttle <-chan time.Time) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
<-throttle // rate limit our client calls
|
||||
client.Call(payload)
|
||||
}
|
||||
|
||||
func CreateThrottle(ctx context.Context, burstLimit int) <-chan time.Time {
|
||||
throttle := make(chan time.Time, burstLimit)
|
||||
for i := 0; i < burstLimit; i++ {
|
||||
throttle <- time.Now()
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(rateLimit)
|
||||
defer ticker.Stop()
|
||||
for t := range ticker.C {
|
||||
select {
|
||||
case throttle <- t:
|
||||
case <-ctx.Done():
|
||||
{
|
||||
fmt.Println("Ticker done")
|
||||
return // exit goroutine when surrounding function returns
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return throttle
|
||||
}
|
||||
32
throttling/rateLimit_test.go
Normal file
32
throttling/rateLimit_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package throttling
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCallFunction(t *testing.T) {
|
||||
client := &Callable{}
|
||||
// create context for app
|
||||
ctx := context.Background()
|
||||
|
||||
fmt.Println("Starting")
|
||||
throttle := CreateThrottle(ctx, 2)
|
||||
CallFunction(ctx, client, &Payload{}, throttle)
|
||||
CallFunction(ctx, client, &Payload{}, throttle)
|
||||
CallFunction(ctx, client, &Payload{}, throttle)
|
||||
time.Sleep(2 * time.Second)
|
||||
fmt.Println("Continuing")
|
||||
CallFunction(ctx, client, &Payload{}, throttle)
|
||||
CallFunction(ctx, client, &Payload{}, throttle)
|
||||
CallFunction(ctx, client, &Payload{}, throttle)
|
||||
}
|
||||
|
||||
type Callable struct {
|
||||
}
|
||||
|
||||
func (c *Callable) Call(p *Payload) {
|
||||
fmt.Println("Called with payload")
|
||||
}
|
||||
Reference in New Issue
Block a user