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 Principal & Member (#950)

Yilong Li90cf3bf02737
diff --git a/api/member.go b/api/member.go
index 7721480a1e..8200078c8a 100644
--- a/api/member.go
+++ b/api/member.go
@@ -1,7 +1,6 @@
package api
import (
- "context"
"encoding/json"
)
@@ -41,44 +40,6 @@ func (e Role) String() string {
return ""
}
-// MemberRaw is the store model for an Member.
-// Fields have exactly the same meanings as Member.
-type MemberRaw struct {
- ID int
-
- // Standard fields
- RowStatus RowStatus
- CreatorID int
- CreatedTs int64
- UpdaterID int
- UpdatedTs int64
-
- // Domain specific fields
- Status MemberStatus
- Role Role
- PrincipalID int
-}
-
-// ToMember creates an instance of Member based on the MemberRaw.
-// This is intended to be called when we need to compose an Member relationship.
-func (raw *MemberRaw) ToMember() *Member {
- return &Member{
- ID: raw.ID,
-
- // Standard fields
- RowStatus: raw.RowStatus,
- CreatorID: raw.CreatorID,
- CreatedTs: raw.CreatedTs,
- UpdaterID: raw.UpdaterID,
- UpdatedTs: raw.UpdatedTs,
-
- // Domain specific fields
- Status: raw.Status,
- Role: raw.Role,
- PrincipalID: raw.PrincipalID,
- }
-}
-
// Member is the API message for a member.
type Member struct {
ID int `jsonapi:"primary,member"`
@@ -140,11 +101,3 @@ type MemberPatch struct {
// Domain specific fields
Role *string `jsonapi:"attr,role"`
}
-
-// MemberService is the service for members.
-type MemberService interface {
- CreateMember(ctx context.Context, create *MemberCreate) (*MemberRaw, error)
- FindMemberList(ctx context.Context, find *MemberFind) ([]*MemberRaw, error)
- FindMember(ctx context.Context, find *MemberFind) (*MemberRaw, error)
- PatchMember(ctx context.Context, patch *MemberPatch) (*MemberRaw, error)
-}
diff --git a/api/principal.go b/api/principal.go
index da8c1d5d96..c0e210aaa9 100644
--- a/api/principal.go
+++ b/api/principal.go
@@ -1,7 +1,6 @@
package api
import (
- "context"
"encoding/json"
)
@@ -55,7 +54,7 @@ type Principal struct {
// Do not return to the client
PasswordHash string
// Role is stored in the member table, but we include it when returning the principal.
- // This simplifies the client code where it won't require order depenendency to fetch the related member info first.
+ // This simplifies the client code where it won't require order dependency to fetch the related member info first.
Role Role `jsonapi:"attr,role"`
}
@@ -129,11 +128,3 @@ type PrincipalPatch struct {
Password *string `jsonapi:"attr,password"`
PasswordHash *string
}
-
-// PrincipalService is the service for principals.
-type PrincipalService interface {
- CreatePrincipal(ctx context.Context, create *PrincipalCreate) (*Principal, error)
- FindPrincipalList(ctx context.Context) ([]*Principal, error)
- FindPrincipal(ctx context.Context, find *PrincipalFind) (*Principal, error)
- PatchPrincipal(ctx context.Context, patch *PrincipalPatch) (*Principal, error)
-}
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index c7f0676977..98f870996c 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -374,27 +374,28 @@ func (m *Main) Run(ctx context.Context) error {
m.db = db
- s := server.NewServer(m.l, 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)
+ cacheService := server.NewCacheService(m.l)
+ storeInstance := store.New(m.l, db, cacheService)
+
+ 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.PrincipalService = store.NewPrincipalService(m.l, db, s.CacheService)
- s.MemberService = store.NewMemberService(m.l, db, s.CacheService)
- s.PolicyService = store.NewPolicyService(m.l, db, s.CacheService)
- s.ProjectService = store.NewProjectService(m.l, db, s.CacheService)
+ 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.EnvironmentService = store.NewEnvironmentService(m.l, db, s.CacheService)
- s.DataSourceService = store.NewDataSourceService(m.l, db, s.CacheService)
+ s.EnvironmentService = store.NewEnvironmentService(m.l, db, cacheService)
+ s.DataSourceService = store.NewDataSourceService(m.l, db, cacheService)
s.BackupService = store.NewBackupService(m.l, db, s.PolicyService)
- s.DatabaseService = store.NewDatabaseService(m.l, db, s.CacheService, s.PolicyService, s.BackupService)
- s.InstanceService = store.NewInstanceService(m.l, db, s.CacheService, s.DatabaseService, s.DataSourceService)
+ s.DatabaseService = store.NewDatabaseService(m.l, db, cacheService, s.PolicyService, s.BackupService)
+ s.InstanceService = store.NewInstanceService(m.l, db, cacheService, s.DatabaseService, s.DataSourceService)
s.InstanceUserService = store.NewInstanceUserService(m.l, db)
s.TableService = store.NewTableService(m.l, db)
s.ColumnService = store.NewColumnService(m.l, db)
s.ViewService = store.NewViewService(m.l, db)
s.IndexService = store.NewIndexService(m.l, db)
- s.IssueService = store.NewIssueService(m.l, db, s.CacheService)
+ s.IssueService = store.NewIssueService(m.l, db, cacheService)
s.IssueSubscriberService = store.NewIssueSubscriberService(m.l, db)
- s.PipelineService = store.NewPipelineService(m.l, db, s.CacheService)
+ s.PipelineService = store.NewPipelineService(m.l, db, cacheService)
s.StageService = store.NewStageService(m.l, db)
s.TaskCheckRunService = store.NewTaskCheckRunService(m.l, db)
s.TaskService = store.NewTaskService(m.l, db, store.NewTaskRunService(m.l, db), s.TaskCheckRunService)
diff --git a/server/acl.go b/server/acl.go
index 9a898df1db..0a7476fd87 100644
--- a/server/acl.go
+++ b/server/acl.go
@@ -47,7 +47,7 @@ func aclMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Hand
memberFind := &api.MemberFind{
PrincipalID: &principalID,
}
- member, err := s.MemberService.FindMember(ctx, memberFind)
+ member, err := s.store.FindMember(ctx, memberFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to process authorize request.").SetInternal(err)
}
diff --git a/server/activity.go b/server/activity.go
index b5445939b6..05ffc79b3b 100644
--- a/server/activity.go
+++ b/server/activity.go
@@ -175,13 +175,13 @@ func (s *Server) registerActivityRoutes(g *echo.Group) {
func (s *Server) composeActivityRelationship(ctx context.Context, raw *api.ActivityRaw) (*api.Activity, error) {
activity := raw.ToActivity()
- creator, err := s.composePrincipalByID(ctx, activity.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, activity.CreatorID)
if err != nil {
return nil, err
}
activity.Creator = creator
- updater, err := s.composePrincipalByID(ctx, activity.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, activity.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/activity_manager.go b/server/activity_manager.go
index 51629ed8f4..da57c919f1 100644
--- a/server/activity_manager.go
+++ b/server/activity_manager.go
@@ -90,7 +90,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activi
principalFind := &api.PrincipalFind{
ID: &create.CreatorID,
}
- updater, err := m.s.PrincipalService.FindPrincipal(ctx, principalFind)
+ updater, err := m.s.store.FindPrincipal(ctx, principalFind)
if err != nil {
return nil, fmt.Errorf("failed to find updater for posting webhook event after changing the issue status: %v, error: %w", meta.issue.Name, err)
}
@@ -168,7 +168,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.A
principalFind := &api.PrincipalFind{
ID: &oldID,
}
- oldAssignee, err = m.s.PrincipalService.FindPrincipal(ctx, principalFind)
+ oldAssignee, err = m.s.store.FindPrincipal(ctx, principalFind)
if err != nil {
m.s.l.Warn("Failed to post webhook event after changing the issue assignee, failed to find old assignee",
zap.String("issue_name", meta.issue.Name),
@@ -198,7 +198,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.A
principalFind := &api.PrincipalFind{
ID: &newID,
}
- newAssignee, err = m.s.PrincipalService.FindPrincipal(ctx, principalFind)
+ newAssignee, err = m.s.store.FindPrincipal(ctx, principalFind)
if err != nil {
m.s.l.Warn("Failed to post webhook event after changing the issue assignee, failed to find new assignee",
zap.String("issue_name", meta.issue.Name),
diff --git a/server/actuator.go b/server/actuator.go
index afb1a474a6..f30422200b 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.MemberService.FindMemberList(ctx, find)
+ memberList, err := s.store.FindMemberList(ctx, find)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch admin setup status").SetInternal(err)
}
diff --git a/server/auth.go b/server/auth.go
index d8ac8f15bb..ba9bc56714 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -63,7 +63,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
Email: &login.Email,
}
var err error
- user, err = s.PrincipalService.FindPrincipal(ctx, principalFind)
+ user, err = s.store.FindPrincipal(ctx, principalFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)
}
@@ -114,7 +114,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
principalFind := &api.PrincipalFind{
Email: &gitlabUserInfo.PublicEmail,
}
- user, err = s.PrincipalService.FindPrincipal(ctx, principalFind)
+ user, err = s.store.FindPrincipal(ctx, principalFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)
}
@@ -145,7 +145,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
memberFind := &api.MemberFind{
PrincipalID: &user.ID,
}
- member, err := s.MemberService.FindMember(ctx, memberFind)
+ member, err := s.store.FindMember(ctx, memberFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)
}
@@ -215,7 +215,8 @@ func trySignUp(ctx context.Context, s *Server, signUp *api.SignUp, CreatorID int
Email: signUp.Email,
PasswordHash: string(passwordHash),
}
- user, err := s.PrincipalService.CreatePrincipal(ctx, principalCreate)
+ // The user has an empty field of Role, which corresponds to the Member object created later.
+ user, err := s.store.CreatePrincipal(ctx, principalCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return nil, echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Email already exists: %s", signUp.Email))
@@ -227,7 +228,7 @@ func trySignUp(ctx context.Context, s *Server, signUp *api.SignUp, CreatorID int
find := &api.MemberFind{
Role: &findRole,
}
- memberList, err := s.MemberService.FindMemberList(ctx, find)
+ memberList, err := s.store.FindMemberList(ctx, find)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to sign up").SetInternal(err)
}
@@ -244,13 +245,14 @@ func trySignUp(ctx context.Context, s *Server, signUp *api.SignUp, CreatorID int
PrincipalID: user.ID,
}
- member, err := s.MemberService.CreateMember(ctx, memberCreate)
+ member, err := s.store.CreateMember(ctx, memberCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return nil, echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Member already exists: %s", signUp.Email))
}
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to sign up").SetInternal(err)
}
+ // From now on, the Principal we just created could be composed with a valid Role field.
{
bytes, err := json.Marshal(api.ActivityMemberCreatePayload{
diff --git a/server/bookmark.go b/server/bookmark.go
index 28f393b862..9014d910cd 100644
--- a/server/bookmark.go
+++ b/server/bookmark.go
@@ -101,13 +101,13 @@ func (s *Server) registerBookmarkRoutes(g *echo.Group) {
func (s *Server) composeBookmarkRelationship(ctx context.Context, raw *api.BookmarkRaw) (*api.Bookmark, error) {
bookmark := raw.ToBookmark()
- creator, err := s.composePrincipalByID(ctx, bookmark.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, bookmark.CreatorID)
if err != nil {
return nil, err
}
bookmark.Creator = creator
- updater, err := s.composePrincipalByID(ctx, bookmark.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, bookmark.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/database.go b/server/database.go
index f3cd9b62c0..32e3e647d3 100644
--- a/server/database.go
+++ b/server/database.go
@@ -992,13 +992,13 @@ func (s *Server) composeDatabaseListByFind(ctx context.Context, find *api.Databa
func (s *Server) composeDatabaseRelationship(ctx context.Context, raw *api.DatabaseRaw) (*api.Database, error) {
db := raw.ToDatabase()
- creator, err := s.composePrincipalByID(ctx, db.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, db.CreatorID)
if err != nil {
return nil, err
}
db.Creator = creator
- updater, err := s.composePrincipalByID(ctx, db.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, db.UpdaterID)
if err != nil {
return nil, err
}
@@ -1043,11 +1043,11 @@ func (s *Server) composeDatabaseRelationship(ctx context.Context, raw *api.Datab
// TODO(dragonly): implement composeAnomalyRelationship
db.AnomalyList = anomalyList
for _, anomaly := range db.AnomalyList {
- anomaly.Creator, err = s.composePrincipalByID(ctx, anomaly.CreatorID)
+ anomaly.Creator, err = s.store.GetPrincipalByID(ctx, anomaly.CreatorID)
if err != nil {
return nil, err
}
- anomaly.Updater, err = s.composePrincipalByID(ctx, anomaly.UpdaterID)
+ anomaly.Updater, err = s.store.GetPrincipalByID(ctx, anomaly.UpdaterID)
if err != nil {
return nil, err
}
@@ -1092,13 +1092,13 @@ func (s *Server) composeDatabaseRelationship(ctx context.Context, raw *api.Datab
func (s *Server) composeTableRelationship(ctx context.Context, raw *api.TableRaw) (*api.Table, error) {
table := raw.ToTable()
- creator, err := s.composePrincipalByID(ctx, table.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, table.CreatorID)
if err != nil {
return nil, err
}
table.Creator = creator
- updater, err := s.composePrincipalByID(ctx, table.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, table.UpdaterID)
if err != nil {
return nil, err
}
@@ -1110,13 +1110,13 @@ func (s *Server) composeTableRelationship(ctx context.Context, raw *api.TableRaw
func (s *Server) composeViewRelationship(ctx context.Context, raw *api.ViewRaw) (*api.View, error) {
view := raw.ToView()
- creator, err := s.composePrincipalByID(ctx, view.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, view.CreatorID)
if err != nil {
return nil, err
}
view.Creator = creator
- updater, err := s.composePrincipalByID(ctx, view.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, view.UpdaterID)
if err != nil {
return nil, err
}
@@ -1148,13 +1148,13 @@ func (s *Server) composeBackupByID(ctx context.Context, id int) (*api.Backup, er
// composeBackupRelationship will compose the relationship of a backup.
func (s *Server) composeBackupRelationship(ctx context.Context, raw *api.BackupRaw) (*api.Backup, error) {
backup := raw.ToBackup()
- creator, err := s.composePrincipalByID(ctx, backup.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, backup.CreatorID)
if err != nil {
return nil, err
}
backup.Creator = creator
- updater, err := s.composePrincipalByID(ctx, backup.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, backup.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/environment.go b/server/environment.go
index 134ee223f7..2cc7455888 100644
--- a/server/environment.go
+++ b/server/environment.go
@@ -174,13 +174,13 @@ func (s *Server) composeEnvironmentByID(ctx context.Context, id int) (*api.Envir
func (s *Server) composeEnvironmentRelationship(ctx context.Context, raw *api.EnvironmentRaw) (*api.Environment, error) {
env := raw.ToEnvironment()
- creator, err := s.composePrincipalByID(ctx, env.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, env.CreatorID)
if err != nil {
return nil, err
}
env.Creator = creator
- updater, err := s.composePrincipalByID(ctx, env.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, env.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/instance.go b/server/instance.go
index 9d06bfbba9..3ce7911443 100644
--- a/server/instance.go
+++ b/server/instance.go
@@ -447,13 +447,13 @@ func (s *Server) composeInstanceByID(ctx context.Context, id int) (*api.Instance
func (s *Server) composeInstanceRelationship(ctx context.Context, raw *api.InstanceRaw) (*api.Instance, error) {
instance := raw.ToInstance()
- creator, err := s.composePrincipalByID(ctx, instance.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, instance.CreatorID)
if err != nil {
return nil, err
}
instance.Creator = creator
- updater, err := s.composePrincipalByID(ctx, instance.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, instance.UpdaterID)
if err != nil {
return nil, err
}
@@ -481,10 +481,10 @@ func (s *Server) composeInstanceRelationship(ctx context.Context, raw *api.Insta
// TODO(dragonly): implement composeAnomalyRelationship
instance.AnomalyList = anomalyList
for _, anomaly := range instance.AnomalyList {
- if anomaly.Creator, err = s.composePrincipalByID(ctx, anomaly.CreatorID); err != nil {
+ if anomaly.Creator, err = s.store.GetPrincipalByID(ctx, anomaly.CreatorID); err != nil {
return nil, err
}
- if anomaly.Updater, err = s.composePrincipalByID(ctx, anomaly.UpdaterID); err != nil {
+ if anomaly.Updater, err = s.store.GetPrincipalByID(ctx, anomaly.UpdaterID); err != nil {
return nil, err
}
}
@@ -502,10 +502,10 @@ func (s *Server) composeInstanceRelationship(ctx context.Context, raw *api.Insta
}
instance.DataSourceList = dataSourceList
for _, dataSource := range instance.DataSourceList {
- if dataSource.Creator, err = s.composePrincipalByID(ctx, dataSource.CreatorID); err != nil {
+ if dataSource.Creator, err = s.store.GetPrincipalByID(ctx, dataSource.CreatorID); err != nil {
return nil, err
}
- if dataSource.Updater, err = s.composePrincipalByID(ctx, dataSource.UpdaterID); err != nil {
+ if dataSource.Updater, err = s.store.GetPrincipalByID(ctx, dataSource.UpdaterID); err != nil {
return nil, err
}
}
diff --git a/server/issue.go b/server/issue.go
index 9557212632..1a7c6c6ae3 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -287,19 +287,19 @@ func (s *Server) composeIssueByID(ctx context.Context, id int) (*api.Issue, erro
func (s *Server) composeIssueRelationship(ctx context.Context, raw *api.IssueRaw) (*api.Issue, error) {
issue := raw.ToIssue()
- creator, err := s.composePrincipalByID(ctx, issue.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, issue.CreatorID)
if err != nil {
return nil, err
}
issue.Creator = creator
- updater, err := s.composePrincipalByID(ctx, issue.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, issue.UpdaterID)
if err != nil {
return nil, err
}
issue.Updater = updater
- assignee, err := s.composePrincipalByID(ctx, issue.AssigneeID)
+ assignee, err := s.store.GetPrincipalByID(ctx, issue.AssigneeID)
if err != nil {
return nil, err
}
@@ -339,17 +339,17 @@ func (s *Server) composeIssueRelationship(ctx context.Context, raw *api.IssueRaw
func (s *Server) composeIssueRelationshipValidateOnly(ctx context.Context, issue *api.Issue) error {
var err error
- issue.Creator, err = s.composePrincipalByID(ctx, issue.CreatorID)
+ issue.Creator, err = s.store.GetPrincipalByID(ctx, issue.CreatorID)
if err != nil {
return err
}
- issue.Updater, err = s.composePrincipalByID(ctx, issue.UpdaterID)
+ issue.Updater, err = s.store.GetPrincipalByID(ctx, issue.UpdaterID)
if err != nil {
return err
}
- issue.Assignee, err = s.composePrincipalByID(ctx, issue.AssigneeID)
+ issue.Assignee, err = s.store.GetPrincipalByID(ctx, issue.AssigneeID)
if err != nil {
return err
}
@@ -383,7 +383,7 @@ func (s *Server) composeIssueRelationshipValidateOnly(ctx context.Context, issue
// Only allow Bot/Owner/DBA as the assignee, not Developer.
func (s *Server) validateAssigneeRoleByID(ctx context.Context, assigneeID int) error {
- assignee, err := s.PrincipalService.FindPrincipal(ctx, &api.PrincipalFind{
+ assignee, err := s.store.FindPrincipal(ctx, &api.PrincipalFind{
ID: &assigneeID,
})
if err != nil {
@@ -392,9 +392,6 @@ func (s *Server) validateAssigneeRoleByID(ctx context.Context, assigneeID int) e
if assignee == nil {
return fmt.Errorf("Principal ID not found: %d", assigneeID)
}
- if err = s.composePrincipalRole(ctx, assignee); err != nil {
- return err
- }
if assignee.Role != api.Owner && assignee.Role != api.DBA {
return fmt.Errorf("%s is not allowed as assignee", assignee.Role)
}
diff --git a/server/issue_subscriber.go b/server/issue_subscriber.go
index 24da1c7050..b20d7fb2f7 100644
--- a/server/issue_subscriber.go
+++ b/server/issue_subscriber.go
@@ -107,7 +107,7 @@ func (s *Server) registerIssueSubscriberRoutes(g *echo.Group) {
func (s *Server) composeIssueSubscriberRelationship(ctx context.Context, raw *api.IssueSubscriberRaw) (*api.IssueSubscriber, error) {
issueSubscriber := raw.ToIssueSubscriber()
- subscriber, err := s.composePrincipalByID(ctx, issueSubscriber.SubscriberID)
+ subscriber, err := s.store.GetPrincipalByID(ctx, issueSubscriber.SubscriberID)
if err != nil {
return nil, err
}
diff --git a/server/jwt.go b/server/jwt.go
index cd30546451..0bbd5f756b 100644
--- a/server/jwt.go
+++ b/server/jwt.go
@@ -10,6 +10,7 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/store"
"github.com/golang-jwt/jwt/v4"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
@@ -164,7 +165,7 @@ func removeUserCookie(c echo.Context) {
// JWTMiddleware validates the access token.
// If the access token is about to expire or has expired and the request has a valid refresh token, it
// will try to generate new access token and refresh token.
-func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc, mode string, secret string) echo.HandlerFunc {
+func JWTMiddleware(l *zap.Logger, principalStore *store.Store, next echo.HandlerFunc, mode string, secret string) echo.HandlerFunc {
return func(c echo.Context) error {
// Skips auth, actuator, plan
if common.HasPrefixes(c.Path(), "/api/auth", "/api/actuator", "/api/plan") {
@@ -228,7 +229,7 @@ func JWTMiddleware(l *zap.Logger, p api.PrincipalService, next echo.HandlerFunc,
principalFind := &api.PrincipalFind{
ID: &principalID,
}
- user, err := p.FindPrincipal(ctx, principalFind)
+ user, err := principalStore.FindPrincipal(ctx, principalFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find user ID: %d", principalID)).SetInternal(err)
}
diff --git a/server/member.go b/server/member.go
index 25fcdae5e9..091fc20dc9 100644
--- a/server/member.go
+++ b/server/member.go
@@ -23,24 +23,20 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
memberCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)
- memberRaw, err := s.MemberService.CreateMember(ctx, memberCreate)
+ member, err := s.store.CreateMember(ctx, memberCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Member for user ID already exists: %d", memberCreate.PrincipalID))
}
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create member").SetInternal(err)
}
- member, err := s.composeMemberRelationship(ctx, memberRaw)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create member").SetInternal(err)
- }
// Record activity
{
principalFind := &api.PrincipalFind{
ID: &member.PrincipalID,
}
- user, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
+ user, err := s.store.FindPrincipal(ctx, principalFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find user ID: %d", member.PrincipalID)).SetInternal(err)
}
@@ -81,18 +77,10 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
g.GET("/member", func(c echo.Context) error {
ctx := context.Background()
memberFind := &api.MemberFind{}
- memberRawList, err := s.MemberService.FindMemberList(ctx, memberFind)
+ memberList, err := s.store.FindMemberList(ctx, memberFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch member list").SetInternal(err)
}
- var memberList []*api.Member
- for _, memberRaw := range memberRawList {
- member, err := s.composeMemberRelationship(ctx, memberRaw)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch member relationship: %v", memberRaw.ID)).SetInternal(err)
- }
- memberList = append(memberList, member)
- }
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, memberList); err != nil {
@@ -111,17 +99,13 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
memberFind := &api.MemberFind{
ID: &id,
}
- memberRaw, err := s.MemberService.FindMember(ctx, memberFind)
+ member, err := s.store.FindMember(ctx, memberFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find member ID: %d", id)).SetInternal(err)
}
- if memberRaw == nil {
+ if member == nil {
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find member ID: %d", id))
}
- member, err := s.composeMemberRelationship(ctx, memberRaw)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to compose member relationship with ID %d", id)).SetInternal(err)
- }
memberPatch := &api.MemberPatch{
ID: id,
@@ -131,24 +115,20 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch member request").SetInternal(err)
}
- updatedMemberRaw, err := s.MemberService.PatchMember(ctx, memberPatch)
+ updatedMember, err := s.store.PatchMember(ctx, memberPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Member ID not found: %d", id))
}
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch member ID: %v", id)).SetInternal(err)
}
- updatedMember, err := s.composeMemberRelationship(ctx, updatedMemberRaw)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to compose member relationship with ID %v", id)).SetInternal(err)
- }
// Record activity
{
principalFind := &api.PrincipalFind{
ID: &updatedMember.PrincipalID,
}
- user, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
+ user, err := s.store.FindPrincipal(ctx, principalFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find user ID: %d", updatedMember.PrincipalID)).SetInternal(err)
}
@@ -213,27 +193,3 @@ func (s *Server) registerMemberRoutes(g *echo.Group) {
return nil
})
}
-
-func (s *Server) composeMemberRelationship(ctx context.Context, raw *api.MemberRaw) (*api.Member, error) {
- member := raw.ToMember()
-
- creator, err := s.composePrincipalByID(ctx, member.CreatorID)
- if err != nil {
- return nil, err
- }
- member.Creator = creator
-
- updater, err := s.composePrincipalByID(ctx, member.UpdaterID)
- if err != nil {
- return nil, err
- }
- member.Updater = updater
-
- principal, err := s.composePrincipalByID(ctx, member.PrincipalID)
- if err != nil {
- return nil, err
- }
- member.Principal = principal
-
- return member, nil
-}
diff --git a/server/pipeline.go b/server/pipeline.go
index 368148be19..9079489f29 100644
--- a/server/pipeline.go
+++ b/server/pipeline.go
@@ -30,13 +30,13 @@ func (s *Server) composePipelineByID(ctx context.Context, id int) (*api.Pipeline
func (s *Server) composePipelineRelationship(ctx context.Context, raw *api.PipelineRaw) (*api.Pipeline, error) {
pipeline := raw.ToPipeline()
- creator, err := s.composePrincipalByID(ctx, pipeline.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, pipeline.CreatorID)
if err != nil {
return nil, err
}
pipeline.Creator = creator
- updater, err := s.composePrincipalByID(ctx, pipeline.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, pipeline.UpdaterID)
if err != nil {
return nil, err
}
@@ -55,12 +55,12 @@ func (s *Server) composePipelineRelationship(ctx context.Context, raw *api.Pipel
func (s *Server) composePipelineRelationshipValidateOnly(ctx context.Context, pipeline *api.Pipeline) error {
var err error
- pipeline.Creator, err = s.composePrincipalByID(ctx, pipeline.CreatorID)
+ pipeline.Creator, err = s.store.GetPrincipalByID(ctx, pipeline.CreatorID)
if err != nil {
return err
}
- pipeline.Updater, err = s.composePrincipalByID(ctx, pipeline.UpdaterID)
+ pipeline.Updater, err = s.store.GetPrincipalByID(ctx, pipeline.UpdaterID)
if err != nil {
return err
}
diff --git a/server/policy.go b/server/policy.go
index d29f1f3333..c77bad9260 100644
--- a/server/policy.go
+++ b/server/policy.go
@@ -108,13 +108,13 @@ func (s *Server) registerPolicyRoutes(g *echo.Group) {
func (s *Server) composePolicyRelationship(ctx context.Context, raw *api.PolicyRaw) (*api.Policy, error) {
policy := raw.ToPolicy()
- creator, err := s.composePrincipalByID(ctx, policy.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, policy.CreatorID)
if err != nil {
return nil, err
}
policy.Creator = creator
- updater, err := s.composePrincipalByID(ctx, policy.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, policy.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/principal.go b/server/principal.go
index e0242f2e5f..50e375cd06 100644
--- a/server/principal.go
+++ b/server/principal.go
@@ -10,7 +10,6 @@ import (
"github.com/bytebase/bytebase/common"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
- "go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
)
@@ -30,7 +29,7 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
}
principalCreate.PasswordHash = string(passwordHash)
- principal, err := s.PrincipalService.CreatePrincipal(ctx, principalCreate)
+ principal, err := s.store.CreatePrincipal(ctx, principalCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, "User already exists")
@@ -49,30 +48,13 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
g.GET("/principal", func(c echo.Context) error {
ctx := context.Background()
- principalList, err := s.PrincipalService.FindPrincipalList(ctx)
+ principalList, err := s.store.GetPrincipalList(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch principal list").SetInternal(err)
}
- filteredList := []*api.Principal{}
- for _, principal := range principalList {
- if err := s.composePrincipalRole(ctx, principal); err != nil {
- // Normally this should not happen since we create the member together with the principal
- // and we don't allow deleting the member. Just in case.
- if common.ErrorCode(err) == common.NotFound {
- s.l.Error("Principal has not been assigned a role. Skip",
- zap.Int("id", principal.ID),
- zap.String("name", principal.Name),
- )
- continue
- }
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch role for principal: %v", principal.Name)).SetInternal(err)
- }
- filteredList = append(filteredList, principal)
- }
-
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, filteredList); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, principalList); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal principal list response").SetInternal(err)
}
return nil
@@ -85,7 +67,7 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("principalID"))).SetInternal(err)
}
- principal, err := s.composePrincipalByID(ctx, id)
+ principal, err := s.store.FindPrincipal(ctx, &api.PrincipalFind{ID: &id})
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("User ID not found: %d", id))
@@ -123,16 +105,13 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
principalPatch.PasswordHash = &passwordHashStr
}
- principal, err := s.PrincipalService.PatchPrincipal(ctx, principalPatch)
+ principal, err := s.store.PatchPrincipal(ctx, principalPatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("User ID not found: %d", id))
}
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch principal ID: %v", id)).SetInternal(err)
}
- if err := s.composePrincipalRole(ctx, principal); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch role for principal: %v", principal.Name)).SetInternal(err)
- }
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {
@@ -141,41 +120,3 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
return nil
})
}
-
-func (s *Server) composePrincipalByID(ctx context.Context, id int) (*api.Principal, error) {
- principalFind := &api.PrincipalFind{
- ID: &id,
- }
- principal, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
- if err != nil {
- return nil, err
- }
- if id > 0 && principal == nil {
- return nil, fmt.Errorf("Principal not found with ID %v", id)
- }
-
- if err = s.composePrincipalRole(ctx, principal); err != nil {
- return nil, err
- }
-
- return principal, nil
-}
-
-func (s *Server) composePrincipalRole(ctx context.Context, principal *api.Principal) error {
- if principal.ID == api.SystemBotID {
- principal.Role = api.Owner
- } else {
- memberFind := &api.MemberFind{
- PrincipalID: &principal.ID,
- }
- member, err := s.MemberService.FindMember(ctx, memberFind)
- if err != nil {
- return err
- }
- if principal.ID > 0 && member == nil {
- return fmt.Errorf("Member not found for ID %v", principal.ID)
- }
- principal.Role = member.Role
- }
- return nil
-}
diff --git a/server/project.go b/server/project.go
index 0b0bff769a..8193068109 100644
--- a/server/project.go
+++ b/server/project.go
@@ -611,13 +611,13 @@ func (s *Server) composeProjectByID(ctx context.Context, id int) (*api.Project,
func (s *Server) composeProjectRelationship(ctx context.Context, raw *api.ProjectRaw) (*api.Project, error) {
project := raw.ToProject()
- creator, err := s.composePrincipalByID(ctx, project.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, project.CreatorID)
if err != nil {
return nil, err
}
project.Creator = creator
- updater, err := s.composePrincipalByID(ctx, project.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, project.UpdaterID)
if err != nil {
return nil, err
}
@@ -634,11 +634,11 @@ func (s *Server) composeProjectRelationship(ctx context.Context, raw *api.Projec
func (s *Server) composeDeploymentConfigRelationship(ctx context.Context, deploymentConfig *api.DeploymentConfig) error {
var err error
- deploymentConfig.Creator, err = s.composePrincipalByID(ctx, deploymentConfig.CreatorID)
+ deploymentConfig.Creator, err = s.store.GetPrincipalByID(ctx, deploymentConfig.CreatorID)
if err != nil {
return err
}
- deploymentConfig.Updater, err = s.composePrincipalByID(ctx, deploymentConfig.UpdaterID)
+ deploymentConfig.Updater, err = s.store.GetPrincipalByID(ctx, deploymentConfig.UpdaterID)
if err != nil {
return err
}
diff --git a/server/project_member.go b/server/project_member.go
index 787b31495e..9b4de734a3 100644
--- a/server/project_member.go
+++ b/server/project_member.go
@@ -79,7 +79,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
}
findPrincipal := &api.PrincipalFind{Email: &projectMember.Email}
- principal, err := s.PrincipalService.FindPrincipal(ctx, findPrincipal)
+ principal, err := s.store.FindPrincipal(ctx, findPrincipal)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch principal info").SetInternal(err)
}
@@ -163,7 +163,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
if createdMember.Role == deletedMember.Role && createdMember.RoleProvider == deletedMember.RoleProvider {
continue
}
- principal, err := s.composePrincipalByID(ctx, createdMember.PrincipalID)
+ principal, err := s.store.GetPrincipalByID(ctx, createdMember.PrincipalID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Fail to create member relation, Principal ID: %v", principal.ID)).SetInternal(err)
}
@@ -187,7 +187,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
} else {
// elsewise, we will create a MEMBER CREATE activity
principalFind := &api.PrincipalFind{ID: &createdMember.PrincipalID}
- principal, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
+ principal, err := s.store.FindPrincipal(ctx, principalFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Fail to find the relevant principal of the member relation, principal ID: %v", principal.ID)).SetInternal(err)
}
@@ -216,7 +216,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
// if the member does exist in createdMemberList, meaning we need to update this member(already done above).
continue
}
- principal, err := s.composePrincipalByID(ctx, deletedMember.PrincipalID)
+ principal, err := s.store.GetPrincipalByID(ctx, deletedMember.PrincipalID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Fail to create member relation, Principal ID: %v", deletedMember.PrincipalID)).SetInternal(err)
}
@@ -399,7 +399,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
}
{
- projectMember.Principal, err = s.composePrincipalByID(ctx, projectMember.PrincipalID)
+ projectMember.Principal, err = s.store.GetPrincipalByID(ctx, projectMember.PrincipalID)
if err == nil {
activityCreate := &api.ActivityCreate{
CreatorID: c.Get(getPrincipalIDContextKey()).(int),
@@ -450,19 +450,19 @@ func (s *Server) composeProjectMemberListByProjectID(ctx context.Context, projec
func (s *Server) composeProjectMemberRelationship(ctx context.Context, raw *api.ProjectMemberRaw) (*api.ProjectMember, error) {
projectMember := raw.ToProjectMember()
- creator, err := s.composePrincipalByID(ctx, projectMember.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, projectMember.CreatorID)
if err != nil {
return nil, err
}
projectMember.Creator = creator
- updater, err := s.composePrincipalByID(ctx, projectMember.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, projectMember.UpdaterID)
if err != nil {
return nil, err
}
projectMember.Updater = updater
- principal, err := s.composePrincipalByID(ctx, projectMember.PrincipalID)
+ principal, err := s.store.GetPrincipalByID(ctx, projectMember.PrincipalID)
if err != nil {
return nil, err
}
diff --git a/server/project_webhook.go b/server/project_webhook.go
index e5fbec9e4c..c6cab8a01c 100644
--- a/server/project_webhook.go
+++ b/server/project_webhook.go
@@ -257,13 +257,13 @@ func (s *Server) registerProjectWebhookRoutes(g *echo.Group) {
func (s *Server) composeProjectWebhookRelationship(ctx context.Context, raw *api.ProjectWebhookRaw) (*api.ProjectWebhook, error) {
webhook := raw.ToProjectWebhook()
- creator, err := s.composePrincipalByID(ctx, webhook.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, webhook.CreatorID)
if err != nil {
return nil, err
}
webhook.Creator = creator
- updater, err := s.composePrincipalByID(ctx, webhook.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, webhook.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/repository.go b/server/repository.go
index 6785e04360..b813d1ccf5 100644
--- a/server/repository.go
+++ b/server/repository.go
@@ -10,13 +10,13 @@ import (
func (s *Server) composeRepositoryRelationship(ctx context.Context, raw *api.RepositoryRaw) (*api.Repository, error) {
repository := raw.ToRepository()
- creator, err := s.composePrincipalByID(ctx, repository.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, repository.CreatorID)
if err != nil {
return nil, err
}
repository.Creator = creator
- updater, err := s.composePrincipalByID(ctx, repository.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, repository.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/server.go b/server/server.go
index 6745abf226..631e3faa8a 100644
--- a/server/server.go
+++ b/server/server.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/store"
// embed will embeds the acl policy.
_ "embed"
@@ -35,11 +36,7 @@ type Server struct {
ActivityManager *ActivityManager
- CacheService api.CacheService
-
SettingService api.SettingService
- PrincipalService api.PrincipalService
- MemberService api.MemberService
PolicyService api.PolicyService
ProjectService api.ProjectService
ProjectMemberService api.ProjectMemberService
@@ -73,6 +70,7 @@ type Server struct {
e *echo.Echo
+ store *store.Store
l *zap.Logger
lvl *zap.AtomicLevel
version string
@@ -103,13 +101,13 @@ var casbinDBAPolicy string
var casbinDeveloperPolicy string
// NewServer creates a server.
-func NewServer(logger *zap.Logger, loggerLevel *zap.AtomicLevel, version string, host string, port int, frontendHost string, frontendPort, datastorePort int, mode string, dataDir string, backupRunnerInterval time.Duration, secret string, readonly bool, demo bool, debug bool) *Server {
+func NewServer(logger *zap.Logger, storeInstance *store.Store, loggerLevel *zap.AtomicLevel, version string, host string, port int, frontendHost string, frontendPort, datastorePort int, mode string, dataDir string, backupRunnerInterval time.Duration, secret string, readonly bool, demo bool, debug bool) *Server {
e := echo.New()
e.Debug = debug
e.HideBanner = true
e.HidePort = true
- // Disallow to be embedded in an iframe
+ // Disallow to be embedded in an iFrame
e.Use(middleware.SecureWithConfig(middleware.SecureConfig{
XFrameOptions: "DENY",
}))
@@ -117,9 +115,9 @@ func NewServer(logger *zap.Logger, loggerLevel *zap.AtomicLevel, version string,
embedFrontend(logger, e)
s := &Server{
+ store: storeInstance,
l: logger,
lvl: loggerLevel,
- CacheService: NewCacheService(logger),
e: e,
version: version,
mode: mode,
@@ -209,7 +207,7 @@ func NewServer(logger *zap.Logger, loggerLevel *zap.AtomicLevel, version string,
apiGroup := e.Group("/api")
apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
- return JWTMiddleware(logger, s.PrincipalService, next, mode, secret)
+ return JWTMiddleware(logger, s.store, next, mode, secret)
})
m, err := model.NewModelFromString(casbinModel)
diff --git a/server/setting.go b/server/setting.go
index 22d8293bfc..33fd11a499 100644
--- a/server/setting.go
+++ b/server/setting.go
@@ -86,13 +86,13 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {
func (s *Server) composeSettingRelationship(ctx context.Context, raw *api.SettingRaw) (*api.Setting, error) {
setting := raw.ToSetting()
- creator, err := s.composePrincipalByID(ctx, setting.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, setting.CreatorID)
if err != nil {
return nil, err
}
setting.Creator = creator
- updater, err := s.composePrincipalByID(ctx, setting.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, setting.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/sheet.go b/server/sheet.go
index e2d6d10e8b..ccd3f7ede7 100644
--- a/server/sheet.go
+++ b/server/sheet.go
@@ -209,13 +209,13 @@ func (s *Server) registerSheetRoutes(g *echo.Group) {
func (s *Server) composeSheetRelationship(ctx context.Context, raw *api.SheetRaw) (*api.Sheet, error) {
sheet := raw.ToSheet()
- creator, err := s.composePrincipalByID(ctx, sheet.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, sheet.CreatorID)
if err != nil {
return nil, err
}
sheet.Creator = creator
- updater, err := s.composePrincipalByID(ctx, sheet.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, sheet.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/server/stage.go b/server/stage.go
index 18edeb4f46..5b56f5b3ee 100644
--- a/server/stage.go
+++ b/server/stage.go
@@ -30,13 +30,13 @@ func (s *Server) composeStageListByPipelineID(ctx context.Context, pipelineID in
func (s *Server) composeStageRelationship(ctx context.Context, raw *api.StageRaw) (*api.Stage, error) {
stage := raw.ToStage()
- creator, err := s.composePrincipalByID(ctx, stage.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, stage.CreatorID)
if err != nil {
return nil, err
}
stage.Creator = creator
- updater, err := s.composePrincipalByID(ctx, stage.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, stage.UpdaterID)
if err != nil {
return nil, err
}
@@ -60,12 +60,12 @@ func (s *Server) composeStageRelationship(ctx context.Context, raw *api.StageRaw
// TODO(dragonly): remove this hack
func (s *Server) composeStageRelationshipValidateOnly(ctx context.Context, stage *api.Stage) error {
var err error
- stage.Creator, err = s.composePrincipalByID(ctx, stage.CreatorID)
+ stage.Creator, err = s.store.GetPrincipalByID(ctx, stage.CreatorID)
if err != nil {
return err
}
- stage.Updater, err = s.composePrincipalByID(ctx, stage.UpdaterID)
+ stage.Updater, err = s.store.GetPrincipalByID(ctx, stage.UpdaterID)
if err != nil {
return err
}
diff --git a/server/task.go b/server/task.go
index 4ad19019f3..fabec3638f 100644
--- a/server/task.go
+++ b/server/task.go
@@ -329,7 +329,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Issue not found by pipeline ID: %d", task.PipelineID))
}
if issue.AssigneeID == api.SystemBotID {
- currentPrincipal, err := s.composePrincipalByID(ctx, currentPrincipalID)
+ currentPrincipal, err := s.store.GetPrincipalByID(ctx, currentPrincipalID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find principal").SetInternal(err)
}
@@ -418,26 +418,26 @@ func (s *Server) composeTaskListByPipelineAndStageID(ctx context.Context, pipeli
func (s *Server) composeTaskRelationship(ctx context.Context, raw *api.TaskRaw) (*api.Task, error) {
task := raw.ToTask()
- creator, err := s.composePrincipalByID(ctx, task.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, task.CreatorID)
if err != nil {
return nil, err
}
task.Creator = creator
- updater, err := s.composePrincipalByID(ctx, task.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, task.UpdaterID)
if err != nil {
return nil, err
}
task.Updater = updater
for _, taskRun := range task.TaskRunList {
- creator, err := s.composePrincipalByID(ctx, taskRun.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, taskRun.CreatorID)
if err != nil {
return nil, err
}
taskRun.Creator = creator
- updater, err := s.composePrincipalByID(ctx, taskRun.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, taskRun.UpdaterID)
if err != nil {
return nil, err
}
@@ -445,13 +445,13 @@ func (s *Server) composeTaskRelationship(ctx context.Context, raw *api.TaskRaw)
}
for _, taskCheckRun := range task.TaskCheckRunList {
- creator, err := s.composePrincipalByID(ctx, taskCheckRun.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, taskCheckRun.CreatorID)
if err != nil {
return nil, err
}
taskCheckRun.Creator = creator
- updater, err := s.composePrincipalByID(ctx, taskCheckRun.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, taskCheckRun.UpdaterID)
if err != nil {
return nil, err
}
@@ -485,35 +485,35 @@ func (s *Server) composeTaskRelationship(ctx context.Context, raw *api.TaskRaw)
func (s *Server) composeTaskRelationshipValidateOnly(ctx context.Context, task *api.Task) error {
var err error
- task.Creator, err = s.composePrincipalByID(ctx, task.CreatorID)
+ task.Creator, err = s.store.GetPrincipalByID(ctx, task.CreatorID)
if err != nil {
return err
}
- task.Updater, err = s.composePrincipalByID(ctx, task.UpdaterID)
+ task.Updater, err = s.store.GetPrincipalByID(ctx, task.UpdaterID)
if err != nil {
return err
}
for _, taskRun := range task.TaskRunList {
- taskRun.Creator, err = s.composePrincipalByID(ctx, taskRun.CreatorID)
+ taskRun.Creator, err = s.store.GetPrincipalByID(ctx, taskRun.CreatorID)
if err != nil {
return err
}
- taskRun.Updater, err = s.composePrincipalByID(ctx, taskRun.UpdaterID)
+ taskRun.Updater, err = s.store.GetPrincipalByID(ctx, taskRun.UpdaterID)
if err != nil {
return err
}
}
for _, taskCheckRun := range task.TaskCheckRunList {
- taskCheckRun.Creator, err = s.composePrincipalByID(ctx, taskCheckRun.CreatorID)
+ taskCheckRun.Creator, err = s.store.GetPrincipalByID(ctx, taskCheckRun.CreatorID)
if err != nil {
return err
}
- taskCheckRun.Updater, err = s.composePrincipalByID(ctx, taskCheckRun.UpdaterID)
+ taskCheckRun.Updater, err = s.store.GetPrincipalByID(ctx, taskCheckRun.UpdaterID)
if err != nil {
return err
}
diff --git a/server/task_executor.go b/server/task_executor.go
index 775c32a1e4..72bed37634 100644
--- a/server/task_executor.go
+++ b/server/task_executor.go
@@ -51,7 +51,7 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.
}
if vcsPushEvent == nil {
mi.Source = db.UI
- creator, err := server.composePrincipalByID(ctx, task.CreatorID)
+ creator, err := server.store.GetPrincipalByID(ctx, task.CreatorID)
if err != nil {
// If somehow we unable to find the principal, we just emit the error since it's not
// critical enough to fail the entire operation.
diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.go
index 102fb5503f..cfc47e5f07 100644
--- a/server/task_executor_database_create.go
+++ b/server/task_executor_database_create.go
@@ -73,7 +73,7 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser
Description: "Create database",
CreateDatabase: true,
}
- creator, err := server.composePrincipalByID(ctx, task.CreatorID)
+ creator, err := server.store.GetPrincipalByID(ctx, task.CreatorID)
if err != nil {
// If somehow we unable to find the principal, we just emit the error since it's not
// critical enough to fail the entire operation.
diff --git a/server/vcs.go b/server/vcs.go
index 951f815d7b..790152bf5d 100644
--- a/server/vcs.go
+++ b/server/vcs.go
@@ -199,13 +199,13 @@ func (s *Server) composeVCSByID(ctx context.Context, id int) (*api.VCS, error) {
func (s *Server) composeVCSRelationship(ctx context.Context, raw *api.VCSRaw) (*api.VCS, error) {
vcs := raw.ToVCS()
- creator, err := s.composePrincipalByID(ctx, vcs.CreatorID)
+ creator, err := s.store.GetPrincipalByID(ctx, vcs.CreatorID)
if err != nil {
return nil, err
}
vcs.Creator = creator
- updater, err := s.composePrincipalByID(ctx, vcs.UpdaterID)
+ updater, err := s.store.GetPrincipalByID(ctx, vcs.UpdaterID)
if err != nil {
return nil, err
}
diff --git a/store/member.go b/store/member.go
index 06c46f3f9b..db799e32c2 100644
--- a/store/member.go
+++ b/store/member.go
@@ -8,35 +8,115 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
- "go.uber.org/zap"
)
-var (
- _ api.MemberService = (*MemberService)(nil)
-)
+// memberRaw is the store model for an Member.
+// Fields have exactly the same meanings as Member.
+type memberRaw struct {
+ ID int
+
+ // Standard fields
+ RowStatus api.RowStatus
+ CreatorID int
+ CreatedTs int64
+ UpdaterID int
+ UpdatedTs int64
+
+ // Domain specific fields
+ Status api.MemberStatus
+ Role api.Role
+ PrincipalID int
+}
+
+// ToMember creates an instance of Member based on the memberRaw.
+// This is intended to be called when we need to compose an Member relationship.
+func (raw *memberRaw) ToMember() *api.Member {
+ return &api.Member{
+ ID: raw.ID,
+
+ // Standard fields
+ RowStatus: raw.RowStatus,
+ CreatorID: raw.CreatorID,
+ CreatedTs: raw.CreatedTs,
+ UpdaterID: raw.UpdaterID,
+ UpdatedTs: raw.UpdatedTs,
+
+ // Domain specific fields
+ Status: raw.Status,
+ Role: raw.Role,
+ PrincipalID: raw.PrincipalID,
+ }
+}
-// MemberService represents a service for managing member.
-type MemberService struct {
- l *zap.Logger
- db *DB
+// CreateMember creates an instance of Member
+func (s *Store) CreateMember(ctx context.Context, create *api.MemberCreate) (*api.Member, error) {
+ memberRaw, err := s.createMemberRaw(ctx, create)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to create Member with MemberCreate[%+v], error[%w]", create, err)
+ }
+ member, err := s.composeMember(ctx, memberRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Member with memberRaw[%+v], error[%w]", memberRaw, err)
+ }
+ return member, nil
+}
- cache api.CacheService
+// FindMemberList finds a list of Member instances
+func (s *Store) FindMemberList(ctx context.Context, find *api.MemberFind) ([]*api.Member, error) {
+ memberRawList, err := s.findMemberRawList(ctx, find)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to find Member list, error[%w]", err)
+ }
+ var memberList []*api.Member
+ for _, raw := range memberRawList {
+ member, err := s.composeMember(ctx, raw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Member role with memberRaw[%+v], error[%w]", raw, err)
+ }
+ memberList = append(memberList, member)
+ }
+ return memberList, nil
}
-// NewMemberService returns a new instance of MemberService.
-func NewMemberService(logger *zap.Logger, db *DB, cache api.CacheService) *MemberService {
- return &MemberService{l: logger, db: db, cache: cache}
+// 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)
+ 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
}
-// CreateMember creates a new member.
-func (s *MemberService) CreateMember(ctx context.Context, create *api.MemberCreate) (*api.MemberRaw, error) {
+// PatchMember patches an instance of Member
+func (s *Store) PatchMember(ctx context.Context, patch *api.MemberPatch) (*api.Member, error) {
+ memberRaw, err := s.patchMemberRaw(ctx, patch)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to patch Member with MemberPatch[%+v], error[%w]", patch, 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
+}
+
+//
+// private functions
+//
+
+// createMemberRaw creates a new member.
+func (s *Store) createMemberRaw(ctx context.Context, create *api.MemberCreate) (*memberRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- member, err := createMember(ctx, tx.PTx, create)
+ member, err := createMemberImpl(ctx, tx.PTx, create)
if err != nil {
return nil, err
}
@@ -52,35 +132,33 @@ func (s *MemberService) CreateMember(ctx context.Context, create *api.MemberCrea
return member, nil
}
-// FindMemberList retrieves a list of members based on find.
-func (s *MemberService) FindMemberList(ctx context.Context, find *api.MemberFind) ([]*api.MemberRaw, error) {
+// findMemberRawList retrieves a list of memberRaw instances.
+func (s *Store) findMemberRawList(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()
- list, err := findMemberList(ctx, tx.PTx, find)
+ memberRawList, err := findMemberRawListImpl(ctx, tx.PTx, find)
if err != nil {
return nil, err
}
- if err == nil {
- for _, member := range list {
- if err := s.cache.UpsertCache(api.MemberCache, member.PrincipalID, member); err != nil {
- return nil, err
- }
+ for _, member := range memberRawList {
+ if err := s.cache.UpsertCache(api.MemberCache, member.PrincipalID, member); err != nil {
+ return nil, err
}
}
- return list, nil
+ return memberRawList, nil
}
-// FindMember retrieves a single member based on find.
+// findMemberRaw retrieves an instance of memberRaw.
// Returns ECONFLICT if finding more than 1 matching records.
-func (s *MemberService) FindMember(ctx context.Context, find *api.MemberFind) (*api.MemberRaw, error) {
+func (s *Store) findMemberRaw(ctx context.Context, find *api.MemberFind) (*memberRaw, error) {
if find.PrincipalID != nil {
- memberRaw := &api.MemberRaw{}
+ memberRaw := &memberRaw{}
has, err := s.cache.FindCache(api.MemberCache, *find.PrincipalID, memberRaw)
if err != nil {
return nil, err
@@ -96,13 +174,13 @@ func (s *MemberService) FindMember(ctx context.Context, find *api.MemberFind) (*
}
defer tx.PTx.Rollback()
- list, err := findMemberList(ctx, tx.PTx, find)
+ list, err := findMemberRawListImpl(ctx, tx.PTx, find)
if err != nil {
return nil, err
}
if len(list) == 0 {
- return nil, nil
+ return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("member not found with MemberFind[%+v]", find)}
} else if len(list) > 1 {
return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d members with filter %+v, expect 1", len(list), find)}
}
@@ -112,16 +190,16 @@ func (s *MemberService) FindMember(ctx context.Context, find *api.MemberFind) (*
return list[0], nil
}
-// PatchMember updates an existing member by ID.
+// patchMemberRaw updates an existing instance of memberRaw by ID.
// Returns ENOTFOUND if member does not exist.
-func (s *MemberService) PatchMember(ctx context.Context, patch *api.MemberPatch) (*api.MemberRaw, error) {
+func (s *Store) patchMemberRaw(ctx context.Context, patch *api.MemberPatch) (*memberRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- member, err := patchMember(ctx, tx.PTx, patch)
+ member, err := patchMemberImpl(ctx, tx.PTx, patch)
if err != nil {
return nil, FormatError(err)
}
@@ -137,8 +215,33 @@ func (s *MemberService) PatchMember(ctx context.Context, patch *api.MemberPatch)
return member, nil
}
-// createMember creates a new member.
-func createMember(ctx context.Context, tx *sql.Tx, create *api.MemberCreate) (*api.MemberRaw, error) {
+// composeMember composes an instance of Member by memberRaw
+func (s *Store) composeMember(ctx context.Context, raw *memberRaw) (*api.Member, error) {
+ member := raw.ToMember()
+
+ creator, err := s.GetPrincipalByID(ctx, member.CreatorID)
+ if err != nil {
+ return nil, err
+ }
+ member.Creator = creator
+
+ updater, err := s.GetPrincipalByID(ctx, member.UpdaterID)
+ if err != nil {
+ return nil, err
+ }
+ member.Updater = updater
+
+ principal, err := s.GetPrincipalByID(ctx, member.PrincipalID)
+ if err != nil {
+ return nil, err
+ }
+ member.Principal = principal
+
+ return member, nil
+}
+
+// createMemberImpl creates a new member.
+func createMemberImpl(ctx context.Context, tx *sql.Tx, create *api.MemberCreate) (*memberRaw, error) {
// Insert row into database.
row, err := tx.QueryContext(ctx, `
INSERT INTO member (
@@ -164,7 +267,7 @@ func createMember(ctx context.Context, tx *sql.Tx, create *api.MemberCreate) (*a
defer row.Close()
row.Next()
- var memberRaw api.MemberRaw
+ var memberRaw memberRaw
if err := row.Scan(
&memberRaw.ID,
&memberRaw.RowStatus,
@@ -182,7 +285,7 @@ func createMember(ctx context.Context, tx *sql.Tx, create *api.MemberCreate) (*a
return &memberRaw, nil
}
-func findMemberList(ctx context.Context, tx *sql.Tx, find *api.MemberFind) ([]*api.MemberRaw, error) {
+func findMemberRawListImpl(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 {
@@ -216,9 +319,9 @@ func findMemberList(ctx context.Context, tx *sql.Tx, find *api.MemberFind) ([]*a
defer rows.Close()
// Iterate over result set and deserialize rows into memberRawList.
- var memberRawList []*api.MemberRaw
+ var memberRawList []*memberRaw
for rows.Next() {
- var memberRaw api.MemberRaw
+ var memberRaw memberRaw
if err := rows.Scan(
&memberRaw.ID,
&memberRaw.RowStatus,
@@ -242,8 +345,8 @@ func findMemberList(ctx context.Context, tx *sql.Tx, find *api.MemberFind) ([]*a
return memberRawList, nil
}
-// patchMember updates a member by ID. Returns the new state of the member after update.
-func patchMember(ctx context.Context, tx *sql.Tx, patch *api.MemberPatch) (*api.MemberRaw, error) {
+// patchMemberImpl updates a member by ID. Returns the new state of the member after update.
+func patchMemberImpl(ctx context.Context, tx *sql.Tx, patch *api.MemberPatch) (*memberRaw, error) {
// Build UPDATE clause.
set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
if v := patch.RowStatus; v != nil {
@@ -270,7 +373,7 @@ func patchMember(ctx context.Context, tx *sql.Tx, patch *api.MemberPatch) (*api.
defer row.Close()
if row.Next() {
- var memberRaw api.MemberRaw
+ var memberRaw memberRaw
if err := row.Scan(
&memberRaw.ID,
&memberRaw.RowStatus,
diff --git a/store/principal.go b/store/principal.go
index 9042f1d7e8..402b492d21 100644
--- a/store/principal.go
+++ b/store/principal.go
@@ -11,32 +11,138 @@ import (
"go.uber.org/zap"
)
-var (
- _ api.PrincipalService = (*PrincipalService)(nil)
-)
+// principalRaw is the store model for a Principal.
+// Fields have exactly the same meanings as Principal.
+type principalRaw struct {
+ ID int
+
+ // Standard fields
+ CreatorID int
+ CreatedTs int64
+ UpdaterID int
+ UpdatedTs int64
+
+ // Domain specific fields
+ Type api.PrincipalType
+ Name string
+ Email string
+ // Do not return to the client
+ PasswordHash string
+}
-// PrincipalService represents a service for managing principal.
-type PrincipalService struct {
- l *zap.Logger
- db *DB
+// ToPrincipal creates an instance of Principal based on the principalRaw.
+// This is intended to be called when we need to compose a Principal relationship.
+func (raw *principalRaw) ToPrincipal() *api.Principal {
+ return &api.Principal{
+ ID: raw.ID,
+
+ // Standard fields
+ CreatorID: raw.CreatorID,
+ CreatedTs: raw.CreatedTs,
+ UpdaterID: raw.UpdaterID,
+ UpdatedTs: raw.UpdatedTs,
+
+ // Domain specific fields
+ Type: raw.Type,
+ Name: raw.Name,
+ Email: raw.Email,
+ // Do not return to the client
+ PasswordHash: raw.PasswordHash,
+ }
+}
- cache api.CacheService
+// CreatePrincipal creates an instance of Principal
+func (s *Store) CreatePrincipal(ctx context.Context, create *api.PrincipalCreate) (*api.Principal, error) {
+ principalRaw, err := s.createPrincipalRaw(ctx, create)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to create Principal with PrincipalCreate[%+v], error[%w]", create, err)
+ }
+ // NOTE: Currently the corresponding Member object is not created yet.
+ // YES, we are returning a Principal with empty Role field. OMG.
+ principal := principalRaw.ToPrincipal()
+ return principal, nil
+}
+
+// GetPrincipalList gets a list of Principal instances
+func (s *Store) GetPrincipalList(ctx context.Context) ([]*api.Principal, error) {
+ principalRawList, err := s.findPrincipalRawList(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to find Principal list, error[%w]", err)
+ }
+ var principalList []*api.Principal
+ for _, raw := range principalRawList {
+ principal, err := s.composePrincipal(ctx, raw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Principal role with principalRaw[%+v], error[%w]", raw, err)
+ }
+ principalList = append(principalList, principal)
+ }
+ return principalList, nil
+}
+
+// FindPrincipal finds an instance of Principal
+func (s *Store) FindPrincipal(ctx context.Context, find *api.PrincipalFind) (*api.Principal, error) {
+ principalRaw, err := s.findPrincipalRaw(ctx, find)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to find Principal with PrincipalFind[%+v], error[%w]", find, err)
+ }
+ if principalRaw == nil {
+ return nil, nil
+ }
+ principal, err := s.composePrincipal(ctx, principalRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Principal role with principalRaw[%+v], error[%w]", principalRaw, err)
+ }
+ return principal, nil
+}
+
+// PatchPrincipal patches an instance of Principal
+func (s *Store) PatchPrincipal(ctx context.Context, patch *api.PrincipalPatch) (*api.Principal, error) {
+ principalRaw, err := s.patchPrincipalRaw(ctx, patch)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to patch Principal with PrincipalPatch[%+v], error[%w]", patch, err)
+ }
+ principal, err := s.composePrincipal(ctx, principalRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Principal role with principalRaw[%+v], error[%w]", principalRaw, err)
+ }
+ return principal, nil
}
-// NewPrincipalService returns a new instance of PrincipalService.
-func NewPrincipalService(logger *zap.Logger, db *DB, cache api.CacheService) *PrincipalService {
- return &PrincipalService{l: logger, db: db, cache: cache}
+// GetPrincipalByID composes an instance of Principal by ID
+func (s *Store) GetPrincipalByID(ctx context.Context, id int) (*api.Principal, error) {
+ principalFind := &api.PrincipalFind{
+ ID: &id,
+ }
+ principalRaw, err := s.findPrincipalRaw(ctx, principalFind)
+ if err != nil {
+ return nil, err
+ }
+ if id > 0 && principalRaw == nil {
+ return nil, fmt.Errorf("Principal not found with ID[%d], error[%w]", id, err)
+ }
+
+ principal, err := s.composePrincipal(ctx, principalRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Principal role with principalRaw[%+v], error[%w]", principalRaw, err)
+ }
+
+ return principal, nil
}
-// CreatePrincipal creates a new principal.
-func (s *PrincipalService) CreatePrincipal(ctx context.Context, create *api.PrincipalCreate) (*api.Principal, error) {
+//
+// private functions
+//
+
+// createPrincipalRaw creates an instance of principalRaw.
+func (s *Store) createPrincipalRaw(ctx context.Context, create *api.PrincipalCreate) (*principalRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- principal, err := createPrincipal(ctx, tx.PTx, create)
+ principal, err := createPrincipalImpl(ctx, tx.PTx, create)
if err != nil {
return nil, err
}
@@ -52,41 +158,39 @@ func (s *PrincipalService) CreatePrincipal(ctx context.Context, create *api.Prin
return principal, nil
}
-// FindPrincipalList retrieves a list of principals.
-func (s *PrincipalService) FindPrincipalList(ctx context.Context) ([]*api.Principal, error) {
+// findPrincipalRawList retrieves a list of principalRaw instances.
+func (s *Store) findPrincipalRawList(ctx context.Context) ([]*principalRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- list, err := findPrincipalList(ctx, tx.PTx, &api.PrincipalFind{})
+ list, err := findPrincipalRawListImpl(ctx, tx.PTx, &api.PrincipalFind{})
if err != nil {
return nil, err
}
- if err == nil {
- for _, principal := range list {
- if err := s.cache.UpsertCache(api.PrincipalCache, principal.ID, principal); err != nil {
- return nil, err
- }
+ for _, principal := range list {
+ if err := s.cache.UpsertCache(api.PrincipalCache, principal.ID, principal); err != nil {
+ return nil, err
}
}
return list, nil
}
-// FindPrincipal retrieves a principal based on find.
+// findPrincipalRaw retrieves an instance of principalRaw based on find.
// Returns ECONFLICT if finding more than 1 matching records.
-func (s *PrincipalService) FindPrincipal(ctx context.Context, find *api.PrincipalFind) (*api.Principal, error) {
+func (s *Store) findPrincipalRaw(ctx context.Context, find *api.PrincipalFind) (*principalRaw, error) {
if find.ID != nil {
- principal := &api.Principal{}
- has, err := s.cache.FindCache(api.PrincipalCache, *find.ID, principal)
+ principalRaw := &principalRaw{}
+ has, err := s.cache.FindCache(api.PrincipalCache, *find.ID, principalRaw)
if err != nil {
return nil, err
}
if has {
- return principal, nil
+ return principalRaw, nil
}
}
@@ -96,15 +200,15 @@ func (s *PrincipalService) FindPrincipal(ctx context.Context, find *api.Principa
}
defer tx.PTx.Rollback()
- list, err := findPrincipalList(ctx, tx.PTx, find)
+ list, err := findPrincipalRawListImpl(ctx, tx.PTx, find)
if err != nil {
return nil, err
}
if len(list) == 0 {
- return nil, nil
+ return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("principal not found with PrincipalFind[%+v]", find)}
} else if len(list) > 1 {
- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d principals with filter %+v, expect 1", len(list), find)}
+ return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d principals with PrincipalFind[%+v], expect 1", len(list), find)}
}
if err := s.cache.UpsertCache(api.PrincipalCache, list[0].ID, list[0]); err != nil {
return nil, err
@@ -113,16 +217,16 @@ func (s *PrincipalService) FindPrincipal(ctx context.Context, find *api.Principa
return list[0], nil
}
-// PatchPrincipal updates an existing principal by ID.
+// patchPrincipalRaw updates an existing instance of principalRaw by ID.
// Returns ENOTFOUND if principal does not exist.
-func (s *PrincipalService) PatchPrincipal(ctx context.Context, patch *api.PrincipalPatch) (*api.Principal, error) {
+func (s *Store) patchPrincipalRaw(ctx context.Context, patch *api.PrincipalPatch) (*principalRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- principal, err := patchPrincipal(ctx, tx.PTx, patch)
+ principal, err := patchPrincipalImpl(ctx, tx.PTx, patch)
if err != nil {
return nil, FormatError(err)
}
@@ -138,8 +242,33 @@ func (s *PrincipalService) PatchPrincipal(ctx context.Context, patch *api.Princi
return principal, nil
}
-// createPrincipal creates a new principal.
-func createPrincipal(ctx context.Context, tx *sql.Tx, create *api.PrincipalCreate) (*api.Principal, error) {
+// composePrincipal composes an instance of Principal by principalRaw
+func (s *Store) composePrincipal(ctx context.Context, raw *principalRaw) (*api.Principal, error) {
+ principal := raw.ToPrincipal()
+
+ if principal.ID == api.SystemBotID {
+ principal.Role = api.Owner
+ } else {
+ memberFind := &api.MemberFind{
+ PrincipalID: &principal.ID,
+ }
+ memberRaw, err := s.findMemberRaw(ctx, memberFind)
+ if err != nil {
+ if common.ErrorCode(err) == common.NotFound {
+ s.l.Error("Principal has not been assigned a role.",
+ zap.Int("id", principal.ID),
+ zap.String("name", principal.Name),
+ )
+ }
+ return nil, err
+ }
+ principal.Role = memberRaw.Role
+ }
+ return principal, nil
+}
+
+// createPrincipalImpl creates a new principal.
+func createPrincipalImpl(ctx context.Context, tx *sql.Tx, create *api.PrincipalCreate) (*principalRaw, error) {
// Insert row into database.
row, err := tx.QueryContext(ctx, `
INSERT INTO principal (
@@ -167,25 +296,25 @@ func createPrincipal(ctx context.Context, tx *sql.Tx, create *api.PrincipalCreat
defer row.Close()
row.Next()
- var principal api.Principal
+ var principalRaw principalRaw
if err := row.Scan(
- &principal.ID,
- &principal.CreatorID,
- &principal.CreatedTs,
- &principal.UpdaterID,
- &principal.UpdatedTs,
- &principal.Type,
- &principal.Name,
- &principal.Email,
- &principal.PasswordHash,
+ &principalRaw.ID,
+ &principalRaw.CreatorID,
+ &principalRaw.CreatedTs,
+ &principalRaw.UpdaterID,
+ &principalRaw.UpdatedTs,
+ &principalRaw.Type,
+ &principalRaw.Name,
+ &principalRaw.Email,
+ &principalRaw.PasswordHash,
); err != nil {
return nil, FormatError(err)
}
- return &principal, nil
+ return &principalRaw, nil
}
-func findPrincipalList(ctx context.Context, tx *sql.Tx, find *api.PrincipalFind) ([]*api.Principal, error) {
+func findPrincipalRawListImpl(ctx context.Context, tx *sql.Tx, find *api.PrincipalFind) ([]*principalRaw, error) {
// Build WHERE clause.
where, args := []string{"1 = 1"}, []interface{}{}
if v := find.ID; v != nil {
@@ -215,35 +344,35 @@ func findPrincipalList(ctx context.Context, tx *sql.Tx, find *api.PrincipalFind)
}
defer rows.Close()
- // Iterate over result set and deserialize rows into principalList.
- var principalList []*api.Principal
+ // Iterate over result set and deserialize rows into principalRawList.
+ var principalRawList []*principalRaw
for rows.Next() {
- var principal api.Principal
+ var principalRaw principalRaw
if err := rows.Scan(
- &principal.ID,
- &principal.CreatorID,
- &principal.CreatedTs,
- &principal.UpdaterID,
- &principal.UpdatedTs,
- &principal.Type,
- &principal.Name,
- &principal.Email,
- &principal.PasswordHash,
+ &principalRaw.ID,
+ &principalRaw.CreatorID,
+ &principalRaw.CreatedTs,
+ &principalRaw.UpdaterID,
+ &principalRaw.UpdatedTs,
+ &principalRaw.Type,
+ &principalRaw.Name,
+ &principalRaw.Email,
+ &principalRaw.PasswordHash,
); err != nil {
return nil, FormatError(err)
}
- principalList = append(principalList, &principal)
+ principalRawList = append(principalRawList, &principalRaw)
}
if err := rows.Err(); err != nil {
return nil, FormatError(err)
}
- return principalList, nil
+ return principalRawList, nil
}
-// patchPrincipal updates a principal by ID. Returns the new state of the principal after update.
-func patchPrincipal(ctx context.Context, tx *sql.Tx, patch *api.PrincipalPatch) (*api.Principal, error) {
+// patchPrincipalImpl updates a principal by ID. Returns the new state of the principal after update.
+func patchPrincipalImpl(ctx context.Context, tx *sql.Tx, patch *api.PrincipalPatch) (*principalRaw, error) {
set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
if v := patch.Name; v != nil {
set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
@@ -269,22 +398,22 @@ func patchPrincipal(ctx context.Context, tx *sql.Tx, patch *api.PrincipalPatch)
defer row.Close()
if row.Next() {
- var principal api.Principal
+ var principalRaw principalRaw
if err := row.Scan(
- &principal.ID,
- &principal.CreatorID,
- &principal.CreatedTs,
- &principal.UpdaterID,
- &principal.UpdatedTs,
- &principal.Type,
- &principal.Name,
- &principal.Email,
- &principal.PasswordHash,
+ &principalRaw.ID,
+ &principalRaw.CreatorID,
+ &principalRaw.CreatedTs,
+ &principalRaw.UpdaterID,
+ &principalRaw.UpdatedTs,
+ &principalRaw.Type,
+ &principalRaw.Name,
+ &principalRaw.Email,
+ &principalRaw.PasswordHash,
); err != nil {
return nil, FormatError(err)
}
- return &principal, nil
+ return &principalRaw, nil
}
return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("principal ID not found: %d", patch.ID)}
diff --git a/store/store.go b/store/store.go
new file mode 100644
index 0000000000..2d03e45c87
--- /dev/null
+++ b/store/store.go
@@ -0,0 +1,22 @@
+package store
+
+import (
+ "github.com/bytebase/bytebase/api"
+ "go.uber.org/zap"
+)
+
+// Store provides database access to all raw objects
+type Store struct {
+ l *zap.Logger
+ db *DB
+ cache api.CacheService
+}
+
+// New creates a new instance of Store
+func New(l *zap.Logger, db *DB, cache api.CacheService) *Store {
+ return &Store{
+ l: l,
+ db: db,
+ cache: cache,
+ }
+}