Skip to content

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

refactor: decouple api/service/store packages for Policy (#971)

Yilong Li94a1faaa24c5
diff --git a/api/policy.go b/api/policy.go
index 53c1834dff..7452db5bbb 100644
--- a/api/policy.go
+++ b/api/policy.go
@@ -1,7 +1,6 @@
package api
import (
- "context"
"encoding/json"
"fmt"
)
@@ -42,48 +41,6 @@ var (
}
)
-// PolicyRaw is the store model for an Policy.
-// Fields have exactly the same meanings as Policy.
-type PolicyRaw struct {
- ID int
-
- // Standard fields
- RowStatus RowStatus
- CreatorID int
- CreatedTs int64
- UpdaterID int
- UpdatedTs int64
-
- // Related fields
- EnvironmentID int
-
- // Domain specific fields
- Type PolicyType
- Payload string
-}
-
-// ToPolicy creates an instance of Policy based on the PolicyRaw.
-// This is intended to be called when we need to compose an Policy relationship.
-func (raw *PolicyRaw) ToPolicy() *Policy {
- return &Policy{
- ID: raw.ID,
-
- // Standard fields
- RowStatus: raw.RowStatus,
- CreatorID: raw.CreatorID,
- CreatedTs: raw.CreatedTs,
- UpdaterID: raw.UpdaterID,
- UpdatedTs: raw.UpdatedTs,
-
- // Related fields
- EnvironmentID: raw.EnvironmentID,
-
- // Domain specific fields
- Type: raw.Type,
- Payload: raw.Payload,
- }
-}
-
// Policy is the API message for a policy.
type Policy struct {
ID int `jsonapi:"primary,policy"`
@@ -133,14 +90,6 @@ type PolicyUpsert struct {
Payload string `jsonapi:"attr,payload"`
}
-// PolicyService is the backend for policies.
-type PolicyService interface {
- FindPolicy(ctx context.Context, find *PolicyFind) (*PolicyRaw, error)
- UpsertPolicy(ctx context.Context, upsert *PolicyUpsert) (*PolicyRaw, error)
- GetBackupPlanPolicy(ctx context.Context, environmentID int) (*BackupPlanPolicy, error)
- GetPipelineApprovalPolicy(ctx context.Context, environmentID int) (*PipelineApprovalPolicy, error)
-}
-
// PipelineApprovalPolicy is the policy configuration for pipeline approval
type PipelineApprovalPolicy struct {
Value PipelineApprovalValue `json:"value"`
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index 991559c569..de9952b0d9 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -375,12 +375,11 @@ func (m *Main) Run(ctx context.Context) error {
s := server.NewServer(m.l, storeInstance, m.lvl, version, host, m.profile.port, frontendHost, frontendPort, m.profile.datastorePort, m.profile.mode, m.profile.dataDir, m.profile.backupRunnerInterval, config.secret, readonly, demo, debug)
s.SettingService = settingService
- s.PolicyService = store.NewPolicyService(m.l, db, cacheService)
s.ProjectService = store.NewProjectService(m.l, db, cacheService)
s.ProjectMemberService = store.NewProjectMemberService(m.l, db)
s.ProjectWebhookService = store.NewProjectWebhookService(m.l, db)
- s.BackupService = store.NewBackupService(m.l, db, s.PolicyService)
- s.DatabaseService = store.NewDatabaseService(m.l, db, cacheService, s.PolicyService, s.BackupService)
+ s.BackupService = store.NewBackupService(m.l, db, storeInstance)
+ s.DatabaseService = store.NewDatabaseService(m.l, db, cacheService, storeInstance, s.BackupService)
s.InstanceService = store.NewInstanceService(m.l, db, cacheService, s.DatabaseService, storeInstance)
s.InstanceUserService = store.NewInstanceUserService(m.l, db)
s.TableService = store.NewTableService(m.l, db)
diff --git a/server/acl.go b/server/acl.go
index 0a7476fd87..1cbeae411b 100644
--- a/server/acl.go
+++ b/server/acl.go
@@ -44,10 +44,7 @@ func aclMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Hand
// Gets principal id from the context.
principalID := c.Get(getPrincipalIDContextKey()).(int)
- memberFind := &api.MemberFind{
- PrincipalID: &principalID,
- }
- member, err := s.store.FindMember(ctx, memberFind)
+ member, err := s.store.GetMemberByPrincipalID(ctx, principalID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to process authorize request.").SetInternal(err)
}
diff --git a/server/actuator.go b/server/actuator.go
index f30422200b..7944a0cf86 100644
--- a/server/actuator.go
+++ b/server/actuator.go
@@ -25,7 +25,7 @@ func (s *Server) registerActuatorRoutes(g *echo.Group) {
find := &api.MemberFind{
Role: &findRole,
}
- memberList, err := s.store.FindMemberList(ctx, find)
+ memberList, err := s.store.FindMember(ctx, find)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch admin setup status").SetInternal(err)
}
diff --git a/server/anomaly_scanner.go b/server/anomaly_scanner.go
index 8c8ea91b78..145272781a 100644
--- a/server/anomaly_scanner.go
+++ b/server/anomaly_scanner.go
@@ -66,7 +66,7 @@ func (s *AnomalyScanner) Run(ctx context.Context, wg *sync.WaitGroup) {
backupPlanPolicyMap := make(map[int]*api.BackupPlanPolicy)
for _, env := range envList {
- policy, err := s.server.PolicyService.GetBackupPlanPolicy(ctx, env.ID)
+ policy, err := s.server.store.GetBackupPlanPolicyByEnvID(ctx, env.ID)
if err != nil {
s.l.Error("Failed to retrieve backup policy",
zap.String("environment", env.Name),
diff --git a/server/auth.go b/server/auth.go
index c78d52c716..8aea0d96fc 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -141,10 +141,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
}
// test the status of this user
- memberFind := &api.MemberFind{
- PrincipalID: &user.ID,
- }
- member, err := s.store.FindMember(ctx, memberFind)
+ member, err := s.store.GetMemberByPrincipalID(ctx, user.ID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)
}
@@ -227,7 +224,7 @@ func trySignUp(ctx context.Context, s *Server, signUp *api.SignUp, CreatorID int
find := &api.MemberFind{
Role: &findRole,
}
- memberList, err := s.store.FindMemberList(ctx, find)
+ memberList, err := s.store.FindMember(ctx, find)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to sign up").SetInternal(err)
}
diff --git a/server/issue.go b/server/issue.go
index 1a7c6c6ae3..3c4e53790e 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -664,7 +664,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.I
}
taskStatus := api.TaskPendingApproval
- policy, err := s.PolicyService.GetPipelineApprovalPolicy(ctx, instance.EnvironmentID)
+ policy, err := s.store.GetPipelineApprovalPolicy(ctx, instance.EnvironmentID)
if err != nil {
return nil, fmt.Errorf("failed to get approval policy for environment ID %v, error %v", instance.EnvironmentID, err)
}
@@ -819,7 +819,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.I
environmentSet[database.Instance.Environment.Name] = true
environmentID = database.Instance.EnvironmentID
taskStatus := api.TaskPendingApproval
- policy, err := s.PolicyService.GetPipelineApprovalPolicy(ctx, environmentID)
+ policy, err := s.store.GetPipelineApprovalPolicy(ctx, environmentID)
if err != nil {
return nil, fmt.Errorf("failed to get approval policy for environment ID %v, error %v", environmentID, err)
}
@@ -865,7 +865,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.I
}
taskStatus := api.TaskPendingApproval
- policy, err := s.PolicyService.GetPipelineApprovalPolicy(ctx, database.Instance.EnvironmentID)
+ policy, err := s.store.GetPipelineApprovalPolicy(ctx, database.Instance.EnvironmentID)
if err != nil {
return nil, fmt.Errorf("failed to get approval policy for environment ID %v, error %v", database.Instance.EnvironmentID, err)
}
diff --git a/server/member.go b/server/member.go
index 091fc20dc9..d8dc937ced 100644
--- a/server/member.go
+++ b/server/member.go
@@ -77,7 +77,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
g.GET("/member", func(c echo.Context) error {
ctx := context.Background()
memberFind := &api.MemberFind{}
- memberList, err := s.store.FindMemberList(ctx, memberFind)
+ memberList, err := s.store.FindMember(ctx, memberFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch member list").SetInternal(err)
}
@@ -96,10 +96,7 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
}
- memberFind := &api.MemberFind{
- ID: &id,
- }
- member, err := s.store.FindMember(ctx, memberFind)
+ member, err := s.store.GetMemberByID(ctx, id)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find member ID: %d", id)).SetInternal(err)
}
diff --git a/server/policy.go b/server/policy.go
index 2d107669db..e14ad200e9 100644
--- a/server/policy.go
+++ b/server/policy.go
@@ -56,16 +56,11 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusForbidden, err.Error()).SetInternal(err)
}
- policyRaw, err := s.PolicyService.UpsertPolicy(ctx, policyUpsert)
+ policy, err := s.store.UpsertPolicy(ctx, policyUpsert)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to set policy for type %q", pType)).SetInternal(err)
}
- policy, err := s.composePolicyRelationship(ctx, policyRaw)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to compose policy relationship for type %q", pType)).SetInternal(err)
- }
-
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, policy); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create set policy response").SetInternal(err)
@@ -87,16 +82,11 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
policyFind.Type = &pType
policyFind.EnvironmentID = &environmentID
- policyRaw, err := s.PolicyService.FindPolicy(ctx, policyFind)
+ policy, err := s.store.GetPolicy(ctx, policyFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get policy for type %q", pType)).SetInternal(err)
}
- policy, err := s.composePolicyRelationship(ctx, policyRaw)
- if err != nil {
- return err
- }
-
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, policy); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal get policy response: %v", pType)).SetInternal(err)
@@ -104,27 +94,3 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
return nil
})
}
-
-func (s *Server) composePolicyRelationship(ctx context.Context, raw *api.PolicyRaw) (*api.Policy, error) {
- policy := raw.ToPolicy()
-
- creator, err := s.store.GetPrincipalByID(ctx, policy.CreatorID)
- if err != nil {
- return nil, err
- }
- policy.Creator = creator
-
- updater, err := s.store.GetPrincipalByID(ctx, policy.UpdaterID)
- if err != nil {
- return nil, err
- }
- policy.Updater = updater
-
- env, err := s.store.GetEnvironmentByID(ctx, policy.EnvironmentID)
- if err != nil {
- return nil, err
- }
- policy.Environment = env
-
- return policy, nil
-}
diff --git a/server/server.go b/server/server.go
index f7aaf30c60..eced4bedaa 100644
--- a/server/server.go
+++ b/server/server.go
@@ -37,7 +37,6 @@ type Server struct {
ActivityManager *ActivityManager
SettingService api.SettingService
- PolicyService api.PolicyService
ProjectService api.ProjectService
ProjectMemberService api.ProjectMemberService
ProjectWebhookService api.ProjectWebhookService
diff --git a/store/backup.go b/store/backup.go
index 64e030d3aa..8246b01068 100644
--- a/store/backup.go
+++ b/store/backup.go
@@ -17,14 +17,14 @@ var (
// BackupService represents a service for managing backup.
type BackupService struct {
- l *zap.Logger
- db *DB
- policyService api.PolicyService
+ l *zap.Logger
+ db *DB
+ store *Store
}
// NewBackupService returns a new instance of BackupService.
-func NewBackupService(logger *zap.Logger, db *DB, policyService api.PolicyService) *BackupService {
- return &BackupService{l: logger, db: db, policyService: policyService}
+func NewBackupService(logger *zap.Logger, db *DB, store *Store) *BackupService {
+ return &BackupService{l: logger, db: db, store: store}
}
// CreateBackup creates a new backup.
@@ -364,7 +364,7 @@ func (s *BackupService) findBackupSetting(ctx context.Context, tx *sql.Tx, find
// UpsertBackupSetting sets the backup settings for a database.
func (s *BackupService) UpsertBackupSetting(ctx context.Context, upsert *api.BackupSettingUpsert) (*api.BackupSettingRaw, error) {
- backupPlanPolicy, err := s.policyService.GetBackupPlanPolicy(ctx, upsert.EnvironmentID)
+ backupPlanPolicy, err := s.store.GetBackupPlanPolicyByEnvID(ctx, upsert.EnvironmentID)
if err != nil {
return nil, err
}
diff --git a/store/database.go b/store/database.go
index 50e0c2fb21..41113bd928 100644
--- a/store/database.go
+++ b/store/database.go
@@ -22,17 +22,17 @@ type DatabaseService struct {
db *DB
cache api.CacheService
- policyService api.PolicyService
+ store *Store
backupService api.BackupService
}
// NewDatabaseService returns a new instance of DatabaseService.
-func NewDatabaseService(logger *zap.Logger, db *DB, cache api.CacheService, policyService api.PolicyService, backupService api.BackupService) *DatabaseService {
+func NewDatabaseService(logger *zap.Logger, db *DB, cache api.CacheService, store *Store, backupService api.BackupService) *DatabaseService {
return &DatabaseService{
l: logger,
db: db,
cache: cache,
- policyService: policyService,
+ store: store,
backupService: backupService,
}
}
@@ -59,7 +59,7 @@ func (s *DatabaseService) CreateDatabase(ctx context.Context, create *api.Databa
// CreateDatabaseTx creates a database with a transaction.
func (s *DatabaseService) CreateDatabaseTx(ctx context.Context, tx *sql.Tx, create *api.DatabaseCreate) (*api.DatabaseRaw, error) {
- backupPlanPolicy, err := s.policyService.GetBackupPlanPolicy(ctx, create.EnvironmentID)
+ backupPlanPolicy, err := s.store.GetBackupPlanPolicyByEnvID(ctx, create.EnvironmentID)
if err != nil {
return nil, err
}
diff --git a/store/member.go b/store/member.go
index 6498e4bf53..17e06ba5c3 100644
--- a/store/member.go
+++ b/store/member.go
@@ -61,9 +61,9 @@ func (s *Store) CreateMember(ctx context.Context, create *api.MemberCreate) (*ap
return member, nil
}
-// FindMemberList finds a list of Member instances
-func (s *Store) FindMemberList(ctx context.Context, find *api.MemberFind) ([]*api.Member, error) {
- memberRawList, err := s.findMemberListRaw(ctx, find)
+// FindMember finds a list of Member instances
+func (s *Store) FindMember(ctx context.Context, find *api.MemberFind) ([]*api.Member, error) {
+ memberRawList, err := s.findMemberRaw(ctx, find)
if err != nil {
return nil, fmt.Errorf("Failed to find Member list, error[%w]", err)
}
@@ -78,9 +78,24 @@ func (s *Store) FindMemberList(ctx context.Context, find *api.MemberFind) ([]*ap
return memberList, nil
}
-// FindMember finds an instance of Member
-func (s *Store) FindMember(ctx context.Context, find *api.MemberFind) (*api.Member, error) {
- memberRaw, err := s.findMemberRaw(ctx, find)
+// GetMemberByPrincipalID gets an instance of Member
+func (s *Store) GetMemberByPrincipalID(ctx context.Context, id int) (*api.Member, error) {
+ find := &api.MemberFind{PrincipalID: &id}
+ memberRaw, err := s.getMemberRaw(ctx, find)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to find Member with MemberFind[%+v], error[%w]", find, err)
+ }
+ member, err := s.composeMember(ctx, memberRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Member role with memberRaw[%+v], error[%w]", memberRaw, err)
+ }
+ return member, nil
+}
+
+// GetMemberByID gets an instance of Member
+func (s *Store) GetMemberByID(ctx context.Context, id int) (*api.Member, error) {
+ find := &api.MemberFind{ID: &id}
+ memberRaw, err := s.getMemberRaw(ctx, find)
if err != nil {
return nil, fmt.Errorf("Failed to find Member with MemberFind[%+v], error[%w]", find, err)
}
@@ -132,15 +147,15 @@ func (s *Store) createMemberRaw(ctx context.Context, create *api.MemberCreate) (
return member, nil
}
-// findMemberListRaw retrieves a list of memberRaw instances.
-func (s *Store) findMemberListRaw(ctx context.Context, find *api.MemberFind) ([]*memberRaw, error) {
+// findMemberRaw retrieves a list of memberRaw instances.
+func (s *Store) findMemberRaw(ctx context.Context, find *api.MemberFind) ([]*memberRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- memberRawList, err := findMemberListImpl(ctx, tx.PTx, find)
+ memberRawList, err := findMemberImpl(ctx, tx.PTx, find)
if err != nil {
return nil, err
}
@@ -154,9 +169,9 @@ func (s *Store) findMemberListRaw(ctx context.Context, find *api.MemberFind) ([]
return memberRawList, nil
}
-// findMemberRaw retrieves an instance of memberRaw.
+// getMemberRaw retrieves an instance of memberRaw.
// Returns ECONFLICT if finding more than 1 matching records.
-func (s *Store) findMemberRaw(ctx context.Context, find *api.MemberFind) (*memberRaw, error) {
+func (s *Store) getMemberRaw(ctx context.Context, find *api.MemberFind) (*memberRaw, error) {
if find.PrincipalID != nil {
memberRaw := &memberRaw{}
has, err := s.cache.FindCache(api.MemberCache, *find.PrincipalID, memberRaw)
@@ -174,7 +189,7 @@ func (s *Store) findMemberRaw(ctx context.Context, find *api.MemberFind) (*membe
}
defer tx.PTx.Rollback()
- list, err := findMemberListImpl(ctx, tx.PTx, find)
+ list, err := findMemberImpl(ctx, tx.PTx, find)
if err != nil {
return nil, err
}
@@ -285,7 +300,7 @@ func createMemberImpl(ctx context.Context, tx *sql.Tx, create *api.MemberCreate)
return &memberRaw, nil
}
-func findMemberListImpl(ctx context.Context, tx *sql.Tx, find *api.MemberFind) ([]*memberRaw, error) {
+func findMemberImpl(ctx context.Context, tx *sql.Tx, find *api.MemberFind) ([]*memberRaw, error) {
// Build WHERE clause.
where, args := []string{"1 = 1"}, []interface{}{}
if v := find.ID; v != nil {
diff --git a/store/policy.go b/store/policy.go
index 67e1f33fdf..368081ff77 100644
--- a/store/policy.go
+++ b/store/policy.go
@@ -8,29 +8,133 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
- "go.uber.org/zap"
)
-var (
- _ api.PolicyService = (*PolicyService)(nil)
-)
+// policyRaw is the store model for an Policy.
+// Fields have exactly the same meanings as Policy.
+type policyRaw struct {
+ ID int
+
+ // Standard fields
+ RowStatus api.RowStatus
+ CreatorID int
+ CreatedTs int64
+ UpdaterID int
+ UpdatedTs int64
+
+ // Related fields
+ EnvironmentID int
+
+ // Domain specific fields
+ Type api.PolicyType
+ Payload string
+}
+
+// toPolicy creates an instance of Policy based on the PolicyRaw.
+// This is intended to be called when we need to compose an Policy relationship.
+func (raw *policyRaw) toPolicy() *api.Policy {
+ return &api.Policy{
+ ID: raw.ID,
+
+ // Standard fields
+ RowStatus: raw.RowStatus,
+ CreatorID: raw.CreatorID,
+ CreatedTs: raw.CreatedTs,
+ UpdaterID: raw.UpdaterID,
+ UpdatedTs: raw.UpdatedTs,
+
+ // Related fields
+ EnvironmentID: raw.EnvironmentID,
+
+ // Domain specific fields
+ Type: raw.Type,
+ Payload: raw.Payload,
+ }
+}
-// PolicyService represents a service for managing environment based policies.
-type PolicyService struct {
- l *zap.Logger
- db *DB
+// UpsertPolicy upserts an instance of Policy
+func (s *Store) UpsertPolicy(ctx context.Context, upsert *api.PolicyUpsert) (*api.Policy, error) {
+ policyRaw, err := s.upsertPolicyRaw(ctx, upsert)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to upsert policy with PolicyUpsert[%+v], error[%w]", upsert, err)
+ }
+ policy, err := s.composePolicy(ctx, policyRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose policy with policyRaw[%+v], error[%w]", policyRaw, err)
+ }
+ return policy, nil
+}
- cache api.CacheService
+// GetPolicy gets a policy
+func (s *Store) GetPolicy(ctx context.Context, find *api.PolicyFind) (*api.Policy, error) {
+ policyRaw, err := s.getPolicyRaw(ctx, find)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to get policy with PolicyFind[%+v], error[%w]", find, err)
+ }
+ policy, err := s.composePolicy(ctx, policyRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose policy with policyRaw[%+v], error[%w]", policyRaw, err)
+ }
+ return policy, nil
}
-// NewPolicyService returns a new instance of PolicyService.
-func NewPolicyService(logger *zap.Logger, db *DB, cache api.CacheService) *PolicyService {
- return &PolicyService{l: logger, db: db, cache: cache}
+// GetBackupPlanPolicyByEnvID will get the backup plan policy for an environment.
+func (s *Store) GetBackupPlanPolicyByEnvID(ctx context.Context, environmentID int) (*api.BackupPlanPolicy, error) {
+ pType := api.PolicyTypeBackupPlan
+ policy, err := s.getPolicyRaw(ctx, &api.PolicyFind{
+ EnvironmentID: &environmentID,
+ Type: &pType,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return api.UnmarshalBackupPlanPolicy(policy.Payload)
}
-// FindPolicy finds the policy for an environment.
+// GetPipelineApprovalPolicy will get the pipeline approval policy for an environment.
+func (s *Store) GetPipelineApprovalPolicy(ctx context.Context, environmentID int) (*api.PipelineApprovalPolicy, error) {
+ pType := api.PolicyTypePipelineApproval
+ policy, err := s.getPolicyRaw(ctx, &api.PolicyFind{
+ EnvironmentID: &environmentID,
+ Type: &pType,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return api.UnmarshalPipelineApprovalPolicy(policy.Payload)
+}
+
+//
+// private functions
+//
+
+func (s *Store) composePolicy(ctx context.Context, raw *policyRaw) (*api.Policy, error) {
+ policy := raw.toPolicy()
+
+ creator, err := s.GetPrincipalByID(ctx, policy.CreatorID)
+ if err != nil {
+ return nil, err
+ }
+ policy.Creator = creator
+
+ updater, err := s.GetPrincipalByID(ctx, policy.UpdaterID)
+ if err != nil {
+ return nil, err
+ }
+ policy.Updater = updater
+
+ env, err := s.GetEnvironmentByID(ctx, policy.EnvironmentID)
+ if err != nil {
+ return nil, err
+ }
+ policy.Environment = env
+
+ return policy, nil
+}
+
+// getPolicyRaw finds the policy for an environment.
// Returns ECONFLICT if finding more than 1 matching records.
-func (s *PolicyService) FindPolicy(ctx context.Context, find *api.PolicyFind) (*api.PolicyRaw, error) {
+func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policyRaw, error) {
// Validate policy type existence.
if find.Type != nil && *find.Type != "" {
if err := api.ValidatePolicy(*find.Type, ""); err != nil {
@@ -43,14 +147,14 @@ func (s *PolicyService) FindPolicy(ctx context.Context, find *api.PolicyFind) (*
}
defer tx.PTx.Rollback()
- policyRawList, err := s.findPolicy(ctx, tx.PTx, find)
- var ret *api.PolicyRaw
+ policyRawList, err := s.findPolicyImpl(ctx, tx.PTx, find)
+ var ret *policyRaw
if err != nil {
return nil, err
}
if len(policyRawList) == 0 {
- ret = &api.PolicyRaw{
+ ret = &policyRaw{
CreatorID: api.SystemBotID,
UpdaterID: api.SystemBotID,
EnvironmentID: *find.EnvironmentID,
@@ -73,7 +177,7 @@ func (s *PolicyService) FindPolicy(ctx context.Context, find *api.PolicyFind) (*
return ret, nil
}
-func (s *PolicyService) findPolicy(ctx context.Context, tx *sql.Tx, find *api.PolicyFind) ([]*api.PolicyRaw, error) {
+func (s *Store) findPolicyImpl(ctx context.Context, tx *sql.Tx, find *api.PolicyFind) ([]*policyRaw, error) {
// Build WHERE clause.
where, args := []string{"1 = 1"}, []interface{}{}
if v := find.ID; v != nil {
@@ -106,9 +210,9 @@ func (s *PolicyService) findPolicy(ctx context.Context, tx *sql.Tx, find *api.Po
defer rows.Close()
// Iterate over result set and deserialize rows into policyRawList.
- var policyRawList []*api.PolicyRaw
+ var policyRawList []*policyRaw
for rows.Next() {
- var policyRaw api.PolicyRaw
+ var policyRaw policyRaw
if err := rows.Scan(
&policyRaw.ID,
&policyRaw.CreatorID,
@@ -131,8 +235,8 @@ func (s *PolicyService) findPolicy(ctx context.Context, tx *sql.Tx, find *api.Po
return policyRawList, nil
}
-// UpsertPolicy sets a policy for an environment.
-func (s *PolicyService) UpsertPolicy(ctx context.Context, upsert *api.PolicyUpsert) (*api.PolicyRaw, error) {
+// upsertPolicyRaw sets a policy for an environment.
+func (s *Store) upsertPolicyRaw(ctx context.Context, upsert *api.PolicyUpsert) (*policyRaw, error) {
// Validate policy.
if upsert.Type != "" {
if err := api.ValidatePolicy(upsert.Type, upsert.Payload); err != nil {
@@ -145,7 +249,7 @@ func (s *PolicyService) UpsertPolicy(ctx context.Context, upsert *api.PolicyUpse
}
defer tx.PTx.Rollback()
- policy, err := s.upsertPolicy(ctx, tx.PTx, upsert)
+ policy, err := s.upsertPolicyImpl(ctx, tx.PTx, upsert)
if err != nil {
return nil, err
}
@@ -157,8 +261,8 @@ func (s *PolicyService) UpsertPolicy(ctx context.Context, upsert *api.PolicyUpse
return policy, nil
}
-// upsertPolicy updates an existing policy.
-func (s *PolicyService) upsertPolicy(ctx context.Context, tx *sql.Tx, upsert *api.PolicyUpsert) (*api.PolicyRaw, error) {
+// upsertPolicyImpl updates an existing policy.
+func (s *Store) upsertPolicyImpl(ctx context.Context, tx *sql.Tx, upsert *api.PolicyUpsert) (*policyRaw, error) {
// Upsert row into policy.
if upsert.Payload == "" {
upsert.Payload = "{}"
@@ -189,7 +293,7 @@ func (s *PolicyService) upsertPolicy(ctx context.Context, tx *sql.Tx, upsert *ap
defer row.Close()
row.Next()
- var policyRaw api.PolicyRaw
+ var policyRaw policyRaw
if err := row.Scan(
&policyRaw.ID,
&policyRaw.CreatorID,
@@ -205,29 +309,3 @@ func (s *PolicyService) upsertPolicy(ctx context.Context, tx *sql.Tx, upsert *ap
return &policyRaw, nil
}
-
-// GetBackupPlanPolicy will get the backup plan policy for an environment.
-func (s *PolicyService) GetBackupPlanPolicy(ctx context.Context, environmentID int) (*api.BackupPlanPolicy, error) {
- pType := api.PolicyTypeBackupPlan
- policy, err := s.FindPolicy(ctx, &api.PolicyFind{
- EnvironmentID: &environmentID,
- Type: &pType,
- })
- if err != nil {
- return nil, err
- }
- return api.UnmarshalBackupPlanPolicy(policy.Payload)
-}
-
-// GetPipelineApprovalPolicy will get the pipeline approval policy for an environment.
-func (s *PolicyService) GetPipelineApprovalPolicy(ctx context.Context, environmentID int) (*api.PipelineApprovalPolicy, error) {
- pType := api.PolicyTypePipelineApproval
- policy, err := s.FindPolicy(ctx, &api.PolicyFind{
- EnvironmentID: &environmentID,
- Type: &pType,
- })
- if err != nil {
- return nil, err
- }
- return api.UnmarshalPipelineApprovalPolicy(policy.Payload)
-}
diff --git a/store/principal.go b/store/principal.go
index a93563426b..be640244ed 100644
--- a/store/principal.go
+++ b/store/principal.go
@@ -252,7 +252,7 @@ func (s *Store) composePrincipal(ctx context.Context, raw *principalRaw) (*api.P
memberFind := &api.MemberFind{
PrincipalID: &principal.ID,
}
- memberRaw, err := s.findMemberRaw(ctx, memberFind)
+ memberRaw, err := s.getMemberRaw(ctx, memberFind)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
s.l.Error("Principal has not been assigned a role.",