Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: feature guard for instance & user count (#6847)

ecmadao1e3fe01851ee
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index a67516d88b..2071ae6bce 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -89,6 +89,10 @@ func (s *AuthService) ListUsers(ctx context.Context, request *v1pb.ListUsersRequ
// CreateUser creates a user.
func (s *AuthService) CreateUser(ctx context.Context, request *v1pb.CreateUserRequest) (*v1pb.User, error) {
+ if err := s.userCountGuard(ctx); err != nil {
+ return nil, err
+ }
+
setting, err := s.store.GetWorkspaceGeneralSetting(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to find workspace setting, error: %v", err)
@@ -869,3 +873,17 @@ func generateRecoveryCodes(n int) ([]string, error) {
}
return recoveryCodes, nil
}
+
+func (s *AuthService) userCountGuard(ctx context.Context) error {
+ userLimit := s.licenseService.GetPlanLimitValue(enterpriseAPI.PlanLimitMaximumUser)
+
+ count, err := s.store.CountPrincipal(ctx)
+ if err != nil {
+ return status.Errorf(codes.Internal, err.Error())
+ }
+ if int64(count) >= userLimit {
+ return status.Errorf(codes.ResourceExhausted, "reached the maximum user count %d", userLimit)
+ }
+
+ return nil
+}
diff --git a/backend/api/v1/environment_service.go b/backend/api/v1/environment_service.go
index d2fcffced0..8c5c266149 100644
--- a/backend/api/v1/environment_service.go
+++ b/backend/api/v1/environment_service.go
@@ -71,7 +71,7 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, request *v1p
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
- maximumEnvironmentLimit := s.licenseService.GetPlanLimitValue(api.PlanLimitMaximumEnvironment)
+ maximumEnvironmentLimit := s.licenseService.GetPlanLimitValue(enterpriseAPI.PlanLimitMaximumEnvironment)
if int64(len(environments)) >= maximumEnvironmentLimit {
return nil, status.Errorf(codes.ResourceExhausted, "current plan can create up to %d environments.", maximumEnvironmentLimit)
}
diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.go
index 5841964740..7c62835090 100644
--- a/backend/api/v1/instance_service.go
+++ b/backend/api/v1/instance_service.go
@@ -87,6 +87,10 @@ func (s *InstanceService) CreateInstance(ctx context.Context, request *v1pb.Crea
return nil, status.Errorf(codes.InvalidArgument, "invalid instance ID %v", request.InstanceId)
}
+ if err := s.instanceCountGuard(ctx); err != nil {
+ return nil, err
+ }
+
instanceMessage, err := s.convertToInstanceMessage(request.InstanceId, request.Instance)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
@@ -764,6 +768,20 @@ func (s *InstanceService) convertToDataSourceMessage(dataSource *v1pb.DataSource
}, nil
}
+func (s *InstanceService) instanceCountGuard(ctx context.Context) error {
+ instanceLimit := s.licenseService.GetPlanLimitValue(enterpriseAPI.PlanLimitMaximumInstance)
+
+ count, err := s.store.CountInstance(ctx, &store.CountInstanceMessage{})
+ if err != nil {
+ return status.Errorf(codes.Internal, err.Error())
+ }
+ if int64(count) >= instanceLimit {
+ return status.Errorf(codes.ResourceExhausted, "reached the maximum instance count %d", instanceLimit)
+ }
+
+ return nil
+}
+
func convertDataSourceTp(tp v1pb.DataSourceType) (api.DataSourceType, error) {
var dsType api.DataSourceType
switch tp {
diff --git a/backend/enterprise/api/license.go b/backend/enterprise/api/license.go
index 065e3a1eff..b35ce0fbcd 100644
--- a/backend/enterprise/api/license.go
+++ b/backend/enterprise/api/license.go
@@ -3,6 +3,7 @@ package api
import (
"context"
+ "math"
"strings"
"time"
@@ -12,6 +13,28 @@ import (
"github.com/bytebase/bytebase/backend/store"
)
+// PlanLimit is the type for plan limits.
+type PlanLimit int
+
+const (
+ // PlanLimitMaximumTask is the key name for maximum number of tasks for a plan.
+ PlanLimitMaximumTask PlanLimit = iota
+ // PlanLimitMaximumEnvironment is the key name for maximum number of environments for a plan.
+ PlanLimitMaximumEnvironment
+ // PlanLimitMaximumInstance is the key name for maximum number of instance for a plan.
+ PlanLimitMaximumInstance
+ // 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][3]int64{
+ PlanLimitMaximumTask: {math.MaxInt64, math.MaxInt64, math.MaxInt64},
+ PlanLimitMaximumEnvironment: {math.MaxInt64, math.MaxInt64, math.MaxInt64},
+ PlanLimitMaximumInstance: {20, 20, math.MaxInt64},
+ PlanLimitMaximumUser: {20, math.MaxInt64, math.MaxInt64},
+}
+
// validPlans is a string array of valid plan types.
var validPlans = []api.PlanType{
api.TEAM,
@@ -70,7 +93,7 @@ type LicenseService interface {
// GetEffectivePlan gets the effective plan.
GetEffectivePlan() api.PlanType
// GetPlanLimitValue gets the limit value for the plan.
- GetPlanLimitValue(name api.PlanLimit) int64
+ GetPlanLimitValue(name PlanLimit) int64
// GetInstanceLicenseCount returns the instance count limit for current subscription.
GetInstanceLicenseCount(ctx context.Context) int
// RefreshCache will invalidate and refresh the subscription cache.
diff --git a/backend/enterprise/config/config.go b/backend/enterprise/config/config.go
index 20b53ca897..2462dcde68 100644
--- a/backend/enterprise/config/config.go
+++ b/backend/enterprise/config/config.go
@@ -35,8 +35,6 @@ const (
issuer = "bytebase"
// audience is the license token audience.
audience = "bb.license"
- // MaximumInstanceForFreePlan is the maximum instance limit for the FREE plan.
- MaximumInstanceForFreePlan = 20
)
// NewConfig will create a new enterprise config instance.
diff --git a/backend/enterprise/service/license.go b/backend/enterprise/service/license.go
index d636b8e016..eeb7d464c2 100644
--- a/backend/enterprise/service/license.go
+++ b/backend/enterprise/service/license.go
@@ -84,8 +84,9 @@ func (s *LicenseService) LoadSubscription(ctx context.Context) enterpriseAPI.Sub
return enterpriseAPI.Subscription{
Plan: api.FREE,
// -1 means not expire, just for free plan
- ExpiresTs: -1,
- InstanceCount: config.MaximumInstanceForFreePlan,
+ ExpiresTs: -1,
+ // Instance license count.
+ InstanceCount: 0,
}
}
@@ -112,6 +113,11 @@ func (s *LicenseService) IsFeatureEnabled(feature api.FeatureType) error {
// IsFeatureEnabledForInstance returns whether a feature is enabled for the instance.
func (s *LicenseService) IsFeatureEnabledForInstance(feature api.FeatureType, instance *store.InstanceMessage) error {
+ plan := s.GetEffectivePlan()
+ // DONOT check instance license fo FREE plan.
+ if plan == api.FREE {
+ return s.IsFeatureEnabled(feature)
+ }
if err := s.IsFeatureEnabled(feature); err != nil {
return err
}
@@ -145,8 +151,8 @@ func (s *LicenseService) GetEffectivePlan() api.PlanType {
}
// GetPlanLimitValue gets the limit value for the plan.
-func (s *LicenseService) GetPlanLimitValue(name api.PlanLimit) int64 {
- v, ok := api.PlanLimitValues[name]
+func (s *LicenseService) GetPlanLimitValue(name enterpriseAPI.PlanLimit) int64 {
+ v, ok := enterpriseAPI.PlanLimitValues[name]
if !ok {
return 0
}
diff --git a/backend/legacyapi/plan.go b/backend/legacyapi/plan.go
index 8e6fec23a8..9cfb53ab53 100644
--- a/backend/legacyapi/plan.go
+++ b/backend/legacyapi/plan.go
@@ -2,7 +2,6 @@ package api
import (
"fmt"
- "math"
)
// PlanType is the type for a plan.
@@ -346,22 +345,6 @@ var InstanceLimitFeature = map[FeatureType]bool{
// FeatureCustomApproval: true,
}
-// PlanLimit is the type for plan limits.
-type PlanLimit int
-
-const (
- // PlanLimitMaximumTask is the key name for maximum number of tasks for a plan.
- PlanLimitMaximumTask PlanLimit = iota
- // PlanLimitMaximumEnvironment is the key name for maximum number of environments for a plan.
- PlanLimitMaximumEnvironment
-)
-
-// PlanLimitValues is the plan limit value mapping.
-var PlanLimitValues = map[PlanLimit][3]int64{
- PlanLimitMaximumTask: {math.MaxInt64, math.MaxInt64, math.MaxInt64},
- PlanLimitMaximumEnvironment: {math.MaxInt64, math.MaxInt64, math.MaxInt64},
-}
-
// Feature returns whether a particular feature is available in a particular plan.
func Feature(feature FeatureType, plan PlanType) bool {
matrix, ok := FeatureMatrix[feature]
diff --git a/backend/server/issue.go b/backend/server/issue.go
index 33504ebd4b..7b8d259fae 100644
--- a/backend/server/issue.go
+++ b/backend/server/issue.go
@@ -23,6 +23,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/activity"
+ enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
metricAPI "github.com/bytebase/bytebase/backend/metric"
"github.com/bytebase/bytebase/backend/plugin/db"
@@ -950,7 +951,7 @@ func (s *Server) getPipelineCreateForDatabaseSchemaAndDataUpdate(ctx context.Con
return nil, echo.NewHTTPError(http.StatusForbidden, err.Error())
}
}
- maximumTaskLimit := s.licenseService.GetPlanLimitValue(api.PlanLimitMaximumTask)
+ maximumTaskLimit := s.licenseService.GetPlanLimitValue(enterpriseAPI.PlanLimitMaximumTask)
if int64(databaseIDCount) > maximumTaskLimit {
return nil, echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("Current plan can update up to %d databases, got %d.", maximumTaskLimit, databaseIDCount))
}
diff --git a/backend/server/server.go b/backend/server/server.go
index ded7514787..b0e8118236 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -5,7 +5,6 @@ import (
"context"
"encoding/json"
"fmt"
- "math"
"net"
"net/http"
"runtime"
@@ -1070,8 +1069,8 @@ func (s *Server) generateOnboardingData(ctx context.Context, userID int) error {
},
},
EnvironmentID: api.DefaultProdEnvironmentID,
- Activation: true,
- }, userID, math.MaxInt)
+ Activation: false,
+ }, userID, -1)
if err != nil {
return errors.Wrapf(err, "failed to create onboarding instance")
}
diff --git a/backend/store/stats.go b/backend/store/stats.go
index 771bfeb688..08bb348687 100644
--- a/backend/store/stats.go
+++ b/backend/store/stats.go
@@ -49,6 +49,37 @@ func (s *Store) CountInstance(ctx context.Context, find *CountInstanceMessage) (
return count, nil
}
+// CountPrincipal counts the number of endusers.
+func (s *Store) CountPrincipal(ctx context.Context) (int, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+
+ query := `
+ SELECT
+ count(1)
+ FROM principal
+ WHERE principal.type = $1`
+ var count int
+ if err := tx.QueryRowContext(ctx, `
+ SELECT
+ count(1)
+ FROM principal
+ WHERE principal.type = $1
+ `, api.EndUser).Scan(&count); err != nil {
+ if err == sql.ErrNoRows {
+ return 0, common.FormatDBErrorEmptyRowWithQuery(query)
+ }
+ return 0, err
+ }
+ if err := tx.Commit(); err != nil {
+ return 0, err
+ }
+ return count, nil
+}
+
// CountDatabaseGroupByBackupScheduleAndEnabled counts database, group by backup schedule and enabled.
func (s *Store) CountDatabaseGroupByBackupScheduleAndEnabled(ctx context.Context) ([]*metric.DatabaseCountMetric, error) {
tx, err := s.db.BeginTx(ctx, nil)
diff --git a/backend/tests/data_source_test.go b/backend/tests/data_source_test.go
index c545aa8863..35e4e15f1b 100644
--- a/backend/tests/data_source_test.go
+++ b/backend/tests/data_source_test.go
@@ -47,6 +47,8 @@ func TestDataSource(t *testing.T) {
})
a.NoError(err)
+ err = ctl.removeLicense()
+ a.NoError(err)
_, err = ctl.instanceServiceClient.AddDataSource(ctx, &v1pb.AddDataSourceRequest{
Instance: instance.Name,
DataSource: &v1pb.DataSource{
diff --git a/backend/tests/subscription_test.go b/backend/tests/subscription_test.go
index 447dba4c3a..058cf12b77 100644
--- a/backend/tests/subscription_test.go
+++ b/backend/tests/subscription_test.go
@@ -33,6 +33,8 @@ func TestSubscription(t *testing.T) {
a.NoError(err)
defer ctl.Close(ctx)
+ err = ctl.removeLicense()
+ a.NoError(err)
subscription, err := ctl.getSubscription()
a.NoError(err)
a.Equal(v1pb.PlanType_FREE, subscription.Plan)
diff --git a/backend/tests/tests.go b/backend/tests/tests.go
index c981b81a99..ece84cd849 100644
--- a/backend/tests/tests.go
+++ b/backend/tests/tests.go
@@ -273,6 +273,9 @@ func (ctl *controller) StartServerWithExternalPg(ctx context.Context, config *co
if err := ctl.initWorkspaceProfile(metaCtx); err != nil {
return nil, err
}
+ if err := ctl.setLicense(); err != nil {
+ return nil, err
+ }
return metaCtx, nil
}
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
index 41002ecda2..81ea664676 100644
--- a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
@@ -3,6 +3,7 @@
<FeatureAttentionForInstanceLicense
v-if="existMatchedUnactivateInstance"
custom-class="mb-5"
+ :style="`WARN`"
feature="bb.feature.database-grouping"
/>
<div class="w-full grid grid-cols-3 gap-x-6 pb-6 mb-4 border-b">
@@ -285,15 +286,6 @@ const validateResourceId = async (
return [];
};
-defineExpose({
- getFormState: () => {
- return {
- ...state,
- resourceId: resourceIdField.value?.resourceId || "",
- };
- },
-});
-
const matchedDatabaseList = ref<ComposedDatabase[]>([]);
const unmatchedDatabaseList = ref<ComposedDatabase[]>([]);
const updateDatabaseMatchingState = useDebounceFn(async () => {
@@ -379,4 +371,14 @@ const existMatchedUnactivateInstance = computed(() => {
);
}
});
+
+defineExpose({
+ getFormState: () => {
+ return {
+ ...state,
+ resourceId: resourceIdField.value?.resourceId || "",
+ existMatchedUnactivateInstance: existMatchedUnactivateInstance.value,
+ };
+ },
+});
</script>
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue
index 76ce818018..4c0500e891 100644
--- a/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue
@@ -110,6 +110,9 @@ const allowConfirm = computed(() => {
}
const formState = formRef.value.getFormState();
+ if (formState.existMatchedUnactivateInstance) {
+ return false;
+ }
if (props.resourceType === "DATABASE_GROUP") {
return (
formState.resourceId && formState.placeholder && formState.environmentId
diff --git a/frontend/src/components/FeatureGuard/FeatureAttentionForInstanceLicense.vue b/frontend/src/components/FeatureGuard/FeatureAttentionForInstanceLicense.vue
index 7a2a210eeb..6169f98fb8 100644
--- a/frontend/src/components/FeatureGuard/FeatureAttentionForInstanceLicense.vue
+++ b/frontend/src/components/FeatureGuard/FeatureAttentionForInstanceLicense.vue
@@ -1,8 +1,11 @@
<template>
<BBAttention
- v-if="instanceLimitFeature.has(feature)"
+ v-if="
+ instanceLimitFeature.has(feature) &&
+ subscriptionV1Store.currentPlan !== PlanType.FREE
+ "
:class="customClass"
- :style="`INFO`"
+ :style="style ?? `INFO`"
:title="$t(`subscription.features.${featureKey}.desc`)"
:description="
$t('subscription.instance-assignment.missing-license-attention')
@@ -17,28 +20,27 @@
</template>
<script lang="ts" setup>
-import { reactive, PropType } from "vue";
+import { reactive } from "vue";
import { FeatureType, instanceLimitFeature } from "@/types";
+import { BBAttentionStyle } from "@/bbkit";
+import { PlanType } from "@/types/proto/v1/subscription_service";
+import { useSubscriptionV1Store } from "@/store";
interface LocalState {
showInstanceAssignmentDrawer: boolean;
}
-const props = defineProps({
- feature: {
- required: true,
- type: String as PropType<FeatureType>,
- },
- customClass: {
- require: false,
- default: "",
- type: String,
- },
-});
+const props = defineProps<{
+ style?: BBAttentionStyle;
+ feature: FeatureType;
+ customClass: string;
+}>();
const state = reactive<LocalState>({
showInstanceAssignmentDrawer: false,
});
+
+const subscriptionV1Store = useSubscriptionV1Store();
const featureKey = props.feature.split(".").join("-");
const onClick = () => {
diff --git a/frontend/src/components/Instance/InstanceArchiveRestoreButton.vue b/frontend/src/components/Instance/InstanceArchiveRestoreButton.vue
index 109826c97a..a6d98b78ce 100644
--- a/frontend/src/components/Instance/InstanceArchiveRestoreButton.vue
+++ b/frontend/src/components/Instance/InstanceArchiveRestoreButton.vue
@@ -41,10 +41,15 @@
/>
</template>
</template>
+ <FeatureModal
+ v-if="state.showFeatureModal"
+ feature="bb.feature.instance-count"
+ @cancel="state.showFeatureModal = false"
+ />
</template>
<script setup lang="ts">
-import { computed, ref } from "vue";
+import { computed, ref, reactive } from "vue";
import { NCheckbox } from "naive-ui";
import { useI18n } from "vue-i18n";
@@ -52,18 +57,28 @@ import {
useCurrentUserV1,
useInstanceV1Store,
pushNotification,
+ useSubscriptionV1Store,
} from "@/store";
import { ComposedInstance } from "@/types";
import { State } from "@/types/proto/v1/common";
import { hasWorkspacePermissionV1 } from "@/utils";
+interface LocalState {
+ showFeatureModal: boolean;
+}
+
const props = defineProps<{
instance: ComposedInstance;
}>();
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+});
+
const { t } = useI18n();
const currentUserV1 = useCurrentUserV1();
const instanceStore = useInstanceV1Store();
+const subscriptionStore = useSubscriptionV1Store();
const force = ref(false);
@@ -85,6 +100,11 @@ const archiveOrRestoreInstance = async (archive: boolean) => {
]),
});
} else {
+ const instanceList = instanceStore.activeInstanceList;
+ if (subscriptionStore.instanceCountLimit <= instanceList.length) {
+ state.showFeatureModal = true;
+ return;
+ }
await instanceStore.restoreInstance(props.instance);
pushNotification({
module: "bytebase",
diff --git a/frontend/src/components/InstanceAssignment.vue b/frontend/src/components/InstanceAssignment.vue
index 64a721acf8..1be48b61aa 100644
--- a/frontend/src/components/InstanceAssignment.vue
+++ b/frontend/src/components/InstanceAssignment.vue
@@ -52,7 +52,7 @@
:indeterminate="allSelectionState.indeterminate"
:disabled="
!allSelectionState.checked &&
- instanceList.length > instanceCount
+ instanceList.length > instanceLicenseCount
"
@input="
selectAllInstances(
@@ -78,7 +78,7 @@
type="checkbox"
class="ml-2 h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
:checked="isInstanceSelected(instance)"
- :disabled="state.selectedInstance.size == instanceCount"
+ :disabled="state.selectedInstance.size == instanceLicenseCount"
/>
</BBTableCell>
<BBTableCell class="bb-grid-cell">
@@ -117,7 +117,7 @@
:disabled="
!assignmentChanged ||
state.processing ||
- state.selectedInstance.size > instanceCount
+ state.selectedInstance.size > instanceLicenseCount
"
type="primary"
@click.prevent="updateAssignment"
@@ -189,7 +189,7 @@ const subscriptionStore = useSubscriptionV1Store();
const { t } = useI18n();
const { instanceList } = useInstanceV1List(false /* !showDeleted */);
-const { instanceCount } = storeToRefs(subscriptionStore);
+const { instanceLicenseCount } = storeToRefs(subscriptionStore);
watchEffect(() => {
for (const instance of instanceList.value) {
@@ -200,10 +200,10 @@ watchEffect(() => {
});
const totalLicenseCount = computed((): string => {
- if (instanceCount.value === Number.MAX_VALUE) {
+ if (instanceLicenseCount.value === Number.MAX_VALUE) {
return t("subscription.unlimited");
}
- return `${instanceCount.value}`;
+ return `${instanceLicenseCount.value}`;
});
const assignedLicenseCount = computed((): string => {
diff --git a/frontend/src/components/InstanceForm/InstanceForm.vue b/frontend/src/components/InstanceForm/InstanceForm.vue
index 86adfd4a58..266ae8fcb3 100644
--- a/frontend/src/components/InstanceForm/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm/InstanceForm.vue
@@ -60,7 +60,10 @@
/>
</div>
- <div class="sm:col-span-2 ml-0 sm:ml-3">
+ <div
+ class="sm:col-span-2 ml-0 sm:ml-3"
+ v-if="subscriptionStore.currentPlan !== PlanType.FREE"
+ >
<label for="activation" class="textlabel block">
{{ $t("subscription.instance-assignment.assign-license") }}
({{
@@ -679,6 +682,7 @@ import {
} from "@/types/proto/v1/instance_service";
import { Engine, State } from "@/types/proto/v1/common";
import { instanceServiceClient } from "@/grpcweb";
+import { PlanType } from "@/types/proto/v1/subscription_service";
const props = defineProps({
instance: {
@@ -750,7 +754,8 @@ const hasReadonlyReplicaFeature = featureToRef(
const availableLicenseCount = computed(() => {
return Math.max(
0,
- subscriptionStore.instanceCount - instanceV1Store.activateInstanceCount
+ subscriptionStore.instanceLicenseCount -
+ instanceV1Store.activateInstanceCount
);
});
@@ -763,7 +768,9 @@ const extractBasicInfo = (instance: Instance | undefined): BasicInfo => {
engine: instance?.engine ?? Engine.MYSQL,
externalLink: instance?.externalLink ?? "",
environment: instance?.environment ?? UNKNOWN_ENVIRONMENT_NAME,
- activation: instance?.activation ?? false,
+ activation: instance
+ ? instance.activation
+ : availableLicenseCount.value > 0,
};
};
diff --git a/frontend/src/components/QuickActionPanel.vue b/frontend/src/components/QuickActionPanel.vue
index 6222b01e3b..33ba8cbd7d 100644
--- a/frontend/src/components/QuickActionPanel.vue
+++ b/frontend/src/components/QuickActionPanel.vue
@@ -295,6 +295,12 @@
"
@dismiss="state.quickActionType = undefined"
/>
+
+ <FeatureModal
+ v-if="state.showFeatureModal && state.feature"
+ :feature="state.feature"
+ @cancel="state.showFeatureModal = false"
+ />
</template>
<script lang="ts" setup>
@@ -306,6 +312,7 @@ import { useRoute, useRouter } from "vue-router";
import { QuickActionType } from "@/types";
import { idFromSlug, isDev } from "@/utils";
import {
+ useInstanceV1Store,
useCommandStore,
useCurrentUserIamPolicy,
useProjectV1ListByCurrentUser,
@@ -322,6 +329,8 @@ import RequestExportPanel from "@/components/Issue/panel/RequestExportPanel/inde
import RequestQueryPanel from "@/components/Issue/panel/RequestQueryPanel/index.vue";
interface LocalState {
+ feature?: string;
+ showFeatureModal: boolean;
quickActionType: QuickActionType | undefined;
showRequestQueryPanel: boolean;
showRequestExportPanel: boolean;
@@ -345,6 +354,7 @@ const hasDBAWorkflowFeature = computed(() => {
});
const state = reactive<LocalState>({
+ showFeatureModal: false,
quickActionType: undefined,
showRequestQueryPanel: false,
showRequestExportPanel: false,
@@ -386,6 +396,12 @@ const transferOutDatabase = () => {
};
const createInstance = () => {
+ const instanceList = useInstanceV1Store().instanceList;
+ if (subscriptionStore.instanceCountLimit <= instanceList.length) {
+ state.feature = "bb.feature.instance-count";
+ state.showFeatureModal = true;
+ return;
+ }
state.quickActionType = "quickaction.bb.instance.create";
};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index c8da9de2af..a40c629d0b 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1891,7 +1891,7 @@
"require-license": "Require instance license",
"missing-license-attention": "You need to assign license to the instance to enable this feature.",
"n-license-remain": "remain {n}",
- "manage-license": "Manage License",
+ "manage-license": "Manage Instance License",
"used-and-total-license": "Assigned / Total Instance License",
"success-notification": "Successfully update license assignment",
"missing-license-for-instances": "You have {count} instances ({name}) missing required license to unlock this feature."
@@ -1924,6 +1924,13 @@
"runoutof": "Your have run out of your {total} instance quota.",
"upgrade": "@:{'subscription.upgrade'} to get more instance quota."
},
+ "bb-feature-user-count": {
+ "title": "User count limit",
+ "desc": "You have reached the maximum user count limit. Please upgrade to get unlimited user quota.",
+ "remaining": "Your total user quota is {total}, only have {count} user remained.",
+ "runoutof": "Your have run out of your {total} user quota.",
+ "upgrade": "@:{'subscription.upgrade'} to get unlimited user quota."
+ },
"bb-feature-multi-tenancy": {
"title": "Batch mode",
"desc": "Batch changing a group of databases from different tenants or partitions."
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index feb20f7604..8c2d44a843 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1910,6 +1910,13 @@
"runoutof": "Te has quedado sin tu cuota de instancias {total}.",
"upgrade": "@:{'subscription.upgrade'} para obtener más cuota de instancias."
},
+ "bb-feature-user-count": {
+ "title": "Límite de conteo de usuarios",
+ "desc": "Ha alcanzado el límite máximo de recuento de usuarios. Actualice para obtener una cuota de usuario ilimitada.",
+ "remaining": "Su cuota total de usuarios es {total}, solo quedan {count} usuarios.",
+ "runoutof": "Se ha quedado sin su cuota de usuario {total}.",
+ "upgrade": "@:{'subscription.upgrade'} para obtener una cuota de usuario ilimitada."
+ },
"bb-feature-multi-tenancy": {
"title": "Modo Lote",
"desc": "Cambio por lotes de un grupo de bases de datos de diferentes inquilinos o particiones."
diff --git a/frontend/src/locales/subscription/en-US.json b/frontend/src/locales/subscription/en-US.json
index d9a0991aca..4c5ff87562 100644
--- a/frontend/src/locales/subscription/en-US.json
+++ b/frontend/src/locales/subscription/en-US.json
@@ -2,6 +2,7 @@
"current": "Current plan",
"unlimited": "Unlimited",
"instance-count": "Instance count",
+ "user-count": "User count",
"expires-at": "Expires at",
"start-free-trial": "Start free trial",
"free-trial": "You can start a free trial for 14 days - no credit card required",
@@ -52,6 +53,7 @@
"title": "Change Management",
"features": {
"user-count": "User count",
+ "user-maximum-20": "Up to 20",
"user-unlimited": "Unlimited",
"instance-count": "Instance count",
"instance-customized": "Customized",
diff --git a/frontend/src/locales/subscription/es-ES.json b/frontend/src/locales/subscription/es-ES.json
index 6e74723e51..ecb05883bb 100644
--- a/frontend/src/locales/subscription/es-ES.json
+++ b/frontend/src/locales/subscription/es-ES.json
@@ -2,6 +2,7 @@
"current": "Plan actual",
"unlimited": "Ilimitado",
"instance-count": "Cantidad de instancias",
+ "user-count": "Conteo de usuarios",
"expires-at": "Expira el",
"start-free-trial": "Comience la prueba gratuita",
"free-trial": "Puede comenzar una prueba gratuita durante 14 días - no se requiere tarjeta de crédito",
@@ -52,6 +53,7 @@
"title": "Gestión del cambio",
"features": {
"user-count": "Cantidad de usuarios",
+ "user-maximum-20": "Hasta 20",
"user-unlimited": "Ilimitado",
"instance-count": "Cantidad de instancias",
"instance-customized": "Personalizado",
diff --git a/frontend/src/locales/subscription/zh-CN.json b/frontend/src/locales/subscription/zh-CN.json
index 318fd450d5..6892d0afee 100644
--- a/frontend/src/locales/subscription/zh-CN.json
+++ b/frontend/src/locales/subscription/zh-CN.json
@@ -2,6 +2,7 @@
"current": "当前版本",
"unlimited": "无限制",
"instance-count": "实例数",
+ "user-count": "用户数",
"expires-at": "过期时间",
"start-free-trial": "开始免费试用",
"free-trial": "您可以免费试用 14 天 - 无需信用卡或预付费",
@@ -52,6 +53,7 @@
"title": "变更管理",
"features": {
"user-count": "用户数",
+ "user-maximum-20": "不超过 20 个",
"user-unlimited": "无限制",
"instance-count": "实例数",
"instance-customized": "自定义",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 2b71c3c371..21f3b3d858 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1919,6 +1919,13 @@
"runoutof": "已用尽全部 {total} 个实例额度。",
"upgrade": "@:{'subscription.upgrade'}来获取更多实例额度。"
},
+ "bb-feature-user-count": {
+ "title": "用户数量限制",
+ "desc": "您已达最大用户数量限制,请付费升级来获取无限的用户额度。",
+ "remaining": "当前总用户额度为 {total},目前仅剩 {count} 个份额可用。",
+ "runoutof": "已用尽全部 {total} 个用户额度。",
+ "upgrade": "@:{'subscription.upgrade'}来获取无限的用户额度。"
+ },
"bb-feature-multi-tenancy": {
"title": "批量模式",
"desc": "批量变更一组属于不同租户或者数据库分库的数据库。"
diff --git a/frontend/src/store/modules/v1/subscription.ts b/frontend/src/store/modules/v1/subscription.ts
index 0dcec45891..efbdec31da 100644
--- a/frontend/src/store/modules/v1/subscription.ts
+++ b/frontend/src/store/modules/v1/subscription.ts
@@ -3,7 +3,13 @@ import dayjs from "dayjs";
import { computed, Ref } from "vue";
import { useI18n } from "vue-i18n";
import { subscriptionServiceClient } from "@/grpcweb";
-import { FeatureType, planTypeToString, instanceLimitFeature } from "@/types";
+import {
+ FeatureType,
+ planTypeToString,
+ instanceCountLimit,
+ userCountLimit,
+ instanceLimitFeature,
+} from "@/types";
import {
PlanType,
Subscription,
@@ -25,9 +31,15 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", {
featureMatrix: new Map<FeatureType, boolean[]>(),
}),
getters: {
- instanceCount(state): number {
+ instanceCountLimit(state): number {
+ return instanceCountLimit.get(this.currentPlan) ?? 0;
+ },
+ userCountLimit(state): number {
+ return userCountLimit.get(this.currentPlan) ?? 0;
+ },
+ instanceLicenseCount(state): number {
const count = state.subscription?.instanceCount ?? 0;
- if (count <= 0) {
+ if (count < 0) {
return Number.MAX_VALUE;
}
return count;
@@ -119,6 +131,10 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", {
type: FeatureType,
instance: Instance | undefined = undefined
) {
+ // DONOT check instance license fo FREE plan.
+ if (this.currentPlan === PlanType.FREE) {
+ return this.hasFeature(type);
+ }
if (!instanceLimitFeature.has(type) || !instance) {
return this.hasFeature(type);
}
@@ -198,7 +214,8 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", {
trial: {
plan: planType,
days: this.trialingDays,
- instanceCount: 20,
+ // Instance license count.
+ instanceCount: 10,
},
});
this.setSubscription(subscription);
diff --git a/frontend/src/types/plan.ts b/frontend/src/types/plan.ts
index 7cd8042466..ea80aec2a2 100644
--- a/frontend/src/types/plan.ts
+++ b/frontend/src/types/plan.ts
@@ -120,6 +120,19 @@ export const PLANS: Plan[] = planData.planList.map((raw: Plan) => ({
type: planTypeFromJSON(raw.type + 1),
}));
+// TODO: it's better to get the count limit from the backend.
+export const userCountLimit = new Map<PlanType, number>([
+ [PlanType.FREE, 20],
+ [PlanType.TEAM, Number.MAX_VALUE],
+ [PlanType.ENTERPRISE, Number.MAX_VALUE],
+]);
+
+export const instanceCountLimit = new Map<PlanType, number>([
+ [PlanType.FREE, 20],
+ [PlanType.TEAM, 20],
+ [PlanType.ENTERPRISE, Number.MAX_VALUE],
+]);
+
export const getFeatureLocalization = (feature: PlanFeature): PlanFeature => {
const { t } = useI18n();
for (const section of FEATURE_SECTIONS) {
diff --git a/frontend/src/types/plan.yaml b/frontend/src/types/plan.yaml
index 62cc7417a0..771e252783 100644
--- a/frontend/src/types/plan.yaml
+++ b/frontend/src/types/plan.yaml
@@ -68,7 +68,7 @@ planList:
featureList:
# Change Management
- type: user-count
- content: user-unlimited
+ content: user-maximum-20
- type: instance-count
content: instance-maximum-20
- type: environment-count
diff --git a/frontend/src/utils/v1/instance.ts b/frontend/src/utils/v1/instance.ts
index 7f657daee0..6f86725e37 100644
--- a/frontend/src/utils/v1/instance.ts
+++ b/frontend/src/utils/v1/instance.ts
@@ -6,6 +6,8 @@ import { DataSourceType, Instance } from "@/types/proto/v1/instance_service";
import { Engine, State } from "@/types/proto/v1/common";
import { Environment } from "@/types/proto/v1/environment_service";
import { ComposedInstance } from "@/types";
+import { useSubscriptionV1Store } from "@/store";
+import { PlanType } from "@/types/proto/v1/subscription_service";
export const instanceV1Slug = (instance: Instance): string => {
return [slug(instance.title), instance.uid].join("-");
@@ -13,11 +15,12 @@ export const instanceV1Slug = (instance: Instance): string => {
export function instanceV1Name(instance: Instance) {
const { t } = useI18n();
+ const store = useSubscriptionV1Store();
let name = instance.title;
// instance cannot be deleted and activated at the same time.
if (instance.state === State.DELETED) {
name += ` (${t("common.archived")})`;
- } else if (!instance.activation) {
+ } else if (!instance.activation && store.currentPlan !== PlanType.FREE) {
name += ` (${t("common.no-license")})`;
}
return name;
diff --git a/frontend/src/views/DatabaseGroupDetail.vue b/frontend/src/views/DatabaseGroupDetail.vue
index 6c92659941..cbc48e1413 100644
--- a/frontend/src/views/DatabaseGroupDetail.vue
+++ b/frontend/src/views/DatabaseGroupDetail.vue
@@ -70,6 +70,7 @@
<FeatureAttentionForInstanceLicense
v-if="existMatchedUnactivateInstance"
custom-class="m-5"
+ :style="`WARN`"
feature="bb.feature.database-grouping"
/>
diff --git a/frontend/src/views/InstanceDashboard.vue b/frontend/src/views/InstanceDashboard.vue
index b414f91042..01a2473feb 100644
--- a/frontend/src/views/InstanceDashboard.vue
+++ b/frontend/src/views/InstanceDashboard.vue
@@ -45,6 +45,7 @@ import {
useInstanceV1List,
useInstanceV1Store,
} from "@/store";
+import { PlanType } from "@/types/proto/v1/subscription_service";
interface LocalState {
searchText: string;
@@ -109,24 +110,57 @@ const filteredInstanceV1List = computed(() => {
});
const remainingInstanceCount = computed((): number => {
+ if (subscriptionStore.currentPlan === PlanType.FREE) {
+ return Math.max(
+ 0,
+ subscriptionStore.instanceCountLimit -
+ instanceV1Store.activeInstanceList.length
+ );
+ }
+
return Math.max(
0,
- subscriptionStore.instanceCount - instanceV1Store.activateInstanceCount
+ subscriptionStore.instanceLicenseCount -
+ instanceV1Store.activateInstanceCount
);
});
const instanceCountAttention = computed((): string => {
const upgrade = t("subscription.features.bb-feature-instance-count.upgrade");
let status = "";
- if (remainingInstanceCount.value > 0) {
- status = t("subscription.features.bb-feature-instance-count.remaining", {
- total: subscriptionStore.instanceCount,
- count: remainingInstanceCount.value,
- });
- } else {
- status = t("subscription.features.bb-feature-instance-count.runoutof", {
- total: subscriptionStore.instanceCount,
- });
+
+ switch (subscriptionStore.currentPlan) {
+ case PlanType.FREE:
+ if (remainingInstanceCount.value > 0) {
+ status = t(
+ "subscription.features.bb-feature-instance-count.remaining",
+ {
+ total: subscriptionStore.instanceCountLimit,
+ count: remainingInstanceCount.value,
+ }
+ );
+ } else {
+ status = t("subscription.features.bb-feature-instance-count.runoutof", {
+ total: subscriptionStore.instanceCountLimit,
+ });
+ }
+ break;
+ case PlanType.TEAM:
+ case PlanType.ENTERPRISE:
+ if (remainingInstanceCount.value > 0) {
+ status = t(
+ "subscription.features.bb-feature-instance-count.remaining",
+ {
+ total: subscriptionStore.instanceLicenseCount,
+ count: remainingInstanceCount.value,
+ }
+ );
+ } else {
+ status = t("subscription.features.bb-feature-instance-count.runoutof", {
+ total: subscriptionStore.instanceLicenseCount,
+ });
+ }
+ break;
}
return `${status} ${upgrade}`;
diff --git a/frontend/src/views/SchemaGroupDetail.vue b/frontend/src/views/SchemaGroupDetail.vue
index 226e1f4a82..bf6b880d51 100644
--- a/frontend/src/views/SchemaGroupDetail.vue
+++ b/frontend/src/views/SchemaGroupDetail.vue
@@ -64,6 +64,7 @@
<FeatureAttentionForInstanceLicense
v-if="existMatchedUnactivateInstance"
custom-class="m-5"
+ :style="`WARN`"
feature="bb.feature.database-grouping"
/>
diff --git a/frontend/src/views/SettingWorkspaceMember.vue b/frontend/src/views/SettingWorkspaceMember.vue
index a109b03ede..0fc5eb040c 100644
--- a/frontend/src/views/SettingWorkspaceMember.vue
+++ b/frontend/src/views/SettingWorkspaceMember.vue
@@ -1,4 +1,11 @@
<template>
+ <FeatureAttention
+ v-if="remainingUserCount <= 3"
+ custom-class="m-5"
+ feature="bb.feature.user-count"
+ :description="userCountAttention"
+ />
+
<div class="w-full pb-4">
<div v-if="allowAddOrInvite" class="w-full flex justify-center mb-6">
<MemberAddOrInvite />
@@ -67,13 +74,19 @@
<script lang="ts" setup>
import { computed, reactive } from "vue";
import { NCheckbox } from "naive-ui";
+import { useI18n } from "vue-i18n";
import { MemberAddOrInvite, UserTable } from "@/components/User/Settings";
import { SearchBox } from "@/components/v2";
import { hasWorkspacePermissionV1 } from "../utils";
import { SYSTEM_BOT_USER_NAME, filterUserListByKeyword } from "../types";
-import { featureToRef, useCurrentUserV1, useUserStore } from "@/store";
+import {
+ useSubscriptionV1Store,
+ useCurrentUserV1,
+ useUserStore,
+} from "@/store";
import { State } from "@/types/proto/v1/common";
+import { UserType } from "@/types/proto/v1/auth_service";
type LocalState = {
activeUserFilterText: string;
@@ -87,9 +100,13 @@ const state = reactive<LocalState>({
showInactiveUserList: false,
});
+const { t } = useI18n();
const userStore = useUserStore();
const currentUserV1 = useCurrentUserV1();
-const hasRBACFeature = featureToRef("bb.feature.rbac");
+const subscriptionV1Store = useSubscriptionV1Store();
+const hasRBACFeature = computed(() =>
+ subscriptionV1Store.hasFeature("bb.feature.rbac")
+);
const activeUserList = computed(() => {
const list = userStore.userList.filter((user) => user.state === State.ACTIVE);
@@ -133,4 +150,35 @@ const showUpgradeInfo = computed(() => {
)
);
});
+
+const endUserList = computed(() => {
+ return userStore.activeUserList.filter(
+ (user) => user.userType === UserType.USER
+ );
+});
+
+const remainingUserCount = computed((): number => {
+ return Math.max(
+ 0,
+ subscriptionV1Store.userCountLimit - endUserList.value.length
+ );
+});
+
+const userCountAttention = computed((): string => {
+ const upgrade = t("subscription.features.bb-feature-user-count.upgrade");
+ let status = "";
+
+ if (remainingUserCount.value > 0) {
+ status = t("subscription.features.bb-feature-user-count.remaining", {
+ total: subscriptionV1Store.userCountLimit,
+ count: remainingUserCount.value,
+ });
+ } else {
+ status = t("subscription.features.bb-feature-user-count.runoutof", {
+ total: subscriptionV1Store.userCountLimit,
+ });
+ }
+
+ return `${status} ${upgrade}`;
+});
</script>
diff --git a/frontend/src/views/SettingWorkspaceSubscription.vue b/frontend/src/views/SettingWorkspaceSubscription.vue
index 25744ef5ed..728d39ae54 100644
--- a/frontend/src/views/SettingWorkspaceSubscription.vue
+++ b/frontend/src/views/SettingWorkspaceSubscription.vue
@@ -39,7 +39,19 @@
</div>
</dd>
</div>
- <div class="my-3">
+ <div v-if="subscriptionStore.currentPlan === PlanType.FREE" class="my-3">
+ <dt class="text-gray-400">
+ {{ $t("subscription.instance-count") }}
+ </dt>
+ <dd
+ class="mt-1 text-4xl flex items-center gap-x-2 cursor-pointer group"
+ >
+ <span class="group-hover:underline">{{
+ subscriptionStore.instanceCountLimit
+ }}</span>
+ </dd>
+ </div>
+ <div v-else class="my-3">
<dt class="text-gray-400">
{{ $t("subscription.instance-assignment.used-and-total-license") }}
</dt>
@@ -207,14 +219,14 @@ const uploadLicense = async () => {
}
};
-const { expireAt, isTrialing, isExpired, instanceCount } =
+const { expireAt, isTrialing, isExpired, instanceLicenseCount } =
storeToRefs(subscriptionStore);
const totalLicenseCount = computed((): string => {
- if (instanceCount.value === Number.MAX_VALUE) {
+ if (instanceLicenseCount.value === Number.MAX_VALUE) {
return t("subscription.unlimited");
}
- return `${instanceCount.value}`;
+ return `${instanceLicenseCount.value}`;
});
const activateLicenseCount = computed((): string => {