Throttling with bug

This commit is contained in:
2024-11-10 20:55:10 +01:00
commit 07c3e411e9
11 changed files with 2737 additions and 0 deletions

56
throttling/rateLimit.go Normal file
View 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
}

View 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")
}