Skip to content

Commit

Permalink
Example proto for incremented values
Browse files Browse the repository at this point in the history
  • Loading branch information
ehsundar committed Dec 30, 2023
1 parent 8c2895a commit 169344d
Show file tree
Hide file tree
Showing 5 changed files with 784 additions and 0 deletions.
7 changes: 7 additions & 0 deletions examples/ratelimit/app/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package main

func main() {
// see test file to usage examples
// you may try your custom usage of kvstore here
return
}
71 changes: 71 additions & 0 deletions examples/ratelimit/app/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package main

import (
"context"
"testing"
"time"

"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/suite"

"github.com/ehsundar/kvstore"
"github.com/ehsundar/kvstore/examples/ratelimit"
)

type RateLimitTestSuite struct {
suite.Suite

r *redis.Client
}

func TestRateLimitTestSuite(t *testing.T) {
suite.Run(t, new(RateLimitTestSuite))
}

func (s *RateLimitTestSuite) SetupSuite() {
r := redis.NewClient(&redis.Options{
Network: "tcp",
Addr: "localhost:6379",
ClientName: "tests",
})

_, err := r.FlushAll(context.Background()).Result()
s.Nil(err)

s.r = r
}

func (s *RateLimitTestSuite) TearDownTest() {
_, err := s.r.FlushAll(context.Background()).Result()
s.Nil(err)
}

func (s *RateLimitTestSuite) TestShouldReadWriteToStorage() {
ctx := context.Background()
storage := ratelimit.NewRateLimitStore(s.r)

bucketSizeSeconds := int64(1)
timeBucket := time.Now().Unix() / bucketSizeSeconds

for i := int64(1); i <= 10; i++ {
// you need to calculate bucket whenever a request arrives.
// we comment it here to avoid unwanted situations and test result inconsistencies
//timeBucket = time.Now().Unix() / bucketSizeSeconds

rate, err := storage.Incr(ctx, &ratelimit.CallInfo{
PathName: "some/path",
CallerId: "caller-1",
TimeBucket: timeBucket,
}, 1, kvstore.WithIncrTTL(time.Duration(bucketSizeSeconds)*time.Second, true))
s.Nil(err)
s.Equal(i, rate)
}

value, err := storage.Get(ctx, &ratelimit.CallInfo{
PathName: "some/path",
CallerId: "caller-1",
TimeBucket: timeBucket,
})
s.Nil(err)
s.Equal(int64(10), value)
}
Loading

0 comments on commit 169344d

Please sign in to comment.