-
Notifications
You must be signed in to change notification settings - Fork 0
fix: apply global filters to ambient recommendations #471
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
Open
cristim
wants to merge
2
commits into
main
Choose a base branch
from
fix/global-ambient-filters
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
120 changes: 120 additions & 0 deletions
120
internal/api/handler_recommendations_global_filters_integration_test.go
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,120 @@ | ||
| //go:build integration | ||
|
|
||
| package api | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/LeanerCloud/cloud-commitments-go/pkg/common" | ||
| "github.com/LeanerCloud/cloud-commitments-go/pkg/provider" | ||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/auth" | ||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/config" | ||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/database/postgres/migrations" | ||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/database/postgres/testhelpers" | ||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/scheduler" | ||
| "github.com/aws/aws-lambda-go/events" | ||
| "github.com/aws/aws-sdk-go-v2/aws" | ||
| "github.com/aws/aws-sdk-go-v2/service/sts" | ||
| "github.com/google/uuid" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| type globalFilterProvider struct { | ||
| provider.FactoryInterface | ||
| provider.Provider | ||
| provider.RecommendationsClient | ||
| } | ||
|
|
||
| func (p globalFilterProvider) CreateAndValidateProvider(_ context.Context, name string, cfg *provider.ProviderConfig) (provider.Provider, error) { | ||
| if name != "aws" || cfg != nil { | ||
| return nil, fmt.Errorf("unexpected provider request: %s", name) | ||
| } | ||
| return p, nil | ||
| } | ||
|
|
||
| func (p globalFilterProvider) GetRecommendationsClient(context.Context) (provider.RecommendationsClient, error) { | ||
| return p, nil | ||
| } | ||
|
|
||
| func (globalFilterProvider) GetAllRecommendations(context.Context) ([]common.Recommendation, error) { | ||
| return []common.Recommendation{{Provider: common.ProviderAWS, Service: common.ServiceEC2, Region: "us-east-1", ResourceType: "m5.large", Count: 1, Term: "1yr", PaymentOption: "all-upfront", EstimatedSavings: 100}}, nil | ||
| } | ||
|
|
||
| type globalFilterSTS struct{} | ||
|
|
||
| func (globalFilterSTS) GetCallerIdentity(context.Context, *sts.GetCallerIdentityInput, ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error) { | ||
| return &sts.GetCallerIdentityOutput{Account: aws.String("123456789012")}, nil | ||
| } | ||
|
|
||
| func TestGlobalFiltersCollectedRecommendationsAPI(t *testing.T) { | ||
| for _, registered := range []bool{false, true} { | ||
| t.Run(fmt.Sprintf("registered=%t", registered), func(t *testing.T) { | ||
| ctx := t.Context() | ||
| pg, err := testhelpers.SetupPostgresContainer(ctx, t) | ||
| require.NoError(t, err) | ||
| t.Cleanup(func() { require.NoError(t, pg.Cleanup(context.Background())) }) | ||
| require.NoError(t, migrations.RunMigrations(ctx, pg.DB.Pool(), "../database/postgres/migrations", "", "")) | ||
| store := config.NewPostgresStore(pg.DB) | ||
| require.NoError(t, store.SaveGlobalConfig(ctx, &config.GlobalConfig{EnabledProviders: []string{"aws"}, DefaultTerm: 1, DefaultPayment: "all-upfront"})) | ||
| account := uuid.NewString() | ||
| if registered { | ||
| require.NoError(t, store.CreateCloudAccount(ctx, &config.CloudAccount{ID: account, Name: "host", Provider: "aws", ExternalID: "123456789012", Enabled: false})) | ||
| } | ||
| collector := scheduler.NewScheduler(scheduler.SchedulerConfig{ConfigStore: store, ProviderFactory: globalFilterProvider{}, STSClient: globalFilterSTS{}, EmailSender: &stubEmailNotifier{}, IsLambda: true}) | ||
| result, err := collector.CollectRecommendations(ctx, "") | ||
| require.NoError(t, err) | ||
| require.Empty(t, result.FailedProviders) | ||
| require.Equal(t, 1, result.Recommendations) | ||
| rows, err := store.ListStoredRecommendations(ctx, config.RecommendationFilter{}) | ||
| require.NoError(t, err) | ||
| require.Len(t, rows, 1) | ||
| if registered { | ||
| require.Equal(t, &account, rows[0].CloudAccountID) | ||
| } else { | ||
| require.Nil(t, rows[0].CloudAccountID) | ||
| } | ||
| var nulls int | ||
| require.NoError(t, pg.DB.Pool().QueryRow(ctx, "SELECT count(*) FROM recommendations WHERE cloud_account_id IS NULL").Scan(&nulls)) | ||
| assert.Equal(t, !registered, nulls == 1) | ||
| authStore := auth.NewPostgresStore(pg.DB) | ||
| csrf := []byte(strings.Repeat("f", 32)) | ||
| _, token, _ := marketplaceSession(t, authStore, []auth.Permission{{Action: auth.ActionView, Resource: "recommendations"}}, []string{"*"}, csrf) | ||
| h := NewHandler(HandlerConfig{ConfigStore: store, Scheduler: collector, AuthService: &marketplaceAuthFixture{service: auth.NewService(auth.ServiceConfig{Store: authStore, CSRFKey: csrf})}}) | ||
| request := func(path string, out any) { | ||
| t.Helper() | ||
| response, err := h.HandleRequest(ctx, &events.LambdaFunctionURLRequest{Headers: map[string]string{"authorization": "Bearer " + token}, RequestContext: events.LambdaFunctionURLRequestContext{HTTP: events.LambdaFunctionURLRequestContextHTTPDescription{Method: "GET", Path: path}}}) | ||
| require.NoError(t, err) | ||
| require.Equal(t, 200, response.StatusCode, response.Body) | ||
| require.NoError(t, json.Unmarshal([]byte(response.Body), out)) | ||
| } | ||
| var initial RecommendationsResponse | ||
| request("/api/recommendations", &initial) | ||
| require.Len(t, initial.Recommendations, 1, "no global configuration") | ||
| for _, enabled := range []bool{true, false, true} { | ||
| require.NoError(t, store.SaveServiceConfig(ctx, &config.ServiceConfig{Provider: "aws", Service: "ec2", Enabled: enabled, Term: 1, Payment: "all-upfront", Coverage: 100})) | ||
| var list RecommendationsResponse | ||
| request("/api/recommendations", &list) | ||
| var detail RecommendationDetailResponse | ||
| request("/api/recommendations/"+rows[0].ID+"/detail", &detail) | ||
| var summary DashboardSummaryResponse | ||
| request("/api/dashboard/summary", &summary) | ||
| if enabled { | ||
| assert.Len(t, list.Recommendations, 1) | ||
| assert.Equal(t, 1, summary.TotalRecommendations) | ||
| assert.Equal(t, 100.0, summary.PotentialMonthlySavings) | ||
| assert.Empty(t, detail.HiddenBy) | ||
| } else { | ||
| assert.Empty(t, list.Recommendations) | ||
| assert.Zero(t, summary.TotalRecommendations) | ||
| assert.Zero(t, summary.PotentialMonthlySavings) | ||
| assert.Equal(t, []string{"enabled=false"}, detail.HiddenBy) | ||
| } | ||
| } | ||
| }) | ||
| } | ||
| } |
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
102 changes: 102 additions & 0 deletions
102
internal/scheduler/scheduler_global_filters_integration_test.go
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,102 @@ | ||
| //go:build integration | ||
|
|
||
| package scheduler | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/config" | ||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/database/postgres/migrations" | ||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/database/postgres/testhelpers" | ||
| "github.com/google/uuid" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestGlobalFiltersPersistedAmbientAndRegistered(t *testing.T) { | ||
| ctx := t.Context() | ||
| pg, err := testhelpers.SetupPostgresContainer(ctx, t) | ||
| require.NoError(t, err) | ||
| t.Cleanup(func() { require.NoError(t, pg.Cleanup(context.Background())) }) | ||
| require.NoError(t, migrations.RunMigrations(ctx, pg.DB.Pool(), "../database/postgres/migrations", "", "")) | ||
| store := config.NewPostgresStore(pg.DB) | ||
| account := uuid.NewString() | ||
| require.NoError(t, store.CreateCloudAccount(ctx, &config.CloudAccount{ID: account, Name: "registered", Provider: "aws", ExternalID: "111111111111", Enabled: true})) | ||
| records := make([]config.RecommendationRecord, 0, 10) | ||
| for i, id := range []*string{nil, &account} { | ||
| for _, count := range []int{1, 10, 11} { | ||
| records = append(records, config.RecommendationRecord{ID: fmt.Sprintf("%d-%d", i, count), Provider: "aws", Service: "rds", Region: "us-east-1", ResourceType: fmt.Sprintf("db.m5.%d", count), Engine: "mysql", Count: count, Term: 1, Payment: "all-upfront", CloudAccountID: id}) | ||
| } | ||
| records = append(records, | ||
| config.RecommendationRecord{ID: fmt.Sprintf("%d-sibling", i), Provider: "aws", Service: "rds", Region: "us-west-2", ResourceType: "db.r6g.large", Engine: "postgres", Count: 12, Term: 1, Payment: "all-upfront", CloudAccountID: id}, | ||
| config.RecommendationRecord{ID: fmt.Sprintf("%d-other", i), Provider: "aws", Service: "ec2", Region: "us-east-1", ResourceType: "m5.large", Count: 1, Term: 1, Payment: "all-upfront", CloudAccountID: id}) | ||
| } | ||
| require.NoError(t, store.UpsertRecommendations(ctx, time.Now(), records, nil)) | ||
| s := &Scheduler{config: store, isLambda: true} | ||
| _, err = store.GetServiceConfig(ctx, "aws", "rds") | ||
| require.ErrorIs(t, err, config.ErrNotFound) | ||
| all, err := s.ListRecommendations(ctx, config.RecommendationFilter{}) | ||
| require.NoError(t, err) | ||
| require.Len(t, all, 10) | ||
| for _, tc := range []struct { | ||
| name string | ||
| policy config.ServiceConfig | ||
| want []string | ||
| reason string | ||
| }{ | ||
| {"disabled", config.ServiceConfig{}, nil, "enabled=false"}, | ||
| {"enabled", config.ServiceConfig{Enabled: true}, []string{"1", "10", "11", "sibling"}, ""}, | ||
| {"minimum", config.ServiceConfig{Enabled: true, MinCount: 10}, []string{"10", "11", "sibling"}, ""}, | ||
| {"include engine", config.ServiceConfig{Enabled: true, IncludeEngines: []string{"postgres"}}, []string{"sibling"}, "engine"}, | ||
| {"exclude engine", config.ServiceConfig{Enabled: true, ExcludeEngines: []string{"mysql"}}, []string{"sibling"}, "engine"}, | ||
| {"include region", config.ServiceConfig{Enabled: true, IncludeRegions: []string{"us-west-2"}}, []string{"sibling"}, "region"}, | ||
| {"exclude region", config.ServiceConfig{Enabled: true, ExcludeRegions: []string{"us-east-1"}}, []string{"sibling"}, "region"}, | ||
| {"include type", config.ServiceConfig{Enabled: true, IncludeTypes: []string{"db.m5.10"}}, []string{"10"}, "resource_type"}, | ||
| {"exclude type", config.ServiceConfig{Enabled: true, ExcludeTypes: []string{"db.m5.1"}}, []string{"10", "11", "sibling"}, "resource_type"}, | ||
| {"exclude wins", config.ServiceConfig{Enabled: true, IncludeRegions: []string{"us-east-1", "us-west-2"}, ExcludeRegions: []string{"us-east-1"}}, []string{"sibling"}, "region"}, | ||
| } { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| tc.policy.Provider, tc.policy.Service, tc.policy.Term, tc.policy.Payment = "aws", "rds", 1, "all-upfront" | ||
| require.NoError(t, store.SaveServiceConfig(ctx, &tc.policy)) | ||
| got, err := s.ListRecommendations(ctx, config.RecommendationFilter{}) | ||
| require.NoError(t, err) | ||
| ids := make([]string, 0, len(got)) | ||
| for _, rec := range got { | ||
| ids = append(ids, rec.ID) | ||
| _, hidden, err := s.GetRecommendationByID(ctx, rec.ID) | ||
| require.NoError(t, err) | ||
| assert.Empty(t, hidden, "visible recommendation %s", rec.ID) | ||
| } | ||
| want := make([]string, 2, 2+2*len(tc.want)) | ||
| want[0], want[1] = "0-other", "1-other" | ||
| for _, suffix := range tc.want { | ||
| want = append(want, "0-"+suffix, "1-"+suffix) | ||
| } | ||
| assert.ElementsMatch(t, want, ids) | ||
| for _, id := range []string{"0-1", "1-1"} { | ||
| rec, hidden, err := s.GetRecommendationByID(ctx, id) | ||
| require.NoError(t, err) | ||
| require.NotNil(t, rec) | ||
| if tc.reason != "" { | ||
| assert.Contains(t, hidden, tc.reason) | ||
| } else { | ||
| assert.Empty(t, hidden) | ||
| } | ||
| } | ||
| }) | ||
| } | ||
| t.Run("registered override wins", func(t *testing.T) { | ||
| require.NoError(t, store.SaveServiceConfig(ctx, &config.ServiceConfig{Provider: "aws", Service: "rds", Term: 1, Payment: "all-upfront"})) | ||
| require.NoError(t, store.SaveAccountServiceOverride(ctx, &config.AccountServiceOverride{AccountID: account, Provider: "aws", Service: "rds", Enabled: boolPtr(true)})) | ||
| got, err := s.ListRecommendations(ctx, config.RecommendationFilter{}) | ||
| require.NoError(t, err) | ||
| ids := make([]string, 0, len(got)) | ||
| for _, rec := range got { | ||
| ids = append(ids, rec.ID) | ||
| } | ||
| assert.ElementsMatch(t, []string{"0-other", "1-other", "1-1", "1-10", "1-11", "1-sibling"}, ids) | ||
| }) | ||
| } |
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.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Distinguish global policy from an account override in the detail response.
When global configuration hides an ambient recommendation, this line populates
HiddenByeven though the recommendation has no account override.internal/api/types.godescribes that field as an override marker and says the frontend displays “hidden by your override.” Use a source-neutral explanation, or identify the policy source so the detail page does not direct users to a nonexistent override.🤖 Prompt for AI Agents