Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: migrate to golang-lru cache (part 1) (#9277)
Danny Xude66e549f346
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.goindex 8fc8df0498..6fa7d9bd72 100644--- a/backend/api/v1/auth_service.go+++ b/backend/api/v1/auth_service.go@@ -675,7 +675,7 @@ func (s *AuthService) Logout(ctx context.Context, _ *v1pb.LogoutRequest) (*emptyif err != nil {return nil, status.Errorf(codes.Unauthenticated, err.Error())}- s.stateCfg.ExpireCache.Set(accessTokenStr, true, 1)+ s.stateCfg.ExpireCache.Add(accessTokenStr, true)if err := grpc.SetHeader(ctx, metadata.New(map[string]string{auth.GatewayMetadataAccessTokenKey: "",diff --git a/backend/component/state/state.go b/backend/component/state/state.goindex 477d967ee0..6e2042fc1e 100644--- a/backend/component/state/state.go+++ b/backend/component/state/state.go@@ -5,9 +5,10 @@ import ("sync""time"+ lru "github.com/hashicorp/golang-lru/v2"+v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"- "github.com/dgraph-io/ristretto""github.com/pkg/errors")@@ -68,17 +69,13 @@ type State struct {// TaskRunTickleChan is the tickler for task run scheduler.TaskRunTickleChan chan int- ExpireCache *ristretto.Cache+ ExpireCache *lru.Cache[string, bool]sync.Mutex}func New() (*State, error) {- expireCache, err := ristretto.NewCache(&ristretto.Config{- NumCounters: 1_000,- MaxCost: 1_000, // ~1KB- BufferItems: 64,- })+ expireCache, err := lru.New[string, bool](128)if err != nil {return nil, errors.Wrapf(err, "failed to create auth expire cache")}diff --git a/backend/enterprise/service/license.go b/backend/enterprise/service/license.goindex f4f20ce02e..d410579464 100644--- a/backend/enterprise/service/license.go+++ b/backend/enterprise/service/license.go@@ -81,7 +81,6 @@ func (s *LicenseService) LoadSubscription(ctx context.Context) enterprise.Subscrlicense := s.loadLicense(ctx)if license == nil {- s.store.RefreshSwap(false)return enterprise.Subscription{Plan: api.FREE,// -1 means not expire, just for free plan@@ -101,9 +100,6 @@ func (s *LicenseService) LoadSubscription(ctx context.Context) enterprise.SubscrOrgID: license.OrgID(),OrgName: license.OrgName,}- if !license.Trialing && license.Plan != api.FREE {- s.store.RefreshSwap(true)- }return *s.cachedSubscription}diff --git a/backend/migrator/migrator.go b/backend/migrator/migrator.goindex 3b3bb347fc..7674aa17d5 100644--- a/backend/migrator/migrator.go+++ b/backend/migrator/migrator.go@@ -42,7 +42,10 @@ func MigrateSchema(ctx context.Context, storeDB *store.DB, pgBinDir, serverVersi}defer metadataDriver.Close(ctx)- storeInstance := store.New(storeDB)+ storeInstance, err := store.New(storeDB)+ if err != nil {+ return nil, err+ }// Calculate prod cutoffSchemaVersion.cutoffSchemaVersion, err := getProdCutoffVersion()if err != nil {diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex 959794e2c0..60346b16c5 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -186,7 +186,8 @@ func TestMigrationCompatibility(t *testing.T) {db := store.NewDB(metadataConnConfig, pgBinDir, false, common.ReleaseModeDev)err = db.Open(ctx, true /* createDB */)require.NoError(t, err)- storeInstance := store.New(db)+ storeInstance, err := store.New(db)+ require.NoError(t, err)releaseVersion, err := getProdCutoffVersion()require.NoError(t, err)diff --git a/backend/server/server.go b/backend/server/server.goindex a8ff6ad32f..baa1196578 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -193,7 +193,10 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {// return s so that caller can call s.Close() to shut down the postgres server if embedded.return nil, errors.Wrap(err, "cannot open metadb")}- storeInstance := store.New(storeDB)+ storeInstance, err := store.New(storeDB)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to new store")+ }if profile.Readonly {slog.Info("Database is opened in readonly mode. Skip migration and demo data setup.")} else {diff --git a/backend/store/db_schema.go b/backend/store/db_schema.goindex 26747543e6..646d5edc20 100644--- a/backend/store/db_schema.go+++ b/backend/store/db_schema.go@@ -5,7 +5,6 @@ import ("database/sql""fmt""strings"- "time""google.golang.org/protobuf/encoding/protojson"@@ -25,12 +24,8 @@ func (s *Store) GetDBSchema(ctx context.Context, databaseID int) (*model.DBScheminstanceCount++return true})- if s.dbSchemaCache.MaxCost() != 1_000_000 || instanceCount <= 10 {- if dbSchema, ok := s.dbSchemaCache.Get(databaseID); ok {- if v, ok := dbSchema.(*model.DBSchema); ok {- return v, nil- }- }+ if v, ok := s.dbSchemaCache.Get(databaseID); ok {+ return v, nil}// Build WHERE clause.@@ -71,7 +66,7 @@ func (s *Store) GetDBSchema(ctx context.Context, databaseID int) (*model.DBSchemreturn nil, err}- s.dbSchemaCache.SetWithTTL(databaseID, dbSchema, int64(len(dbSchema.GetSchema())), 1*time.Hour)+ s.dbSchemaCache.Add(databaseID, dbSchema)return dbSchema, nil}@@ -125,7 +120,7 @@ func (s *Store) UpsertDBSchema(ctx context.Context, databaseID int, dbSchema *moreturn err}- s.dbSchemaCache.SetWithTTL(databaseID, updatedDBSchema, int64(len(updatedDBSchema.GetSchema())), 1*time.Hour)+ s.dbSchemaCache.Add(databaseID, updatedDBSchema)return nil}@@ -158,7 +153,7 @@ func (s *Store) UpdateDBSchema(ctx context.Context, databaseID int, patch *Updatreturn err}// Invalid the cache and read the value again.- s.dbSchemaCache.Del(databaseID)+ s.dbSchemaCache.Remove(databaseID)return nil}diff --git a/backend/store/sheet.go b/backend/store/sheet.goindex f445060a04..19678e976c 100644--- a/backend/store/sheet.go+++ b/backend/store/sheet.go@@ -129,10 +129,8 @@ type PatchSheetMessage struct {// GetSheetStatementByID gets the statement of a sheet by ID.func (s *Store) GetSheetStatementByID(ctx context.Context, id int) (string, error) {- if statement, ok := s.sheetStatementCache.Get(id); ok {- if v, ok := statement.(string); ok {- return v, nil- }+ if v, ok := s.sheetCache.Get(id); ok {+ return v, nil}sheets, err := s.ListSheets(ctx, &FindSheetMessage{UID: &id, LoadFull: true}, SystemBotID)@@ -146,7 +144,7 @@ func (s *Store) GetSheetStatementByID(ctx context.Context, id int) (string, erroreturn "", errors.Errorf("expected 1 sheet, got %d", len(sheets))}statement := sheets[0].Statement- s.sheetStatementCache.SetWithTTL(id, statement, int64(len(statement)), time.Hour)+ s.sheetCache.Add(id, statement)return statement, nil}@@ -396,8 +394,7 @@ func (s *Store) PatchSheet(ctx context.Context, patch *PatchSheetMessage) (*Sheeif err := tx.Commit(); err != nil {return nil, errors.Wrapf(err, "failed to commit transaction")}- s.sheetStatementCache.Del(patch.UID)-+ s.sheetCache.Remove(patch.UID)return sheet, nil}@@ -417,8 +414,7 @@ func (s *Store) DeleteSheet(ctx context.Context, sheetUID int) error {return err}- s.sheetStatementCache.Del(sheetUID)-+ s.sheetCache.Remove(sheetUID)return nil}diff --git a/backend/store/store.go b/backend/store/store.goindex f8729da2c5..213a21f0eb 100644--- a/backend/store/store.go+++ b/backend/store/store.go@@ -7,10 +7,11 @@ import ("strings""sync"- "github.com/dgraph-io/ristretto"+ lru "github.com/hashicorp/golang-lru/v2""google.golang.org/protobuf/encoding/protojson"api "github.com/bytebase/bytebase/backend/legacyapi"+ "github.com/bytebase/bytebase/backend/store/model")var (@@ -23,66 +24,51 @@ var (type Store struct {db *DB- userIDCache sync.Map // map[int]*UserMessage- environmentCache sync.Map // map[string]*EnvironmentMessage- environmentIDCache sync.Map // map[int]*EnvironmentMessage- instanceCache sync.Map // map[string]*InstanceMessage- instanceIDCache sync.Map // map[int]*InstanceMessage- databaseCache sync.Map // map[string]*DatabaseMessage- databaseIDCache sync.Map // map[int]*DatabaseMessage- projectCache sync.Map // map[string]*ProjectMessage- projectIDCache sync.Map // map[int]*ProjectMessage- projectPolicyCache sync.Map // map[string]*IAMPolicyMessage- projectIDPolicyCache sync.Map // map[int]*IAMPolicyMessage- policyCache sync.Map // map[string]*PolicyMessage- issueCache sync.Map // map[int]*IssueMessage- issueByPipelineCache sync.Map // map[int]*IssueMessage- pipelineCache sync.Map // map[int]*PipelineMessage- dbSchemaCache *ristretto.Cache // map[int]*DBSchema- settingCache sync.Map // map[string]*SettingMessage- idpCache sync.Map // map[string]*IdentityProvider- projectIDDeploymentConfigCache sync.Map // map[int]*DeploymentConfigMessage- risksCache sync.Map // []*RiskMessage, use 0 as the key- databaseGroupCache sync.Map // map[string]*DatabaseGroupMessage- databaseGroupIDCache sync.Map // map[int]*DatabaseGroupMessage- schemaGroupCache sync.Map // map[string]*SchemaGroupMessage- // sheetStatementCache caches the statement of a sheet.- sheetStatementCache *ristretto.Cache // map[sheetUID]sheetStatementString- vcsIDCache sync.Map // map[int]*ExternalVersionControlMessage+ userIDCache sync.Map // map[int]*UserMessage+ environmentCache sync.Map // map[string]*EnvironmentMessage+ environmentIDCache sync.Map // map[int]*EnvironmentMessage+ instanceCache sync.Map // map[string]*InstanceMessage+ instanceIDCache sync.Map // map[int]*InstanceMessage+ databaseCache sync.Map // map[string]*DatabaseMessage+ databaseIDCache sync.Map // map[int]*DatabaseMessage+ projectCache sync.Map // map[string]*ProjectMessage+ projectIDCache sync.Map // map[int]*ProjectMessage+ projectPolicyCache sync.Map // map[string]*IAMPolicyMessage+ projectIDPolicyCache sync.Map // map[int]*IAMPolicyMessage+ policyCache sync.Map // map[string]*PolicyMessage+ issueCache sync.Map // map[int]*IssueMessage+ issueByPipelineCache sync.Map // map[int]*IssueMessage+ pipelineCache sync.Map // map[int]*PipelineMessage+ settingCache sync.Map // map[string]*SettingMessage+ idpCache sync.Map // map[string]*IdentityProvider+ projectIDDeploymentConfigCache sync.Map // map[int]*DeploymentConfigMessage+ risksCache sync.Map // []*RiskMessage, use 0 as the key+ databaseGroupCache sync.Map // map[string]*DatabaseGroupMessage+ databaseGroupIDCache sync.Map // map[int]*DatabaseGroupMessage+ schemaGroupCache sync.Map // map[string]*SchemaGroupMessage+ vcsIDCache sync.Map // map[int]*ExternalVersionControlMessage++ sheetCache *lru.Cache[int, string]+ dbSchemaCache *lru.Cache[int, *model.DBSchema]}// New creates a new instance of Store.-func New(db *DB) *Store {- sheetStatementCache, err := ristretto.NewCache(&ristretto.Config{- NumCounters: 1_000,- MaxCost: 1_000_000_000, // ~1GB- BufferItems: 64,- })+func New(db *DB) (*Store, error) {+ sheetCache, err := lru.New[int, string](10)if err != nil {- panic(fmt.Sprintf("failed to create sheet statement cache: %v", err))+ return nil, err}- dbsCache, err := ristretto.NewCache(&ristretto.Config{- NumCounters: 10_000,- MaxCost: 1_000_000, // ~1MB- BufferItems: 64,- })+ dbSchemaCache, err := lru.New[int, *model.DBSchema](100)if err != nil {- panic(fmt.Sprintf("failed to create sheet statement cache: %v", err))+ return nil, err}+return &Store{- db: db,- sheetStatementCache: sheetStatementCache,- dbSchemaCache: dbsCache,- }-}+ db: db,-// RefreshSwap updates the cache.-func (s *Store) RefreshSwap(refresh bool) {- cost := int64(1_000_000)- if refresh {- cost = 500_000_000- }- s.dbSchemaCache.UpdateMaxCost(cost)+ sheetCache: sheetCache,+ dbSchemaCache: dbSchemaCache,+ }, nil}// Close closes underlying db.diff --git a/go.mod b/go.modindex 71a0f57381..f727751b9f 100644--- a/go.mod+++ b/go.mod@@ -19,7 +19,6 @@ require (github.com/bytebase/snowsql-parser v0.0.0-20230706111031-cafd8faa2dc9github.com/cenkalti/backoff/v4 v4.2.1github.com/coreos/go-oidc v2.2.1+incompatible- github.com/dgraph-io/ristretto v0.1.1github.com/github/gh-ost v1.1.5github.com/go-ego/gse v0.80.2github.com/go-ldap/ldap/v3 v3.4.6@@ -33,6 +32,7 @@ require (github.com/gosimple/slug v1.13.1github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.1github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0+ github.com/hashicorp/golang-lru/v2 v2.0.7github.com/improbable-eng/grpc-web v0.15.0github.com/jackc/pgtype v1.14.0github.com/jackc/pgx/v4 v4.18.1@@ -97,14 +97,13 @@ require (github.com/apache/thrift v0.19.0 // indirectgithub.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirectgithub.com/danieljoos/wincred v1.2.0 // indirect- github.com/dustin/go-humanize v1.0.1 // indirect+ github.com/dgraph-io/ristretto v0.1.1 // indirectgithub.com/dvsekhvalnov/jose2go v1.5.0 // indirectgithub.com/ghodss/yaml v1.0.0 // indirectgithub.com/go-asn1-ber/asn1-ber v1.5.5 // indirectgithub.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirectgithub.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirectgithub.com/golang-sql/sqlexp v0.1.0 // indirect- github.com/golang/glog v1.1.2 // indirectgithub.com/google/s2a-go v0.1.7 // indirectgithub.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirectgithub.com/hashicorp/go-uuid v1.0.3 // indirectdiff --git a/go.sum b/go.sumindex a595413ae9..d7c64d1ba2 100644--- a/go.sum+++ b/go.sum@@ -481,6 +481,8 @@ github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=