Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: refactor limit (#16497)
Danny Xu828b88a17794
diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.goindex 0129ce10d6..1c9fc5d07a 100644--- a/backend/api/v1/instance_service.go+++ b/backend/api/v1/instance_service.go@@ -321,14 +321,14 @@ func (s *InstanceService) CreateInstance(ctx context.Context, request *v1pb.Creareturn convertInstanceMessage(instanceMessage)}- instanceCountLimit := s.licenseService.GetInstanceLicenseCount(ctx)+ activatedInstanceLimit := s.licenseService.GetActivatedInstanceLimit(ctx)if instanceMessage.Metadata.GetActivation() {count, err := s.store.GetActivatedInstanceCount(ctx)if err != nil {return nil, status.Error(codes.Internal, err.Error())}- if count >= instanceCountLimit {- return nil, status.Errorf(codes.ResourceExhausted, instanceExceededError, instanceCountLimit)+ if count >= activatedInstanceLimit {+ return nil, status.Errorf(codes.ResourceExhausted, instanceExceededError, activatedInstanceLimit)}}@@ -479,14 +479,14 @@ func (s *InstanceService) UpdateInstance(ctx context.Context, request *v1pb.Upda}}- instanceCountLimit := s.licenseService.GetInstanceLicenseCount(ctx)+ activatedInstanceLimit := s.licenseService.GetActivatedInstanceLimit(ctx)if updateActivation {count, err := s.store.GetActivatedInstanceCount(ctx)if err != nil {return nil, status.Error(codes.Internal, err.Error())}- if count >= instanceCountLimit {- return nil, status.Errorf(codes.ResourceExhausted, instanceExceededError, instanceCountLimit)+ if count >= activatedInstanceLimit {+ return nil, status.Errorf(codes.ResourceExhausted, instanceExceededError, activatedInstanceLimit)}}@@ -1414,7 +1414,7 @@ func convertV1DataSourceType(tp v1pb.DataSourceType) (storepb.DataSourceType, er}func (s *InstanceService) instanceCountGuard(ctx context.Context) error {- instanceLimit := s.licenseService.GetPlanLimitValue(ctx, enterprise.PlanLimitMaximumInstance)+ instanceLimit := s.licenseService.GetInstanceLimit(ctx)count, err := s.store.CountInstance(ctx, &store.CountInstanceMessage{})if err != nil {diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.goindex 36a91530ff..9ae5697370 100644--- a/backend/api/v1/user_service.go+++ b/backend/api/v1/user_service.go@@ -921,7 +921,7 @@ func generateRecoveryCodes(n int) ([]string, error) {}func (s *UserService) userCountGuard(ctx context.Context) error {- userLimit := s.licenseService.GetPlanLimitValue(ctx, enterprise.PlanLimitMaximumUser)+ userLimit := s.licenseService.GetUserLimit(ctx)count, err := s.store.CountActiveUsers(ctx)if err != nil {diff --git a/backend/enterprise/license.go b/backend/enterprise/license.goindex 247a8426d9..4333524c68 100644--- a/backend/enterprise/license.go+++ b/backend/enterprise/license.go@@ -58,7 +58,8 @@ func (s *LicenseService) LoadSubscription(ctx context.Context) *v1pb.Subscriptios.mu.RUnlock()if cached != nil {- if cached.Plan == v1pb.PlanType_FREE || isSubscriptionExpired(cached) {+ // Invalidate the cache if expired.+ if cached.ExpiresTime != nil && cached.ExpiresTime.AsTime().Before(time.Now()) {// refresh expired subscriptions.mu.Lock()s.cachedSubscription = nil@@ -73,26 +74,32 @@ func (s *LicenseService) LoadSubscription(ctx context.Context) *v1pb.Subscriptio// Cache the subscription.s.mu.Lock()defer s.mu.Unlock()- // Double-check after acquiring write lock- if s.cachedSubscription != nil && s.cachedSubscription.Plan != v1pb.PlanType_FREE && !isSubscriptionExpired(s.cachedSubscription) {- return s.cachedSubscription++ subscription := s.provider.LoadSubscription(ctx)+ if subscription == nil {+ // Never had a subscription, set to free plan.+ subscription = &v1pb.Subscription{+ Plan: v1pb.PlanType_FREE,+ }+ }+ // Switch to free plan if the subscription is expired.+ if subscription.ExpiresTime != nil && subscription.ExpiresTime.AsTime().Before(time.Now()) {+ subscription.Plan = v1pb.PlanType_FREE}- s.cachedSubscription = s.provider.LoadSubscription(ctx)- return s.cachedSubscription+ s.cachedSubscription = subscription+ return subscription}-// isSubscriptionExpired returns if the subscription is expired.-func isSubscriptionExpired(s *v1pb.Subscription) bool {- if s.Plan == v1pb.PlanType_FREE || s.ExpiresTime == nil {- return false- }- return s.ExpiresTime.AsTime().Before(time.Now())+// GetEffectivePlan gets the effective plan.+func (s *LicenseService) GetEffectivePlan() v1pb.PlanType {+ ctx := context.Background()+ return s.LoadSubscription(ctx).Plan}// IsFeatureEnabled returns whether a feature is enabled.func (s *LicenseService) IsFeatureEnabled(f v1pb.PlanFeature) error {plan := s.GetEffectivePlan()- features, ok := PlanFeatureMatrix[plan]+ features, ok := planFeatureMatrix[plan]if !ok || !features[f] {return errors.New(accessErrorMessage(f))}@@ -109,66 +116,48 @@ func (s *LicenseService) IsFeatureEnabledForInstance(f v1pb.PlanFeature, instancif err := s.IsFeatureEnabled(f); err != nil {return err}- if !instanceLimitFeature[f] {- // If the feature not exists in the limit map, we just need to check the feature for current plan.- return nil- }if !instance.Metadata.GetActivation() {return errors.Errorf(`feature "%s" is not available for instance %s, please assign license to the instance to enable it`, f.String(), instance.ResourceID)}return nil}-// GetInstanceLicenseCount returns the instance count limit for current subscription.-func (s *LicenseService) GetInstanceLicenseCount(ctx context.Context) int {- instanceCount := s.LoadSubscription(ctx).InstanceCount- if instanceCount < 0 {+// GetActivatedInstanceLimit returns the activated instance limit for the current subscription.+func (s *LicenseService) GetActivatedInstanceLimit(ctx context.Context) int {+ limit := s.LoadSubscription(ctx).InstanceCount+ if limit < 0 {return math.MaxInt}- return int(instanceCount)+ return int(limit)}-// GetEffectivePlan gets the effective plan.-func (s *LicenseService) GetEffectivePlan() v1pb.PlanType {- ctx := context.Background()+// GetUserLimit gets the user limit value for the plan.+func (s *LicenseService) GetUserLimit(ctx context.Context) int {subscription := s.LoadSubscription(ctx)- if subscription.ExpiresTime != nil && subscription.ExpiresTime.AsTime().Before(time.Now()) {- return v1pb.PlanType_FREE+ limit := userLimitValues[subscription.Plan]+ if subscription.Plan == v1pb.PlanType_FREE {+ return limit+ }++ // To be compatible with old licenses which don't have seat field set in the claim.+ if subscription.SeatCount == 0 {+ return math.MaxInt}- return subscription.Plan-}-// GetPlanLimitValue gets the limit value for the plan.-func (s *LicenseService) GetPlanLimitValue(ctx context.Context, name PlanLimit) int {- v, ok := PlanLimitValues[name]- if !ok {- return 0+ // Unlimited seat license.+ if subscription.SeatCount < 0 {+ return math.MaxInt}+ return int(subscription.SeatCount)+}++// GetInstanceLimit gets the instance limit value for the plan.+func (s *LicenseService) GetInstanceLimit(ctx context.Context) int {subscription := s.LoadSubscription(ctx)- limit := v[subscription.Plan]+ limit := instanceLimitValues[subscription.Plan]if limit == -1 {limit = math.MaxInt}-- switch subscription.Plan {- case v1pb.PlanType_FREE:- return limit- case v1pb.PlanType_TEAM, v1pb.PlanType_ENTERPRISE:- switch name {- case PlanLimitMaximumInstance:- return limit- case PlanLimitMaximumUser:- if subscription.SeatCount == 0 {- // to compatible with old license.- return limit- }- if subscription.SeatCount < 0 {- return math.MaxInt- }- return int(subscription.SeatCount)- }- }-return limit}@@ -180,8 +169,6 @@ func (s *LicenseService) RefreshCache(ctx context.Context) {s.LoadSubscription(ctx)}-// Helper functions to avoid circular import-// accessErrorMessage returns a error message with feature name and minimum supported plan.func accessErrorMessage(f v1pb.PlanFeature) string {plan := minimumSupportedPlan(f)@@ -191,18 +178,11 @@ func accessErrorMessage(f v1pb.PlanFeature) string {// minimumSupportedPlan will find the minimum plan which supports the target feature.func minimumSupportedPlan(f v1pb.PlanFeature) v1pb.PlanType {// Check from lowest to highest plan- if PlanFeatureMatrix[v1pb.PlanType_FREE][f] {+ if planFeatureMatrix[v1pb.PlanType_FREE][f] {return v1pb.PlanType_FREE}- if PlanFeatureMatrix[v1pb.PlanType_TEAM][f] {+ if planFeatureMatrix[v1pb.PlanType_TEAM][f] {return v1pb.PlanType_TEAM}return v1pb.PlanType_ENTERPRISE}--// instanceLimitFeature is the map for instance feature. Only allowed to access these feature for activate instance.-var instanceLimitFeature = map[v1pb.PlanFeature]bool{- v1pb.PlanFeature_FEATURE_DATABASE_SECRET_VARIABLES: true,- v1pb.PlanFeature_FEATURE_INSTANCE_READ_ONLY_CONNECTION: true,- v1pb.PlanFeature_FEATURE_DATA_MASKING: true,-}diff --git a/backend/enterprise/limit.go b/backend/enterprise/limit.goindex 0343bf14a1..07cb325a9b 100644--- a/backend/enterprise/limit.go+++ b/backend/enterprise/limit.go@@ -13,24 +13,11 @@ import (//go:embed plan.yamlvar planConfigStr string-// PlanLimit is the type for plan limits.-type PlanLimit int+var userLimitValues = map[v1pb.PlanType]int{}+var instanceLimitValues = map[v1pb.PlanType]int{}-const (- // PlanLimitMaximumInstance is the key name for maximum number of instance for a plan.- PlanLimitMaximumInstance = iota- // PlanLimitMaximumUser is the key name for maximum number of user for a plan.- PlanLimitMaximumUser-)--// PlanLimitValues is the plan limit value mapping.-var PlanLimitValues = map[PlanLimit]map[v1pb.PlanType]int{- PlanLimitMaximumInstance: {},- PlanLimitMaximumUser: {},-}--// PlanFeatureMatrix maps plans to their available features-var PlanFeatureMatrix = make(map[v1pb.PlanType]map[v1pb.PlanFeature]bool)+// planFeatureMatrix maps plans to their available features+var planFeatureMatrix = make(map[v1pb.PlanType]map[v1pb.PlanFeature]bool)func init() {// First unmarshal YAML to a generic map, then convert to JSON for protojson@@ -52,13 +39,12 @@ func init() {}for _, plan := range conf.Plans {- PlanLimitValues[PlanLimitMaximumInstance][plan.Type] = int(plan.MaximumInstanceCount)- PlanLimitValues[PlanLimitMaximumUser][plan.Type] = int(plan.MaximumSeatCount)+ userLimitValues[plan.Type] = int(plan.MaximumSeatCount)+ instanceLimitValues[plan.Type] = int(plan.MaximumInstanceCount)- // Initialize feature map for this plan- PlanFeatureMatrix[plan.Type] = make(map[v1pb.PlanFeature]bool)+ planFeatureMatrix[plan.Type] = make(map[v1pb.PlanFeature]bool)for _, feature := range plan.Features {- PlanFeatureMatrix[plan.Type][feature] = true+ planFeatureMatrix[plan.Type][feature] = true}}}diff --git a/backend/enterprise/plugin/aws/aws.go b/backend/enterprise/plugin/aws/aws.goindex 3b12d00a50..35139fcc67 100644--- a/backend/enterprise/plugin/aws/aws.go+++ b/backend/enterprise/plugin/aws/aws.go@@ -66,26 +66,22 @@ func (*Provider) StoreLicense(_ context.Context, _ string) error {// LoadSubscription will load the aws subscription.func (p *Provider) LoadSubscription(ctx context.Context) *v1pb.Subscription {- subscription := &v1pb.Subscription{- InstanceCount: 0,- SeatCount: 0,- Plan: v1pb.PlanType_FREE,- OrgName: aws.ToString(p.identity.Account),- }-license, err := p.checkoutLicense(ctx)if err != nil {slog.Error("failed to checkout license",log.BBError(err),)- return subscription+ return nil}if license.Status != types.LicenseStatusAvailable {- return subscription+ return nil}- subscription.Plan = v1pb.PlanType_ENTERPRISE+ subscription := &v1pb.Subscription{+ Plan: v1pb.PlanType_ENTERPRISE,+ OrgName: aws.ToString(p.identity.Account),+ }if v := license.Validity; v != nil {end, err := time.Parse(time.RFC3339, aws.ToString(v.End))@@ -94,9 +90,9 @@ func (p *Provider) LoadSubscription(ctx context.Context) *v1pb.Subscription {slog.String("end", *v.Begin),log.BBError(err),)- } else {- subscription.ExpiresTime = timestamppb.New(end.UTC())+ return nil}+ subscription.ExpiresTime = timestamppb.New(end.UTC())}for _, entitlement := range license.Entitlements {diff --git a/backend/enterprise/plugin/hub/hub.go b/backend/enterprise/plugin/hub/hub.goindex d03ac850a6..390f5160fd 100644--- a/backend/enterprise/plugin/hub/hub.go+++ b/backend/enterprise/plugin/hub/hub.go@@ -93,22 +93,29 @@ func (p *Provider) StoreLicense(ctx context.Context, license string) error {// LoadSubscription will load the hub subscription.func (p *Provider) LoadSubscription(ctx context.Context) *v1pb.Subscription {- license := p.loadLicense(ctx)+ license, err := p.findEnterpriseLicense(ctx)+ if err != nil {+ slog.Debug("failed to load enterprise license", log.BBError(err))+ }+if license == nil {- return &v1pb.Subscription{- Plan: v1pb.PlanType_FREE,- // nil ExpiresTime means not expire, just for free plan- ExpiresTime: nil,- // Instance license count.- InstanceCount: 0,- SeatCount: 0,+ license, err = p.fetchAndStoreLicense(ctx)+ if err != nil {+ slog.Debug("failed to fetch license", log.BBError(err))}}+ if license == nil {+ return nil+ }+ if err := validateSubscription(license); err != nil {+ slog.Debug("license is invalid", log.BBError(err))+ return nil+ }return license}-func (p *Provider) fetchLicense(ctx context.Context) (*v1pb.Subscription, error) {+func (p *Provider) fetchAndStoreLicense(ctx context.Context) (*v1pb.Subscription, error) {license, err := p.remoteProvider.FetchLicense(ctx)if err != nil {return nil, err@@ -131,31 +138,6 @@ func (p *Provider) fetchLicense(ctx context.Context) (*v1pb.Subscription, error)return result, nil}-// loadLicense will load license and validate it.-func (p *Provider) loadLicense(ctx context.Context) *v1pb.Subscription {- license, err := p.findEnterpriseLicense(ctx)- if err != nil {- slog.Debug("failed to load enterprise license", log.BBError(err))- }-- if license == nil {- license, err = p.fetchLicense(ctx)- if err != nil {- slog.Debug("failed to fetch license", log.BBError(err))- }- }- if license == nil {- return nil- }-- if err := validateSubscription(license); err != nil {- slog.Debug("license is invalid", log.BBError(err))- return nil- }-- return license-}-func (p *Provider) parseLicense(ctx context.Context, license string) (*v1pb.Subscription, error) {claim := &claims{}if err := parseJWTToken(license, p.config.Version, p.config.PublicKey, claim); err != nil {