Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Clock interface and LeakyBucket #675

Merged
merged 14 commits into from
Apr 9, 2024
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/livekit/protocol
go 1.21

require (
github.com/benbjohnson/clock v1.3.5
github.com/eapache/channels v1.1.0
github.com/frostbyte73/core v0.0.10
github.com/fsnotify/fsnotify v1.7.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o=
github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
Expand Down
20 changes: 20 additions & 0 deletions utils/clock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package utils

import "time"

type Clock interface {
Now() time.Time
Sleep(time.Duration)
}

type SystemClock struct{}

var _ Clock = &SystemClock{}

func (clock *SystemClock) Now() time.Time {
return time.Now()
}

func (clock *SystemClock) Sleep(d time.Duration) {
time.Sleep(d)
}
92 changes: 92 additions & 0 deletions utils/rate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// EDIT: slight modification to allow setting rate limit on the fly
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please add a link to the source where this is taken from?

Is the only change to add SetRateLimit API compared to the original?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did add a test here with a simulated clock, https://github.com/livekit/cloud-protocol/pull/747/files#diff-bf1c81b11717ede4526978ba2d3024bb771a5732c0768b6bafebb86af9f6f516R218-R241

I'll look into adding a unit test here as well

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is only adding SetRateLimit. Per comments in this PR, the change will evolve to modify the internal logic a bit.

// SCOPE: LeakyBucket
package utils

import (
"sync/atomic"
lherman-cs marked this conversation as resolved.
Show resolved Hide resolved
"time"
)

type LeakyBucket struct {
//lint:ignore U1000 Padding is unused but it is crucial to maintain performance
// of this rate limiter in case of collocation with other frequently accessed memory.
prepadding [64]byte // cache line size = 64; created to avoid false sharing.
state int64 // unix nanoseconds of the next permissions issue.
//lint:ignore U1000 like prepadding.
postpadding [56]byte // cache line size - state size = 64 - 8; created to avoid false sharing.
lherman-cs marked this conversation as resolved.
Show resolved Hide resolved

perRequest time.Duration
maxSlack time.Duration
clock Clock
}

func NewLeakyBucket(rateLimit int, slack time.Duration, clock Clock) *LeakyBucket {
var lb LeakyBucket
lb.SetRateLimit(rateLimit)
lb.maxSlack = slack * lb.perRequest
lherman-cs marked this conversation as resolved.
Show resolved Hide resolved
lb.clock = clock
atomic.StoreInt64(&lb.state, 0)
return &lb
}

func (lb *LeakyBucket) SetRateLimit(rateLimit int) {
lb.perRequest = time.Second / time.Duration(rateLimit)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are SetRateLimit and Take meant to be externally synchronized? the go race detector will raise errors about this. we don't seem to have a test for this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, there were meant to be externally synchronized. But, rethinking about this, it would make more sense to handle the synchronization here, especially Take is already synchronized. I'll work on this.

Copy link
Contributor Author

@lherman-cs lherman-cs Apr 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Spent too much time making this work with atomic. In the end, the code became complicated since state occupied 64 bits. It's possible to cramp the rate limit state to 64 bits, but it has to be u64. Then, handling time without negative numbers became tricky...

In the end, I reverted to the good ol' mutex. For now, we're not going to run into a performance issue since we only use this in QoS from a single goroutine. In the future, we might revisit if there's a need for a large amount of goroutines accessing this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@paulwe added a test

}

// Take blocks to ensure that the time spent between multiple
// Take calls is on average time.Second/rate.
func (t *LeakyBucket) Take() time.Time {
lherman-cs marked this conversation as resolved.
Show resolved Hide resolved
var (
newTimeOfNextPermissionIssue int64
now int64
)
for {
now = t.clock.Now().UnixNano()
timeOfNextPermissionIssue := atomic.LoadInt64(&t.state)

switch {
case timeOfNextPermissionIssue == 0 || (t.maxSlack == 0 && now-timeOfNextPermissionIssue > int64(t.perRequest)):
// if this is our first call or t.maxSlack == 0 we need to shrink issue time to now
newTimeOfNextPermissionIssue = now
case t.maxSlack > 0 && now-timeOfNextPermissionIssue > int64(t.maxSlack)+int64(t.perRequest):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perRequest is not locked and also not atomic. Are there any down sides to this running and rate limit being set on the fly?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is okay. The effect of changing the rate won't apply immediately. I don't see a different behavior that's more appropriate though.

Copy link
Contributor Author

@lherman-cs lherman-cs Apr 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I misunderstood the question. It was originally meant to be synchronized externally. @paulwe also raised a similar concern, #675 (comment). At the end, I think I should handle the synchronization here after all to avoid unexpected race errors.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced the synchronization handling with mutex instead. I put the details in @paulwe comment thread

// a lot of nanoseconds passed since the last Take call
// we will limit max accumulated time to maxSlack
newTimeOfNextPermissionIssue = now - int64(t.maxSlack)
default:
// calculate the time at which our permission was issued
newTimeOfNextPermissionIssue = timeOfNextPermissionIssue + int64(t.perRequest)
}

if atomic.CompareAndSwapInt64(&t.state, timeOfNextPermissionIssue, newTimeOfNextPermissionIssue) {
break
}
}

sleepDuration := time.Duration(newTimeOfNextPermissionIssue - now)
if sleepDuration > 0 {
t.clock.Sleep(sleepDuration)
return time.Unix(0, newTimeOfNextPermissionIssue)
}
// return now if we don't sleep as atomicLimiter does
return time.Unix(0, now)
}
Loading
Loading