mirror of
https://github.com/rulego/gflow-engine.git
synced 2026-12-06 00:00:57 +00:00
fix: 跨副本执行门闩接线分布式锁,Update驱逐enginePool并广播失效,数组变量合并容忍
This commit is contained in:
1 parent
9065c39753
commit
405e7e4432
9 files changed
+654
-12
No files matched your search
@@ -65,6 +65,21 @@ func (aspect *TaskCreator) Type() string {
|
||||
// 持锁方崩溃后锁永不释放(实例完成后 end 不应再执行,TTL 到期释放无副作用)。
|
||||
var endNodeDedupLock = lock.DefaultKeyLock
|
||||
|
||||
// endDedupTTL end 去重锁 TTL:持锁方崩溃后兜底释放;须覆盖 CompleteProcessInstance
|
||||
// 与 onCompleted 规则链(可能含 LLM 调用)的执行时长,锁先过期会让对端副本重复执行 end。
|
||||
const endDedupTTL = 2 * time.Minute
|
||||
|
||||
// endDedupLocker 取 end 去重锁实现:宿主注入了分布式锁(多副本部署)则跨副本
|
||||
// 生效,否则退回进程内 LocalLock(单机部署)。
|
||||
func (aspect *TaskCreator) endDedupLocker() lock.Locker {
|
||||
if aspect.workflowEngine != nil {
|
||||
if l := aspect.workflowEngine.GetLocker(); l != nil {
|
||||
return l
|
||||
}
|
||||
}
|
||||
return endNodeDedupLock
|
||||
}
|
||||
|
||||
func endNodeLockKey(instanceID string) string {
|
||||
return "bpm:end-dedup:" + instanceID
|
||||
}
|
||||
@@ -106,7 +121,7 @@ func (aspect *TaskCreator) Before(ctx types.RuleContext, msg types.RuleMsg, rela
|
||||
// 未抢到的重复执行直接返回(不建任务、不更新 current activity),保证
|
||||
// end 任务只创建一条、CompleteProcessInstance / onCompleted 规则链只触发一次。
|
||||
if ctx.Self().Type() == types.NodeTypeEnd {
|
||||
lockVal, ok, err := endNodeDedupLock.TryLock(ctx.GetContext(), endNodeLockKey(instanceId), time.Minute)
|
||||
lockVal, ok, err := aspect.endDedupLocker().TryLock(ctx.GetContext(), endNodeLockKey(instanceId), endDedupTTL)
|
||||
if err != nil {
|
||||
// 锁服务异常时保守放行(宁可重复执行也不能卡死流程)
|
||||
logrus.WithError(err).Warnf("end-node dedup TryLock error, allow execution, instanceId: %s", instanceId)
|
||||
@@ -217,7 +232,7 @@ func (aspect *TaskCreator) After(ctx types.RuleContext, msg types.RuleMsg, err e
|
||||
if ctx.Self().Type() == types.NodeTypeEnd {
|
||||
lockVal := msg.GetMetadata().GetValue(constants.KeyEndExecLock)
|
||||
defer func() {
|
||||
if err := endNodeDedupLock.Unlock(context.Background(), endNodeLockKey(instanceId), lockVal); err != nil {
|
||||
if err := aspect.endDedupLocker().Unlock(context.Background(), endNodeLockKey(instanceId), lockVal); err != nil {
|
||||
logrus.WithError(err).Debugf("end-node dedup unlock failed, instanceId: %s", instanceId)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// 跨副本链驱动门闩:ExecuteNext / Restore / ForceResume / Start 初始驱动在进程内
|
||||
// execGate(runtime_exec_gate.go)之上再加一层分布式互斥。多副本共享同一数据库时,
|
||||
// 两副本可能同时判定 fork-join 已收齐而各自 multi-restore,产生重复下游任务与
|
||||
// 重复 end 执行;userTask 查-建去重与 end 去重锁同样只在本进程生效,跨副本互斥
|
||||
// 只能由 Locker 承担——宿主多副本部署时注入 Redis 锁,单机默认 LocalLock(execGate
|
||||
// 已串行化本进程驱动,LocalLock 恒可立即获得,无额外开销)。
|
||||
//
|
||||
// 可用性优先:等待预算耗尽或锁服务异常时放行执行,重复驱动由 userTask 查-建幂等、
|
||||
// end 去重与 suspend 节点重入幂等兜底,不因锁故障卡死流程;持锁方崩溃由 TTL 兜底。
|
||||
//
|
||||
// var 而非 const:测试需要缩短重试预算。
|
||||
var (
|
||||
distExecGateTTL = 3 * time.Minute
|
||||
distExecGateInterval = 100 * time.Millisecond
|
||||
distExecGateRetries = 150 // 100ms × 150 ≈ 15s 等待预算,与 WithInstanceTx 锁超时同量级
|
||||
)
|
||||
|
||||
func distExecGateKey(instanceID string) string {
|
||||
return "bpm:exec-gate:" + instanceID
|
||||
}
|
||||
|
||||
// acquireDistExecGate 获取实例级跨副本驱动门闩。返回 nil 表示未持锁(放行执行,
|
||||
// 调用方无须释放);返回非 nil 时驱动完成后须调用释放函数(幂等)。同 goroutine
|
||||
// 重入由上层 execGate 的 reentrant 标记跳过,此处不做重入计数。
|
||||
func (s *RuntimeServiceImpl) acquireDistExecGate(ctx context.Context, instanceID string) func() {
|
||||
if instanceID == "" {
|
||||
return nil
|
||||
}
|
||||
if s.workflowEngine == nil {
|
||||
return nil
|
||||
}
|
||||
locker := s.workflowEngine.GetLocker()
|
||||
if locker == nil {
|
||||
return nil
|
||||
}
|
||||
key := distExecGateKey(instanceID)
|
||||
value, err := locker.LockWithRetry(ctx, key, distExecGateTTL, distExecGateInterval, distExecGateRetries)
|
||||
if err != nil {
|
||||
logrus.WithError(err).WithField("instanceId", instanceID).
|
||||
Warn("dist exec gate: acquire failed, proceed without cross-replica mutual exclusion")
|
||||
return nil
|
||||
}
|
||||
return func() {
|
||||
if err := locker.Unlock(context.Background(), key, value); err != nil {
|
||||
logrus.WithError(err).WithField("instanceId", instanceID).Debug("dist exec gate: unlock failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/rulego/gflow-engine/utils/lock"
|
||||
)
|
||||
|
||||
// gateTestEngine 仅实现 GetLocker 的最小引擎替身(嵌入接口满足其余方法签名,
|
||||
// 不被调用)。acquireDistExecGate 只消费 GetLocker。
|
||||
type gateTestEngine struct {
|
||||
WorkflowEngine
|
||||
l lock.Locker
|
||||
}
|
||||
|
||||
func (e *gateTestEngine) GetLocker() lock.Locker { return e.l }
|
||||
|
||||
func newGateTestRuntime(l lock.Locker) *RuntimeServiceImpl {
|
||||
return &RuntimeServiceImpl{workflowEngine: &gateTestEngine{l: l}}
|
||||
}
|
||||
|
||||
// 两副本共享同一把锁(模拟 Redis 锁跨进程互斥):
|
||||
// 副本 A 持锁期间副本 B 的 acquireDistExecGate 必须等待,A 释放后 B 才能获得。
|
||||
func TestDistExecGate_CrossReplicaMutualExclusion(t *testing.T) {
|
||||
shared := lock.NewLocalLock()
|
||||
defer shared.Close()
|
||||
|
||||
replicaA := newGateTestRuntime(shared)
|
||||
replicaB := newGateTestRuntime(shared)
|
||||
|
||||
// A 先持有(模拟对端副本正在驱动该实例)
|
||||
unlockA := replicaA.acquireDistExecGate(context.Background(), "inst-1")
|
||||
require.NotNil(t, unlockA)
|
||||
|
||||
acquired := make(chan struct{})
|
||||
var unlockB func()
|
||||
go func() {
|
||||
unlockB = replicaB.acquireDistExecGate(context.Background(), "inst-1")
|
||||
close(acquired)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-acquired:
|
||||
t.Fatal("副本 B 在 A 持锁期间不应拿到门闩(跨副本互斥失效)")
|
||||
case <-time.After(150 * time.Millisecond):
|
||||
}
|
||||
|
||||
// A 释放后 B 应能获得
|
||||
unlockA()
|
||||
select {
|
||||
case <-acquired:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("A 释放后 B 未能获得门闩")
|
||||
}
|
||||
require.NotNil(t, unlockB)
|
||||
unlockB()
|
||||
}
|
||||
|
||||
// 锁被他人长期持有(重试预算耗尽):放行执行返回 nil(可用性优先,不卡死流程)。
|
||||
func TestDistExecGate_BudgetExhausted_ProceedsWithoutGate(t *testing.T) {
|
||||
shared := lock.NewLocalLock()
|
||||
defer shared.Close()
|
||||
|
||||
// 缩短重试预算,避免测试跑 15 秒
|
||||
oldInterval, oldRetries := distExecGateInterval, distExecGateRetries
|
||||
distExecGateInterval, distExecGateRetries = 5*time.Millisecond, 5
|
||||
defer func() { distExecGateInterval, distExecGateRetries = oldInterval, oldRetries }()
|
||||
|
||||
// 占住锁不放(模拟对端副本驱动卡死,TTL 未到)
|
||||
_, err := shared.Lock(context.Background(), distExecGateKey("inst-2"), time.Minute)
|
||||
require.NoError(t, err)
|
||||
|
||||
replica := newGateTestRuntime(shared)
|
||||
start := time.Now()
|
||||
unlock := replica.acquireDistExecGate(context.Background(), "inst-2")
|
||||
assert.Nil(t, unlock, "重试预算耗尽后应放行(返回 nil)")
|
||||
assert.Less(t, time.Since(start), 3*time.Second, "不应阻塞到默认 15s 预算")
|
||||
}
|
||||
|
||||
// 锁空闲:立即获得,释放后可再次获得(正常生命周期);nil Locker 引擎返回 nil。
|
||||
func TestDistExecGate_Lifecycle(t *testing.T) {
|
||||
shared := lock.NewLocalLock()
|
||||
defer shared.Close()
|
||||
|
||||
replica := newGateTestRuntime(shared)
|
||||
unlock := replica.acquireDistExecGate(context.Background(), "inst-3")
|
||||
require.NotNil(t, unlock)
|
||||
unlock()
|
||||
|
||||
// 释放后可重入
|
||||
unlock2 := replica.acquireDistExecGate(context.Background(), "inst-3")
|
||||
require.NotNil(t, unlock2)
|
||||
unlock2()
|
||||
|
||||
// 空 instanceID / nil Locker:no-op 放行
|
||||
assert.Nil(t, replica.acquireDistExecGate(context.Background(), ""))
|
||||
nilLocker := newGateTestRuntime(nil)
|
||||
assert.Nil(t, nilLocker.acquireDistExecGate(context.Background(), "inst-3"))
|
||||
}
|
||||
@@ -147,6 +147,11 @@ func (s *ProcessServiceImpl) Update(ctx context.Context, actor Actor, process *m
|
||||
// 被沿用。
|
||||
InvalidateForkGraphCache(process.ID)
|
||||
|
||||
// 同理驱逐 enginePool 已装载链:GetExecution 快路径不回读 DB,不驱逐则本副本
|
||||
// 继续用旧定义推进实例;多副本下另一副本装载的已是新定义,同一实例两套定义
|
||||
// 创建任务,join 永远收不齐或路由分叉。
|
||||
InvalidateExecutionCache(process.ID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -366,6 +371,7 @@ func (s *ProcessServiceImpl) Delete(ctx context.Context, actor Actor, processID
|
||||
// 占内存。流程定义本身不可变,正常 Deploy 走新版本(新 processID)不命中老
|
||||
// 缓存——只有 Delete 才需要显式清理。
|
||||
InvalidateForkGraphCache(processID)
|
||||
InvalidateExecutionCache(processID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/rulego/gflow-engine/dao"
|
||||
"github.com/rulego/gflow-engine/model"
|
||||
@@ -12,6 +13,69 @@ import (
|
||||
"github.com/rulego/rulego/api/types"
|
||||
)
|
||||
|
||||
// runtimeServiceRegistry 已创建的 RuntimeServiceImpl 注册表。enginePool(已装载的
|
||||
// 规则链)挂在每个服务实例上,失效时须逐个清理;池缓存按 processID 键且不回读 DB
|
||||
// (见 GetExecution 快路径),Update 就地改 definition_json 后若不驱逐,本副本会
|
||||
// 继续用旧链推进实例。
|
||||
var runtimeServiceRegistry sync.Map // *RuntimeServiceImpl -> struct{}
|
||||
|
||||
// enginePoolInvalidateHook 跨副本失效广播钩子(多副本部署由 gflow 注入:PUBLISH 到
|
||||
// redis),语义与 forkGraph 的同名机制一致(见 fork_aware_resume.go)。
|
||||
var (
|
||||
enginePoolHookMu sync.RWMutex
|
||||
enginePoolInvalidateHook func(processID string)
|
||||
)
|
||||
|
||||
// SetEnginePoolInvalidateHook 注入跨副本 enginePool 失效广播钩子(gflow 启动时调)。
|
||||
func SetEnginePoolInvalidateHook(h func(processID string)) {
|
||||
enginePoolHookMu.Lock()
|
||||
defer enginePoolHookMu.Unlock()
|
||||
enginePoolInvalidateHook = h
|
||||
}
|
||||
|
||||
func getEnginePoolHook() func(processID string) {
|
||||
enginePoolHookMu.RLock()
|
||||
defer enginePoolHookMu.RUnlock()
|
||||
return enginePoolInvalidateHook
|
||||
}
|
||||
|
||||
// InvalidateExecutionCache 驱逐所有引擎池(含各租户池)中 processID 的已装载链,
|
||||
// 并触发跨副本失效广播。ProcessService.Update / Delete(就地改 definition_json、
|
||||
// processID 不变)调用;Deploy 走新版本新 processID,不命中旧缓存。
|
||||
func InvalidateExecutionCache(processID string) {
|
||||
if processID == "" {
|
||||
return
|
||||
}
|
||||
invalidateExecutionCacheLocal(processID)
|
||||
if hook := getEnginePoolHook(); hook != nil {
|
||||
hook(processID)
|
||||
}
|
||||
}
|
||||
|
||||
// ApplyRemoteExecutionInvalidate 仅清本地(不广播),供跨副本订阅方收到远程失效
|
||||
// 消息时调用,避免广播循环。
|
||||
func ApplyRemoteExecutionInvalidate(processID string) {
|
||||
if processID == "" {
|
||||
return
|
||||
}
|
||||
invalidateExecutionCacheLocal(processID)
|
||||
}
|
||||
|
||||
func invalidateExecutionCacheLocal(processID string) {
|
||||
runtimeServiceRegistry.Range(func(k, _ any) bool {
|
||||
if s, ok := k.(*RuntimeServiceImpl); ok && s != nil {
|
||||
s.enginePool.Del(processID)
|
||||
s.enginePools.Range(func(_, v any) bool {
|
||||
if p, ok := v.(types.RuleEnginePool); ok {
|
||||
p.Del(processID)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// GetExecution 根据ID获取执行实例(租户感知:先查 processID→tenant 缓存定位租户池)。
|
||||
func (s *RuntimeServiceImpl) GetExecution(ctx context.Context, processID string) (types.RuleEngine, error) {
|
||||
// 快速路径:缓存命中(processID→tenant)+ 池命中 → 免 DB 查询
|
||||
|
||||
@@ -317,3 +317,53 @@ func TestInitExecution_MigratesLegacyRouteGateway(t *testing.T) {
|
||||
t.Fatal("engine should not be nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEnginePool_InvalidateExecutionCache: Update/Delete 就地改 definition_json 后,
|
||||
// InvalidateExecutionCache 必须驱逐注册表内所有服务实例的池条目(默认池+各租户池)
|
||||
// 并触发跨副本广播钩子;ApplyRemoteExecutionInvalidate 只清本地、不再广播(防循环);
|
||||
// 驱逐后 GetExecution 按需自愈重装载。
|
||||
func TestEnginePool_InvalidateExecutionCache(t *testing.T) {
|
||||
rs, db := newPoolTestRS(t)
|
||||
// 测试直构的 rs 不经 NewRuntimeService,手动登记进失效注册表
|
||||
runtimeServiceRegistry.Store(rs, struct{}{})
|
||||
t.Cleanup(func() { runtimeServiceRegistry.Delete(rs) })
|
||||
const tenant = "tenant-inval"
|
||||
require := assert.New(t)
|
||||
|
||||
seedProcess(db, "proc-inval", "inval-key", 1, tenant, "chain-inval")
|
||||
require.NoError(rs.PreloadChain(tenant, "proc-inval", poolTestChainDef("chain-inval")))
|
||||
_, ok := rs.poolFor(tenant).Get("proc-inval")
|
||||
require.True(ok, "预加载后应在租户池")
|
||||
|
||||
broadcast := make(chan string, 1)
|
||||
oldHook := getEnginePoolHook()
|
||||
SetEnginePoolInvalidateHook(func(processID string) { broadcast <- processID })
|
||||
t.Cleanup(func() { SetEnginePoolInvalidateHook(oldHook) })
|
||||
|
||||
InvalidateExecutionCache("proc-inval")
|
||||
|
||||
_, ok = rs.poolFor(tenant).Get("proc-inval")
|
||||
require.False(ok, "失效后应从租户池驱逐")
|
||||
select {
|
||||
case got := <-broadcast:
|
||||
require.Equal("proc-inval", got)
|
||||
default:
|
||||
t.Fatal("InvalidateExecutionCache 应触发跨副本广播钩子")
|
||||
}
|
||||
|
||||
// 自愈:驱逐后 GetExecution 慢路径从 DB 重装载最新定义
|
||||
_, err := rs.GetExecution(context.Background(), "proc-inval")
|
||||
require.NoError(err)
|
||||
_, ok = rs.poolFor(tenant).Get("proc-inval")
|
||||
require.True(ok, "驱逐后 GetExecution 应自愈重装载")
|
||||
|
||||
// 远程失效路径:只清本地、不触发钩子
|
||||
ApplyRemoteExecutionInvalidate("proc-inval")
|
||||
_, ok = rs.poolFor(tenant).Get("proc-inval")
|
||||
require.False(ok)
|
||||
select {
|
||||
case got := <-broadcast:
|
||||
t.Fatalf("ApplyRemoteExecutionInvalidate 不应再广播,却收到 %q", got)
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -165,8 +165,7 @@ func (s *RuntimeServiceImpl) StartProcessInstanceByID(ctx context.Context, actor
|
||||
return "", err
|
||||
}
|
||||
if engine != nil {
|
||||
// 初始驱动与对端副本的恢复/AfterCommit 驱动共用同一把跨副本门闩,避免
|
||||
// 启动驱动与启动期恢复巡检并发重入同一实例重复建首任务。
|
||||
// 与对端副本的恢复/AfterCommit 驱动共用同一把门闩,避免并发重入同一实例重复建首任务
|
||||
if unlock := s.acquireDistExecGate(ctx, instanceID); unlock != nil {
|
||||
defer unlock()
|
||||
}
|
||||
@@ -1144,8 +1143,7 @@ func (s *RuntimeServiceImpl) ExecuteNext(ctx context.Context, processInstanceID,
|
||||
release, reentrant := s.acquireExecGate(processInstanceID)
|
||||
defer release()
|
||||
if !reentrant {
|
||||
// 跨副本互斥:execGate 只串行化本进程;多副本共享库时由 Locker(宿主注入
|
||||
// Redis 锁,单机 LocalLock 无感)串行化两副本对同一实例的并发驱动。
|
||||
// 跨副本互斥:execGate 只管本进程,副本间由 Locker 串行化(单机 LocalLock 无感)
|
||||
if unlock := s.acquireDistExecGate(ctx, processInstanceID); unlock != nil {
|
||||
defer unlock()
|
||||
}
|
||||
@@ -1297,8 +1295,7 @@ func (s *RuntimeServiceImpl) ForceResumeInstance(ctx context.Context, actor Acto
|
||||
return fmt.Errorf("process instance is in terminal status: %s", inst.Status)
|
||||
}
|
||||
|
||||
// 跨副本门闩:强制恢复是管理员手动触发的 multi-restore,同样须与对端副本的
|
||||
// AfterCommit 驱动互斥(读-判-驱窗口与 RestoreProcessInstance 同构)。
|
||||
// 与 RestoreProcessInstance 同一读-判-驱窗口,同样须与对端副本的驱动互斥
|
||||
if unlock := s.acquireDistExecGate(ctx, processInstanceID); unlock != nil {
|
||||
defer unlock()
|
||||
}
|
||||
@@ -1439,8 +1436,7 @@ func (s *RuntimeServiceImpl) RestoreProcessInstance(ctx context.Context, actor A
|
||||
return err
|
||||
}
|
||||
|
||||
// 跨副本门闩:恢复的"读任务 → 判定 → 驱动"窗口须与对端副本的 AfterCommit
|
||||
// 驱动互斥,否则可能基于过期任务快照重复 restore。
|
||||
// 恢复的读-判-驱窗口须与对端副本的驱动互斥,避免基于过期任务快照重复 restore
|
||||
if unlock := s.acquireDistExecGate(ctx, processInstanceID); unlock != nil {
|
||||
defer unlock()
|
||||
}
|
||||
|
||||
@@ -19,7 +19,8 @@ import (
|
||||
utils2 "github.com/rulego/gflow-engine/utils"
|
||||
)
|
||||
|
||||
// mergeVariables 合并任务变量
|
||||
// mergeVariables 合并任务变量。既有变量为合法 JSON 但非对象时(fork-join 后 end
|
||||
// 节点的 variables 是 join 收集的分支消息数组)无法按键合并,跳过既有值只用新变量。
|
||||
func (s *TaskServiceImpl) mergeVariables(existingVariables *string, newVariables map[string]interface{}) (*string, error) {
|
||||
if newVariables == nil {
|
||||
return existingVariables, nil
|
||||
@@ -29,9 +30,15 @@ func (s *TaskServiceImpl) mergeVariables(existingVariables *string, newVariables
|
||||
|
||||
// 解析现有变量
|
||||
if existingVariables != nil && *existingVariables != "" {
|
||||
if err := utils2.FromJSON(*existingVariables, &merged); err != nil {
|
||||
var existing any
|
||||
if err := utils2.FromJSON(*existingVariables, &existing); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse existing variables: %w", err)
|
||||
}
|
||||
if m, ok := existing.(map[string]interface{}); ok {
|
||||
merged = m
|
||||
} else {
|
||||
merged = make(map[string]interface{})
|
||||
}
|
||||
} else {
|
||||
merged = make(map[string]interface{})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
// Package multiinstance — 双副本共享一库的并发安全集成测试。
|
||||
//
|
||||
// 两个引擎实例(各自的 execGate / enginePool / service 集)连接同一个 PostgreSQL
|
||||
// 库,注入同一把共享键锁(对应多副本部署的 Redis 分布式锁),验证:
|
||||
// - fork-join 最后两条分支在两个副本上并发 approve,end 只执行一次、各分支任务
|
||||
// 各只一条,实例恰好完成一次
|
||||
// - ProcessService.Update 后 InvalidateExecutionCache 对另一副本的已装载链生效
|
||||
//
|
||||
// 独立成包(不与 test/e2e 混用):components.Register 是进程级全局注册表,同包
|
||||
// 注册两个引擎的 services 会互相覆盖。PG 行锁(FOR UPDATE)真实生效,与生产多实例
|
||||
// 行为一致;无 PG 环境自动跳过(GFLOW_MULTI_PG_DSN 可覆盖 DSN)。
|
||||
package multiinstance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/rulego/gflow-engine/components"
|
||||
"github.com/rulego/gflow-engine/config"
|
||||
"github.com/rulego/gflow-engine/model"
|
||||
"github.com/rulego/gflow-engine/service"
|
||||
"github.com/rulego/gflow-engine/types/enums"
|
||||
"github.com/rulego/gflow-engine/utils/lock"
|
||||
)
|
||||
|
||||
const miTenantID = "default"
|
||||
|
||||
// miDDL PG 方言的引擎表 DDL(与生产 schema 对齐的最小集,不含业务扩展列)。
|
||||
var miDDL = []string{
|
||||
`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 TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, tenant_id TEXT NOT NULL,
|
||||
created_by TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_by TEXT, updated_at TIMESTAMP, ext TEXT,
|
||||
process_type TEXT NOT NULL DEFAULT 'main', icon TEXT NOT NULL DEFAULT '')`,
|
||||
`CREATE TABLE IF NOT EXISTS wf_instance (
|
||||
id TEXT PRIMARY KEY, process_id TEXT NOT NULL, business_key TEXT, name TEXT NOT NULL,
|
||||
start_user_id TEXT NOT NULL DEFAULT '', status TEXT NOT NULL, variables TEXT,
|
||||
current_activity TEXT, priority INTEGER NOT NULL DEFAULT 50, parent_id TEXT,
|
||||
tenant_id TEXT NOT NULL, created_by TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_by TEXT, updated_at TIMESTAMP,
|
||||
end_reason TEXT, duration INTEGER, ended_at TIMESTAMP)`,
|
||||
`CREATE TABLE IF NOT EXISTS wf_task (
|
||||
id TEXT PRIMARY KEY, process_instance_id TEXT, process_id TEXT, parent_id TEXT,
|
||||
task_def_key TEXT, task_type TEXT, name TEXT, description TEXT, status TEXT,
|
||||
assignee TEXT, owner TEXT, priority INTEGER DEFAULT 50, sequence_order INTEGER DEFAULT 0,
|
||||
due_date TIMESTAMP, form_key TEXT, variables TEXT, claimed_at TIMESTAMP,
|
||||
approval_type TEXT, approval_rule TEXT, delegate_from TEXT, delegate_reason TEXT,
|
||||
delegate_time TIMESTAMP, ended_at TIMESTAMP, comment TEXT, end_reason TEXT,
|
||||
duration INTEGER, tenant_id TEXT, created_by TEXT, created_at TIMESTAMP,
|
||||
updated_by TEXT, updated_at TIMESTAMP)`,
|
||||
`CREATE TABLE IF NOT EXISTS wf_task_assignee (
|
||||
id TEXT PRIMARY KEY, task_id TEXT NOT NULL, entity_type TEXT NOT NULL DEFAULT 'role',
|
||||
entity_id TEXT NOT NULL, tenant_id TEXT NOT NULL DEFAULT '', created_at TIMESTAMP)`,
|
||||
`CREATE TABLE IF NOT EXISTS wf_hi_instance (
|
||||
id TEXT PRIMARY KEY, process_id TEXT NOT NULL, business_key TEXT, name TEXT NOT NULL,
|
||||
start_user_id TEXT NOT NULL DEFAULT '', status TEXT NOT NULL, variables TEXT,
|
||||
current_activity TEXT, priority INTEGER NOT NULL DEFAULT 50, parent_id TEXT,
|
||||
tenant_id TEXT NOT NULL, created_by TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_by TEXT, updated_at TIMESTAMP,
|
||||
end_reason TEXT, duration INTEGER, ended_at TIMESTAMP)`,
|
||||
`CREATE TABLE IF NOT EXISTS wf_hi_task (
|
||||
id TEXT PRIMARY KEY, process_instance_id TEXT, process_id TEXT, parent_id TEXT,
|
||||
task_def_key TEXT, task_type TEXT, name TEXT, description TEXT, status TEXT,
|
||||
assignee TEXT, owner TEXT, priority INTEGER DEFAULT 50, sequence_order INTEGER DEFAULT 0,
|
||||
due_date TIMESTAMP, form_key TEXT, variables TEXT, claimed_at TIMESTAMP,
|
||||
approval_type TEXT, approval_rule TEXT, delegate_from TEXT, delegate_reason TEXT,
|
||||
delegate_time TIMESTAMP, ended_at TIMESTAMP, comment TEXT, end_reason TEXT,
|
||||
duration INTEGER, tenant_id TEXT, created_by TEXT, created_at TIMESTAMP,
|
||||
updated_by TEXT, updated_at TIMESTAMP)`,
|
||||
`CREATE TABLE IF NOT EXISTS wf_task_comment (
|
||||
id TEXT PRIMARY KEY, task_id TEXT NOT NULL, process_instance_id TEXT NOT NULL DEFAULT '',
|
||||
tenant_id TEXT NOT NULL DEFAULT '', user_id TEXT NOT NULL,
|
||||
user_name TEXT NOT NULL DEFAULT '', content TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
|
||||
}
|
||||
|
||||
// miEnv 两个副本引擎 + 共享 PG 库。
|
||||
type miEnv struct {
|
||||
t *testing.T
|
||||
replicaA service.WorkflowEngine // 首个副本:组件全局注册表指向它的 services
|
||||
replicaB service.WorkflowEngine
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func newMultiReplicaEnv(t *testing.T) *miEnv {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("GFLOW_MULTI_PG_DSN")
|
||||
if dsn == "" {
|
||||
dsn = "postgres://postgres:postgres@localhost:5432/gflow_engine_pgtest?sslmode=disable"
|
||||
}
|
||||
|
||||
// 建表用独立连接(引擎起来前把 schema 准备好)
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("PG 不可用,跳过双副本测试: %v", err)
|
||||
}
|
||||
for _, ddl := range miDDL {
|
||||
require.NoError(t, db.Exec(ddl).Error, "create table")
|
||||
}
|
||||
for _, tbl := range []string{"wf_task_comment", "wf_hi_task", "wf_hi_instance", "wf_task_assignee", "wf_task", "wf_instance", "wf_process"} {
|
||||
require.NoError(t, db.Exec("DELETE FROM "+tbl).Error, "clear "+tbl)
|
||||
}
|
||||
|
||||
// 共享键锁:两副本注入同一实例,模拟多副本部署下的 Redis 分布式锁语义
|
||||
shared := lock.NewLocalLock()
|
||||
t.Cleanup(shared.Close)
|
||||
|
||||
cfgA := &config.Config{Database: &config.DatabaseConfig{Driver: "postgres", Dsn: dsn, MaxOpenConns: 8, MaxIdleConns: 4}}
|
||||
replicaA, err := service.NewWorkflowEngineBuilder().
|
||||
SetName("replica-a").SetConfig(cfgA).
|
||||
SetIDGenerator(service.NewIDGenerator()).
|
||||
SetLocker(shared).
|
||||
Build()
|
||||
require.NoError(t, err, "build replica A")
|
||||
require.NoError(t, replicaA.Start(context.Background()), "start replica A")
|
||||
|
||||
cfgB := &config.Config{Database: &config.DatabaseConfig{Driver: "postgres", Dsn: dsn, MaxOpenConns: 8, MaxIdleConns: 4}}
|
||||
replicaB, err := service.NewWorkflowEngineBuilder().
|
||||
SetName("replica-b").SetConfig(cfgB).
|
||||
SetIDGenerator(service.NewIDGenerator()).
|
||||
SetLocker(shared).
|
||||
Build()
|
||||
require.NoError(t, err, "build replica B")
|
||||
require.NoError(t, replicaB.Start(context.Background()), "start replica B")
|
||||
|
||||
// components.Register 是进程级全局注册表(两副本同进程只注册一次)。
|
||||
// 节点服务经 A 注入;A/B 的 services 都绑定同一个 PG 库,语义等价。
|
||||
require.NoError(t, components.Register(components.ComponentDeps{
|
||||
TaskService: replicaA.GetTaskServiceInternal(),
|
||||
IdentityService: replicaA.GetIdentityService(),
|
||||
RuntimeService: replicaA.GetRuntimeServiceInternal(),
|
||||
}), "register components")
|
||||
|
||||
t.Cleanup(func() {
|
||||
_ = replicaB.Stop(context.Background())
|
||||
_ = replicaA.Stop(context.Background())
|
||||
if sqlDB, e := db.DB(); e == nil {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
})
|
||||
return &miEnv{t: t, replicaA: replicaA, replicaB: replicaB, db: db}
|
||||
}
|
||||
|
||||
func (e *miEnv) deployForkJoin(processKey string) {
|
||||
e.t.Helper()
|
||||
def := map[string]interface{}{
|
||||
"ruleChain": map[string]interface{}{"id": processKey, "name": processKey, "root": true},
|
||||
"metadata": map[string]interface{}{
|
||||
"firstNodeIndex": 0,
|
||||
"nodes": []map[string]interface{}{
|
||||
{"id": "fork1", "type": "fork", "name": "Parallel Fork"},
|
||||
{"id": "task_a", "type": "userTask", "name": "Branch A", "configuration": map[string]interface{}{
|
||||
"candidateType": "user", "candidateConfig": map[string]interface{}{"userIds": []string{"user_a"}}, "approvalType": "single"}},
|
||||
{"id": "task_b", "type": "userTask", "name": "Branch B", "configuration": map[string]interface{}{
|
||||
"candidateType": "user", "candidateConfig": map[string]interface{}{"userIds": []string{"user_b"}}, "approvalType": "single"}},
|
||||
{"id": "join1", "type": "join", "name": "Parallel Join", "configuration": map[string]interface{}{"timeout": 5}},
|
||||
{"id": "end", "type": "end", "name": "End"},
|
||||
},
|
||||
"connections": []map[string]interface{}{
|
||||
{"fromId": "fork1", "toId": "task_a", "type": "Success"},
|
||||
{"fromId": "fork1", "toId": "task_b", "type": "Success"},
|
||||
{"fromId": "task_a", "toId": "join1", "type": "Success"},
|
||||
{"fromId": "task_a", "toId": "join1", "type": "Failure"},
|
||||
{"fromId": "task_b", "toId": "join1", "type": "Success"},
|
||||
{"fromId": "task_b", "toId": "join1", "type": "Failure"},
|
||||
{"fromId": "join1", "toId": "end", "type": "Success"},
|
||||
},
|
||||
},
|
||||
}
|
||||
raw, err := json.Marshal(def)
|
||||
require.NoError(e.t, err)
|
||||
_, err = e.replicaA.GetProcessService().Deploy(context.Background(),
|
||||
service.Actor{UserID: "admin", TenantID: miTenantID},
|
||||
&model.WfProcess{ProcessKey: processKey, Name: processKey, DefinitionJSON: string(raw),
|
||||
Status: string(enums.ProcessStatusActive), TenantID: miTenantID, CreatedBy: "admin"}, true)
|
||||
require.NoError(e.t, err, "deploy fork/join process")
|
||||
}
|
||||
|
||||
func (e *miEnv) startInstance(processKey, via string) string {
|
||||
e.t.Helper()
|
||||
var eng service.WorkflowEngine
|
||||
if via == "B" {
|
||||
eng = e.replicaB
|
||||
} else {
|
||||
eng = e.replicaA
|
||||
}
|
||||
instID, err := eng.GetRuntimeService().StartProcessInstanceByKey(context.Background(),
|
||||
service.Actor{UserID: "starter", TenantID: miTenantID}, processKey, "", map[string]interface{}{"amount": 100})
|
||||
require.NoError(e.t, err, "start instance via replica "+via)
|
||||
return instID
|
||||
}
|
||||
|
||||
func (e *miEnv) activeTaskID(instanceID, defKey string) string {
|
||||
e.t.Helper()
|
||||
require.Eventually(e.t, func() bool {
|
||||
var n int64
|
||||
_ = e.db.Raw("SELECT COUNT(*) FROM wf_task WHERE process_instance_id = ? AND task_def_key = ? AND status = ?",
|
||||
instanceID, defKey, string(enums.TaskStatusActive)).Scan(&n).Error
|
||||
return n == 1
|
||||
}, 3*time.Second, 50*time.Millisecond, defKey+" 应恰好有 1 条 Active 任务")
|
||||
var id string
|
||||
require.NoError(e.t, e.db.Raw("SELECT id FROM wf_task WHERE process_instance_id = ? AND task_def_key = ? AND status = ? LIMIT 1",
|
||||
instanceID, defKey, string(enums.TaskStatusActive)).Scan(&id).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
func (e *miEnv) approveVia(via, taskID, who string) error {
|
||||
eng := e.replicaA
|
||||
if via == "B" {
|
||||
eng = e.replicaB
|
||||
}
|
||||
ctx := service.WithAPICallingMode(service.SetUserToCtx(context.Background(),
|
||||
&service.Actor{UserID: who, UserName: who, TenantID: miTenantID}))
|
||||
return eng.GetTaskService().Approve(ctx, service.Actor{UserID: who, UserName: who, TenantID: miTenantID}, taskID, "multi-replica", nil)
|
||||
}
|
||||
|
||||
func (e *miEnv) instanceStatus(instanceID string) string {
|
||||
e.t.Helper()
|
||||
var st string
|
||||
_ = e.db.Raw("SELECT status FROM wf_instance WHERE id = ?", instanceID).Scan(&st).Error
|
||||
if st != "" {
|
||||
return st
|
||||
}
|
||||
// 完成即归档删运行时行,读历史表(与 e2e 的 instanceStatus 同口径)
|
||||
require.NoError(e.t, e.db.Raw("SELECT status FROM wf_hi_instance WHERE id = ?", instanceID).Scan(&st).Error)
|
||||
return st
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// fork 两分支的最后两张任务分别经 A、B 两副本并发 approve:两副本的 AfterCommit
|
||||
// 驱动同时判定 fork-join 收齐时,跨副本门闩须保证先到者恢复、后到者幂等退出。
|
||||
// ---------------------------------------------------------------------------
|
||||
func TestMultiReplica_ForkJoinConcurrentApprove_SingleEndRun(t *testing.T) {
|
||||
env := newMultiReplicaEnv(t)
|
||||
env.deployForkJoin("mi_fork_concurrent")
|
||||
instID := env.startInstance("mi_fork_concurrent", "A")
|
||||
|
||||
taskA := env.activeTaskID(instID, "task_a")
|
||||
taskB := env.activeTaskID(instID, "task_b")
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
wg.Add(2)
|
||||
go func() { defer wg.Done(); errs[0] = env.approveVia("A", taskA, "user_a") }()
|
||||
go func() { defer wg.Done(); errs[1] = env.approveVia("B", taskB, "user_b") }()
|
||||
wg.Wait()
|
||||
for i, err := range errs {
|
||||
require.NoError(t, err, fmt.Sprintf("replica %c approve", 'A'+rune(i)))
|
||||
}
|
||||
|
||||
// 实例恰好完成一次
|
||||
require.Eventually(t, func() bool {
|
||||
return env.instanceStatus(instID) == string(enums.InstanceStatusCompleted)
|
||||
}, 5*time.Second, 50*time.Millisecond, "两副本并发 approve 后实例应完成,status=%q", env.instanceStatus(instID))
|
||||
|
||||
// 归档落定后断言不变量
|
||||
require.Eventually(t, func() bool {
|
||||
var n int64
|
||||
_ = env.db.Raw("SELECT COUNT(*) FROM wf_hi_task WHERE process_instance_id = ?", instID).Scan(&n).Error
|
||||
return n > 0
|
||||
}, 3*time.Second, 50*time.Millisecond, "wf_hi_task 应已归档")
|
||||
|
||||
count := func(sql string, args ...interface{}) int64 {
|
||||
var n int64
|
||||
require.NoError(t, env.db.Raw(sql, args...).Scan(&n).Error)
|
||||
return n
|
||||
}
|
||||
assert.Equal(t, int64(1), count("SELECT COUNT(*) FROM wf_hi_task WHERE process_instance_id = ? AND task_type = 'end'", instID),
|
||||
"end 节点应恰好执行 1 次")
|
||||
assert.Equal(t, int64(1), count("SELECT COUNT(*) FROM wf_hi_task WHERE process_instance_id = ? AND task_type = 'end' AND status = 'completed'", instID),
|
||||
"end 任务应 Completed(join 收集的数组变量不能让 complete 合并失败)")
|
||||
assert.Equal(t, int64(1), count("SELECT COUNT(*) FROM wf_hi_task WHERE process_instance_id = ? AND task_def_key = 'task_a'", instID),
|
||||
"task_a 应恰好 1 条")
|
||||
assert.Equal(t, int64(1), count("SELECT COUNT(*) FROM wf_hi_task WHERE process_instance_id = ? AND task_def_key = 'task_b'", instID),
|
||||
"task_b 应恰好 1 条")
|
||||
// 运行时表应清空(归档迁移完成,无孤儿行)
|
||||
assert.Equal(t, int64(0), count("SELECT COUNT(*) FROM wf_task WHERE process_instance_id = ?", instID),
|
||||
"实例完成后 wf_task 不应残留")
|
||||
assert.Equal(t, int64(0), count("SELECT COUNT(*) FROM wf_instance WHERE id = ?", instID),
|
||||
"实例完成后 wf_instance 不应残留")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 缓存失效:A 副本 Update 定义(就地改 definition_json)后,B 副本已装载的链应被
|
||||
// 驱逐(跨副本广播),下次 GetExecution 装载新定义而非命中旧缓存。
|
||||
// ---------------------------------------------------------------------------
|
||||
func TestMultiReplica_ExecutionCacheInvalidation(t *testing.T) {
|
||||
env := newMultiReplicaEnv(t)
|
||||
|
||||
def := map[string]interface{}{
|
||||
"ruleChain": map[string]interface{}{"id": "mi_cache_inval", "name": "旧名", "root": true},
|
||||
"metadata": map[string]interface{}{
|
||||
"firstNodeIndex": 0,
|
||||
"nodes": []map[string]interface{}{
|
||||
{"id": "end", "type": "end", "name": "End"},
|
||||
},
|
||||
"connections": []map[string]interface{}{},
|
||||
},
|
||||
}
|
||||
rawOld, _ := json.Marshal(def)
|
||||
proc, err := env.replicaA.GetProcessService().Deploy(context.Background(),
|
||||
service.Actor{UserID: "admin", TenantID: miTenantID},
|
||||
&model.WfProcess{ProcessKey: "mi_cache_inval", Name: "mi_cache_inval", DefinitionJSON: string(rawOld),
|
||||
Status: string(enums.ProcessStatusActive), TenantID: miTenantID, CreatedBy: "admin"}, true)
|
||||
require.NoError(t, err, "deploy")
|
||||
|
||||
// B 副本装载旧链
|
||||
rsB, ok := env.replicaB.GetRuntimeService().(*service.RuntimeServiceImpl)
|
||||
require.True(t, ok, "RuntimeService 实现应为 RuntimeServiceImpl")
|
||||
eOld, err := rsB.GetExecution(context.Background(), proc.ID)
|
||||
require.NoError(t, err, "B 装载链")
|
||||
require.Equal(t, "旧名", eOld.Definition().RuleChain.Name, "装载的应是旧定义")
|
||||
|
||||
// A 副本就地改名
|
||||
def["ruleChain"].(map[string]interface{})["name"] = "新名"
|
||||
rawNew, _ := json.Marshal(def)
|
||||
require.NoError(t, env.replicaA.GetProcessService().Update(context.Background(),
|
||||
service.Actor{UserID: "admin", TenantID: miTenantID},
|
||||
&model.WfProcess{ID: proc.ID, ProcessKey: proc.ProcessKey, Name: "mi_cache_inval",
|
||||
DefinitionJSON: string(rawNew), Status: string(enums.ProcessStatusActive),
|
||||
TenantID: miTenantID}), "update definition")
|
||||
|
||||
// Update 内部已驱逐+广播;B 再取链应拿到新定义而非旧缓存
|
||||
eNew, err := rsB.GetExecution(context.Background(), proc.ID)
|
||||
require.NoError(t, err, "B 重新装载链")
|
||||
assert.Equal(t, "新名", eNew.Definition().RuleChain.Name, "失效广播后 B 应装载新定义")
|
||||
}
|
||||
Reference in new issue
Block a user