Skip to content

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

Add the approval workflow

天舟97870d2996da
diff --git a/backend/server/acl_casbin_policy_dba.csv b/backend/server/acl_casbin_policy_dba.csv
index 66a3f1e26d..88fbace24b 100644
--- a/backend/server/acl_casbin_policy_dba.csv
+++ b/backend/server/acl_casbin_policy_dba.csv
@@ -33,5 +33,6 @@ p, DBA, /bookmark, POST
p, DBA, /bookmark, GET
p, DBA, /bookmark/{id}, DELETE_SELF
p, DBA, /pipeline/{pipelineId}/task/{taskId}/status, PATCH
+p, DBA, /pipeline/{pipelineId}/task/{taskId}/approve, POST
p, DBA, /sql/ping, POST
p, DBA, /sql/syncschema, POST
\ No newline at end of file
diff --git a/backend/server/acl_casbin_policy_developer.csv b/backend/server/acl_casbin_policy_developer.csv
index 0f9a7f4e6b..c44f01251a 100644
--- a/backend/server/acl_casbin_policy_developer.csv
+++ b/backend/server/acl_casbin_policy_developer.csv
@@ -29,4 +29,5 @@ p, DEVELOPER, /bookmark, POST
p, DEVELOPER, /bookmark, GET
p, DEVELOPER, /bookmark/{id}, DELETE_SELF
p, DEVELOPER, /pipeline/{pipelineId}/task/{taskId}/status, PATCH
+p, DEVELOPER, /pipeline/{pipelineId}/task/{taskId}/approve, POST
p, DEVELOPER, /sql/ping, POST
diff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csv
index 48d37196cd..e59ff68582 100644
--- a/backend/server/acl_casbin_policy_owner.csv
+++ b/backend/server/acl_casbin_policy_owner.csv
@@ -38,5 +38,6 @@ p, OWNER, /bookmark, POST
p, OWNER, /bookmark, GET
p, OWNER, /bookmark/{id}, DELETE_SELF
p, OWNER, /pipeline/{pipelineId}/task/{taskId}/status, PATCH
+p, OWNER, /pipeline/{pipelineId}/task/{taskId}/approve, POST
p, OWNER, /sql/ping, POST
p, OWNER, /sql/syncschema, POST
diff --git a/backend/server/issue.go b/backend/server/issue.go
index f7043bf90a..7d0d882fae 100644
--- a/backend/server/issue.go
+++ b/backend/server/issue.go
@@ -73,16 +73,9 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
return err
}
- for _, stage := range issue.Pipeline.StageList {
- for _, task := range stage.TaskList {
- _, err := s.TaskScheduler.Schedule(*task)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to schedule task after creating the issue: %v", issue.Name)).SetInternal(err)
- }
- goto End
- }
+ if err := s.ScheduleNextTaskIfNeeded(context.Background(), issue.Pipeline); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to schedule task after creating the issue: %v", issue.Name)).SetInternal(err)
}
- End:
activityCreate := &api.ActivityCreate{
CreatorId: c.Get(GetPrincipalIdContextKey()).(int),
@@ -226,7 +219,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
// Returns error if any of the tasks is not in the end status.
for _, stage := range issue.Pipeline.StageList {
for _, task := range stage.TaskList {
- if task.Status.IsEndStatus() {
+ if !task.Status.IsEndStatus() {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Failed to resolve issue: %v. Task %v is in %v status.", issue.Name, task.Name, task.Status))
}
}
diff --git a/backend/server/pipeline.go b/backend/server/pipeline.go
index 4605cc5d7d..25f9f9875a 100644
--- a/backend/server/pipeline.go
+++ b/backend/server/pipeline.go
@@ -49,3 +49,21 @@ func (s *Server) ComposePipelineRelationship(ctx context.Context, pipeline *api.
return nil
}
+
+// Try to schedule the next task if needed
+func (s *Server) ScheduleNextTaskIfNeeded(ctx context.Context, pipeline *api.Pipeline) error {
+ for _, stage := range pipeline.StageList {
+ for _, task := range stage.TaskList {
+ if !task.Status.IsEndStatus() {
+ if task.When == api.TaskOnSuccess {
+ _, err := s.TaskScheduler.Schedule(context.Background(), *task, api.SYSTEM_BOT_ID)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ }
+ }
+ return nil
+}
diff --git a/backend/server/task.go b/backend/server/task.go
index cb36d745a9..6ba2e43b63 100644
--- a/backend/server/task.go
+++ b/backend/server/task.go
@@ -46,6 +46,35 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
}
return nil
})
+
+ g.POST("/pipeline/:pipelineId/task/:taskId/approve", func(c echo.Context) error {
+ taskId, err := strconv.Atoi(c.Param("taskId"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task ID is not a number: %s", c.Param("taskId"))).SetInternal(err)
+ }
+
+ task, err := s.ComposeTaskById(context.Background(), taskId, []string{})
+ if err != nil {
+ return err
+ }
+
+ if task.When != api.TaskManual {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task does not require approval: %v", task.Name))
+ }
+
+ if task.Status != api.TaskPending {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task is not waiting for approval: %v", task.Name))
+ }
+
+ _, err = s.TaskScheduler.Schedule(context.Background(), *task, c.Get(GetPrincipalIdContextKey()).(int))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to schedule task after approval: %v", task.Name))
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ c.Response().WriteHeader(http.StatusOK)
+ return nil
+ })
}
func (s *Server) ComposeTaskListByStageId(ctx context.Context, stageId int, includeList []string) ([]*api.Task, error) {
@@ -66,6 +95,25 @@ func (s *Server) ComposeTaskListByStageId(ctx context.Context, stageId int, incl
return taskList, nil
}
+func (s *Server) ComposeTaskById(ctx context.Context, id int, includeList []string) (*api.Task, error) {
+ taskFind := &api.TaskFind{
+ ID: &id,
+ }
+ task, err := s.TaskService.FindTask(context.Background(), taskFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Task ID not found: %d", id))
+ }
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch task ID: %v", id)).SetInternal(err)
+ }
+
+ if err := s.ComposeTaskRelationship(ctx, task, includeList); err != nil {
+ return nil, err
+ }
+
+ return task, nil
+}
+
func (s *Server) ComposeTaskRelationship(ctx context.Context, task *api.Task, includeList []string) error {
var err error
diff --git a/backend/server/task_scheduler.go b/backend/server/task_scheduler.go
index 1a2605fefd..827e30f849 100644
--- a/backend/server/task_scheduler.go
+++ b/backend/server/task_scheduler.go
@@ -103,14 +103,16 @@ func (s *TaskScheduler) Register(taskType string, executor TaskExecutor) {
s.executors[taskType] = executor
}
-func (s *TaskScheduler) Schedule(task api.Task) (*api.TaskRun, error) {
+func (s *TaskScheduler) Schedule(ctx context.Context, task api.Task, creatorId int) (*api.TaskRun, error) {
taskRunCreate := &api.TaskRunCreate{
- TaskId: task.ID,
- Name: fmt.Sprintf("%s %d", task.Name, time.Now().Unix()),
- Type: task.Type,
- Payload: task.Payload,
+ CreatorId: creatorId,
+ WorkspaceId: api.DEFAULT_WORKPSACE_ID,
+ TaskId: task.ID,
+ Name: fmt.Sprintf("%s %d", task.Name, time.Now().Unix()),
+ Type: task.Type,
+ Payload: task.Payload,
}
- createdTaskRun, err := s.server.TaskRunService.CreateTaskRun(context.Background(), taskRunCreate)
+ createdTaskRun, err := s.server.TaskRunService.CreateTaskRun(ctx, taskRunCreate)
if err != nil {
return nil, fmt.Errorf("failed to create task: %w", err)
}
diff --git a/backend/store/migration/0001_init_schema.up.sql b/backend/store/migration/0001_init_schema.up.sql
index d2c2ecae30..c83c1a5719 100644
--- a/backend/store/migration/0001_init_schema.up.sql
+++ b/backend/store/migration/0001_init_schema.up.sql
@@ -561,8 +561,8 @@ CREATE TABLE issue (
description TEXT NOT NULL,
assignee_id INTEGER REFERENCES principal (id),
subscriber_id_list TEXT NOT NULL,
- `sql` TEXT NOT NULL,
- rollback_sql TEXT NOT NULL,
+ `sql` TEXT NOT NULL DEFAULT '',
+ rollback_sql TEXT NOT NULL DEFAULT '',
payload TEXT NOT NULL DEFAULT ''
);
diff --git a/backend/store/seed/0110_task.sql b/backend/store/seed/0110_task.sql
index 17db8335d8..f32fa08c71 100644
--- a/backend/store/seed/0110_task.sql
+++ b/backend/store/seed/0110_task.sql
@@ -11,7 +11,8 @@ INSERT INTO
name,
`type`,
`status`,
- `when`
+ `when`,
+ payload
)
VALUES
(
@@ -22,10 +23,11 @@ VALUES
9001,
10001,
7008,
- 'Waiting approval',
+ 'Welcome',
'bb.task.approve',
'PENDING',
- 'MANUAL'
+ 'MANUAL',
+ '{"Sql":"SELECT ''Welcome Tech Lead, DBA, Developer'';"}'
);
-- Task for Pipeline 9002 add column
@@ -177,7 +179,7 @@ VALUES
'Update fakedb1',
'bb.task.database.schema.update',
'PENDING',
- 'ON_SUCCESS'
+ 'MANUAL'
);
-- Task for stage 10003 "Integration" to update database 7004 'fakedb2'
diff --git a/backend/store/seed/0130_issue.sql b/backend/store/seed/0130_issue.sql
index 52a4857073..3785b20408 100644
--- a/backend/store/seed/0130_issue.sql
+++ b/backend/store/seed/0130_issue.sql
@@ -13,8 +13,7 @@ INSERT INTO
description,
assignee_id,
subscriber_id_list,
- `sql`,
- rollback_sql
+ `sql`
)
VALUES
(
@@ -27,11 +26,10 @@ VALUES
'Hello world!',
'OPEN',
'bb.issue.general',
- 'Welcome to Bytebase, this is the issue interface where tech leads, developers and DBAs collaborate on database management issues such as: ' || char(10, 10) || ' - Requesting a new database' || char(10) || ' - Creating a table' || char(10) || ' - Creating an index' || char(10) || ' - Adding a column' || char(10) || ' - Troubleshooting performance issue' || char(10, 10) || 'Let''s bookmark this issue by clicking the star icon on the top of this page.',
+ 'Welcome to Bytebase, this is the issue interface where tech leads, developers and DBAs collaborate on database management issues such as: ' || char(10, 10) || ' - Requesting a new database' || char(10) || ' - Creating a table' || char(10) || ' - Creating an index' || char(10) || ' - Adding a column' || char(10) || ' - Troubleshooting performance issue' || char(10, 10) || 'Let''s bookmark this issue by clicking the star icon on the top of this page.' || char(10, 10) || 'And then click the ''Approve'' button on the top right.',
1001,
'1001,1002,1003,1004',
- 'SELECT ''Welcome''' || char(10) || 'FROM engineering' || char(10) || 'WHERE role IN (''Tech Lead'', ''Developer'', ''DBA'')' || char(10) || 'AND taste = ''Good'';',
- ''
+ 'SELECT ''Welcome Tech Lead, DBA, Developer'';'
);
-- Issue for the multi stage add column pipeline
diff --git a/frontend/src/components/IssueStatusTransitionButtonGroup.vue b/frontend/src/components/IssueStatusTransitionButtonGroup.vue
index 464d9333a1..7d24e591f5 100644
--- a/frontend/src/components/IssueStatusTransitionButtonGroup.vue
+++ b/frontend/src/components/IssueStatusTransitionButtonGroup.vue
@@ -157,6 +157,7 @@ import {
ISSUE_STATUS_TRANSITION_LIST,
Principal,
TaskId,
+ TaskStatusChange,
TaskStatusPatch,
} from "../types";
import { OutputField, IssueTemplate } from "../plugins";
@@ -249,6 +250,10 @@ export default {
updateStatusModalState.style = "INFO";
updateStatusModalState.title = `Run '${task.name}'?`;
break;
+ case "APPROVE":
+ updateStatusModalState.style = "INFO";
+ updateStatusModalState.title = `Approve '${task.name}'?`;
+ break;
case "RETRY":
updateStatusModalState.style = "INFO";
updateStatusModalState.title = `Retry '${task.name}'?`;
@@ -272,19 +277,34 @@ export default {
taskId: TaskId,
comment?: string
) => {
- const taskStatusPatch: TaskStatusPatch = {
- updaterId: currentUser.value.id,
- containerId: (props.issue as Issue).id,
- status: transition.to,
- comment: comment ? comment.trim() : undefined,
- };
+ if (transition.type == "APPROVE") {
+ const taskStatusChange: TaskStatusChange = {
+ updaterId: currentUser.value.id,
+ containerId: (props.issue as Issue).id,
+ comment: comment ? comment.trim() : undefined,
+ };
- store.dispatch("task/updateStatus", {
- issueId: (props.issue as Issue).id,
- pipelineId: (props.issue as Issue).pipeline.id,
- taskId,
- taskStatusPatch,
- });
+ store.dispatch("task/approve", {
+ issueId: (props.issue as Issue).id,
+ pipelineId: (props.issue as Issue).pipeline.id,
+ taskId,
+ taskStatusChange,
+ });
+ } else {
+ const taskStatusPatch: TaskStatusPatch = {
+ updaterId: currentUser.value.id,
+ containerId: (props.issue as Issue).id,
+ status: transition.to,
+ comment: comment ? comment.trim() : undefined,
+ };
+
+ store.dispatch("task/updateStatus", {
+ issueId: (props.issue as Issue).id,
+ pipelineId: (props.issue as Issue).pipeline.id,
+ taskId,
+ taskStatusPatch,
+ });
+ }
};
const applicableIssueStatusTransitionList = computed(
diff --git a/frontend/src/components/StatusTransitionForm.vue b/frontend/src/components/StatusTransitionForm.vue
index a21d1cac3e..ae7261e83b 100644
--- a/frontend/src/components/StatusTransitionForm.vue
+++ b/frontend/src/components/StatusTransitionForm.vue
@@ -50,7 +50,16 @@
<textarea
ref="commentTextArea"
rows="3"
- class="textarea block w-full resize-none mt-1 text-sm text-control rounded-md whitespace-pre-wrap"
+ class="
+ textarea
+ block
+ w-full
+ resize-none
+ mt-1
+ text-sm text-control
+ rounded-md
+ whitespace-pre-wrap
+ "
placeholder="(Optional) Add a note..."
v-model="state.comment"
@input="
@@ -158,6 +167,8 @@ export default {
switch ((props.transition as TaskStatusTransition).type) {
case "RUN":
return "btn-primary";
+ case "APPROVE":
+ return "btn-primary";
case "RETRY":
return "btn-primary";
case "CANCEL":
diff --git a/frontend/src/store/modules/task.ts b/frontend/src/store/modules/task.ts
index 694706994d..7262a03762 100644
--- a/frontend/src/store/modules/task.ts
+++ b/frontend/src/store/modules/task.ts
@@ -16,6 +16,7 @@ import {
ResourceIdentifier,
Principal,
TaskRun,
+ TaskStatusChange,
} from "../../types";
const state: () => TaskState = () => ({});
@@ -143,6 +144,33 @@ const actions = {
dispatch("issue/fetchIssueById", issueId, { root: true });
},
+
+ async approve(
+ { dispatch }: any,
+ {
+ issueId,
+ pipelineId,
+ taskId,
+ taskStatusChange,
+ }: {
+ issueId: IssueId;
+ pipelineId: PipelineId;
+ taskId: TaskId;
+ taskStatusChange: TaskStatusChange;
+ }
+ ) {
+ // TODO: Returns the updated pipeline and update the issue.
+ const data = (
+ await axios.post(`/api/pipeline/${pipelineId}/task/${taskId}/approve`, {
+ data: {
+ type: "taskStatusChange",
+ attributes: taskStatusChange,
+ },
+ })
+ ).data;
+
+ dispatch("issue/fetchIssueById", issueId, { root: true });
+ },
};
const mutations = {};
diff --git a/frontend/src/types/pipeline.ts b/frontend/src/types/pipeline.ts
index b498607f7a..6e61fe6346 100644
--- a/frontend/src/types/pipeline.ts
+++ b/frontend/src/types/pipeline.ts
@@ -248,6 +248,16 @@ export type TaskStatusPatch = {
comment?: string;
};
+export type TaskStatusChange = {
+ // Standard fields
+ updaterId: PrincipalId;
+
+ // Domain specific fields
+ // This is the container containing the pipeline this task belongs.
+ containerId: ContainerId;
+ comment?: string;
+};
+
// TaskRun is one run of a particular task
export type TaskRunStatus =
| "PENDING"
diff --git a/frontend/src/utils/pipeline.ts b/frontend/src/utils/pipeline.ts
index 867433810a..393057e445 100644
--- a/frontend/src/utils/pipeline.ts
+++ b/frontend/src/utils/pipeline.ts
@@ -127,7 +127,12 @@ export function activeDatabase(pipeline: Pipeline): Database {
return task.database;
}
-export type TaskStatusTransitionType = "RUN" | "RETRY" | "CANCEL" | "SKIP";
+export type TaskStatusTransitionType =
+ | "RUN"
+ | "APPROVE"
+ | "RETRY"
+ | "CANCEL"
+ | "SKIP";
export interface TaskStatusTransition {
type: TaskStatusTransitionType;
@@ -149,6 +154,15 @@ const TASK_STATUS_TRANSITION_LIST: Map<
buttonClass: "btn-primary",
},
],
+ [
+ "APPROVE",
+ {
+ type: "APPROVE",
+ to: "RUNNING",
+ buttonName: "Approve",
+ buttonClass: "btn-primary",
+ },
+ ],
[
"RETRY",
{
@@ -179,12 +193,15 @@ const TASK_STATUS_TRANSITION_LIST: Map<
],
]);
+type TaskTransitionStatus = TaskStatus | "PENDING_APPROVAL";
+
// The transition button is ordered from right to left on the UI
const APPLICABLE_TASK_TRANSITION_LIST: Map<
- TaskStatus,
+ TaskTransitionStatus,
TaskStatusTransitionType[]
> = new Map([
["PENDING", ["RUN", "SKIP"]],
+ ["PENDING_APPROVAL", ["APPROVE", "SKIP"]],
["RUNNING", ["CANCEL"]],
["DONE", []],
["FAILED", ["RETRY", "SKIP"]],
@@ -200,9 +217,13 @@ export function applicableTaskTransition(
return [];
}
- const list: TaskStatusTransitionType[] = APPLICABLE_TASK_TRANSITION_LIST.get(
- task.status
- )!;
+ const status =
+ task.status == "PENDING" && task.when == "MANUAL"
+ ? "PENDING_APPROVAL"
+ : task.status;
+
+ const list: TaskStatusTransitionType[] =
+ APPLICABLE_TASK_TRANSITION_LIST.get(status)!;
return list.map((type: TaskStatusTransitionType) => {
return TASK_STATUS_TRANSITION_LIST.get(type)!;