Skip to content

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

chore: renovate schema syncer (#12629)

Danny Xu1b86c23c26d3
diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.go
index 4aa223c5c0..7e9aef565f 100644
--- a/backend/api/v1/instance_service.go
+++ b/backend/api/v1/instance_service.go
@@ -230,11 +230,7 @@ func (s *InstanceService) CreateInstance(ctx context.Context, request *v1pb.Crea
instance = updatedInstance
}
// Sync all databases in the instance asynchronously.
- s.stateCfg.InstanceSyncs.Store(instance.UID, instance)
- select {
- case s.stateCfg.InstanceSyncTickleChan <- 0:
- default:
- }
+ s.schemaSyncer.SyncAllDatabases(ctx, instance)
}
s.metricReporter.Report(ctx, &metric.Metric{
@@ -634,8 +630,7 @@ func (s *InstanceService) SyncInstance(ctx context.Context, request *v1pb.SyncIn
return nil, err
}
// Sync all databases in the instance asynchronously.
- s.stateCfg.InstanceSyncs.Store(instance.UID, updatedInstance)
- s.stateCfg.InstanceSyncTickleChan <- 0
+ s.schemaSyncer.SyncAllDatabases(ctx, updatedInstance)
return &v1pb.SyncInstanceResponse{}, nil
}
@@ -650,15 +645,13 @@ func (s *InstanceService) BatchSyncInstance(ctx context.Context, request *v1pb.B
if instance.Deleted {
return nil, status.Errorf(codes.NotFound, "instance %q has been deleted", r.Name)
}
- // Sync all databases in the instance asynchronously.
- select {
- case s.stateCfg.InstanceSyncTickleChan <- 0:
- default:
+
+ updatedInstance, err := s.schemaSyncer.SyncInstance(ctx, instance)
+ if err != nil {
+ return nil, err
}
- }
- select {
- case s.stateCfg.InstanceSyncTickleChan <- 0:
- default:
+ // Sync all databases in the instance asynchronously.
+ s.schemaSyncer.SyncAllDatabases(ctx, updatedInstance)
}
return &v1pb.BatchSyncInstanceResponse{}, nil
diff --git a/backend/component/state/state.go b/backend/component/state/state.go
index b33a08d168..190780061f 100644
--- a/backend/component/state/state.go
+++ b/backend/component/state/state.go
@@ -17,8 +17,6 @@ const DefaultInstanceMaximumConnections = 10
// State is the state for all in-memory states within the server.
type State struct {
- // InstanceDatabaseSyncChan is the channel for synchronizing schemas for instances.
- InstanceSyncs sync.Map // map[instance.ID]*store.InstanceMessage
// InstanceSlowQuerySyncChan is the channel for synchronizing slow query logs for instances.
InstanceSlowQuerySyncChan chan *InstanceSlowQuerySyncMessage
@@ -51,8 +49,6 @@ type State struct {
// TaskSkippedOrDoneChan is the channel for notifying the task is skipped or done.
TaskSkippedOrDoneChan chan int
- // InstanceSyncTickleChan is the tickler for syncing instances.
- InstanceSyncTickleChan chan int
// PlanCheckTickleChan is the tickler for plan check scheduler.
PlanCheckTickleChan chan int
// TaskRunTickleChan is the tickler for task run scheduler.
@@ -71,7 +67,6 @@ func New() (*State, error) {
InstanceOutstandingConnections: &connectionLimiter{connections: map[int]int{}},
IssueExternalApprovalRelayCancelChan: make(chan int, 1),
TaskSkippedOrDoneChan: make(chan int, 1000),
- InstanceSyncTickleChan: make(chan int, 50000),
PlanCheckTickleChan: make(chan int, 1000),
TaskRunTickleChan: make(chan int, 1000),
ExpireCache: expireCache,
diff --git a/backend/runner/schemasync/syncer.go b/backend/runner/schemasync/syncer.go
index f2d5a1e387..2df5af7f9c 100644
--- a/backend/runner/schemasync/syncer.go
+++ b/backend/runner/schemasync/syncer.go
@@ -32,16 +32,17 @@ import (
)
const (
- schemaSyncInterval = 1 * time.Minute
+ schemaSyncInterval = 10 * time.Minute
+ databaseSyncCheckerInterval = 1 * time.Second
// defaultSyncInterval means never sync.
defaultSyncInterval = 0 * time.Second
MaximumOutstanding = 100
)
// NewSyncer creates a schema syncer.
-func NewSyncer(store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, profile config.Profile, licenseService enterprise.LicenseService) *Syncer {
+func NewSyncer(stores *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, profile config.Profile, licenseService enterprise.LicenseService) *Syncer {
return &Syncer{
- store: store,
+ store: stores,
dbFactory: dbFactory,
stateCfg: stateCfg,
profile: profile,
@@ -51,38 +52,68 @@ func NewSyncer(store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *sta
// Syncer is the schema syncer.
type Syncer struct {
- store *store.Store
- dbFactory *dbfactory.DBFactory
- stateCfg *state.State
- profile config.Profile
- licenseService enterprise.LicenseService
+ sync.Mutex
+
+ store *store.Store
+ dbFactory *dbfactory.DBFactory
+ stateCfg *state.State
+ profile config.Profile
+ licenseService enterprise.LicenseService
+ databaseSyncMap sync.Map // map[int]*store.DatabaseMessage
}
// Run will run the schema syncer once.
func (s *Syncer) Run(ctx context.Context, wg *sync.WaitGroup) {
- ticker := time.NewTicker(schemaSyncInterval)
- defer ticker.Stop()
defer wg.Done()
- slog.Debug(fmt.Sprintf("Schema syncer started and will run every %v", schemaSyncInterval))
- for {
- select {
- case <-ticker.C:
- s.trySyncAll(ctx)
- case <-s.stateCfg.InstanceSyncTickleChan:
- s.stateCfg.InstanceSyncs.Range(func(key, value any) bool {
- s.stateCfg.InstanceSyncs.Delete(key)
- instance, ok := value.(*store.InstanceMessage)
- if !ok {
+
+ sp := pool.New()
+ sp.Go(func() {
+ slog.Debug(fmt.Sprintf("Schema syncer started and will run every %v", schemaSyncInterval))
+ ticker := time.NewTicker(schemaSyncInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ s.trySyncAll(ctx)
+ case <-ctx.Done(): // if cancel() execute
+ return
+ }
+ }
+ })
+
+ sp.Go(func() {
+ ticker := time.NewTicker(databaseSyncCheckerInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ dbwp := pool.New().WithMaxGoroutines(MaximumOutstanding)
+ s.databaseSyncMap.Range(func(key, value any) bool {
+ s.databaseSyncMap.Delete(key)
+ database, ok := value.(*store.DatabaseMessage)
+ if !ok {
+ return true
+ }
+
+ dbwp.Go(func() {
+ slog.Debug("Sync database schema", slog.String("instance", database.InstanceID), slog.String("database", database.DatabaseName))
+ if err := s.SyncDatabaseSchema(ctx, database, false /* force */); err != nil {
+ slog.Debug("Failed to sync database schema",
+ slog.String("instance", database.InstanceID),
+ slog.String("databaseName", database.DatabaseName),
+ log.BBError(err))
+ }
+ })
return true
- }
- // Sync all databases for instance.
- s.syncAllDatabases(ctx, instance)
- return true
- })
- case <-ctx.Done(): // if cancel() execute
- return
+ })
+ dbwp.Wait()
+ case <-ctx.Done(): // if cancel() execute
+ return
+ }
}
- }
+ })
+ sp.Wait()
}
func (s *Syncer) trySyncAll(ctx context.Context) {
@@ -138,7 +169,6 @@ func (s *Syncer) trySyncAll(ctx context.Context) {
slog.Error("Failed to retrieve databases", log.BBError(err))
return
}
- dbwp := pool.New().WithMaxGoroutines(MaximumOutstanding)
for _, database := range databases {
database := database
if database.SyncState != api.OK {
@@ -161,30 +191,11 @@ func (s *Syncer) trySyncAll(ctx context.Context) {
continue
}
- dbwp.Go(func() {
- slog.Debug("Sync database schema", slog.String("instance", database.InstanceID), slog.String("database", database.DatabaseName))
- if err := s.SyncDatabaseSchema(ctx, database, false /* force */); err != nil {
- slog.Debug("Failed to sync database schema",
- slog.String("instance", instance.ResourceID),
- slog.String("databaseName", database.DatabaseName),
- log.BBError(err))
- }
- })
+ s.databaseSyncMap.Store(database.UID, database)
}
- dbwp.Wait()
}
-func (s *Syncer) syncAllDatabases(ctx context.Context, instance *store.InstanceMessage) {
- defer func() {
- if r := recover(); r != nil {
- err, ok := r.(error)
- if !ok {
- err = errors.Errorf("%v", r)
- }
- slog.Error("Database syncer PANIC RECOVER", log.BBError(err), log.BBStack("panic-stack"))
- }
- }()
-
+func (s *Syncer) SyncAllDatabases(ctx context.Context, instance *store.InstanceMessage) {
find := &store.FindDatabaseMessage{}
if instance != nil {
find.InstanceID = &instance.ResourceID
@@ -196,32 +207,12 @@ func (s *Syncer) syncAllDatabases(ctx context.Context, instance *store.InstanceM
return
}
- instanceMap := make(map[string][]*store.DatabaseMessage)
for _, database := range databases {
// Skip deleted databases.
if database.SyncState != api.OK {
continue
}
- instanceMap[database.InstanceID] = append(instanceMap[database.InstanceID], database)
- }
-
- for _, databaseList := range instanceMap {
- for _, database := range databaseList {
- instanceID := database.InstanceID
- slog.Debug("Sync database schema",
- slog.String("instance", instanceID),
- slog.String("database", database.DatabaseName),
- slog.Int64("lastSuccessfulSyncTs", database.SuccessfulSyncTimeTs),
- )
- // If we fail to sync a particular database due to permission issue, we will continue to sync the rest of the databases.
- // We don't force dump database schema because it's rarely changed till the metadata is changed.
- if err := s.SyncDatabaseSchema(ctx, database, false /* force */); err != nil {
- slog.Debug("Failed to sync database schema",
- slog.String("instance", instanceID),
- slog.String("databaseName", database.DatabaseName),
- log.BBError(err))
- }
- }
+ s.databaseSyncMap.Store(database.UID, database)
}
}