Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: decouple api/service/store packages for Task (#1179)
Yilong Li7cba91e9290f
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.goindex b359e9f853..5a72d00323 100644--- a/bin/server/cmd/root.go+++ b/bin/server/cmd/root.go@@ -465,7 +465,6 @@ func (m *Main) Run(ctx context.Context) error {s.IssueService = store.NewIssueService(m.l, db, cacheService)s.PipelineService = store.NewPipelineService(m.l, db, cacheService)s.StageService = store.NewStageService(m.l, db)- s.TaskService = store.NewTaskService(m.l, db, storeInstance)s.RepositoryService = store.NewRepositoryService(m.l, db, storeInstance)s.DeploymentConfigService = store.NewDeploymentConfigService(m.l, db)s.SheetService = store.NewSheetService(m.l, db)diff --git a/server/activity_manager.go b/server/activity_manager.goindex 5369915944..76ad1b32a8 100644--- a/server/activity_manager.go+++ b/server/activity_manager.go@@ -233,10 +233,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Areturn webhookCtx, err}- taskFind := &api.TaskFind{- ID: &update.TaskID,- }- task, err := m.s.TaskService.FindTask(ctx, taskFind)+ task, err := m.s.store.GetTaskByID(ctx, update.TaskID)if err != nil {m.s.l.Warn("Failed to post webhook event after changing the issue task status, failed to find task",zap.String("issue_name", meta.issue.Name),diff --git a/server/backup_runner.go b/server/backup_runner.goindex 819a7ee6ef..dd1c023ce5 100644--- a/server/backup_runner.go+++ b/server/backup_runner.go@@ -200,7 +200,7 @@ func (s *BackupRunner) scheduleBackupTask(ctx context.Context, database *api.Datreturn fmt.Errorf("failed to create stage: %w", err)}- _, err = s.server.TaskService.CreateTask(ctx, &api.TaskCreate{+ _, err = s.server.store.CreateTask(ctx, &api.TaskCreate{Name: backupName,PipelineID: createdPipeline.ID,StageID: createdStage.ID,diff --git a/server/database.go b/server/database.goindex f5ca715b3c..3c0293c160 100644--- a/server/database.go+++ b/server/database.go@@ -574,7 +574,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create backup stage").SetInternal(err)}- _, err = s.TaskService.CreateTask(ctx, &api.TaskCreate{+ _, err = s.store.CreateTask(ctx, &api.TaskCreate{Name: fmt.Sprintf("backup-task-%s", backup.Name),PipelineID: createdPipeline.ID,StageID: createdStage.ID,diff --git a/server/issue.go b/server/issue.goindex d44751dc3d..1cb1c75f21 100644--- a/server/issue.go+++ b/server/issue.go@@ -14,7 +14,6 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/vcs"- "github.com/bytebase/bytebase/store"ghostsql "github.com/github/gh-ost/go/sql""github.com/google/jsonapi""github.com/labstack/echo/v4"@@ -489,76 +488,6 @@ func (s *Server) createIssue(ctx context.Context, issueCreate *api.IssueCreate,return issue, nil}-func (s *Server) createPipelineValidateOnly(ctx context.Context, pc *api.PipelineCreate, creatorID int) (*api.Pipeline, error) {- // We cannot emit ID or use default zero by following https://google.aip.dev/163, otherwise- // jsonapi resource relationships will collide different resources into the same bucket.- id := 0- ts := time.Now().Unix()- pipeline := &api.Pipeline{- ID: id,- Name: pc.Name,- Status: api.PipelineOpen,- CreatorID: creatorID,- CreatedTs: ts,- UpdaterID: creatorID,- UpdatedTs: ts,- }- for _, sc := range pc.StageList {- id++- stage := &api.Stage{- ID: id,- Name: sc.Name,- CreatorID: creatorID,- CreatedTs: ts,- UpdaterID: creatorID,- UpdatedTs: ts,- PipelineID: sc.PipelineID,- EnvironmentID: sc.EnvironmentID,- }- // We don't know IDs before inserting, so we use array index instead.- // indexBlockedByIndex[indexA] holds indexes of the tasks that block taskList[indexA]- indexBlockedByIndex := make(map[int][]int)- for _, indexDAG := range sc.TaskIndexDAGList {- indexBlockedByIndex[indexDAG.ToIndex] = append(indexBlockedByIndex[indexDAG.ToIndex], indexDAG.FromIndex)- }- idOffset := id + 1- // The ID of sc.TaskList[index].ID equals index + idOffset.- for index, tc := range sc.TaskList {- id++- var blockedBy []string- for _, blockedByIndex := range indexBlockedByIndex[index] {- // Convert array index to ID.- blockedBy = append(blockedBy, strconv.Itoa(blockedByIndex+idOffset))- }- taskRaw := &store.TaskRaw{- ID: id,- Name: tc.Name,- Status: tc.Status,- CreatorID: creatorID,- CreatedTs: ts,- UpdaterID: creatorID,- UpdatedTs: ts,- Type: tc.Type,- Payload: tc.Payload,- EarliestAllowedTs: tc.EarliestAllowedTs,- PipelineID: pipeline.ID,- StageID: stage.ID,- InstanceID: tc.InstanceID,- DatabaseID: tc.DatabaseID,- }- task, err := s.composeTaskRelationship(ctx, taskRaw)- // We need to compose task.BlockedBy here because task and taskDAG are not inserted yet.- task.BlockedBy = blockedBy- if err != nil {- return nil, err- }- stage.TaskList = append(stage.TaskList, task)- }- pipeline.StageList = append(pipeline.StageList, stage)- }- return pipeline, nil-}-func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.IssueCreate, creatorID int, validateOnly bool) (*api.Pipeline, error) {var pipelineCreate *api.PipelineCreateswitch issueCreate.Type {@@ -960,7 +889,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.I// Create the pipeline, stages, and tasks.if validateOnly {- return s.createPipelineValidateOnly(ctx, pipelineCreate, creatorID)+ return s.store.CreatePipelineValidateOnly(ctx, pipelineCreate, creatorID)}pipelineCreate.CreatorID = creatorID@@ -983,7 +912,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.ItaskCreate.CreatorID = creatorIDtaskCreate.PipelineID = pipelineRawCreated.IDtaskCreate.StageID = createdStage.ID- task, err := s.TaskService.CreateTask(ctx, &taskCreate)+ task, err := s.store.CreateTask(ctx, &taskCreate)if err != nil {return nil, fmt.Errorf("failed to create task for issue, error %v", err)}diff --git a/server/server.go b/server/server.goindex 79ec98037e..5f028a7eb1 100644--- a/server/server.go+++ b/server/server.go@@ -47,7 +47,6 @@ type Server struct {IssueService api.IssueServicePipelineService api.PipelineServiceStageService api.StageService- TaskService store.TaskServiceRepositoryService api.RepositoryServiceDeploymentConfigService api.DeploymentConfigServiceLicenseService enterprise.LicenseServicediff --git a/server/stage.go b/server/stage.goindex 7b84e666c2..b6ec27a348 100644--- a/server/stage.go+++ b/server/stage.go@@ -48,7 +48,11 @@ func (s *Server) composeStageRelationship(ctx context.Context, raw *api.StageRaw}stage.Environment = env- taskList, err := s.composeTaskListByPipelineAndStageID(ctx, stage.PipelineID, stage.ID)+ taskFind := &api.TaskFind{+ PipelineID: &stage.PipelineID,+ StageID: &stage.ID,+ }+ taskList, err := s.store.FindTask(ctx, taskFind, true)if err != nil {return nil, err}diff --git a/server/task.go b/server/task.goindex ce96c5c643..278b17f9b6 100644--- a/server/task.go+++ b/server/task.go@@ -10,7 +10,6 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db"- "github.com/bytebase/bytebase/store""github.com/google/jsonapi""github.com/labstack/echo/v4""go.uber.org/zap"@@ -56,10 +55,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusForbidden, api.FeatureTaskScheduleTime.AccessErrorMessage())}- taskFind := &api.TaskFind{- ID: &taskID,- }- task, err := s.TaskService.FindTask(ctx, taskFind)+ task, err := s.store.GetTaskByID(ctx, taskID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to update task").SetInternal(err)}@@ -135,19 +131,15 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {}}- taskPatchedRaw, err := s.TaskService.PatchTask(ctx, taskPatch)+ taskPatched, err := s.store.PatchTask(ctx, taskPatch)if err != nil {+ // TODO(dragonly): double check whether this should be common.Invalid or notif common.ErrorCode(err) == common.Invalid {return echo.NewHTTPError(http.StatusBadRequest, common.ErrorMessage(err))}return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update task \"%v\"", task.Name)).SetInternal(err)}- taskPatched, err := s.composeTaskRelationship(ctx, taskPatchedRaw)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated task \"%v\" relationship", taskPatchedRaw.Name)).SetInternal(err)- }-// create an activity and trigger task check for statement updateif taskPatched.Type == api.TaskDatabaseSchemaUpdate || taskPatched.Type == api.TaskDatabaseDataUpdate {if oldStatement != newStatement {@@ -287,7 +279,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, taskPatched); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal update task \"%v\" status response", taskPatchedRaw.Name)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal update task \"%v\" status response", taskPatched.Name)).SetInternal(err)}return nil})@@ -308,23 +300,16 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformatted update task status request").SetInternal(err)}- taskFind := &api.TaskFind{- ID: &taskID,- }- taskRaw, err := s.TaskService.FindTask(ctx, taskFind)+ task, err := s.store.GetTaskByID(ctx, taskID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to update task status").SetInternal(err)}- if taskRaw == nil {+ if task == nil {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Task not found with ID %d", taskID))}- task, err := s.composeTaskRelationship(ctx, taskRaw)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to compose task relationship with ID %d", taskID)).SetInternal(err)- }issue, err := s.IssueService.FindIssue(ctx, &api.IssueFind{- PipelineID: &taskRaw.PipelineID,+ PipelineID: &task.PipelineID,})if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find issue").SetInternal(err)@@ -368,25 +353,18 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task ID is not a number: %s", c.Param("taskID"))).SetInternal(err)}- taskFind := &api.TaskFind{- ID: &taskID,- }- taskRaw, err := s.TaskService.FindTask(ctx, taskFind)+ task, err := s.store.GetTaskByID(ctx, taskID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to update task status").SetInternal(err)}- if taskRaw == nil {+ if task == nil {return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Task not found with ID %d", taskID))}- task, err := s.composeTaskRelationship(ctx, taskRaw)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to compose task %v(%v) relationship", taskRaw.ID, taskRaw.Name)).SetInternal(err)- }skipIfAlreadyTerminated := falsetaskUpdated, err := s.TaskCheckScheduler.ScheduleCheckIfNeeded(ctx, task, c.Get(getPrincipalIDContextKey()).(int), skipIfAlreadyTerminated)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to run task check \"%v\"", taskRaw.Name)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to run task check \"%v\"", task.Name)).SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)@@ -397,101 +375,6 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {})}-func (s *Server) composeTaskListByPipelineAndStageID(ctx context.Context, pipelineID int, stageID int) ([]*api.Task, error) {- taskFind := &api.TaskFind{- PipelineID: &pipelineID,- StageID: &stageID,- }- taskRawList, err := s.TaskService.FindTaskList(ctx, taskFind)- if err != nil {- return nil, err- }-- var taskList []*api.Task- for _, taskRaw := range taskRawList {- task, err := s.composeTaskRelationship(ctx, taskRaw)- if err != nil {- return nil, err- }- taskList = append(taskList, task)- }-- return taskList, nil-}--func (s *Server) composeTaskRelationship(ctx context.Context, raw *store.TaskRaw) (*api.Task, error) {- task := raw.ToTask()-- creator, err := s.store.GetPrincipalByID(ctx, task.CreatorID)- if err != nil {- return nil, err- }- task.Creator = creator-- 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.store.GetPrincipalByID(ctx, taskRun.CreatorID)- if err != nil {- return nil, err- }- taskRun.Creator = creator-- updater, err := s.store.GetPrincipalByID(ctx, taskRun.UpdaterID)- if err != nil {- return nil, err- }- taskRun.Updater = updater- }-- for _, taskCheckRun := range task.TaskCheckRunList {- creator, err := s.store.GetPrincipalByID(ctx, taskCheckRun.CreatorID)- if err != nil {- return nil, err- }- taskCheckRun.Creator = creator-- updater, err := s.store.GetPrincipalByID(ctx, taskCheckRun.UpdaterID)- if err != nil {- return nil, err- }- taskCheckRun.Updater = updater- }-- blockedBy := []string{}- taskDAGList, err := s.store.FindTaskDAGList(ctx, &api.TaskDAGFind{ToTaskID: raw.ID})- if err != nil {- return nil, err- }- for _, taskDAG := range taskDAGList {- blockedBy = append(blockedBy, strconv.Itoa(taskDAG.FromTaskID))- }- task.BlockedBy = blockedBy-- instance, err := s.store.GetInstanceByID(ctx, task.InstanceID)- if err != nil {- return nil, err- }- task.Instance = instance-- if task.DatabaseID != nil {- database, err := s.store.GetDatabase(ctx, &api.DatabaseFind{ID: task.DatabaseID})- if err != nil {- return nil, err- }- if database == nil {- return nil, fmt.Errorf("database not found with ID %v", task.DatabaseID)- }- task.Database = database- }-- return task, nil-}-// TODO(dragonly): remove this hackfunc (s *Server) composeTaskRelationshipValidateOnly(ctx context.Context, task *api.Task) error {var err error@@ -576,16 +459,11 @@ func (s *Server) changeTaskStatusWithPatch(ctx context.Context, task *api.Task,Err: fmt.Errorf("invalid task status transition from %v to %v. Applicable transition(s) %v", task.Status, taskStatusPatch.Status, applicableTaskStatusTransition[task.Status])}}- taskPatchedRaw, err := s.TaskService.PatchTaskStatus(ctx, taskStatusPatch)+ taskPatched, err := s.store.PatchTaskStatus(ctx, taskStatusPatch)if err != nil {return nil, fmt.Errorf("failed to change task %v(%v) status: %w", task.ID, task.Name, err)}- taskPatched, err := s.composeTaskRelationship(ctx, taskPatchedRaw)- if err != nil {- return nil, fmt.Errorf("failed to compose task %v(%v) relationship: %w", task.ID, task.Name, err)- }-// Most tasks belong to a pipeline which in turns belongs to an issue. The followup code// behaves differently depending on whether the task is wrapped in an issue.// TODO(tianzhou): Refactor the followup code into chained onTaskStatusChange hook.diff --git a/server/task_check_executor_database_connect.go b/server/task_check_executor_database_connect.goindex bd5c9ebaf2..9aa8dcb65f 100644--- a/server/task_check_executor_database_connect.go+++ b/server/task_check_executor_database_connect.go@@ -23,10 +23,7 @@ type TaskCheckDatabaseConnectExecutor struct {// Run will run the task check database connector executor once.func (exec *TaskCheckDatabaseConnectExecutor) Run(ctx context.Context, server *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {- taskFind := &api.TaskFind{- ID: &taskCheckRun.TaskID,- }- task, err := server.TaskService.FindTask(ctx, taskFind)+ task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)if err != nil {return []api.TaskCheckResult{}, common.Errorf(common.Internal, err)}diff --git a/server/task_check_executor_migration_schema.go b/server/task_check_executor_migration_schema.goindex ccb93e0265..44ce24c2c8 100644--- a/server/task_check_executor_migration_schema.go+++ b/server/task_check_executor_migration_schema.go@@ -23,10 +23,7 @@ type TaskCheckMigrationSchemaExecutor struct {// Run will run the task check migration schema executor once.func (exec *TaskCheckMigrationSchemaExecutor) Run(ctx context.Context, server *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {- taskFind := &api.TaskFind{- ID: &taskCheckRun.TaskID,- }- task, err := server.TaskService.FindTask(ctx, taskFind)+ task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)if err != nil {return []api.TaskCheckResult{}, common.Errorf(common.Internal, err)}diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.goindex c97d3a1e23..7b698b33fd 100644--- a/server/task_executor_database_create.go+++ b/server/task_executor_database_create.go@@ -146,7 +146,7 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *SerUpdaterID: api.SystemBotID,DatabaseID: &database.ID,}- _, err = server.TaskService.PatchTask(ctx, taskDatabaseIDPatch)+ _, err = server.store.PatchTask(ctx, taskDatabaseIDPatch)if err != nil {return true, nil, err}diff --git a/server/task_scheduler.go b/server/task_scheduler.goindex cedd0e2313..1a38bf08c3 100644--- a/server/task_scheduler.go+++ b/server/task_scheduler.go@@ -101,38 +101,29 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {taskFind := &api.TaskFind{StatusList: &taskStatusList,}- taskRawList, err := s.server.TaskService.FindTaskList(ctx, taskFind)+ // This fetches quite a bit info and may cause performance issue if we have many ongoing tasks+ // We may optimize this in the future since only some relationship info is needed by the executor+ taskList, err := s.server.store.FindTask(ctx, taskFind, false)if err != nil {s.l.Error("Failed to retrieve running tasks", zap.Error(err))return}- for _, taskRaw := range taskRawList {- if taskRaw.ID == api.OnboardingTaskID1 || taskRaw.ID == api.OnboardingTaskID2 {+ for _, task := range taskList {+ if task.ID == api.OnboardingTaskID1 || task.ID == api.OnboardingTaskID2 {continue}- executor, ok := s.executors[string(taskRaw.Type)]+ executor, ok := s.executors[string(task.Type)]if !ok {s.l.Error("Skip running task with unknown type",- zap.Int("id", taskRaw.ID),- zap.String("name", taskRaw.Name),- zap.String("type", string(taskRaw.Type)),+ zap.Int("id", task.ID),+ zap.String("name", task.Name),+ zap.String("type", string(task.Type)),)continue}- // This fetches quite a bit info and may cause performance issue if we have many ongoing tasks- // We may optimize this in the future since only some relationship info is needed by the executor- task, err := s.server.composeTaskRelationship(ctx, taskRaw)- if err != nil {- s.l.Error("Failed to fetch task relationship",- zap.Int("id", taskRaw.ID),- zap.String("name", taskRaw.Name),- zap.String("type", string(taskRaw.Type)),- )- continue- }// Skip execution if has any dependency not finished.isBlocked, err := s.isTaskBlocked(ctx, task)if err != nil {@@ -325,10 +316,7 @@ func (s *TaskScheduler) isTaskBlocked(ctx context.Context, task *api.Task) (boolif err != nil {return true, fmt.Errorf("failed to convert id string to int, id string: %v, error: %w", blockingTaskIDString, err)}- taskFind := api.TaskFind{- ID: &blockingTaskID,- }- blockingTask, err := s.server.TaskService.FindTask(ctx, &taskFind)+ blockingTask, err := s.server.store.GetTaskByID(ctx, blockingTaskID)if err != nil {return true, fmt.Errorf("failed to fetch the blocking task, id: %v, error: %w", blockingTaskID, err)}diff --git a/store/issue.go b/store/issue.goindex a11a92e90a..9716d2a843 100644--- a/store/issue.go+++ b/store/issue.go@@ -5,7 +5,9 @@ import ("database/sql""encoding/json""fmt"+ "strconv""strings"+ "time""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -29,6 +31,77 @@ func NewIssueService(logger *zap.Logger, db *DB, cache api.CacheService) *IssueSreturn &IssueService{l: logger, db: db, cache: cache}}+// CreatePipelineValidateOnly creates a pipeline for validation purpose+func (s *Store) CreatePipelineValidateOnly(ctx context.Context, pc *api.PipelineCreate, creatorID int) (*api.Pipeline, error) {+ // We cannot emit ID or use default zero by following https://google.aip.dev/163, otherwise+ // jsonapi resource relationships will collide different resources into the same bucket.+ id := 0+ ts := time.Now().Unix()+ pipeline := &api.Pipeline{+ ID: id,+ Name: pc.Name,+ Status: api.PipelineOpen,+ CreatorID: creatorID,+ CreatedTs: ts,+ UpdaterID: creatorID,+ UpdatedTs: ts,+ }+ for _, sc := range pc.StageList {+ id+++ stage := &api.Stage{+ ID: id,+ Name: sc.Name,+ CreatorID: creatorID,+ CreatedTs: ts,+ UpdaterID: creatorID,+ UpdatedTs: ts,+ PipelineID: sc.PipelineID,+ EnvironmentID: sc.EnvironmentID,+ }+ // We don't know IDs before inserting, so we use array index instead.+ // indexBlockedByIndex[indexA] holds indexes of the tasks that block taskList[indexA]+ indexBlockedByIndex := make(map[int][]int)+ for _, indexDAG := range sc.TaskIndexDAGList {+ indexBlockedByIndex[indexDAG.ToIndex] = append(indexBlockedByIndex[indexDAG.ToIndex], indexDAG.FromIndex)+ }+ idOffset := id + 1+ // The ID of sc.TaskList[index].ID equals index + idOffset.+ for index, tc := range sc.TaskList {+ id+++ var blockedBy []string+ for _, blockedByIndex := range indexBlockedByIndex[index] {+ // Convert array index to ID.+ blockedBy = append(blockedBy, strconv.Itoa(blockedByIndex+idOffset))+ }+ taskRaw := &taskRaw{+ ID: id,+ Name: tc.Name,+ Status: tc.Status,+ CreatorID: creatorID,+ CreatedTs: ts,+ UpdaterID: creatorID,+ UpdatedTs: ts,+ Type: tc.Type,+ Payload: tc.Payload,+ EarliestAllowedTs: tc.EarliestAllowedTs,+ PipelineID: pipeline.ID,+ StageID: stage.ID,+ InstanceID: tc.InstanceID,+ DatabaseID: tc.DatabaseID,+ }+ task, err := s.composeTask(ctx, taskRaw)+ // We need to compose task.BlockedBy here because task and taskDAG are not inserted yet.+ task.BlockedBy = blockedBy+ if err != nil {+ return nil, err+ }+ stage.TaskList = append(stage.TaskList, task)+ }+ pipeline.StageList = append(pipeline.StageList, stage)+ }+ return pipeline, nil+}+// CreateIssue creates a new issue.func (s *IssueService) CreateIssue(ctx context.Context, create *api.IssueCreate) (*api.IssueRaw, error) {tx, err := s.db.BeginTx(ctx, nil)diff --git a/store/task.go b/store/task.goindex 2b24acb3f2..7df22d9092 100644--- a/store/task.go+++ b/store/task.go@@ -4,6 +4,7 @@ import ("context""database/sql""fmt"+ "strconv""strings""time"@@ -12,18 +13,9 @@ import ("go.uber.org/zap")-// TaskService is the service for tasks.-type TaskService interface {- CreateTask(ctx context.Context, create *api.TaskCreate) (*TaskRaw, error)- FindTaskList(ctx context.Context, find *api.TaskFind) ([]*TaskRaw, error)- FindTask(ctx context.Context, find *api.TaskFind) (*TaskRaw, error)- PatchTask(ctx context.Context, patch *api.TaskPatch) (*TaskRaw, error)- PatchTaskStatus(ctx context.Context, patch *api.TaskStatusPatch) (*TaskRaw, error)-}--// TaskRaw is the store model for an Task.+// taskRaw is the store model for an Task.// Fields have exactly the same meanings as Task.-type TaskRaw struct {+type taskRaw struct {ID int// Standard fields@@ -50,9 +42,9 @@ type TaskRaw struct {BlockedBy []string}-// ToTask creates an instance of Task based on the TaskRaw.+// toTask creates an instance of Task based on the taskRaw.// This is intended to be called when we need to compose an Task relationship.-func (raw *TaskRaw) ToTask() *api.Task {+func (raw *taskRaw) toTask() *api.Task {task := &api.Task{ID: raw.ID,@@ -86,32 +78,172 @@ func (raw *TaskRaw) ToTask() *api.Task {return task}-var (- _ TaskService = (*TaskServiceImpl)(nil)-)+// CreateTask creates an instance of Task+func (s *Store) CreateTask(ctx context.Context, create *api.TaskCreate) (*api.Task, error) {+ taskRaw, err := s.createTaskRaw(ctx, create)+ if err != nil {+ return nil, fmt.Errorf("failed to create Task with TaskCreate[%+v], error[%w]", create, err)+ }+ task, err := s.composeTask(ctx, taskRaw)+ if err != nil {+ return nil, fmt.Errorf("failed to compose Task with taskRaw[%+v], error[%w]", taskRaw, err)+ }+ return task, nil+}++// GetTaskByID gets an instance of Task+func (s *Store) GetTaskByID(ctx context.Context, id int) (*api.Task, error) {+ find := &api.TaskFind{ID: &id}+ taskRaw, err := s.getTaskRaw(ctx, find)+ if err != nil {+ return nil, fmt.Errorf("failed to get Task with ID[%d], error[%w]", id, err)+ }+ if taskRaw == nil {+ return nil, nil+ }+ task, err := s.composeTask(ctx, taskRaw)+ if err != nil {+ return nil, fmt.Errorf("failed to compose Task with taskRaw[%+v], error[%w]", taskRaw, err)+ }+ return task, nil+}-// TaskServiceImpl represents a service for managing task.-type TaskServiceImpl struct {- l *zap.Logger- db *DB+// FindTask finds a list of Task instances+func (s *Store) FindTask(ctx context.Context, find *api.TaskFind, returnOnErr bool) ([]*api.Task, error) {+ taskRawList, err := s.findTaskRaw(ctx, find)+ if err != nil {+ return nil, fmt.Errorf("failed to find Task list, error[%w]", err)+ }+ var taskList []*api.Task+ for _, raw := range taskRawList {+ task, err := s.composeTask(ctx, raw)+ if err != nil {+ if returnOnErr {+ return nil, fmt.Errorf("failed to compose Task with taskRaw[%+v], error[%w]", raw, err)+ }+ s.l.Error("failed to compose Task",+ zap.Any("taskRaw", raw),+ zap.Error(err))+ continue- store *Store+ }+ taskList = append(taskList, task)+ }+ return taskList, nil}-// NewTaskService returns a new instance of TaskService.-func NewTaskService(logger *zap.Logger, db *DB, store *Store) *TaskServiceImpl {- return &TaskServiceImpl{l: logger, db: db, store: store}+// PatchTask patches an instance of Task+func (s *Store) PatchTask(ctx context.Context, patch *api.TaskPatch) (*api.Task, error) {+ taskRaw, err := s.patchTaskRaw(ctx, patch)+ if err != nil {+ return nil, fmt.Errorf("failed to patch Task with TaskPatch[%+v], error[%w]", patch, err)+ }+ task, err := s.composeTask(ctx, taskRaw)+ if err != nil {+ return nil, fmt.Errorf("failed to compose Task with taskRaw[%+v], error[%w]", taskRaw, err)+ }+ return task, nil+}++// PatchTaskStatus patches an instance of TaskStatus+func (s *Store) PatchTaskStatus(ctx context.Context, patch *api.TaskStatusPatch) (*api.Task, error) {+ taskRaw, err := s.patchTaskRawStatus(ctx, patch)+ if err != nil {+ return nil, fmt.Errorf("failed to patch TaskStatus with TaskStatusPatch[%+v], error[%w]", patch, err)+ }+ task, err := s.composeTask(ctx, taskRaw)+ if err != nil {+ return nil, fmt.Errorf("failed to compose TaskStatus with taskRaw[%+v], error[%w]", taskRaw, err)+ }+ return task, nil}-// CreateTask creates a new task.-func (s *TaskServiceImpl) CreateTask(ctx context.Context, create *api.TaskCreate) (*TaskRaw, error) {+//+// private functions+//++func (s *Store) composeTask(ctx context.Context, raw *taskRaw) (*api.Task, error) {+ task := raw.toTask()++ creator, err := s.GetPrincipalByID(ctx, task.CreatorID)+ if err != nil {+ return nil, err+ }+ task.Creator = creator++ updater, err := s.GetPrincipalByID(ctx, task.UpdaterID)+ if err != nil {+ return nil, err+ }+ task.Updater = updater++ for _, taskRun := range task.TaskRunList {+ creator, err := s.GetPrincipalByID(ctx, taskRun.CreatorID)+ if err != nil {+ return nil, err+ }+ taskRun.Creator = creator++ updater, err := s.GetPrincipalByID(ctx, taskRun.UpdaterID)+ if err != nil {+ return nil, err+ }+ taskRun.Updater = updater+ }++ for _, taskCheckRun := range task.TaskCheckRunList {+ creator, err := s.GetPrincipalByID(ctx, taskCheckRun.CreatorID)+ if err != nil {+ return nil, err+ }+ taskCheckRun.Creator = creator++ updater, err := s.GetPrincipalByID(ctx, taskCheckRun.UpdaterID)+ if err != nil {+ return nil, err+ }+ taskCheckRun.Updater = updater+ }++ blockedBy := []string{}+ taskDAGList, err := s.FindTaskDAGList(ctx, &api.TaskDAGFind{ToTaskID: raw.ID})+ if err != nil {+ return nil, err+ }+ for _, taskDAG := range taskDAGList {+ blockedBy = append(blockedBy, strconv.Itoa(taskDAG.FromTaskID))+ }+ task.BlockedBy = blockedBy++ instance, err := s.GetInstanceByID(ctx, task.InstanceID)+ if err != nil {+ return nil, err+ }+ task.Instance = instance++ if task.DatabaseID != nil {+ database, err := s.GetDatabase(ctx, &api.DatabaseFind{ID: task.DatabaseID})+ if err != nil {+ return nil, err+ }+ if database == nil {+ return nil, fmt.Errorf("database not found with ID %v", task.DatabaseID)+ }+ task.Database = database+ }++ return task, nil+}++// createTaskRaw creates a new task.+func (s *Store) createTaskRaw(ctx context.Context, create *api.TaskCreate) (*taskRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)}defer tx.PTx.Rollback()- task, err := s.createTask(ctx, tx.PTx, create)+ task, err := s.createTaskImpl(ctx, tx.PTx, create)if err != nil {return nil, err}@@ -123,15 +255,15 @@ func (s *TaskServiceImpl) CreateTask(ctx context.Context, create *api.TaskCreatereturn task, nil}-// FindTaskList retrieves a list of tasks based on find.-func (s *TaskServiceImpl) FindTaskList(ctx context.Context, find *api.TaskFind) ([]*TaskRaw, error) {+// findTaskRaw retrieves a list of tasks based on find.+func (s *Store) findTaskRaw(ctx context.Context, find *api.TaskFind) ([]*taskRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)}defer tx.PTx.Rollback()- list, err := s.findTaskList(ctx, tx.PTx, find)+ list, err := s.findTaskImpl(ctx, tx.PTx, find)if err != nil {return nil, err}@@ -139,28 +271,42 @@ func (s *TaskServiceImpl) FindTaskList(ctx context.Context, find *api.TaskFind)return list, nil}-// FindTask retrieves a single task based on find.+// getTaskRaw retrieves a single task based on find.// Returns ECONFLICT if finding more than 1 matching records.-func (s *TaskServiceImpl) FindTask(ctx context.Context, find *api.TaskFind) (*TaskRaw, error) {+func (s *Store) getTaskRaw(ctx context.Context, find *api.TaskFind) (*taskRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)}defer tx.PTx.Rollback()- return s.findTask(ctx, tx.PTx, find)+ return s.getTaskRawTx(ctx, tx.PTx, find)+}++func (s *Store) getTaskRawTx(ctx context.Context, tx *sql.Tx, find *api.TaskFind) (*taskRaw, error) {+ list, err := s.findTaskImpl(ctx, tx, find)+ if err != nil {+ return nil, err+ }++ if len(list) == 0 {+ return nil, nil+ } else if len(list) > 1 {+ return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d tasks with filter %+v, expect 1", len(list), find)}+ }+ return list[0], nil}-// PatchTask updates an existing task.+// patchTaskRaw updates an existing task.// Returns ENOTFOUND if task does not exist.-func (s *TaskServiceImpl) PatchTask(ctx context.Context, patch *api.TaskPatch) (*TaskRaw, error) {+func (s *Store) patchTaskRaw(ctx context.Context, patch *api.TaskPatch) (*taskRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)}defer tx.PTx.Rollback()- task, err := s.patchTask(ctx, tx.PTx, patch)+ task, err := s.patchTaskImpl(ctx, tx.PTx, patch)if err != nil {return nil, FormatError(err)}@@ -172,9 +318,9 @@ func (s *TaskServiceImpl) PatchTask(ctx context.Context, patch *api.TaskPatch) (return task, nil}-// PatchTaskStatus updates an existing task status and the corresponding task run status atomically.+// patchTaskRawStatus updates an existing task status and the corresponding task run status atomically.// Returns ENOTFOUND if task does not exist.-func (s *TaskServiceImpl) PatchTaskStatus(ctx context.Context, patch *api.TaskStatusPatch) (*TaskRaw, error) {+func (s *Store) patchTaskRawStatus(ctx context.Context, patch *api.TaskStatusPatch) (*taskRaw, error) {// Without using serializable isolation transaction, we will get race condition and have multiple task runs inserted because// we do a read and write on task, without guanrantee consistency on task runs.// Once we have multiple task runs, the task will get to unrecoverable state because find task run will fail with two active runs.@@ -184,7 +330,7 @@ func (s *TaskServiceImpl) PatchTaskStatus(ctx context.Context, patch *api.TaskSt}defer tx.PTx.Rollback()- task, err := s.patchTaskStatus(ctx, tx.PTx, patch)+ task, err := s.patchTaskStatusImpl(ctx, tx.PTx, patch)if err != nil {return nil, FormatError(err)}@@ -196,8 +342,8 @@ func (s *TaskServiceImpl) PatchTaskStatus(ctx context.Context, patch *api.TaskStreturn task, nil}-// createTask creates a new task.-func (s *TaskServiceImpl) createTask(ctx context.Context, tx *sql.Tx, create *api.TaskCreate) (*TaskRaw, error) {+// createTaskImpl creates a new task.+func (s *Store) createTaskImpl(ctx context.Context, tx *sql.Tx, create *api.TaskCreate) (*taskRaw, error) {var row *sql.Rowsvar err error@@ -270,7 +416,7 @@ func (s *TaskServiceImpl) createTask(ctx context.Context, tx *sql.Tx, create *apdefer row.Close()row.Next()- var taskRaw TaskRaw+ var taskRaw taskRawvar databaseID sql.NullInt32if err := row.Scan(&taskRaw.ID,@@ -299,21 +445,7 @@ func (s *TaskServiceImpl) createTask(ctx context.Context, tx *sql.Tx, create *apreturn &taskRaw, nil}-func (s *TaskServiceImpl) findTask(ctx context.Context, tx *sql.Tx, find *api.TaskFind) (*TaskRaw, error) {- list, err := s.findTaskList(ctx, tx, find)- if err != nil {- return nil, err- }-- if len(list) == 0 {- return nil, nil- } else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d tasks with filter %+v, expect 1", len(list), find)}- }- return list[0], nil-}--func (s *TaskServiceImpl) findTaskList(ctx context.Context, tx *sql.Tx, find *api.TaskFind) ([]*TaskRaw, error) {+func (s *Store) findTaskImpl(ctx context.Context, tx *sql.Tx, find *api.TaskFind) ([]*taskRaw, error) {// Build WHERE clause.where, args := []string{"1 = 1"}, []interface{}{}if v := find.ID; v != nil {@@ -360,9 +492,9 @@ func (s *TaskServiceImpl) findTaskList(ctx context.Context, tx *sql.Tx, find *apdefer rows.Close()// Iterate over result set and deserialize rows into taskRawList.- var taskRawList []*TaskRaw+ var taskRawList []*taskRawfor rows.Next() {- var taskRaw TaskRaw+ var taskRaw taskRawif err := rows.Scan(&taskRaw.ID,&taskRaw.CreatorID,@@ -388,7 +520,7 @@ func (s *TaskServiceImpl) findTaskList(ctx context.Context, tx *sql.Tx, find *aptaskRunFind := &api.TaskRunFind{TaskID: &taskRaw.ID,}- taskRunRawList, err := s.store.findTaskRunImpl(ctx, tx, taskRunFind)+ taskRunRawList, err := s.findTaskRunImpl(ctx, tx, taskRunFind)if err != nil {return nil, err}@@ -397,7 +529,7 @@ func (s *TaskServiceImpl) findTaskList(ctx context.Context, tx *sql.Tx, find *aptaskCheckRunFind := &api.TaskCheckRunFind{TaskID: &taskRaw.ID,}- taskCheckRunRawList, err := s.store.findTaskCheckRunImpl(ctx, tx, taskCheckRunFind)+ taskCheckRunRawList, err := s.findTaskCheckRunImpl(ctx, tx, taskCheckRunFind)if err != nil {return nil, err}@@ -409,8 +541,8 @@ func (s *TaskServiceImpl) findTaskList(ctx context.Context, tx *sql.Tx, find *apreturn taskRawList, nil}-// patchTask updates a task by ID. Returns the new state of the task after update.-func (s *TaskServiceImpl) patchTask(ctx context.Context, tx *sql.Tx, patch *api.TaskPatch) (*TaskRaw, error) {+// patchTaskImpl updates a task by ID. Returns the new state of the task after update.+func (s *Store) patchTaskImpl(ctx context.Context, tx *sql.Tx, patch *api.TaskPatch) (*taskRaw, error) {// Build UPDATE clause.set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}if v := patch.DatabaseID; v != nil {@@ -443,7 +575,7 @@ func (s *TaskServiceImpl) patchTask(ctx context.Context, tx *sql.Tx, patch *api.defer row.Close()if row.Next() {- var taskRaw TaskRaw+ var taskRaw taskRawif err := row.Scan(&taskRaw.ID,&taskRaw.CreatorID,@@ -469,30 +601,30 @@ func (s *TaskServiceImpl) patchTask(ctx context.Context, tx *sql.Tx, patch *api.return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("task not found with ID %d", patch.ID)}}-// patchTaskStatus updates a task status by ID. Returns the new state of the task after update.-func (s *TaskServiceImpl) patchTaskStatus(ctx context.Context, tx *sql.Tx, patch *api.TaskStatusPatch) (*TaskRaw, error) {+// patchTaskStatusImpl updates a task status by ID. Returns the new state of the task after update.+func (s *Store) patchTaskStatusImpl(ctx context.Context, tx *sql.Tx, patch *api.TaskStatusPatch) (*taskRaw, error) {// Updates the corresponding task run if applicable.// We update the task run first because updating task below returns row and it's a bit complicated to// arrange code to prevent that opening row interfering with the task run update.taskFind := &api.TaskFind{ID: &patch.ID,}- taskRaw, err := s.findTask(ctx, tx, taskFind)+ taskRawObj, err := s.getTaskRawTx(ctx, tx, taskFind)if err != nil {return nil, err}- if taskRaw == nil {+ if taskRawObj == nil {return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("task ID not found: %d", patch.ID)}}- if !(taskRaw.Status == api.TaskPendingApproval && patch.Status == api.TaskPending) {+ if !(taskRawObj.Status == api.TaskPendingApproval && patch.Status == api.TaskPending) {taskRunFind := &api.TaskRunFind{- TaskID: &taskRaw.ID,+ TaskID: &taskRawObj.ID,StatusList: &[]api.TaskRunStatus{api.TaskRunRunning,},}- taskRunRaw, err := s.store.getTaskRunRawTx(ctx, tx, taskRunFind)+ taskRunRaw, err := s.getTaskRunRawTx(ctx, tx, taskRunFind)if err != nil {return nil, err}@@ -502,17 +634,17 @@ func (s *TaskServiceImpl) patchTaskStatus(ctx context.Context, tx *sql.Tx, patch}taskRunCreate := &api.TaskRunCreate{CreatorID: patch.UpdaterID,- TaskID: taskRaw.ID,- Name: fmt.Sprintf("%s %d", taskRaw.Name, time.Now().Unix()),- Type: taskRaw.Type,- Payload: taskRaw.Payload,+ TaskID: taskRawObj.ID,+ Name: fmt.Sprintf("%s %d", taskRawObj.Name, time.Now().Unix()),+ Type: taskRawObj.Type,+ Payload: taskRawObj.Payload,}- if _, err := s.store.createTaskRunImpl(ctx, tx, taskRunCreate); err != nil {+ if _, err := s.createTaskRunImpl(ctx, tx, taskRunCreate); err != nil {return nil, err}} else {if patch.Status == api.TaskRunning {- return nil, fmt.Errorf("task is already running: %v", taskRaw.Name)+ return nil, fmt.Errorf("task is already running: %v", taskRawObj.Name)}taskRunStatusPatch := &api.TaskRunStatusPatch{ID: &taskRunRaw.ID,@@ -532,7 +664,7 @@ func (s *TaskServiceImpl) patchTaskStatus(ctx context.Context, tx *sql.Tx, patchcase api.TaskCanceled:taskRunStatusPatch.Status = api.TaskRunCanceled}- if _, err := s.store.patchTaskRunStatusImpl(ctx, tx, taskRunStatusPatch); err != nil {+ if _, err := s.patchTaskRunStatusImpl(ctx, tx, taskRunStatusPatch); err != nil {return nil, err}}@@ -557,9 +689,9 @@ func (s *TaskServiceImpl) patchTaskStatus(ctx context.Context, tx *sql.Tx, patchreturn nil, FormatError(err)}- var taskPatchedRaw *TaskRaw+ var taskPatchedRaw *taskRawif row.Next() {- var taskRaw TaskRaw+ var taskRaw taskRawif err := row.Scan(&taskRaw.ID,&taskRaw.CreatorID,@@ -589,22 +721,22 @@ func (s *TaskServiceImpl) patchTaskStatus(ctx context.Context, tx *sql.Tx, patch}taskRunFind := &api.TaskRunFind{- TaskID: &taskRaw.ID,+ TaskID: &taskRawObj.ID,}- taskRunRawList, err := s.store.findTaskRunImpl(ctx, tx, taskRunFind)+ taskRunRawList, err := s.findTaskRunImpl(ctx, tx, taskRunFind)if err != nil {return nil, err}- taskRaw.TaskRunRawList = taskRunRawList+ taskRawObj.TaskRunRawList = taskRunRawListtaskCheckRunFind := &api.TaskCheckRunFind{- TaskID: &taskRaw.ID,+ TaskID: &taskRawObj.ID,}- taskCheckRunRawList, err := s.store.findTaskCheckRunImpl(ctx, tx, taskCheckRunFind)+ taskCheckRunRawList, err := s.findTaskCheckRunImpl(ctx, tx, taskCheckRunFind)if err != nil {return nil, err}- taskRaw.TaskCheckRunRawList = taskCheckRunRawList+ taskRawObj.TaskCheckRunRawList = taskCheckRunRawListreturn taskPatchedRaw, nil}