-
Notifications
You must be signed in to change notification settings - Fork 54
[PECOBLR-1146] Implement Feature Flag Cache with Reference Counting #304
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 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
126c10f
[PECOBLR-1146] Implement feature flag cache with reference counting
samikshya-db cfb8ab8
Fix thread-safety issues in feature flag cache
samikshya-db d568c79
Fix errcheck linter: explicitly ignore io.Copy error
samikshya-db f9fe5c7
Merge branch 'main' into stack/PECOBLR-1146-feature-flag-cache
samikshya-db 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,156 @@ | ||
| package telemetry | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "sync" | ||
| "time" | ||
| ) | ||
|
|
||
| // featureFlagCache manages feature flag state per host with reference counting. | ||
| // This prevents rate limiting by caching feature flag responses. | ||
| type featureFlagCache struct { | ||
| mu sync.RWMutex | ||
| contexts map[string]*featureFlagContext | ||
| } | ||
|
|
||
| // featureFlagContext holds feature flag state and reference count for a host. | ||
| type featureFlagContext struct { | ||
| enabled *bool | ||
| lastFetched time.Time | ||
| refCount int | ||
| cacheDuration time.Duration | ||
| } | ||
|
|
||
| var ( | ||
| flagCacheOnce sync.Once | ||
| flagCacheInstance *featureFlagCache | ||
| ) | ||
|
|
||
| // getFeatureFlagCache returns the singleton instance. | ||
| func getFeatureFlagCache() *featureFlagCache { | ||
| flagCacheOnce.Do(func() { | ||
| flagCacheInstance = &featureFlagCache{ | ||
| contexts: make(map[string]*featureFlagContext), | ||
| } | ||
| }) | ||
| return flagCacheInstance | ||
| } | ||
|
|
||
| // getOrCreateContext gets or creates a feature flag context for the host. | ||
| // Increments reference count. | ||
| func (c *featureFlagCache) getOrCreateContext(host string) *featureFlagContext { | ||
| c.mu.Lock() | ||
| defer c.mu.Unlock() | ||
|
|
||
| ctx, exists := c.contexts[host] | ||
| if !exists { | ||
| ctx = &featureFlagContext{ | ||
| cacheDuration: 15 * time.Minute, | ||
| } | ||
| c.contexts[host] = ctx | ||
| } | ||
| ctx.refCount++ | ||
| return ctx | ||
| } | ||
|
|
||
| // releaseContext decrements reference count for the host. | ||
| // Removes context when ref count reaches zero. | ||
| func (c *featureFlagCache) releaseContext(host string) { | ||
| c.mu.Lock() | ||
| defer c.mu.Unlock() | ||
|
|
||
| if ctx, exists := c.contexts[host]; exists { | ||
| ctx.refCount-- | ||
| if ctx.refCount <= 0 { | ||
| delete(c.contexts, host) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // isTelemetryEnabled checks if telemetry is enabled for the host. | ||
| // Uses cached value if available and not expired. | ||
| func (c *featureFlagCache) isTelemetryEnabled(ctx context.Context, host string, httpClient *http.Client) (bool, error) { | ||
| c.mu.RLock() | ||
| flagCtx, exists := c.contexts[host] | ||
| c.mu.RUnlock() | ||
|
|
||
| if !exists { | ||
| return false, nil | ||
| } | ||
|
|
||
| // Check if cache is valid | ||
| if flagCtx.enabled != nil && time.Since(flagCtx.lastFetched) < flagCtx.cacheDuration { | ||
| return *flagCtx.enabled, nil | ||
samikshya-db marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| // Fetch fresh value | ||
| enabled, err := fetchFeatureFlag(ctx, host, httpClient) | ||
samikshya-db marked this conversation as resolved.
Show resolved
Hide resolved
samikshya-db marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if err != nil { | ||
| // Return cached value on error, or false if no cache | ||
| if flagCtx.enabled != nil { | ||
| return *flagCtx.enabled, nil | ||
| } | ||
| return false, err | ||
| } | ||
|
|
||
| // Update cache | ||
| c.mu.Lock() | ||
| flagCtx.enabled = &enabled | ||
| flagCtx.lastFetched = time.Now() | ||
| c.mu.Unlock() | ||
|
|
||
| return enabled, nil | ||
| } | ||
|
|
||
| // isExpired returns true if the cache has expired. | ||
| func (c *featureFlagContext) isExpired() bool { | ||
| return c.enabled == nil || time.Since(c.lastFetched) > c.cacheDuration | ||
| } | ||
|
|
||
| // fetchFeatureFlag fetches the feature flag value from Databricks. | ||
| func fetchFeatureFlag(ctx context.Context, host string, httpClient *http.Client) (bool, error) { | ||
| // Construct endpoint URL, adding https:// if not already present | ||
| var endpoint string | ||
| if len(host) > 7 && (host[:7] == "http://" || host[:8] == "https://") { | ||
samikshya-db marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| endpoint = fmt.Sprintf("%s/api/2.0/feature-flags", host) | ||
| } else { | ||
| endpoint = fmt.Sprintf("https://%s/api/2.0/feature-flags", host) | ||
| } | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil) | ||
| if err != nil { | ||
| return false, fmt.Errorf("failed to create feature flag request: %w", err) | ||
| } | ||
|
|
||
| // Add query parameter for the specific feature flag | ||
| q := req.URL.Query() | ||
| q.Add("flags", "databricks.partnerplatform.clientConfigsFeatureFlags.enableTelemetryForGoDriver") | ||
| req.URL.RawQuery = q.Encode() | ||
|
|
||
| resp, err := httpClient.Do(req) | ||
| if err != nil { | ||
| return false, fmt.Errorf("failed to fetch feature flag: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return false, fmt.Errorf("feature flag check failed: %d", resp.StatusCode) | ||
samikshya-db marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| var result struct { | ||
| Flags map[string]bool `json:"flags"` | ||
| } | ||
| if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { | ||
| return false, fmt.Errorf("failed to decode feature flag response: %w", err) | ||
| } | ||
|
|
||
| enabled, ok := result.Flags["databricks.partnerplatform.clientConfigsFeatureFlags.enableTelemetryForGoDriver"] | ||
| if !ok { | ||
| return false, nil | ||
| } | ||
|
|
||
| return enabled, nil | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.