override.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. package common
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/types"
  11. "github.com/samber/lo"
  12. "github.com/tidwall/gjson"
  13. "github.com/tidwall/sjson"
  14. )
  15. var negativeIndexRegexp = regexp.MustCompile(`\.(-\d+)`)
  16. const (
  17. paramOverrideContextRequestHeaders = "request_headers"
  18. paramOverrideContextRequestHeadersRaw = "request_headers_raw"
  19. paramOverrideContextHeaderOverride = "header_override"
  20. paramOverrideContextHeaderOverrideNormalized = "header_override_normalized"
  21. )
  22. type ConditionOperation struct {
  23. Path string `json:"path"` // JSON路径
  24. Mode string `json:"mode"` // full, prefix, suffix, contains, gt, gte, lt, lte
  25. Value interface{} `json:"value"` // 匹配的值
  26. Invert bool `json:"invert"` // 反选功能,true表示取反结果
  27. PassMissingKey bool `json:"pass_missing_key"` // 未获取到json key时的行为
  28. }
  29. type ParamOperation struct {
  30. Path string `json:"path"`
  31. Mode string `json:"mode"` // delete, set, move, copy, prepend, append, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, regex_replace, return_error, prune_objects, set_header, delete_header, copy_header, move_header, pass_headers, sync_fields
  32. Value interface{} `json:"value"`
  33. KeepOrigin bool `json:"keep_origin"`
  34. From string `json:"from,omitempty"`
  35. To string `json:"to,omitempty"`
  36. Conditions []ConditionOperation `json:"conditions,omitempty"` // 条件列表
  37. Logic string `json:"logic,omitempty"` // AND, OR (默认OR)
  38. }
  39. type ParamOverrideReturnError struct {
  40. Message string
  41. StatusCode int
  42. Code string
  43. Type string
  44. SkipRetry bool
  45. }
  46. func (e *ParamOverrideReturnError) Error() string {
  47. if e == nil {
  48. return "param override return error"
  49. }
  50. if e.Message == "" {
  51. return "param override return error"
  52. }
  53. return e.Message
  54. }
  55. func AsParamOverrideReturnError(err error) (*ParamOverrideReturnError, bool) {
  56. if err == nil {
  57. return nil, false
  58. }
  59. var target *ParamOverrideReturnError
  60. if errors.As(err, &target) {
  61. return target, true
  62. }
  63. return nil, false
  64. }
  65. func NewAPIErrorFromParamOverride(err *ParamOverrideReturnError) *types.NewAPIError {
  66. if err == nil {
  67. return types.NewError(
  68. errors.New("param override return error is nil"),
  69. types.ErrorCodeChannelParamOverrideInvalid,
  70. types.ErrOptionWithSkipRetry(),
  71. )
  72. }
  73. statusCode := err.StatusCode
  74. if statusCode < http.StatusContinue || statusCode > http.StatusNetworkAuthenticationRequired {
  75. statusCode = http.StatusBadRequest
  76. }
  77. errorCode := err.Code
  78. if strings.TrimSpace(errorCode) == "" {
  79. errorCode = string(types.ErrorCodeInvalidRequest)
  80. }
  81. errorType := err.Type
  82. if strings.TrimSpace(errorType) == "" {
  83. errorType = "invalid_request_error"
  84. }
  85. message := strings.TrimSpace(err.Message)
  86. if message == "" {
  87. message = "request blocked by param override"
  88. }
  89. opts := make([]types.NewAPIErrorOptions, 0, 1)
  90. if err.SkipRetry {
  91. opts = append(opts, types.ErrOptionWithSkipRetry())
  92. }
  93. return types.WithOpenAIError(types.OpenAIError{
  94. Message: message,
  95. Type: errorType,
  96. Code: errorCode,
  97. }, statusCode, opts...)
  98. }
  99. func ApplyParamOverride(jsonData []byte, paramOverride map[string]interface{}, conditionContext map[string]interface{}) ([]byte, error) {
  100. if len(paramOverride) == 0 {
  101. return jsonData, nil
  102. }
  103. // 尝试断言为操作格式
  104. if operations, ok := tryParseOperations(paramOverride); ok {
  105. // 使用新方法
  106. result, err := applyOperations(string(jsonData), operations, conditionContext)
  107. return []byte(result), err
  108. }
  109. // 直接使用旧方法
  110. return applyOperationsLegacy(jsonData, paramOverride)
  111. }
  112. func ApplyParamOverrideWithRelayInfo(jsonData []byte, info *RelayInfo) ([]byte, error) {
  113. paramOverride := getParamOverrideMap(info)
  114. if len(paramOverride) == 0 {
  115. return jsonData, nil
  116. }
  117. overrideCtx := BuildParamOverrideContext(info)
  118. result, err := ApplyParamOverride(jsonData, paramOverride, overrideCtx)
  119. if err != nil {
  120. return nil, err
  121. }
  122. syncRuntimeHeaderOverrideFromContext(info, overrideCtx)
  123. return result, nil
  124. }
  125. func getParamOverrideMap(info *RelayInfo) map[string]interface{} {
  126. if info == nil || info.ChannelMeta == nil {
  127. return nil
  128. }
  129. return info.ChannelMeta.ParamOverride
  130. }
  131. func getHeaderOverrideMap(info *RelayInfo) map[string]interface{} {
  132. if info == nil || info.ChannelMeta == nil {
  133. return nil
  134. }
  135. return info.ChannelMeta.HeadersOverride
  136. }
  137. func tryParseOperations(paramOverride map[string]interface{}) ([]ParamOperation, bool) {
  138. // 检查是否包含 "operations" 字段
  139. if opsValue, exists := paramOverride["operations"]; exists {
  140. if opsSlice, ok := opsValue.([]interface{}); ok {
  141. var operations []ParamOperation
  142. for _, op := range opsSlice {
  143. if opMap, ok := op.(map[string]interface{}); ok {
  144. operation := ParamOperation{}
  145. // 断言必要字段
  146. if path, ok := opMap["path"].(string); ok {
  147. operation.Path = path
  148. }
  149. if mode, ok := opMap["mode"].(string); ok {
  150. operation.Mode = mode
  151. } else {
  152. return nil, false // mode 是必需的
  153. }
  154. // 可选字段
  155. if value, exists := opMap["value"]; exists {
  156. operation.Value = value
  157. }
  158. if keepOrigin, ok := opMap["keep_origin"].(bool); ok {
  159. operation.KeepOrigin = keepOrigin
  160. }
  161. if from, ok := opMap["from"].(string); ok {
  162. operation.From = from
  163. }
  164. if to, ok := opMap["to"].(string); ok {
  165. operation.To = to
  166. }
  167. if logic, ok := opMap["logic"].(string); ok {
  168. operation.Logic = logic
  169. } else {
  170. operation.Logic = "OR" // 默认为OR
  171. }
  172. // 解析条件
  173. if conditions, exists := opMap["conditions"]; exists {
  174. parsedConditions, err := parseConditionOperations(conditions)
  175. if err != nil {
  176. return nil, false
  177. }
  178. operation.Conditions = append(operation.Conditions, parsedConditions...)
  179. }
  180. operations = append(operations, operation)
  181. } else {
  182. return nil, false
  183. }
  184. }
  185. return operations, true
  186. }
  187. }
  188. return nil, false
  189. }
  190. func checkConditions(jsonStr, contextJSON string, conditions []ConditionOperation, logic string) (bool, error) {
  191. if len(conditions) == 0 {
  192. return true, nil // 没有条件,直接通过
  193. }
  194. results := make([]bool, len(conditions))
  195. for i, condition := range conditions {
  196. result, err := checkSingleCondition(jsonStr, contextJSON, condition)
  197. if err != nil {
  198. return false, err
  199. }
  200. results[i] = result
  201. }
  202. if strings.ToUpper(logic) == "AND" {
  203. return lo.EveryBy(results, func(item bool) bool { return item }), nil
  204. }
  205. return lo.SomeBy(results, func(item bool) bool { return item }), nil
  206. }
  207. func checkSingleCondition(jsonStr, contextJSON string, condition ConditionOperation) (bool, error) {
  208. // 处理负数索引
  209. path := processNegativeIndex(jsonStr, condition.Path)
  210. value := gjson.Get(jsonStr, path)
  211. if !value.Exists() && contextJSON != "" {
  212. value = gjson.Get(contextJSON, condition.Path)
  213. }
  214. if !value.Exists() {
  215. if condition.PassMissingKey {
  216. return true, nil
  217. }
  218. return false, nil
  219. }
  220. // 利用gjson的类型解析
  221. targetBytes, err := common.Marshal(condition.Value)
  222. if err != nil {
  223. return false, fmt.Errorf("failed to marshal condition value: %v", err)
  224. }
  225. targetValue := gjson.ParseBytes(targetBytes)
  226. result, err := compareGjsonValues(value, targetValue, strings.ToLower(condition.Mode))
  227. if err != nil {
  228. return false, fmt.Errorf("comparison failed for path %s: %v", condition.Path, err)
  229. }
  230. if condition.Invert {
  231. result = !result
  232. }
  233. return result, nil
  234. }
  235. func processNegativeIndex(jsonStr string, path string) string {
  236. matches := negativeIndexRegexp.FindAllStringSubmatch(path, -1)
  237. if len(matches) == 0 {
  238. return path
  239. }
  240. result := path
  241. for _, match := range matches {
  242. negIndex := match[1]
  243. index, _ := strconv.Atoi(negIndex)
  244. arrayPath := strings.Split(path, negIndex)[0]
  245. if strings.HasSuffix(arrayPath, ".") {
  246. arrayPath = arrayPath[:len(arrayPath)-1]
  247. }
  248. array := gjson.Get(jsonStr, arrayPath)
  249. if array.IsArray() {
  250. length := len(array.Array())
  251. actualIndex := length + index
  252. if actualIndex >= 0 && actualIndex < length {
  253. result = strings.Replace(result, match[0], "."+strconv.Itoa(actualIndex), 1)
  254. }
  255. }
  256. }
  257. return result
  258. }
  259. // compareGjsonValues 直接比较两个gjson.Result,支持所有比较模式
  260. func compareGjsonValues(jsonValue, targetValue gjson.Result, mode string) (bool, error) {
  261. switch mode {
  262. case "full":
  263. return compareEqual(jsonValue, targetValue)
  264. case "prefix":
  265. return strings.HasPrefix(jsonValue.String(), targetValue.String()), nil
  266. case "suffix":
  267. return strings.HasSuffix(jsonValue.String(), targetValue.String()), nil
  268. case "contains":
  269. return strings.Contains(jsonValue.String(), targetValue.String()), nil
  270. case "gt":
  271. return compareNumeric(jsonValue, targetValue, "gt")
  272. case "gte":
  273. return compareNumeric(jsonValue, targetValue, "gte")
  274. case "lt":
  275. return compareNumeric(jsonValue, targetValue, "lt")
  276. case "lte":
  277. return compareNumeric(jsonValue, targetValue, "lte")
  278. default:
  279. return false, fmt.Errorf("unsupported comparison mode: %s", mode)
  280. }
  281. }
  282. func compareEqual(jsonValue, targetValue gjson.Result) (bool, error) {
  283. // 对null值特殊处理:两个都是null返回true,一个是null另一个不是返回false
  284. if jsonValue.Type == gjson.Null || targetValue.Type == gjson.Null {
  285. return jsonValue.Type == gjson.Null && targetValue.Type == gjson.Null, nil
  286. }
  287. // 对布尔值特殊处理
  288. if (jsonValue.Type == gjson.True || jsonValue.Type == gjson.False) &&
  289. (targetValue.Type == gjson.True || targetValue.Type == gjson.False) {
  290. return jsonValue.Bool() == targetValue.Bool(), nil
  291. }
  292. // 如果类型不同,报错
  293. if jsonValue.Type != targetValue.Type {
  294. return false, fmt.Errorf("compare for different types, got %v and %v", jsonValue.Type, targetValue.Type)
  295. }
  296. switch jsonValue.Type {
  297. case gjson.True, gjson.False:
  298. return jsonValue.Bool() == targetValue.Bool(), nil
  299. case gjson.Number:
  300. return jsonValue.Num == targetValue.Num, nil
  301. case gjson.String:
  302. return jsonValue.String() == targetValue.String(), nil
  303. default:
  304. return jsonValue.String() == targetValue.String(), nil
  305. }
  306. }
  307. func compareNumeric(jsonValue, targetValue gjson.Result, operator string) (bool, error) {
  308. // 只有数字类型才支持数值比较
  309. if jsonValue.Type != gjson.Number || targetValue.Type != gjson.Number {
  310. return false, fmt.Errorf("numeric comparison requires both values to be numbers, got %v and %v", jsonValue.Type, targetValue.Type)
  311. }
  312. jsonNum := jsonValue.Num
  313. targetNum := targetValue.Num
  314. switch operator {
  315. case "gt":
  316. return jsonNum > targetNum, nil
  317. case "gte":
  318. return jsonNum >= targetNum, nil
  319. case "lt":
  320. return jsonNum < targetNum, nil
  321. case "lte":
  322. return jsonNum <= targetNum, nil
  323. default:
  324. return false, fmt.Errorf("unsupported numeric operator: %s", operator)
  325. }
  326. }
  327. // applyOperationsLegacy 原参数覆盖方法
  328. func applyOperationsLegacy(jsonData []byte, paramOverride map[string]interface{}) ([]byte, error) {
  329. reqMap := make(map[string]interface{})
  330. err := common.Unmarshal(jsonData, &reqMap)
  331. if err != nil {
  332. return nil, err
  333. }
  334. for key, value := range paramOverride {
  335. reqMap[key] = value
  336. }
  337. return common.Marshal(reqMap)
  338. }
  339. func applyOperations(jsonStr string, operations []ParamOperation, conditionContext map[string]interface{}) (string, error) {
  340. context := ensureContextMap(conditionContext)
  341. contextJSON, err := marshalContextJSON(context)
  342. if err != nil {
  343. return "", fmt.Errorf("failed to marshal condition context: %v", err)
  344. }
  345. result := jsonStr
  346. for _, op := range operations {
  347. // 检查条件是否满足
  348. ok, err := checkConditions(result, contextJSON, op.Conditions, op.Logic)
  349. if err != nil {
  350. return "", err
  351. }
  352. if !ok {
  353. continue // 条件不满足,跳过当前操作
  354. }
  355. // 处理路径中的负数索引
  356. opPath := processNegativeIndex(result, op.Path)
  357. switch op.Mode {
  358. case "delete":
  359. result, err = sjson.Delete(result, opPath)
  360. case "set":
  361. if op.KeepOrigin && gjson.Get(result, opPath).Exists() {
  362. continue
  363. }
  364. result, err = sjson.Set(result, opPath, op.Value)
  365. case "move":
  366. opFrom := processNegativeIndex(result, op.From)
  367. opTo := processNegativeIndex(result, op.To)
  368. result, err = moveValue(result, opFrom, opTo)
  369. case "copy":
  370. if op.From == "" || op.To == "" {
  371. return "", fmt.Errorf("copy from/to is required")
  372. }
  373. opFrom := processNegativeIndex(result, op.From)
  374. opTo := processNegativeIndex(result, op.To)
  375. result, err = copyValue(result, opFrom, opTo)
  376. case "prepend":
  377. result, err = modifyValue(result, opPath, op.Value, op.KeepOrigin, true)
  378. case "append":
  379. result, err = modifyValue(result, opPath, op.Value, op.KeepOrigin, false)
  380. case "trim_prefix":
  381. result, err = trimStringValue(result, opPath, op.Value, true)
  382. case "trim_suffix":
  383. result, err = trimStringValue(result, opPath, op.Value, false)
  384. case "ensure_prefix":
  385. result, err = ensureStringAffix(result, opPath, op.Value, true)
  386. case "ensure_suffix":
  387. result, err = ensureStringAffix(result, opPath, op.Value, false)
  388. case "trim_space":
  389. result, err = transformStringValue(result, opPath, strings.TrimSpace)
  390. case "to_lower":
  391. result, err = transformStringValue(result, opPath, strings.ToLower)
  392. case "to_upper":
  393. result, err = transformStringValue(result, opPath, strings.ToUpper)
  394. case "replace":
  395. result, err = replaceStringValue(result, opPath, op.From, op.To)
  396. case "regex_replace":
  397. result, err = regexReplaceStringValue(result, opPath, op.From, op.To)
  398. case "return_error":
  399. returnErr, parseErr := parseParamOverrideReturnError(op.Value)
  400. if parseErr != nil {
  401. return "", parseErr
  402. }
  403. return "", returnErr
  404. case "prune_objects":
  405. result, err = pruneObjects(result, opPath, contextJSON, op.Value)
  406. case "set_header":
  407. err = setHeaderOverrideInContext(context, op.Path, op.Value, op.KeepOrigin)
  408. if err == nil {
  409. contextJSON, err = marshalContextJSON(context)
  410. }
  411. case "delete_header":
  412. err = deleteHeaderOverrideInContext(context, op.Path)
  413. if err == nil {
  414. contextJSON, err = marshalContextJSON(context)
  415. }
  416. case "copy_header":
  417. sourceHeader := strings.TrimSpace(op.From)
  418. targetHeader := strings.TrimSpace(op.To)
  419. if sourceHeader == "" {
  420. sourceHeader = strings.TrimSpace(op.Path)
  421. }
  422. if targetHeader == "" {
  423. targetHeader = strings.TrimSpace(op.Path)
  424. }
  425. err = copyHeaderInContext(context, sourceHeader, targetHeader, op.KeepOrigin)
  426. if err == nil {
  427. contextJSON, err = marshalContextJSON(context)
  428. }
  429. case "move_header":
  430. sourceHeader := strings.TrimSpace(op.From)
  431. targetHeader := strings.TrimSpace(op.To)
  432. if sourceHeader == "" {
  433. sourceHeader = strings.TrimSpace(op.Path)
  434. }
  435. if targetHeader == "" {
  436. targetHeader = strings.TrimSpace(op.Path)
  437. }
  438. err = moveHeaderInContext(context, sourceHeader, targetHeader, op.KeepOrigin)
  439. if err == nil {
  440. contextJSON, err = marshalContextJSON(context)
  441. }
  442. case "pass_headers":
  443. headerNames, parseErr := parseHeaderPassThroughNames(op.Value)
  444. if parseErr != nil {
  445. return "", parseErr
  446. }
  447. for _, headerName := range headerNames {
  448. if err = copyHeaderInContext(context, headerName, headerName, op.KeepOrigin); err != nil {
  449. break
  450. }
  451. }
  452. if err == nil {
  453. contextJSON, err = marshalContextJSON(context)
  454. }
  455. case "sync_fields":
  456. result, err = syncFieldsBetweenTargets(result, context, op.From, op.To)
  457. if err == nil {
  458. contextJSON, err = marshalContextJSON(context)
  459. }
  460. default:
  461. return "", fmt.Errorf("unknown operation: %s", op.Mode)
  462. }
  463. if err != nil {
  464. return "", fmt.Errorf("operation %s failed: %w", op.Mode, err)
  465. }
  466. }
  467. return result, nil
  468. }
  469. func parseParamOverrideReturnError(value interface{}) (*ParamOverrideReturnError, error) {
  470. result := &ParamOverrideReturnError{
  471. StatusCode: http.StatusBadRequest,
  472. Code: string(types.ErrorCodeInvalidRequest),
  473. Type: "invalid_request_error",
  474. SkipRetry: true,
  475. }
  476. switch raw := value.(type) {
  477. case nil:
  478. return nil, fmt.Errorf("return_error value is required")
  479. case string:
  480. result.Message = strings.TrimSpace(raw)
  481. case map[string]interface{}:
  482. if message, ok := raw["message"].(string); ok {
  483. result.Message = strings.TrimSpace(message)
  484. }
  485. if result.Message == "" {
  486. if message, ok := raw["msg"].(string); ok {
  487. result.Message = strings.TrimSpace(message)
  488. }
  489. }
  490. if code, exists := raw["code"]; exists {
  491. codeStr := strings.TrimSpace(fmt.Sprintf("%v", code))
  492. if codeStr != "" {
  493. result.Code = codeStr
  494. }
  495. }
  496. if errType, ok := raw["type"].(string); ok {
  497. errType = strings.TrimSpace(errType)
  498. if errType != "" {
  499. result.Type = errType
  500. }
  501. }
  502. if skipRetry, ok := raw["skip_retry"].(bool); ok {
  503. result.SkipRetry = skipRetry
  504. }
  505. if statusCodeRaw, exists := raw["status_code"]; exists {
  506. statusCode, ok := parseOverrideInt(statusCodeRaw)
  507. if !ok {
  508. return nil, fmt.Errorf("return_error status_code must be an integer")
  509. }
  510. result.StatusCode = statusCode
  511. } else if statusRaw, exists := raw["status"]; exists {
  512. statusCode, ok := parseOverrideInt(statusRaw)
  513. if !ok {
  514. return nil, fmt.Errorf("return_error status must be an integer")
  515. }
  516. result.StatusCode = statusCode
  517. }
  518. default:
  519. return nil, fmt.Errorf("return_error value must be string or object")
  520. }
  521. if result.Message == "" {
  522. return nil, fmt.Errorf("return_error message is required")
  523. }
  524. if result.StatusCode < http.StatusContinue || result.StatusCode > http.StatusNetworkAuthenticationRequired {
  525. return nil, fmt.Errorf("return_error status code out of range: %d", result.StatusCode)
  526. }
  527. return result, nil
  528. }
  529. func parseOverrideInt(v interface{}) (int, bool) {
  530. switch value := v.(type) {
  531. case int:
  532. return value, true
  533. case float64:
  534. if value != float64(int(value)) {
  535. return 0, false
  536. }
  537. return int(value), true
  538. default:
  539. return 0, false
  540. }
  541. }
  542. func ensureContextMap(conditionContext map[string]interface{}) map[string]interface{} {
  543. if conditionContext != nil {
  544. return conditionContext
  545. }
  546. return make(map[string]interface{})
  547. }
  548. func marshalContextJSON(context map[string]interface{}) (string, error) {
  549. if context == nil || len(context) == 0 {
  550. return "", nil
  551. }
  552. ctxBytes, err := common.Marshal(context)
  553. if err != nil {
  554. return "", err
  555. }
  556. return string(ctxBytes), nil
  557. }
  558. func setHeaderOverrideInContext(context map[string]interface{}, headerName string, value interface{}, keepOrigin bool) error {
  559. headerName = strings.TrimSpace(headerName)
  560. if headerName == "" {
  561. return fmt.Errorf("header name is required")
  562. }
  563. if keepOrigin {
  564. if _, exists := getHeaderValueFromContext(context, headerName); exists {
  565. return nil
  566. }
  567. }
  568. if value == nil {
  569. return fmt.Errorf("header value is required")
  570. }
  571. headerValue := strings.TrimSpace(fmt.Sprintf("%v", value))
  572. if headerValue == "" {
  573. return fmt.Errorf("header value is required")
  574. }
  575. rawHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverride)
  576. rawHeaders[headerName] = headerValue
  577. normalizedHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverrideNormalized)
  578. normalizedHeaders[normalizeHeaderContextKey(headerName)] = headerValue
  579. return nil
  580. }
  581. func copyHeaderInContext(context map[string]interface{}, fromHeader, toHeader string, keepOrigin bool) error {
  582. fromHeader = strings.TrimSpace(fromHeader)
  583. toHeader = strings.TrimSpace(toHeader)
  584. if fromHeader == "" || toHeader == "" {
  585. return fmt.Errorf("copy_header from/to is required")
  586. }
  587. value, exists := getHeaderValueFromContext(context, fromHeader)
  588. if !exists {
  589. return fmt.Errorf("source header does not exist: %s", fromHeader)
  590. }
  591. return setHeaderOverrideInContext(context, toHeader, value, keepOrigin)
  592. }
  593. func moveHeaderInContext(context map[string]interface{}, fromHeader, toHeader string, keepOrigin bool) error {
  594. fromHeader = strings.TrimSpace(fromHeader)
  595. toHeader = strings.TrimSpace(toHeader)
  596. if fromHeader == "" || toHeader == "" {
  597. return fmt.Errorf("move_header from/to is required")
  598. }
  599. if err := copyHeaderInContext(context, fromHeader, toHeader, keepOrigin); err != nil {
  600. return err
  601. }
  602. if strings.EqualFold(fromHeader, toHeader) {
  603. return nil
  604. }
  605. return deleteHeaderOverrideInContext(context, fromHeader)
  606. }
  607. func deleteHeaderOverrideInContext(context map[string]interface{}, headerName string) error {
  608. headerName = strings.TrimSpace(headerName)
  609. if headerName == "" {
  610. return fmt.Errorf("header name is required")
  611. }
  612. rawHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverride)
  613. for key := range rawHeaders {
  614. if strings.EqualFold(strings.TrimSpace(key), headerName) {
  615. delete(rawHeaders, key)
  616. }
  617. }
  618. normalizedHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverrideNormalized)
  619. delete(normalizedHeaders, normalizeHeaderContextKey(headerName))
  620. return nil
  621. }
  622. func parseHeaderPassThroughNames(value interface{}) ([]string, error) {
  623. normalizeNames := func(values []string) []string {
  624. names := lo.FilterMap(values, func(item string, _ int) (string, bool) {
  625. headerName := strings.TrimSpace(item)
  626. if headerName == "" {
  627. return "", false
  628. }
  629. return headerName, true
  630. })
  631. return lo.Uniq(names)
  632. }
  633. switch raw := value.(type) {
  634. case nil:
  635. return nil, fmt.Errorf("pass_headers value is required")
  636. case string:
  637. trimmed := strings.TrimSpace(raw)
  638. if trimmed == "" {
  639. return nil, fmt.Errorf("pass_headers value is required")
  640. }
  641. if strings.HasPrefix(trimmed, "[") || strings.HasPrefix(trimmed, "{") {
  642. var parsed interface{}
  643. if err := common.UnmarshalJsonStr(trimmed, &parsed); err == nil {
  644. return parseHeaderPassThroughNames(parsed)
  645. }
  646. }
  647. names := normalizeNames(strings.Split(trimmed, ","))
  648. if len(names) == 0 {
  649. return nil, fmt.Errorf("pass_headers value is invalid")
  650. }
  651. return names, nil
  652. case []interface{}:
  653. names := lo.FilterMap(raw, func(item interface{}, _ int) (string, bool) {
  654. headerName := strings.TrimSpace(fmt.Sprintf("%v", item))
  655. if headerName == "" {
  656. return "", false
  657. }
  658. return headerName, true
  659. })
  660. names = lo.Uniq(names)
  661. if len(names) == 0 {
  662. return nil, fmt.Errorf("pass_headers value is invalid")
  663. }
  664. return names, nil
  665. case map[string]interface{}:
  666. candidates := make([]string, 0, 8)
  667. if headersRaw, ok := raw["headers"]; ok {
  668. names, err := parseHeaderPassThroughNames(headersRaw)
  669. if err == nil {
  670. candidates = append(candidates, names...)
  671. }
  672. }
  673. if namesRaw, ok := raw["names"]; ok {
  674. names, err := parseHeaderPassThroughNames(namesRaw)
  675. if err == nil {
  676. candidates = append(candidates, names...)
  677. }
  678. }
  679. if headerRaw, ok := raw["header"]; ok {
  680. names, err := parseHeaderPassThroughNames(headerRaw)
  681. if err == nil {
  682. candidates = append(candidates, names...)
  683. }
  684. }
  685. names := normalizeNames(candidates)
  686. if len(names) == 0 {
  687. return nil, fmt.Errorf("pass_headers value is invalid")
  688. }
  689. return names, nil
  690. default:
  691. return nil, fmt.Errorf("pass_headers value must be string, array or object")
  692. }
  693. }
  694. type syncTarget struct {
  695. kind string
  696. key string
  697. }
  698. func parseSyncTarget(spec string) (syncTarget, error) {
  699. raw := strings.TrimSpace(spec)
  700. if raw == "" {
  701. return syncTarget{}, fmt.Errorf("sync_fields target is required")
  702. }
  703. idx := strings.Index(raw, ":")
  704. if idx < 0 {
  705. // Backward compatibility: treat bare value as JSON path.
  706. return syncTarget{
  707. kind: "json",
  708. key: raw,
  709. }, nil
  710. }
  711. kind := strings.ToLower(strings.TrimSpace(raw[:idx]))
  712. key := strings.TrimSpace(raw[idx+1:])
  713. if key == "" {
  714. return syncTarget{}, fmt.Errorf("sync_fields target key is required: %s", raw)
  715. }
  716. switch kind {
  717. case "json", "body":
  718. return syncTarget{
  719. kind: "json",
  720. key: key,
  721. }, nil
  722. case "header":
  723. return syncTarget{
  724. kind: "header",
  725. key: key,
  726. }, nil
  727. default:
  728. return syncTarget{}, fmt.Errorf("sync_fields target prefix is invalid: %s", raw)
  729. }
  730. }
  731. func readSyncTargetValue(jsonStr string, context map[string]interface{}, target syncTarget) (interface{}, bool, error) {
  732. switch target.kind {
  733. case "json":
  734. path := processNegativeIndex(jsonStr, target.key)
  735. value := gjson.Get(jsonStr, path)
  736. if !value.Exists() || value.Type == gjson.Null {
  737. return nil, false, nil
  738. }
  739. if value.Type == gjson.String && strings.TrimSpace(value.String()) == "" {
  740. return nil, false, nil
  741. }
  742. return value.Value(), true, nil
  743. case "header":
  744. value, ok := getHeaderValueFromContext(context, target.key)
  745. if !ok || strings.TrimSpace(value) == "" {
  746. return nil, false, nil
  747. }
  748. return value, true, nil
  749. default:
  750. return nil, false, fmt.Errorf("unsupported sync_fields target kind: %s", target.kind)
  751. }
  752. }
  753. func writeSyncTargetValue(jsonStr string, context map[string]interface{}, target syncTarget, value interface{}) (string, error) {
  754. switch target.kind {
  755. case "json":
  756. path := processNegativeIndex(jsonStr, target.key)
  757. nextJSON, err := sjson.Set(jsonStr, path, value)
  758. if err != nil {
  759. return "", err
  760. }
  761. return nextJSON, nil
  762. case "header":
  763. if err := setHeaderOverrideInContext(context, target.key, value, false); err != nil {
  764. return "", err
  765. }
  766. return jsonStr, nil
  767. default:
  768. return "", fmt.Errorf("unsupported sync_fields target kind: %s", target.kind)
  769. }
  770. }
  771. func syncFieldsBetweenTargets(jsonStr string, context map[string]interface{}, fromSpec string, toSpec string) (string, error) {
  772. fromTarget, err := parseSyncTarget(fromSpec)
  773. if err != nil {
  774. return "", err
  775. }
  776. toTarget, err := parseSyncTarget(toSpec)
  777. if err != nil {
  778. return "", err
  779. }
  780. fromValue, fromExists, err := readSyncTargetValue(jsonStr, context, fromTarget)
  781. if err != nil {
  782. return "", err
  783. }
  784. toValue, toExists, err := readSyncTargetValue(jsonStr, context, toTarget)
  785. if err != nil {
  786. return "", err
  787. }
  788. // If one side exists and the other side is missing, sync the missing side.
  789. if fromExists && !toExists {
  790. return writeSyncTargetValue(jsonStr, context, toTarget, fromValue)
  791. }
  792. if toExists && !fromExists {
  793. return writeSyncTargetValue(jsonStr, context, fromTarget, toValue)
  794. }
  795. return jsonStr, nil
  796. }
  797. func ensureMapKeyInContext(context map[string]interface{}, key string) map[string]interface{} {
  798. if context == nil {
  799. return map[string]interface{}{}
  800. }
  801. if existing, ok := context[key]; ok {
  802. if mapVal, ok := existing.(map[string]interface{}); ok {
  803. return mapVal
  804. }
  805. }
  806. result := make(map[string]interface{})
  807. context[key] = result
  808. return result
  809. }
  810. func getHeaderValueFromContext(context map[string]interface{}, headerName string) (string, bool) {
  811. headerName = strings.TrimSpace(headerName)
  812. if headerName == "" {
  813. return "", false
  814. }
  815. if value, ok := findHeaderValueInMap(ensureMapKeyInContext(context, paramOverrideContextHeaderOverride), headerName); ok {
  816. return value, true
  817. }
  818. if value, ok := findHeaderValueInMap(ensureMapKeyInContext(context, paramOverrideContextRequestHeadersRaw), headerName); ok {
  819. return value, true
  820. }
  821. normalizedName := normalizeHeaderContextKey(headerName)
  822. if normalizedName == "" {
  823. return "", false
  824. }
  825. if value, ok := findHeaderValueInMap(ensureMapKeyInContext(context, paramOverrideContextHeaderOverrideNormalized), normalizedName); ok {
  826. return value, true
  827. }
  828. if value, ok := findHeaderValueInMap(ensureMapKeyInContext(context, paramOverrideContextRequestHeaders), normalizedName); ok {
  829. return value, true
  830. }
  831. return "", false
  832. }
  833. func findHeaderValueInMap(source map[string]interface{}, key string) (string, bool) {
  834. if len(source) == 0 {
  835. return "", false
  836. }
  837. entries := lo.Entries(source)
  838. entry, ok := lo.Find(entries, func(item lo.Entry[string, interface{}]) bool {
  839. return strings.EqualFold(strings.TrimSpace(item.Key), key)
  840. })
  841. if !ok {
  842. return "", false
  843. }
  844. value := strings.TrimSpace(fmt.Sprintf("%v", entry.Value))
  845. if value == "" {
  846. return "", false
  847. }
  848. return value, true
  849. }
  850. func normalizeHeaderContextKey(key string) string {
  851. key = strings.TrimSpace(strings.ToLower(key))
  852. if key == "" {
  853. return ""
  854. }
  855. var b strings.Builder
  856. b.Grow(len(key))
  857. previousUnderscore := false
  858. for _, r := range key {
  859. switch {
  860. case r >= 'a' && r <= 'z':
  861. b.WriteRune(r)
  862. previousUnderscore = false
  863. case r >= '0' && r <= '9':
  864. b.WriteRune(r)
  865. previousUnderscore = false
  866. default:
  867. if !previousUnderscore {
  868. b.WriteByte('_')
  869. previousUnderscore = true
  870. }
  871. }
  872. }
  873. result := strings.Trim(b.String(), "_")
  874. return result
  875. }
  876. func buildNormalizedHeaders(headers map[string]string) map[string]interface{} {
  877. if len(headers) == 0 {
  878. return map[string]interface{}{}
  879. }
  880. entries := lo.Entries(headers)
  881. normalizedEntries := lo.FilterMap(entries, func(item lo.Entry[string, string], _ int) (lo.Entry[string, string], bool) {
  882. normalized := normalizeHeaderContextKey(item.Key)
  883. value := strings.TrimSpace(item.Value)
  884. if normalized == "" || value == "" {
  885. return lo.Entry[string, string]{}, false
  886. }
  887. return lo.Entry[string, string]{Key: normalized, Value: value}, true
  888. })
  889. return lo.SliceToMap(normalizedEntries, func(item lo.Entry[string, string]) (string, interface{}) {
  890. return item.Key, item.Value
  891. })
  892. }
  893. func buildRawHeaders(headers map[string]string) map[string]interface{} {
  894. if len(headers) == 0 {
  895. return map[string]interface{}{}
  896. }
  897. entries := lo.Entries(headers)
  898. rawEntries := lo.FilterMap(entries, func(item lo.Entry[string, string], _ int) (lo.Entry[string, string], bool) {
  899. key := strings.TrimSpace(item.Key)
  900. value := strings.TrimSpace(item.Value)
  901. if key == "" || value == "" {
  902. return lo.Entry[string, string]{}, false
  903. }
  904. return lo.Entry[string, string]{Key: key, Value: value}, true
  905. })
  906. return lo.SliceToMap(rawEntries, func(item lo.Entry[string, string]) (string, interface{}) {
  907. return item.Key, item.Value
  908. })
  909. }
  910. func buildHeaderOverrideContext(headers map[string]interface{}) (map[string]interface{}, map[string]interface{}) {
  911. if len(headers) == 0 {
  912. return map[string]interface{}{}, map[string]interface{}{}
  913. }
  914. entries := lo.Entries(headers)
  915. rawEntries := lo.FilterMap(entries, func(item lo.Entry[string, interface{}], _ int) (lo.Entry[string, string], bool) {
  916. key := strings.TrimSpace(item.Key)
  917. value := strings.TrimSpace(fmt.Sprintf("%v", item.Value))
  918. if key == "" || value == "" {
  919. return lo.Entry[string, string]{}, false
  920. }
  921. return lo.Entry[string, string]{Key: key, Value: value}, true
  922. })
  923. raw := lo.SliceToMap(rawEntries, func(item lo.Entry[string, string]) (string, interface{}) {
  924. return item.Key, item.Value
  925. })
  926. normalizedEntries := lo.FilterMap(rawEntries, func(item lo.Entry[string, string], _ int) (lo.Entry[string, string], bool) {
  927. normalized := normalizeHeaderContextKey(item.Key)
  928. if normalized == "" {
  929. return lo.Entry[string, string]{}, false
  930. }
  931. return lo.Entry[string, string]{Key: normalized, Value: item.Value}, true
  932. })
  933. normalized := lo.SliceToMap(normalizedEntries, func(item lo.Entry[string, string]) (string, interface{}) {
  934. return item.Key, item.Value
  935. })
  936. return raw, normalized
  937. }
  938. func syncRuntimeHeaderOverrideFromContext(info *RelayInfo, context map[string]interface{}) {
  939. if info == nil || context == nil {
  940. return
  941. }
  942. raw, exists := context[paramOverrideContextHeaderOverride]
  943. if !exists {
  944. return
  945. }
  946. rawMap, ok := raw.(map[string]interface{})
  947. if !ok {
  948. return
  949. }
  950. entries := lo.Entries(rawMap)
  951. sanitized := lo.FilterMap(entries, func(item lo.Entry[string, interface{}], _ int) (lo.Entry[string, interface{}], bool) {
  952. key := strings.TrimSpace(item.Key)
  953. if key == "" {
  954. return lo.Entry[string, interface{}]{}, false
  955. }
  956. value := strings.TrimSpace(fmt.Sprintf("%v", item.Value))
  957. if value == "" {
  958. return lo.Entry[string, interface{}]{}, false
  959. }
  960. return lo.Entry[string, interface{}]{Key: key, Value: value}, true
  961. })
  962. info.RuntimeHeadersOverride = lo.SliceToMap(sanitized, func(item lo.Entry[string, interface{}]) (string, interface{}) {
  963. return item.Key, item.Value
  964. })
  965. info.UseRuntimeHeadersOverride = true
  966. }
  967. func moveValue(jsonStr, fromPath, toPath string) (string, error) {
  968. sourceValue := gjson.Get(jsonStr, fromPath)
  969. if !sourceValue.Exists() {
  970. return jsonStr, fmt.Errorf("source path does not exist: %s", fromPath)
  971. }
  972. result, err := sjson.Set(jsonStr, toPath, sourceValue.Value())
  973. if err != nil {
  974. return "", err
  975. }
  976. return sjson.Delete(result, fromPath)
  977. }
  978. func copyValue(jsonStr, fromPath, toPath string) (string, error) {
  979. sourceValue := gjson.Get(jsonStr, fromPath)
  980. if !sourceValue.Exists() {
  981. return jsonStr, fmt.Errorf("source path does not exist: %s", fromPath)
  982. }
  983. return sjson.Set(jsonStr, toPath, sourceValue.Value())
  984. }
  985. func modifyValue(jsonStr, path string, value interface{}, keepOrigin, isPrepend bool) (string, error) {
  986. current := gjson.Get(jsonStr, path)
  987. switch {
  988. case current.IsArray():
  989. return modifyArray(jsonStr, path, value, isPrepend)
  990. case current.Type == gjson.String:
  991. return modifyString(jsonStr, path, value, isPrepend)
  992. case current.Type == gjson.JSON:
  993. return mergeObjects(jsonStr, path, value, keepOrigin)
  994. }
  995. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  996. }
  997. func modifyArray(jsonStr, path string, value interface{}, isPrepend bool) (string, error) {
  998. current := gjson.Get(jsonStr, path)
  999. var newArray []interface{}
  1000. // 添加新值
  1001. addValue := func() {
  1002. if arr, ok := value.([]interface{}); ok {
  1003. newArray = append(newArray, arr...)
  1004. } else {
  1005. newArray = append(newArray, value)
  1006. }
  1007. }
  1008. // 添加原值
  1009. addOriginal := func() {
  1010. current.ForEach(func(_, val gjson.Result) bool {
  1011. newArray = append(newArray, val.Value())
  1012. return true
  1013. })
  1014. }
  1015. if isPrepend {
  1016. addValue()
  1017. addOriginal()
  1018. } else {
  1019. addOriginal()
  1020. addValue()
  1021. }
  1022. return sjson.Set(jsonStr, path, newArray)
  1023. }
  1024. func modifyString(jsonStr, path string, value interface{}, isPrepend bool) (string, error) {
  1025. current := gjson.Get(jsonStr, path)
  1026. valueStr := fmt.Sprintf("%v", value)
  1027. var newStr string
  1028. if isPrepend {
  1029. newStr = valueStr + current.String()
  1030. } else {
  1031. newStr = current.String() + valueStr
  1032. }
  1033. return sjson.Set(jsonStr, path, newStr)
  1034. }
  1035. func trimStringValue(jsonStr, path string, value interface{}, isPrefix bool) (string, error) {
  1036. current := gjson.Get(jsonStr, path)
  1037. if current.Type != gjson.String {
  1038. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  1039. }
  1040. if value == nil {
  1041. return jsonStr, fmt.Errorf("trim value is required")
  1042. }
  1043. valueStr := fmt.Sprintf("%v", value)
  1044. var newStr string
  1045. if isPrefix {
  1046. newStr = strings.TrimPrefix(current.String(), valueStr)
  1047. } else {
  1048. newStr = strings.TrimSuffix(current.String(), valueStr)
  1049. }
  1050. return sjson.Set(jsonStr, path, newStr)
  1051. }
  1052. func ensureStringAffix(jsonStr, path string, value interface{}, isPrefix bool) (string, error) {
  1053. current := gjson.Get(jsonStr, path)
  1054. if current.Type != gjson.String {
  1055. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  1056. }
  1057. if value == nil {
  1058. return jsonStr, fmt.Errorf("ensure value is required")
  1059. }
  1060. valueStr := fmt.Sprintf("%v", value)
  1061. if valueStr == "" {
  1062. return jsonStr, fmt.Errorf("ensure value is required")
  1063. }
  1064. currentStr := current.String()
  1065. if isPrefix {
  1066. if strings.HasPrefix(currentStr, valueStr) {
  1067. return jsonStr, nil
  1068. }
  1069. return sjson.Set(jsonStr, path, valueStr+currentStr)
  1070. }
  1071. if strings.HasSuffix(currentStr, valueStr) {
  1072. return jsonStr, nil
  1073. }
  1074. return sjson.Set(jsonStr, path, currentStr+valueStr)
  1075. }
  1076. func transformStringValue(jsonStr, path string, transform func(string) string) (string, error) {
  1077. current := gjson.Get(jsonStr, path)
  1078. if current.Type != gjson.String {
  1079. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  1080. }
  1081. return sjson.Set(jsonStr, path, transform(current.String()))
  1082. }
  1083. func replaceStringValue(jsonStr, path, from, to string) (string, error) {
  1084. current := gjson.Get(jsonStr, path)
  1085. if current.Type != gjson.String {
  1086. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  1087. }
  1088. if from == "" {
  1089. return jsonStr, fmt.Errorf("replace from is required")
  1090. }
  1091. return sjson.Set(jsonStr, path, strings.ReplaceAll(current.String(), from, to))
  1092. }
  1093. func regexReplaceStringValue(jsonStr, path, pattern, replacement string) (string, error) {
  1094. current := gjson.Get(jsonStr, path)
  1095. if current.Type != gjson.String {
  1096. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  1097. }
  1098. if pattern == "" {
  1099. return jsonStr, fmt.Errorf("regex pattern is required")
  1100. }
  1101. re, err := regexp.Compile(pattern)
  1102. if err != nil {
  1103. return jsonStr, err
  1104. }
  1105. return sjson.Set(jsonStr, path, re.ReplaceAllString(current.String(), replacement))
  1106. }
  1107. type pruneObjectsOptions struct {
  1108. conditions []ConditionOperation
  1109. logic string
  1110. recursive bool
  1111. }
  1112. func pruneObjects(jsonStr, path, contextJSON string, value interface{}) (string, error) {
  1113. options, err := parsePruneObjectsOptions(value)
  1114. if err != nil {
  1115. return "", err
  1116. }
  1117. if path == "" {
  1118. var root interface{}
  1119. if err := common.Unmarshal([]byte(jsonStr), &root); err != nil {
  1120. return "", err
  1121. }
  1122. cleaned, _, err := pruneObjectsNode(root, options, contextJSON, true)
  1123. if err != nil {
  1124. return "", err
  1125. }
  1126. cleanedBytes, err := common.Marshal(cleaned)
  1127. if err != nil {
  1128. return "", err
  1129. }
  1130. return string(cleanedBytes), nil
  1131. }
  1132. target := gjson.Get(jsonStr, path)
  1133. if !target.Exists() {
  1134. return jsonStr, nil
  1135. }
  1136. var targetNode interface{}
  1137. if target.Type == gjson.JSON {
  1138. if err := common.Unmarshal([]byte(target.Raw), &targetNode); err != nil {
  1139. return "", err
  1140. }
  1141. } else {
  1142. targetNode = target.Value()
  1143. }
  1144. cleaned, _, err := pruneObjectsNode(targetNode, options, contextJSON, true)
  1145. if err != nil {
  1146. return "", err
  1147. }
  1148. cleanedBytes, err := common.Marshal(cleaned)
  1149. if err != nil {
  1150. return "", err
  1151. }
  1152. return sjson.SetRaw(jsonStr, path, string(cleanedBytes))
  1153. }
  1154. func parsePruneObjectsOptions(value interface{}) (pruneObjectsOptions, error) {
  1155. opts := pruneObjectsOptions{
  1156. logic: "AND",
  1157. recursive: true,
  1158. }
  1159. switch raw := value.(type) {
  1160. case nil:
  1161. return opts, fmt.Errorf("prune_objects value is required")
  1162. case string:
  1163. v := strings.TrimSpace(raw)
  1164. if v == "" {
  1165. return opts, fmt.Errorf("prune_objects value is required")
  1166. }
  1167. opts.conditions = []ConditionOperation{
  1168. {
  1169. Path: "type",
  1170. Mode: "full",
  1171. Value: v,
  1172. },
  1173. }
  1174. case map[string]interface{}:
  1175. if logic, ok := raw["logic"].(string); ok && strings.TrimSpace(logic) != "" {
  1176. opts.logic = logic
  1177. }
  1178. if recursive, ok := raw["recursive"].(bool); ok {
  1179. opts.recursive = recursive
  1180. }
  1181. if condRaw, exists := raw["conditions"]; exists {
  1182. conditions, err := parseConditionOperations(condRaw)
  1183. if err != nil {
  1184. return opts, err
  1185. }
  1186. opts.conditions = append(opts.conditions, conditions...)
  1187. }
  1188. if whereRaw, exists := raw["where"]; exists {
  1189. whereMap, ok := whereRaw.(map[string]interface{})
  1190. if !ok {
  1191. return opts, fmt.Errorf("prune_objects where must be object")
  1192. }
  1193. for key, val := range whereMap {
  1194. key = strings.TrimSpace(key)
  1195. if key == "" {
  1196. continue
  1197. }
  1198. opts.conditions = append(opts.conditions, ConditionOperation{
  1199. Path: key,
  1200. Mode: "full",
  1201. Value: val,
  1202. })
  1203. }
  1204. }
  1205. if matchType, exists := raw["type"]; exists {
  1206. opts.conditions = append(opts.conditions, ConditionOperation{
  1207. Path: "type",
  1208. Mode: "full",
  1209. Value: matchType,
  1210. })
  1211. }
  1212. default:
  1213. return opts, fmt.Errorf("prune_objects value must be string or object")
  1214. }
  1215. if len(opts.conditions) == 0 {
  1216. return opts, fmt.Errorf("prune_objects conditions are required")
  1217. }
  1218. return opts, nil
  1219. }
  1220. func parseConditionOperations(raw interface{}) ([]ConditionOperation, error) {
  1221. switch typed := raw.(type) {
  1222. case map[string]interface{}:
  1223. entries := lo.Entries(typed)
  1224. conditions := lo.FilterMap(entries, func(item lo.Entry[string, interface{}], _ int) (ConditionOperation, bool) {
  1225. path := strings.TrimSpace(item.Key)
  1226. if path == "" {
  1227. return ConditionOperation{}, false
  1228. }
  1229. return ConditionOperation{
  1230. Path: path,
  1231. Mode: "full",
  1232. Value: item.Value,
  1233. }, true
  1234. })
  1235. if len(conditions) == 0 {
  1236. return nil, fmt.Errorf("conditions object must contain at least one key")
  1237. }
  1238. return conditions, nil
  1239. case []interface{}:
  1240. items := typed
  1241. result := make([]ConditionOperation, 0, len(items))
  1242. for _, item := range items {
  1243. itemMap, ok := item.(map[string]interface{})
  1244. if !ok {
  1245. return nil, fmt.Errorf("condition must be object")
  1246. }
  1247. path, _ := itemMap["path"].(string)
  1248. mode, _ := itemMap["mode"].(string)
  1249. if strings.TrimSpace(path) == "" || strings.TrimSpace(mode) == "" {
  1250. return nil, fmt.Errorf("condition path/mode is required")
  1251. }
  1252. condition := ConditionOperation{
  1253. Path: path,
  1254. Mode: mode,
  1255. }
  1256. if value, exists := itemMap["value"]; exists {
  1257. condition.Value = value
  1258. }
  1259. if invert, ok := itemMap["invert"].(bool); ok {
  1260. condition.Invert = invert
  1261. }
  1262. if passMissingKey, ok := itemMap["pass_missing_key"].(bool); ok {
  1263. condition.PassMissingKey = passMissingKey
  1264. }
  1265. result = append(result, condition)
  1266. }
  1267. return result, nil
  1268. default:
  1269. return nil, fmt.Errorf("conditions must be an array or object")
  1270. }
  1271. }
  1272. func pruneObjectsNode(node interface{}, options pruneObjectsOptions, contextJSON string, isRoot bool) (interface{}, bool, error) {
  1273. switch value := node.(type) {
  1274. case []interface{}:
  1275. result := make([]interface{}, 0, len(value))
  1276. for _, item := range value {
  1277. next, drop, err := pruneObjectsNode(item, options, contextJSON, false)
  1278. if err != nil {
  1279. return nil, false, err
  1280. }
  1281. if drop {
  1282. continue
  1283. }
  1284. result = append(result, next)
  1285. }
  1286. return result, false, nil
  1287. case map[string]interface{}:
  1288. shouldDrop, err := shouldPruneObject(value, options, contextJSON)
  1289. if err != nil {
  1290. return nil, false, err
  1291. }
  1292. if shouldDrop && !isRoot {
  1293. return nil, true, nil
  1294. }
  1295. if !options.recursive {
  1296. return value, false, nil
  1297. }
  1298. for key, child := range value {
  1299. next, drop, err := pruneObjectsNode(child, options, contextJSON, false)
  1300. if err != nil {
  1301. return nil, false, err
  1302. }
  1303. if drop {
  1304. delete(value, key)
  1305. continue
  1306. }
  1307. value[key] = next
  1308. }
  1309. return value, false, nil
  1310. default:
  1311. return node, false, nil
  1312. }
  1313. }
  1314. func shouldPruneObject(node map[string]interface{}, options pruneObjectsOptions, contextJSON string) (bool, error) {
  1315. nodeBytes, err := common.Marshal(node)
  1316. if err != nil {
  1317. return false, err
  1318. }
  1319. return checkConditions(string(nodeBytes), contextJSON, options.conditions, options.logic)
  1320. }
  1321. func mergeObjects(jsonStr, path string, value interface{}, keepOrigin bool) (string, error) {
  1322. current := gjson.Get(jsonStr, path)
  1323. var currentMap, newMap map[string]interface{}
  1324. // 解析当前值
  1325. if err := common.Unmarshal([]byte(current.Raw), &currentMap); err != nil {
  1326. return "", err
  1327. }
  1328. // 解析新值
  1329. switch v := value.(type) {
  1330. case map[string]interface{}:
  1331. newMap = v
  1332. default:
  1333. jsonBytes, _ := common.Marshal(v)
  1334. if err := common.Unmarshal(jsonBytes, &newMap); err != nil {
  1335. return "", err
  1336. }
  1337. }
  1338. // 合并
  1339. result := make(map[string]interface{})
  1340. for k, v := range currentMap {
  1341. result[k] = v
  1342. }
  1343. for k, v := range newMap {
  1344. if !keepOrigin || result[k] == nil {
  1345. result[k] = v
  1346. }
  1347. }
  1348. return sjson.Set(jsonStr, path, result)
  1349. }
  1350. // BuildParamOverrideContext 提供 ApplyParamOverride 可用的上下文信息。
  1351. // 目前内置以下字段:
  1352. // - upstream_model/model:始终为通道映射后的上游模型名。
  1353. // - original_model:请求最初指定的模型名。
  1354. // - request_path:请求路径
  1355. // - is_channel_test:是否为渠道测试请求(同 is_test)。
  1356. func BuildParamOverrideContext(info *RelayInfo) map[string]interface{} {
  1357. if info == nil {
  1358. return nil
  1359. }
  1360. ctx := make(map[string]interface{})
  1361. if info.ChannelMeta != nil && info.ChannelMeta.UpstreamModelName != "" {
  1362. ctx["model"] = info.ChannelMeta.UpstreamModelName
  1363. ctx["upstream_model"] = info.ChannelMeta.UpstreamModelName
  1364. }
  1365. if info.OriginModelName != "" {
  1366. ctx["original_model"] = info.OriginModelName
  1367. if _, exists := ctx["model"]; !exists {
  1368. ctx["model"] = info.OriginModelName
  1369. }
  1370. }
  1371. if info.RequestURLPath != "" {
  1372. requestPath := info.RequestURLPath
  1373. if requestPath != "" {
  1374. ctx["request_path"] = requestPath
  1375. }
  1376. }
  1377. ctx[paramOverrideContextRequestHeaders] = buildNormalizedHeaders(info.RequestHeaders)
  1378. ctx[paramOverrideContextRequestHeadersRaw] = buildRawHeaders(info.RequestHeaders)
  1379. headerOverrideSource := getHeaderOverrideMap(info)
  1380. if info.UseRuntimeHeadersOverride {
  1381. headerOverrideSource = info.RuntimeHeadersOverride
  1382. }
  1383. rawHeaderOverride, normalizedHeaderOverride := buildHeaderOverrideContext(headerOverrideSource)
  1384. ctx[paramOverrideContextHeaderOverride] = rawHeaderOverride
  1385. ctx[paramOverrideContextHeaderOverrideNormalized] = normalizedHeaderOverride
  1386. ctx["retry_index"] = info.RetryIndex
  1387. ctx["is_retry"] = info.RetryIndex > 0
  1388. ctx["retry"] = map[string]interface{}{
  1389. "index": info.RetryIndex,
  1390. "is_retry": info.RetryIndex > 0,
  1391. }
  1392. if info.LastError != nil {
  1393. code := string(info.LastError.GetErrorCode())
  1394. errorType := string(info.LastError.GetErrorType())
  1395. lastError := map[string]interface{}{
  1396. "status_code": info.LastError.StatusCode,
  1397. "message": info.LastError.Error(),
  1398. "code": code,
  1399. "error_code": code,
  1400. "type": errorType,
  1401. "error_type": errorType,
  1402. "skip_retry": types.IsSkipRetryError(info.LastError),
  1403. }
  1404. ctx["last_error"] = lastError
  1405. ctx["last_error_status_code"] = info.LastError.StatusCode
  1406. ctx["last_error_message"] = info.LastError.Error()
  1407. ctx["last_error_code"] = code
  1408. ctx["last_error_type"] = errorType
  1409. }
  1410. ctx["is_channel_test"] = info.IsChannelTest
  1411. return ctx
  1412. }