Skip to content
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

chore: Improve performance of TenantID #541

Merged
merged 4 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion tenant/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,18 @@ import (
//
//nolint:revive
func TenantID(ctx context.Context) (string, error) {
orgIDs, err := TenantIDs(ctx)
//lint:ignore faillint wrapper around upstream method
orgID, err := user.ExtractOrgID(ctx)
if err != nil {
return "", err
}
if !strings.Contains(orgID, tenantIDsSeparator) {
if err := ValidTenantID(orgID); err != nil {
return "", err
}
return orgID, nil
}
orgIDs, err := tenantIDsFromString(orgID)
if err != nil {
return "", err
}
Expand All @@ -42,6 +53,10 @@ func TenantIDs(ctx context.Context) ([]string, error) {
return nil, err
}

return tenantIDsFromString(orgID)
}

func tenantIDsFromString(orgID string) ([]string, error) {
orgIDs := strings.Split(orgID, tenantIDsSeparator)
for _, id := range orgIDs {
if err := ValidTenantID(id); err != nil {
Expand Down
23 changes: 23 additions & 0 deletions tenant/tenant_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package tenant

import (
"context"
"strings"
"testing"

"github.com/grafana/dskit/user"

"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -48,3 +51,23 @@ func TestValidTenantIDs(t *testing.T) {
})
}
}

func BenchmarkTenantID(b *testing.B) {
singleCtx := context.Background()
singleCtx = user.InjectOrgID(singleCtx, "tenant-a")
multiCtx := context.Background()
multiCtx = user.InjectOrgID(multiCtx, "tenant-a|tenant-b|tenant-c")

b.ResetTimer()
b.ReportAllocs()
b.Run("single", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_, _ = TenantID(singleCtx)
}
})
b.Run("multi", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_, _ = TenantID(multiCtx)
}
})
}