Skip to content

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

chore: update metric and last active time (#5164)

ecmadao1877ba15d2b4
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index bf2698453a..9c140d9359 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -162,20 +162,18 @@ func (s *AuthService) CreateUser(ctx context.Context, request *v1pb.CreateUserRe
return nil, err
}
- if s.metricReporter != nil {
- isFirstUser := user.ID == api.PrincipalIDForFirstUser
- s.metricReporter.Report(&metric.Metric{
- Name: metricAPI.PrincipalRegistrationMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "email": user.Email,
- "name": user.Name,
- // We only send lark notification for the first principal registration.
- // false means do not notify upfront. Later the notification will be triggered by the scheduler.
- "lark_notified": !isFirstUser,
- },
- })
- }
+ isFirstUser := user.ID == api.PrincipalIDForFirstUser
+ s.metricReporter.Report(&metric.Metric{
+ Name: metricAPI.PrincipalRegistrationMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "email": user.Email,
+ "name": user.Name,
+ // We only send lark notification for the first principal registration.
+ // false means do not notify upfront. Later the notification will be triggered by the scheduler.
+ "lark_notified": !isFirstUser,
+ },
+ })
bytes, err := json.Marshal(api.ActivityMemberCreatePayload{
PrincipalID: user.ID,
PrincipalName: user.Name,
diff --git a/backend/metric/metric.go b/backend/metric/metric.go
index 2cf9bda7fb..0633b9b51f 100644
--- a/backend/metric/metric.go
+++ b/backend/metric/metric.go
@@ -40,6 +40,8 @@ const (
SQLEditorExecutionMetricName metric.Name = "bb.sql-editor.execute"
// PrincipalCreateMetricName is the metric name for principal creation event.
PrincipalCreateMetricName metric.Name = "bb.principal.create"
+ // APIRequestMetricName is the metric name for api request.
+ APIRequestMetricName metric.Name = "bb.api.request"
)
// InstanceCountMetric is the API message for bb.instance.count.
diff --git a/backend/plugin/metric/segment/mock.go b/backend/plugin/metric/segment/mock.go
new file mode 100644
index 0000000000..2075ef18d4
--- /dev/null
+++ b/backend/plugin/metric/segment/mock.go
@@ -0,0 +1,26 @@
+package segment
+
+import "github.com/bytebase/bytebase/backend/plugin/metric"
+
+// mockreporter is the metrics collector https://segment.com/.
+type mockreporter struct {
+}
+
+// NewMockReporter creates a new instance of segment mock reporter.
+func NewMockReporter() metric.Reporter {
+ return &mockreporter{}
+}
+
+// Close will close the segment client.
+func (*mockreporter) Close() {
+}
+
+// Report will exec all the segment reporter.
+func (*mockreporter) Report(_ *metric.Metric) error {
+ return nil
+}
+
+// Identify will identify the workspace with license.
+func (*mockreporter) Identify(_ *metric.Identifier) error {
+ return nil
+}
diff --git a/backend/runner/metricreport/reporter.go b/backend/runner/metricreport/reporter.go
index 55324b353a..3a63f03e9a 100644
--- a/backend/runner/metricreport/reporter.go
+++ b/backend/runner/metricreport/reporter.go
@@ -44,8 +44,13 @@ type Reporter struct {
}
// NewReporter creates a new metric scheduler.
-func NewReporter(store *store.Store, licenseService enterpriseAPI.LicenseService, profile config.Profile, workspaceID string) *Reporter {
- r := segment.NewReporter(profile.MetricConnectionKey, workspaceID)
+func NewReporter(store *store.Store, licenseService enterpriseAPI.LicenseService, profile config.Profile, workspaceID string, enabled bool) *Reporter {
+ var r metric.Reporter
+ if enabled {
+ r = segment.NewReporter(profile.MetricConnectionKey, workspaceID)
+ } else {
+ r = segment.NewMockReporter()
+ }
return &Reporter{
licenseService: licenseService,
@@ -81,7 +86,7 @@ func (m *Reporter) Run(ctx context.Context, wg *sync.WaitGroup) {
ctx := context.Background()
// identify will be triggered in every schedule loop so that we can update the latest workspace profile such as subscription plan.
- m.Identify(ctx)
+ m.identify(ctx)
for name, collector := range m.collectors {
log.Debug("Run metric collector", zap.String("collector", name))
@@ -117,7 +122,7 @@ func (m *Reporter) Register(metricName metric.Name, collector metric.Collector)
}
// Identify will identify the workspace and update the subscription plan.
-func (m *Reporter) Identify(ctx context.Context) {
+func (m *Reporter) identify(ctx context.Context) {
subscription := m.licenseService.LoadSubscription(ctx)
plan := subscription.Plan.String()
orgID := subscription.OrgID
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.go
index 34d361fbdf..e667da372d 100644
--- a/backend/runner/taskrun/scheduler.go
+++ b/backend/runner/taskrun/scheduler.go
@@ -342,16 +342,14 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
}
}
- if s.metricReporter != nil {
- s.metricReporter.Report(&metric.Metric{
- Name: metricAPI.TaskStatusMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "type": task.Type,
- "value": taskStatusPatch.Status,
- },
- })
- }
+ s.metricReporter.Report(&metric.Metric{
+ Name: metricAPI.TaskStatusMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "type": task.Type,
+ "value": taskStatusPatch.Status,
+ },
+ })
}
return
}
diff --git a/backend/server/issue.go b/backend/server/issue.go
index 72b0580b60..a26be7a3d1 100644
--- a/backend/server/issue.go
+++ b/backend/server/issue.go
@@ -42,15 +42,13 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create issue").SetInternal(err)
}
- if s.MetricReporter != nil {
- s.MetricReporter.Report(&metric.Metric{
- Name: metricAPI.IssueCreateMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "type": issue.Type,
- },
- })
- }
+ s.MetricReporter.Report(&metric.Metric{
+ Name: metricAPI.IssueCreateMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "type": issue.Type,
+ },
+ })
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, issue); err != nil {
diff --git a/backend/server/openapi_metric.go b/backend/server/openapi_metric.go
index 0a5235c4ee..7f8dce7ffa 100644
--- a/backend/server/openapi_metric.go
+++ b/backend/server/openapi_metric.go
@@ -20,18 +20,16 @@ func openAPIMetricMiddleware(s *Server, next echo.HandlerFunc) echo.HandlerFunc
requestPath := c.Path()
responseCode := c.Response().Status
- if s.MetricReporter != nil {
- s.MetricReporter.Report(&metric.Metric{
- Name: metricAPI.OpenAPIMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "latency_ns": strconv.FormatInt(duration.Nanoseconds(), 10),
- "request_method": requestMethod,
- "request_path": requestPath,
- "response_code": strconv.Itoa(responseCode),
- },
- })
- }
+ s.MetricReporter.Report(&metric.Metric{
+ Name: metricAPI.OpenAPIMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "latency_ns": strconv.FormatInt(duration.Nanoseconds(), 10),
+ "request_method": requestMethod,
+ "request_path": requestPath,
+ "response_code": strconv.Itoa(responseCode),
+ },
+ })
}()
if err := next(c); err != nil {
diff --git a/backend/server/openapi_sql.go b/backend/server/openapi_sql.go
index 6eb0bb5a4c..d776616803 100644
--- a/backend/server/openapi_sql.go
+++ b/backend/server/openapi_sql.go
@@ -175,16 +175,14 @@ func (s *Server) sqlCheckController(c echo.Context) error {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to run sql check").SetInternal(err)
}
- if s.MetricReporter != nil {
- s.MetricReporter.Report(&metric.Metric{
- Name: metricAPI.SQLAdviseAPIMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "database_type": databaseType,
- "environment": request.EnvironmentName,
- },
- })
- }
+ s.MetricReporter.Report(&metric.Metric{
+ Name: metricAPI.SQLAdviseAPIMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "database_type": databaseType,
+ "environment": request.EnvironmentName,
+ },
+ })
return c.JSON(http.StatusOK, adviceList)
}
diff --git a/backend/server/principal.go b/backend/server/principal.go
index 9805a74b29..b209329706 100644
--- a/backend/server/principal.go
+++ b/backend/server/principal.go
@@ -83,22 +83,20 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
principal.ServiceKey = password
}
- if s.MetricReporter != nil {
- count, err := s.store.CountUsers(ctx, api.EndUser)
- if err != nil {
- // it's okay to ignore the error to avoid workflow broken.
- log.Debug("failed to count end users", zap.Error(err))
- }
- s.MetricReporter.Report(&metric.Metric{
- Name: metricAPI.PrincipalCreateMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "type": principal.Type,
- "role": principal.Role,
- "rank": count,
- },
- })
+ count, err := s.store.CountUsers(ctx, api.EndUser)
+ if err != nil {
+ // it's okay to ignore the error to avoid workflow broken.
+ log.Debug("failed to count end users", zap.Error(err))
}
+ s.MetricReporter.Report(&metric.Metric{
+ Name: metricAPI.PrincipalCreateMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "type": principal.Type,
+ "role": principal.Role,
+ "rank": count,
+ },
+ })
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {
diff --git a/backend/server/server.go b/backend/server/server.go
index 4f5733435a..23b27fb8d4 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -57,6 +57,7 @@ import (
advisorDb "github.com/bytebase/bytebase/backend/plugin/advisor/db"
"github.com/bytebase/bytebase/backend/plugin/app/feishu"
"github.com/bytebase/bytebase/backend/plugin/db"
+ metricPlugin "github.com/bytebase/bytebase/backend/plugin/metric"
bbs3 "github.com/bytebase/bytebase/backend/plugin/storage/s3"
"github.com/bytebase/bytebase/backend/resources/mongoutil"
"github.com/bytebase/bytebase/backend/resources/mysqlutil"
@@ -329,9 +330,20 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
defer func() {
- if !common.HasPrefixes(c.Request().URL.Path, "/healthz", "/v1/actuator") {
- s.profile.LastActiveTs = time.Now().Unix()
+ // only update for authorized request
+ id, ok := c.Get(getPrincipalIDContextKey()).(int)
+ if !ok || id <= 0 {
+ return
}
+ s.profile.LastActiveTs = time.Now().Unix()
+ s.MetricReporter.Report(&metricPlugin.Metric{
+ Name: metric.APIRequestMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "path": c.Request().URL.Path,
+ "method": c.Request().Method,
+ },
+ })
}()
return next(c)
}
@@ -352,6 +364,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {
s.s3Client = s3Client
}
+ s.MetricReporter = metricreport.NewReporter(s.store, s.licenseService, s.profile, s.GetWorkspaceID(), false)
if !profile.Readonly {
s.SchemaSyncer = schemasync.NewSyncer(storeInstance, s.dbFactory, s.stateCfg, profile)
// TODO(p0ny): enable Feishu provider only when it is needed.
@@ -595,18 +608,16 @@ func (s *Server) registerOpenAPIRoutes(e *echo.Echo, ce *casbin.Enforcer, prof c
// initMetricReporter will initial the metric scheduler.
func (s *Server) initMetricReporter(workspaceID string) {
enabled := s.profile.Mode == common.ReleaseModeProd && s.profile.DemoName != "" && !s.profile.DisableMetric
- if enabled {
- metricReporter := metricreport.NewReporter(s.store, s.licenseService, s.profile, workspaceID)
- metricReporter.Register(metric.InstanceCountMetricName, metricCollector.NewInstanceCountCollector(s.store))
- metricReporter.Register(metric.IssueCountMetricName, metricCollector.NewIssueCountCollector(s.store))
- metricReporter.Register(metric.ProjectCountMetricName, metricCollector.NewProjectCountCollector(s.store))
- metricReporter.Register(metric.PolicyCountMetricName, metricCollector.NewPolicyCountCollector(s.store))
- metricReporter.Register(metric.TaskCountMetricName, metricCollector.NewTaskCountCollector(s.store))
- metricReporter.Register(metric.DatabaseCountMetricName, metricCollector.NewDatabaseCountCollector(s.store))
- metricReporter.Register(metric.SheetCountMetricName, metricCollector.NewSheetCountCollector(s.store))
- metricReporter.Register(metric.MemberCountMetricName, metricCollector.NewMemberCountCollector(s.store))
- s.MetricReporter = metricReporter
- }
+ metricReporter := metricreport.NewReporter(s.store, s.licenseService, s.profile, workspaceID, enabled)
+ metricReporter.Register(metric.InstanceCountMetricName, metricCollector.NewInstanceCountCollector(s.store))
+ metricReporter.Register(metric.IssueCountMetricName, metricCollector.NewIssueCountCollector(s.store))
+ metricReporter.Register(metric.ProjectCountMetricName, metricCollector.NewProjectCountCollector(s.store))
+ metricReporter.Register(metric.PolicyCountMetricName, metricCollector.NewPolicyCountCollector(s.store))
+ metricReporter.Register(metric.TaskCountMetricName, metricCollector.NewTaskCountCollector(s.store))
+ metricReporter.Register(metric.DatabaseCountMetricName, metricCollector.NewDatabaseCountCollector(s.store))
+ metricReporter.Register(metric.SheetCountMetricName, metricCollector.NewSheetCountCollector(s.store))
+ metricReporter.Register(metric.MemberCountMetricName, metricCollector.NewMemberCountCollector(s.store))
+ s.MetricReporter = metricReporter
}
// retrieved via the SettingService upon startup.
@@ -758,10 +769,8 @@ func (s *Server) Run(ctx context.Context, port int) error {
s.runnerWG.Add(1)
go s.RollbackRunner.Run(ctx, &s.runnerWG)
- if s.MetricReporter != nil {
- s.runnerWG.Add(1)
- go s.MetricReporter.Run(ctx, &s.runnerWG)
- }
+ s.runnerWG.Add(1)
+ go s.MetricReporter.Run(ctx, &s.runnerWG)
}
listen, err := net.Listen("tcp", fmt.Sprintf(":%d", port+1))
diff --git a/backend/server/sql.go b/backend/server/sql.go
index 2979be7ec8..f5acb07578 100644
--- a/backend/server/sql.go
+++ b/backend/server/sql.go
@@ -557,17 +557,15 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
}
}
- if s.MetricReporter != nil {
- s.MetricReporter.Report(&metric.Metric{
- Name: metricAPI.SQLEditorExecutionMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "engine": instance.Engine,
- "readonly": exec.Readonly,
- "admin_mode": false,
- },
- })
- }
+ s.MetricReporter.Report(&metric.Metric{
+ Name: metricAPI.SQLEditorExecutionMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "engine": instance.Engine,
+ "readonly": exec.Readonly,
+ "admin_mode": false,
+ },
+ })
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, resultSet); err != nil {
@@ -761,17 +759,15 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
}
}
- if s.MetricReporter != nil {
- s.MetricReporter.Report(&metric.Metric{
- Name: metricAPI.SQLEditorExecutionMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "engine": instance.Engine,
- "readonly": exec.Readonly,
- "admin_mode": true,
- },
- })
- }
+ s.MetricReporter.Report(&metric.Metric{
+ Name: metricAPI.SQLEditorExecutionMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "engine": instance.Engine,
+ "readonly": exec.Readonly,
+ "admin_mode": true,
+ },
+ })
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, resultSet); err != nil {
diff --git a/backend/server/subscription.go b/backend/server/subscription.go
index 154d143656..7e5e59baca 100644
--- a/backend/server/subscription.go
+++ b/backend/server/subscription.go
@@ -145,17 +145,15 @@ func (s *Server) registerSubscriptionRoutes(g *echo.Group) {
s.licenseService.RefreshCache(ctx)
subscription = s.licenseService.LoadSubscription(ctx)
currentPlan := subscription.Plan
- if s.MetricReporter != nil {
- s.MetricReporter.Report(&metric.Metric{
- Name: metricAPI.SubscriptionTrialMetricName,
- Value: 1,
- Labels: map[string]interface{}{
- "trial_plan": currentPlan.String(),
- "from_plan": basePlan.String(),
- "lark_notified": false,
- },
- })
- }
+ s.MetricReporter.Report(&metric.Metric{
+ Name: metricAPI.SubscriptionTrialMetricName,
+ Value: 1,
+ Labels: map[string]interface{}{
+ "trial_plan": currentPlan.String(),
+ "from_plan": basePlan.String(),
+ "lark_notified": false,
+ },
+ })
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, &subscription); err != nil {