juju / ratelimit

Efficient token-bucket-based rate limiter package.
Other
2.79k stars 312 forks source link

I believe capacity is broken? #12

Closed MaerF0x0 closed 8 years ago

MaerF0x0 commented 8 years ago

I'm trying out setting a bucket that makes 1 token per second w/ a max of 1 token waiting. Unclear what I'm doing wrong.

package main

import (
  "fmt"
  "time"

  "github.com/juju/ratelimit"
)

func main() {
  fmt.Printf("[DEBUG]: Creating bucket with capacity = %d\n", 1)
  ratelimiter := ratelimit.NewBucketWithRate(float64(1), 1)
  ticker := time.NewTicker(1 * time.Second)
  quit := make(chan struct{})
  go func() {
    for {
      select {
      case <-ticker.C:
        fmt.Printf("[DEBUG]: current bucket tokens = %d/%d\n", ratelimiter.Available, ratelimiter.Capacity)
        fmt.Printf("%#v\n", ratelimiter)
      case <-quit:
        ticker.Stop()
        return
      }
    }
  }()

  block := make(chan bool)
  block <- true
}

output:

[DEBUG]: Creating bucket with capacity = 1
[DEBUG]: current bucket tokens = 8784/8848
(repeated)

Expected: I figured that it would have a capacity of 1 available and capacity of 1. I'm seeing similar issues using other values than 1 .

MaerF0x0 commented 8 years ago

Ok This is my bad.

The issue was i was printing ratelimter.Available and ratelimiter.Capacity as function pointers, not invoking them as functions.

After correcting the invocation it works as expected.