Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: simplify the sample logic (#21229)
ecmadao0126d371fb51
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex cdeeb310b5..5793316010 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -8340,10 +8340,6 @@ components:title: total_instance_countformat: int32description: The total number of database instances.- enableSample:- type: boolean- title: enable_sample- description: Whether sample data setup is enabled.externalUrlFromFlag:type: booleantitle: external_url_from_flag@@ -8369,6 +8365,10 @@ components:title: active_vcs_user_countformat: int32description: The number of active VCS users seen in the active window.+ sample:+ title: sample+ description: Sample setup availability and provisioned resources.+ $ref: '#/components/schemas/bytebase.v1.SampleInfo'title: ActuatorInfoadditionalProperties: falsedescription: |-@@ -17913,6 +17913,28 @@ components:- BUILTIN_WALK_THROUGH_CHECK- STATEMENT_DISALLOW_TRUNCATE- BUILTIN_STATEMENT_MAXIMUM_SQL_SIZE+ bytebase.v1.SampleInfo:+ type: object+ properties:+ available:+ type: boolean+ title: available+ description: Whether sample setup is currently available.+ instances:+ type: array+ items:+ type: string+ title: instances+ description: |-+ The provisioned sample instances.+ Format: instances/{instance}+ expireTime:+ title: expire_time+ description: The time when the provisioned sample resources expire.+ $ref: '#/components/schemas/google.protobuf.Timestamp'+ title: SampleInfo+ additionalProperties: false+ description: SampleInfo describes sample setup availability and provisioned resources.bytebase.v1.SavedQuery:type: objectproperties:diff --git a/backend/api/v1/actuator_service.go b/backend/api/v1/actuator_service.goindex c435c7c208..4f1b3a392a 100644--- a/backend/api/v1/actuator_service.go+++ b/backend/api/v1/actuator_service.go@@ -17,6 +17,7 @@ import ("github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/sampleinstance"+ "github.com/bytebase/bytebase/backend/component/sampleprojectinstance""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"@@ -28,11 +29,12 @@ import (// ActuatorService implements the Connect RPC interface for ActuatorService.type ActuatorService struct {v1connect.UnimplementedActuatorServiceHandler- store *store.Store- profile *config.Profile- licenseService *enterprise.LicenseService- schemaSyncer *schemasync.Syncer- sampleInstanceManager *sampleinstance.Manager+ store *store.Store+ profile *config.Profile+ licenseService *enterprise.LicenseService+ schemaSyncer *schemasync.Syncer+ sampleInstanceManager *sampleinstance.Manager+ sampleProjectInstanceManager *sampleprojectinstance.ManageractiveVCSUserCountSnapshot *expirable.LRU[string, int]}@@ -46,14 +48,16 @@ func NewActuatorService(schemaSyncer *schemasync.Syncer,licenseService *enterprise.LicenseService,sampleInstanceManager *sampleinstance.Manager,+ sampleProjectInstanceManager *sampleprojectinstance.Manager,) *ActuatorService {return &ActuatorService{- store: store,- profile: profile,- licenseService: licenseService,- schemaSyncer: schemaSyncer,- sampleInstanceManager: sampleInstanceManager,- activeVCSUserCountSnapshot: expirable.NewLRU[string, int](1024, nil, activeVCSUserCountSnapshotTTL),+ store: store,+ profile: profile,+ licenseService: licenseService,+ schemaSyncer: schemaSyncer,+ sampleInstanceManager: sampleInstanceManager,+ sampleProjectInstanceManager: sampleProjectInstanceManager,+ activeVCSUserCountSnapshot: expirable.NewLRU[string, int](1024, nil, activeVCSUserCountSnapshotTTL),}}@@ -115,10 +119,25 @@ func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string)ExternalUrlFromFlag: s.profile.ExternalURL != "",ReplicaCount: int32(s.licenseService.CountActiveReplicas(ctx)),ExternalUrl: s.profile.ExternalURL,+ Sample: &v1pb.SampleInfo{},}if workspaceID != "" {serverInfo.Workspace = common.FormatWorkspace(workspaceID)+ if s.profile.SaaS {+ serverInfo.Sample.Available = s.sampleProjectInstanceManager != nil && s.sampleProjectInstanceManager.Available(ctx)+ sample, err := s.store.GetSampleProjectInstance(ctx, workspaceID)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get sample information"))+ }+ if sample != nil && sample.ExpiresAt != nil && sample.DeletedAt == nil {+ serverInfo.Sample.Instances = []string{common.FormatInstance(sample.InstanceID)}+ serverInfo.Sample.ExpireTime = timestamppb.New(*sample.ExpiresAt)+ }+ } else {+ hasSampleInstances, _ := s.store.HasSampleInstances(ctx, workspaceID)+ serverInfo.Sample.Available = hasSampleInstances+ }defaultProjectID, err := s.store.GetDefaultProjectID(ctx, workspaceID)if err != nil {@@ -153,10 +172,6 @@ func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string)}serverInfo.ActiveVcsUserCount = int32(activeVCSUserCount)- // Check if sample instances are available- hasSampleInstances, _ := s.store.HasSampleInstances(ctx, workspaceID)- serverInfo.EnableSample = hasSampleInstances-setting, err := s.store.GetWorkspaceProfileSetting(ctx, workspaceID)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find workspace setting"))diff --git a/backend/api/v1/actuator_service_test.go b/backend/api/v1/actuator_service_test.goindex ed091023fa..547d5618e5 100644--- a/backend/api/v1/actuator_service_test.go+++ b/backend/api/v1/actuator_service_test.go@@ -5,6 +5,7 @@ import ("fmt""slices""testing"+ "time""connectrpc.com/connect""github.com/stretchr/testify/require"@@ -13,6 +14,7 @@ import ("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/component/sampleprojectinstance""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"@@ -38,7 +40,14 @@ func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {GitCommit: "sensitive-commit",ExternalURL: "https://bytebase.example.com",}- actuatorService := NewActuatorService(stores, profile, nil, licenseService, nil)+ sampleProjectManager, err := sampleprojectinstance.NewManagerFromURL(+ nil,+ fmt.Sprintf("postgresql://postgres:root-password@%s:%s/postgres?sslmode=disable", container.GetHost(), container.GetPort()),+ nil,+ sampleprojectinstance.ManagerOptions{},+ )+ require.NoError(t, err)+ actuatorService := NewActuatorService(stores, profile, nil, licenseService, nil, sampleProjectManager)authService := NewAuthService(stores, "test-secret", licenseService, profile, nil)publicResponse, err := authService.GetAuthenticationRestriction(ctx, connect.NewRequest(&v1pb.GetAuthenticationRestrictionRequest{}))@@ -90,6 +99,23 @@ func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {require.NoError(t, err)authenticatedCtx := context.WithValue(ctx, common.UserContextKey, user)authenticatedCtx = context.WithValue(authenticatedCtx, common.WorkspaceIDContextKey, workspaceID)+ defaultProjectID, err := stores.GetDefaultProjectID(ctx, workspaceID)+ require.NoError(t, err)+ reservation, created, err := stores.ReserveSampleProjectInstance(ctx, &store.SampleProjectInstanceMessage{+ WorkspaceID: workspaceID,+ ProjectID: defaultProjectID,+ InstanceID: "sample-instance",+ DBName: "sample-database",+ RoleName: "sample-role",+ ReplicaID: "replica-a",+ })+ require.NoError(t, err)+ require.True(t, created)+ expiresAt := time.Now().Add(7 * 24 * time.Hour).Truncate(time.Microsecond)+ activated, err := stores.ActivateSampleProjectInstance(ctx, workspaceID, reservation.InstanceID, reservation.ReplicaID, expiresAt)+ require.NoError(t, err)+ require.True(t, activated)+ profile.SaaS = trueprivateResponse, err := actuatorService.GetActuatorInfo(authenticatedCtx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))require.NoError(t, err)@@ -97,4 +123,7 @@ func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {require.Equal(t, "sensitive-commit", privateResponse.Msg.GitCommit)require.Equal(t, common.FormatWorkspace(workspaceID), privateResponse.Msg.Workspace)require.NotEmpty(t, privateResponse.Msg.DefaultProject)+ require.True(t, privateResponse.Msg.Sample.Available)+ require.Equal(t, []string{common.FormatInstance(reservation.InstanceID)}, privateResponse.Msg.Sample.Instances)+ require.True(t, expiresAt.Equal(privateResponse.Msg.Sample.ExpireTime.AsTime()))}diff --git a/backend/api/v1/audit_redact_inventory_test.go b/backend/api/v1/audit_redact_inventory_test.goindex 575fdccc96..b19bdb6327 100644--- a/backend/api/v1/audit_redact_inventory_test.go+++ b/backend/api/v1/audit_redact_inventory_test.go@@ -832,6 +832,7 @@ var auditRecordedFields = []string{"bytebase.v1.SQLReviewRule.NamingRulePayload.format","bytebase.v1.SQLReviewRule.StringArrayRulePayload.list","bytebase.v1.SQLReviewRule.StringRulePayload.value",+ "bytebase.v1.SampleInfo.instances","bytebase.v1.SavedQuery.creator","bytebase.v1.SavedQuery.database","bytebase.v1.SavedQuery.folder",diff --git a/backend/api/v1/sample_project_instance_integration_test.go b/backend/api/v1/sample_project_instance_integration_test.goindex a892c797c1..5b3cb940e2 100644--- a/backend/api/v1/sample_project_instance_integration_test.go+++ b/backend/api/v1/sample_project_instance_integration_test.go@@ -301,12 +301,13 @@ func newSampleProjectInstanceFixture(t *testing.T, clock func() time.Time) (contsampleTarget, err := sampleprojectinstance.NewTarget(targetURL)require.NoError(t, err)inspector := newSampleTargetInspector(t, targetURL)- manager := sampleprojectinstance.NewManagerFromURL(+ manager, err := sampleprojectinstance.NewManagerFromURL(stores,targetURL,syncer,sampleprojectinstance.ManagerOptions{Clock: clock, ReplicaID: "replica-a"},)+ require.NoError(t, err)return context.WithValue(ctx, common.WorkspaceIDContextKey, "sample-workspace"), &sampleProjectInstanceFixture{store: stores,service: &InstanceService{diff --git a/backend/component/sampleprojectinstance/manager.go b/backend/component/sampleprojectinstance/manager.goindex 0b66799472..7db3140918 100644--- a/backend/component/sampleprojectinstance/manager.go+++ b/backend/component/sampleprojectinstance/manager.go@@ -12,6 +12,7 @@ import ("fmt""io""log/slog"+ "sync""time""github.com/bytebase/bytebase/backend/common"@@ -22,12 +23,13 @@ import (const (sampleProjectInstanceTitle = "Sample Project Instance"- testEnvironmentID = "test"sampleLifetime = 7 * 24 * time.HourprepareDeadline = 3 * time.MinuteprovisionDeadline = 2 * time.MinutecompensationDeadline = time.MinutecleanupValidationDeadline = 10 * time.Second+ targetAvailabilityDeadline = 3 * time.Second+ targetAvailabilityCacheTTL = time.MinutecleanupAttemptDeadline = time.MinutestaleReservationAge = time.HourreplicaHeartbeatStaleness = time.Minute@@ -90,7 +92,7 @@ type AllocationNames struct {func sampleNames(instanceID string) AllocationNames {sum := sha256.Sum256([]byte(instanceID))- token := fmt.Sprintf("%x", sum[:16])+ token := fmt.Sprintf("%x", sum[:8])return AllocationNames{Database: "bb_sample_" + token,Role: "bb_sample_role_" + token,@@ -161,33 +163,34 @@ type ManagerOptions struct {// Manager orchestrates reservation, physical provisioning, metadata// registration, discovery, expiration, and cleanup.type Manager struct {- store *store.Store- target *Target- targetErr error- syncer *schemasync.Syncer- clock func() time.Time- random io.Reader- logger *slog.Logger- replicaID string-}--// NewManagerFromURL creates a startup-safe manager from raw target-// configuration. Invalid static configuration is retained for lifecycle calls-// instead of failing process startup.+ store *store.Store+ target *Target+ syncer *schemasync.Syncer+ clock func() time.Time+ random io.Reader+ logger *slog.Logger++ targetAvailabilityMu sync.Mutex+ targetAvailabilityCheckedAt time.Time+ targetAvailable bool+ replicaID string+}++// NewManagerFromURL creates a manager from raw target configuration.func NewManagerFromURL(s *store.Store,targetURL string,syncer *schemasync.Syncer,options ManagerOptions,-) *Manager {+) (*Manager, error) {target, err := NewTarget(targetURL)- manager := NewManager(s, target, syncer, options)- manager.targetErr = err- return manager+ if err != nil {+ return nil, err+ }+ return newManager(s, target, syncer, options), nil}-// NewManager creates a Sample Project Instance lifecycle manager.-func NewManager(+func newManager(s *store.Store,target *Target,syncer *schemasync.Syncer,@@ -213,9 +216,49 @@ func NewManager(}}+// ValidateTarget verifies the configured target before enabling Sample Project+// Instance provisioning.+func (m *Manager) ValidateTarget(ctx context.Context) error {+ if m == nil || m.target == nil {+ return errors.New("sample project instance target is not configured")+ }+ validationCtx, cancel := context.WithTimeout(ctx, cleanupValidationDeadline)+ defer cancel()+ err := m.target.Validate(validationCtx)+ m.recordTargetAvailability(err == nil)+ return err+}++// Available reports cached target readiness, refreshing stale state with a+// short validation probe.+func (m *Manager) Available(ctx context.Context) bool {+ if m == nil || m.target == nil {+ return false+ }+ m.targetAvailabilityMu.Lock()+ defer m.targetAvailabilityMu.Unlock()++ now := m.clock()+ if !m.targetAvailabilityCheckedAt.IsZero() && now.Before(m.targetAvailabilityCheckedAt.Add(targetAvailabilityCacheTTL)) {+ return m.targetAvailable+ }+ validationCtx, cancel := context.WithTimeout(ctx, targetAvailabilityDeadline)+ defer cancel()+ m.targetAvailable = m.target.Validate(validationCtx) == nil+ m.targetAvailabilityCheckedAt = m.clock()+ return m.targetAvailable+}++func (m *Manager) recordTargetAvailability(available bool) {+ m.targetAvailabilityMu.Lock()+ defer m.targetAvailabilityMu.Unlock()+ m.targetAvailable = available+ m.targetAvailabilityCheckedAt = m.clock()+}+// Prepare provisions and registers a seven-day sample instance for a project.func (m *Manager) Prepare(ctx context.Context, request PrepareRequest) (*PrepareResult, error) {- if m.store == nil || (m.target == nil && m.targetErr == nil) || m.syncer == nil || m.replicaID == "" {+ if m.store == nil || m.target == nil || m.syncer == nil || m.replicaID == "" {return nil, errors.New("sample project instance manager is not configured")}if request.WorkspaceID == "" || request.ProjectID == "" {@@ -339,9 +382,6 @@ func (m *Manager) prepareOwned(workCtx, workCancel := preparationWorkContext(lifecycleCtx)defer workCancel()if takeover {- if m.targetErr != nil {- return nil, mapTargetError(m.targetErr)- }m.logger.InfoContext(workCtx, "reconciling stale sample project instance reservation", "workspace", request.WorkspaceID)if err := m.reconcile(workCtx, allocation, reservation.InstanceID, request); err != nil {m.logger.ErrorContext(workCtx, "failed to reconcile stale sample project instance reservation", "workspace", request.WorkspaceID, "error", err)@@ -349,10 +389,7 @@ func (m *Manager) prepareOwned(}}- if m.targetErr != nil {- return nil, m.discardReservation(lifecycleCtx, reservation, mapTargetError(m.targetErr))- }- if err := m.target.Validate(workCtx); err != nil {+ if err := m.ValidateTarget(workCtx); err != nil {return nil, m.discardReservation(lifecycleCtx, reservation, mapTargetError(err))}if request.CheckCreatePolicy != nil {@@ -369,16 +406,8 @@ func (m *Manager) prepareOwned(return nil, m.discardReservation(lifecycleCtx, reservation, errors.Join(errors.New("failed to inspect sample project instance environments"), err))}environmentID := ""- for _, environment := range environments.GetEnvironments() {- if environmentID == "" || environment.Id == testEnvironmentID {- environmentID = environment.Id- }- if environment.Id == testEnvironmentID {- break- }- }- if environmentID == "" {- return nil, m.discardReservation(lifecycleCtx, reservation, newFailure(FailureFailedPrecondition, errors.New("sample project instance requires an environment")))+ if environments := environments.GetEnvironments(); len(environments) > 0 {+ environmentID = environments[0].Id}password, err := randomPassword(m.random)@@ -534,15 +563,12 @@ func (m *Manager) handleActivationFailure(// Cleanup removes expired target resources and reconciles stale reservations.func (m *Manager) Cleanup(ctx context.Context, now time.Time) error {- if m.store == nil || (m.target == nil && m.targetErr == nil) {+ if m.store == nil || m.target == nil {return errors.New("sample project instance manager is not configured")}- targetErr := m.targetErr- if targetErr == nil {- validationCtx, validationCancel := context.WithTimeout(ctx, cleanupValidationDeadline)- targetErr = m.target.ValidateForCleanup(validationCtx)- validationCancel()- }+ validationCtx, validationCancel := context.WithTimeout(ctx, cleanupValidationDeadline)+ targetErr := m.target.ValidateForCleanup(validationCtx)+ validationCancel()if targetErr != nil {count, countErr := m.store.CountSampleProjectInstancesForCleanup(ctx, now, now.Add(-staleReservationAge))if countErr != nil {@@ -616,7 +642,7 @@ func randomPassword(reader io.Reader) (string, error) {}func randomInstanceID(reader io.Reader) (string, error) {- bytes := make([]byte, 16)+ bytes := make([]byte, 8)if _, err := io.ReadFull(reader, bytes); err != nil {return "", err}diff --git a/backend/component/sampleprojectinstance/manager_test.go b/backend/component/sampleprojectinstance/manager_test.goindex f47234c710..ff251b6a49 100644--- a/backend/component/sampleprojectinstance/manager_test.go+++ b/backend/component/sampleprojectinstance/manager_test.go@@ -1,6 +1,7 @@package sampleprojectinstanceimport (+ "bytes""context""database/sql""errors"@@ -24,6 +25,18 @@ import ("github.com/bytebase/bytebase/backend/store")+func TestRandomInstanceIDUses16CharacterToken(t *testing.T) {+ id, err := randomInstanceID(bytes.NewReader(make([]byte, 8)))+ require.NoError(t, err)+ require.Equal(t, "sample-0000000000000000", id)+}++func TestSampleNamesUse16CharacterTokens(t *testing.T) {+ names := sampleNames("sample-0000000000000000")+ require.Regexp(t, `^bb_sample_[0-9a-f]{16}$`, names.Database)+ require.Regexp(t, `^bb_sample_role_[0-9a-f]{16}$`, names.Role)+}+func TestFailureKindOf(t *testing.T) {require.Equal(t, FailureUnknown, FailureKindOf(errors.New("unexpected")))require.Equal(t, FailureFailedPrecondition, FailureKindOf(newFailure(FailureFailedPrecondition, errors.New("invalid target"))))@@ -37,6 +50,39 @@ func TestMapTargetErrorUsesManagerFailureVocabulary(t *testing.T) {require.Equal(t, FailureDeadlineExceeded, FailureKindOf(mapTargetError(context.DeadlineExceeded)))}+func TestManagerValidateTargetRejectsInvalidConfiguration(t *testing.T) {+ manager, err := NewManagerFromURL(nil, "postgresql://control:[email protected]:5432/postgres?sslmode=prefer", nil, ManagerOptions{})+ require.Nil(t, manager)+ require.ErrorContains(t, err, "unsupported sslmode")+ require.NotContains(t, err.Error(), "secret")+}++func TestManagerAvailabilityRecoversAfterCachedValidationFailure(t *testing.T) {+ if testing.Short() {+ t.Skip("skipping PostgreSQL testcontainer test in short mode")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ t.Cleanup(cancel)+ container := testcontainer.GetTestPgContainer(ctx, t)+ t.Cleanup(func() { container.Close(context.Background()) })++ now := time.Now()+ target := newLocalTarget(t, container)+ manager := newManager(nil, target, nil, ManagerOptions{Clock: func() time.Time { return now }})+ require.True(t, manager.Available(ctx))++ port := target.config.Port+ target.config.Port = 1+ require.True(t, manager.Available(ctx))+ now = now.Add(targetAvailabilityCacheTTL)+ require.False(t, manager.Available(ctx))++ target.config.Port = port+ require.False(t, manager.Available(ctx))+ now = now.Add(targetAvailabilityCacheTTL)+ require.True(t, manager.Available(ctx))+}+func TestPreparationLifecycleContextRenewsDeadline(t *testing.T) {oldLifecycle, oldCancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second))defer oldCancel()@@ -296,7 +342,7 @@ func TestManagerHealthyOwnerProvisionsOnce(t *testing.T) {ctx, _, s, target, first := newConcreteManager(t)licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, s, false, "")require.NoError(t, err)- second := NewManager(s, target, schemasync.NewSyncer(s, dbfactory.New(s, licenseService), licenseService, nil), ManagerOptions{ReplicaID: "replica-b"})+ second := newManager(s, target, schemasync.NewSyncer(s, dbfactory.New(s, licenseService), licenseService, nil), ManagerOptions{ReplicaID: "replica-b"})require.NoError(t, s.UpsertReplicaHeartbeat(ctx, "replica-a"))entered := make(chan struct{})@@ -353,7 +399,7 @@ func TestManagerTakesOverStaleReservationAfterReconciling(t *testing.T) {licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, s, false, "")require.NoError(t, err)- second := NewManager(s, target, schemasync.NewSyncer(s, dbfactory.New(s, licenseService), licenseService, nil), ManagerOptions{ReplicaID: "replica-b"})+ second := newManager(s, target, schemasync.NewSyncer(s, dbfactory.New(s, licenseService), licenseService, nil), ManagerOptions{ReplicaID: "replica-b"})prepared, err := second.Prepare(ctx, PrepareRequest{WorkspaceID: "workspace-a", ProjectID: "project-a"})require.NoError(t, err)require.NotNil(t, prepared.Instance)@@ -369,13 +415,14 @@ func TestManagerTakesOverStaleReservationAfterReconciling(t *testing.T) {require.True(t, exists)}-func TestManagerUsesFirstEnvironmentWhenTestIsMissing(t *testing.T) {+func TestManagerUsesFirstEnvironment(t *testing.T) {ctx, _, s, _, manager := newConcreteManager(t)_, err := s.UpsertSetting(ctx, &store.SettingMessage{Name: storepb.SettingName_ENVIRONMENT,Workspace: "workspace-a",Value: &storepb.EnvironmentSetting{Environments: []*storepb.EnvironmentSetting_Environment{{Title: "Production", Id: "prod"},+ {Title: "Test", Id: "test"},}},})require.NoError(t, err)@@ -390,6 +437,20 @@ func TestManagerUsesFirstEnvironmentWhenTestIsMissing(t *testing.T) {require.Equal(t, names.Role, reservation.RoleName)}+func TestManagerAllowsNoEnvironment(t *testing.T) {+ ctx, _, s, _, manager := newConcreteManager(t)+ _, err := s.UpsertSetting(ctx, &store.SettingMessage{+ Name: storepb.SettingName_ENVIRONMENT,+ Workspace: "workspace-a",+ Value: &storepb.EnvironmentSetting{},+ })+ require.NoError(t, err)++ result, err := manager.Prepare(ctx, PrepareRequest{WorkspaceID: "workspace-a", ProjectID: "project-a"})+ require.NoError(t, err)+ require.Nil(t, result.Instance.EnvironmentID)+}+func TestManagerCompensatesProvisionFailures(t *testing.T) {stages := []provisionStage{provisionStageRoleCreated,@@ -462,7 +523,7 @@ func TestManagerReconcileAttemptsTargetCleanupWhenMetadataRemovalFails(t *testin_, err = manager.createMetadata(ctx, registration{WorkspaceID: "workspace-a",ProjectID: "project-b",- EnvironmentID: testEnvironmentID,+ EnvironmentID: "test",InstanceID: reservation.InstanceID,Title: sampleProjectInstanceTitle,Engine: storepb.Engine_POSTGRES,@@ -488,7 +549,7 @@ func newConcreteManager(t *testing.T) (context.Context, *sql.DB, *store.Store, *Name: storepb.SettingName_ENVIRONMENT,Workspace: "workspace-a",Value: &storepb.EnvironmentSetting{Environments: []*storepb.EnvironmentSetting_Environment{- {Title: "Test", Id: testEnvironmentID},+ {Title: "Test", Id: "test"},}},})require.NoError(t, err)@@ -509,7 +570,7 @@ func newConcreteManager(t *testing.T) (context.Context, *sql.DB, *store.Store, *licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, s, false, "")require.NoError(t, err)syncer := schemasync.NewSyncer(s, dbfactory.New(s, licenseService), licenseService, nil)- return ctx, db, s, target, NewManager(s, target, syncer, ManagerOptions{ReplicaID: "replica-a"})+ return ctx, db, s, target, newManager(s, target, syncer, ManagerOptions{ReplicaID: "replica-a"})}func assertAllocationAbsent(ctx context.Context, t *testing.T, target *Target, names AllocationNames) {diff --git a/backend/component/sampleprojectinstance/target.go b/backend/component/sampleprojectinstance/target.goindex f087b1993d..b32795915e 100644--- a/backend/component/sampleprojectinstance/target.go+++ b/backend/component/sampleprojectinstance/target.go@@ -36,6 +36,7 @@ type InstanceConfig struct {// Target manages direct PostgreSQL operations for sample project instances.type Target struct {config *pgx.ConnConfig+ useSSL boolverifyTLS boolsslCA stringprovisionHook func(provisionStage) error@@ -83,8 +84,19 @@ func NewTarget(targetURL string) (*Target, error) {}query := u.Query()- if len(query["sslmode"]) != 1 || query.Get("sslmode") != "verify-full" {- return nil, staticTargetError("sample project instance target URL requires sslmode=verify-full")+ if len(query["sslmode"]) > 1 {+ return nil, staticTargetError("sample project instance target URL requires at most one sslmode")+ }+ sslMode := query.Get("sslmode")+ switch sslMode {+ case "":+ sslMode = "disable"+ query.Set("sslmode", sslMode)+ u.RawQuery = query.Encode()+ targetURL = u.String()+ case "disable", "require", "verify-full":+ default:+ return nil, staticTargetError("sample project instance target URL has unsupported sslmode")}for key := range query {if key != "sslmode" && key != "sslrootcert" {@@ -113,7 +125,7 @@ func NewTarget(targetURL string) (*Target, error) {}sslCA = resolved.GetSslCa()}- return newTargetFromConfig(config, true, sslCA), nil+ return newTargetFromConfig(config, sslMode == "verify-full", sslCA), nil}// InstanceConfig builds the persisted admin datasource and its exact discovery@@ -131,7 +143,7 @@ func (t *Target) InstanceConfig(allocation Allocation) (*InstanceConfig, error)Database: allocation.Database,Username: allocation.Role,Password: allocation.Password,- UseSsl: true,+ UseSsl: t.useSSL,VerifyTlsCertificate: t.verifyTLS,SslCa: t.sslCA,},@@ -142,24 +154,19 @@ func (t *Target) InstanceConfig(allocation Allocation) (*InstanceConfig, error)func newTargetFromConfig(config *pgx.ConnConfig, verifyTLS bool, sslCA string) *Target {return &Target{config: config,+ useSSL: config.TLSConfig != nil,verifyTLS: verifyTLS,sslCA: sslCA,}}-// Validate verifies the target is reachable and has the static isolation-// baseline required before allocating shared sample databases.+// Validate verifies the target is reachable and can allocate sample databases.func (t *Target) Validate(ctx context.Context) error {- if err := t.validateCapabilities(ctx, true); err != nil {- return err- }- return t.validateIsolationBaseline(ctx)+ return t.validateCapabilities(ctx, true)}// ValidateForCleanup verifies the connectivity and target capabilities needed-// to remove existing allocations. Unlike Validate, it does not require the-// provisioning isolation baseline because a partially provisioned allocation-// may need cleanup before that baseline can be restored.+// to remove existing allocations. Cleanup does not require CREATEDB.func (t *Target) ValidateForCleanup(ctx context.Context) error {return t.validateCapabilities(ctx, false)}@@ -188,60 +195,6 @@ func (t *Target) validateCapabilities(ctx context.Context, requireCreateDB bool)return nil}-func (t *Target) validateIsolationBaseline(ctx context.Context) error {- conn, err := t.connect(ctx, "", "", "")- if err != nil {- return errors.New("failed to connect to sample project instance target")- }- defer conn.Close(ctx)-- rows, err := conn.Query(ctx, `- SELECT- datname,- datallowconn,- EXISTS (- SELECT 1- FROM aclexplode(COALESCE(datacl, acldefault('d', datdba))) AS privilege- WHERE privilege.grantee = 0- AND privilege.privilege_type IN ('CONNECT', 'TEMPORARY')- )- FROM pg_database- `)- if err != nil {- return errors.New("failed to inspect sample project instance target database privileges")- }- defer rows.Close()-- for rows.Next() {- var name string- var allowConnections, publicAccess bool- if err := rows.Scan(&name, &allowConnections, &publicAccess); err != nil {- return errors.New("failed to read sample project instance target database privileges")- }- switch name {- case "postgres", "template1":- if publicAccess {- return staticTargetError("sample project instance target requires postgres and template1 to deny PUBLIC access")- }- case "template0":- if allowConnections {- return staticTargetError("sample project instance target requires template0 to deny connections")- }- case "cloudsqladmin":- // Cloud SQL reserves this exact database for its administration- // service. It is not a tenant-accessible sample database.- default:- if allowConnections && publicAccess {- return staticTargetError("sample project instance target has a connectable database with PUBLIC access")- }- }- }- if err := rows.Err(); err != nil {- return errors.New("failed to inspect sample project instance target database privileges")- }- return nil-}-// Provision creates a sample role and database, applies the isolation policy,// and seeds the employee data as the sample role. On failure, callers clean up// any resources created by this attempt with Remove.@@ -371,7 +324,7 @@ func (t *Target) Remove(ctx context.Context, allocation Allocation) error {if err := t.runProvisionHook(provisionStageCleanupDatabase); err != nil {return errors.New("failed while removing sample project instance database")}- if _, err := admin.Exec(ctx, fmt.Sprintf("DROP DATABASE %s WITH (FORCE)", quoteIdentifier(allocation.Database))); err != nil {+ if _, err := admin.Exec(ctx, fmt.Sprintf("DROP DATABASE %s", quoteIdentifier(allocation.Database))); err != nil {return errors.New("failed to drop sample project instance database")}}diff --git a/backend/component/sampleprojectinstance/target_test.go b/backend/component/sampleprojectinstance/target_test.goindex ddfeebbb0b..9c7432c87a 100644--- a/backend/component/sampleprojectinstance/target_test.go+++ b/backend/component/sampleprojectinstance/target_test.go@@ -24,8 +24,7 @@ func TestNewTargetRejectsUnsafeConfiguration(t *testing.T) {{name: "empty", targetURL: ""},{name: "keyword form", targetURL: "user=postgres password=secret host=db.example.com port=5432 dbname=postgres sslmode=require"},{name: "missing port", targetURL: "postgres://postgres:[email protected]/postgres?sslmode=require"},- {name: "insecure TLS", targetURL: "postgres://postgres:[email protected]:5432/postgres?sslmode=disable"},- {name: "unauthenticated TLS", targetURL: "postgres://postgres:[email protected]:5432/postgres?sslmode=require"},+ {name: "unsupported TLS mode", targetURL: "postgres://postgres:[email protected]:5432/postgres?sslmode=prefer"},{name: "missing password", targetURL: "postgres://[email protected]:5432/postgres?sslmode=require"},{name: "passfile", targetURL: "postgres://postgres:[email protected]:5432/postgres?sslmode=require&passfile=/tmp/password"},} {@@ -38,6 +37,43 @@ func TestNewTargetRejectsUnsafeConfiguration(t *testing.T) {}}+func TestNewTargetBuildsRegistrationConfigWithoutTLS(t *testing.T) {+ for _, targetURL := range []string{+ "postgres://control:[email protected]:5432/postgres",+ "postgres://control:[email protected]:5432/postgres?sslmode=disable",+ } {+ target, err := NewTarget(targetURL)+ require.NoError(t, err)+ require.Nil(t, target.config.TLSConfig)++ config, err := target.InstanceConfig(Allocation{+ Database: "sample_database",+ Role: "sample_role",+ Password: "sample-password",+ })+ require.NoError(t, err)+ require.False(t, config.AdminDataSource.UseSsl)+ require.False(t, config.AdminDataSource.VerifyTlsCertificate)+ require.Empty(t, config.AdminDataSource.SslCa)+ }+}++func TestNewTargetBuildsRegistrationConfigWithTLSWithoutVerification(t *testing.T) {+ target, err := NewTarget("postgres://control:[email protected]:5432/postgres?sslmode=require")+ require.NoError(t, err)+ require.NotNil(t, target.config.TLSConfig)++ config, err := target.InstanceConfig(Allocation{+ Database: "sample_database",+ Role: "sample_role",+ Password: "sample-password",+ })+ require.NoError(t, err)+ require.True(t, config.AdminDataSource.UseSsl)+ require.False(t, config.AdminDataSource.VerifyTlsCertificate)+ require.Empty(t, config.AdminDataSource.SslCa)+}+func TestNewTargetBuildsRegistrationConfig(t *testing.T) {caPath := t.TempDir() + "/ca.pem"caPEM := `-----BEGIN CERTIFICATE-----@@ -213,19 +249,7 @@ func TestTargetProvisionAndRemove(t *testing.T) {require.NoError(t, err)}-func TestTargetValidateRejectsPublicAccess(t *testing.T) {- if testing.Short() {- t.Skip("skipping PostgreSQL testcontainer test in short mode")- }- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)- t.Cleanup(cancel)- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(context.Background()) })-- require.Error(t, newLocalTarget(t, container).Validate(ctx))-}--func TestTargetValidateAllowsCloudSQLAdminPublicAccess(t *testing.T) {+func TestTargetValidateAllowsPublicAccess(t *testing.T) {if testing.Short() {t.Skip("skipping PostgreSQL testcontainer test in short mode")}@@ -234,19 +258,10 @@ func TestTargetValidateAllowsCloudSQLAdminPublicAccess(t *testing.T) {container := testcontainer.GetTestPgContainer(ctx, t)t.Cleanup(func() { container.Close(context.Background()) })- admin := connectLocal(ctx, t, container, "postgres", "postgres", "root-password")- defer admin.Close(ctx)- require.NoError(t, prepareBaseline(ctx, admin))- _, err := admin.Exec(ctx, "CREATE DATABASE cloudsqladmin")- require.NoError(t, err)- t.Cleanup(func() {- _, _ = admin.Exec(context.Background(), "DROP DATABASE cloudsqladmin")- })-require.NoError(t, newLocalTarget(t, container).Validate(ctx))}-func TestTargetValidateRejectsUnexpectedPublicDatabase(t *testing.T) {+func TestTargetValidateAllowsExistingPublicDatabase(t *testing.T) {if testing.Short() {t.Skip("skipping PostgreSQL testcontainer test in short mode")}@@ -257,38 +272,14 @@ func TestTargetValidateRejectsUnexpectedPublicDatabase(t *testing.T) {admin := connectLocal(ctx, t, container, "postgres", "postgres", "root-password")defer admin.Close(ctx)- require.NoError(t, prepareBaseline(ctx, admin))- _, err := admin.Exec(ctx, "CREATE DATABASE unexpected_public_database")+ _, err := admin.Exec(ctx, "CREATE DATABASE existing_public_database")require.NoError(t, err)t.Cleanup(func() {- _, _ = admin.Exec(context.Background(), "DROP DATABASE unexpected_public_database")- })-- err = newLocalTarget(t, container).Validate(ctx)- require.Error(t, err)- require.True(t, isStaticTargetError(err))-}--func TestTargetValidateForCleanupAllowsUnexpectedPublicDatabase(t *testing.T) {- if testing.Short() {- t.Skip("skipping PostgreSQL testcontainer test in short mode")- }- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)- t.Cleanup(cancel)- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(context.Background()) })-- admin := connectLocal(ctx, t, container, "postgres", "postgres", "root-password")- defer admin.Close(ctx)- require.NoError(t, prepareBaseline(ctx, admin))- _, err := admin.Exec(ctx, "CREATE DATABASE unexpected_public_cleanup_database")- require.NoError(t, err)- t.Cleanup(func() {- _, _ = admin.Exec(context.Background(), "DROP DATABASE unexpected_public_cleanup_database")+ _, _ = admin.Exec(context.Background(), "DROP DATABASE existing_public_database")})target := newLocalTarget(t, container)- require.Error(t, target.Validate(ctx))+ require.NoError(t, target.Validate(ctx))require.NoError(t, target.ValidateForCleanup(ctx))}diff --git a/backend/generated-go/v1/actuator_service.pb.go b/backend/generated-go/v1/actuator_service.pb.goindex 977780a473..c6470af5c9 100644--- a/backend/generated-go/v1/actuator_service.pb.go+++ b/backend/generated-go/v1/actuator_service.pb.go@@ -98,6 +98,71 @@ func (*GetActuatorInfoRequest) Descriptor() ([]byte, []int) {return file_v1_actuator_service_proto_rawDescGZIP(), []int{1}}+// SampleInfo describes sample setup availability and provisioned resources.+type SampleInfo struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // Whether sample setup is currently available.+ Available bool `protobuf:"varint,1,opt,name=available,proto3" json:"available,omitempty"`+ // The provisioned sample instances.+ // Format: instances/{instance}+ Instances []string `protobuf:"bytes,2,rep,name=instances,proto3" json:"instances,omitempty"`+ // The time when the provisioned sample resources expire.+ ExpireTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SampleInfo) Reset() {+ *x = SampleInfo{}+ mi := &file_v1_actuator_service_proto_msgTypes[2]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SampleInfo) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SampleInfo) ProtoMessage() {}++func (x *SampleInfo) ProtoReflect() protoreflect.Message {+ mi := &file_v1_actuator_service_proto_msgTypes[2]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SampleInfo.ProtoReflect.Descriptor instead.+func (*SampleInfo) Descriptor() ([]byte, []int) {+ return file_v1_actuator_service_proto_rawDescGZIP(), []int{2}+}++func (x *SampleInfo) GetAvailable() bool {+ if x != nil {+ return x.Available+ }+ return false+}++func (x *SampleInfo) GetInstances() []string {+ if x != nil {+ return x.Instances+ }+ return nil+}++func (x *SampleInfo) GetExpireTime() *timestamppb.Timestamp {+ if x != nil {+ return x.ExpireTime+ }+ return nil+}+// System information and configuration for the Bytebase instance.// Actuator concept is similar to the Spring Boot Actuator.type ActuatorInfo struct {@@ -121,8 +186,6 @@ type ActuatorInfo struct {ActivatedInstanceCount int32 `protobuf:"varint,20,opt,name=activated_instance_count,json=activatedInstanceCount,proto3" json:"activated_instance_count,omitempty"`// The total number of database instances.TotalInstanceCount int32 `protobuf:"varint,21,opt,name=total_instance_count,json=totalInstanceCount,proto3" json:"total_instance_count,omitempty"`- // Whether sample data setup is enabled.- EnableSample bool `protobuf:"varint,22,opt,name=enable_sample,json=enableSample,proto3" json:"enable_sample,omitempty"`// Whether the external URL is set via command-line flag (and thus cannot be changed via UI).ExternalUrlFromFlag bool `protobuf:"varint,23,opt,name=external_url_from_flag,json=externalUrlFromFlag,proto3" json:"external_url_from_flag,omitempty"`// The number of active replicas (servers sharing the same database).@@ -134,13 +197,15 @@ type ActuatorInfo struct {UserCountInIam int32 `protobuf:"varint,27,opt,name=user_count_in_iam,json=userCountInIam,proto3" json:"user_count_in_iam,omitempty"`// The number of active VCS users seen in the active window.ActiveVcsUserCount int32 `protobuf:"varint,28,opt,name=active_vcs_user_count,json=activeVcsUserCount,proto3" json:"active_vcs_user_count,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // Sample setup availability and provisioned resources.+ Sample *SampleInfo `protobuf:"bytes,29,opt,name=sample,proto3" json:"sample,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *ActuatorInfo) Reset() {*x = ActuatorInfo{}- mi := &file_v1_actuator_service_proto_msgTypes[2]+ mi := &file_v1_actuator_service_proto_msgTypes[3]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -152,7 +217,7 @@ func (x *ActuatorInfo) String() string {func (*ActuatorInfo) ProtoMessage() {}func (x *ActuatorInfo) ProtoReflect() protoreflect.Message {- mi := &file_v1_actuator_service_proto_msgTypes[2]+ mi := &file_v1_actuator_service_proto_msgTypes[3]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -165,7 +230,7 @@ func (x *ActuatorInfo) ProtoReflect() protoreflect.Message {// Deprecated: Use ActuatorInfo.ProtoReflect.Descriptor instead.func (*ActuatorInfo) Descriptor() ([]byte, []int) {- return file_v1_actuator_service_proto_rawDescGZIP(), []int{2}+ return file_v1_actuator_service_proto_rawDescGZIP(), []int{3}}func (x *ActuatorInfo) GetVersion() string {@@ -231,13 +296,6 @@ func (x *ActuatorInfo) GetTotalInstanceCount() int32 {return 0}-func (x *ActuatorInfo) GetEnableSample() bool {- if x != nil {- return x.EnableSample- }- return false-}-func (x *ActuatorInfo) GetExternalUrlFromFlag() bool {if x != nil {return x.ExternalUrlFromFlag@@ -273,13 +331,27 @@ func (x *ActuatorInfo) GetActiveVcsUserCount() int32 {return 0}+func (x *ActuatorInfo) GetSample() *SampleInfo {+ if x != nil {+ return x.Sample+ }+ return nil+}+var File_v1_actuator_service_proto protoreflect.FileDescriptorconst file_v1_actuator_service_proto_rawDesc = "" +"\n" +- "\x19v1/actuator_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x13v1/annotation.proto\"\x14\n" ++ "\x19v1/actuator_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x13v1/annotation.proto\"\x14\n" +"\x12SetupSampleRequest\"\x18\n" +- "\x16GetActuatorInfoRequest\"\x80\x06\n" ++ "\x16GetActuatorInfoRequest\"\xae\x01\n" ++ "\n" ++ "SampleInfo\x12!\n" ++ "\tavailable\x18\x01 \x01(\bB\x03\xe0A\x03R\tavailable\x12;\n" ++ "\tinstances\x18\x02 \x03(\tB\x1d\xe0A\x03\xfaA\x17\n" ++ "\x15bytebase.com/InstanceR\tinstances\x12@\n" ++ "\vexpire_time\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\n" ++ "expireTime\"\x92\x06\n" +"\fActuatorInfo\x12\x1d\n" +"\aversion\x18\x01 \x01(\tB\x03\xe0A\x03R\aversion\x12\"\n" +"\n" +@@ -290,15 +362,15 @@ const file_v1_actuator_service_proto_rawDesc = "" +"\tworkspace\x18\r \x01(\tB\x03\xe0A\x03R\tworkspace\x124\n" +"\x13unlicensed_features\x18\x0f \x03(\tB\x03\xe0A\x03R\x12unlicensedFeatures\x12=\n" +"\x18activated_instance_count\x18\x14 \x01(\x05B\x03\xe0A\x03R\x16activatedInstanceCount\x125\n" +- "\x14total_instance_count\x18\x15 \x01(\x05B\x03\xe0A\x03R\x12totalInstanceCount\x12(\n" +- "\renable_sample\x18\x16 \x01(\bB\x03\xe0A\x03R\fenableSample\x128\n" ++ "\x14total_instance_count\x18\x15 \x01(\x05B\x03\xe0A\x03R\x12totalInstanceCount\x128\n" +"\x16external_url_from_flag\x18\x17 \x01(\bB\x03\xe0A\x03R\x13externalUrlFromFlag\x12(\n" +"\rreplica_count\x18\x18 \x01(\x05B\x03\xe0A\x03R\freplicaCount\x12,\n" +"\x0fdefault_project\x18\x1a \x01(\tB\x03\xe0A\x03R\x0edefaultProject\x12.\n" +"\x11user_count_in_iam\x18\x1b \x01(\x05B\x03\xe0A\x03R\x0euserCountInIam\x126\n" +- "\x15active_vcs_user_count\x18\x1c \x01(\x05B\x03\xe0A\x03R\x12activeVcsUserCountJ\x04\b\x03\x10\x04J\x04\b\x05\x10\bJ\x04\b\t\x10\n" ++ "\x15active_vcs_user_count\x18\x1c \x01(\x05B\x03\xe0A\x03R\x12activeVcsUserCount\x124\n" ++ "\x06sample\x18\x1d \x01(\v2\x17.bytebase.v1.SampleInfoB\x03\xe0A\x03R\x06sampleJ\x04\b\x03\x10\x04J\x04\b\x05\x10\bJ\x04\b\t\x10\n" +"J\x04\b\n" +- "\x10\vJ\x04\b\f\x10\rJ\x04\b\x0e\x10\x0fJ\x04\b\x10\x10\x14J\x04\b\x19\x10\x1a2\x97\x02\n" ++ "\x10\vJ\x04\b\f\x10\rJ\x04\b\x0e\x10\x0fJ\x04\b\x10\x10\x14J\x04\b\x16\x10\x17J\x04\b\x19\x10\x1a2\x97\x02\n" +"\x0fActuatorService\x12s\n" +"\x0fGetActuatorInfo\x12#.bytebase.v1.GetActuatorInfoRequest\x1a\x19.bytebase.v1.ActuatorInfo\" \xdaA\x00\xa0\xea0\x01\x82\xd3\xe4\x93\x02\x13\x12\x11/v1/actuator/info\x12\x8e\x01\n" +"\vSetupSample\x12\x1f.bytebase.v1.SetupSampleRequest\x1a\x16.google.protobuf.Empty\"F\x8a\xea0\x12bb.projects.create\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02\x1a\"\x18/v1/actuator:setupSampleB\xaa\x01\n" +@@ -316,25 +388,28 @@ func file_v1_actuator_service_proto_rawDescGZIP() []byte {return file_v1_actuator_service_proto_rawDescData}-var file_v1_actuator_service_proto_msgTypes = make([]protoimpl.MessageInfo, 3)+var file_v1_actuator_service_proto_msgTypes = make([]protoimpl.MessageInfo, 4)var file_v1_actuator_service_proto_goTypes = []any{(*SetupSampleRequest)(nil), // 0: bytebase.v1.SetupSampleRequest(*GetActuatorInfoRequest)(nil), // 1: bytebase.v1.GetActuatorInfoRequest- (*ActuatorInfo)(nil), // 2: bytebase.v1.ActuatorInfo- (*timestamppb.Timestamp)(nil), // 3: google.protobuf.Timestamp- (*emptypb.Empty)(nil), // 4: google.protobuf.Empty+ (*SampleInfo)(nil), // 2: bytebase.v1.SampleInfo+ (*ActuatorInfo)(nil), // 3: bytebase.v1.ActuatorInfo+ (*timestamppb.Timestamp)(nil), // 4: google.protobuf.Timestamp+ (*emptypb.Empty)(nil), // 5: google.protobuf.Empty}var file_v1_actuator_service_proto_depIdxs = []int32{- 3, // 0: bytebase.v1.ActuatorInfo.last_active_time:type_name -> google.protobuf.Timestamp- 1, // 1: bytebase.v1.ActuatorService.GetActuatorInfo:input_type -> bytebase.v1.GetActuatorInfoRequest- 0, // 2: bytebase.v1.ActuatorService.SetupSample:input_type -> bytebase.v1.SetupSampleRequest- 2, // 3: bytebase.v1.ActuatorService.GetActuatorInfo:output_type -> bytebase.v1.ActuatorInfo- 4, // 4: bytebase.v1.ActuatorService.SetupSample:output_type -> google.protobuf.Empty- 3, // [3:5] is the sub-list for method output_type- 1, // [1:3] is the sub-list for method input_type- 1, // [1:1] is the sub-list for extension type_name- 1, // [1:1] is the sub-list for extension extendee- 0, // [0:1] is the sub-list for field type_name+ 4, // 0: bytebase.v1.SampleInfo.expire_time:type_name -> google.protobuf.Timestamp+ 4, // 1: bytebase.v1.ActuatorInfo.last_active_time:type_name -> google.protobuf.Timestamp+ 2, // 2: bytebase.v1.ActuatorInfo.sample:type_name -> bytebase.v1.SampleInfo+ 1, // 3: bytebase.v1.ActuatorService.GetActuatorInfo:input_type -> bytebase.v1.GetActuatorInfoRequest+ 0, // 4: bytebase.v1.ActuatorService.SetupSample:input_type -> bytebase.v1.SetupSampleRequest+ 3, // 5: bytebase.v1.ActuatorService.GetActuatorInfo:output_type -> bytebase.v1.ActuatorInfo+ 5, // 6: bytebase.v1.ActuatorService.SetupSample:output_type -> google.protobuf.Empty+ 5, // [5:7] is the sub-list for method output_type+ 3, // [3:5] is the sub-list for method input_type+ 3, // [3:3] is the sub-list for extension type_name+ 3, // [3:3] is the sub-list for extension extendee+ 0, // [0:3] is the sub-list for field type_name}func init() { file_v1_actuator_service_proto_init() }@@ -349,7 +424,7 @@ func file_v1_actuator_service_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_actuator_service_proto_rawDesc), len(file_v1_actuator_service_proto_rawDesc)),NumEnums: 0,- NumMessages: 3,+ NumMessages: 4,NumExtensions: 0,NumServices: 1,},diff --git a/backend/generated-go/v1/actuator_service_equal.pb.go b/backend/generated-go/v1/actuator_service_equal.pb.goindex 5b34ed1a4f..c3476243ec 100644--- a/backend/generated-go/v1/actuator_service_equal.pb.go+++ b/backend/generated-go/v1/actuator_service_equal.pb.go@@ -23,6 +23,30 @@ func (x *GetActuatorInfoRequest) Equal(y *GetActuatorInfoRequest) bool {return true}+func (x *SampleInfo) Equal(y *SampleInfo) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Available != y.Available {+ return false+ }+ if len(x.Instances) != len(y.Instances) {+ return false+ }+ for i := 0; i < len(x.Instances); i++ {+ if x.Instances[i] != y.Instances[i] {+ return false+ }+ }+ if p, q := x.ExpireTime, y.ExpireTime; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {+ return false+ }+ return true+}+func (x *ActuatorInfo) Equal(y *ActuatorInfo) bool {if x == y {return true@@ -62,9 +86,6 @@ func (x *ActuatorInfo) Equal(y *ActuatorInfo) bool {if x.TotalInstanceCount != y.TotalInstanceCount {return false}- if x.EnableSample != y.EnableSample {- return false- }if x.ExternalUrlFromFlag != y.ExternalUrlFromFlag {return false}@@ -80,5 +101,8 @@ func (x *ActuatorInfo) Equal(y *ActuatorInfo) bool {if x.ActiveVcsUserCount != y.ActiveVcsUserCount {return false}+ if !x.Sample.Equal(y.Sample) {+ return false+ }return true}diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.goindex d8dc031714..ce1d247062 100644--- a/backend/server/grpc_routes.go+++ b/backend/server/grpc_routes.go@@ -94,7 +94,7 @@ func configureGrpcRouters()aiService := apiv1.NewAIService(stores)accessGrantService := apiv1.NewAccessGrantService(stores, licenseService, webhookManager, bus)- actuatorService := apiv1.NewActuatorService(stores, profile, schemaSyncer, licenseService, sampleInstanceManager)+ actuatorService := apiv1.NewActuatorService(stores, profile, schemaSyncer, licenseService, sampleInstanceManager, sampleProjectManager)auditLogService := apiv1.NewAuditLogService(stores, licenseService)authService := apiv1.NewAuthService(stores, secret, licenseService, profile, iamManager)celService := apiv1.NewCelService()diff --git a/backend/server/sample_project_instance_test.go b/backend/server/sample_project_instance_test.gonew file mode 100644index 0000000000..0ba6ca43fa--- /dev/null+++ b/backend/server/sample_project_instance_test.go@@ -0,0 +1,60 @@+package server++import (+ "bytes"+ "context"+ "log/slog"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestConfigureSampleProjectManagerDisablesInvalidTarget(t *testing.T) {+ var output bytes.Buffer+ originalLogger := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&output, nil)))+ t.Cleanup(func() { slog.SetDefault(originalLogger) })++ manager := configureSampleProjectManager(+ context.Background(),+ "postgresql://control:[email protected]:5432/postgres?sslmode=prefer",+ nil,+ nil,+ "replica",+ )++ require.Nil(t, manager)+ require.Contains(t, output.String(), "Sample Project Instance is disabled")+ require.NotContains(t, output.String(), "secret")+}++func TestConfigureSampleProjectManagerIgnoresEmptyTarget(t *testing.T) {+ var output bytes.Buffer+ originalLogger := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&output, nil)))+ t.Cleanup(func() { slog.SetDefault(originalLogger) })++ manager := configureSampleProjectManager(context.Background(), "", nil, nil, "replica")++ require.Nil(t, manager)+ require.Empty(t, output.String())+}++func TestConfigureSampleProjectManagerRetainsTemporarilyUnavailableTarget(t *testing.T) {+ var output bytes.Buffer+ originalLogger := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&output, nil)))+ t.Cleanup(func() { slog.SetDefault(originalLogger) })++ manager := configureSampleProjectManager(+ context.Background(),+ "postgresql://control:[email protected]:1/postgres",+ nil,+ nil,+ "replica",+ )++ require.NotNil(t, manager)+ require.Contains(t, output.String(), "temporarily unavailable")+ require.NotContains(t, output.String(), "secret")+}diff --git a/backend/server/server.go b/backend/server/server.goindex 2765f8193f..38d012813d 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -224,13 +224,16 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {}s.schemaSyncer = schemasync.NewSyncer(stores, s.dbFactory, s.licenseService, productMetrics)if profile.SaaS {- s.sampleProjectManager = sampleprojectinstance.NewManagerFromURL(- stores,+ s.sampleProjectManager = configureSampleProjectManager(+ ctx,profile.SampleProjectInstancePgURL,+ stores,s.schemaSyncer,- sampleprojectinstance.ManagerOptions{ReplicaID: profile.ReplicaID},+ profile.ReplicaID,)- s.sampleProjectRunner = sampleprojectinstancerunner.NewRunner(s.sampleProjectManager)+ if s.sampleProjectManager != nil {+ s.sampleProjectRunner = sampleprojectinstancerunner.NewRunner(s.sampleProjectManager)+ }}s.approvalRunner = review.NewRunner(stores, s.bus, s.webhookManager, s.licenseService)@@ -270,6 +273,32 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {return s, nil}+func configureSampleProjectManager(+ ctx context.Context,+ targetURL string,+ stores *store.Store,+ syncer *schemasync.Syncer,+ replicaID string,+) *sampleprojectinstance.Manager {+ if targetURL == "" {+ return nil+ }+ manager, err := sampleprojectinstance.NewManagerFromURL(+ stores,+ targetURL,+ syncer,+ sampleprojectinstance.ManagerOptions{ReplicaID: replicaID},+ )+ if err != nil {+ slog.Warn("invalid SAMPLE_PROJECT_INSTANCE_PG_URL; Sample Project Instance is disabled", log.BBError(err))+ return nil+ }+ if err := manager.ValidateTarget(ctx); err != nil {+ slog.Warn("Sample Project Instance target is temporarily unavailable", log.BBError(err))+ }+ return manager+}+// Run will run the server.func (s *Server) Run(ctx context.Context, port int) error {ctx, cancel := context.WithCancel(ctx)diff --git a/docs/operations/sample-project-instance.md b/docs/operations/sample-project-instance.mdindex 986849d693..3bb162df0d 100644--- a/docs/operations/sample-project-instance.md+++ b/docs/operations/sample-project-instance.md@@ -1,20 +1,19 @@# Operate Bytebase Cloud Sample Project Instances-Sample Project Instances are SaaS-only temporary-evaluation aggregates. Each aggregate has one Bytebase Project Instance and one dedicated database and login role on the shared, dedicated Cloud SQL PostgreSQL instance. A Workspace receives one lifetime entitlement. Do not provide reset tooling or expose a separate user-visible expired state.+Sample Project Instances are SaaS-only temporary-evaluation aggregates. Each aggregate has one Bytebase Project Instance and one dedicated database and login role on the configured PostgreSQL target. A Workspace receives one lifetime entitlement. Do not provide reset tooling or expose a separate user-visible expired state.## Configure the target-Set `SAMPLE_PROJECT_INSTANCE_PG_URL` on every SaaS replica to the same direct PostgreSQL password URL for the dedicated Cloud SQL instance. The URL must use `sslmode=verify-full`; `sslmode=require` is rejected because it encrypts the connection without authenticating the server.+Set `SAMPLE_PROJECT_INSTANCE_PG_URL` on every SaaS replica to the same direct PostgreSQL password URL. TLS is optional: omit `sslmode` or use `sslmode=disable` for a trusted local connection, use `sslmode=require` for encryption without server identity verification, or use `sslmode=verify-full` for encryption with server identity verification.- Supply the password in the URL. File indirection and hot credential rotation are not supported for this setting.-- Optionally supply `sslrootcert` pointing to a mounted PEM CA bundle. Bytebase resolves that PEM while loading the target configuration and copies it into the generated sample data source so later connections use the same trust anchor.-- Use a hostname in the URL that resolves to the Cloud SQL instance and matches the server certificate. `sslmode=verify-full` requires both CA trust and hostname verification; ensure every SaaS replica has DNS access to that hostname.+- With `sslmode=verify-full`, optionally supply `sslrootcert` pointing to a mounted PEM CA bundle. Bytebase resolves that PEM while loading the target configuration and copies it into the generated sample data source so later connections use the same trust anchor.+- With `sslmode=verify-full`, use a hostname in the URL that resolves to the PostgreSQL instance and matches the server certificate. This mode requires both CA trust and hostname verification; ensure every SaaS replica has DNS access to that hostname.- Keep the value out of source control, shell history, diagnostic dumps, and application logs. Use the deployment secret mechanism and rotate by replacing the deployment configuration uniformly across replicas.- The configured control-plane role requires `CREATEDB`, `CREATEROLE`, and membership in `pg_signal_backend`.-- Maintain the isolation baseline: revoke `PUBLIC` access from `postgres` and `template1`, deny connections to `template0`, and do not leave any connectable database with `PUBLIC` access except Cloud SQL's exact provider-managed `cloudsqladmin` database.-- Bytebase must not modify `cloudsqladmin`: Cloud SQL documents its corresponding system user as non-modifiable and excludes the database from `pg_dumpall` exports because customer tooling cannot access it. All customer-managed databases remain hardened. See [Cloud SQL SSL/TLS configuration](https://cloud.google.com/sql/docs/postgres/configure-ssl-instance), [Cloud SQL system users](https://cloud.google.com/sql/docs/postgres/users), and [Cloud SQL dump exports](https://cloud.google.com/sql/docs/postgres/import-export/import-export-dmp).+- The target may contain existing databases with `PUBLIC` access. Bytebase does not grant generated sample roles privileges on those databases, but PostgreSQL's existing grants still apply. Use a dedicated target or revoke `PUBLIC` access when stronger cross-database isolation is required.-An absent or invalid target configuration must not block server startup. Preparation is unavailable until configuration and the full privilege and isolation baseline validation succeed. Cleanup uses a separate 10-second connectivity and capability preflight so a partial database cannot block its own cleanup by violating the provisioning baseline. Startup and hourly cleanup still report structured, redacted errors for outstanding lifecycle records.+An absent or syntactically invalid target configuration must not block server startup and leaves preparation disabled. A syntactically valid target remains configured when connectivity or capability validation fails. Bytebase logs the transient failure, rechecks target availability through a one-minute cache when serving actuator information, and validates again before every preparation, so repairing the target does not require a service restart. Cleanup uses a separate 10-second connectivity and capability preflight that does not require `CREATEDB`. Startup and hourly cleanup still report structured, redacted errors for outstanding lifecycle records.## Provisioning and readinessdiff --git a/frontend/src/components/SampleExpirationAlert.tsx b/frontend/src/components/SampleExpirationAlert.tsxnew file mode 100644index 0000000000..7d647f32f9--- /dev/null+++ b/frontend/src/components/SampleExpirationAlert.tsx@@ -0,0 +1,39 @@+import { useTranslation } from "react-i18next";+import { Alert } from "@/components/ui/alert";+import { useAppStore } from "@/stores/app";+import { getTimeForPbTimestampProtoEs } from "@/types";+import { extractInstanceResourceName, formatAbsoluteDateTime } from "@/utils";++const DAY_MS = 24 * 60 * 60 * 1000;++type SampleExpirationAlertProps = Readonly<{+ instanceName: string;+}>;++export function SampleExpirationAlert({+ instanceName,+}: SampleExpirationAlertProps) {+ const { t } = useTranslation();+ const sample = useAppStore((state) => state.serverInfo?.sample);+ const expireTime = sample?.expireTime;+ const canonicalInstanceName = `instances/${extractInstanceResourceName(instanceName)}`;++ if (!expireTime || !sample.instances.includes(canonicalInstanceName)) {+ return null;+ }++ const expireTimeMs = getTimeForPbTimestampProtoEs(expireTime);+ const formattedExpireTime = formatAbsoluteDateTime(expireTimeMs);+ const remainingMs = expireTimeMs - Date.now();+ const description =+ remainingMs > 0+ ? t("instance.sample-expiration-future", {+ count: Math.ceil(remainingMs / DAY_MS),+ time: formattedExpireTime,+ })+ : t("instance.sample-expiration-expired", {+ time: formattedExpireTime,+ });++ return <Alert variant="warning" description={description} />;+}diff --git a/frontend/src/components/WorkspaceSetupGuide.test.tsx b/frontend/src/components/WorkspaceSetupGuide.test.tsxindex 339ea78b57..772bc46328 100644--- a/frontend/src/components/WorkspaceSetupGuide.test.tsx+++ b/frontend/src/components/WorkspaceSetupGuide.test.tsx@@ -301,6 +301,34 @@ describe("WorkspaceSetupGuide", () => {});});+ it("uses compact controls below 2xl and prominent controls at 2xl", async () => {+ await render(<WorkspaceSetupGuide />);++ expect(container.firstElementChild?.getAttribute("class")).toContain(+ "py-2"+ );+ expect(container.firstElementChild?.getAttribute("class")).toContain(+ "2xl:py-4"+ );+ const projectStep = container.querySelector(+ "[data-testid='setup-step-hasProject']"+ );+ expect(projectStep?.getAttribute("class")).toContain("text-sm");+ expect(projectStep?.getAttribute("class")).toContain("2xl:text-base");+ expect(projectStep?.getAttribute("class")).toContain("py-1");+ expect(projectStep?.getAttribute("class")).toContain("2xl:py-2");+ expect(+ container+ .querySelector("[data-testid='dismiss-guide']")+ ?.getAttribute("class")+ ).toContain("h-7");+ expect(+ container+ .querySelector("[data-testid='dismiss-guide']")+ ?.getAttribute("class")+ ).toContain("2xl:h-9");+ });+it("hides when the workspace has more than one member", async () => {mocks.workspacePolicy = {bindings: [@@ -681,15 +709,31 @@ describe("WorkspaceSetupGuide", () => {expect(container.querySelector("[data-testid='active-action']")).toBeNull();});- it("does not highlight the create project step on project database pages", async () => {+ it("highlights the active query step on project database pages", async () => {mocks.currentRoute = { name: "workspace.project.database" };mocks.fetchProjectList.mockResolvedValue({projects: [{ name: "projects/project-a" }],nextPageToken: "",});+ mocks.fetchInstanceList.mockImplementation(+ async (params?: { parent?: string }) => ({+ instances:+ params?.parent === "projects/project-a"+ ? [{ name: "projects/project-a/instances/instance-a" }]+ : [],+ nextPageToken: "",+ })+ );+ mocks.fetchDatabases.mockResolvedValue({+ databases: [{ name: "instances/instance-a/databases/db-a" }],+ nextPageToken: "",+ });await render(<WorkspaceSetupGuide />);+ expect(mocks.fetchInstanceList).toHaveBeenCalledWith(+ expect.objectContaining({ parent: "projects/project-a" })+ );expect(container.querySelector("[data-testid='setup-step-hasProject']")@@ -700,8 +744,14 @@ describe("WorkspaceSetupGuide", () => {.querySelector("[data-testid='setup-step-hasInstance']")?.getAttribute("class")).not.toContain("bg-accent/10");-- expect(container.querySelector("[data-testid='active-action']")).toBeNull();+ expect(+ container+ .querySelector("[data-testid='setup-step-hasFirstQuery']")+ ?.getAttribute("class")+ ).toContain("bg-accent/10");+ expect(+ container.querySelector("[data-testid='active-action']")+ ).not.toBeNull();});it("does not highlight the next setup step on unrelated pages", async () => {@@ -848,6 +898,9 @@ describe("WorkspaceSetupGuide", () => {"[data-testid='secondary-action']");expect(secondaryAction).not.toBeNull();+ expect(secondaryAction?.getAttribute("class")).toContain(+ "2xl:inline-flex"+ );expect(secondaryAction!.compareDocumentPosition(actionLink as Node) &Node.DOCUMENT_POSITION_FOLLOWINGdiff --git a/frontend/src/components/WorkspaceSetupGuide.tsx b/frontend/src/components/WorkspaceSetupGuide.tsxindex 055d760187..aa18f9e348 100644--- a/frontend/src/components/WorkspaceSetupGuide.tsx+++ b/frontend/src/components/WorkspaceSetupGuide.tsx@@ -145,10 +145,26 @@ export function WorkspaceSetupGuide() {)?.name ?? ""): "";const hasProject = !!projectName;- const hasInstance =+ let hasInstance =instanceCacheSize > 0 ||(instanceResult.status === "fulfilled" &&instanceResult.value.instances.length > 0);+ if (+ !hasInstance &&+ projectName &&+ hasWorkspacePermissionV2("bb.instances.list")+ ) {+ try {+ const projectInstanceResult = await store.fetchInstanceList({+ parent: projectName,+ pageSize: 1,+ silent: true,+ });+ hasInstance = projectInstanceResult.instances.length > 0;+ } catch {+ hasInstance = false;+ }+ }let databaseName = "";let hasWorkspaceDatabase = databaseCacheSize > 0;let hasFirstQuery = false;@@ -307,7 +323,12 @@ export function WorkspaceSetupGuide() {const routeMatchedStep = steps.find((step) => step.matchesRoute?.(currentRoute.name) ?? false);- const highlightedStep = selectedStep ?? routeMatchedStep;+ const highlightedStep =+ selectedStep ??+ routeMatchedStep ??+ (isRouteInside(currentRoute.name, PROJECT_V1_ROUTE_DATABASES)+ ? activeStep+ : undefined);const actionStep =highlightedStep && !highlightedStep.done ? highlightedStep : activeStep;@@ -341,21 +362,21 @@ export function WorkspaceSetupGuide() {}return (- <div className="flex w-full shrink-0 items-center gap-x-3 border-t border-block-border bg-white px-4 py-3 shadow-[0_-2px_10px_rgba(0,0,0,0.04)]">- <div className="flex min-w-0 flex-1 items-center gap-x-4 overflow-hidden">+ <div className="flex w-full shrink-0 items-center gap-x-2 border-t border-block-border bg-white px-3 py-2 shadow-[0_-2px_10px_rgba(0,0,0,0.04)] 2xl:gap-x-4 2xl:px-5 2xl:py-4">+ <div className="flex min-w-0 flex-1 items-center gap-x-2 overflow-hidden 2xl:gap-x-5"><div className="flex shrink-0 items-baseline gap-x-2">- <div className="shrink-0 text-sm font-medium text-main">+ <div className="shrink-0 text-sm font-semibold text-main 2xl:text-base">{t("workspace-setup-guide.self")}</div></div>- <div className="flex min-w-0 flex-1 items-center gap-x-2 overflow-x-auto pr-2">+ <div className="flex min-w-0 flex-1 items-center gap-x-2 overflow-x-auto pr-1 2xl:gap-x-3 2xl:pr-2">{steps.map((step, index) => {const isHighlighted = step.key === highlightedStep?.key;const tooltipContent = step.disabled? t("workspace-setup-guide.previous-step-required"): step.description;const className = cn(- "inline-flex items-center gap-x-1.5 rounded-sm px-2 py-1 text-sm whitespace-nowrap",+ "inline-flex items-center gap-x-1 rounded-sm px-2 py-1 text-sm whitespace-nowrap 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base",isHighlighted? "bg-accent/10 text-accent": step.done@@ -364,7 +385,10 @@ export function WorkspaceSetupGuide() {);return (- <div key={step.key} className="inline-flex items-center gap-x-2">+ <div+ key={step.key}+ className="inline-flex items-center gap-x-2 2xl:gap-x-3"+ ><Tooltip content={tooltipContent}><Buttontype="button"@@ -372,21 +396,23 @@ export function WorkspaceSetupGuide() {data-testid={`setup-step-${step.key}`}className={cn(className,- "h-auto justify-start py-1 font-normal"+ "h-auto justify-start py-1 font-medium 2xl:py-2")}disabled={step.disabled}onClick={() => onSelectStep(step)}>{step.done ? (- <CheckCircle className="h-4 w-4 text-success" />+ <CheckCircle className="size-4 text-success 2xl:size-5" />) : (- <Circle className="h-4 w-4" />+ <Circle className="size-4 2xl:size-5" />)}<span>{step.label}</span></Button></Tooltip>{index < steps.length - 1 && (- <span className="text-control-light">›</span>+ <span className="text-sm text-control-light 2xl:text-base">+ ›+ </span>)}</div>);@@ -401,8 +427,8 @@ export function WorkspaceSetupGuide() {type="button"data-testid="secondary-action"appearance="secondary"- size="sm"- className="hidden xl:inline-flex"+ size="md"+ className="hidden 2xl:inline-flex"onClick={handleCreateFirstChange}>{t("workspace-setup-guide.actions.change")}@@ -413,6 +439,7 @@ export function WorkspaceSetupGuide() {data-testid="active-action"database={sqlEditorDatabase}size="sm"+ className="2xl:h-9 2xl:gap-1.5 2xl:px-3 2xl:text-sm 2xl:leading-5"label={t("workspace-setup-guide.actions.query")}/>)}@@ -422,10 +449,10 @@ export function WorkspaceSetupGuide() {aria-label={t("workspace-setup-guide.dismiss")}appearance="secondary"size="sm"- className="text-control-light hover:text-control"+ className="text-control-light hover:text-control 2xl:h-9 2xl:gap-1.5 2xl:px-3 2xl:text-sm 2xl:leading-5"onClick={handleDismiss}>- <X className="h-4 w-4" />+ <X className="size-4 2xl:size-5" /></Button></div></div>diff --git a/frontend/src/components/header/ProfileMenuTrigger.test.tsx b/frontend/src/components/header/ProfileMenuTrigger.test.tsxindex 64d1fa7311..9a05f65668 100644--- a/frontend/src/components/header/ProfileMenuTrigger.test.tsx+++ b/frontend/src/components/header/ProfileMenuTrigger.test.tsx@@ -134,7 +134,7 @@ vi.mock("@/hooks/useAppState", () => ({email: "[email protected]",}),useServerInfo: () => ({- enableSample: true,+ sample: { available: true },userCountInIam: 1,}),useSubscription: () => ({diff --git a/frontend/src/components/header/ProfileMenuTrigger.tsx b/frontend/src/components/header/ProfileMenuTrigger.tsxindex c1b637b6bd..b7a1110382 100644--- a/frontend/src/components/header/ProfileMenuTrigger.tsx+++ b/frontend/src/components/header/ProfileMenuTrigger.tsx@@ -73,7 +73,7 @@ export function ProfileMenuTrigger({];const quickStartEnabled =!hideQuickStart &&- Boolean(serverInfo?.enableSample) &&+ Boolean(serverInfo?.sample?.available) &&(serverInfo?.userCountInIam ?? 0) <= 1;const customLogo = workspace?.logo ?? "";const [open, setOpen] = useState(false);diff --git a/frontend/src/components/instance/CreateInstanceView.test.tsx b/frontend/src/components/instance/CreateInstanceView.test.tsxindex 14238618f8..bf4c6c575b 100644--- a/frontend/src/components/instance/CreateInstanceView.test.tsx+++ b/frontend/src/components/instance/CreateInstanceView.test.tsx@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({prepareSampleProjectInstance: vi.fn(),pushNotification: vi.fn(),isSaaSMode: false,+ sampleAvailable: true,instanceCountLimit: 10,activatedInstanceCount: 0,providerProps: undefined as Record<string, unknown> | undefined,@@ -61,6 +62,7 @@ vi.mock("@/stores/app", () => ({<T,>(selector: (state: Record<string, unknown>) => T) =>selector({isSaaSMode: () => mocks.isSaaSMode,+ serverInfo: { sample: { available: mocks.sampleAvailable } },prepareSampleProjectInstance: mocks.prepareSampleProjectInstance,}),{@@ -119,6 +121,7 @@ vi.mock("@/components/instance", () => ({beforeEach(async () => {vi.clearAllMocks();mocks.isSaaSMode = false;+ mocks.sampleAvailable = true;mocks.instanceCountLimit = 10;mocks.activatedInstanceCount = 0;mocks.prepareSampleProjectInstance.mockResolvedValue({@@ -342,6 +345,29 @@ describe("CreateInstanceView", () => {});});+ test("hides sample instance creation when the target is unavailable", () => {+ mocks.isSaaSMode = true;+ mocks.sampleAvailable = false;+ const container = document.createElement("div");+ const root = createRoot(container);++ act(() => {+ root.render(+ <CreateInstanceView+ parent="projects/demo"+ onDismiss={mocks.onDismiss}+ onCreated={mocks.onCreated}+ />+ );+ });++ expect(container.textContent).not.toContain("Use sample instance");++ act(() => {+ root.unmount();+ });+ });+test("disables the sample action while preparation is running", async () => {mocks.isSaaSMode = true;let resolvePreparation: (instance: { name: string }) => void;diff --git a/frontend/src/components/instance/CreateInstanceView.tsx b/frontend/src/components/instance/CreateInstanceView.tsxindex e3032a62a7..34a888b4a2 100644--- a/frontend/src/components/instance/CreateInstanceView.tsx+++ b/frontend/src/components/instance/CreateInstanceView.tsx@@ -40,8 +40,11 @@ export function CreateInstanceView({}: CreateInstanceViewProps) {const { t } = useTranslation();const isSaaSMode = useAppStore((state) => state.isSaaSMode());+ const sampleAvailable = useAppStore(+ (state) => state.serverInfo?.sample?.available ?? false+ );const canPrepareSampleProjectInstance =- isSaaSMode && !!parent && isValidProjectName(parent);+ isSaaSMode && sampleAvailable && !!parent && isValidProjectName(parent);// Check instance limit on mountuseEffect(() => {@@ -199,7 +202,7 @@ function CreateInstanceFormInner({<div className="min-w-0 min-h-0 flex-1 flex flex-col">{/* Body */}<div className="flex-1 min-h-0 overflow-auto">- <div className="px-4 py-4 sm:px-6">+ <div className="px-4 py-4 sm:px-6 gap-y-4 flex flex-col">{canPrepareSampleProjectInstance && (<Alerttitle={t("instance.sample-project-instance-title")}diff --git a/frontend/src/components/instance/InstanceDetailView.test.tsx b/frontend/src/components/instance/InstanceDetailView.test.tsxindex 40ff0d5967..151cc0350f 100644--- a/frontend/src/components/instance/InstanceDetailView.test.tsx+++ b/frontend/src/components/instance/InstanceDetailView.test.tsx@@ -48,6 +48,13 @@ const mocks = vi.hoisted(() => ({syncProps: undefined as Record<string, unknown> | undefined,providerProps: undefined as Record<string, unknown> | undefined,batchProps: undefined as Record<string, unknown> | undefined,+ serverInfo: { defaultProject: "projects/default" } as {+ defaultProject: string;+ sample?: {+ instances: string[];+ expireTime?: { seconds: bigint; nanos: number };+ };+ },}));vi.mock("react-router", () => ({@@ -91,7 +98,7 @@ vi.mock("@/stores/app", () => {removeDatabaseMetadataCache: mocks.removeDatabaseMetadataCache,instancesByName: { [mocks.instance.name]: mocks.instance },environmentList: [],- serverInfo: { defaultProject: "projects/default" },+ serverInfo: mocks.serverInfo,});const useAppStore = (selector?: (s: ReturnType<typeof getState>) => unknown) =>selector ? selector(getState()) : getState();@@ -118,6 +125,7 @@ vi.mock("@/utils", () => ({},extractInstanceResourceName: (name: string) => name.split("/").pop() ?? "",extractProjectResourceName: (name: string) => name.split("/").pop() ?? "",+ formatAbsoluteDateTime: () => "Aug 30, 2026, 1:30:00 PM GMT+8",getDefaultPagination: () => 10,hasWorkspacePermissionV2: () => true,instanceV1Name: (instance: Instance) => instance.title,@@ -267,6 +275,7 @@ beforeEach(() => {mocks.syncProps = undefined;mocks.providerProps = undefined;mocks.batchProps = undefined;+ mocks.serverInfo = { defaultProject: "projects/default" };mocks.fetchProjectList.mockImplementation(async () => ({projects: mocks.projects,nextPageToken: "",@@ -284,6 +293,50 @@ afterEach(() => {});describe("InstanceDetailView", () => {+ it("shows the sample expiration warning for a sample instance", async () => {+ mocks.serverInfo = {+ defaultProject: "projects/default",+ sample: {+ instances: ["instances/prod"],+ expireTime: {+ seconds: BigInt(Math.floor(Date.now() / 1000) + 7 * 24 * 60 * 60),+ nanos: 0,+ },+ },+ };+ mocks.instance = {+ ...mocks.instance,+ name: "projects/app/instances/prod",+ } as Instance;++ await render(+ <InstanceDetailView instanceName="projects/app/instances/prod" />+ );++ expect(container.textContent).toContain(+ "instance.sample-expiration-future"+ );+ });++ it("shows the pending-removal warning for an expired sample instance", async () => {+ mocks.serverInfo = {+ defaultProject: "projects/default",+ sample: {+ instances: ["instances/prod"],+ expireTime: {+ seconds: BigInt(Math.floor(Date.now() / 1000) - 60),+ nanos: 0,+ },+ },+ };++ await render(<InstanceDetailView instanceName="instances/prod" />);++ expect(container.textContent).toContain(+ "instance.sample-expiration-expired"+ );+ });+it("does not show the post-sync transfer action when there is no user project", async () => {await render(<InstanceDetailView instanceName="instances/prod" />);diff --git a/frontend/src/components/instance/InstanceDetailView.tsx b/frontend/src/components/instance/InstanceDetailView.tsxindex 1abf3b0bc5..a885496bc2 100644--- a/frontend/src/components/instance/InstanceDetailView.tsx+++ b/frontend/src/components/instance/InstanceDetailView.tsx@@ -32,6 +32,7 @@ import {InstanceSyncButton,useInstanceFormContext,} from "@/components/instance";+import { SampleExpirationAlert } from "@/components/SampleExpirationAlert";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";@@ -570,6 +571,8 @@ export function InstanceDetailView({</div>)}+ <SampleExpirationAlert instanceName={instanceName} />+{/* No environment warning */}{!instance.environment && (<Alertdiff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 18a23ac12d..2a90dbf8d0 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1217,6 +1217,9 @@"role-arn": "Role ARN","role-arn-description": "IAM role to assume for cross-account access. Leave empty for same-account access.","role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "sample-expiration-expired": "The sample instance expired at {{time}} and will be removed shortly.",+ "sample-expiration-future_one": "The sample instance will be removed in {{count}} day, at {{time}}.",+ "sample-expiration-future_other": "The sample instance will be removed in {{count}} days, at {{time}}.","sample-project-instance-description": "Use a Sample Project Instance to explore Bytebase with a ready-to-use database for 7 days.","sample-project-instance-title": "Try a Sample Project Instance","scan-interval": {@@ -2696,6 +2699,7 @@"display-name": "Your name","display-name-placeholder": "Enter your name","email": "Email",+ "enable-sample-databases": "Enable sample databases","password": "Password","password-confirm": "Password Confirm","password-confirm-placeholder": "Confirm new password",@@ -2706,6 +2710,7 @@"setup-failed": "Failed to update profile.","setup-first-project": "Setup 1st project","setup-skip": "I'll do this later",+ "setup-submit": "Setup my workspace","setup-success": "Profile updated.","setup-title": "Welcome! Set up your workspace","workspace-name": "Workspace name",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex e080c446a1..445b2d9f9a 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1217,6 +1217,9 @@"role-arn": "ARN del rol","role-arn-description": "Rol IAM para asumir en acceso entre cuentas. Dejar vacío para acceso en la misma cuenta.","role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "sample-expiration-expired": "La instancia de muestra venció el {{time}} y se eliminará en breve.",+ "sample-expiration-future_one": "La instancia de muestra se eliminará en {{count}} día, a las {{time}}.",+ "sample-expiration-future_other": "La instancia de muestra se eliminará en {{count}} días, a las {{time}}.","sample-project-instance-description": "Use una instancia de proyecto de muestra para explorar Bytebase con una base de datos lista para usar durante 7 días.","sample-project-instance-title": "Pruebe una instancia de proyecto de muestra","scan-interval": {@@ -2696,6 +2699,7 @@"display-name": "Su nombre","display-name-placeholder": "Ingrese su nombre","email": "Correo electrónico",+ "enable-sample-databases": "Habilitar bases de datos de ejemplo","password": "Contraseña","password-confirm": "Confirmar contraseña","password-confirm-placeholder": "Confirmar nueva contraseña",@@ -2706,6 +2710,7 @@"setup-failed": "Error al actualizar el perfil.","setup-first-project": "Configurar el primer proyecto","setup-skip": "Lo haré después",+ "setup-submit": "Configurar mi espacio de trabajo","setup-success": "Perfil actualizado.","setup-title": "¡Bienvenido! Configure su espacio de trabajo","workspace-name": "Nombre del espacio de trabajo",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 6d591dda06..1d99934aef 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1217,6 +1217,9 @@"role-arn": "ロール ARN","role-arn-description": "クロスアカウントアクセス用の IAM ロール。同一アカウントアクセスの場合は空のままにしてください。","role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "sample-expiration-expired": "サンプルインスタンスは {{time}} に期限切れとなり、まもなく削除されます。",+ "sample-expiration-future_one": "サンプルインスタンスは {{count}} 日後の {{time}} に削除されます。",+ "sample-expiration-future_other": "サンプルインスタンスは {{count}} 日後の {{time}} に削除されます。","sample-project-instance-description": "すぐに使えるデータベースを備えたサンプルプロジェクトインスタンスを 7 日間使用して、Bytebase を試すことができます。","sample-project-instance-title": "サンプルプロジェクトインスタンスを試す","scan-interval": {@@ -2696,6 +2699,7 @@"display-name": "あなたの名前","display-name-placeholder": "名前を入力してください","email": "メールアドレス",+ "enable-sample-databases": "サンプルデータベースを有効にする","password": "パスワード","password-confirm": "パスワードの確認","password-confirm-placeholder": "新しいパスワードを確認します",@@ -2706,6 +2710,7 @@"setup-failed": "プロフィールの更新に失敗しました。","setup-first-project": "最初のプロジェクトを設定","setup-skip": "後で設定する",+ "setup-submit": "ワークスペースをセットアップ","setup-success": "プロフィールが更新されました。","setup-title": "ようこそ!ワークスペースを設定してください","workspace-name": "ワークスペース名",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex efc03f1a0e..30e86a3d81 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1217,6 +1217,9 @@"role-arn": "ARN vai trò","role-arn-description": "Vai trò IAM để đảm nhận cho truy cập xuyên tài khoản. Để trống cho truy cập cùng tài khoản.","role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "sample-expiration-expired": "Phiên bản mẫu đã hết hạn vào {{time}} và sẽ sớm bị xóa.",+ "sample-expiration-future_one": "Phiên bản mẫu sẽ bị xóa sau {{count}} ngày, vào {{time}}.",+ "sample-expiration-future_other": "Phiên bản mẫu sẽ bị xóa sau {{count}} ngày, vào {{time}}.","sample-project-instance-description": "Sử dụng Phiên bản dự án mẫu để khám phá Bytebase với cơ sở dữ liệu sẵn sàng sử dụng trong 7 ngày.","sample-project-instance-title": "Dùng thử Phiên bản dự án mẫu","scan-interval": {@@ -2696,6 +2699,7 @@"display-name": "Tên của bạn","display-name-placeholder": "Nhập tên của bạn","email": "Email",+ "enable-sample-databases": "Bật cơ sở dữ liệu mẫu","password": "Mật khẩu","password-confirm": "Xác nhận mật khẩu","password-confirm-placeholder": "Xác nhận mật khẩu mới",@@ -2706,6 +2710,7 @@"setup-failed": "Cập nhật hồ sơ thất bại.","setup-first-project": "Thiết lập dự án đầu tiên","setup-skip": "Để sau",+ "setup-submit": "Thiết lập không gian làm việc của tôi","setup-success": "Hồ sơ đã được cập nhật.","setup-title": "Chào mừng! Thiết lập không gian làm việc của bạn","workspace-name": "Tên không gian làm việc",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 0ab5f050a2..e56ffc145b 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1217,6 +1217,9 @@"role-arn": "角色 ARN","role-arn-description": "用于跨账户访问的 IAM 角色。同账户访问请留空。","role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "sample-expiration-expired": "示例实例已于 {{time}} 过期,即将被移除。",+ "sample-expiration-future_one": "示例实例将在 {{count}} 天后的 {{time}} 被移除。",+ "sample-expiration-future_other": "示例实例将在 {{count}} 天后的 {{time}} 被移除。","sample-project-instance-description": "使用示例项目实例探索 Bytebase,并在 7 天内使用预配置的数据库。","sample-project-instance-title": "试用示例项目实例","scan-interval": {@@ -2696,6 +2699,7 @@"display-name": "您的姓名","display-name-placeholder": "输入您的姓名","email": "邮箱",+ "enable-sample-databases": "启用示例数据库","password": "密码","password-confirm": "确认密码","password-confirm-placeholder": "确认新密码",@@ -2706,6 +2710,7 @@"setup-failed": "更新个人资料失败。","setup-first-project": "设置第一个项目","setup-skip": "稍后再说",+ "setup-submit": "设置我的工作空间","setup-success": "个人资料已更新。","setup-title": "欢迎!设置您的工作空间","workspace-name": "工作空间名称",diff --git a/frontend/src/routes/auth/ProfileSetupPage.test.tsx b/frontend/src/routes/auth/ProfileSetupPage.test.tsxindex 2ee7a4ae9d..9eab95a2a9 100644--- a/frontend/src/routes/auth/ProfileSetupPage.test.tsx+++ b/frontend/src/routes/auth/ProfileSetupPage.test.tsx@@ -38,11 +38,13 @@ const mocks = vi.hoisted(() => ({updateUser: vi.fn(),updateWorkspace: vi.fn(),createProject: vi.fn(),+ prepareSampleProjectInstance: vi.fn(),setRecentProject: vi.fn(),routerReplace: vi.fn(),pushNotification: vi.fn(),hasWorkspacePermissionV2: vi.fn(() => false),canCreateProject: true,+ sampleAvailable: true,}));vi.mock("@/hooks/useAppState", () => ({@@ -64,12 +66,18 @@ vi.mock("@/stores/app", () => ({workspacePolicy: IamPolicy;updateUser: typeof mocks.updateUser;updateWorkspace: typeof mocks.updateWorkspace;+ prepareSampleProjectInstance: typeof mocks.prepareSampleProjectInstance;+ serverInfo: { sample: { available: boolean } };}) => unknown) =>selector({workspacePolicy: mocks.workspacePolicy,updateUser: mocks.updateUser,updateWorkspace: mocks.updateWorkspace,+ prepareSampleProjectInstance: mocks.prepareSampleProjectInstance,+ serverInfo: {+ sample: { available: mocks.sampleAvailable },+ },}),}));@@ -109,6 +117,8 @@ vi.mock("@/stores", () => ({}));vi.mock("@/utils", () => ({+ extractInstanceResourceName: (name: string) =>+ name.match(/(?:^|\/)instances\/([^/]+)/)?.[1] ?? "",extractProjectResourceName: (name: string) => name.split("/").pop() ?? "",hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,}));@@ -125,6 +135,11 @@ vi.mock("react-i18next", () => ({({"settings.profile.setup-title": "Welcome! Set up your workspace","settings.profile.setup-first-project": "Setup 1st project",+ "settings.profile.enable-sample-databases":+ "Enable sample databases",+ "settings.profile.setup-submit": "Setup my workspace",+ "instance.prepare-sample-instance-failed":+ "Failed to prepare Sample Project Instance.","settings.profile.default-project-name": "New project","settings.profile.create-project-description":"Optional. If you create a project here, we will take you to its database page next.",@@ -156,6 +171,7 @@ beforeEach(async () => {vi.clearAllMocks();mocks.canUpdateWorkspace = true;mocks.canCreateProject = true;+ mocks.sampleAvailable = true;mocks.workspacePolicy = {bindings: [{@@ -168,6 +184,9 @@ beforeEach(async () => {name: "projects/new-project",title: "New Project",});+ mocks.prepareSampleProjectInstance.mockResolvedValue({+ name: "projects/new-project/instances/sample",+ });({ ProfileSetupPage } = await import("./ProfileSetupPage"));});@@ -178,8 +197,9 @@ describe("ProfileSetupPage", () => {});expect(source).toContain(- "query: { [PRODUCT_INTRO_QUERY_KEY]: CONNECT_DATABASE_PRODUCT_INTRO }"+ "[PRODUCT_INTRO_QUERY_KEY]: CONNECT_DATABASE_PRODUCT_INTRO");+ expect(source).toContain("PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO");expect(source).toContain("query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO }");@@ -269,8 +289,15 @@ describe("ProfileSetupPage", () => {)).toBe(false);+ const sampleCheckbox = page.container.querySelector(+ "[data-testid='enable-sample-databases']"+ ) as HTMLButtonElement;+ expect(sampleCheckbox).toBeChecked();+ expect(sampleCheckbox).toBeEnabled();+ expect(page.container.textContent).toContain("Enable sample databases");+const save = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent?.includes("common.save")+ (button) => button.textContent?.includes("Setup my workspace")) as HTMLButtonElement;await act(async () => {save.click();@@ -283,16 +310,25 @@ describe("ProfileSetupPage", () => {"new-project");expect(mocks.setRecentProject).toHaveBeenCalledWith("projects/new-project");+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledWith(+ "projects/new-project"+ );+ expect(mocks.createProject.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.prepareSampleProjectInstance.mock.invocationCallOrder[0]+ );expect(mocks.routerReplace).toHaveBeenCalledWith({name: "workspace.project.database",params: { projectId: "new-project" },- query: { intro: "connect-database" },+ query: {+ syncingInstance: "sample",+ intro: "project-instance-synced",+ },});page.unmount();});- test("does not create a project when the optional project name is empty", async () => {+ test("creates a project with an empty title when its resource ID remains", async () => {const page = renderIntoContainer(<ProfileSetupPage />);page.render();@@ -307,11 +343,20 @@ describe("ProfileSetupPage", () => {});expect(- page.container.querySelector("[data-testid='project-resource-id']")- ).toBeNull();+ (+ page.container.querySelector(+ "[data-testid='project-resource-id']"+ ) as HTMLInputElement+ ).value+ ).toBe("new-project");+ const sampleCheckbox = page.container.querySelector(+ "[data-testid='enable-sample-databases']"+ ) as HTMLButtonElement;+ expect(sampleCheckbox).toBeChecked();+ expect(sampleCheckbox).not.toHaveAttribute("aria-disabled", "true");const save = Array.from(page.container.querySelectorAll("button")).find(- (button) => button.textContent?.includes("common.save")+ (button) => button.textContent?.includes("Setup my workspace")) as HTMLButtonElement;await act(async () => {save.click();@@ -319,16 +364,103 @@ describe("ProfileSetupPage", () => {await Promise.resolve();});- expect(mocks.createProject).not.toHaveBeenCalled();- expect(mocks.setRecentProject).not.toHaveBeenCalled();+ expect(mocks.createProject).toHaveBeenCalledWith("", "new-project");+ expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledWith(+ "projects/new-project"+ );+ expect(mocks.setRecentProject).toHaveBeenCalledWith("projects/new-project");expect(mocks.routerReplace).toHaveBeenCalledWith({- name: "workspace.project",- query: { intro: "create-project" },+ name: "workspace.project.database",+ params: { projectId: "new-project" },+ query: {+ syncingInstance: "sample",+ intro: "project-instance-synced",+ },});page.unmount();});+ test("does not prepare sample databases when the user opts out", async () => {+ const page = renderIntoContainer(<ProfileSetupPage />);++ page.render();++ const sampleCheckbox = page.container.querySelector(+ "[data-testid='enable-sample-databases']"+ ) as HTMLButtonElement;+ await act(async () => {+ sampleCheckbox.click();+ });+ expect(sampleCheckbox).not.toBeChecked();++ const submit = Array.from(page.container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Setup my workspace")+ ) as HTMLButtonElement;+ await act(async () => {+ submit.click();+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(mocks.createProject).toHaveBeenCalled();+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: "workspace.project.database",+ params: { projectId: "new-project" },+ query: { intro: "connect-database" },+ });++ page.unmount();+ });++ test("finishes setup when sample database preparation fails", async () => {+ mocks.prepareSampleProjectInstance.mockRejectedValue(+ new Error("sample target unavailable")+ );+ const page = renderIntoContainer(<ProfileSetupPage />);++ page.render();++ const submit = Array.from(page.container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Setup my workspace")+ ) as HTMLButtonElement;+ await act(async () => {+ submit.click();+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(mocks.pushNotification).toHaveBeenCalledWith(+ expect.objectContaining({+ style: "CRITICAL",+ title: "Failed to prepare Sample Project Instance.",+ })+ );+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: "workspace.project.database",+ params: { projectId: "new-project" },+ query: { intro: "connect-database" },+ });++ page.unmount();+ });++ test("hides sample database setup when the target is unavailable", () => {+ mocks.sampleAvailable = false;+ const page = renderIntoContainer(<ProfileSetupPage />);++ page.render();++ expect(+ page.container.querySelector(+ "[data-testid='enable-sample-databases']"+ )+ ).toBeNull();++ page.unmount();+ });+test("skips profile setup to the projects page with create project highlighted", async () => {const page = renderIntoContainer(<ProfileSetupPage />);diff --git a/frontend/src/routes/auth/ProfileSetupPage.tsx b/frontend/src/routes/auth/ProfileSetupPage.tsxindex 3fdf7c2737..2f62f135fc 100644--- a/frontend/src/routes/auth/ProfileSetupPage.tsx+++ b/frontend/src/routes/auth/ProfileSetupPage.tsx@@ -10,6 +10,7 @@ import {import { ResourceIdField } from "@/components/ResourceIdField";import { UserAvatar } from "@/components/UserAvatar";import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";import { FormField } from "@/components/ui/form";import { Input } from "@/components/ui/input";import {@@ -22,20 +23,32 @@ import {CONNECT_DATABASE_PRODUCT_INTRO,CREATE_PROJECT_PRODUCT_INTRO,PRODUCT_INTRO_QUERY_KEY,+ PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,} from "@/lib/productIntro";+import { cn } from "@/lib/utils";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";import { projectNamePrefix } from "@/stores/modules/v1/common";import type { ValidatedMessage } from "@/types";import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";import { WorkspaceSchema } from "@/types/proto-es/v1/workspace_service_pb";-import { extractProjectResourceName } from "@/utils";+import {+ extractInstanceResourceName,+ extractProjectResourceName,+} from "@/utils";+import { extractGrpcErrorMessage } from "@/utils/connect";export function ProfileSetupPage() {const { t } = useTranslation();const currentUser = useCurrentUser();const updateUser = useAppStore((state) => state.updateUser);const updateWorkspace = useAppStore((state) => state.updateWorkspace);+ const prepareSampleProjectInstance = useAppStore(+ (state) => state.prepareSampleProjectInstance+ );+ const sampleAvailable = useAppStore(+ (state) => state.serverInfo?.sample?.available ?? false+ );const { createProject, setRecentProject } = useCreateProject();const workspace = useWorkspace();const workspacePolicy = useAppStore((state) => state.workspacePolicy);@@ -72,9 +85,9 @@ export function ProfileSetupPage() {const [projectResourceId, setProjectResourceId] = useState("");const [isProjectResourceIdValid, setIsProjectResourceIdValid] =useState(false);+ const [enableSampleDatabases, setEnableSampleDatabases] = useState(true);const [saving, setSaving] = useState(false);- const projectTitleTrimmed = projectTitle.trim();- const shouldCreateProject = canCreateProject && !!projectTitleTrimmed;+ const shouldCreateProject = canCreateProject && !!projectResourceId;const validateProjectResourceId = useCallback(async (id: string): Promise<ValidatedMessage[]> => {@@ -123,13 +136,29 @@ export function ProfileSetupPage() {);}let createdProjectName = "";+ let sampleInstanceName = "";if (shouldCreateProject) {const createdProject = await createProject(- projectTitleTrimmed,+ projectTitle.trim(),projectResourceId);setRecentProject(createdProject.name);createdProjectName = createdProject.name;+ if (enableSampleDatabases && sampleAvailable && createdProject.name) {+ try {+ const sampleInstance = await prepareSampleProjectInstance(+ createdProject.name+ );+ sampleInstanceName = sampleInstance.name;+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("instance.prepare-sample-instance-failed"),+ description: extractGrpcErrorMessage(error),+ });+ }+ }}pushNotification({module: "bytebase",@@ -137,12 +166,22 @@ export function ProfileSetupPage() {title: t("settings.profile.setup-success"),});if (createdProjectName) {+ const sampleInstanceId =+ extractInstanceResourceName(sampleInstanceName);router.replace({name: PROJECT_V1_ROUTE_DATABASES,params: {projectId: extractProjectResourceName(createdProjectName),},- query: { [PRODUCT_INTRO_QUERY_KEY]: CONNECT_DATABASE_PRODUCT_INTRO },+ query: sampleInstanceId+ ? {+ syncingInstance: sampleInstanceId,+ [PRODUCT_INTRO_QUERY_KEY]:+ PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ }+ : {+ [PRODUCT_INTRO_QUERY_KEY]: CONNECT_DATABASE_PRODUCT_INTRO,+ },});} else {goToDashboard();@@ -174,7 +213,7 @@ export function ProfileSetupPage() {title={displayName}colorSeed={currentUser?.email}size="md"- className="!size-16 !text-2xl"+ className="size-16! text-2xl!"/><div className="text-center">@@ -215,19 +254,46 @@ export function ProfileSetupPage() {<Inputdata-testid="profile-project-title"value={projectTitle}- onChange={(e) => setProjectTitle(e.target.value)}+ onChange={(e) => {+ const value = e.target.value;+ setProjectTitle(value);+ }}placeholder={t("quick-action.new-project")}/>- {projectTitleTrimmed && (- <ResourceIdField- suffix- value={projectResourceId}- resourceName={t("common.project")}- resourceTitle={projectTitle}- validate={validateProjectResourceId}- onChange={setProjectResourceId}- onValidationChange={setIsProjectResourceIdValid}- />+ <ResourceIdField+ suffix+ value={projectResourceId}+ resourceName={t("common.project")}+ resourceTitle={projectTitle}+ validate={validateProjectResourceId}+ onChange={(val) => {+ setProjectResourceId(val);+ if (!val) {+ setEnableSampleDatabases(false);+ }+ }}+ onValidationChange={setIsProjectResourceIdValid}+ />+ {sampleAvailable && (+ <div className="flex items-center gap-x-2 pt-1">+ <Checkbox+ id="enable-sample-databases"+ data-testid="enable-sample-databases"+ checked={enableSampleDatabases}+ disabled={!shouldCreateProject}+ onCheckedChange={setEnableSampleDatabases}+ />+ <label+ htmlFor="enable-sample-databases"+ className={cn(+ "cursor-pointer",+ !shouldCreateProject &&+ "cursor-not-allowed text-control-placeholder"+ )}+ >+ {t("settings.profile.enable-sample-databases")}+ </label>+ </div>)}</FormField>)}@@ -238,7 +304,7 @@ export function ProfileSetupPage() {disabled={!canSave}className="w-full">- {t("common.save")}+ {t("settings.profile.setup-submit")}</Button><Buttonappearance="secondary"diff --git a/frontend/src/routes/project/ProjectCreateInstancePage.test.tsx b/frontend/src/routes/project/ProjectCreateInstancePage.test.tsxindex 5c224b5c84..853d765705 100644--- a/frontend/src/routes/project/ProjectCreateInstancePage.test.tsx+++ b/frontend/src/routes/project/ProjectCreateInstancePage.test.tsx@@ -71,7 +71,7 @@ describe("ProjectCreateInstancePage", () => {act(() => page.root.unmount());});- test("opens the nested detail route after creation", async () => {+ test("opens the project databases page after creation", async () => {const page = await renderPage();const onCreated = mocks.viewProps?.onCreated as (instance: unknown) => void;@@ -85,10 +85,12 @@ describe("ProjectCreateInstancePage", () => {});expect(mocks.push).toHaveBeenCalledWith({- name: "workspace.project.instance.detail",- params: { projectId: "app", instanceId: "prod" },- query: { syncingInstance: "prod" },- hash: "databases",+ name: "workspace.project.database",+ params: { projectId: "app" },+ query: {+ syncingInstance: "prod",+ intro: "project-instance-synced",+ },});act(() => page.root.unmount());diff --git a/frontend/src/routes/project/ProjectCreateInstancePage.tsx b/frontend/src/routes/project/ProjectCreateInstancePage.tsxindex b5d2e78c46..4670c93e08 100644--- a/frontend/src/routes/project/ProjectCreateInstancePage.tsx+++ b/frontend/src/routes/project/ProjectCreateInstancePage.tsx@@ -2,10 +2,13 @@ import { useCallback, useEffect } from "react";import { router } from "@/app/router";import {PROJECT_V1_ROUTE_DATABASES,- PROJECT_V1_ROUTE_INSTANCE_DETAIL,PROJECT_V1_ROUTE_INSTANCES,} from "@/app/router/handles";import { CreateInstanceView } from "@/components/instance/CreateInstanceView";+import {+ PRODUCT_INTRO_QUERY_KEY,+ PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+} from "@/lib/productIntro";import { useAppStore } from "@/stores/app";import type { Instance } from "@/types/proto-es/v1/instance_service_pb";import { extractInstanceResourceName } from "@/utils";@@ -41,10 +44,12 @@ export function ProjectCreateInstancePage({(instance: Instance) => {const instanceId = extractInstanceResourceName(instance.name);router.push({- name: PROJECT_V1_ROUTE_INSTANCE_DETAIL,- params: { projectId, instanceId },- query: { syncingInstance: instanceId },- hash: "databases",+ name: PROJECT_V1_ROUTE_DATABASES,+ params: { projectId },+ query: {+ syncingInstance: instanceId,+ [PRODUCT_INTRO_QUERY_KEY]: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,+ },});},[projectId]diff --git a/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx b/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsxindex c02b6e4e25..a894c24eca 100644--- a/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx+++ b/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx@@ -178,6 +178,12 @@ const mocks = vi.hoisted(() => {routeNames: {databaseDetail: "workspace.project.database.detail",},+ serverInfo: {} as {+ sample?: {+ instances: string[];+ expireTime?: { seconds: bigint; nanos: number };+ };+ },};});@@ -280,7 +286,8 @@ vi.mock("@/stores", () => ({// working unchanged.vi.mock("@/stores/app", () => ({useAppStore: Object.assign(- (selector: (s: unknown) => unknown) => selector(mocks.dbSchemaStore()),+ (selector: (s: unknown) => unknown) =>+ selector({ ...mocks.dbSchemaStore(), serverInfo: mocks.serverInfo }),{getState: () => ({...mocks.dbSchemaStore(),@@ -467,6 +474,7 @@ beforeEach(() => {fullPath: "/sql-editor/projects/proj1",});mocks.useProjectDatabaseDetail.mockReset();+ mocks.serverInfo = {};mocks.LoaderCircle.mockClear();mocks.TabsList.mockClear();mocks.TabsTrigger.mockClear();@@ -542,6 +550,50 @@ beforeEach(() => {});describe("ProjectDatabaseDetailPage", () => {+ test("shows the sample expiration warning for a sample database", async () => {+ mocks.serverInfo = {+ sample: {+ instances: ["instances/inst1"],+ expireTime: {+ seconds: BigInt(Math.floor(Date.now() / 1000) + 7 * 24 * 60 * 60),+ nanos: 0,+ },+ },+ };+ mocks.useProjectDatabaseDetail.mockReturnValue({+ database: {+ name: "instances/inst1/databases/db1",+ project: "projects/proj1",+ effectiveEnvironment: "environments/prod",+ instanceResource: {+ name: "projects/proj1/instances/inst1",+ title: "Sample instance",+ },+ },+ databaseName: "instances/inst1/databases/db1",+ loading: false,+ ready: true,+ allowAlterSchema: true,+ isDefaultProject: false,+ });++ const { container, render, unmount } = renderIntoContainer(+ createElement(ProjectDatabaseDetailPage, {+ projectId: "proj1",+ instanceId: "inst1",+ databaseName: "db1",+ })+ );++ render();++ expect(container.textContent).toContain(+ "instance.sample-expiration-future"+ );++ unmount();+ });+test("shows a spinner while the shared database hook is loading", async () => {mocks.useProjectDatabaseDetail.mockReturnValue({database: undefined,diff --git a/frontend/src/routes/project/ProjectDatabaseDetailPage.tsx b/frontend/src/routes/project/ProjectDatabaseDetailPage.tsxindex 7393aa7c2e..dcd279dde0 100644--- a/frontend/src/routes/project/ProjectDatabaseDetailPage.tsx+++ b/frontend/src/routes/project/ProjectDatabaseDetailPage.tsx@@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next";import { router } from "@/app/router";import { ComponentPermissionGuard } from "@/components/ComponentPermissionGuard";import { TransferProjectSheet } from "@/components/database";+import { SampleExpirationAlert } from "@/components/SampleExpirationAlert";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";@@ -154,6 +155,10 @@ export function ProjectDatabaseDetailPage({return (<div className="flex min-h-full flex-col gap-y-4 p-4">+ <SampleExpirationAlert+ instanceName={detail.database.instanceResource?.name ?? parent}+ />+{!detail.database.effectiveEnvironment && (<Alertvariant="warning"diff --git a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx b/frontend/src/routes/project/ProjectDatabasesPage.test.tsxindex 7476ee4124..a210927a60 100644--- a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx+++ b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx@@ -521,6 +521,9 @@ describe("ProjectDatabasesPage", () => {test("opens a synced project instance database in SQL Editor", async () => {mocks.routerCurrentQuery = { syncingInstance: "prod" };+ mocks.fetchInstanceList.mockResolvedValueOnce({+ instances: [{ name: "instances/prod", title: "Prod" }],+ });mocks.visibleDatabases = [{name: "projects/demo/instances/prod/databases/app",@@ -581,9 +584,9 @@ describe("ProjectDatabasesPage", () => {expect(sqlEditorButton.className).toContain("bg-accent");expect(nextActionButton.className).toContain("border-control-border");expect(- sqlEditorButton.compareDocumentPosition(nextActionButton) &+ nextActionButton.compareDocumentPosition(sqlEditorButton) &Node.DOCUMENT_POSITION_FOLLOWING- ).toBeTruthy();+ ).toBe(Node.DOCUMENT_POSITION_FOLLOWING);await act(async () => {sqlEditorButton.click();});@@ -602,6 +605,77 @@ describe("ProjectDatabasesPage", () => {});});+ test("hides post-sync guidance when the workspace has multiple instances", async () => {+ mocks.routerCurrentQuery = { syncingInstance: "prod" };+ mocks.fetchInstanceList.mockResolvedValueOnce({+ instances: [+ { name: "instances/prod", title: "Prod" },+ { name: "instances/staging", title: "Staging" },+ ],+ });+ mocks.visibleDatabases = [+ {+ name: "projects/demo/instances/prod/databases/app",+ project: "projects/demo",+ },+ ];+ const container = document.createElement("div");+ const root = createRoot(container);++ await act(async () => {+ root.render(<ProjectDatabasesPage projectId="demo" />);+ await Promise.resolve();+ });++ expect(mocks.fetchInstanceList).toHaveBeenCalledWith({ pageSize: 2 });+ expect(container.textContent).not.toContain(+ "db.project-instance-synced-title"+ );+ expect(mocks.useProductIntro).toHaveBeenCalledWith(+ expect.objectContaining({+ id: "project-instance-synced",+ disabled: true,+ })+ );++ act(() => {+ root.unmount();+ });+ });++ test("hides post-sync guidance without permission to list instances", async () => {+ mocks.workspacePermissions.delete("bb.instances.list");+ mocks.routerCurrentQuery = { syncingInstance: "prod" };+ mocks.visibleDatabases = [+ {+ name: "projects/demo/instances/prod/databases/app",+ project: "projects/demo",+ },+ ];+ const container = document.createElement("div");+ const root = createRoot(container);++ await act(async () => {+ root.render(<ProjectDatabasesPage projectId="demo" />);+ await Promise.resolve();+ });++ expect(mocks.fetchInstanceList).not.toHaveBeenCalled();+ expect(container.textContent).not.toContain(+ "db.project-instance-synced-title"+ );+ expect(mocks.useProductIntro).toHaveBeenCalledWith(+ expect.objectContaining({+ id: "project-instance-synced",+ disabled: true,+ })+ );++ act(() => {+ root.unmount();+ });+ });+test("shows transfer project batch action for the default project", async () => {mocks.visibleDatabases = [{ name: "instances/prod/databases/app" }];mocks.databasesByName = {diff --git a/frontend/src/routes/project/ProjectDatabasesPage.tsx b/frontend/src/routes/project/ProjectDatabasesPage.tsxindex 58b9661850..14cf720456 100644--- a/frontend/src/routes/project/ProjectDatabasesPage.tsx+++ b/frontend/src/routes/project/ProjectDatabasesPage.tsx@@ -110,9 +110,13 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {const [showTransferDrawer, setShowTransferDrawer] = useState(false);const [showUnassignConfirm, setShowUnassignConfirm] = useState(false);const [refreshToken, setRefreshToken] = useState(0);- const [workspaceHasInstance, setWorkspaceHasInstance] = useState<- boolean | undefined+ const [workspaceInstanceCount, setWorkspaceInstanceCount] = useState<+ number | undefined>(undefined);+ const workspaceHasInstance =+ workspaceInstanceCount === undefined+ ? undefined+ : workspaceInstanceCount > 0;const [syncingRefreshExhausted, setSyncingRefreshExhausted] = useState(false);const autoRefreshCountRef = useRef(0);@@ -296,22 +300,22 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {useEffect(() => {if (!hasWorkspacePermissionV2("bb.instances.list")) {- setWorkspaceHasInstance(false);+ setWorkspaceInstanceCount(0);return;}let cancelled = false;useAppStore.getState()- .fetchInstanceList({ pageSize: 1 })+ .fetchInstanceList({ pageSize: 2 }).then(({ instances }) => {if (!cancelled) {- setWorkspaceHasInstance(instances.length > 0);+ setWorkspaceInstanceCount(instances.length);}}).catch(() => {if (!cancelled) {- setWorkspaceHasInstance(false);+ setWorkspaceInstanceCount(0);}});@@ -501,7 +505,8 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {const hasVisibleDatabase = visibleDatabases.length > 0;const showSyncingInstanceHint =!!syncingInstanceId && !hasVisibleDatabase && !syncingRefreshExhausted;- const showPostSyncNextAction = !!syncingInstanceId && hasVisibleDatabase;+ const showPostSyncNextAction =+ workspaceInstanceCount === 1 && !!syncingInstanceId && hasVisibleDatabase;const checkingWorkspaceInstance =!hasVisibleDatabase &&!showSyncingInstanceHint &&@@ -668,6 +673,18 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {<div className="flex flex-col gap-y-3"><span>{t("db.project-instance-synced-description")}</span><div className="ml-auto flex flex-wrap items-center gap-x-2 gap-y-2">+ <PermissionGuard+ permissions={PERMISSIONS_FOR_DATABASE_CREATE_ISSUE}+ project={project}+ >+ <Button+ size="sm"+ appearance="outline"+ onClick={handleCreateFirstChange}+ >+ {t("db.project-instance-synced-action")}+ </Button>+ </PermissionGuard><PermissionGuardpermissions={["bb.sql.select"]}project={project}@@ -683,18 +700,6 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {/></span></PermissionGuard>- <PermissionGuard- permissions={PERMISSIONS_FOR_DATABASE_CREATE_ISSUE}- project={project}- >- <Button- size="sm"- appearance="outline"- onClick={handleCreateFirstChange}- >- {t("db.project-instance-synced-action")}- </Button>- </PermissionGuard></div></div>}diff --git a/frontend/src/routes/project/database-detail/DatabaseDetailHeader.test.tsx b/frontend/src/routes/project/database-detail/DatabaseDetailHeader.test.tsxnew file mode 100644index 0000000000..d9ac7ad113--- /dev/null+++ b/frontend/src/routes/project/database-detail/DatabaseDetailHeader.test.tsx@@ -0,0 +1,82 @@+import type { ReactNode } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Database } from "@/types/proto-es/v1/database_service_pb";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/hooks/useAppState", () => ({+ useEnvironment: () => undefined,+ usePlanFeature: () => false,+}));++vi.mock("@/components/InstanceLabel", () => ({+ InstanceLabel: () => <span>Sample Project Instance</span>,+}));++vi.mock("@/components/RouterLink", () => ({+ RouterLink: ({ children }: { children: ReactNode }) => <a>{children}</a>,+}));++vi.mock("@/lib/clipboard", () => ({+ writeTextToClipboard: vi.fn(async () => true),+}));++vi.mock("@/utils", () => ({+ extractInstanceResourceName: (name: string) =>+ name.replace(/^instances\//, ""),+ getInstanceResource: () => ({+ name: "instances/sample-0123456789abcdef",+ title: "Sample Project Instance",+ }),+ hexToRgb: () => [0, 0, 0],+}));++vi.mock("./DatabaseSQLEditorButton", () => ({+ DatabaseSQLEditorButton: () => <button type="button">SQL Editor</button>,+}));++import { DatabaseDetailHeader } from "./DatabaseDetailHeader";++describe("DatabaseDetailHeader", () => {+ let container: HTMLDivElement;+ let root: ReturnType<typeof createRoot>;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ });++ it("truncates long database identifiers without hiding their full values", () => {+ const databaseName = "bb_sample_0123456789abcdef";+ const resourceName = `projects/project-a/instances/sample-0123456789abcdef/databases/${databaseName}`;++ act(() => {+ root.render(+ <DatabaseDetailHeader+ database={{ name: resourceName } as Database}+ />+ );+ });++ const id = container.querySelector(`[title="${databaseName}"]`);+ const resource = container.querySelector(`[title="${resourceName}"]`);+ expect(id?.getAttribute("class")).toContain("min-w-0");+ expect(id?.getAttribute("class")).toContain("truncate");+ expect(resource?.getAttribute("class")).toContain("min-w-0");+ expect(resource?.getAttribute("class")).toContain("truncate");+ });+});diff --git a/frontend/src/routes/project/database-detail/DatabaseDetailHeader.tsx b/frontend/src/routes/project/database-detail/DatabaseDetailHeader.tsxindex 72d79d3bdc..e05cda47ab 100644--- a/frontend/src/routes/project/database-detail/DatabaseDetailHeader.tsx+++ b/frontend/src/routes/project/database-detail/DatabaseDetailHeader.tsx@@ -95,11 +95,15 @@ export function DatabaseDetailHeader({ database }: { database: Database }) {return (<div className="flex min-w-0 flex-1 shrink-0 flex-col gap-y-2"><div className="flex w-full min-w-0 flex-col">- <div className="flex items-center gap-x-2 truncate text-xl font-bold text-main">- {databaseName}+ <div className="flex min-w-0 items-center gap-x-2 text-xl font-bold text-main">+ <span className="min-w-0 truncate" title={databaseName}>+ {databaseName}+ </span></div><div className="mt-1 flex w-full min-w-0 items-center gap-x-1 text-sm text-control-light">- <span className="truncate">{database.name}</span>+ <span className="min-w-0 flex-1 truncate" title={database.name}>+ {database.name}+ </span><buttontype="button"className="inline-flex shrink-0 items-center p-0.5 text-control-light hover:text-main"diff --git a/frontend/src/stores/app/instance.test.ts b/frontend/src/stores/app/instance.test.tsindex 62dce439a9..05f74bef84 100644--- a/frontend/src/stores/app/instance.test.ts+++ b/frontend/src/stores/app/instance.test.ts@@ -11,8 +11,10 @@ const mocks = vi.hoisted(() => ({getInstance: vi.fn(),listInstances: vi.fn(),createInstance: vi.fn(),+ prepareSampleProjectInstance: vi.fn(),batchSyncInstances: vi.fn(),batchUpdateInstances: vi.fn(),+ refreshServerInfo: vi.fn(),hasWorkspacePermissionV2: vi.fn(() => true),hasProjectPermissionV2: vi.fn(() => true),}));@@ -22,6 +24,7 @@ vi.mock("@/api", () => ({getInstance: mocks.getInstance,listInstances: mocks.listInstances,createInstance: mocks.createInstance,+ prepareSampleProjectInstance: mocks.prepareSampleProjectInstance,batchSyncInstances: mocks.batchSyncInstances,batchUpdateInstances: mocks.batchUpdateInstances,},@@ -34,7 +37,9 @@ vi.mock("@/utils", async (importOriginal) => ({}));const createStore = () => {- const state: Record<string, unknown> = {};+ const state: Record<string, unknown> = {+ refreshServerInfo: mocks.refreshServerInfo,+ };const set = (updater: unknown) => {const patch =typeof updater === "function"@@ -65,6 +70,13 @@ describe("instance store project parent", () => {title: "Prod",}));+ mocks.prepareSampleProjectInstance.mockResolvedValue(+ create(InstanceSchema, {+ name: "projects/app/instances/sample",+ title: "Sample",+ })+ );+ mocks.refreshServerInfo.mockResolvedValue({});mocks.batchSyncInstances.mockResolvedValue({});mocks.batchUpdateInstances.mockResolvedValue({ instances: [] });});@@ -109,6 +121,30 @@ describe("instance store project parent", () => {});});+ test("refreshes sample metadata after preparing a sample instance", async () => {+ const store = createStore();++ const instance = await store.prepareSampleProjectInstance("projects/app");++ expect(mocks.prepareSampleProjectInstance.mock.calls[0][0]).toMatchObject({+ parent: "projects/app",+ });+ expect(mocks.refreshServerInfo).toHaveBeenCalledOnce();+ expect(instance.name).toBe("projects/app/instances/sample");+ expect(store.instancesByName[instance.name]).toBe(instance);+ });++ test("returns the prepared sample when refreshing metadata fails", async () => {+ const store = createStore();+ mocks.refreshServerInfo.mockRejectedValue(new Error("refresh failed"));++ await expect(+ store.prepareSampleProjectInstance("projects/app")+ ).resolves.toMatchObject({+ name: "projects/app/instances/sample",+ });+ });+test("uses project permission to fetch a nested instance", async () => {const store = createStore();const project = create(ProjectSchema, { name: "projects/app" });diff --git a/frontend/src/stores/app/instance.ts b/frontend/src/stores/app/instance.tsindex 2958ea2b81..6bf0b3ed8a 100644--- a/frontend/src/stores/app/instance.ts+++ b/frontend/src/stores/app/instance.ts@@ -210,7 +210,11 @@ export const createInstanceSlice: AppSliceCreator<InstanceSlice> = (await instanceServiceClientConnect.prepareSampleProjectInstance(createProto(PrepareSampleProjectInstanceRequestSchema, { parent }));- return upsertInstances([response])[0];+ const instance = upsertInstances([response])[0];+ await get()+ .refreshServerInfo()+ .catch(() => undefined);+ return instance;},updateInstance: async (instance, updateMask) => {diff --git a/frontend/src/stores/app/workspace.ts b/frontend/src/stores/app/workspace.tsindex faa1269032..b8ee1c3b3c 100644--- a/frontend/src/stores/app/workspace.ts+++ b/frontend/src/stores/app/workspace.ts@@ -692,7 +692,7 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (if (get().appFeatures["bb.feature.hide-quick-start"]) {return false;}- if (!get().serverInfo?.enableSample) {+ if (!get().serverInfo?.sample?.available) {return false;}return get().userCountInIam() <= 1;diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts b/frontend/src/types/proto-es/v1/actuator_service_pb.d.tsindex b8be772db8..02783fe65e 100644--- a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts@@ -39,6 +39,41 @@ export declare type GetActuatorInfoRequest = Message<"bytebase.v1.GetActuatorInf*/export declare const GetActuatorInfoRequestSchema: GenMessage<GetActuatorInfoRequest>;+/**+ * SampleInfo describes sample setup availability and provisioned resources.+ *+ * @generated from message bytebase.v1.SampleInfo+ */+export declare type SampleInfo = Message<"bytebase.v1.SampleInfo"> & {+ /**+ * Whether sample setup is currently available.+ *+ * @generated from field: bool available = 1;+ */+ available: boolean;++ /**+ * The provisioned sample instances.+ * Format: instances/{instance}+ *+ * @generated from field: repeated string instances = 2;+ */+ instances: string[];++ /**+ * The time when the provisioned sample resources expire.+ *+ * @generated from field: google.protobuf.Timestamp expire_time = 3;+ */+ expireTime?: Timestamp | undefined;+};++/**+ * Describes the message bytebase.v1.SampleInfo.+ * Use `create(SampleInfoSchema)` to create a new message.+ */+export declare const SampleInfoSchema: GenMessage<SampleInfo>;+/*** System information and configuration for the Bytebase instance.* Actuator concept is similar to the Spring Boot Actuator.@@ -110,13 +145,6 @@ export declare type ActuatorInfo = Message<"bytebase.v1.ActuatorInfo"> & {*/totalInstanceCount: number;- /**- * Whether sample data setup is enabled.- *- * @generated from field: bool enable_sample = 22;- */- enableSample: boolean;-/*** Whether the external URL is set via command-line flag (and thus cannot be changed via UI).*@@ -152,6 +180,13 @@ export declare type ActuatorInfo = Message<"bytebase.v1.ActuatorInfo"> & {* @generated from field: int32 active_vcs_user_count = 28;*/activeVcsUserCount: number;++ /**+ * Sample setup availability and provisioned resources.+ *+ * @generated from field: bytebase.v1.SampleInfo sample = 29;+ */+ sample?: SampleInfo | undefined;};/**diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.js b/frontend/src/types/proto-es/v1/actuator_service_pb.jsindex 458f1cb270..c678c057e5 100644--- a/frontend/src/types/proto-es/v1/actuator_service_pb.js+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.js@@ -6,6 +6,7 @@ import { fileDesc, messageDesc, serviceDesc } from "@bufbuild/protobuf/codegenv2import { file_google_api_annotations } from "../google/api/annotations_pb";import { file_google_api_client } from "../google/api/client_pb";import { file_google_api_field_behavior } from "../google/api/field_behavior_pb";+import { file_google_api_resource } from "../google/api/resource_pb";import { file_google_protobuf_empty, file_google_protobuf_timestamp } from "@bufbuild/protobuf/wkt";import { file_v1_annotation } from "./annotation_pb";@@ -13,7 +14,7 @@ import { file_v1_annotation } from "./annotation_pb";* Describes the file v1/actuator_service.proto.*/export const file_v1_actuator_service = /*@__PURE__*/- fileDesc("Chl2MS9hY3R1YXRvcl9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSIUChJTZXR1cFNhbXBsZVJlcXVlc3QiGAoWR2V0QWN0dWF0b3JJbmZvUmVxdWVzdCKZBAoMQWN0dWF0b3JJbmZvEhQKB3ZlcnNpb24YASABKAlCA+BBAxIXCgpnaXRfY29tbWl0GAIgASgJQgPgQQMSEQoEc2FhcxgEIAEoCEID4EEDEhkKDGV4dGVybmFsX3VybBgIIAEoCUID4EEDEjkKEGxhc3RfYWN0aXZlX3RpbWUYCyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wQgPgQQMSFgoJd29ya3NwYWNlGA0gASgJQgPgQQMSIAoTdW5saWNlbnNlZF9mZWF0dXJlcxgPIAMoCUID4EEDEiUKGGFjdGl2YXRlZF9pbnN0YW5jZV9jb3VudBgUIAEoBUID4EEDEiEKFHRvdGFsX2luc3RhbmNlX2NvdW50GBUgASgFQgPgQQMSGgoNZW5hYmxlX3NhbXBsZRgWIAEoCEID4EEDEiMKFmV4dGVybmFsX3VybF9mcm9tX2ZsYWcYFyABKAhCA+BBAxIaCg1yZXBsaWNhX2NvdW50GBggASgFQgPgQQMSHAoPZGVmYXVsdF9wcm9qZWN0GBogASgJQgPgQQMSHgoRdXNlcl9jb3VudF9pbl9pYW0YGyABKAVCA+BBAxIiChVhY3RpdmVfdmNzX3VzZXJfY291bnQYHCABKAVCA+BBA0oECAMQBEoECAUQCEoECAkQCkoECAoQC0oECAwQDUoECA4QD0oECBAQFEoECBkQGjKXAgoPQWN0dWF0b3JTZXJ2aWNlEnMKD0dldEFjdHVhdG9ySW5mbxIjLmJ5dGViYXNlLnYxLkdldEFjdHVhdG9ySW5mb1JlcXVlc3QaGS5ieXRlYmFzZS52MS5BY3R1YXRvckluZm8iINpBAKDqMAGC0+STAhMSES92MS9hY3R1YXRvci9pbmZvEo4BCgtTZXR1cFNhbXBsZRIfLmJ5dGViYXNlLnYxLlNldHVwU2FtcGxlUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSJGiuowEmJiLnByb2plY3RzLmNyZWF0ZZDqMAGY6jABoOowBKjqMAmC0+STAhoiGC92MS9hY3R1YXRvcjpzZXR1cFNhbXBsZUKqAQoPY29tLmJ5dGViYXNlLnYxQhRBY3R1YXRvclNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_protobuf_empty, file_google_protobuf_timestamp, file_v1_annotation]);+ fileDesc("Chl2MS9hY3R1YXRvcl9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSIUChJTZXR1cFNhbXBsZVJlcXVlc3QiGAoWR2V0QWN0dWF0b3JJbmZvUmVxdWVzdCKMAQoKU2FtcGxlSW5mbxIWCglhdmFpbGFibGUYASABKAhCA+BBAxIwCglpbnN0YW5jZXMYAiADKAlCHeBBA/pBFwoVYnl0ZWJhc2UuY29tL0luc3RhbmNlEjQKC2V4cGlyZV90aW1lGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDIrEECgxBY3R1YXRvckluZm8SFAoHdmVyc2lvbhgBIAEoCUID4EEDEhcKCmdpdF9jb21taXQYAiABKAlCA+BBAxIRCgRzYWFzGAQgASgIQgPgQQMSGQoMZXh0ZXJuYWxfdXJsGAggASgJQgPgQQMSOQoQbGFzdF9hY3RpdmVfdGltZRgLIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIWCgl3b3Jrc3BhY2UYDSABKAlCA+BBAxIgChN1bmxpY2Vuc2VkX2ZlYXR1cmVzGA8gAygJQgPgQQMSJQoYYWN0aXZhdGVkX2luc3RhbmNlX2NvdW50GBQgASgFQgPgQQMSIQoUdG90YWxfaW5zdGFuY2VfY291bnQYFSABKAVCA+BBAxIjChZleHRlcm5hbF91cmxfZnJvbV9mbGFnGBcgASgIQgPgQQMSGgoNcmVwbGljYV9jb3VudBgYIAEoBUID4EEDEhwKD2RlZmF1bHRfcHJvamVjdBgaIAEoCUID4EEDEh4KEXVzZXJfY291bnRfaW5faWFtGBsgASgFQgPgQQMSIgoVYWN0aXZlX3Zjc191c2VyX2NvdW50GBwgASgFQgPgQQMSLAoGc2FtcGxlGB0gASgLMhcuYnl0ZWJhc2UudjEuU2FtcGxlSW5mb0ID4EEDSgQIAxAESgQIBRAISgQICRAKSgQIChALSgQIDBANSgQIDhAPSgQIEBAUSgQIFhAXSgQIGRAaMpcCCg9BY3R1YXRvclNlcnZpY2UScwoPR2V0QWN0dWF0b3JJbmZvEiMuYnl0ZWJhc2UudjEuR2V0QWN0dWF0b3JJbmZvUmVxdWVzdBoZLmJ5dGViYXNlLnYxLkFjdHVhdG9ySW5mbyIg2kEAoOowAYLT5JMCExIRL3YxL2FjdHVhdG9yL2luZm8SjgEKC1NldHVwU2FtcGxlEh8uYnl0ZWJhc2UudjEuU2V0dXBTYW1wbGVSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IkaK6jASYmIucHJvamVjdHMuY3JlYXRlkOowAZjqMAGg6jAEqOowCYLT5JMCGiIYL3YxL2FjdHVhdG9yOnNldHVwU2FtcGxlQqoBCg9jb20uYnl0ZWJhc2UudjFCFEFjdHVhdG9yU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_timestamp, file_v1_annotation]);/*** Describes the message bytebase.v1.SetupSampleRequest.@@ -29,12 +30,19 @@ export const SetupSampleRequestSchema = /*@__PURE__*/export const GetActuatorInfoRequestSchema = /*@__PURE__*/messageDesc(file_v1_actuator_service, 1);+/**+ * Describes the message bytebase.v1.SampleInfo.+ * Use `create(SampleInfoSchema)` to create a new message.+ */+export const SampleInfoSchema = /*@__PURE__*/+ messageDesc(file_v1_actuator_service, 2);+/*** Describes the message bytebase.v1.ActuatorInfo.* Use `create(ActuatorInfoSchema)` to create a new message.*/export const ActuatorInfoSchema = /*@__PURE__*/- messageDesc(file_v1_actuator_service, 2);+ messageDesc(file_v1_actuator_service, 3);/*** ActuatorService manages system health and operational information.diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex 3ae43d967d..df18f71c98 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -18985,11 +18985,6 @@ components:format: int32description: The total number of database instances.readOnly: true- enableSample:- type: boolean- title: enable_sample- description: Whether sample data setup is enabled.- readOnly: trueexternalUrlFromFlag:type: booleantitle: external_url_from_flag@@ -19020,6 +19015,11 @@ components:format: int32description: The number of active VCS users seen in the active window.readOnly: true+ sample:+ title: sample+ description: Sample setup availability and provisioned resources.+ readOnly: true+ $ref: '#/components/schemas/bytebase.v1.SampleInfo'title: ActuatorInfoadditionalProperties: falsedescription: |-@@ -28960,6 +28960,32 @@ components:- BUILTIN_WALK_THROUGH_CHECK- STATEMENT_DISALLOW_TRUNCATE- BUILTIN_STATEMENT_MAXIMUM_SQL_SIZE+ bytebase.v1.SampleInfo:+ type: object+ properties:+ available:+ type: boolean+ title: available+ description: Whether sample setup is currently available.+ readOnly: true+ instances:+ type: array+ items:+ type: string+ readOnly: true+ title: instances+ description: |-+ The provisioned sample instances.+ Format: instances/{instance}+ readOnly: true+ expireTime:+ title: expire_time+ description: The time when the provisioned sample resources expire.+ readOnly: true+ $ref: '#/components/schemas/google.protobuf.Timestamp'+ title: SampleInfo+ additionalProperties: false+ description: SampleInfo describes sample setup availability and provisioned resources.bytebase.v1.SavedQuery:type: objectproperties:diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 9f74eaca93..bb1d3c1c2e 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -35,6 +35,7 @@- [v1/actuator_service.proto](#v1_actuator_service-proto)- [ActuatorInfo](#bytebase-v1-ActuatorInfo)- [GetActuatorInfoRequest](#bytebase-v1-GetActuatorInfoRequest)+ - [SampleInfo](#bytebase-v1-SampleInfo)- [SetupSampleRequest](#bytebase-v1-SetupSampleRequest)- [ActuatorService](#bytebase-v1-ActuatorService)@@ -1150,12 +1151,12 @@ Actuator concept is similar to the Spring Boot Actuator.| unlicensed_features | [string](#string) | repeated | List of features that are not licensed. || activated_instance_count | [int32](#int32) | | The number of activated database instances. || total_instance_count | [int32](#int32) | | The total number of database instances. |-| enable_sample | [bool](#bool) | | Whether sample data setup is enabled. || external_url_from_flag | [bool](#bool) | | Whether the external URL is set via command-line flag (and thus cannot be changed via UI). || replica_count | [int32](#int32) | | The number of active replicas (servers sharing the same database). || default_project | [string](#string) | | The default project for unassigned databases. Format: projects/{id} || user_count_in_iam | [int32](#int32) | | The number of users in the workspace IAM (for seat limit display). || active_vcs_user_count | [int32](#int32) | | The number of active VCS users seen in the active window. |+| sample | [SampleInfo](#bytebase-v1-SampleInfo) | | Sample setup availability and provisioned resources. |@@ -1172,6 +1173,23 @@ Request message for getting actuator information.+<a name="bytebase-v1-SampleInfo"></a>++### SampleInfo+SampleInfo describes sample setup availability and provisioned resources.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| available | [bool](#bool) | | Whether sample setup is currently available. |+| instances | [string](#string) | repeated | The provisioned sample instances. Format: instances/{instance} |+| expire_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The time when the provisioned sample resources expire. |++++++<a name="bytebase-v1-SetupSampleRequest"></a>### SetupSampleRequestdiff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 1cbdcd587f..b000df4310 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -296,6 +296,10 @@<a href="#bytebase.v1.GetActuatorInfoRequest"><span class="badge">M</span>GetActuatorInfoRequest</a></li>+ <li>+ <a href="#bytebase.v1.SampleInfo"><span class="badge">M</span>SampleInfo</a>+ </li>+<li><a href="#bytebase.v1.SetupSampleRequest"><span class="badge">M</span>SetupSampleRequest</a></li>@@ -4227,13 +4231,6 @@ Format: workspaces/{id} </p></td><td><p>The total number of database instances. </p></td></tr>- <tr>- <td>enable_sample</td>- <td><a href="#bool">bool</a></td>- <td></td>- <td><p>Whether sample data setup is enabled. </p></td>- </tr>-<tr><td>external_url_from_flag</td><td><a href="#bool">bool</a></td>@@ -4270,6 +4267,13 @@ Format: projects/{id} </p></td><td><p>The number of active VCS users seen in the active window. </p></td></tr>+ <tr>+ <td>sample</td>+ <td><a href="#bytebase.v1.SampleInfo">SampleInfo</a></td>+ <td></td>+ <td><p>Sample setup availability and provisioned resources. </p></td>+ </tr>+</tbody></table>@@ -4284,6 +4288,45 @@ Format: projects/{id} </p></td>+ <h3 id="bytebase.v1.SampleInfo">SampleInfo</h3>+ <p>SampleInfo describes sample setup availability and provisioned resources.</p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>available</td>+ <td><a href="#bool">bool</a></td>+ <td></td>+ <td><p>Whether sample setup is currently available. </p></td>+ </tr>++ <tr>+ <td>instances</td>+ <td><a href="#string">string</a></td>+ <td>repeated</td>+ <td><p>The provisioned sample instances.+Format: instances/{instance} </p></td>+ </tr>++ <tr>+ <td>expire_time</td>+ <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>+ <td></td>+ <td><p>The time when the provisioned sample resources expire. </p></td>+ </tr>++ </tbody>+ </table>+++++<h3 id="bytebase.v1.SetupSampleRequest">SetupSampleRequest</h3><p>Request message for setting up sample data.</p>diff --git a/proto/v1/v1/actuator_service.proto b/proto/v1/v1/actuator_service.protoindex 3bdb5fa8e6..94eadf2b72 100644--- a/proto/v1/v1/actuator_service.proto+++ b/proto/v1/v1/actuator_service.proto@@ -5,6 +5,7 @@ package bytebase.v1;import "google/api/annotations.proto";import "google/api/client.proto";import "google/api/field_behavior.proto";+import "google/api/resource.proto";import "google/protobuf/empty.proto";import "google/protobuf/timestamp.proto";import "v1/annotation.proto";@@ -43,10 +44,26 @@ message SetupSampleRequest {}// Request message for getting actuator information.message GetActuatorInfoRequest {}+// SampleInfo describes sample setup availability and provisioned resources.+message SampleInfo {+ // Whether sample setup is currently available.+ bool available = 1 [(google.api.field_behavior) = OUTPUT_ONLY];++ // The provisioned sample instances.+ // Format: instances/{instance}+ repeated string instances = 2 [+ (google.api.field_behavior) = OUTPUT_ONLY,+ (google.api.resource_reference) = {type: "bytebase.com/Instance"}+ ];++ // The time when the provisioned sample resources expire.+ google.protobuf.Timestamp expire_time = 3 [(google.api.field_behavior) = OUTPUT_ONLY];+}+// System information and configuration for the Bytebase instance.// Actuator concept is similar to the Spring Boot Actuator.message ActuatorInfo {- reserved 3, 5 to 7, 9, 10, 12, 14, 16 to 19, 25;+ reserved 3, 5 to 7, 9, 10, 12, 14, 16 to 19, 22, 25;// The Bytebase server version.string version = 1 [(google.api.field_behavior) = OUTPUT_ONLY];@@ -76,9 +93,6 @@ message ActuatorInfo {// The total number of database instances.int32 total_instance_count = 21 [(google.api.field_behavior) = OUTPUT_ONLY];- // Whether sample data setup is enabled.- bool enable_sample = 22 [(google.api.field_behavior) = OUTPUT_ONLY];-// Whether the external URL is set via command-line flag (and thus cannot be changed via UI).bool external_url_from_flag = 23 [(google.api.field_behavior) = OUTPUT_ONLY];@@ -94,4 +108,7 @@ message ActuatorInfo {// The number of active VCS users seen in the active window.int32 active_vcs_user_count = 28 [(google.api.field_behavior) = OUTPUT_ONLY];++ // Sample setup availability and provisioned resources.+ SampleInfo sample = 29 [(google.api.field_behavior) = OUTPUT_ONLY];}