-
Notifications
You must be signed in to change notification settings - Fork 26
feat: Adding a batch updater to allow usage updates to be batched #1326
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
14 commits
Select commit
Hold shift + click to select a range
e08ef93
feat: Adding a batch updater to allow usage updates to be batched
mnorbury 2e00acd
Adding retry logic with `maxRetries` and `maxWaitTime`
mnorbury d4b85a3
Replace waitGroup with final close error
mnorbury 22de9a3
Add support for `retry-after` header
mnorbury 8e4964f
Remove log messages
mnorbury ba03f2d
Replace with duration
mnorbury 59e4ab2
Add a minimum update check - we don't want to hit the API too much, s…
mnorbury c2f5be4
Tidy up tests
mnorbury 0184ea7
Clean up min/max time between flushes naming
mnorbury 8375810
Do not error if server wait time exceeds max wait time
mnorbury c54c81c
We are happy with any 2xx response going forward
mnorbury ba46c4a
Only retry on `429` and `503` status codes
mnorbury 85a4d7e
Add some jitter to retry delay
mnorbury 1c0c0b5
Only calculate retry duration on retryable errors
mnorbury 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,272 @@ | ||
| package premium | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| cqapi "github.com/cloudquery/cloudquery-api-go" | ||
| "github.com/google/uuid" | ||
| "github.com/rs/zerolog/log" | ||
| "math/rand" | ||
| "net/http" | ||
| "sync/atomic" | ||
| "time" | ||
| ) | ||
|
|
||
| const ( | ||
| defaultBatchLimit = 1000 | ||
| defaultMaxRetries = 5 | ||
| defaultMaxWaitTime = 60 * time.Second | ||
| defaultMinTimeBetweenFlushes = 10 * time.Second | ||
| defaultMaxTimeBetweenFlushes = 30 * time.Second | ||
| ) | ||
|
|
||
| type UsageClient interface { | ||
| // Increase updates the usage by the given number of rows | ||
| Increase(context.Context, uint32) | ||
| // HasQuota returns true if the quota has not been exceeded | ||
| HasQuota(context.Context) (bool, error) | ||
| // Close flushes any remaining rows and closes the quota service | ||
| Close() error | ||
| } | ||
|
|
||
| type UpdaterOptions func(updater *BatchUpdater) | ||
|
|
||
| // WithBatchLimit sets the maximum number of rows to update in a single request | ||
| func WithBatchLimit(batchLimit uint32) UpdaterOptions { | ||
| return func(updater *BatchUpdater) { | ||
| updater.batchLimit = batchLimit | ||
| } | ||
| } | ||
|
|
||
| // WithMaxTimeBetweenFlushes sets the flush duration - the time at which an update will be triggered even if the batch limit is not reached | ||
| func WithMaxTimeBetweenFlushes(maxTimeBetweenFlushes time.Duration) UpdaterOptions { | ||
| return func(updater *BatchUpdater) { | ||
| updater.maxTimeBetweenFlushes = maxTimeBetweenFlushes | ||
| } | ||
| } | ||
|
|
||
| // WithMinTimeBetweenFlushes sets the minimum time between updates | ||
| func WithMinTimeBetweenFlushes(minTimeBetweenFlushes time.Duration) UpdaterOptions { | ||
| return func(updater *BatchUpdater) { | ||
| updater.minTimeBetweenFlushes = minTimeBetweenFlushes | ||
| } | ||
| } | ||
|
|
||
| // WithMaxRetries sets the maximum number of retries to update the usage in case of an API error | ||
| func WithMaxRetries(maxRetries int) UpdaterOptions { | ||
| return func(updater *BatchUpdater) { | ||
| updater.maxRetries = maxRetries | ||
| } | ||
| } | ||
|
|
||
| // WithMaxWaitTime sets the maximum time to wait before retrying a failed update | ||
| func WithMaxWaitTime(maxWaitTime time.Duration) UpdaterOptions { | ||
| return func(updater *BatchUpdater) { | ||
| updater.maxWaitTime = maxWaitTime | ||
| } | ||
| } | ||
|
|
||
| type BatchUpdater struct { | ||
| apiClient *cqapi.ClientWithResponses | ||
|
|
||
| // Plugin details | ||
| teamName string | ||
| pluginTeam string | ||
| pluginKind string | ||
| pluginName string | ||
|
|
||
| // Configuration | ||
| batchLimit uint32 | ||
| maxRetries int | ||
| maxWaitTime time.Duration | ||
| minTimeBetweenFlushes time.Duration | ||
| maxTimeBetweenFlushes time.Duration | ||
|
|
||
| // State | ||
| lastUpdateTime time.Time | ||
| rowsToUpdate atomic.Uint32 | ||
| triggerUpdate chan struct{} | ||
| done chan struct{} | ||
| closeError chan error | ||
| isClosed bool | ||
| } | ||
|
|
||
| func NewUsageClient(ctx context.Context, apiClient *cqapi.ClientWithResponses, teamName, pluginTeam, pluginKind, pluginName string, ops ...UpdaterOptions) *BatchUpdater { | ||
| u := &BatchUpdater{ | ||
| apiClient: apiClient, | ||
|
|
||
| teamName: teamName, | ||
| pluginTeam: pluginTeam, | ||
| pluginKind: pluginKind, | ||
| pluginName: pluginName, | ||
|
|
||
| batchLimit: defaultBatchLimit, | ||
| minTimeBetweenFlushes: defaultMinTimeBetweenFlushes, | ||
| maxTimeBetweenFlushes: defaultMaxTimeBetweenFlushes, | ||
| maxRetries: defaultMaxRetries, | ||
| maxWaitTime: defaultMaxWaitTime, | ||
| triggerUpdate: make(chan struct{}), | ||
| done: make(chan struct{}), | ||
| closeError: make(chan error), | ||
| } | ||
| for _, op := range ops { | ||
| op(u) | ||
| } | ||
|
|
||
| u.backgroundUpdater(ctx) | ||
|
|
||
| return u | ||
| } | ||
|
|
||
| func (u *BatchUpdater) Increase(_ context.Context, rows uint32) error { | ||
| if rows <= 0 { | ||
| return fmt.Errorf("rows must be greater than zero got %d", rows) | ||
| } | ||
|
|
||
| if u.isClosed { | ||
| return fmt.Errorf("usage updater is closed") | ||
| } | ||
|
|
||
| u.rowsToUpdate.Add(rows) | ||
|
|
||
| // Trigger an update unless an update is already in process | ||
| select { | ||
| case u.triggerUpdate <- struct{}{}: | ||
| default: | ||
| return nil | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func (u *BatchUpdater) HasQuota(ctx context.Context) (bool, error) { | ||
| usage, err := u.apiClient.GetTeamPluginUsageWithResponse(ctx, u.teamName, u.pluginTeam, cqapi.PluginKind(u.pluginKind), u.pluginName) | ||
| if err != nil { | ||
| return false, fmt.Errorf("failed to get usage: %w", err) | ||
| } | ||
| if usage.StatusCode() != http.StatusOK { | ||
| return false, fmt.Errorf("failed to get usage: %s", usage.Status()) | ||
| } | ||
| return *usage.JSON200.RemainingRows > 0, nil | ||
| } | ||
|
|
||
| func (u *BatchUpdater) Close(_ context.Context) error { | ||
| u.isClosed = true | ||
|
|
||
| close(u.done) | ||
|
|
||
| return <-u.closeError | ||
| } | ||
|
|
||
| func (u *BatchUpdater) backgroundUpdater(ctx context.Context) { | ||
| started := make(chan struct{}) | ||
|
|
||
| flushDuration := time.NewTicker(u.maxTimeBetweenFlushes) | ||
|
|
||
| go func() { | ||
| started <- struct{}{} | ||
| for { | ||
| select { | ||
| case <-u.triggerUpdate: | ||
| if time.Since(u.lastUpdateTime) < u.minTimeBetweenFlushes { | ||
| // Not enough time since last update | ||
| continue | ||
| } | ||
|
|
||
| rowsToUpdate := u.rowsToUpdate.Load() | ||
| if rowsToUpdate < u.batchLimit { | ||
| // Not enough rows to update | ||
| continue | ||
| } | ||
| if err := u.updateUsageWithRetryAndBackoff(ctx, rowsToUpdate); err != nil { | ||
| log.Warn().Err(err).Msg("failed to update usage") | ||
| continue | ||
| } | ||
| u.rowsToUpdate.Add(-rowsToUpdate) | ||
| case <-flushDuration.C: | ||
| if time.Since(u.lastUpdateTime) < u.minTimeBetweenFlushes { | ||
| // Not enough time since last update | ||
| continue | ||
| } | ||
| rowsToUpdate := u.rowsToUpdate.Load() | ||
| if rowsToUpdate == 0 { | ||
| continue | ||
| } | ||
| if err := u.updateUsageWithRetryAndBackoff(ctx, rowsToUpdate); err != nil { | ||
| log.Warn().Err(err).Msg("failed to update usage") | ||
| continue | ||
| } | ||
| u.rowsToUpdate.Add(-rowsToUpdate) | ||
| case <-u.done: | ||
| remainingRows := u.rowsToUpdate.Load() | ||
| if remainingRows != 0 { | ||
| if err := u.updateUsageWithRetryAndBackoff(ctx, remainingRows); err != nil { | ||
| u.closeError <- err | ||
| return | ||
| } | ||
| u.rowsToUpdate.Add(-remainingRows) | ||
| } | ||
| u.closeError <- nil | ||
| return | ||
| } | ||
| } | ||
| }() | ||
| <-started | ||
| } | ||
|
|
||
| func (u *BatchUpdater) updateUsageWithRetryAndBackoff(ctx context.Context, numberToUpdate uint32) error { | ||
| for retry := 0; retry < u.maxRetries; retry++ { | ||
| queryStartTime := time.Now() | ||
|
|
||
| resp, err := u.apiClient.IncreaseTeamPluginUsageWithResponse(ctx, u.teamName, cqapi.IncreaseTeamPluginUsageJSONRequestBody{ | ||
| RequestId: uuid.New(), | ||
| PluginTeam: u.pluginTeam, | ||
| PluginKind: cqapi.PluginKind(u.pluginKind), | ||
| PluginName: u.pluginName, | ||
| Rows: int(numberToUpdate), | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to update usage: %w", err) | ||
| } | ||
| if resp.StatusCode() >= 200 && resp.StatusCode() < 300 { | ||
| u.lastUpdateTime = time.Now().UTC() | ||
| return nil | ||
| } | ||
|
|
||
| retryDuration, err := u.calculateRetryDuration(resp.StatusCode(), resp.HTTPResponse.Header, queryStartTime, retry) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to calculate retry duration: %w", err) | ||
| } | ||
| if retryDuration > 0 { | ||
| time.Sleep(retryDuration) | ||
| } | ||
| } | ||
| return fmt.Errorf("failed to update usage: max retries exceeded") | ||
| } | ||
|
|
||
| // calculateRetryDuration calculates the duration to sleep relative to the query start time before retrying an update | ||
| func (u *BatchUpdater) calculateRetryDuration(statusCode int, headers http.Header, queryStartTime time.Time, retry int) (time.Duration, error) { | ||
| if !retryableStatusCode(statusCode) { | ||
| return 0, fmt.Errorf("non-retryable status code: %d", statusCode) | ||
| } | ||
|
|
||
| // Check if we have a retry-after header | ||
| retryAfter := headers.Get("Retry-After") | ||
| if retryAfter != "" { | ||
| retryDelay, err := time.ParseDuration(retryAfter + "s") | ||
| if err != nil { | ||
| return 0, fmt.Errorf("failed to parse retry-after header: %w", err) | ||
| } | ||
| return retryDelay, nil | ||
| } | ||
|
|
||
| // Calculate exponential backoff | ||
| baseRetry := min(time.Duration(1<<retry)*time.Second, u.maxWaitTime) | ||
| jitter := time.Duration(rand.Intn(1000)) * time.Millisecond | ||
| retryDelay := baseRetry + jitter | ||
| return retryDelay - time.Since(queryStartTime), nil | ||
| } | ||
|
|
||
| func retryableStatusCode(statusCode int) bool { | ||
| return statusCode == http.StatusTooManyRequests || statusCode == http.StatusServiceUnavailable | ||
| } | ||
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.