-
Notifications
You must be signed in to change notification settings - Fork 851
Add local cache to regexResolver #7363
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
SungJin1212
merged 6 commits into
cortexproject:master
from
SungJin1212:Add-local-cache-to-regexResolver
Mar 23, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1c4067b
Add local cache to regexResolver
SungJin1212 c5c6e12
Add cache hit/miss metrics
SungJin1212 f401869
Refactor test
SungJin1212 9c4240d
fix lint
SungJin1212 363d6a5
update v1-guarantees
SungJin1212 63c919a
annotation
SungJin1212 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
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 |
|---|---|---|
|
|
@@ -10,6 +10,7 @@ import ( | |
|
|
||
| "github.com/go-kit/log" | ||
| "github.com/go-kit/log/level" | ||
| lru "github.com/hashicorp/golang-lru/v2" | ||
|
Member
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. lru is the right choice. I feel. |
||
| "github.com/pkg/errors" | ||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/promauto" | ||
|
|
@@ -27,6 +28,8 @@ var ( | |
| errInvalidRegex = errors.New("invalid regex present") | ||
|
|
||
| ErrTooManyTenants = "too many tenants, max: %d, actual: %d" | ||
|
|
||
| defaultRegexCacheSize = 1000 | ||
| ) | ||
|
|
||
| // RegexResolver resolves tenantIDs matched given regex. | ||
|
|
@@ -38,12 +41,20 @@ type RegexResolver struct { | |
| maxTenant int | ||
| userScanner users.Scanner | ||
| logger log.Logger | ||
| sync.Mutex | ||
| sync.RWMutex | ||
|
|
||
| // matchedCache stores the results of regex matching | ||
| matchedCache *lru.Cache[string, []string] | ||
|
|
||
| // lastUpdateUserRun stores the timestamps of the latest update user loop run | ||
| lastUpdateUserRun prometheus.Gauge | ||
| // discoveredUsers stores the number of discovered user | ||
| discoveredUsers prometheus.Gauge | ||
| // matchedCacheSize stores the size of the matchedCache | ||
| matchedCacheSize prometheus.Gauge | ||
|
|
||
| matchedCacheHits prometheus.Counter | ||
| matchedCacheMisses prometheus.Counter | ||
| } | ||
|
|
||
| func NewRegexResolver(cfg users.UsersScannerConfig, tenantFederationCfg Config, reg prometheus.Registerer, bucketClientFactory func(ctx context.Context) (objstore.InstrumentedBucket, error), logger log.Logger) (*RegexResolver, error) { | ||
|
|
@@ -64,6 +75,27 @@ func NewRegexResolver(cfg users.UsersScannerConfig, tenantFederationCfg Config, | |
| logger: logger, | ||
| } | ||
|
|
||
| if tenantFederationCfg.RegexCacheSize > 0 { | ||
| matchedCache, err := lru.New[string, []string](tenantFederationCfg.RegexCacheSize) | ||
| if err != nil { | ||
| return nil, errors.Wrap(err, "failed to create regex cache") | ||
| } | ||
| r.matchedCache = matchedCache | ||
|
|
||
| r.matchedCacheSize = promauto.With(reg).NewGauge(prometheus.GaugeOpts{ | ||
| Name: "cortex_regex_resolver_matched_cache_size", | ||
| Help: "Number of entries stored in the matched cache.", | ||
| }) | ||
| r.matchedCacheHits = promauto.With(reg).NewCounter(prometheus.CounterOpts{ | ||
| Name: "cortex_regex_resolver_matched_cache_hits_total", | ||
| Help: "Total number of successful cache lookups for the regex matched.", | ||
| }) | ||
| r.matchedCacheMisses = promauto.With(reg).NewCounter(prometheus.CounterOpts{ | ||
| Name: "cortex_regex_resolver_matched_cache_misses_total", | ||
| Help: "Total number of cache misses for the regex matched.", | ||
| }) | ||
| } | ||
|
|
||
| r.lastUpdateUserRun = promauto.With(reg).NewGauge(prometheus.GaugeOpts{ | ||
| Name: "cortex_regex_resolver_last_update_run_timestamp_seconds", | ||
| Help: "Unix timestamp of the last successful regex resolver update user run.", | ||
|
|
@@ -88,8 +120,7 @@ func (r *RegexResolver) running(ctx context.Context) error { | |
| case <-ctx.Done(): | ||
| return ctx.Err() | ||
| case <-ticker.C: | ||
| // active and deleting users are considered | ||
| // The store-gateway can query for deleting users. | ||
| // Active and deleting users are considered | ||
| active, deleting, _, err := r.userScanner.ScanUsers(ctx) | ||
| if err != nil { | ||
| level.Error(r.logger).Log("msg", "failed to discover users from bucket", "err", err) | ||
|
|
@@ -99,6 +130,12 @@ func (r *RegexResolver) running(ctx context.Context) error { | |
| r.knownUsers = append(active, deleting...) | ||
| // We keep it sort | ||
| sort.Strings(r.knownUsers) | ||
|
|
||
| // Reset the cache because the set of available users has changed. | ||
| if r.matchedCache != nil { | ||
| r.matchedCache.Purge() | ||
| r.matchedCacheSize.Set(0) | ||
| } | ||
| r.Unlock() | ||
| r.lastUpdateUserRun.SetToCurrentTime() | ||
| r.discoveredUsers.Set(float64(len(active) + len(deleting))) | ||
|
|
@@ -126,31 +163,48 @@ func (r *RegexResolver) TenantIDs(ctx context.Context) ([]string, error) { | |
| return nil, err | ||
| } | ||
|
|
||
| orgIDs, err := r.getRegexMatchedOrgIds(orgID) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| return users.ValidateOrgIDs(orgIDs) | ||
| return r.getRegexMatchedOrgIds(orgID) | ||
| } | ||
|
|
||
| func (r *RegexResolver) getRegexMatchedOrgIds(orgID string) ([]string, error) { | ||
| var matched []string | ||
| if r.matchedCache != nil { | ||
| if cachedMatched, ok := r.matchedCache.Get(orgID); ok { | ||
| r.matchedCacheHits.Inc() | ||
| return r.validateAndReturnMatched(orgID, cachedMatched) | ||
| } | ||
| r.matchedCacheMisses.Inc() | ||
| } | ||
|
|
||
| // Use the Prometheus FastRegexMatcher | ||
| m, err := labels.NewFastRegexMatcher(orgID) | ||
| if err != nil { | ||
| return nil, errInvalidRegex | ||
| } | ||
|
|
||
| r.Lock() | ||
| defer r.Unlock() | ||
| var matched []string | ||
|
|
||
| r.RLock() | ||
| for _, id := range r.knownUsers { | ||
| if m.MatchString(id) { | ||
| matched = append(matched, id) | ||
| } | ||
| } | ||
| r.RUnlock() | ||
|
|
||
| validatedMatched, err := users.ValidateOrgIDs(matched) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if r.matchedCache != nil { | ||
| r.matchedCache.Add(orgID, validatedMatched) | ||
| r.matchedCacheSize.Set(float64(r.matchedCache.Len())) | ||
| } | ||
|
|
||
| return r.validateAndReturnMatched(orgID, validatedMatched) | ||
| } | ||
|
|
||
| func (r *RegexResolver) validateAndReturnMatched(orgID string, matched []string) ([]string, error) { | ||
| if len(matched) == 0 { | ||
| if err := users.ValidTenantID(orgID); err == nil { | ||
| // when querying for a newly created orgID, the query may not | ||
|
|
@@ -165,6 +219,7 @@ func (r *RegexResolver) getRegexMatchedOrgIds(orgID string) ([]string, error) { | |
| return []string{"fake"}, nil | ||
| } | ||
|
|
||
| // Enforce the maximum number of tenants allowed in a federated query. | ||
| if r.maxTenant > 0 && len(matched) > r.maxTenant { | ||
| return nil, httpgrpc.Errorf(http.StatusBadRequest, "%s", fmt.Errorf(ErrTooManyTenants, r.maxTenant, len(matched)).Error()) | ||
| } | ||
|
|
||
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.
If it is experimental it should be mentioned in v1-guarantees