Skip to content

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

feat: expose license seat metrics

p0nyc590cf54e84d
diff --git a/CONTEXT.md b/CONTEXT.md
index f80518206a..415468733d 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -8,6 +8,10 @@ Bytebase is a governed database development workspace. It turns proposed databas
The top-level collaboration boundary that contains projects, database connections, environments, users, and policies.
_Avoid_: Project, organization
+**Seat-Occupying User**:
+An end user who consumes one workspace license seat through workspace membership. Pending invited users count; soft-deleted users and non-user identities do not.
+_Avoid_: Active user, principal count, logged-in user
+
**Project**:
A governance boundary for an application or team's databases. It can own project instances and owns database membership, issue workflow, approvals, labels, and rollout limits.
_Avoid_: Workspace, repository, environment
diff --git a/backend/enterprise/license.go b/backend/enterprise/license.go
index a8a3edd018..f3f643faa4 100644
--- a/backend/enterprise/license.go
+++ b/backend/enterprise/license.go
@@ -319,7 +319,39 @@ func (s *LicenseService) IsFeatureEnabledForInstance(ctx context.Context, worksp
// GetUserLimit gets the user limit value for the plan.
func (s *LicenseService) GetUserLimit(ctx context.Context, workspaceID string) int {
- subscription := s.LoadSubscription(ctx, workspaceID)
+ return userLimitFromSubscription(s.LoadSubscription(ctx, workspaceID))
+}
+
+// GetUserLimitUncached returns the effective user limit read directly from the
+// database, bypassing the per-replica subscription and setting caches. Metrics
+// collection uses this so replicas derive equivalent values from shared
+// metadata. A metadata read failure is returned as an error instead of silently
+// falling back to the Free plan.
+func (s *LicenseService) GetUserLimitUncached(ctx context.Context, workspaceID string) (int, error) {
+ setting, err := s.store.GetSystemSettingUncached(ctx, workspaceID)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to get system setting")
+ }
+ if setting == nil {
+ return userLimitFromSubscription(defaultFreeSubscription), nil
+ }
+ if setting.License == "" {
+ return userLimitFromSubscription(defaultFreeSubscription), nil
+ }
+ subscription := defaultFreeSubscription
+ parsedSubscription, parseErr := s.parseLicense(setting.License, workspaceID)
+ if parseErr == nil {
+ subscription = parsedSubscription
+ }
+ // An expired or malformed license has the effective Free plan, mirroring
+ // LoadSubscription.
+ if isExpired(subscription) {
+ subscription = &v1pb.Subscription{Plan: v1pb.PlanType_FREE}
+ }
+ return userLimitFromSubscription(subscription), nil
+}
+
+func userLimitFromSubscription(subscription *v1pb.Subscription) int {
// Prefer to take values from the license first.
if subscription.Seats > 0 {
return int(subscription.Seats)
@@ -332,11 +364,7 @@ func (s *LicenseService) GetUserLimit(ctx context.Context, workspaceID string) i
// To be compatible with old licenses which don't have seat field set in the claim.
// Unlimited seat license.
- if subscription.Seats <= 0 {
- return math.MaxInt
- }
-
- return int(subscription.Seats)
+ return math.MaxInt
}
// GetInstanceLimit gets the instance limit value for the plan.
diff --git a/backend/enterprise/license_test.go b/backend/enterprise/license_test.go
index 1fc56f8b96..2c95abdf41 100644
--- a/backend/enterprise/license_test.go
+++ b/backend/enterprise/license_test.go
@@ -2,14 +2,24 @@ package enterprise
import (
"context"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/pem"
+ "fmt"
"math"
"testing"
"time"
+ "github.com/golang-jwt/jwt/v5"
"github.com/hashicorp/golang-lru/v2/expirable"
+ "github.com/stretchr/testify/require"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/migrator"
"github.com/bytebase/bytebase/backend/store"
)
@@ -126,3 +136,83 @@ func TestCreateLicenseUsesEqualInstanceClaims(t *testing.T) {
t.Fatalf("ActiveInstances = %d, want 10", claims.ActiveInstances)
}
}
+
+func TestGetUserLimitUncached(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+
+ pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort())
+ s, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+ t.Cleanup(func() { s.Close() })
+
+ // Sign licenses with a test-only keypair so finite and expired licenses can
+ // be exercised.
+ privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+ require.NoError(t, err)
+ publicKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(&privateKey.PublicKey)})
+ publicKey, err := jwt.ParseRSAPublicKeyFromPEM(publicKeyPEM)
+ require.NoError(t, err)
+ licenseService := &LicenseService{
+ store: s,
+ config: &Config{
+ PublicKey: publicKey,
+ PrivateKey: privateKey,
+ Version: keyID,
+ Issuer: issuer,
+ Audience: audience,
+ Mode: common.ReleaseModeDev,
+ },
+ cache: expirable.NewLRU[string, *v1pb.Subscription](8, nil, time.Minute),
+ }
+ licenseService.replicaCache.Store(&replicaCacheState{replicaCount: 1, loadedAt: time.Now()})
+
+ // No workspace: the Free plan limit applies.
+ limit, err := licenseService.GetUserLimitUncached(ctx, "")
+ require.NoError(t, err)
+ require.Equal(t, userLimitValues[v1pb.PlanType_FREE], limit)
+
+ // Workspace without a license: the Free plan limit applies.
+ _, err = s.CreateWorkspace(ctx, &store.WorkspaceMessage{ResourceID: "ws-a"}, "[email protected]")
+ require.NoError(t, err)
+ limit, err = licenseService.GetUserLimitUncached(ctx, "ws-a")
+ require.NoError(t, err)
+ require.Equal(t, userLimitValues[v1pb.PlanType_FREE], limit)
+
+ storeLicense := func(t *testing.T, params *LicenseParams) {
+ t.Helper()
+ token, err := licenseService.CreateLicense(params)
+ require.NoError(t, err)
+ require.NoError(t, s.UpdateLicense(ctx, "ws-a", token))
+ }
+
+ // Finite Enterprise license: the seat claim wins.
+ storeLicense(t, &LicenseParams{
+ Plan: v1pb.PlanType_ENTERPRISE.String(), Seats: 100, WorkspaceID: "ws-a",
+ })
+ limit, err = licenseService.GetUserLimitUncached(ctx, "ws-a")
+ require.NoError(t, err)
+ require.Equal(t, 100, limit)
+
+ // Legacy Enterprise license without a seat claim: unlimited.
+ storeLicense(t, &LicenseParams{
+ Plan: v1pb.PlanType_ENTERPRISE.String(), Seats: 0, WorkspaceID: "ws-a",
+ })
+ limit, err = licenseService.GetUserLimitUncached(ctx, "ws-a")
+ require.NoError(t, err)
+ require.Equal(t, math.MaxInt, limit)
+
+ // Expired Enterprise license: falls back to the Free plan limit.
+ storeLicense(t, &LicenseParams{
+ Plan: v1pb.PlanType_ENTERPRISE.String(), Seats: 100, WorkspaceID: "ws-a",
+ ExpiresAt: time.Now().Add(-time.Hour),
+ })
+ limit, err = licenseService.GetUserLimitUncached(ctx, "ws-a")
+ require.NoError(t, err)
+ require.Equal(t, userLimitValues[v1pb.PlanType_FREE], limit)
+}
diff --git a/backend/server/echo_routes.go b/backend/server/echo_routes.go
index 8d10ae8ee8..84779cda0c 100644
--- a/backend/server/echo_routes.go
+++ b/backend/server/echo_routes.go
@@ -22,7 +22,9 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/enterprise"
stripeplugin "github.com/bytebase/bytebase/backend/plugin/stripe"
+ "github.com/bytebase/bytebase/backend/store"
)
func configureEchoRouters(
@@ -32,6 +34,8 @@ func configureEchoRouters(
oauth2Service *oauth2.Service,
mcpServer *mcp.Server,
stripeWebhookHandler *stripeapi.WebhookHandler,
+ stores *store.Store,
+ licenseService *enterprise.LicenseService,
profile *config.Profile,
) {
e.Use(recoverMiddleware)
@@ -63,7 +67,7 @@ func configureEchoRouters(
registerPprof(e, &profile.RuntimeDebug)
- registerMetricsRoute(e, profile)
+ registerMetricsRoute(e, profile, stores, licenseService)
e.GET("/healthz", func(c *echo.Context) error {
return c.String(http.StatusOK, "OK")
@@ -93,7 +97,7 @@ func configureEchoRouters(
embedFrontend(e)
}
-func registerMetricsRoute(e *echo.Echo, profile *config.Profile) {
+func registerMetricsRoute(e *echo.Echo, profile *config.Profile, stores *store.Store, licenseService *enterprise.LicenseService) {
if profile.SaaS {
return
}
@@ -121,11 +125,16 @@ func registerMetricsRoute(e *echo.Echo, profile *config.Profile) {
// Use promhttp directly: pass the local registry as the Registerer
// for self-instrumentation; pass the Gatherers fold as the gather
// source. Both observability surfaces preserved.
+ // Product-level license gauges are registered on the local registry only;
+ // they are computed synchronously on every scrape from fresh shared
+ // metadata. A collection failure fails the whole scrape (HTTP 500 via
+ // HTTPErrorOnError) instead of emitting zero, stale, or missing gauges.
+ registry.MustRegister(newLicenseSeatsCollector(stores, licenseService))
e.GET("/metrics", echo.WrapHandler(promhttp.InstrumentMetricHandler(
registry,
promhttp.HandlerFor(
prometheus.Gatherers{registry, prometheus.DefaultGatherer},
- promhttp.HandlerOpts{},
+ promhttp.HandlerOpts{ErrorHandling: promhttp.HTTPErrorOnError},
),
)))
}
diff --git a/backend/server/echo_routes_test.go b/backend/server/echo_routes_test.go
index 5cde7b2df4..b7bba6047b 100644
--- a/backend/server/echo_routes_test.go
+++ b/backend/server/echo_routes_test.go
@@ -92,7 +92,14 @@ func TestMetricsRouteDisabledInSaaS(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := echo.New()
- registerMetricsRoute(e, &config.Profile{SaaS: tt.saas})
+ if tt.saas {
+ registerMetricsRoute(e, &config.Profile{SaaS: true}, nil, nil)
+ } else {
+ // Self-host: use a real store and license service so the
+ // product-level license gauges are registered and collected.
+ _, st, licenseService := newMetricsTestEcho(t)
+ registerMetricsRoute(e, &config.Profile{SaaS: false}, st, licenseService)
+ }
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
rec := httptest.NewRecorder()
diff --git a/backend/server/metrics.go b/backend/server/metrics.go
new file mode 100644
index 0000000000..5f363596f7
--- /dev/null
+++ b/backend/server/metrics.go
@@ -0,0 +1,93 @@
+package server
+
+import (
+ "context"
+ "math"
+ "time"
+
+ "github.com/pkg/errors"
+ "github.com/prometheus/client_golang/prometheus"
+
+ "github.com/bytebase/bytebase/backend/enterprise"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// metricsCollectionTimeout bounds each collection so a slow metadata read cannot
+// hang a scrape indefinitely. Collectors receive no request context.
+const metricsCollectionTimeout = 5 * time.Second
+
+// licenseSeatsCollector exposes product-level license seat gauges at /metrics.
+// Both values are computed synchronously on every scrape from fresh shared
+// metadata (no per-replica caches), so replicas expose equivalent values.
+// A failed metadata read fails the whole scrape instead of emitting zero,
+// stale, or missing gauges.
+type licenseSeatsCollector struct {
+ stores *store.Store
+ licenseService *enterprise.LicenseService
+
+ usedSeats *prometheus.Desc
+ seatLimit *prometheus.Desc
+}
+
+func newLicenseSeatsCollector(stores *store.Store, licenseService *enterprise.LicenseService) *licenseSeatsCollector {
+ return &licenseSeatsCollector{
+ stores: stores,
+ licenseService: licenseService,
+ usedSeats: prometheus.NewDesc(
+ "bytebase_license_seats_used",
+ "Number of distinct end users occupying license seats in this Bytebase installation, including pending invites and group members, excluding deleted users and non-user identities.",
+ nil, nil,
+ ),
+ seatLimit: prometheus.NewDesc(
+ "bytebase_license_seats_limit",
+ "Effective seat limit enforced for this Bytebase installation. +Inf means the license has no seat limit.",
+ nil, nil,
+ ),
+ }
+}
+
+func (c *licenseSeatsCollector) Describe(ch chan<- *prometheus.Desc) {
+ ch <- c.usedSeats
+ ch <- c.seatLimit
+}
+
+func (c *licenseSeatsCollector) Collect(ch chan<- prometheus.Metric) {
+ ctx, cancel := context.WithTimeout(context.Background(), metricsCollectionTimeout)
+ defer cancel()
+
+ workspaceID, err := c.stores.GetWorkspaceID(ctx)
+ if err != nil {
+ failMetricCollection(ch, errors.Wrap(err, "failed to get workspace ID"))
+ return
+ }
+
+ used := 0
+ if workspaceID != "" {
+ used, err = c.stores.CountSeatOccupyingUsers(ctx, workspaceID)
+ if err != nil {
+ failMetricCollection(ch, errors.Wrapf(err, "failed to count seat-occupying users for workspace %q", workspaceID))
+ return
+ }
+ }
+
+ limit, err := c.licenseService.GetUserLimitUncached(ctx, workspaceID)
+ if err != nil {
+ failMetricCollection(ch, errors.Wrapf(err, "failed to read the user limit for workspace %q", workspaceID))
+ return
+ }
+
+ limitValue := float64(limit)
+ if limit == math.MaxInt {
+ limitValue = math.Inf(1)
+ }
+
+ ch <- prometheus.MustNewConstMetric(c.usedSeats, prometheus.GaugeValue, float64(used))
+ ch <- prometheus.MustNewConstMetric(c.seatLimit, prometheus.GaugeValue, limitValue)
+}
+
+// failMetricCollection emits an invalid metric, which makes Registry.Gather
+// fail and therefore fails the whole scrape (HTTP 500 via HTTPErrorOnError)
+// instead of reporting zero, stale, or partial values.
+func failMetricCollection(ch chan<- prometheus.Metric, err error) {
+ ch <- prometheus.NewInvalidMetric(prometheus.NewInvalidDesc(err), err)
+}
diff --git a/backend/server/metrics_test.go b/backend/server/metrics_test.go
new file mode 100644
index 0000000000..b38ab50b03
--- /dev/null
+++ b/backend/server/metrics_test.go
@@ -0,0 +1,175 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/labstack/echo/v5"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/enterprise"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// devEnterpriseLicense is the pre-signed dev-mode Enterprise license used by the
+// test suite (see backend/tests/subscription.go). It has no seat claim, so it
+// means unlimited seats.
+const devEnterpriseLicense = "eyJhbGciOiJSUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJpbnN0YW5jZUNvdW50Ijo5OTksInRyaWFsaW5nIjpmYWxzZSwicGxhbiI6IkVOVEVSUFJJU0UiLCJvcmdOYW1lIjoiYmIiLCJhdWQiOiJiYi5saWNlbnNlIiwiZXhwIjo3OTc0OTc5MjAwLCJpYXQiOjE2NjM2Njc1NjEsImlzcyI6ImJ5dGViYXNlIiwic3ViIjoiMDAwMDEwMDAuIn0.JjYCMeAAMB9FlVeDFLdN3jvFcqtPsbEzaIm1YEDhUrfekthCbIOeX_DB2Bg2OUji3HSX5uDvG9AkK4Gtrc4gLMPI3D5mk3L-6wUKZ0L4REztS47LT4oxVhpqPQayYa9lKJB1YoHaqeMV4Z5FXeOXwuACoELznlwpT6pXo9xXm_I6QwQiO7-zD83XOTO4PRjByc-q3GKQu_64zJMIKiCW0I8a3GvrdSnO7jUuYU1KPmCuk0ZRq3I91m29LTo478BMST59HqCLj1GGuCKtR3SL_376XsZfUUM0iSAur5scg99zNGWRj-sUo05wbAadYx6V6TKaWrBUi_8_0RnJyP5gbA"
+
+// newMetricsTestEcho returns an echo server with the self-host /metrics route
+// wired to a real store and license service backed by a fresh PostgreSQL.
+func newMetricsTestEcho(t *testing.T) (*echo.Echo, *store.Store, *enterprise.LicenseService) {
+ t.Helper()
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+
+ pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort())
+ st, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+ t.Cleanup(func() { st.Close() })
+
+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, st, false, "")
+ require.NoError(t, err)
+
+ e := echo.New()
+ registerMetricsRoute(e, &config.Profile{SaaS: false}, st, licenseService)
+ return e, st, licenseService
+}
+
+func scrapeMetrics(t *testing.T, e *echo.Echo, wantStatus int) string {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, req)
+ require.Equal(t, wantStatus, rec.Code, rec.Body.String())
+ return rec.Body.String()
+}
+
+func TestCollisionMetricsLicenseSeats(t *testing.T) {
+ ctx := context.Background()
+ e, st, licenseService := newMetricsTestEcho(t)
+
+ // No workspace yet: no seats, Free-plan limit.
+ body := scrapeMetrics(t, e, http.StatusOK)
+ require.Contains(t, body, "bytebase_license_seats_used 0")
+ require.Contains(t, body, "bytebase_license_seats_limit 20")
+
+ _, err := st.GetDB().ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws-test');
+ INSERT INTO setting (name, workspace, value) VALUES ('SYSTEM', 'ws-test', '{}'::jsonb);
+ INSERT INTO principal (name, email, password_hash, deleted) VALUES
+ ('alice', '[email protected]', 'x', FALSE),
+ ('bob', '[email protected]', 'x', FALSE),
+ ('carol', '[email protected]', 'x', TRUE),
+ ('eve', '[email protected]', 'x', FALSE);
+ INSERT INTO user_group (id, workspace, email, name, description, payload) VALUES
+ ('group-1', 'ws-test', '[email protected]', 'Eng', '', '{"members":[{"member":"users/[email protected]","role":"MEMBER"},{"member":"users/[email protected]","role":"MEMBER"}]}'::jsonb);
+ `)
+ require.NoError(t, err)
+
+ policyPayload, err := protojson.Marshal(&storepb.IamPolicy{
+ Bindings: []*storepb.Binding{
+ {
+ Role: "roles/workspaceAdmin",
+ Members: []string{
+ // Direct end user.
+ // Deleted principal: does not occupy a seat.
+ // Pending invite: no principal yet, still occupies a seat.
+ // Non-user identities: never occupy seats.
+ "serviceAccounts/[email protected]",
+ "workloadIdentities/[email protected]",
+ // Group expansion: bob (principal) and dave (pending invite).
+ "groups/[email protected]",
+ },
+ },
+ },
+ })
+ require.NoError(t, err)
+ _, err = st.GetDB().ExecContext(ctx, `
+ INSERT INTO policy (workspace, resource_type, resource, type, payload, inherit_from_parent, enforce)
+ VALUES ('ws-test', 'WORKSPACE', 'workspaces/ws-test', 'IAM', $1, FALSE, TRUE)
+ `, string(policyPayload))
+ require.NoError(t, err)
+
+ // Alice (direct), pending (direct), bob (group), dave (group) = 4 seats.
+ body = scrapeMetrics(t, e, http.StatusOK)
+ require.Contains(t, body, "bytebase_license_seats_used 4")
+ require.Contains(t, body, "bytebase_license_seats_limit 20")
+
+ // A colliding group email in another workspace must not leak into this
+ // workspace's count. Keep the second workspace deleted so GetWorkspaceID
+ // continues to select ws-test.
+ otherPolicyPayload, err := protojson.Marshal(&storepb.IamPolicy{
+ Bindings: []*storepb.Binding{{Role: "roles/workspaceAdmin", Members: []string{"groups/[email protected]"}}},
+ })
+ require.NoError(t, err)
+ _, err = st.GetDB().ExecContext(ctx, `
+ INSERT INTO workspace (resource_id, deleted) VALUES ('ws-other', TRUE);
+ INSERT INTO user_group (id, workspace, email, name, description, payload) VALUES
+ ('group-other', 'ws-other', '[email protected]', 'Other Eng', '', '{"members":[{"member":"users/[email protected]","role":"MEMBER"}]}'::jsonb);
+ `)
+ require.NoError(t, err)
+ _, err = st.GetDB().ExecContext(ctx, `
+ INSERT INTO policy (workspace, resource_type, resource, type, payload, inherit_from_parent, enforce)
+ VALUES ('ws-other', 'WORKSPACE', 'workspaces/ws-other', 'IAM', $1, FALSE, TRUE)
+ `, string(otherPolicyPayload))
+ require.NoError(t, err)
+ body = scrapeMetrics(t, e, http.StatusOK)
+ require.Contains(t, body, "bytebase_license_seats_used 4")
+
+ // An Enterprise license without a seat claim means unlimited seats (+Inf).
+ require.NoError(t, licenseService.StoreLicense(ctx, "ws-test", devEnterpriseLicense))
+ body = scrapeMetrics(t, e, http.StatusOK)
+ require.Contains(t, body, "bytebase_license_seats_used 4")
+ require.Contains(t, body, "bytebase_license_seats_limit +Inf")
+
+ // A failing metadata read must fail the scrape instead of emitting
+ // zero, stale, or missing gauges.
+ require.NoError(t, st.Close())
+ scrapeMetrics(t, e, http.StatusInternalServerError)
+}
+
+func TestMetricsLicenseSeatsAllUsers(t *testing.T) {
+ ctx := context.Background()
+ e, st, _ := newMetricsTestEcho(t)
+
+ _, err := st.GetDB().ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws-allusers');
+ INSERT INTO principal (name, email, password_hash, deleted) VALUES
+ ('p1', '[email protected]', 'x', FALSE),
+ ('p2', '[email protected]', 'x', FALSE),
+ ('p3', '[email protected]', 'x', TRUE);
+ `)
+ require.NoError(t, err)
+ policyPayload, err := protojson.Marshal(&storepb.IamPolicy{
+ Bindings: []*storepb.Binding{{Role: "roles/workspaceMember", Members: []string{"allUsers"}}},
+ })
+ require.NoError(t, err)
+ _, err = st.GetDB().ExecContext(ctx, `
+ INSERT INTO policy (workspace, resource_type, resource, type, payload, inherit_from_parent, enforce)
+ VALUES ('ws-allusers', 'WORKSPACE', 'workspaces/ws-allusers', 'IAM', $1, FALSE, TRUE)
+ `, string(policyPayload))
+ require.NoError(t, err)
+
+ // allUsers means every active principal occupies a seat.
+ body := scrapeMetrics(t, e, http.StatusOK)
+ require.Contains(t, body, "bytebase_license_seats_used 2")
+ require.Contains(t, body, "bytebase_license_seats_limit 20")
+}
diff --git a/backend/server/server.go b/backend/server/server.go
index 44f978d5e3..5f78d01c46 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -245,7 +245,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
if err := configureGrpcRouters(ctx, s.echoServer, s.store, sheetManager, s.dbFactory, s.licenseService, s.profile, s.bus, s.schemaSyncer, s.webhookManager, s.iamManager, secret, s.sampleInstanceManager); err != nil {
return nil, errors.Wrapf(err, "failed to configure gRPC routers")
}
- configureEchoRouters(s.echoServer, s.lspServer, directorySyncServer, oauth2Service, mcpServer, stripeWebhookHandler, profile)
+ configureEchoRouters(s.echoServer, s.lspServer, directorySyncServer, oauth2Service, mcpServer, stripeWebhookHandler, s.store, s.licenseService, profile)
serverStarted = true
return s, nil
diff --git a/backend/store/setting.go b/backend/store/setting.go
index ae7fbe3cc1..c2e6b6c101 100644
--- a/backend/store/setting.go
+++ b/backend/store/setting.go
@@ -122,6 +122,23 @@ func (s *Store) GetSystemSetting(ctx context.Context, workspaceID string) (*stor
return val, nil
}
+// GetSystemSettingUncached gets the SYSTEM setting directly from the database,
+// bypassing the setting cache. Returns (nil, nil) if no SYSTEM setting exists.
+func (s *Store) GetSystemSettingUncached(ctx context.Context, workspaceID string) (*storepb.SystemSetting, error) {
+ setting, err := s.GetSettingUncached(ctx, workspaceID, storepb.SettingName_SYSTEM)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get setting %v", storepb.SettingName_SYSTEM)
+ }
+ if setting == nil {
+ return nil, nil
+ }
+ val, ok := setting.Value.(*storepb.SystemSetting)
+ if !ok {
+ return nil, errors.Errorf("invalid setting value type for %s", storepb.SettingName_SYSTEM)
+ }
+ return val, nil
+}
+
// UpdateLicense updates the license in SYSTEM setting.
func (s *Store) UpdateLicense(ctx context.Context, workspaceID string, license string) error {
setting, err := s.GetSetting(ctx, workspaceID, storepb.SettingName_SYSTEM)
diff --git a/backend/store/stats.go b/backend/store/stats.go
index a1512ef2ea..7cc40b7827 100644
--- a/backend/store/stats.go
+++ b/backend/store/stats.go
@@ -38,3 +38,69 @@ func (s *Store) CountActivePrincipals(ctx context.Context) (int, error) {
}
return count, nil
}
+
+// CountSeatOccupyingUsers counts the distinct end users occupying license seats
+// in a workspace: direct workspace IAM members (users/{email}) plus members of
+// IAM groups (groups/{email} or groups/{id}), deduplicated. Pending invites
+// (emails without a principal yet) count; soft-deleted principals, service
+// accounts, and workload identities do not. When the workspace IAM policy
+// includes allUsers, every active principal occupies a seat.
+//
+// The query reads the shared metadata tables directly and bypasses every
+// per-replica cache so replicas derive equivalent values from the same state.
+func (s *Store) CountSeatOccupyingUsers(ctx context.Context, workspaceID string) (int, error) {
+ const query = `
+WITH seat_emails AS (
+ SELECT DISTINCT lower(substring(member FROM char_length('users/') + 1)) AS email
+ FROM policy p,
+ jsonb_array_elements(p.payload->'bindings') AS binding,
+ jsonb_array_elements_text(binding->'members') AS member
+ WHERE p.workspace = $1
+ AND p.resource_type = 'WORKSPACE'
+ AND p.resource = 'workspaces/' || $1
+ AND p.type = 'IAM'
+ AND member LIKE 'users/%'
+ UNION
+ SELECT DISTINCT lower(substring(gm->>'member' FROM char_length('users/') + 1)) AS email
+ FROM policy p,
+ jsonb_array_elements(p.payload->'bindings') AS binding,
+ jsonb_array_elements_text(binding->'members') AS member,
+ user_group ug,
+ jsonb_array_elements(ug.payload->'members') AS gm
+ WHERE p.workspace = $1
+ AND p.resource_type = 'WORKSPACE'
+ AND p.resource = 'workspaces/' || $1
+ AND p.type = 'IAM'
+ AND member LIKE 'groups/%'
+ AND ug.workspace = $1
+ AND ('groups/' || ug.email = member OR 'groups/' || ug.id = member)
+ AND gm->>'member' LIKE 'users/%'
+)
+SELECT
+ CASE
+ WHEN EXISTS (
+ SELECT 1
+ FROM policy p,
+ jsonb_array_elements(p.payload->'bindings') AS binding,
+ jsonb_array_elements_text(binding->'members') AS member
+ WHERE p.workspace = $1
+ AND p.resource_type = 'WORKSPACE'
+ AND p.resource = 'workspaces/' || $1
+ AND p.type = 'IAM'
+ AND member = 'allUsers'
+ )
+ THEN (SELECT count(*) FROM principal WHERE deleted = FALSE)
+ ELSE (
+ SELECT count(*)
+ FROM seat_emails s
+ WHERE NOT EXISTS (
+ SELECT 1 FROM principal p WHERE p.email = s.email AND p.deleted
+ )
+ )
+ END`
+ var count int
+ if err := s.GetDB().QueryRowContext(ctx, query, workspaceID).Scan(&count); err != nil {
+ return 0, errors.Wrapf(err, "failed to count seat-occupying users for workspace %q", workspaceID)
+ }
+ return count, nil
+}
diff --git a/backend/tests/metrics_test.go b/backend/tests/metrics_test.go
new file mode 100644
index 0000000000..2551031dd2
--- /dev/null
+++ b/backend/tests/metrics_test.go
@@ -0,0 +1,78 @@
+package tests
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "regexp"
+ "slices"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+func TestCollisionMetricsLicenseSeats(t *testing.T) {
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ actuator, err := ctl.actuatorServiceClient.GetActuatorInfo(ctx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))
+ a.NoError(err)
+ base := actuator.Msg.UserCountInIam
+ a.Greater(base, int32(0), "workspace seat count precondition")
+
+ projectOnly, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{
+ User: &v1pb.User{
+ Title: "project-only",
+ Email: "[email protected]",
+ Password: "1024bytebase",
+ },
+ }))
+ a.NoError(err)
+
+ policyResp, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{
+ Resource: ctl.project.Name,
+ }))
+ a.NoError(err)
+ member := fmt.Sprintf("user:%s", projectOnly.Msg.Email)
+ policyResp.Msg.Bindings = append(policyResp.Msg.Bindings, &v1pb.Binding{
+ Role: "roles/projectDeveloper",
+ Members: []string{member},
+ })
+ _, err = ctl.projectServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{
+ Resource: ctl.project.Name,
+ Policy: policyResp.Msg,
+ }))
+ a.NoError(err)
+
+ readback, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{
+ Resource: ctl.project.Name,
+ }))
+ a.NoError(err)
+ found := false
+ for _, binding := range readback.Msg.Bindings {
+ if binding.Role == "roles/projectDeveloper" {
+ found = found || slices.Contains(binding.Members, member)
+ }
+ }
+ a.True(found, "project IAM collision precondition")
+
+ actuator, err = ctl.actuatorServiceClient.GetActuatorInfo(ctx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))
+ a.NoError(err)
+ a.Equal(base, actuator.Msg.UserCountInIam, "project IAM member must not occupy a workspace seat")
+
+ resp, err := ctl.client.Get(ctl.rootURL + "/metrics")
+ a.NoError(err)
+ defer resp.Body.Close()
+ a.Equal(http.StatusOK, resp.StatusCode)
+ body, err := io.ReadAll(resp.Body)
+ a.NoError(err)
+ a.Regexp(regexp.MustCompile(fmt.Sprintf(`(?m)^bytebase_license_seats_used %d$`, base)), string(body))
+}
diff --git a/docs/adr/0003-collect-state-metrics-on-every-replica.md b/docs/adr/0003-collect-state-metrics-on-every-replica.md
new file mode 100644
index 0000000000..dd6ce3ea02
--- /dev/null
+++ b/docs/adr/0003-collect-state-metrics-on-every-replica.md
@@ -0,0 +1,3 @@
+# Collect state metrics on every replica
+
+Every Bytebase replica serves installation-scoped state metrics from `/metrics` and computes them synchronously when scraped. This avoids leader election, failover gaps, and additional scrape topology at the cost of duplicate computation across the small replica set; add caching only when a metric-specific benchmark shows it is necessary.