mirror of
https://github.com/rulego/gflow-engine.git
synced 2026-12-06 16:01:00 +00:00
fix: 发起即撤回在首任务未落库窗口按实例终止,switch分支可确定性预测upcoming,草稿禁止终止
This commit is contained in:
1 parent
8fe1eb843a
commit
ce9828ea8d
5 files changed
+302
-11
No files matched your search
+73
-4
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/rulego/gflow-engine/types/constants"
|
||||
"github.com/rulego/gflow-engine/types/dto"
|
||||
"github.com/rulego/rulego/api/types"
|
||||
"github.com/rulego/rulego/utils/el"
|
||||
)
|
||||
|
||||
// approverPreviewResolver 审批人预览解析器,由组件层经 SetApproverPreviewResolver
|
||||
@@ -55,7 +56,15 @@ func approverPreviewResolverForRead() func(cfg map[string]interface{}, tenantID,
|
||||
return approverPreviewResolver
|
||||
}
|
||||
|
||||
// branchingNodeTypes 条件分支节点:出边走向取决于运行时条件求值,预测在此截断。
|
||||
// deterministicBranchTypes 能用实例变量确定性求值的分支节点(与 rulego SwitchNode
|
||||
// 同口径:cases 顺序求值、首真命中、未命中走 Default)。其余分支型节点求值依赖
|
||||
// JS 引擎或 metadata,预测继续截断。
|
||||
var deterministicBranchTypes = map[string]bool{
|
||||
constants.NodeTypeSwitch: true,
|
||||
"condition": true,
|
||||
}
|
||||
|
||||
// branchingNodeTypes 条件分支节点:出边走向取决于运行时条件求值。
|
||||
var branchingNodeTypes = map[string]bool{
|
||||
constants.NodeTypeSwitch: true,
|
||||
constants.NodeTypeJsSwitch: true,
|
||||
@@ -78,9 +87,19 @@ func BuildUpcomingNodes(chain *types.RuleChain, activeNodeIDs []string, tenantID
|
||||
nodeByID[n.Id] = n
|
||||
}
|
||||
successors := make(map[string][]string)
|
||||
// from → 关系类型 → 首个后继:switch 分支按 case.then 命中连线
|
||||
succByType := make(map[string]map[string]string)
|
||||
for _, conn := range chain.Metadata.Connections {
|
||||
if conn.Type == types.Success || conn.Type == "" {
|
||||
successors[conn.FromId] = append(successors[conn.FromId], conn.ToId)
|
||||
rt := conn.Type
|
||||
if rt == "" {
|
||||
rt = types.Success
|
||||
}
|
||||
successors[conn.FromId] = append(successors[conn.FromId], conn.ToId)
|
||||
if succByType[conn.FromId] == nil {
|
||||
succByType[conn.FromId] = make(map[string]string)
|
||||
}
|
||||
if _, dup := succByType[conn.FromId][rt]; !dup {
|
||||
succByType[conn.FromId][rt] = conn.ToId
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,8 +130,12 @@ func BuildUpcomingNodes(chain *types.RuleChain, activeNodeIDs []string, tenantID
|
||||
if node.Type == constants.NodeTypeEnd {
|
||||
continue
|
||||
}
|
||||
// 条件分支节点:走向未知,预测截断
|
||||
if branchingNodeTypes[node.Type] {
|
||||
// switch/条件节点:能用当前变量确定性求值时沿命中分支继续预测,
|
||||
// 求值不干净或其余分支型节点维持截断
|
||||
if nextID := resolveSwitchSuccessor(node, variables, succByType); nextID != "" {
|
||||
enqueue([]string{nextID})
|
||||
}
|
||||
continue
|
||||
}
|
||||
// 活跃节点是遍历起点(进行中),不计入预测输出
|
||||
@@ -124,6 +147,52 @@ func BuildUpcomingNodes(chain *types.RuleChain, activeNodeIDs []string, tenantID
|
||||
return upcoming
|
||||
}
|
||||
|
||||
// resolveSwitchSuccessor 按运行时同口径(cases 顺序求值、首真命中、未命中走
|
||||
// Default)对分支节点做确定性求值,返回命中的后继节点 ID。求值不干净——表达式
|
||||
// 为空/编译失败/执行出错/命中关系无对应连线——返回空串,预测退回截断:预测环境
|
||||
// 只提供 msg(实例变量),引用 metadata/global 的表达式会出错从而截断,预测宁可
|
||||
// 缺席,不可给错。
|
||||
func resolveSwitchSuccessor(node *types.RuleNode, variables map[string]interface{}, succByType map[string]map[string]string) string {
|
||||
if !deterministicBranchTypes[node.Type] {
|
||||
return ""
|
||||
}
|
||||
cfg := map[string]interface{}(node.Configuration)
|
||||
rawCases, _ := cfg["cases"].([]interface{})
|
||||
env := map[string]interface{}{types.MsgKey: variables}
|
||||
next := ""
|
||||
decided := false
|
||||
for _, raw := range rawCases {
|
||||
c, _ := raw.(map[string]interface{})
|
||||
if c == nil {
|
||||
continue
|
||||
}
|
||||
expr, _ := c["case"].(string)
|
||||
then, _ := c["then"].(string)
|
||||
if expr == "" {
|
||||
return ""
|
||||
}
|
||||
tpl, err := el.NewExprTemplate(expr)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
out, err := tpl.Execute(env)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if b, ok := out.(bool); ok && b {
|
||||
next, decided = then, true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !decided {
|
||||
next = types.DefaultRelationType
|
||||
}
|
||||
if next == "" {
|
||||
return ""
|
||||
}
|
||||
return succByType[node.Id][next]
|
||||
}
|
||||
|
||||
// previewUserTaskNode 解析单个 userTask 节点的审批人预览;解析失败不阻断遍历。
|
||||
func previewUserTaskNode(node *types.RuleNode, tenantID, owner string, variables map[string]interface{},
|
||||
resolver func(cfg map[string]interface{}, tenantID, owner string, variables map[string]interface{}) *ApproverPreview) dto.UpcomingNode {
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package service
|
||||
|
||||
// Tests for forecast.go: switch/condition branch prediction in BuildUpcomingNodes.
|
||||
// A deterministic switch (cases evaluable from instance variables) must be traversed
|
||||
// along the matched branch; anything not cleanly evaluable keeps the old truncation.
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/rulego/gflow-engine/types/constants"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/rulego/gflow-engine/types/dto"
|
||||
"github.com/rulego/rulego/api/types"
|
||||
)
|
||||
|
||||
func forecastChain() *types.RuleChain {
|
||||
node := func(id, typ string, cfg map[string]interface{}) *types.RuleNode {
|
||||
return &types.RuleNode{Id: id, Type: typ, Configuration: cfg}
|
||||
}
|
||||
return &types.RuleChain{
|
||||
Metadata: types.RuleMetadata{
|
||||
Nodes: []*types.RuleNode{
|
||||
node("n_mgr", "userTask", map[string]interface{}{}),
|
||||
node("n_sw", "switch", map[string]interface{}{
|
||||
"cases": []interface{}{
|
||||
map[string]interface{}{"case": "msg.days > 10", "then": "b_backup"},
|
||||
map[string]interface{}{"case": "msg.days > 5", "then": "b_gm"},
|
||||
},
|
||||
}),
|
||||
node("n_gm", "userTask", map[string]interface{}{}),
|
||||
node("n_backup", "userTask", map[string]interface{}{}),
|
||||
node("gflow_end", "end", map[string]interface{}{}),
|
||||
},
|
||||
Connections: []types.NodeConnection{
|
||||
{FromId: "n_mgr", ToId: "n_sw", Type: types.Success},
|
||||
{FromId: "n_sw", ToId: "n_backup", Type: "b_backup"},
|
||||
{FromId: "n_sw", ToId: "n_gm", Type: "b_gm"},
|
||||
{FromId: "n_sw", ToId: "gflow_end", Type: "b_end"},
|
||||
{FromId: "n_gm", ToId: "gflow_end", Type: types.Success},
|
||||
{FromId: "n_backup", ToId: "gflow_end", Type: types.Success},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func forecastResolver() func(map[string]interface{}, string, string, map[string]interface{}) *ApproverPreview {
|
||||
return func(cfg map[string]interface{}, tenantID, owner string, _ map[string]interface{}) *ApproverPreview {
|
||||
return &ApproverPreview{ApproverType: "user", Assignees: []string{"u1"}}
|
||||
}
|
||||
}
|
||||
|
||||
func upcomingIDs(nodes []dto.UpcomingNode) []string {
|
||||
ids := make([]string, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
ids = append(ids, n.NodeID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// 活跃节点后继是 switch 且变量可确定性求值:沿命中分支预测(首真命中,12 天应走
|
||||
// 第一条 >10 分支而非 >5),未命中走 Default。
|
||||
func TestBuildUpcomingNodes_SwitchDeterministicPrediction(t *testing.T) {
|
||||
chain := forecastChain()
|
||||
// 原指向 end 的兜底边改走 Default 且指向 backup(b_backup 保留验证首真命中)
|
||||
chain.Metadata.Connections[3].ToId = "n_backup"
|
||||
chain.Metadata.Connections[3].Type = types.DefaultRelationType
|
||||
|
||||
SetApproverPreviewResolver(forecastResolver())
|
||||
defer SetApproverPreviewResolver(nil)
|
||||
|
||||
// days=8:>10 不成立、>5 成立 → 命中 b_gm
|
||||
up := BuildUpcomingNodes(chain, []string{"n_mgr"}, "t1", "starter", map[string]interface{}{"days": 8})
|
||||
require.Equal(t, []string{"n_gm"}, upcomingIDs(up), "8 天应预测 gm 节点")
|
||||
|
||||
// days=12:首条 >10 即命中 → backup(验证按 cases 顺序首真命中)
|
||||
up = BuildUpcomingNodes(chain, []string{"n_mgr"}, "t1", "starter", map[string]interface{}{"days": 12})
|
||||
require.Equal(t, []string{"n_backup"}, upcomingIDs(up), "12 天应按首真命中预测 backup")
|
||||
|
||||
// days=3:两案均不成立 → Default → backup
|
||||
up = BuildUpcomingNodes(chain, []string{"n_mgr"}, "t1", "starter", map[string]interface{}{"days": 3})
|
||||
require.Equal(t, []string{"n_backup"}, upcomingIDs(up), "未命中应走 Default 分支")
|
||||
}
|
||||
|
||||
// 变量缺失导致表达式求值出错、或分支型节点不可确定性求值(inclusive)时,预测退回截断。
|
||||
func TestBuildUpcomingNodes_NonEvaluableTruncates(t *testing.T) {
|
||||
chain := forecastChain()
|
||||
SetApproverPreviewResolver(forecastResolver())
|
||||
defer SetApproverPreviewResolver(nil)
|
||||
|
||||
// days 为字符串:比较求值出错 → 截断,不给出任何预测(保守:预测宁可缺席不给错)
|
||||
up := BuildUpcomingNodes(chain, []string{"n_mgr"}, "t1", "starter", map[string]interface{}{"days": "abc"})
|
||||
require.Empty(t, upcomingIDs(up), "求值不干净应维持截断")
|
||||
|
||||
// inclusive 分支节点不在确定性求值范围 → 截断
|
||||
chain.Metadata.Nodes[1].Type = constants.NodeTypeInclusive
|
||||
up = BuildUpcomingNodes(chain, []string{"n_mgr"}, "t1", "starter", map[string]interface{}{"days": 8})
|
||||
require.Empty(t, upcomingIDs(up), "inclusive 应维持截断")
|
||||
}
|
||||
@@ -8,6 +8,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -155,3 +156,76 @@ func TestActivateProcessInstance_WakeAuthorization(t *testing.T) {
|
||||
newSuspended("inst-wake-admin")
|
||||
require.NoError(t, rs.ActivateProcessInstance(ctx, Actor{UserID: "admin", TenantID: "t1", WorkflowAdmin: true}, "inst-wake-admin"))
|
||||
}
|
||||
|
||||
// 草稿实例终止被拒绝:与挂起同口径,草稿的生命周期动作是编辑、提交(激活)与删除,
|
||||
// 终止会把它挪进已结束列表,既不能提交也不能再走草稿删除。
|
||||
func TestTerminateInTx_DraftRejected(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
rs := &RuntimeServiceImpl{
|
||||
instanceDAO: dao.NewInstanceDAOWithQuery(q),
|
||||
hiInstanceDAO: dao.NewHiInstanceDAOWithQuery(q),
|
||||
taskDAO: dao.NewTaskDAOWithQuery(q),
|
||||
workflowEngine: &testEngineDouble{listener: func(_ context.Context, _ TaskEvent) {}},
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, rs.instanceDAO.Create(ctx, &model.WfInstance{
|
||||
ID: "inst-draft-term", ProcessID: "proc-1", Name: "草稿单",
|
||||
Status: string(enums.InstanceStatusDraft), TenantID: "t1",
|
||||
StartUserID: "userA", CreatedBy: "userA", CreatedAt: time.Now(),
|
||||
}))
|
||||
|
||||
_, err := rs.TerminateInTx(WithInternalCallingMode(ctx), q, "inst-draft-term", "清理")
|
||||
require.Error(t, err, "草稿实例不可终止")
|
||||
require.True(t, errors.Is(err, ErrValidation), "期望 ErrValidation,got %v", err)
|
||||
|
||||
persisted, err := rs.instanceDAO.Get(ctx, "inst-draft-term")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(enums.InstanceStatusDraft), persisted.Status, "实例应保持草稿态")
|
||||
}
|
||||
|
||||
// 发起后首个任务尚未落库的撤回:start 异步驱动首节点存在窗口,此刻撤回按实例维度
|
||||
// 终止并落 withdrawn 口径,不再按“无活跃任务”拒绝。
|
||||
func TestWithdrawByInstance_BeforeFirstTaskTerminates(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
|
||||
rs := &RuntimeServiceImpl{
|
||||
instanceDAO: dao.NewInstanceDAOWithQuery(q),
|
||||
hiInstanceDAO: dao.NewHiInstanceDAOWithQuery(q),
|
||||
taskDAO: dao.NewTaskDAOWithQuery(q),
|
||||
workflowEngine: &testEngineDouble{listener: func(_ context.Context, _ TaskEvent) {}},
|
||||
}
|
||||
taskSvc := &TaskServiceImpl{
|
||||
taskDAO: dao.NewTaskDAOWithQuery(q),
|
||||
hiTaskDAO: dao.NewHiTaskDAOWithQuery(q),
|
||||
workflowEngine: &testEngineDouble{runtime: rs},
|
||||
}
|
||||
|
||||
require.NoError(t, q.WfInstance.Create(&model.WfInstance{
|
||||
ID: "inst-wd-fresh", ProcessID: "proc-1", Name: "刚提交单",
|
||||
Status: string(enums.InstanceStatusActive), TenantID: "t1",
|
||||
StartUserID: "starter", CreatedBy: "starter", CreatedAt: now,
|
||||
}))
|
||||
|
||||
// 实例 Active 但任务未落库:发起人撤回应直接终止实例
|
||||
require.NoError(t, taskSvc.WithdrawByInstance(ctx, Actor{UserID: "starter", TenantID: "t1"}, "inst-wd-fresh", "提交错了"))
|
||||
|
||||
persisted, err := rs.instanceDAO.Get(ctx, "inst-wd-fresh")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, persisted, "已终止实例应归档出运行表")
|
||||
hiInst, err := q.WfHiInstance.WithContext(ctx).Where(q.WfHiInstance.ID.Eq("inst-wd-fresh")).First()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(enums.InstanceStatusTerminated), hiInst.Status)
|
||||
|
||||
// 非发起人不可借该路径终止他人实例
|
||||
require.NoError(t, q.WfInstance.Create(&model.WfInstance{
|
||||
ID: "inst-wd-fresh2", ProcessID: "proc-1", Name: "他人刚提交单",
|
||||
Status: string(enums.InstanceStatusActive), TenantID: "t1",
|
||||
StartUserID: "starter", CreatedBy: "starter", CreatedAt: now,
|
||||
}))
|
||||
err = taskSvc.WithdrawByInstance(ctx, Actor{UserID: "imposter", TenantID: "t1"}, "inst-wd-fresh2", "想撤")
|
||||
require.Error(t, err, "非发起人撤回必须拒绝")
|
||||
require.True(t, errors.Is(err, ErrPermissionDenied), "期望 ErrPermissionDenied,got %v", err)
|
||||
}
|
||||
@@ -2202,6 +2202,12 @@ func (s *RuntimeServiceImpl) TerminateInTx(ctx context.Context, tx *query.Query,
|
||||
if instance.Status == string(enums.InstanceStatusCompleted) {
|
||||
return nil, fmt.Errorf("cannot terminate completed process instance: %w", ErrInstanceTerminal)
|
||||
}
|
||||
// 草稿不可终止:与挂起同口径——草稿的生命周期动作是编辑、提交(激活)与删除,
|
||||
// 终止会把它挪进已结束列表,既不能提交也不能再走草稿删除。
|
||||
if instance.Status == string(enums.InstanceStatusDraft) {
|
||||
return nil, fmt.Errorf("draft instance %s cannot be terminated; submit or delete it instead: %w",
|
||||
processInstanceID, ErrValidation)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
username := s.GetUsernameFromCtx(ctx)
|
||||
|
||||
@@ -76,17 +76,59 @@ func (s *TaskServiceImpl) WithdrawByInstance(ctx context.Context, actor Actor, i
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list active tasks: %w", err)
|
||||
}
|
||||
if len(tasks) == 0 {
|
||||
return fmt.Errorf("%w: no active task to withdraw for instance %s", ErrValidation, instanceID)
|
||||
if len(tasks) > 0 {
|
||||
// 设计器显式禁用 withdraw → 拒绝
|
||||
if err := s.requireActionEnabled(ctx, tasks[0], "withdraw"); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.withdrawInternal(ctx, scope, tasks[0].ID, userID, reason, isAdmin)
|
||||
}
|
||||
// 设计器显式禁用 withdraw → 拒绝
|
||||
if err := s.requireActionEnabled(ctx, tasks[0], "withdraw"); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.withdrawInternal(ctx, scope, tasks[0].ID, userID, reason, isAdmin)
|
||||
return s.withdrawBeforeFirstTask(ctx, scope, instanceID, userID, reason, isAdmin)
|
||||
})
|
||||
}
|
||||
|
||||
// withdrawBeforeFirstTask 处理“发起后首个任务尚未落库”的撤回:start 提交后异步驱动
|
||||
// 首节点,提交成功到首任务创建之间存在窗口,此刻撤回不能按无任务拒绝。直接按实例
|
||||
// 维度终止(与正常撤回同落 terminated 终态、同撤回原因口径)。仅发起人/管理员、
|
||||
// 且实例仍为 Active 时允许;WithInstanceTx 的终态闸保证终止后链的后续驱动不会再
|
||||
// 落出任务。
|
||||
func (s *TaskServiceImpl) withdrawBeforeFirstTask(ctx context.Context, scope *InstanceScope, instanceID, userID, reason string, isAdmin bool) error {
|
||||
instance, err := scope.Instances().Get(ctx, instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get process instance: %w", err)
|
||||
}
|
||||
if instance == nil {
|
||||
return fmt.Errorf("%w: process instance", ErrNotFound)
|
||||
}
|
||||
if u := GetUserFromCtx(ctx); u != nil && instance.TenantID != u.TenantID {
|
||||
return fmt.Errorf("%w: process instance", ErrNotFound)
|
||||
}
|
||||
if !isInstanceStarterOrAdmin(instance, userID, isAdmin) {
|
||||
return fmt.Errorf("%w: only the process initiator (or admin) can withdraw", ErrPermissionDenied)
|
||||
}
|
||||
if instance.Status != string(enums.InstanceStatusActive) {
|
||||
return fmt.Errorf("%w: only active instances can be withdrawn, current status: %s", ErrValidation, instance.Status)
|
||||
}
|
||||
|
||||
terminateReason := constants.EndReasonPrefixWithdrawn
|
||||
if reason != "" {
|
||||
terminateReason = fmt.Sprintf("%s:%s", constants.EndReasonPrefixWithdrawn, reason)
|
||||
}
|
||||
withdrawCtx := WithEventSource(ctx, EventSourceWithdraw)
|
||||
terminatedEvt, err := terminateProcessInstanceInTx(withdrawCtx, s.workflowEngine.GetRuntimeService(), scope.Tx(), instanceID, terminateReason)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to terminate process instance after withdraw: %w", err)
|
||||
}
|
||||
if terminatedEvt != nil && s.workflowEngine.GetTaskEventListener() != nil {
|
||||
evt := *terminatedEvt
|
||||
scope.AfterCommit(func() error {
|
||||
DispatchTaskEvent(s.workflowEngine.GetTaskEventListener(), evt, withdrawCtx)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// withdrawInternal 在已持有实例行锁的事务内执行 Withdraw 实际逻辑。
|
||||
// 内部调用 runtimeService 的 TerminateInTx(同样假定持锁)——避免重新进入
|
||||
// WithInstanceTx 导致重复 FOR UPDATE 或 savepoint 嵌套。
|
||||
|
||||
Reference in new issue
Block a user