fix: 子流程别名解析未命中回落DB自愈,目标取active最新版本并校验命中活性

This commit is contained in:
rulego-team committed 2026-11-28 23:24:53 +08:00
1 parent ffde2190d2
commit 5fd10e3ec1
9 files changed
+223 -9

No files matched your search

+1 -1
View File
@@ -70,7 +70,7 @@ func (x *SubProcessNode) OnMsg(ctx types.RuleContext, msg types.RuleMsg) {
return
}
tenantID := metaValue(msg, constants.KeyTenantID)
childProcID, ok := x.RuntimeService.ResolveSubProcessTarget(tenantID, x.Config.TargetId)
childProcID, ok := x.RuntimeService.ResolveSubProcessTarget(ctx.GetContext(), tenantID, x.Config.TargetId)
if !ok {
ctx.TellFailure(msg, fmt.Errorf("subProcess target %q not registered (deploy the child process first)", x.Config.TargetId))
return
+15
View File
@@ -240,6 +240,21 @@ func (d *ProcessDAO) GetLatestByKey(ctx context.Context, tenantID, processKey st
return query.Order(q.Version.Desc()).First()
}
// GetActiveByKey 根据流程定义Key获取当前 active 版本的流程定义。部署侧保证同 key
// 至多一个 active,但多版本历史行并存(每次部署新增一行、旧版本停用留档),必须
// 带 status 过滤并按版本降序取——无排序的 First 按主键序返回随机版本,主键是
// 随机 UUID 时多版本场景会抽中已停用旧版本。
func (d *ProcessDAO) GetActiveByKey(ctx context.Context, tenantID, processKey string) (*model.WfProcess, error) {
if processKey == "" {
return nil, fmt.Errorf("processKey cannot be empty")
}
q := d.Query.WfProcess
return q.WithContext(ctx).
Where(q.TenantID.Eq(tenantID), q.ProcessKey.Eq(processKey), q.Status.Eq(string(enums.ProcessStatusActive))).
Order(q.Version.Desc()).First()
}
// GetAllVersionsByKey 根据流程定义Key获取所有版本的流程定义
func (d *ProcessDAO) GetAllVersionsByKey(ctx context.Context, tenantID, processKey string) ([]*model.WfProcess, error) {
if processKey == "" {
+4 -2
View File
@@ -32,8 +32,10 @@ type RuntimeServiceInternal interface {
EvictStaleChain(ctx context.Context, tenantID, processID string)
// ResolveSubProcessTarget 把 subProcess 的 targetId(子链 ruleChain.id)解析为子流程定义ID。
// 注册表在 PreloadChain 时按 (tenant, ruleChain.id) 建立。解析不到返回 ok=false。
ResolveSubProcessTarget(tenantID, ruleChainID string) (processDefID string, ok bool)
// 内存映射在 PreloadChain 时按 (tenant, ruleChain.id) 建立;多实例部署下发起
// 副本可能没有该映射,未命中回落 DB 按 processKey 查 active 定义并回填自愈,
// 仍解析不到返回 ok=false。
ResolveSubProcessTarget(ctx context.Context, tenantID, ruleChainID string) (processDefID string, ok bool)
// StartSubProcessInstance 启动一个子流程实例(call activity 语义):
// child.ParentID=parentInstanceID;记 parentNodeID 用于完成回调恢复父流程。
+39 -4
View File
@@ -3,11 +3,13 @@ package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
"github.com/rulego/gflow-engine/model"
"github.com/rulego/gflow-engine/types/constants"
@@ -155,11 +157,44 @@ func findSubProcessNodeByTarget(def, target string) (string, bool) {
}
// ResolveSubProcessTarget 把 subProcess targetId(子链 ruleChain.id)解析为子流程定义ID。
func (s *RuntimeServiceImpl) ResolveSubProcessTarget(tenantID, ruleChainID string) (string, bool) {
if v, ok := s.subProcessTargets.Load(tenantID + "|" + ruleChainID); ok {
return v.(string), true
// 内存映射在收到部署请求的副本上由 PreloadChain 注册;多实例部署时发起与部署
// 可能落在不同副本:命中先校验映射行仍是 active 版本(子流程在另一副本重新部署
// 后,本副本的映射会指向已停用旧版本),失效即废弃映射走 DB 重解析自愈;未命中
// 回落 DB 按 processKey 查 active 版本(多版本历史行并存,必须带 status 过滤),
// 回填映射并预载链自愈,此后该副本与部署侧同口径。
func (s *RuntimeServiceImpl) ResolveSubProcessTarget(ctx context.Context, tenantID, ruleChainID string) (string, bool) {
key := tenantID + "|" + ruleChainID
if v, ok := s.subProcessTargets.Load(key); ok {
mapped := v.(string)
// 命中校验:子流程启动本身伴随多次 DB 写,一次主键读成本可忽略
if proc, err := s.processDAO.Get(ctx, mapped); err == nil && proc != nil &&
proc.Status == string(enums.ProcessStatusActive) {
return mapped, true
}
s.subProcessTargets.Delete(key)
}
return "", false
if tenantID == "" || ruleChainID == "" {
return "", false
}
proc, err := s.processDAO.GetActiveByKey(ctx, tenantID, ruleChainID)
if err != nil {
// 查无此 key = 子流程未部署,静默返回由调用方报「未注册」;其余错误(DB
// 瞬断等)是异常路径,留痕避免静默吞成「未注册」误导排查
if !errors.Is(err, gorm.ErrRecordNotFound) {
logrus.WithError(err).WithField("processKey", ruleChainID).
Warn("subProcess target fallback query failed")
}
return "", false
}
if proc == nil || proc.Status != string(enums.ProcessStatusActive) {
return "", false
}
// 自愈:回填映射并把子链预载进本副本租户池(幂等),后续 TellFlow 直接命中
if err := s.PreloadChain(tenantID, proc.ID, proc.DefinitionJSON); err != nil {
logrus.WithError(err).WithField("processId", proc.ID).
Warn("subProcess target fallback preload failed; resolution still valid")
}
return proc.ID, true
}
// SubProcessChildState 查询父实例下子流程状态:active(在跑)/ completed(已归档完成)。
+149
View File
@@ -0,0 +1,149 @@
// subProcess 目标解析的单元测试:DB 回退必须取 active 最新版本(无排序 First 会
// 在多版本历史行里按随机主键抽中已停用旧版本),内存映射指向旧版本时命中自愈。
package service
import (
"context"
"testing"
"github.com/glebarez/sqlite"
"github.com/rulego/rulego"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/rulego/gflow-engine/dao"
"github.com/rulego/gflow-engine/query"
"github.com/rulego/gflow-engine/types/enums"
)
// newSubProcessResolveDB 建内存 wf_process 表,返回 gorm.DB 与 query.Query。
func newSubProcessResolveDB(t *testing.T) (*gorm.DB, *query.Query) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:subprocess_resolve_test?mode=memory&cache=shared&_busy_timeout=30000"),
&gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
t.Cleanup(func() {
if c, e := db.DB(); e == nil {
_ = c.Close()
}
})
require.NoError(t, db.Exec(`CREATE TABLE IF NOT EXISTS wf_process (
id TEXT PRIMARY KEY, process_key TEXT NOT NULL, name TEXT NOT NULL,
version INTEGER NOT NULL DEFAULT 1, category TEXT, description TEXT,
definition_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'active',
publish_time DATETIME, tenant_id TEXT NOT NULL, created_by TEXT,
created_at DATETIME, updated_by TEXT, updated_at DATETIME, ext TEXT,
process_type TEXT, icon TEXT
)`).Error, "create table")
require.NoError(t, db.Exec("DELETE FROM wf_process").Error)
return db, query.Use(db)
}
// seedProcessRow 插入一条流程定义行(按 key/version/status 定制)。
// 与生产同构:processKey 即 ruleChain.id(subProcess targetId 寻址键)。
func seedProcessRow(t *testing.T, db *gorm.DB, id, key string, version int32, status string) {
t.Helper()
require.NoError(t, db.Exec(
`INSERT INTO wf_process (id, process_key, name, version, definition_json, status, tenant_id, created_by, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
id, key, "流程"+id, version, `{"ruleChain":{"id":"`+key+`"}}`, status, "t1", "sys").Error, "seed", id)
}
// GetActiveByKey:多版本历史行并存时取版本最高的 active 行——状态过滤 + 版本降序
// 缺一不可(无排序 First 按随机主键返回,会抽中已停用版本)。
func TestGetActiveByKey_PicksNewestActive(t *testing.T) {
db, q := newSubProcessResolveDB(t)
seedProcessRow(t, db, "p-act-v1", "child", 1, string(enums.ProcessStatusActive))
seedProcessRow(t, db, "p-ret-v2", "child", 2, string(enums.ProcessStatusRetired))
seedProcessRow(t, db, "p-act-v3", "child", 3, string(enums.ProcessStatusActive))
proc, err := dao.NewProcessDAOWithQuery(q).GetActiveByKey(context.Background(), "t1", "child")
require.NoError(t, err)
require.NotNil(t, proc)
assert.Equal(t, "p-act-v3", proc.ID, "多个 active 行时取版本最高者")
}
// GetActiveByKey:全部停用 / 无此 key 返回 ErrRecordNotFound。
func TestGetActiveByKey_NoneActive(t *testing.T) {
db, q := newSubProcessResolveDB(t)
seedProcessRow(t, db, "p-ret-v1", "child", 1, string(enums.ProcessStatusRetired))
_, err := dao.NewProcessDAOWithQuery(q).GetActiveByKey(context.Background(), "t1", "child")
require.ErrorIs(t, err, gorm.ErrRecordNotFound)
_, err = dao.NewProcessDAOWithQuery(q).GetActiveByKey(context.Background(), "t1", "ghost")
require.ErrorIs(t, err, gorm.ErrRecordNotFound)
}
// ResolveSubProcessTarget:内存映射指向已停用旧版本(另一副本重新部署后),
// 命中校验判失效 → DB 重解析到 active 新版本并回填映射。
func TestResolveSubProcessTarget_StaleMappingSelfHeals(t *testing.T) {
db, q := newSubProcessResolveDB(t)
seedProcessRow(t, db, "p-ret-v1", "child", 1, string(enums.ProcessStatusRetired))
seedProcessRow(t, db, "p-act-v2", "child", 2, string(enums.ProcessStatusActive))
s := &RuntimeServiceImpl{
processDAO: dao.NewProcessDAOWithQuery(q),
enginePool: rulego.NewRuleGo(),
}
s.subProcessTargets.Store("t1|child", "p-ret-v1")
id, ok := s.ResolveSubProcessTarget(context.Background(), "t1", "child")
require.True(t, ok)
assert.Equal(t, "p-act-v2", id, "旧版本映射必须自愈到 active 新版本")
v, loaded := s.subProcessTargets.Load("t1|child")
require.True(t, loaded)
assert.Equal(t, "p-act-v2", v, "自愈后回填映射")
}
// ResolveSubProcessTarget:映射命中且仍是 active 版本时直接返回(不重解析)。
func TestResolveSubProcessTarget_FreshHitKept(t *testing.T) {
db, q := newSubProcessResolveDB(t)
seedProcessRow(t, db, "p-act-v2", "child", 2, string(enums.ProcessStatusActive))
seedProcessRow(t, db, "p-ret-v1", "child", 1, string(enums.ProcessStatusRetired))
s := &RuntimeServiceImpl{
processDAO: dao.NewProcessDAOWithQuery(q),
enginePool: rulego.NewRuleGo(),
}
s.subProcessTargets.Store("t1|child", "p-act-v2")
id, ok := s.ResolveSubProcessTarget(context.Background(), "t1", "child")
require.True(t, ok)
assert.Equal(t, "p-act-v2", id)
}
// ResolveSubProcessTarget:映射未命中回落 DB 取 active 最新版本(多版本并存)。
func TestResolveSubProcessTarget_FallbackPicksActive(t *testing.T) {
db, q := newSubProcessResolveDB(t)
seedProcessRow(t, db, "p-ret-v1", "child", 1, string(enums.ProcessStatusRetired))
seedProcessRow(t, db, "p-ret-v2", "child", 2, string(enums.ProcessStatusRetired))
seedProcessRow(t, db, "p-act-v3", "child", 3, string(enums.ProcessStatusActive))
s := &RuntimeServiceImpl{
processDAO: dao.NewProcessDAOWithQuery(q),
enginePool: rulego.NewRuleGo(),
}
id, ok := s.ResolveSubProcessTarget(context.Background(), "t1", "child")
require.True(t, ok)
assert.Equal(t, "p-act-v3", id, "DB 回退必须取 active 最新版本,而非主键序随机行")
}
// ResolveSubProcessTarget:全部停用 / 无此 key 返回 false(子流程未部署是正常
// 业务态,调用方报「未注册」)。
func TestResolveSubProcessTarget_NoneActiveFalse(t *testing.T) {
db, q := newSubProcessResolveDB(t)
seedProcessRow(t, db, "p-ret-v1", "child", 1, string(enums.ProcessStatusRetired))
s := &RuntimeServiceImpl{
processDAO: dao.NewProcessDAOWithQuery(q),
enginePool: rulego.NewRuleGo(),
}
_, ok := s.ResolveSubProcessTarget(context.Background(), "t1", "child")
assert.False(t, ok)
_, ok = s.ResolveSubProcessTarget(context.Background(), "t1", "ghost-key")
assert.False(t, ok)
}
+7
View File
@@ -48,12 +48,19 @@ func (f *fakeProcessStore) Get(ctx context.Context, id string) (*model.WfProcess
func (f *fakeProcessStore) GetByIDs(ctx context.Context, ids []string) ([]*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) GetByKey(ctx context.Context, tenantID, processKey string) (*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) GetByKeyAndVersion(ctx context.Context, tenantID, processKey string, version int32) (*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) GetLatestByKey(ctx context.Context, tenantID, processKey string) (*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) GetActiveByKey(ctx context.Context, tenantID, processKey string) (*model.WfProcess, error) {
return nil, errors.New("not implemented")
}
func (f *fakeProcessStore) Update(ctx context.Context, entity *model.WfProcess) error {
return errors.New("not implemented")
}
+6
View File
@@ -75,8 +75,14 @@ type ProcessStore interface {
List(ctx context.Context, request *dto.ProcessQueryRequest) ([]*model.WfProcess, int64, error)
Get(ctx context.Context, id string) (*model.WfProcess, error)
GetByIDs(ctx context.Context, ids []string) ([]*model.WfProcess, error)
// GetByKey 按租户+processKey 取定义(无状态/排序过滤,主键序 First,多版本
// 场景返回哪个版本不确定——按 key 取运行版本用 GetActiveByKey)
GetByKey(ctx context.Context, tenantID, processKey string) (*model.WfProcess, error)
GetByKeyAndVersion(ctx context.Context, tenantID, processKey string, version int32) (*model.WfProcess, error)
GetLatestByKey(ctx context.Context, tenantID, processKey string) (*model.WfProcess, error)
// GetActiveByKey 按租户+processKey 取当前 active 版本(版本降序;部署侧保证
// 同 key 至多一个 active,供 subProcess 别名解析的 DB 回退用)
GetActiveByKey(ctx context.Context, tenantID, processKey string) (*model.WfProcess, error)
Update(ctx context.Context, entity *model.WfProcess) error
Delete(ctx context.Context, tenantID, id string) error
CountActiveReferencingForm(ctx context.Context, tenantID, formKey string) (int64, error)
+1 -1
View File
@@ -52,7 +52,7 @@ func (d *recallInternalDouble) GetExecution(context.Context, string) (types.Rule
func (d *recallInternalDouble) PreloadChain(string, string, string) error { return nil }
func (d *recallInternalDouble) EvictStaleChain(context.Context, string, string) {
}
func (d *recallInternalDouble) ResolveSubProcessTarget(string, string) (string, bool) {
func (d *recallInternalDouble) ResolveSubProcessTarget(context.Context, string, string) (string, bool) {
return "", false
}
func (d *recallInternalDouble) IsInstanceExecutable(context.Context, string) (bool, error) {
+1 -1
View File
@@ -112,7 +112,7 @@ func (r *testRuntimeDouble) GetExecution(ctx context.Context, processID string)
func (r *testRuntimeDouble) PreloadChain(tenantID, processID, processDef string) error { return nil }
func (r *testRuntimeDouble) EvictStaleChain(ctx context.Context, tenantID, processID string) {
}
func (r *testRuntimeDouble) ResolveSubProcessTarget(tenantID, ruleChainID string) (string, bool) {
func (r *testRuntimeDouble) ResolveSubProcessTarget(_ context.Context, tenantID, ruleChainID string) (string, bool) {
return "", false
}
func (r *testRuntimeDouble) StartSubProcessInstance(ctx context.Context, parentInstanceID, parentNodeID, childProcessDefID string, variables map[string]interface{}) (string, error) {