|
| 1 | +package premium |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + cqapi "github.com/cloudquery/cloudquery-api-go" |
| 7 | + "github.com/google/uuid" |
| 8 | + "github.com/rs/zerolog/log" |
| 9 | + "math/rand" |
| 10 | + "net/http" |
| 11 | + "sync/atomic" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + defaultBatchLimit = 1000 |
| 17 | + defaultMaxRetries = 5 |
| 18 | + defaultMaxWaitTime = 60 * time.Second |
| 19 | + defaultMinTimeBetweenFlushes = 10 * time.Second |
| 20 | + defaultMaxTimeBetweenFlushes = 30 * time.Second |
| 21 | +) |
| 22 | + |
| 23 | +type UsageClient interface { |
| 24 | + // Increase updates the usage by the given number of rows |
| 25 | + Increase(context.Context, uint32) |
| 26 | + // HasQuota returns true if the quota has not been exceeded |
| 27 | + HasQuota(context.Context) (bool, error) |
| 28 | + // Close flushes any remaining rows and closes the quota service |
| 29 | + Close() error |
| 30 | +} |
| 31 | + |
| 32 | +type UpdaterOptions func(updater *BatchUpdater) |
| 33 | + |
| 34 | +// WithBatchLimit sets the maximum number of rows to update in a single request |
| 35 | +func WithBatchLimit(batchLimit uint32) UpdaterOptions { |
| 36 | + return func(updater *BatchUpdater) { |
| 37 | + updater.batchLimit = batchLimit |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// WithMaxTimeBetweenFlushes sets the flush duration - the time at which an update will be triggered even if the batch limit is not reached |
| 42 | +func WithMaxTimeBetweenFlushes(maxTimeBetweenFlushes time.Duration) UpdaterOptions { |
| 43 | + return func(updater *BatchUpdater) { |
| 44 | + updater.maxTimeBetweenFlushes = maxTimeBetweenFlushes |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// WithMinTimeBetweenFlushes sets the minimum time between updates |
| 49 | +func WithMinTimeBetweenFlushes(minTimeBetweenFlushes time.Duration) UpdaterOptions { |
| 50 | + return func(updater *BatchUpdater) { |
| 51 | + updater.minTimeBetweenFlushes = minTimeBetweenFlushes |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// WithMaxRetries sets the maximum number of retries to update the usage in case of an API error |
| 56 | +func WithMaxRetries(maxRetries int) UpdaterOptions { |
| 57 | + return func(updater *BatchUpdater) { |
| 58 | + updater.maxRetries = maxRetries |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +// WithMaxWaitTime sets the maximum time to wait before retrying a failed update |
| 63 | +func WithMaxWaitTime(maxWaitTime time.Duration) UpdaterOptions { |
| 64 | + return func(updater *BatchUpdater) { |
| 65 | + updater.maxWaitTime = maxWaitTime |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +type BatchUpdater struct { |
| 70 | + apiClient *cqapi.ClientWithResponses |
| 71 | + |
| 72 | + // Plugin details |
| 73 | + teamName string |
| 74 | + pluginTeam string |
| 75 | + pluginKind string |
| 76 | + pluginName string |
| 77 | + |
| 78 | + // Configuration |
| 79 | + batchLimit uint32 |
| 80 | + maxRetries int |
| 81 | + maxWaitTime time.Duration |
| 82 | + minTimeBetweenFlushes time.Duration |
| 83 | + maxTimeBetweenFlushes time.Duration |
| 84 | + |
| 85 | + // State |
| 86 | + lastUpdateTime time.Time |
| 87 | + rowsToUpdate atomic.Uint32 |
| 88 | + triggerUpdate chan struct{} |
| 89 | + done chan struct{} |
| 90 | + closeError chan error |
| 91 | + isClosed bool |
| 92 | +} |
| 93 | + |
| 94 | +func NewUsageClient(ctx context.Context, apiClient *cqapi.ClientWithResponses, teamName, pluginTeam, pluginKind, pluginName string, ops ...UpdaterOptions) *BatchUpdater { |
| 95 | + u := &BatchUpdater{ |
| 96 | + apiClient: apiClient, |
| 97 | + |
| 98 | + teamName: teamName, |
| 99 | + pluginTeam: pluginTeam, |
| 100 | + pluginKind: pluginKind, |
| 101 | + pluginName: pluginName, |
| 102 | + |
| 103 | + batchLimit: defaultBatchLimit, |
| 104 | + minTimeBetweenFlushes: defaultMinTimeBetweenFlushes, |
| 105 | + maxTimeBetweenFlushes: defaultMaxTimeBetweenFlushes, |
| 106 | + maxRetries: defaultMaxRetries, |
| 107 | + maxWaitTime: defaultMaxWaitTime, |
| 108 | + triggerUpdate: make(chan struct{}), |
| 109 | + done: make(chan struct{}), |
| 110 | + closeError: make(chan error), |
| 111 | + } |
| 112 | + for _, op := range ops { |
| 113 | + op(u) |
| 114 | + } |
| 115 | + |
| 116 | + u.backgroundUpdater(ctx) |
| 117 | + |
| 118 | + return u |
| 119 | +} |
| 120 | + |
| 121 | +func (u *BatchUpdater) Increase(_ context.Context, rows uint32) error { |
| 122 | + if rows <= 0 { |
| 123 | + return fmt.Errorf("rows must be greater than zero got %d", rows) |
| 124 | + } |
| 125 | + |
| 126 | + if u.isClosed { |
| 127 | + return fmt.Errorf("usage updater is closed") |
| 128 | + } |
| 129 | + |
| 130 | + u.rowsToUpdate.Add(rows) |
| 131 | + |
| 132 | + // Trigger an update unless an update is already in process |
| 133 | + select { |
| 134 | + case u.triggerUpdate <- struct{}{}: |
| 135 | + default: |
| 136 | + return nil |
| 137 | + } |
| 138 | + |
| 139 | + return nil |
| 140 | +} |
| 141 | + |
| 142 | +func (u *BatchUpdater) HasQuota(ctx context.Context) (bool, error) { |
| 143 | + usage, err := u.apiClient.GetTeamPluginUsageWithResponse(ctx, u.teamName, u.pluginTeam, cqapi.PluginKind(u.pluginKind), u.pluginName) |
| 144 | + if err != nil { |
| 145 | + return false, fmt.Errorf("failed to get usage: %w", err) |
| 146 | + } |
| 147 | + if usage.StatusCode() != http.StatusOK { |
| 148 | + return false, fmt.Errorf("failed to get usage: %s", usage.Status()) |
| 149 | + } |
| 150 | + return *usage.JSON200.RemainingRows > 0, nil |
| 151 | +} |
| 152 | + |
| 153 | +func (u *BatchUpdater) Close(_ context.Context) error { |
| 154 | + u.isClosed = true |
| 155 | + |
| 156 | + close(u.done) |
| 157 | + |
| 158 | + return <-u.closeError |
| 159 | +} |
| 160 | + |
| 161 | +func (u *BatchUpdater) backgroundUpdater(ctx context.Context) { |
| 162 | + started := make(chan struct{}) |
| 163 | + |
| 164 | + flushDuration := time.NewTicker(u.maxTimeBetweenFlushes) |
| 165 | + |
| 166 | + go func() { |
| 167 | + started <- struct{}{} |
| 168 | + for { |
| 169 | + select { |
| 170 | + case <-u.triggerUpdate: |
| 171 | + if time.Since(u.lastUpdateTime) < u.minTimeBetweenFlushes { |
| 172 | + // Not enough time since last update |
| 173 | + continue |
| 174 | + } |
| 175 | + |
| 176 | + rowsToUpdate := u.rowsToUpdate.Load() |
| 177 | + if rowsToUpdate < u.batchLimit { |
| 178 | + // Not enough rows to update |
| 179 | + continue |
| 180 | + } |
| 181 | + if err := u.updateUsageWithRetryAndBackoff(ctx, rowsToUpdate); err != nil { |
| 182 | + log.Warn().Err(err).Msg("failed to update usage") |
| 183 | + continue |
| 184 | + } |
| 185 | + u.rowsToUpdate.Add(-rowsToUpdate) |
| 186 | + case <-flushDuration.C: |
| 187 | + if time.Since(u.lastUpdateTime) < u.minTimeBetweenFlushes { |
| 188 | + // Not enough time since last update |
| 189 | + continue |
| 190 | + } |
| 191 | + rowsToUpdate := u.rowsToUpdate.Load() |
| 192 | + if rowsToUpdate == 0 { |
| 193 | + continue |
| 194 | + } |
| 195 | + if err := u.updateUsageWithRetryAndBackoff(ctx, rowsToUpdate); err != nil { |
| 196 | + log.Warn().Err(err).Msg("failed to update usage") |
| 197 | + continue |
| 198 | + } |
| 199 | + u.rowsToUpdate.Add(-rowsToUpdate) |
| 200 | + case <-u.done: |
| 201 | + remainingRows := u.rowsToUpdate.Load() |
| 202 | + if remainingRows != 0 { |
| 203 | + if err := u.updateUsageWithRetryAndBackoff(ctx, remainingRows); err != nil { |
| 204 | + u.closeError <- err |
| 205 | + return |
| 206 | + } |
| 207 | + u.rowsToUpdate.Add(-remainingRows) |
| 208 | + } |
| 209 | + u.closeError <- nil |
| 210 | + return |
| 211 | + } |
| 212 | + } |
| 213 | + }() |
| 214 | + <-started |
| 215 | +} |
| 216 | + |
| 217 | +func (u *BatchUpdater) updateUsageWithRetryAndBackoff(ctx context.Context, numberToUpdate uint32) error { |
| 218 | + for retry := 0; retry < u.maxRetries; retry++ { |
| 219 | + queryStartTime := time.Now() |
| 220 | + |
| 221 | + resp, err := u.apiClient.IncreaseTeamPluginUsageWithResponse(ctx, u.teamName, cqapi.IncreaseTeamPluginUsageJSONRequestBody{ |
| 222 | + RequestId: uuid.New(), |
| 223 | + PluginTeam: u.pluginTeam, |
| 224 | + PluginKind: cqapi.PluginKind(u.pluginKind), |
| 225 | + PluginName: u.pluginName, |
| 226 | + Rows: int(numberToUpdate), |
| 227 | + }) |
| 228 | + if err != nil { |
| 229 | + return fmt.Errorf("failed to update usage: %w", err) |
| 230 | + } |
| 231 | + if resp.StatusCode() >= 200 && resp.StatusCode() < 300 { |
| 232 | + u.lastUpdateTime = time.Now().UTC() |
| 233 | + return nil |
| 234 | + } |
| 235 | + |
| 236 | + retryDuration, err := u.calculateRetryDuration(resp.StatusCode(), resp.HTTPResponse.Header, queryStartTime, retry) |
| 237 | + if err != nil { |
| 238 | + return fmt.Errorf("failed to calculate retry duration: %w", err) |
| 239 | + } |
| 240 | + if retryDuration > 0 { |
| 241 | + time.Sleep(retryDuration) |
| 242 | + } |
| 243 | + } |
| 244 | + return fmt.Errorf("failed to update usage: max retries exceeded") |
| 245 | +} |
| 246 | + |
| 247 | +// calculateRetryDuration calculates the duration to sleep relative to the query start time before retrying an update |
| 248 | +func (u *BatchUpdater) calculateRetryDuration(statusCode int, headers http.Header, queryStartTime time.Time, retry int) (time.Duration, error) { |
| 249 | + if !retryableStatusCode(statusCode) { |
| 250 | + return 0, fmt.Errorf("non-retryable status code: %d", statusCode) |
| 251 | + } |
| 252 | + |
| 253 | + // Check if we have a retry-after header |
| 254 | + retryAfter := headers.Get("Retry-After") |
| 255 | + if retryAfter != "" { |
| 256 | + retryDelay, err := time.ParseDuration(retryAfter + "s") |
| 257 | + if err != nil { |
| 258 | + return 0, fmt.Errorf("failed to parse retry-after header: %w", err) |
| 259 | + } |
| 260 | + return retryDelay, nil |
| 261 | + } |
| 262 | + |
| 263 | + // Calculate exponential backoff |
| 264 | + baseRetry := min(time.Duration(1<<retry)*time.Second, u.maxWaitTime) |
| 265 | + jitter := time.Duration(rand.Intn(1000)) * time.Millisecond |
| 266 | + retryDelay := baseRetry + jitter |
| 267 | + return retryDelay - time.Since(queryStartTime), nil |
| 268 | +} |
| 269 | + |
| 270 | +func retryableStatusCode(statusCode int) bool { |
| 271 | + return statusCode == http.StatusTooManyRequests || statusCode == http.StatusServiceUnavailable |
| 272 | +} |
0 commit comments