override.go 42 KB

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