feat: httpCall与serviceTask节点瞬时故障自动重试

This commit is contained in:
rulego-team committed 2026-11-28 23:24:46 +08:00
1 parent bbcec9138c
commit ffde2190d2
10 files changed
+880 -60

No files matched your search

+101 -55
View File
@@ -77,6 +77,8 @@ type HttpCallNodeConfiguration struct {
// ReservedKey 完整响应写入的 msg.Data key(对象存对象、非对象存原文),默认 "_http"。
// 存量配置可自定义;设计器不再暴露此字段。
ReservedKey string `json:"reservedKey"`
// retryCount 从原始 configuration map 直读(见 Init),不走本结构体:
// 与 serviceTask 同一个解析器(retryCountFromConfig),缺省/裁剪口径单点维护。
// SSRF 防护(可选)
// AllowedHosts 允许访问的主机白名单。为空时不做主机限制。
@@ -111,6 +113,8 @@ type HttpCallNode struct {
allowedHostSet map[string]bool
// hostIsDynamic URL 模板的主机部分是否含 ${...} 变量;仅主机动态时才启用危险地址拦截
hostIsDynamic bool
// maxRetries 瞬时故障自动重试预算(Init 时经 retryCountFromConfig 解析,0=关闭)
maxRetries int
}
// GetSelfId 当前节点 ID(CurrentNodeDef 缺失时退回节点类型)
@@ -143,6 +147,8 @@ func (n *HttpCallNode) Init(_ types.Config, cfg types.Configuration) error {
if strings.TrimSpace(n.Config.ReservedKey) == "" {
n.Config.ReservedKey = HTTPReservedKey
}
// 重试预算:未配置走缺省 3,显式值按 [0, NodeRetryMax] 裁剪(0=关闭)
n.maxRetries = retryCountFromConfig(cfg, constants.HttpCallDefaultRetryCount)
// 预编译模板(支持 ${msg.xxx}/${metadata.xxx} 变量替换)
t, err := el.NewTemplate(n.Config.Url)
@@ -232,7 +238,7 @@ func (n *HttpCallNode) Init(_ types.Config, cfg types.Configuration) error {
return nil
}
// OnMsg 渲染请求 → 发送 → 合并响应到 msg → TellSuccess/Failure
// OnMsg 渲染请求 → 发送(瞬时故障预算内自动重试)→ 合并响应到 msg → TellSuccess/Failure
func (n *HttpCallNode) OnMsg(ctx types.RuleContext, msg types.RuleMsg) {
defer recoverNodePanic(ctx, msg, HttpCallNodeType, n.GetSelfId())
start := time.Now()
@@ -247,73 +253,113 @@ func (n *HttpCallNode) OnMsg(ctx types.RuleContext, msg types.RuleMsg) {
ctx.TellFailure(msg, fmt.Errorf("httpCall url scheme not allowed: %q", redactEndpoint(endpoint)))
return
}
// 主机校验:白名单(如配置)+ 动态主机危险地址拦截
// 主机校验:白名单(如配置)+ 动态主机危险地址拦截。校验失败属配置/注入问题,
// 重试无意义,直接终态。
if err := n.validateURLHost(ctx.GetContext(), u); err != nil {
n.auditLog(msg, endpoint, 0, start, err)
ctx.TellFailure(msg, err)
return
}
var bodyReader io.Reader
// body 只渲染一次(表单值重试间稳定),每次重试重建 reader;
// 请求头每次重试重新执行模板——带时间戳/新鲜凭证的头随重试刷新是有意行为
var bodyBytes []byte
if n.bodyTmpl != nil {
bodyReader = bytes.NewReader([]byte(n.bodyTmpl.ExecuteAsString(evn)))
bodyBytes = []byte(n.bodyTmpl.ExecuteAsString(evn))
}
req, err := http.NewRequestWithContext(ctx.GetContext(), n.Config.Method, endpoint, bodyReader)
if err != nil {
berr := redactEndpointInError(fmt.Errorf("build http request: %w", err), endpoint)
n.auditLog(msg, endpoint, 0, start, berr)
ctx.TellFailure(msg, berr)
return
}
for k, t := range n.headerTmpl {
req.Header.Set(k, t.ExecuteAsString(evn))
}
// Idempotency-Key 节点执行实例生成一次、贯穿全部重试:下游接口对同一键去重,
// 重试不产生重复副作用。设计者显式配置的同名头优先。
idemKey := newNodeExecutionID()
resp, err := n.client.Do(req)
if err != nil {
// 脱敏错误串中的 endpoint,避免 query 凭据落日志/终止 reason
lerr := redactEndpointInError(fmt.Errorf("http call failed: %w", err), endpoint)
n.auditLog(msg, endpoint, 0, start, lerr)
ctx.TellFailure(msg, lerr)
return
}
defer resp.Body.Close()
// 多读 1 字节判断截断:静默截断的 JSON 会以"纯文本"形态混入 msg,宁可显式失败
body, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPResponseBytes+1))
if err != nil {
n.auditLog(msg, endpoint, resp.StatusCode, start, fmt.Errorf("read http response: %w", err))
ctx.TellFailure(msg, fmt.Errorf("read http response: %w", err))
return
}
if len(body) > maxHTTPResponseBytes {
err := fmt.Errorf("http response exceeds %d bytes limit", maxHTTPResponseBytes)
n.auditLog(msg, endpoint, resp.StatusCode, start, err)
ctx.TellFailure(msg, err)
return
}
if resp.StatusCode >= 400 {
// 响应体可能很大(上限 10MB),截断进错误串避免撑爆实例终止 reason
snippet := string(body)
if len(snippet) > 1024 {
snippet = snippet[:1024] + "...(truncated)"
attempt := 0 // 已重试次数
statusCode := 0
for {
statusCode = 0 // 每次尝试重置:终态审计只记本次失败的状态码,不残留上次尝试的
req, err := http.NewRequestWithContext(ctx.GetContext(), n.Config.Method, endpoint, bytes.NewReader(bodyBytes))
if err != nil {
// 构建失败=配置问题(方法/URL 非法),不重试
berr := redactEndpointInError(fmt.Errorf("build http request: %w", err), endpoint)
n.auditLog(msg, endpoint, 0, start, berr)
ctx.TellFailure(msg, berr)
return
}
for k, t := range n.headerTmpl {
req.Header.Set(k, t.ExecuteAsString(evn))
}
if req.Header.Get("Idempotency-Key") == "" {
req.Header.Set("Idempotency-Key", idemKey)
}
err := fmt.Errorf("http %d: %s", resp.StatusCode, snippet)
n.auditLog(msg, endpoint, resp.StatusCode, start, err)
ctx.TellFailure(msg, err)
return
}
// 输出合并与 aiAgent 同一套三规则(MergeAgentOutput):完整响应始终写 ReservedKey(默认 _http),
// 平铺模式(默认)再把对象顶层字段并入 msg.Data,映射最后执行(优先级最高)。
flatten := n.Config.FlattenOutput != nil && *n.Config.FlattenOutput
if err := MergeAgentOutput(&msg, body, n.Config.OutputMappings, n.Config.ReservedKey, flatten); err != nil {
ctx.TellFailure(msg, fmt.Errorf("merge http output: %w", err))
return
resp, err := n.client.Do(req)
if err == nil {
// 多读 1 字节判断截断:静默截断的 JSON 会以"纯文本"形态混入 msg,宁可显式失败
body, readErr := io.ReadAll(io.LimitReader(resp.Body, maxHTTPResponseBytes+1))
resp.Body.Close()
if readErr == nil && len(body) <= maxHTTPResponseBytes {
if resp.StatusCode < 400 {
// 成功出口:输出合并与 aiAgent 同一套三规则(MergeAgentOutput)——
// 完整响应始终写 ReservedKey(默认 _http),平铺模式(默认)再把对象
// 顶层字段并入 msg.Data,映射最后执行(优先级最高)。
flatten := n.Config.FlattenOutput != nil && *n.Config.FlattenOutput
if merr := MergeAgentOutput(&msg, body, n.Config.OutputMappings, n.Config.ReservedKey, flatten); merr != nil {
merr = fmt.Errorf("merge http output: %w", merr)
n.auditLog(msg, endpoint, resp.StatusCode, start, merr)
ctx.TellFailure(msg, merr)
return
}
n.auditLog(msg, endpoint, resp.StatusCode, start, nil)
ctx.TellSuccess(msg)
return
}
// 响应体可能很大(上限 10MB),截断进错误串避免撑爆实例终止 reason
snippet := string(body)
if len(snippet) > 1024 {
snippet = snippet[:1024] + "...(truncated)"
}
err = &httpStatusError{code: resp.StatusCode, body: snippet}
statusCode = resp.StatusCode
} else if readErr == nil {
err = fmt.Errorf("http response exceeds %d bytes limit", maxHTTPResponseBytes)
statusCode = resp.StatusCode
} else {
err = fmt.Errorf("read http response: %w", readErr)
statusCode = resp.StatusCode
}
} else {
// 保留错误链(%w):瞬时故障判定靠 errors.Is/As 解原始 net 错误,
// 脱敏只在终态上报时做(redact 会用 errors.New 砍链)
err = fmt.Errorf("http call failed: %w", err)
}
// 重试判定:只重试瞬时技术故障;预算耗尽或非瞬时故障(4xx/解析失败/SSRF)
// 才终态——重试期间不算失败。
if !isTransientNodeError(err) || attempt >= n.maxRetries {
// 终态上报前脱敏 endpoint,避免 query 凭据落日志/终止 reason
rerr := retryExhaustedError(attempt, redactEndpointInError(err, endpoint))
n.auditLog(msg, endpoint, statusCode, start, rerr)
ctx.TellFailure(msg, rerr)
return
}
// 实例终态哨兵:重试期间实例被并发终止/完成时立即停,不对终态实例继续发请求
if retryAbortRequested(msg) {
aerr := redactEndpointInError(retryAbortError(), endpoint)
n.auditLog(msg, endpoint, statusCode, start, aerr)
ctx.TellFailure(msg, aerr)
return
}
idx := attempt
delay := retryBackoffDelay(idx)
attempt++
logNodeRetry(HttpCallNodeType, n.GetSelfId(), attempt, n.maxRetries, delay, err)
if cerr := waitRetryBackoff(ctx.GetContext(), idx); cerr != nil {
// 引擎取消即停:以取消错误终止,不再发起请求
cerr = fmt.Errorf("http call retry backoff canceled: %w", cerr)
n.auditLog(msg, endpoint, statusCode, start, cerr)
ctx.TellFailure(msg, cerr)
return
}
}
n.auditLog(msg, endpoint, resp.StatusCode, start, nil)
ctx.TellSuccess(msg)
}
// auditLog 输出结构化审计日志;endpoint 经 redactEndpoint 脱敏。
+4 -2
View File
@@ -237,7 +237,8 @@ func TestHttpCallNode_4xxFailure(t *testing.T) {
}))
defer srv.Close()
cfg := `{"url":"` + srv.URL + `","method":"GET"}`
// retryCount=0 关闭重试:本用例验证失败终态语义,不验证重试(重试见 node_retry_test.go)
cfg := `{"url":"` + srv.URL + `","method":"GET","retryCount":0}`
engine := buildHttpEngine(t, "t_http_4xx", cfg)
msg := types.NewMsgWithJsonData(`{"days":3}`)
@@ -291,7 +292,8 @@ func TestHttpCall_Timeout(t *testing.T) {
}))
defer srv.Close()
cfg := `{"url":"` + srv.URL + `","method":"GET","timeoutMs":100}`
// retryCount=0 关闭重试:本用例验证超时终态语义,不验证重试(重试见 node_retry_test.go)
cfg := `{"url":"` + srv.URL + `","method":"GET","timeoutMs":100,"retryCount":0}`
engine := buildHttpEngine(t, "t_http_timeout", cfg)
msg := types.NewMsgWithJsonData(`{"days":3}`)
+256
View File
@@ -0,0 +1,256 @@
/*
* Copyright 2025 The RuleGo Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package components
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"net"
"net/http"
"regexp"
"strings"
"syscall"
"time"
"github.com/sirupsen/logrus"
"github.com/rulego/gflow-engine/types/constants"
"github.com/rulego/rulego/api/types"
)
// 节点瞬时故障自动重试的共享策略:可重试判定、指数退避、幂等键生成。
// httpCall(发送段同步循环)与 serviceTask(包装 RuleContext 拦截失败路由)
// 共用本文件的判定口径,重试语义必须一致。
//
// 量级边界:重试在节点 OnMsg 内同步进行,占住实例执行闸的时长≈退避累计
// (1s+4s+16s)+ 重试次数×timeoutMs,配置侧应控制两者乘积不超出业务可容忍窗口。
// nodeRetryBackoffUnit 指数退避时基,生产 1s(1s/4s/16s);测试替换为毫秒级提速。
var nodeRetryBackoffUnit = time.Second
// RetryAbortHook 实例终态哨兵:重试在节点 OnMsg 内同步进行,感知不到实例被并发
// 终止/完成(终止只改库归档,不取消在途 OnMsg),若不干预会对已终态实例继续发起
// 请求/副作用直到预算耗尽。组件装配(Register)时经 ComponentDeps.RuntimeService
// 接线:按消息元数据的 instance_id 查一次运行态,实例已离开可执行状态返回 true,
// 重试循环立即中止。挂起不算离开(挂起可恢复,中止会把本可恢复的实例提前推向
// 终态);查询失败放行(退化为仅按预算兜底)。未接线(未注册组件的嵌入式用法/
// 单测)时为 nil,跳过检查。
var RetryAbortHook func(msg types.RuleMsg) bool
// retryAbortError 实例终态哨兵命中后的终止错误:不再重试,节点走失败路由收尾
// (对已终态实例的失败路由由运行时守卫兜住,无害)。
func retryAbortError() error { return errors.New("实例已离开执行中状态,中止重试") }
// retryAbortRequested 哨兵命中判定。
func retryAbortRequested(msg types.RuleMsg) bool {
return RetryAbortHook != nil && RetryAbortHook(msg)
}
// retryBackoffDelay 第 retryIdx 次(0 起)重试前的等待时长:1x/4x/16x 指数,16x 封顶
// (retryCount 上限 5,后续重试不再放大等待)。
func retryBackoffDelay(retryIdx int) time.Duration {
if retryIdx > 2 {
retryIdx = 2
}
if retryIdx < 0 {
retryIdx = 0
}
return nodeRetryBackoffUnit << (2 * retryIdx)
}
// waitRetryBackoff 等待第 retryIdx 次重试的退避;引擎取消立即停,返回取消错误
// 且不再发起下一次请求。
func waitRetryBackoff(ctx context.Context, retryIdx int) error {
t := time.NewTimer(retryBackoffDelay(retryIdx))
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
// httpStatusError HTTP 状态码错误。保留原始状态码供重试判定(5xx 瞬时可重试、
// 408/429 瞬时可重试、其余 4xx 业务失败终态),错误串格式与历史实现一致
// ("http %d: %s")。
type httpStatusError struct {
code int
body string
}
func (e *httpStatusError) Error() string { return fmt.Sprintf("http %d: %s", e.code, e.body) }
// transient 5xx=服务端瞬时故障;408 请求超时/429 限流虽属 4xx,但同属瞬时过载,
// 重试有意义(429 的 Retry-After 不单独解析,统一按退避节奏重试);其余
// 4xx=请求本身有问题,重试无意义。
func (e *httpStatusError) transient() bool {
return e.code >= 500 || e.code == http.StatusRequestTimeout || e.code == http.StatusTooManyRequests
}
// transientMarker 可重试错误的自证接口:错误类型直接声明自己是否瞬时故障,
// 免去按错误串猜。
type transientMarker interface{ transient() bool }
// http5xxPattern serviceTask 注册函数把上游 5xx 格式化成普通错误串(丢失状态码
// 类型)时的兜底识别,要求 http 前缀锚定("http 502"、"HTTP 502 Bad Gateway"、
// "http503"),裸数字(金额、计数里的 500)不误判;原始状态行 HTTP/1.1 5xx 不在
// 识别面内——注册方应报语义化错误而非透传状态行。httpCall 自身走 httpStatusError
// 不经此路径。
var http5xxPattern = regexp.MustCompile(`http[ /]?5\d\d`)
// isTransientNodeError 判断节点执行错误是否瞬时技术故障(值得重试):
// 连接/读超时、连接拒绝、连接重置、断管、5xx、408/429。其余 4xx 业务失败、
// 解析失败、SSRF 拦截、引擎取消(context.Canceled)一律不可重试。
func isTransientNodeError(err error) bool {
if err == nil {
return false
}
if errors.Is(err, context.Canceled) {
return false
}
var tm transientMarker
if errors.As(err, &tm) {
return tm.transient()
}
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
return true
}
// 底层 syscall 错误跨平台判定(Windows 上 Go 把 ECONNREFUSED 映射到 WSA 同值)
if errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) {
return true
}
// 字符串兜底:serviceTask 注册函数常把底层错误格式化成普通错误串,类型化判定
// 到不了这里。覆盖 Windows 拨号文案("actively refused"=WSAECONNREFUSED、
// "forcibly closed"=WSAECONNRESET、"pipe has been ended"=EPIPE)
s := strings.ToLower(err.Error())
for _, p := range []string{
"connection refused", "actively refused",
"connection reset", "forcibly closed",
"broken pipe", "pipe has been ended",
"timeout", "deadline exceeded",
} {
if strings.Contains(s, p) {
return true
}
}
return http5xxPattern.MatchString(s)
}
// retryCountFromConfig 从节点 configuration 提取 retryCount:缺省给 def(httpCall=3、
// serviceTask=2),显式 0=关闭,负数与超出上限的值按 [0, NodeRetryMax] 裁剪。
// JSON 数字经 map 反序列化是 float64,同时兼容 int 注入。
func retryCountFromConfig(configuration types.Configuration, def int) int {
raw, ok := configuration["retryCount"]
if !ok || raw == nil {
return def
}
var n int
switch v := raw.(type) {
case float64:
n = int(v)
case int:
n = v
default:
return def
}
if n < 0 {
return 0
}
if n > constants.NodeRetryMax {
return constants.NodeRetryMax
}
return n
}
// newNodeExecutionID 生成节点执行实例的幂等键(16 字节随机 hex):同一节点执行的
// 全部重试共用一个键,下游接口据此去重。随机源失效时退回纳秒时间戳(进程内仍
// 满足"同一执行一致")。
func newNodeExecutionID() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return fmt.Sprintf("idem-%d", time.Now().UnixNano())
}
return hex.EncodeToString(b[:])
}
// retryExhaustedError 预算耗尽后的失败包装:错误串带「重试 N 次后失败」,
// 节点执行日志与实例终止 reason 据此可见重试事实。
func retryExhaustedError(retries int, err error) error {
if retries <= 0 {
return err
}
return fmt.Errorf("重试 %d 次后失败: %w", retries, err)
}
// retryServiceContext 包装 RuleContext 拦截失败路由:瞬时故障在预算内重试
// (重新执行 invoke),预算耗尽或业务失败原样交真实下游。
// 嵌入接口委托 TellSuccess/TellNext 等其余方法;只拦截 TellFailure——函数经
// TellNext(Failure) 路由失败时不带错误对象,无从判定瞬时性,不拦。
type retryServiceContext struct {
types.RuleContext
st *serviceRetryState
}
func (c *retryServiceContext) TellFailure(msg types.RuleMsg, err error) {
st := c.st
if st.attempt < st.max && isTransientNodeError(err) {
// 实例终态哨兵:重试期间实例被并发终止/完成时立即停,不再重跑副作用
if retryAbortRequested(msg) {
st.real.TellFailure(msg, retryAbortError())
return
}
idx := st.attempt
delay := retryBackoffDelay(idx)
st.attempt++
logNodeRetry(ServiceTaskNodeType, st.real.GetSelfId(), st.attempt, st.max, delay, err)
if cerr := waitRetryBackoff(st.real.GetContext(), idx); cerr != nil {
st.real.TellFailure(msg, fmt.Errorf("serviceTask 重试退避被取消: %w", cerr))
return
}
st.invoke()
return
}
st.real.TellFailure(msg, retryExhaustedError(st.attempt, err))
}
// serviceRetryState 一次节点执行的重试状态:attempt/max 跨重试共享,invoke 重新
// 执行节点(serviceTask=重跑 FunctionsNode.OnMsg,重解析函数名+重渲染 param)。
// attempt 无锁:依赖 FunctionsNode 契约——注册函数必须同步调用 Tell* 完成路由;
// 异步 goroutine 里回调 TellFailure 的宿主函数不在重试保障范围(会竞态+并发
// 重入 invoke),注册方需自行保证同步回调。
type serviceRetryState struct {
max int
attempt int
real types.RuleContext
invoke func()
}
// logNodeRetry 节点重试留痕:第几次/退避多久/错误,进节点执行日志。
func logNodeRetry(nodeType, nodeID string, attempt, max int, delay time.Duration, cause error) {
logrus.WithFields(logrus.Fields{
"nodeType": nodeType,
"nodeId": nodeID,
"attempt": fmt.Sprintf("%d/%d", attempt, max),
"backoffMs": delay.Milliseconds(),
"cause": cause.Error(),
}).Warn("transient failure, auto retrying")
}
+421
View File
@@ -0,0 +1,421 @@
/*
* Copyright 2025 The RuleGo Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package components
import (
"errors"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/rulego/rulego"
"github.com/rulego/rulego/api/types"
"github.com/rulego/rulego/components/action"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/rulego/gflow-engine/types/constants"
)
// speedUpRetryBackoff 把重试退避时基换到毫秒级(生产为 1s),返回还原函数。
func speedUpRetryBackoff(t *testing.T) func() {
t.Helper()
prev := nodeRetryBackoffUnit
nodeRetryBackoffUnit = time.Millisecond
return func() { nodeRetryBackoffUnit = prev }
}
// buildServiceEngine 构造一条仅含 serviceTask 节点的引擎。
func buildServiceEngine(t *testing.T, chainID, configJSON string) types.RuleEngine {
t.Helper()
def := `{
"ruleChain": {"id": "` + chainID + `", "name": "main", "root": true},
"metadata": {
"firstNodeIndex": 0,
"nodes": [{"id": "s", "type": "serviceTask", "name": "服务", "configuration": ` + configJSON + `}],
"connections": []
}
}`
_ = rulego.Registry.Register(&ServiceTaskNode{}) // 幂等
engine, err := rulego.New(chainID, []byte(def), rulego.WithConfig(rulego.NewConfig()))
require.NoError(t, err)
return engine
}
// retryCountFromConfig 边界:缺省、显式 0、负数裁剪、超上限裁剪、float64/int 兼容、
// 非法类型回缺省。
func TestRetryCountFromConfig(t *testing.T) {
cases := []struct {
name string
raw any
def int
want int
}{
{"absent uses default", nil, 3, 3},
{"explicit zero disables", float64(0), 3, 0},
{"negative clipped to zero", float64(-2), 3, 0},
{"over max clipped", float64(9), 3, 5},
{"max boundary kept", float64(5), 3, 5},
{"int injection", 2, 3, 2},
{"invalid type falls back", "3", 3, 3},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
cfg := types.Configuration{}
if c.raw != nil {
cfg["retryCount"] = c.raw
}
assert.Equal(t, c.want, retryCountFromConfig(cfg, c.def))
})
}
}
// http5xxPattern 识别面:http 前缀锚定的 5xx 文本;裸数字与非 5xx 状态码不误判。
func TestHttp5xxPattern(t *testing.T) {
transient := []string{"http 500: boom", "http 502 bad gateway", "上游 http503"}
for _, s := range transient {
assert.True(t, http5xxPattern.MatchString(strings.ToLower(s)), s)
}
notTransient := []string{"http 400: bad request", "http 404: not found", "金额500元", " http50"}
for _, s := range notTransient {
assert.False(t, http5xxPattern.MatchString(strings.ToLower(s)), s)
}
}
// ---- httpCall 瞬时故障自动重试 ----
// 前 2 次返 500、第 3 次返 200:节点最终 Success、总请求=3、三次带同一 Idempotency-Key。
func TestHttpCall_RetryTransient5xxThenSuccess(t *testing.T) {
registerHttpCallForTest(t)
defer speedUpRetryBackoff(t)()
var mu sync.Mutex
var count int
var keys []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
keys = append(keys, r.Header.Get("Idempotency-Key"))
n := count
mu.Unlock()
if n <= 2 {
w.WriteHeader(http.StatusInternalServerError)
return
}
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer srv.Close()
cfg := `{"url":"` + srv.URL + `","method":"GET","retryCount":3}`
engine := buildHttpEngine(t, "t_http_retry_ok", cfg)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.NoError(t, err)
assert.Equal(t, types.Success, rel)
assert.Equal(t, 3, count, "两次 500 后第三次应成功")
require.Len(t, keys, 3)
assert.NotEmpty(t, keys[0], "必须携带 Idempotency-Key")
assert.Equal(t, keys[0], keys[1], "重试必须复用同一 Idempotency-Key")
assert.Equal(t, keys[1], keys[2], "重试必须复用同一 Idempotency-Key")
}
// 恒返 400:业务失败重试无意义,总请求=1,直接 Failure。
func TestHttpCall_RetryNeverFor4xx(t *testing.T) {
registerHttpCallForTest(t)
defer speedUpRetryBackoff(t)()
var count int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&count, 1)
w.WriteHeader(http.StatusBadRequest)
}))
defer srv.Close()
cfg := `{"url":"` + srv.URL + `","method":"GET","retryCount":3}`
engine := buildHttpEngine(t, "t_http_retry_4xx", cfg)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.Error(t, err)
assert.Equal(t, types.Failure, rel)
assert.Equal(t, int32(1), atomic.LoadInt32(&count), "4xx 不得重试")
}
// 恒返 500 且 retryCount=2:预算耗尽走 Failure,错误串带「重试 2 次后失败」,总请求=3。
func TestHttpCall_RetryExhaustedReportsCount(t *testing.T) {
registerHttpCallForTest(t)
defer speedUpRetryBackoff(t)()
var count int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&count, 1)
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
cfg := `{"url":"` + srv.URL + `","method":"GET","retryCount":2}`
engine := buildHttpEngine(t, "t_http_retry_exhaust", cfg)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.Error(t, err)
assert.Equal(t, types.Failure, rel)
assert.Equal(t, int32(3), atomic.LoadInt32(&count), "首试+2 次重试=3 次请求")
assert.Contains(t, err.Error(), "重试 2 次后失败")
}
// retryCount=0 显式关闭:恒 500 只打一次。
func TestHttpCall_RetryDisabledWhenZero(t *testing.T) {
registerHttpCallForTest(t)
defer speedUpRetryBackoff(t)()
var count int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&count, 1)
w.WriteHeader(http.StatusServiceUnavailable)
}))
defer srv.Close()
cfg := `{"url":"` + srv.URL + `","method":"GET","retryCount":0}`
engine := buildHttpEngine(t, "t_http_retry_off", cfg)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.Error(t, err)
assert.Equal(t, types.Failure, rel)
assert.Equal(t, int32(1), atomic.LoadInt32(&count), "retryCount=0 必须关闭重试")
}
// 连接拒绝(服务没起):瞬时技术故障,预算内重试。
func TestHttpCall_RetryOnConnectionRefused(t *testing.T) {
registerHttpCallForTest(t)
defer speedUpRetryBackoff(t)()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {}))
u := srv.URL
srv.Close() // 先拿到端口再关掉,制造连接拒绝
cfg := `{"url":"` + u + `","method":"GET","retryCount":1}`
engine := buildHttpEngine(t, "t_http_retry_refused", cfg)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.Error(t, err)
assert.Equal(t, types.Failure, rel)
assert.Contains(t, err.Error(), "重试 1 次后失败")
}
// ---- serviceTask 瞬时故障自动重试 ----
// 前 2 次报瞬时故障、第 3 次成功:节点最终 Success、函数共执行 3 次。
func TestServiceTask_RetryTransientThenSuccess(t *testing.T) {
defer speedUpRetryBackoff(t)()
const fn = "test:svc:retry:flaky"
action.Functions.UnRegister(fn)
defer action.Functions.UnRegister(fn)
var calls int32
action.Functions.Register(fn, func(ctx types.RuleContext, msg types.RuleMsg) {
if atomic.AddInt32(&calls, 1) <= 2 {
ctx.TellFailure(msg, errors.New("dial tcp 10.0.0.9:8080: connection refused"))
return
}
ctx.TellSuccess(msg)
})
engine := buildServiceEngine(t, "t_svc_retry_ok",
`{"functionName":"`+fn+`","retryCount":2}`)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.NoError(t, err)
assert.Equal(t, types.Success, rel)
assert.Equal(t, int32(3), atomic.LoadInt32(&calls), "两次瞬时失败后第三次应成功")
}
// 业务错误(非瞬时)不重试:函数只执行 1 次,直接 Failure。
func TestServiceTask_NoRetryForBusinessError(t *testing.T) {
defer speedUpRetryBackoff(t)()
const fn = "test:svc:retry:business"
action.Functions.UnRegister(fn)
defer action.Functions.UnRegister(fn)
var calls int32
action.Functions.Register(fn, func(ctx types.RuleContext, msg types.RuleMsg) {
atomic.AddInt32(&calls, 1)
ctx.TellFailure(msg, errors.New("参数校验失败:金额必须大于 0"))
})
engine := buildServiceEngine(t, "t_svc_retry_biz",
`{"functionName":"`+fn+`","retryCount":2}`)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.Error(t, err)
assert.Equal(t, types.Failure, rel)
assert.Equal(t, int32(1), atomic.LoadInt32(&calls), "业务失败不得重试")
}
// 预算耗尽:错误串带「重试 N 次后失败」。
func TestServiceTask_RetryExhaustedReportsCount(t *testing.T) {
defer speedUpRetryBackoff(t)()
const fn = "test:svc:retry:exhaust"
action.Functions.UnRegister(fn)
defer action.Functions.UnRegister(fn)
var calls int32
action.Functions.Register(fn, func(ctx types.RuleContext, msg types.RuleMsg) {
atomic.AddInt32(&calls, 1)
ctx.TellFailure(msg, errors.New("read timeout"))
})
engine := buildServiceEngine(t, "t_svc_retry_exhaust",
`{"functionName":"`+fn+`","retryCount":2}`)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.Error(t, err)
assert.Equal(t, types.Failure, rel)
assert.Equal(t, int32(3), atomic.LoadInt32(&calls), "首试+2 次重试=3 次执行")
assert.Contains(t, err.Error(), "重试 2 次后失败")
}
// ---- 408/429 瞬时分类 ----
// 408 请求超时与 429 限流同属瞬时过载:预算内重试,第 3 次成功。
func TestHttpCall_RetryOn408And429(t *testing.T) {
for _, code := range []int{http.StatusRequestTimeout, http.StatusTooManyRequests} {
t.Run(http.StatusText(code), func(t *testing.T) {
registerHttpCallForTest(t)
defer speedUpRetryBackoff(t)()
var mu sync.Mutex
var count int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
count++
n := count
mu.Unlock()
if n <= 2 {
w.WriteHeader(code)
return
}
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer srv.Close()
cfg := `{"url":"` + srv.URL + `","method":"GET","retryCount":3}`
// 链 ID 必须随子测试唯一:rulego.New 同 ID 复用旧链(旧 server 已关,必炸)
engine := buildHttpEngine(t, "t_http_retry_code_"+strconv.Itoa(code), cfg)
_, rel, err := runChain(t, engine, types.NewMsgWithJsonData(`{}`))
require.NoError(t, err)
assert.Equal(t, types.Success, rel)
mu.Lock()
defer mu.Unlock()
assert.Equal(t, 3, count, "两次 %d 后第三次应成功", code)
})
}
}
// ---- 实例终态哨兵 ----
// 哨兵命中(实例已被并发终止):httpCall 首次瞬时失败后立即中止,不再发请求。
func TestRetryAbortHook_StopsHttpCallRetry(t *testing.T) {
registerHttpCallForTest(t)
defer speedUpRetryBackoff(t)()
var count int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&count, 1)
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
prev := RetryAbortHook
RetryAbortHook = func(msg types.RuleMsg) bool {
return msg.Metadata.GetValue(constants.KeyInstanceID) == "inst-gone"
}
defer func() { RetryAbortHook = prev }()
cfg := `{"url":"` + srv.URL + `","method":"GET","retryCount":3}`
engine := buildHttpEngine(t, "t_http_retry_abort", cfg)
msg := types.NewMsgWithJsonData(`{}`)
msg.Metadata.PutValue(constants.KeyInstanceID, "inst-gone")
_, rel, err := runChain(t, engine, msg)
require.Error(t, err)
assert.Equal(t, types.Failure, rel)
assert.Equal(t, int32(1), atomic.LoadInt32(&count), "哨兵命中:不得对终态实例继续重试")
assert.Contains(t, err.Error(), "中止重试")
}
// 哨兵放行(实例仍可执行):重试照常,两次 500 后第三次成功。
func TestRetryAbortHook_AllowsLiveInstance(t *testing.T) {
registerHttpCallForTest(t)
defer speedUpRetryBackoff(t)()
var mu sync.Mutex
var count int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
count++
n := count
mu.Unlock()
if n <= 2 {
w.WriteHeader(http.StatusInternalServerError)
return
}
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer srv.Close()
prev := RetryAbortHook
RetryAbortHook = func(msg types.RuleMsg) bool {
return msg.Metadata.GetValue(constants.KeyInstanceID) == "inst-gone"
}
defer func() { RetryAbortHook = prev }()
cfg := `{"url":"` + srv.URL + `","method":"GET","retryCount":3}`
engine := buildHttpEngine(t, "t_http_retry_live", cfg)
msg := types.NewMsgWithJsonData(`{}`)
msg.Metadata.PutValue(constants.KeyInstanceID, "inst-live")
_, rel, err := runChain(t, engine, msg)
require.NoError(t, err)
assert.Equal(t, types.Success, rel)
mu.Lock()
defer mu.Unlock()
assert.Equal(t, 3, count, "哨兵放行:重试语义不变")
}
// 哨兵命中(实例已被并发终止):serviceTask 首次瞬时失败后立即中止,不再重跑副作用。
func TestRetryAbortHook_StopsServiceTaskRetry(t *testing.T) {
defer speedUpRetryBackoff(t)()
const fn = "test:svc:retry:abort"
action.Functions.UnRegister(fn)
defer action.Functions.UnRegister(fn)
var calls int32
action.Functions.Register(fn, func(ctx types.RuleContext, msg types.RuleMsg) {
atomic.AddInt32(&calls, 1)
ctx.TellFailure(msg, errors.New("dial tcp 10.0.0.9:8080: connection refused"))
})
prev := RetryAbortHook
RetryAbortHook = func(msg types.RuleMsg) bool {
return msg.Metadata.GetValue(constants.KeyInstanceID) == "inst-gone"
}
defer func() { RetryAbortHook = prev }()
engine := buildServiceEngine(t, "t_svc_retry_abort",
`{"functionName":"`+fn+`","retryCount":2}`)
msg := types.NewMsgWithJsonData(`{}`)
msg.Metadata.PutValue(constants.KeyInstanceID, "inst-gone")
_, rel, err := runChain(t, engine, msg)
require.Error(t, err)
assert.Equal(t, types.Failure, rel)
assert.Equal(t, int32(1), atomic.LoadInt32(&calls), "哨兵命中:不得对终态实例继续重跑")
assert.Contains(t, err.Error(), "中止重试")
}
+27
View File
@@ -6,10 +6,12 @@ import (
"reflect"
"strings"
"sync"
"time"
"context"
"github.com/rulego/gflow-engine/service"
"github.com/rulego/gflow-engine/types/constants"
"github.com/rulego/gflow-engine/types/enums"
"github.com/rulego/rulego"
"github.com/rulego/rulego/api/types"
@@ -85,6 +87,31 @@ func Register(deps ComponentDeps) error {
// 注入全局附件解析器(AIAgentNode 多模态输入引用;nil 合法)
SetAttachmentResolver(deps.AttachmentResolver)
// 注入实例终态哨兵(httpCall/serviceTask 重试引用):重试在节点 OnMsg 内同步
// 进行,感知不到实例被并发终止/完成;每轮退避前经运行时服务查一次运行态,
// 命中终态立即中止,不对已终态实例继续重试副作用。查询失败/实现未提供该
// 能力(测试替身)视为可执行(放行),退化为仅按重试预算兜底。
// 窄接口断言而非大接口直调:替身嵌入 RuntimeServiceInternal 但未实现
// IsInstanceExecutable,直调会在运行期 panic。
type instanceExecutableChecker interface {
IsInstanceExecutable(ctx context.Context, instanceID string) (bool, error)
}
if checker, ok := runtimeService.(instanceExecutableChecker); ok {
RetryAbortHook = func(msg types.RuleMsg) bool {
instanceID := msg.Metadata.GetValue(constants.KeyInstanceID)
if instanceID == "" {
return false
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
exec, err := checker.IsInstanceExecutable(ctx, instanceID)
if err != nil {
return false // 查询失败放行:不因 DB 抖动误杀正常重试
}
return !exec
}
}
// 注入 serviceTask 函数名校验器:注册表(components.Services)在本包,
// service 层部署期校验经回调取用,避免 service→components 循环依赖。
service.SetServiceFunctionChecker(func(name string) bool {
+27 -3
View File
@@ -35,6 +35,9 @@ const ServiceTaskNodeType = constants.NodeTypeServiceTask
// (与 userTask/ccTask/aiAgent 一致),便于测试替换与依赖装配。
type ServiceTaskNode struct {
action.FunctionsNode
// retryCount 瞬时故障自动重试预算:Init 从 configuration 提取
// (缺省 2、显式 0=关闭、上限 5);函数注册方须自证幂等(无幂等键机制)
retryCount int
}
// Type 返回组件类型,与设计器 NODE_TYPES.SERVICE_TASK 对齐
@@ -51,9 +54,30 @@ func (s *ServiceTaskNode) New() types.Node {
return &ServiceTaskNode{}
}
// OnMsg 包装上游 FunctionsNode.OnMsg,补充 panic 兜底:
// 宿主注册的服务函数 panic 不能击穿引擎所在进程(rulego 引擎侧不 recover)。
// Init 初始化:沿用上游配置解析,另提取 retryCount(FunctionsNodeConfiguration
// 无此字段,map 直读)。
func (s *ServiceTaskNode) Init(ruleConfig types.Config, configuration types.Configuration) error {
if err := s.FunctionsNode.Init(ruleConfig, configuration); err != nil {
return err
}
s.retryCount = retryCountFromConfig(configuration, constants.ServiceTaskDefaultRetryCount)
return nil
}
// OnMsg 包装上游 FunctionsNode.OnMsg:
// - panic 兜底:宿主注册的服务函数 panic 不能击穿引擎所在进程(rulego 引擎侧不 recover)
// - 瞬时故障自动重试:包装 RuleContext 拦截 TellFailure,瞬时技术故障(超时/
// 连接拒绝/5xx)在预算内退避重试,业务失败直接终态;retryCount=0 走原路径
func (s *ServiceTaskNode) OnMsg(ctx types.RuleContext, msg types.RuleMsg) {
defer recoverNodePanic(ctx, msg, ServiceTaskNodeType, ctx.GetSelfId())
s.FunctionsNode.OnMsg(ctx, msg)
if s.retryCount <= 0 {
s.FunctionsNode.OnMsg(ctx, msg)
return
}
st := &serviceRetryState{max: s.retryCount, real: ctx}
st.invoke = func() {
// 每次重试包一层新 wrapper(共享 st 的计数),TellSuccess 原样透传真实下游
s.FunctionsNode.OnMsg(&retryServiceContext{RuleContext: ctx, st: st}, msg)
}
st.invoke()
}
+24
View File
@@ -91,6 +91,30 @@ func NewRuntimeServiceWithQuery(query *query.Query, workflowEngine WorkflowEngin
return s
}
// IsInstanceExecutable 判断实例是否处于可执行状态:运行表在且状态为
// active/suspended/draft。挂起可恢复仍算可执行——节点重试终态哨兵据此区分
// 「已终态不必再重试」与「挂起等恢复」;查无运行行=已终态归档,返回 false,nil。
func (s *RuntimeServiceImpl) IsInstanceExecutable(ctx context.Context, instanceID string) (bool, error) {
if instanceID == "" {
return false, fmt.Errorf("instanceID cannot be empty")
}
inst, err := s.instanceDAO.Get(ctx, instanceID)
if err != nil {
return false, err
}
if inst == nil {
return false, nil
}
switch inst.Status {
case string(enums.InstanceStatusActive),
string(enums.InstanceStatusSuspended),
string(enums.InstanceStatusDraft):
return true, nil
default:
return false, nil
}
}
// StartProcessInstanceByKey 根据流程定义Key启动流程实例
func (s *RuntimeServiceImpl) StartProcessInstanceByKey(ctx context.Context, actor Actor, processDefinitionKey, businessKey string, variables map[string]interface{}, opts ...StartOption) (string, error) {
ctx = bindActor(ctx, actor)
+5
View File
@@ -52,4 +52,9 @@ type RuntimeServiceInternal interface {
// processInstanceID - 流程实例ID, startNodeId - 续跑起点节点ID,
// variables - 本次下传变量(空时回退到实例存储的启动变量)
ExecuteNext(ctx context.Context, processInstanceID, startNodeId string, variables map[string]interface{}) error
// IsInstanceExecutable 判断实例是否处于可执行状态:运行表在且状态为
// active/suspended/draft。挂起可恢复仍算可执行(节点重试哨兵据此区分「已终态
// 不必再重试」与「挂起等恢复」);查无运行行=已终态归档,返回 false,nil。
IsInstanceExecutable(ctx context.Context, instanceID string) (bool, error)
}
+3
View File
@@ -55,6 +55,9 @@ func (d *recallInternalDouble) EvictStaleChain(context.Context, string, string)
func (d *recallInternalDouble) ResolveSubProcessTarget(string, string) (string, bool) {
return "", false
}
func (d *recallInternalDouble) IsInstanceExecutable(context.Context, string) (bool, error) {
return true, nil
}
func (d *recallInternalDouble) StartSubProcessInstance(context.Context, string, string, string, map[string]interface{}) (string, error) {
return "", nil
}
+12
View File
@@ -128,6 +128,18 @@ const (
VarsChildEndReason = "_childEndReason"
)
// 节点瞬时故障自动重试(httpCall/serviceTask)预算口径:
// 只重试连接超时/读超时/连接拒绝/连接重置/断管/5xx,4xx 业务失败与解析失败
// 不重试;退避 1s/4s/16s 指数封顶;预算耗尽才走 Failure 边。
const (
// NodeRetryMax retryCount 配置上限,超出按此裁剪
NodeRetryMax = 5
// HttpCallDefaultRetryCount httpCall 未配置 retryCount 时的缺省重试次数
HttpCallDefaultRetryCount = 3
// ServiceTaskDefaultRetryCount serviceTask 未配置 retryCount 时的缺省重试次数
ServiceTaskDefaultRetryCount = 2
)
// MaxRecallCountPerInstance 单实例累计收回次数上限
const MaxRecallCountPerInstance = 20
const (