Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Introduce a cache leveraging fastcache
天舟dc047aad2907
diff --git a/api/cache.go b/api/cache.gonew file mode 100644index 0000000000..cda9eee7b1--- /dev/null+++ b/api/cache.go@@ -0,0 +1,12 @@+package api++type CacheNamespace string++const (+ PrincipalCache CacheNamespace = "p"+)++type CacheService interface {+ FindCache(namespace CacheNamespace, id int, entry interface{}) (bool, error)+ UpsertCache(namespace CacheNamespace, id int, entry interface{}) error+}diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.goindex 3cd2d9daf9..c62141eb7a 100644--- a/bin/server/cmd/root.go+++ b/bin/server/cmd/root.go@@ -243,7 +243,7 @@ func (m *main) Run() error {m.db = dbserver := server.NewServer(m.l, version, host, port, m.profile.mode, config.secret, readonly, demo, debug)- server.PrincipalService = store.NewPrincipalService(m.l, db)+ server.PrincipalService = store.NewPrincipalService(m.l, db, server.CacheService)server.MemberService = store.NewMemberService(m.l, db)server.ProjectService = store.NewProjectService(m.l, db)server.ProjectMemberService = store.NewProjectMemberService(m.l, db)diff --git a/go.mod b/go.modindex 70e31870f5..943cea4a0a 100644--- a/go.mod+++ b/go.mod@@ -3,9 +3,11 @@ module github.com/bytebase/bytebasego 1.16require (+ github.com/VictoriaMetrics/fastcache v1.6.0github.com/casbin/casbin/v2 v2.29.2github.com/dgrijalva/jwt-go v3.2.0+incompatiblegithub.com/go-sql-driver/mysql v1.6.0+ github.com/golang/snappy v0.0.4 // indirectgithub.com/google/jsonapi v1.0.0github.com/labstack/echo/v4 v4.2.2github.com/mattn/go-sqlite3 v1.14.7@@ -15,4 +17,5 @@ require (go.uber.org/multierr v1.7.0 // indirectgo.uber.org/zap v1.17.0golang.org/x/crypto v0.0.0-20210506145944-38f3c27a63bf+ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c // indirect)diff --git a/go.sum b/go.sumindex 49e725c855..228f1409e1 100644--- a/go.sum+++ b/go.sum@@ -41,6 +41,10 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible h1:1G1pk05UrOh0NlF1oeaaix1x8XzrfjIDK47TY0Zehcw=github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=+github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o=+github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw=+github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8=+github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM=github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=@@ -51,6 +55,8 @@ github.com/casbin/casbin/v2 v2.1.0/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3ngithub.com/casbin/casbin/v2 v2.29.2 h1:a1lsr3ZFh9IQ+7L8L36ddyTebofxH/XoHmRh6iI7Rtg=github.com/casbin/casbin/v2 v2.29.2/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg=github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=+github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=+github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=@@ -113,6 +119,9 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSwgithub.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM=github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=+github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=+github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=+github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=@@ -422,10 +431,12 @@ golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wgolang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE=golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I=+golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=diff --git a/server/cache.go b/server/cache.gonew file mode 100644index 0000000000..4a2a52523c--- /dev/null+++ b/server/cache.go@@ -0,0 +1,62 @@+package server++import (+ "bytes"+ "encoding/binary"+ "encoding/gob"+ "fmt"++ "github.com/VictoriaMetrics/fastcache"+ "github.com/bytebase/bytebase/api"+ "go.uber.org/zap"+)++var (+ // 32 MiB+ CACHE_SIZE = 1024 * 1024 * 32+ _ api.CacheService = (*CacheService)(nil)+)++// CacheService implements a cache.+type CacheService struct {+ cache *fastcache.Cache++ l *zap.Logger+}++func NewCacheService(logger *zap.Logger) *CacheService {+ return &CacheService{+ cache: fastcache.New(CACHE_SIZE),+ l: logger,+ }+}++func (s *CacheService) FindCache(namespace api.CacheNamespace, id int, entry interface{}) (bool, error) {+ buf1 := []byte{0, 0, 0, 0}+ binary.LittleEndian.PutUint32(buf1, uint32(id))++ buf2, has := s.cache.HasGet(nil, append([]byte(namespace), buf1...))+ if has {+ dec := gob.NewDecoder(bytes.NewReader(buf2))+ if err := dec.Decode(entry); err != nil {+ return false, fmt.Errorf("failed to decode entry for cache namespace: %s, error: %w", namespace, err)+ }+ return true, nil+ }++ return false, nil+}++func (s *CacheService) UpsertCache(namespace api.CacheNamespace, id int, entry interface{}) error {+ buf1 := []byte{0, 0, 0, 0}+ binary.LittleEndian.PutUint32(buf1, uint32(id))++ var buf2 bytes.Buffer+ enc := gob.NewEncoder(&buf2)+ if err := enc.Encode(entry); err != nil {+ return fmt.Errorf("failed to encode entry for cache namespace: %s, error: %w", namespace, err)+ }+ s.cache.Set(append([]byte(namespace), buf1...), buf2.Bytes())++ return nil+}diff --git a/server/server.go b/server/server.goindex 7e1bb1c53e..ba75aeb278 100644--- a/server/server.go+++ b/server/server.go@@ -23,6 +23,8 @@ type Server struct {TaskScheduler *TaskSchedulerSchemaSyncer *SchemaSyncer+ CacheService api.CacheService+PrincipalService api.PrincipalServiceMemberService api.MemberServiceProjectService api.ProjectService@@ -97,17 +99,18 @@ func NewServer(logger *zap.Logger, version string, host string, port int, mode se.GET("/assets/*", echo.WrapHandler(assetHandler))s := &Server{- l: logger,- e: e,- version: version,- mode: mode,- host: host,- port: port,- startedTs: time.Now().Unix(),- secret: secret,- readonly: readonly,- demo: demo,- plan: api.TEAM,+ l: logger,+ CacheService: NewCacheService(logger),+ e: e,+ version: version,+ mode: mode,+ host: host,+ port: port,+ startedTs: time.Now().Unix(),+ secret: secret,+ readonly: readonly,+ demo: demo,+ plan: api.TEAM,}if !readonly {diff --git a/store/principal.go b/store/principal.goindex 254cb2977f..1f31eefef8 100644--- a/store/principal.go+++ b/store/principal.go@@ -18,11 +18,13 @@ var (type PrincipalService struct {l *zap.Loggerdb *DB++ cache api.CacheService}// NewPrincipalService returns a new instance of PrincipalService.-func NewPrincipalService(logger *zap.Logger, db *DB) *PrincipalService {- return &PrincipalService{l: logger, db: db}+func NewPrincipalService(logger *zap.Logger, db *DB, cache api.CacheService) *PrincipalService {+ return &PrincipalService{l: logger, db: db, cache: cache}}// CreatePrincipal creates a new principal.@@ -42,6 +44,10 @@ func (s *PrincipalService) CreatePrincipal(ctx context.Context, create *api.Prinreturn nil, FormatError(err)}+ if err := s.cache.UpsertCache(api.PrincipalCache, principal.ID, principal); err != nil {+ return nil, err+ }+return principal, nil}@@ -58,6 +64,14 @@ func (s *PrincipalService) FindPrincipalList(ctx context.Context) ([]*api.Princireturn []*api.Principal{}, err}+ if err == nil {+ for _, principal := range list {+ if err := s.cache.UpsertCache(api.PrincipalCache, principal.ID, principal); err != nil {+ return nil, err+ }+ }+ }+return list, nil}@@ -65,6 +79,17 @@ func (s *PrincipalService) FindPrincipalList(ctx context.Context) ([]*api.Princi// Returns ENOTFOUND if no matching record.// Returns ECONFLICT if finding more than 1 matching records.func (s *PrincipalService) FindPrincipal(ctx context.Context, find *api.PrincipalFind) (*api.Principal, error) {+ if find.ID != nil {+ principal := &api.Principal{}+ has, err := s.cache.FindCache(api.PrincipalCache, *find.ID, principal)+ if err != nil {+ return nil, err+ }+ if has {+ return principal, nil+ }+ }+tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)@@ -79,6 +104,11 @@ func (s *PrincipalService) FindPrincipal(ctx context.Context, find *api.Principa} else if len(list) > 1 {return nil, &bytebase.Error{Code: bytebase.ECONFLICT, Message: fmt.Sprintf("found %d principals with filter %+v, expect 1", len(list), find)}}++ if err := s.cache.UpsertCache(api.PrincipalCache, list[0].ID, list[0]); err != nil {+ return nil, err+ }+return list[0], nil}@@ -100,6 +130,10 @@ func (s *PrincipalService) PatchPrincipal(ctx context.Context, patch *api.Princireturn nil, FormatError(err)}+ if err := s.cache.UpsertCache(api.PrincipalCache, principal.ID, principal); err != nil {+ return nil, err+ }+return principal, nil}