-
Notifications
You must be signed in to change notification settings - Fork 0
Bound feature queries and make polling cancellable #5
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
10 commits
Select commit
Hold shift + click to select a range
3c9289e
Add bounded Receiver feature queries
craffit d9a8038
Make feature polling cancellable and preserve query outcomes
craffit a78db13
Validate capability types per consumer
craffit e2d867b
Merge transport foundation into feature client
craffit a9d2a56
Preserve idle connection cleanup through feature bounds
craffit f0ec060
Merge remote-tracking branch 'origin/receiver-transport' into otel-fe…
craffit 3f3f517
Merge transport trust test fix
craffit 82c5cc1
Merge master after transport foundation
craffit 736091f
Explain bounded feature response reads
craffit f2036fa
Classify proxy CONNECT rejections before transport failures
craffit 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,222 @@ | ||
| package features | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/tls" | ||
| "crypto/x509" | ||
| "errors" | ||
| "io" | ||
| "math/rand/v2" | ||
| "net" | ||
| "net/http" | ||
| "strconv" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/StackVista/stackstate-receiver-go-client/generated/receiver_api" | ||
| "github.com/StackVista/stackstate-receiver-go-client/pkg/openapiclient" | ||
| ) | ||
|
|
||
| // QueryOptions bounds a complete feature query, including attempts and retry waits. | ||
| type QueryOptions struct { | ||
| Timeout, AttemptTimeout time.Duration | ||
| MaxAttempts int | ||
| InitialBackoff, MaxBackoff time.Duration | ||
| // BooleanCapabilities validates only listed keys that are present in the response. | ||
| BooleanCapabilities []string | ||
| } | ||
|
|
||
| // Client queries the generated features API with bounded retries. | ||
| type Client struct { | ||
| api receiver_api.FeaturesAPI | ||
| opts QueryOptions | ||
| now func() time.Time | ||
| random func() float64 | ||
| } | ||
|
|
||
| // NewClient validates query bounds and constructs a feature client. | ||
| func NewClient(api receiver_api.FeaturesAPI, opts QueryOptions) (*Client, error) { | ||
| if api == nil { | ||
| return nil, errors.New("features API is required") | ||
| } | ||
| if opts.Timeout <= 0 || opts.AttemptTimeout <= 0 || opts.AttemptTimeout > opts.Timeout || opts.MaxAttempts < 1 || opts.InitialBackoff <= 0 || opts.MaxBackoff < opts.InitialBackoff { | ||
| return nil, errors.New("invalid feature query timeout, attempt count or backoff bounds") | ||
| } | ||
| opts.BooleanCapabilities = append([]string(nil), opts.BooleanCapabilities...) | ||
| return &Client{api: api, opts: opts, now: time.Now, random: rand.Float64}, nil | ||
| } | ||
|
|
||
| // FetchFeatures returns one observation after the bounded query completes. | ||
| func (c *Client) FetchFeatures(authCtx context.Context) Result { | ||
| queryCtx, cancel := context.WithTimeout(authCtx, c.opts.Timeout) | ||
| defer cancel() | ||
| result := Result{} | ||
| backoff := c.opts.InitialBackoff | ||
| for { | ||
| if queryCtx.Err() != nil { | ||
| result.Class = contextClass(authCtx, queryCtx.Err()) | ||
| break | ||
| } | ||
| attemptCtx, stop := context.WithTimeout(queryCtx, c.opts.AttemptTimeout) | ||
| values, response, err := c.api.GetFeaturesExecute(c.api.GetFeatures(attemptCtx)) | ||
| result.Attempts++ | ||
| result.StatusCode = 0 | ||
| var proxyError *openapiclient.ProxyConnectError | ||
| if errors.As(err, &proxyError) { | ||
| result.StatusCode = proxyError.StatusCode | ||
| } | ||
| retryAfter := time.Duration(0) | ||
| if response != nil { | ||
| result.StatusCode = response.StatusCode | ||
| if response.StatusCode == http.StatusTooManyRequests || response.StatusCode == http.StatusServiceUnavailable { | ||
| retryAfter = parseRetryAfter(response.Header.Get("Retry-After"), c.now(), c.opts.Timeout) | ||
| } | ||
| if response.Body != nil { | ||
| response.Body.Close() | ||
| } | ||
| } | ||
| result.Class = c.classify(authCtx, attemptCtx, values, response, err) | ||
| stop() | ||
| if result.Class == Valid { | ||
| result.Features = values | ||
| } | ||
| if (result.Class != Transient && result.Class != Timeout) || result.Attempts >= c.opts.MaxAttempts { | ||
| break | ||
| } | ||
| if queryCtx.Err() != nil { | ||
| result.Class = contextClass(authCtx, queryCtx.Err()) | ||
| break | ||
| } | ||
| delay := time.Duration(c.random() * float64(backoff)) | ||
| if retryAfter > delay { | ||
| delay = retryAfter | ||
| } | ||
| deadline, _ := queryCtx.Deadline() | ||
| if delay >= time.Until(deadline) { | ||
| break | ||
| } | ||
| timer := time.NewTimer(delay) | ||
| select { | ||
| case <-queryCtx.Done(): | ||
| timer.Stop() | ||
| result.Class = contextClass(authCtx, queryCtx.Err()) | ||
| result.FinishedAt = c.now() | ||
| return result | ||
| case <-timer.C: | ||
| } | ||
| if backoff > c.opts.MaxBackoff/2 { | ||
| backoff = c.opts.MaxBackoff | ||
| } else { | ||
| backoff *= 2 | ||
| } | ||
| } | ||
| result.FinishedAt = c.now() | ||
| return result | ||
| } | ||
|
|
||
| func contextClass(parent context.Context, err error) Class { | ||
| if parent.Err() != nil { | ||
| return Canceled | ||
| } | ||
| if errors.Is(err, context.DeadlineExceeded) { | ||
| return Timeout | ||
| } | ||
| return Canceled | ||
| } | ||
|
|
||
| func (c *Client) classify(parent, attempt context.Context, values map[string]any, response *http.Response, err error) Class { | ||
| if parent.Err() != nil { | ||
| return Canceled | ||
| } | ||
| var proxyError *openapiclient.ProxyConnectError | ||
| if errors.As(err, &proxyError) { | ||
| switch status := proxyError.StatusCode; { | ||
| case status == http.StatusProxyAuthRequired: | ||
| return Configuration | ||
| case status == 408 || status == 429 || status >= 500 && status <= 599: | ||
| return Transient | ||
| default: | ||
| return Rejected | ||
| } | ||
| } | ||
| if response != nil { | ||
| switch status := response.StatusCode; { | ||
| case status == 401 || status == 403: | ||
| return Authentication | ||
| case status == http.StatusProxyAuthRequired: | ||
| return Configuration | ||
| case status == 404: | ||
| return Unsupported | ||
|
craffit marked this conversation as resolved.
|
||
| case status == 408 || status == 429 || status >= 500 && status <= 599: | ||
| return Transient | ||
| case status != 200: | ||
| return Rejected | ||
| } | ||
| } | ||
| if errors.Is(err, openapiclient.ErrMissingCredential) { | ||
| return Authentication | ||
| } | ||
| var verification *tls.CertificateVerificationError | ||
| var unknown x509.UnknownAuthorityError | ||
| var hostname x509.HostnameError | ||
| var invalid x509.CertificateInvalidError | ||
| if errors.As(err, &verification) || errors.As(err, &unknown) || errors.As(err, &hostname) || errors.As(err, &invalid) { | ||
| return Configuration | ||
| } | ||
| if attempt.Err() != nil || errors.Is(err, context.DeadlineExceeded) { | ||
| return Timeout | ||
| } | ||
| if errors.Is(err, context.Canceled) { | ||
| return Canceled | ||
| } | ||
| var network net.Error | ||
| if errors.As(err, &network) && network.Timeout() { | ||
| return Timeout | ||
| } | ||
| var operation *net.OpError | ||
| if errors.As(err, &operation) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || (errors.As(err, &network) && network.Temporary()) { | ||
| return Transient | ||
| } | ||
| if response == nil { | ||
|
craffit marked this conversation as resolved.
|
||
| if err != nil { | ||
| return Transient | ||
| } | ||
| return Rejected | ||
| } | ||
| if err != nil || values == nil { | ||
| return Malformed | ||
| } | ||
| for _, key := range c.opts.BooleanCapabilities { | ||
| if capability, present := values[key]; present { | ||
| if _, ok := capability.(bool); !ok { | ||
| return Malformed | ||
| } | ||
| } | ||
| } | ||
| return Valid | ||
| } | ||
|
|
||
| func parseRetryAfter(value string, now time.Time, limit time.Duration) time.Duration { | ||
| value = strings.TrimSpace(value) | ||
| if value == "" { | ||
| return 0 | ||
| } | ||
| if seconds, err := strconv.ParseUint(value, 10, 64); err == nil { | ||
| if seconds > uint64(limit/time.Second) { | ||
| return limit | ||
| } | ||
| return time.Duration(seconds) * time.Second | ||
| } else if errors.Is(err, strconv.ErrRange) && strings.Trim(value, "0123456789") == "" { | ||
| return limit | ||
| } | ||
| if deadline, err := http.ParseTime(value); err == nil { | ||
| delay := deadline.Sub(now) | ||
| if delay > limit { | ||
| return limit | ||
| } | ||
| if delay > 0 { | ||
| return delay | ||
| } | ||
| } | ||
| return 0 | ||
| } | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is full jitter, so a run of small random values retries almost immediately and the retry bound degrades to
MaxAttemptsback-to-back requests. A floor ofbackoff/2would keep the spacing.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Full jitter is the selected retry policy, so near-zero delays are allowed. MaxAttempts and the whole-query deadline still bound requests, and Retry-After remains a minimum when present. Existing retry/deadline/cancellation tests pass; no minimum spacing is promised for retries.