-
-
Notifications
You must be signed in to change notification settings - Fork 172
Introduce EventTimingControl Package with Throttling and Debouncing #1166
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
Merged
Merged
Changes from all commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
38cf1bf
Implement debouncing throttler
window9u 7386170
Add tests
window9u 87a50e9
Rename package `throttle` -> `limit`
window9u ca8485e
Solve concurrent error in test
window9u f7b9d6d
Refactor test
window9u 3782427
Rename package `throttle` -> `limit`
window9u f044456
Rename components
window9u b9ab305
Change `debouncing` timing to after callback end
window9u 8bf4303
Remove Schedule
window9u 68e05c9
Add limit publisher
window9u 1cd6410
Filter self produced event in client
window9u 99f0ef0
Merge branch 'main' into rate-limiter
hackerwins 9e73b0a
Revert
window9u 90114a7
Remove limiter package
window9u ac19906
Refactor limiter
window9u 7e7efc0
Add webhook manager component
window9u d9be94d
Lint
window9u 02ea226
Fix error handling
window9u 1222c09
Rename constant
window9u 5bdad0c
Execute remain job when closing
window9u 982bcf5
Add expire batch configuration option
window9u b16b7ef
Add NewEventWebhookInfo
window9u 5dcab93
Add close event webhook manager
window9u 5ed551c
Remove golang rate package
window9u 9e93ec1
Lint
window9u dbf0817
Check Event Webhook Requirement
window9u 38f408d
Decrease Throttle window and Debounce time
window9u 01f655e
Refactor event webhook test as spec changed
window9u e2c5efa
Merge branch 'main' into rate-limiter
window9u acd606c
Wait previous debouncing before flushing
window9u 73b6c25
Refactor tests
window9u e794ac6
Add wait group in test
window9u 7d05a69
Add detail stimulation test
window9u 261ef28
refactor test with `occurs` type
window9u b141293
Add comment
window9u 526b370
Set `verifySignature` to helper function
window9u 48e7f65
Add bench test for webhook
window9u f839b16
Refactor limit event stream test
window9u bd7c930
Lint
window9u File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| package limit | ||
|
|
||
| import "time" | ||
|
|
||
| // Bucket represents a single-token bucket that refills every specified time window. | ||
| type Bucket struct { | ||
| window time.Duration // The interval at which the bucket refills. | ||
| last time.Time // The last time a token was granted. | ||
| } | ||
|
|
||
| // NewBucket creates a new Bucket with the given initial time and refill window. | ||
| func NewBucket(now time.Time, window time.Duration) Bucket { | ||
| return Bucket{ | ||
| window: window, | ||
| last: now, | ||
| } | ||
| } | ||
|
|
||
| // Allow checks if a token can be granted at the given time. | ||
| // It returns true if the time has advanced past the refill window, otherwise false. | ||
| func (b *Bucket) Allow(now time.Time) bool { | ||
| if now.Before(b.last.Add(b.window)) { | ||
| return false | ||
| } | ||
|
|
||
| b.last = now | ||
| return true | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| /* | ||
| * Copyright 2025 The Yorkie Authors. All rights reserved. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| // Package limit provides rate-limiting functionality with debouncing support. | ||
| package limit | ||
|
|
||
| import ( | ||
| "container/list" | ||
| "sync" | ||
| "time" | ||
| ) | ||
|
|
||
| // Limiter provides rate limiting functionality with a debouncing callback. | ||
| // It maintains a single token bucket. | ||
| type Limiter[K comparable] struct { | ||
| mu sync.Mutex | ||
| wg sync.WaitGroup | ||
| closing chan struct{} | ||
|
|
||
| expireInterval time.Duration | ||
| throttleWindow time.Duration | ||
| debouncingTime time.Duration | ||
| expireBatchSize int | ||
|
|
||
| // evictionList holds the limiter entries in order of recency. | ||
| evictionList *list.List | ||
| // entries maps keys to their corresponding list element for quick lookup. | ||
| entries map[K]*list.Element | ||
| } | ||
|
|
||
| // NewLimiter creates and returns a new Limiter instance. | ||
| // Parameters: | ||
| // | ||
| // expireInterval: How often to check for expired entries. | ||
| // throttleWindow: The time window for rate limiting. | ||
| // debouncingTime: The time-to-live for each rate bucket entry. | ||
| func NewLimiter[K comparable](expireNum int, expire, throttle, debouncing time.Duration) *Limiter[K] { | ||
| lim := &Limiter[K]{ | ||
| closing: make(chan struct{}), | ||
| expireInterval: expire, | ||
| throttleWindow: throttle, | ||
| debouncingTime: debouncing, | ||
| expireBatchSize: expireNum, | ||
| evictionList: list.New(), | ||
| entries: make(map[K]*list.Element), | ||
| } | ||
|
|
||
| // Start the background expiration process. | ||
| lim.wg.Add(1) | ||
| go lim.expirationLoop() | ||
| return lim | ||
| } | ||
|
|
||
| // limiterEntry represents an entry in the Limiter for a specific key. | ||
| type limiterEntry[K comparable] struct { | ||
| key K | ||
| bucket Bucket | ||
| expireTime time.Time | ||
| debouncingCallback func() | ||
| } | ||
|
|
||
| // Allow checks if an event is allowed for the given key based on the rate bucket. | ||
| // If allowed, it clears any pending debouncing callback; otherwise, it stores the provided callback. | ||
| // It returns true if the event is allowed immediately. | ||
| func (l *Limiter[K]) Allow(key K, callback func()) bool { | ||
| l.mu.Lock() | ||
| defer l.mu.Unlock() | ||
|
|
||
| now := time.Now() | ||
| if elem, exists := l.entries[key]; exists { | ||
| entry := elem.Value.(*limiterEntry[K]) | ||
| allowed := entry.bucket.Allow(now) | ||
| if allowed { | ||
| entry.debouncingCallback = nil | ||
| } else { | ||
| entry.debouncingCallback = callback | ||
| } | ||
| // Update recency and extend TTL. | ||
| l.evictionList.MoveToFront(elem) | ||
| entry.expireTime = now.Add(l.throttleWindow + l.debouncingTime) | ||
| return allowed | ||
| } | ||
|
|
||
| // Create a new rate bucket for a new key. | ||
| bucket := NewBucket(now, l.throttleWindow) | ||
| entry := &limiterEntry[K]{ | ||
| key: key, | ||
| bucket: bucket, | ||
| expireTime: now.Add(l.throttleWindow + l.debouncingTime), | ||
| } | ||
| elem := l.evictionList.PushFront(entry) | ||
| l.entries[key] = elem | ||
| return true | ||
| } | ||
|
|
||
| // expirationLoop runs in a separate goroutine to periodically remove expired entries. | ||
| func (l *Limiter[K]) expirationLoop() { | ||
| ticker := time.NewTicker(l.expireInterval) | ||
| defer func() { | ||
| ticker.Stop() | ||
| l.wg.Done() | ||
| }() | ||
|
|
||
| for { | ||
| select { | ||
| case <-ticker.C: | ||
| expiredEntries := l.collectEntries(true) | ||
| l.runDebounce(expiredEntries) | ||
| case <-l.closing: | ||
| return | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // collectEntries gathers expired entries and removes them from the limiter. | ||
| func (l *Limiter[K]) collectEntries(onlyExpired bool) []*limiterEntry[K] { | ||
| now := time.Now() | ||
| expiredEntries := make([]*limiterEntry[K], 0, l.expireBatchSize) | ||
|
|
||
| l.mu.Lock() | ||
| defer l.mu.Unlock() | ||
|
|
||
| for range l.expireBatchSize { | ||
| elem := l.evictionList.Back() | ||
| if elem == nil { | ||
| break | ||
| } | ||
|
|
||
| entry := elem.Value.(*limiterEntry[K]) | ||
| if onlyExpired && now.Before(entry.expireTime) { | ||
| break | ||
| } | ||
|
|
||
| if entry.debouncingCallback != nil { | ||
| expiredEntries = append(expiredEntries, entry) | ||
| } | ||
| l.evictionList.Remove(elem) | ||
| delete(l.entries, entry.key) | ||
| } | ||
|
|
||
| return expiredEntries | ||
| } | ||
|
|
||
|
Comment on lines
+153
to
+156
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Potential duplicated Close definition starts here (lines 153-156). The file later has lines 168–180, which also define |
||
| // runDebounce runs the debouncing callbacks for expired entries asynchronously. | ||
| func (l *Limiter[K]) runDebounce(entries []*limiterEntry[K]) { | ||
| l.wg.Add(1) | ||
| go func() { | ||
| defer l.wg.Done() | ||
| for _, entry := range entries { | ||
| entry.debouncingCallback() | ||
| } | ||
| }() | ||
| } | ||
|
|
||
| // Close terminates the expiration loop and cleans up resources. | ||
| func (l *Limiter[K]) Close() { | ||
| close(l.closing) | ||
|
|
||
| // Wait for all previous expiration job done. | ||
| l.wg.Wait() | ||
|
|
||
| for l.evictionList.Len() > 0 { | ||
| expiredEntries := l.collectEntries(false) | ||
| l.runDebounce(expiredEntries) | ||
| } | ||
|
|
||
| l.wg.Wait() | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.