From ce9828ea8df74bb3bcc09c31e86feb1e5392f533 Mon Sep 17 00:00:00 2001 From: rulego-team Date: Mon, 28 Sep 2026 00:28:08 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=8F=91=E8=B5=B7=E5=8D=B3=E6=92=A4?= =?UTF-8?q?=E5=9B=9E=E5=9C=A8=E9=A6=96=E4=BB=BB=E5=8A=A1=E6=9C=AA=E8=90=BD?= =?UTF-8?q?=E5=BA=93=E7=AA=97=E5=8F=A3=E6=8C=89=E5=AE=9E=E4=BE=8B=E7=BB=88?= =?UTF-8?q?=E6=AD=A2,switch=E5=88=86=E6=94=AF=E5=8F=AF=E7=A1=AE=E5=AE=9A?= =?UTF-8?q?=E6=80=A7=E9=A2=84=E6=B5=8Bupcoming,=E8=8D=89=E7=A8=BF=E7=A6=81?= =?UTF-8?q?=E6=AD=A2=E7=BB=88=E6=AD=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/forecast.go | 77 +++++++++++++++++- service/forecast_test.go | 100 ++++++++++++++++++++++++ service/runtime_lifecycle_guard_test.go | 74 ++++++++++++++++++ service/runtime_service_impl.go | 6 ++ service/task_service_withdraw.go | 56 +++++++++++-- 5 files changed, 302 insertions(+), 11 deletions(-) create mode 100644 service/forecast_test.go diff --git a/service/forecast.go b/service/forecast.go index 207db94..16dd749 100644 --- a/service/forecast.go +++ b/service/forecast.go @@ -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 { diff --git a/service/forecast_test.go b/service/forecast_test.go new file mode 100644 index 0000000..e6ee17f --- /dev/null +++ b/service/forecast_test.go @@ -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 应维持截断") +} diff --git a/service/runtime_lifecycle_guard_test.go b/service/runtime_lifecycle_guard_test.go index 2e73f98..bd5820a 100644 --- a/service/runtime_lifecycle_guard_test.go +++ b/service/runtime_lifecycle_guard_test.go @@ -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) +} diff --git a/service/runtime_service_impl.go b/service/runtime_service_impl.go index dfbd59a..844d083 100644 --- a/service/runtime_service_impl.go +++ b/service/runtime_service_impl.go @@ -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) diff --git a/service/task_service_withdraw.go b/service/task_service_withdraw.go index e0a7edc..17ae09a 100644 --- a/service/task_service_withdraw.go +++ b/service/task_service_withdraw.go @@ -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 嵌套。