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: support free trial from console (backend) (#3195)
ecmadaod18db594afef
diff --git a/api/setting.go b/api/setting.goindex 184687b2f5..b50dd94c1e 100644--- a/api/setting.go+++ b/api/setting.go@@ -16,6 +16,8 @@ const (SettingWorkspaceID SettingName = "bb.workspace.id"// SettingEnterpriseLicense is the setting name for enterprise license.SettingEnterpriseLicense SettingName = "bb.enterprise.license"+ // SettingEnterpriseTrial is the setting name for free trial.+ SettingEnterpriseTrial SettingName = "bb.enterprise.trial")// Setting is the API message for a setting.diff --git a/enterprise/api/license.go b/enterprise/api/license.goindex 0dbeef9e33..b387b3dd0f 100644--- a/enterprise/api/license.go+++ b/enterprise/api/license.go@@ -18,13 +18,13 @@ var validPlans = []api.PlanType{// License is the API message for enterprise license.type License struct {- Subject string- InstanceCount int- ExpiresTs int64- IssuedTs int64- Plan api.PlanType- Trialing bool- OrgName string+ Subject string `json:"subject"`+ InstanceCount int `json:"instanceCount"`+ ExpiresTs int64 `json:"expiresTs"`+ IssuedTs int64 `json:"issuedTs"`+ Plan api.PlanType `json:"plan"`+ Trialing bool `json:"trialing"`+ OrgName string `json:"orgName"`}// Valid will check if license expired or has correct plan type.diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex 460fecde55..9ca62435da 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -97,6 +97,7 @@ p, DBA, /label, GETp, DBA, /label/{id}, PATCHp, DBA, /subscription, GETp, DBA, /subscription, PATCH+p, DBA, /subscription/trial, POSTp, DBA, /sheet, POSTp, DBA, /sheet/my, GETp, DBA, /sheet/shared, GETdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex c8cd0244a5..dd7811ae8a 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -102,6 +102,7 @@ p, OWNER, /label, GETp, OWNER, /label/{id}, PATCHp, OWNER, /subscription, GETp, OWNER, /subscription, PATCH+p, OWNER, /subscription/trial, POSTp, OWNER, /sheet, POSTp, OWNER, /sheet/my, GETp, OWNER, /sheet/shared, GETdiff --git a/server/instance.go b/server/instance.goindex 581dac856b..5f5f6e9304 100644--- a/server/instance.go+++ b/server/instance.go@@ -516,7 +516,7 @@ func (s *Server) instanceCountGuard(ctx context.Context) error {if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to count instance").SetInternal(err)}- subscription := s.loadSubscription()+ subscription := s.loadSubscription(ctx)if count >= subscription.InstanceCount {return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("You have reached the maximum instance count %d.", subscription.InstanceCount))}diff --git a/server/server.go b/server/server.goindex d7cc30cebb..ffcb6c625a 100644--- a/server/server.go+++ b/server/server.go@@ -381,15 +381,15 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {return nil, errors.Wrap(err, "failed to create license service")}- s.initSubscription()+ s.initSubscription(ctx)serverStarted = truereturn s, nil}// initSubscription will initial the subscription cache in memory.-func (s *Server) initSubscription() {- s.subscription = s.loadSubscription()+func (s *Server) initSubscription(ctx context.Context) {+ s.subscription = s.loadSubscription(ctx)}// initMetricReporter will initial the metric scheduler.diff --git a/server/subscription.go b/server/subscription.goindex aaa603569a..3091a1503b 100644--- a/server/subscription.go+++ b/server/subscription.go@@ -1,11 +1,15 @@package serverimport (+ "context"+ "encoding/json"+ "fmt""net/http""time""github.com/google/jsonapi""github.com/labstack/echo/v4"+ "github.com/pkg/errors""go.uber.org/zap""github.com/bytebase/bytebase/api"@@ -14,6 +18,15 @@ import (enterpriseAPI "github.com/bytebase/bytebase/enterprise/api")+const (+ // freeTrialPlan is the subscription plan for free trial.+ freeTrialPlan = api.ENTERPRISE+ // freeTrialInstanceCount is the instance count for free trial.+ freeTrialInstanceCount = 999+ // freeTrialDays is the trialing days for free trial.+ freeTrialDays = 7+)+func (s *Server) registerSubscriptionRoutes(g *echo.Group) {g.GET("/subscription", func(c echo.Context) error {c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)@@ -37,7 +50,46 @@ func (s *Server) registerSubscriptionRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to store license").SetInternal(err)}- s.subscription = s.loadSubscription()+ ctx := c.Request().Context()+ s.subscription = s.loadSubscription(ctx)++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, &s.subscription); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal subscription response").SetInternal(err)+ }+ return nil+ })++ g.POST("/subscription/trial", func(c echo.Context) error {+ license := &enterpriseAPI.License{+ InstanceCount: freeTrialInstanceCount,+ // trial 7 days+ ExpiresTs: time.Now().Unix() + freeTrialDays*24*60*60,+ IssuedTs: time.Now().Unix(),+ Plan: freeTrialPlan,+ // the subject format for license should be {org id in hub}.{subscription id in hub}+ // as we just need to simply generate the trialing license in console, we can use the workspace id instead.+ Subject: fmt.Sprintf("%s.%s", s.workspaceID, ""),+ Trialing: true,+ OrgName: s.workspaceID,+ }++ value, err := json.Marshal(license)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal license").SetInternal(err)+ }++ ctx := c.Request().Context()+ if _, err := s.store.CreateSettingIfNotExist(ctx, &api.SettingCreate{+ CreatorID: api.SystemBotID,+ Name: api.SettingEnterpriseTrial,+ Value: string(value),+ Description: "The trialing license.",+ }); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create license").SetInternal(err)+ }++ s.subscription = s.loadSubscription(ctx)c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, &s.subscription); err != nil {@@ -49,14 +101,15 @@ func (s *Server) registerSubscriptionRoutes(g *echo.Group) {// loadLicense will load current subscription by license.// Return subscription with free plan if no license found.-func (s *Server) loadSubscription() enterpriseAPI.Subscription {+func (s *Server) loadSubscription(ctx context.Context) enterpriseAPI.Subscription {subscription := enterpriseAPI.Subscription{Plan: api.FREE,// -1 means not expire, just for free planExpiresTs: -1,InstanceCount: 5,}- license, _ := s.loadLicense()++ license, _ := s.loadLicense(ctx)if license != nil {subscription = enterpriseAPI.Subscription{Plan: license.Plan,@@ -73,25 +126,44 @@ func (s *Server) loadSubscription() enterpriseAPI.Subscription {}// loadLicense will get and parse valid license from file.-func (s *Server) loadLicense() (*enterpriseAPI.License, error) {+func (s *Server) loadLicense(ctx context.Context) (*enterpriseAPI.License, error) {license, err := s.LicenseService.LoadLicense()+ if license != nil {+ log.Info(+ "Load valid license",+ zap.String("plan", license.Plan.String()),+ zap.Time("expiresAt", time.Unix(license.ExpiresTs, 0)),+ zap.Int("instanceCount", license.InstanceCount),+ )++ return license, nil+ }++ if common.ErrorCode(err) == common.NotFound {+ log.Debug("Failed to find license", zap.String("error", err.Error()))+ } else {+ log.Warn("Failed to load valid license", zap.String("error", err.Error()))+ }++ // find free trial license in console+ settingName := api.SettingEnterpriseTrial+ settings, err := s.store.FindSetting(ctx, &api.SettingFind{+ Name: &settingName,+ })if err != nil {- if common.ErrorCode(err) == common.NotFound {- log.Debug("Failed to find license", zap.String("error", err.Error()))- } else {- log.Warn("Failed to load valid license", zap.String("error", err.Error()))- }+ log.Warn("Failed to load trial license from settings", zap.String("error", err.Error()))return nil, err}+ if len(settings) == 0 {+ return nil, common.Wrapf(err, common.NotFound, "cannot find license")+ }- log.Info(- "Load valid license",- zap.String("plan", license.Plan.String()),- zap.Time("expiresAt", time.Unix(license.ExpiresTs, 0)),- zap.Int("instanceCount", license.InstanceCount),- )+ var data enterpriseAPI.License+ if err := json.Unmarshal([]byte(settings[0].Value), &data); err != nil {+ return nil, errors.Wrapf(err, "failed to unmarshal value %q", settings[0].Value)+ }- return license, nil+ return &data, nil}func (s *Server) feature(feature api.FeatureType) bool {