override.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  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, 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 "sync_fields":
  443. result, err = syncFieldsBetweenTargets(result, context, op.From, op.To)
  444. if err == nil {
  445. contextJSON, err = marshalContextJSON(context)
  446. }
  447. default:
  448. return "", fmt.Errorf("unknown operation: %s", op.Mode)
  449. }
  450. if err != nil {
  451. return "", fmt.Errorf("operation %s failed: %w", op.Mode, err)
  452. }
  453. }
  454. return result, nil
  455. }
  456. func parseParamOverrideReturnError(value interface{}) (*ParamOverrideReturnError, error) {
  457. result := &ParamOverrideReturnError{
  458. StatusCode: http.StatusBadRequest,
  459. Code: string(types.ErrorCodeInvalidRequest),
  460. Type: "invalid_request_error",
  461. SkipRetry: true,
  462. }
  463. switch raw := value.(type) {
  464. case nil:
  465. return nil, fmt.Errorf("return_error value is required")
  466. case string:
  467. result.Message = strings.TrimSpace(raw)
  468. case map[string]interface{}:
  469. if message, ok := raw["message"].(string); ok {
  470. result.Message = strings.TrimSpace(message)
  471. }
  472. if result.Message == "" {
  473. if message, ok := raw["msg"].(string); ok {
  474. result.Message = strings.TrimSpace(message)
  475. }
  476. }
  477. if code, exists := raw["code"]; exists {
  478. codeStr := strings.TrimSpace(fmt.Sprintf("%v", code))
  479. if codeStr != "" {
  480. result.Code = codeStr
  481. }
  482. }
  483. if errType, ok := raw["type"].(string); ok {
  484. errType = strings.TrimSpace(errType)
  485. if errType != "" {
  486. result.Type = errType
  487. }
  488. }
  489. if skipRetry, ok := raw["skip_retry"].(bool); ok {
  490. result.SkipRetry = skipRetry
  491. }
  492. if statusCodeRaw, exists := raw["status_code"]; exists {
  493. statusCode, ok := parseOverrideInt(statusCodeRaw)
  494. if !ok {
  495. return nil, fmt.Errorf("return_error status_code must be an integer")
  496. }
  497. result.StatusCode = statusCode
  498. } else if statusRaw, exists := raw["status"]; exists {
  499. statusCode, ok := parseOverrideInt(statusRaw)
  500. if !ok {
  501. return nil, fmt.Errorf("return_error status must be an integer")
  502. }
  503. result.StatusCode = statusCode
  504. }
  505. default:
  506. return nil, fmt.Errorf("return_error value must be string or object")
  507. }
  508. if result.Message == "" {
  509. return nil, fmt.Errorf("return_error message is required")
  510. }
  511. if result.StatusCode < http.StatusContinue || result.StatusCode > http.StatusNetworkAuthenticationRequired {
  512. return nil, fmt.Errorf("return_error status code out of range: %d", result.StatusCode)
  513. }
  514. return result, nil
  515. }
  516. func parseOverrideInt(v interface{}) (int, bool) {
  517. switch value := v.(type) {
  518. case int:
  519. return value, true
  520. case float64:
  521. if value != float64(int(value)) {
  522. return 0, false
  523. }
  524. return int(value), true
  525. default:
  526. return 0, false
  527. }
  528. }
  529. func ensureContextMap(conditionContext map[string]interface{}) map[string]interface{} {
  530. if conditionContext != nil {
  531. return conditionContext
  532. }
  533. return make(map[string]interface{})
  534. }
  535. func marshalContextJSON(context map[string]interface{}) (string, error) {
  536. if context == nil || len(context) == 0 {
  537. return "", nil
  538. }
  539. ctxBytes, err := common.Marshal(context)
  540. if err != nil {
  541. return "", err
  542. }
  543. return string(ctxBytes), nil
  544. }
  545. func setHeaderOverrideInContext(context map[string]interface{}, headerName string, value interface{}, keepOrigin bool) error {
  546. headerName = strings.TrimSpace(headerName)
  547. if headerName == "" {
  548. return fmt.Errorf("header name is required")
  549. }
  550. if keepOrigin {
  551. if _, exists := getHeaderValueFromContext(context, headerName); exists {
  552. return nil
  553. }
  554. }
  555. if value == nil {
  556. return fmt.Errorf("header value is required")
  557. }
  558. headerValue := strings.TrimSpace(fmt.Sprintf("%v", value))
  559. if headerValue == "" {
  560. return fmt.Errorf("header value is required")
  561. }
  562. rawHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverride)
  563. rawHeaders[headerName] = headerValue
  564. normalizedHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverrideNormalized)
  565. normalizedHeaders[normalizeHeaderContextKey(headerName)] = headerValue
  566. return nil
  567. }
  568. func copyHeaderInContext(context map[string]interface{}, fromHeader, toHeader string, keepOrigin bool) error {
  569. fromHeader = strings.TrimSpace(fromHeader)
  570. toHeader = strings.TrimSpace(toHeader)
  571. if fromHeader == "" || toHeader == "" {
  572. return fmt.Errorf("copy_header from/to is required")
  573. }
  574. value, exists := getHeaderValueFromContext(context, fromHeader)
  575. if !exists {
  576. return fmt.Errorf("source header does not exist: %s", fromHeader)
  577. }
  578. return setHeaderOverrideInContext(context, toHeader, value, keepOrigin)
  579. }
  580. func moveHeaderInContext(context map[string]interface{}, fromHeader, toHeader string, keepOrigin bool) error {
  581. fromHeader = strings.TrimSpace(fromHeader)
  582. toHeader = strings.TrimSpace(toHeader)
  583. if fromHeader == "" || toHeader == "" {
  584. return fmt.Errorf("move_header from/to is required")
  585. }
  586. if err := copyHeaderInContext(context, fromHeader, toHeader, keepOrigin); err != nil {
  587. return err
  588. }
  589. if strings.EqualFold(fromHeader, toHeader) {
  590. return nil
  591. }
  592. return deleteHeaderOverrideInContext(context, fromHeader)
  593. }
  594. func deleteHeaderOverrideInContext(context map[string]interface{}, headerName string) error {
  595. headerName = strings.TrimSpace(headerName)
  596. if headerName == "" {
  597. return fmt.Errorf("header name is required")
  598. }
  599. rawHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverride)
  600. for key := range rawHeaders {
  601. if strings.EqualFold(strings.TrimSpace(key), headerName) {
  602. delete(rawHeaders, key)
  603. }
  604. }
  605. normalizedHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverrideNormalized)
  606. delete(normalizedHeaders, normalizeHeaderContextKey(headerName))
  607. return nil
  608. }
  609. type syncTarget struct {
  610. kind string
  611. key string
  612. }
  613. func parseSyncTarget(spec string) (syncTarget, error) {
  614. raw := strings.TrimSpace(spec)
  615. if raw == "" {
  616. return syncTarget{}, fmt.Errorf("sync_fields target is required")
  617. }
  618. idx := strings.Index(raw, ":")
  619. if idx < 0 {
  620. // Backward compatibility: treat bare value as JSON path.
  621. return syncTarget{
  622. kind: "json",
  623. key: raw,
  624. }, nil
  625. }
  626. kind := strings.ToLower(strings.TrimSpace(raw[:idx]))
  627. key := strings.TrimSpace(raw[idx+1:])
  628. if key == "" {
  629. return syncTarget{}, fmt.Errorf("sync_fields target key is required: %s", raw)
  630. }
  631. switch kind {
  632. case "json", "body":
  633. return syncTarget{
  634. kind: "json",
  635. key: key,
  636. }, nil
  637. case "header":
  638. return syncTarget{
  639. kind: "header",
  640. key: key,
  641. }, nil
  642. default:
  643. return syncTarget{}, fmt.Errorf("sync_fields target prefix is invalid: %s", raw)
  644. }
  645. }
  646. func readSyncTargetValue(jsonStr string, context map[string]interface{}, target syncTarget) (interface{}, bool, error) {
  647. switch target.kind {
  648. case "json":
  649. path := processNegativeIndex(jsonStr, target.key)
  650. value := gjson.Get(jsonStr, path)
  651. if !value.Exists() || value.Type == gjson.Null {
  652. return nil, false, nil
  653. }
  654. if value.Type == gjson.String && strings.TrimSpace(value.String()) == "" {
  655. return nil, false, nil
  656. }
  657. return value.Value(), true, nil
  658. case "header":
  659. value, ok := getHeaderValueFromContext(context, target.key)
  660. if !ok || strings.TrimSpace(value) == "" {
  661. return nil, false, nil
  662. }
  663. return value, true, nil
  664. default:
  665. return nil, false, fmt.Errorf("unsupported sync_fields target kind: %s", target.kind)
  666. }
  667. }
  668. func writeSyncTargetValue(jsonStr string, context map[string]interface{}, target syncTarget, value interface{}) (string, error) {
  669. switch target.kind {
  670. case "json":
  671. path := processNegativeIndex(jsonStr, target.key)
  672. nextJSON, err := sjson.Set(jsonStr, path, value)
  673. if err != nil {
  674. return "", err
  675. }
  676. return nextJSON, nil
  677. case "header":
  678. if err := setHeaderOverrideInContext(context, target.key, value, false); err != nil {
  679. return "", err
  680. }
  681. return jsonStr, nil
  682. default:
  683. return "", fmt.Errorf("unsupported sync_fields target kind: %s", target.kind)
  684. }
  685. }
  686. func syncFieldsBetweenTargets(jsonStr string, context map[string]interface{}, fromSpec string, toSpec string) (string, error) {
  687. fromTarget, err := parseSyncTarget(fromSpec)
  688. if err != nil {
  689. return "", err
  690. }
  691. toTarget, err := parseSyncTarget(toSpec)
  692. if err != nil {
  693. return "", err
  694. }
  695. fromValue, fromExists, err := readSyncTargetValue(jsonStr, context, fromTarget)
  696. if err != nil {
  697. return "", err
  698. }
  699. toValue, toExists, err := readSyncTargetValue(jsonStr, context, toTarget)
  700. if err != nil {
  701. return "", err
  702. }
  703. // If one side exists and the other side is missing, sync the missing side.
  704. if fromExists && !toExists {
  705. return writeSyncTargetValue(jsonStr, context, toTarget, fromValue)
  706. }
  707. if toExists && !fromExists {
  708. return writeSyncTargetValue(jsonStr, context, fromTarget, toValue)
  709. }
  710. return jsonStr, nil
  711. }
  712. func ensureMapKeyInContext(context map[string]interface{}, key string) map[string]interface{} {
  713. if context == nil {
  714. return map[string]interface{}{}
  715. }
  716. if existing, ok := context[key]; ok {
  717. if mapVal, ok := existing.(map[string]interface{}); ok {
  718. return mapVal
  719. }
  720. }
  721. result := make(map[string]interface{})
  722. context[key] = result
  723. return result
  724. }
  725. func getHeaderValueFromContext(context map[string]interface{}, headerName string) (string, bool) {
  726. headerName = strings.TrimSpace(headerName)
  727. if headerName == "" {
  728. return "", false
  729. }
  730. if value, ok := findHeaderValueInMap(ensureMapKeyInContext(context, paramOverrideContextHeaderOverride), headerName); ok {
  731. return value, true
  732. }
  733. if value, ok := findHeaderValueInMap(ensureMapKeyInContext(context, paramOverrideContextRequestHeadersRaw), headerName); ok {
  734. return value, true
  735. }
  736. normalizedName := normalizeHeaderContextKey(headerName)
  737. if normalizedName == "" {
  738. return "", false
  739. }
  740. if value, ok := findHeaderValueInMap(ensureMapKeyInContext(context, paramOverrideContextHeaderOverrideNormalized), normalizedName); ok {
  741. return value, true
  742. }
  743. if value, ok := findHeaderValueInMap(ensureMapKeyInContext(context, paramOverrideContextRequestHeaders), normalizedName); ok {
  744. return value, true
  745. }
  746. return "", false
  747. }
  748. func findHeaderValueInMap(source map[string]interface{}, key string) (string, bool) {
  749. if len(source) == 0 {
  750. return "", false
  751. }
  752. entries := lo.Entries(source)
  753. entry, ok := lo.Find(entries, func(item lo.Entry[string, interface{}]) bool {
  754. return strings.EqualFold(strings.TrimSpace(item.Key), key)
  755. })
  756. if !ok {
  757. return "", false
  758. }
  759. value := strings.TrimSpace(fmt.Sprintf("%v", entry.Value))
  760. if value == "" {
  761. return "", false
  762. }
  763. return value, true
  764. }
  765. func normalizeHeaderContextKey(key string) string {
  766. key = strings.TrimSpace(strings.ToLower(key))
  767. if key == "" {
  768. return ""
  769. }
  770. var b strings.Builder
  771. b.Grow(len(key))
  772. previousUnderscore := false
  773. for _, r := range key {
  774. switch {
  775. case r >= 'a' && r <= 'z':
  776. b.WriteRune(r)
  777. previousUnderscore = false
  778. case r >= '0' && r <= '9':
  779. b.WriteRune(r)
  780. previousUnderscore = false
  781. default:
  782. if !previousUnderscore {
  783. b.WriteByte('_')
  784. previousUnderscore = true
  785. }
  786. }
  787. }
  788. result := strings.Trim(b.String(), "_")
  789. return result
  790. }
  791. func buildNormalizedHeaders(headers map[string]string) map[string]interface{} {
  792. if len(headers) == 0 {
  793. return map[string]interface{}{}
  794. }
  795. entries := lo.Entries(headers)
  796. normalizedEntries := lo.FilterMap(entries, func(item lo.Entry[string, string], _ int) (lo.Entry[string, string], bool) {
  797. normalized := normalizeHeaderContextKey(item.Key)
  798. value := strings.TrimSpace(item.Value)
  799. if normalized == "" || value == "" {
  800. return lo.Entry[string, string]{}, false
  801. }
  802. return lo.Entry[string, string]{Key: normalized, Value: value}, true
  803. })
  804. return lo.SliceToMap(normalizedEntries, func(item lo.Entry[string, string]) (string, interface{}) {
  805. return item.Key, item.Value
  806. })
  807. }
  808. func buildRawHeaders(headers map[string]string) map[string]interface{} {
  809. if len(headers) == 0 {
  810. return map[string]interface{}{}
  811. }
  812. entries := lo.Entries(headers)
  813. rawEntries := lo.FilterMap(entries, func(item lo.Entry[string, string], _ int) (lo.Entry[string, string], bool) {
  814. key := strings.TrimSpace(item.Key)
  815. value := strings.TrimSpace(item.Value)
  816. if key == "" || value == "" {
  817. return lo.Entry[string, string]{}, false
  818. }
  819. return lo.Entry[string, string]{Key: key, Value: value}, true
  820. })
  821. return lo.SliceToMap(rawEntries, func(item lo.Entry[string, string]) (string, interface{}) {
  822. return item.Key, item.Value
  823. })
  824. }
  825. func buildHeaderOverrideContext(headers map[string]interface{}) (map[string]interface{}, map[string]interface{}) {
  826. if len(headers) == 0 {
  827. return map[string]interface{}{}, map[string]interface{}{}
  828. }
  829. entries := lo.Entries(headers)
  830. rawEntries := lo.FilterMap(entries, func(item lo.Entry[string, interface{}], _ int) (lo.Entry[string, string], bool) {
  831. key := strings.TrimSpace(item.Key)
  832. value := strings.TrimSpace(fmt.Sprintf("%v", item.Value))
  833. if key == "" || value == "" {
  834. return lo.Entry[string, string]{}, false
  835. }
  836. return lo.Entry[string, string]{Key: key, Value: value}, true
  837. })
  838. raw := lo.SliceToMap(rawEntries, func(item lo.Entry[string, string]) (string, interface{}) {
  839. return item.Key, item.Value
  840. })
  841. normalizedEntries := lo.FilterMap(rawEntries, func(item lo.Entry[string, string], _ int) (lo.Entry[string, string], bool) {
  842. normalized := normalizeHeaderContextKey(item.Key)
  843. if normalized == "" {
  844. return lo.Entry[string, string]{}, false
  845. }
  846. return lo.Entry[string, string]{Key: normalized, Value: item.Value}, true
  847. })
  848. normalized := lo.SliceToMap(normalizedEntries, func(item lo.Entry[string, string]) (string, interface{}) {
  849. return item.Key, item.Value
  850. })
  851. return raw, normalized
  852. }
  853. func syncRuntimeHeaderOverrideFromContext(info *RelayInfo, context map[string]interface{}) {
  854. if info == nil || context == nil {
  855. return
  856. }
  857. raw, exists := context[paramOverrideContextHeaderOverride]
  858. if !exists {
  859. return
  860. }
  861. rawMap, ok := raw.(map[string]interface{})
  862. if !ok {
  863. return
  864. }
  865. entries := lo.Entries(rawMap)
  866. sanitized := lo.FilterMap(entries, func(item lo.Entry[string, interface{}], _ int) (lo.Entry[string, interface{}], bool) {
  867. key := strings.TrimSpace(item.Key)
  868. if key == "" {
  869. return lo.Entry[string, interface{}]{}, false
  870. }
  871. value := strings.TrimSpace(fmt.Sprintf("%v", item.Value))
  872. if value == "" {
  873. return lo.Entry[string, interface{}]{}, false
  874. }
  875. return lo.Entry[string, interface{}]{Key: key, Value: value}, true
  876. })
  877. info.RuntimeHeadersOverride = lo.SliceToMap(sanitized, func(item lo.Entry[string, interface{}]) (string, interface{}) {
  878. return item.Key, item.Value
  879. })
  880. info.UseRuntimeHeadersOverride = true
  881. }
  882. func moveValue(jsonStr, fromPath, toPath string) (string, error) {
  883. sourceValue := gjson.Get(jsonStr, fromPath)
  884. if !sourceValue.Exists() {
  885. return jsonStr, fmt.Errorf("source path does not exist: %s", fromPath)
  886. }
  887. result, err := sjson.Set(jsonStr, toPath, sourceValue.Value())
  888. if err != nil {
  889. return "", err
  890. }
  891. return sjson.Delete(result, fromPath)
  892. }
  893. func copyValue(jsonStr, fromPath, toPath string) (string, error) {
  894. sourceValue := gjson.Get(jsonStr, fromPath)
  895. if !sourceValue.Exists() {
  896. return jsonStr, fmt.Errorf("source path does not exist: %s", fromPath)
  897. }
  898. return sjson.Set(jsonStr, toPath, sourceValue.Value())
  899. }
  900. func modifyValue(jsonStr, path string, value interface{}, keepOrigin, isPrepend bool) (string, error) {
  901. current := gjson.Get(jsonStr, path)
  902. switch {
  903. case current.IsArray():
  904. return modifyArray(jsonStr, path, value, isPrepend)
  905. case current.Type == gjson.String:
  906. return modifyString(jsonStr, path, value, isPrepend)
  907. case current.Type == gjson.JSON:
  908. return mergeObjects(jsonStr, path, value, keepOrigin)
  909. }
  910. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  911. }
  912. func modifyArray(jsonStr, path string, value interface{}, isPrepend bool) (string, error) {
  913. current := gjson.Get(jsonStr, path)
  914. var newArray []interface{}
  915. // 添加新值
  916. addValue := func() {
  917. if arr, ok := value.([]interface{}); ok {
  918. newArray = append(newArray, arr...)
  919. } else {
  920. newArray = append(newArray, value)
  921. }
  922. }
  923. // 添加原值
  924. addOriginal := func() {
  925. current.ForEach(func(_, val gjson.Result) bool {
  926. newArray = append(newArray, val.Value())
  927. return true
  928. })
  929. }
  930. if isPrepend {
  931. addValue()
  932. addOriginal()
  933. } else {
  934. addOriginal()
  935. addValue()
  936. }
  937. return sjson.Set(jsonStr, path, newArray)
  938. }
  939. func modifyString(jsonStr, path string, value interface{}, isPrepend bool) (string, error) {
  940. current := gjson.Get(jsonStr, path)
  941. valueStr := fmt.Sprintf("%v", value)
  942. var newStr string
  943. if isPrepend {
  944. newStr = valueStr + current.String()
  945. } else {
  946. newStr = current.String() + valueStr
  947. }
  948. return sjson.Set(jsonStr, path, newStr)
  949. }
  950. func trimStringValue(jsonStr, path string, value interface{}, isPrefix bool) (string, error) {
  951. current := gjson.Get(jsonStr, path)
  952. if current.Type != gjson.String {
  953. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  954. }
  955. if value == nil {
  956. return jsonStr, fmt.Errorf("trim value is required")
  957. }
  958. valueStr := fmt.Sprintf("%v", value)
  959. var newStr string
  960. if isPrefix {
  961. newStr = strings.TrimPrefix(current.String(), valueStr)
  962. } else {
  963. newStr = strings.TrimSuffix(current.String(), valueStr)
  964. }
  965. return sjson.Set(jsonStr, path, newStr)
  966. }
  967. func ensureStringAffix(jsonStr, path string, value interface{}, isPrefix bool) (string, error) {
  968. current := gjson.Get(jsonStr, path)
  969. if current.Type != gjson.String {
  970. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  971. }
  972. if value == nil {
  973. return jsonStr, fmt.Errorf("ensure value is required")
  974. }
  975. valueStr := fmt.Sprintf("%v", value)
  976. if valueStr == "" {
  977. return jsonStr, fmt.Errorf("ensure value is required")
  978. }
  979. currentStr := current.String()
  980. if isPrefix {
  981. if strings.HasPrefix(currentStr, valueStr) {
  982. return jsonStr, nil
  983. }
  984. return sjson.Set(jsonStr, path, valueStr+currentStr)
  985. }
  986. if strings.HasSuffix(currentStr, valueStr) {
  987. return jsonStr, nil
  988. }
  989. return sjson.Set(jsonStr, path, currentStr+valueStr)
  990. }
  991. func transformStringValue(jsonStr, path string, transform func(string) string) (string, error) {
  992. current := gjson.Get(jsonStr, path)
  993. if current.Type != gjson.String {
  994. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  995. }
  996. return sjson.Set(jsonStr, path, transform(current.String()))
  997. }
  998. func replaceStringValue(jsonStr, path, from, to string) (string, error) {
  999. current := gjson.Get(jsonStr, path)
  1000. if current.Type != gjson.String {
  1001. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  1002. }
  1003. if from == "" {
  1004. return jsonStr, fmt.Errorf("replace from is required")
  1005. }
  1006. return sjson.Set(jsonStr, path, strings.ReplaceAll(current.String(), from, to))
  1007. }
  1008. func regexReplaceStringValue(jsonStr, path, pattern, replacement string) (string, error) {
  1009. current := gjson.Get(jsonStr, path)
  1010. if current.Type != gjson.String {
  1011. return jsonStr, fmt.Errorf("operation not supported for type: %v", current.Type)
  1012. }
  1013. if pattern == "" {
  1014. return jsonStr, fmt.Errorf("regex pattern is required")
  1015. }
  1016. re, err := regexp.Compile(pattern)
  1017. if err != nil {
  1018. return jsonStr, err
  1019. }
  1020. return sjson.Set(jsonStr, path, re.ReplaceAllString(current.String(), replacement))
  1021. }
  1022. type pruneObjectsOptions struct {
  1023. conditions []ConditionOperation
  1024. logic string
  1025. recursive bool
  1026. }
  1027. func pruneObjects(jsonStr, path, contextJSON string, value interface{}) (string, error) {
  1028. options, err := parsePruneObjectsOptions(value)
  1029. if err != nil {
  1030. return "", err
  1031. }
  1032. if path == "" {
  1033. var root interface{}
  1034. if err := common.Unmarshal([]byte(jsonStr), &root); err != nil {
  1035. return "", err
  1036. }
  1037. cleaned, _, err := pruneObjectsNode(root, options, contextJSON, true)
  1038. if err != nil {
  1039. return "", err
  1040. }
  1041. cleanedBytes, err := common.Marshal(cleaned)
  1042. if err != nil {
  1043. return "", err
  1044. }
  1045. return string(cleanedBytes), nil
  1046. }
  1047. target := gjson.Get(jsonStr, path)
  1048. if !target.Exists() {
  1049. return jsonStr, nil
  1050. }
  1051. var targetNode interface{}
  1052. if target.Type == gjson.JSON {
  1053. if err := common.Unmarshal([]byte(target.Raw), &targetNode); err != nil {
  1054. return "", err
  1055. }
  1056. } else {
  1057. targetNode = target.Value()
  1058. }
  1059. cleaned, _, err := pruneObjectsNode(targetNode, options, contextJSON, true)
  1060. if err != nil {
  1061. return "", err
  1062. }
  1063. cleanedBytes, err := common.Marshal(cleaned)
  1064. if err != nil {
  1065. return "", err
  1066. }
  1067. return sjson.SetRaw(jsonStr, path, string(cleanedBytes))
  1068. }
  1069. func parsePruneObjectsOptions(value interface{}) (pruneObjectsOptions, error) {
  1070. opts := pruneObjectsOptions{
  1071. logic: "AND",
  1072. recursive: true,
  1073. }
  1074. switch raw := value.(type) {
  1075. case nil:
  1076. return opts, fmt.Errorf("prune_objects value is required")
  1077. case string:
  1078. v := strings.TrimSpace(raw)
  1079. if v == "" {
  1080. return opts, fmt.Errorf("prune_objects value is required")
  1081. }
  1082. opts.conditions = []ConditionOperation{
  1083. {
  1084. Path: "type",
  1085. Mode: "full",
  1086. Value: v,
  1087. },
  1088. }
  1089. case map[string]interface{}:
  1090. if logic, ok := raw["logic"].(string); ok && strings.TrimSpace(logic) != "" {
  1091. opts.logic = logic
  1092. }
  1093. if recursive, ok := raw["recursive"].(bool); ok {
  1094. opts.recursive = recursive
  1095. }
  1096. if condRaw, exists := raw["conditions"]; exists {
  1097. conditions, err := parseConditionOperations(condRaw)
  1098. if err != nil {
  1099. return opts, err
  1100. }
  1101. opts.conditions = append(opts.conditions, conditions...)
  1102. }
  1103. if whereRaw, exists := raw["where"]; exists {
  1104. whereMap, ok := whereRaw.(map[string]interface{})
  1105. if !ok {
  1106. return opts, fmt.Errorf("prune_objects where must be object")
  1107. }
  1108. for key, val := range whereMap {
  1109. key = strings.TrimSpace(key)
  1110. if key == "" {
  1111. continue
  1112. }
  1113. opts.conditions = append(opts.conditions, ConditionOperation{
  1114. Path: key,
  1115. Mode: "full",
  1116. Value: val,
  1117. })
  1118. }
  1119. }
  1120. if matchType, exists := raw["type"]; exists {
  1121. opts.conditions = append(opts.conditions, ConditionOperation{
  1122. Path: "type",
  1123. Mode: "full",
  1124. Value: matchType,
  1125. })
  1126. }
  1127. default:
  1128. return opts, fmt.Errorf("prune_objects value must be string or object")
  1129. }
  1130. if len(opts.conditions) == 0 {
  1131. return opts, fmt.Errorf("prune_objects conditions are required")
  1132. }
  1133. return opts, nil
  1134. }
  1135. func parseConditionOperations(raw interface{}) ([]ConditionOperation, error) {
  1136. switch typed := raw.(type) {
  1137. case map[string]interface{}:
  1138. entries := lo.Entries(typed)
  1139. conditions := lo.FilterMap(entries, func(item lo.Entry[string, interface{}], _ int) (ConditionOperation, bool) {
  1140. path := strings.TrimSpace(item.Key)
  1141. if path == "" {
  1142. return ConditionOperation{}, false
  1143. }
  1144. return ConditionOperation{
  1145. Path: path,
  1146. Mode: "full",
  1147. Value: item.Value,
  1148. }, true
  1149. })
  1150. if len(conditions) == 0 {
  1151. return nil, fmt.Errorf("conditions object must contain at least one key")
  1152. }
  1153. return conditions, nil
  1154. case []interface{}:
  1155. items := typed
  1156. result := make([]ConditionOperation, 0, len(items))
  1157. for _, item := range items {
  1158. itemMap, ok := item.(map[string]interface{})
  1159. if !ok {
  1160. return nil, fmt.Errorf("condition must be object")
  1161. }
  1162. path, _ := itemMap["path"].(string)
  1163. mode, _ := itemMap["mode"].(string)
  1164. if strings.TrimSpace(path) == "" || strings.TrimSpace(mode) == "" {
  1165. return nil, fmt.Errorf("condition path/mode is required")
  1166. }
  1167. condition := ConditionOperation{
  1168. Path: path,
  1169. Mode: mode,
  1170. }
  1171. if value, exists := itemMap["value"]; exists {
  1172. condition.Value = value
  1173. }
  1174. if invert, ok := itemMap["invert"].(bool); ok {
  1175. condition.Invert = invert
  1176. }
  1177. if passMissingKey, ok := itemMap["pass_missing_key"].(bool); ok {
  1178. condition.PassMissingKey = passMissingKey
  1179. }
  1180. result = append(result, condition)
  1181. }
  1182. return result, nil
  1183. default:
  1184. return nil, fmt.Errorf("conditions must be an array or object")
  1185. }
  1186. }
  1187. func pruneObjectsNode(node interface{}, options pruneObjectsOptions, contextJSON string, isRoot bool) (interface{}, bool, error) {
  1188. switch value := node.(type) {
  1189. case []interface{}:
  1190. result := make([]interface{}, 0, len(value))
  1191. for _, item := range value {
  1192. next, drop, err := pruneObjectsNode(item, options, contextJSON, false)
  1193. if err != nil {
  1194. return nil, false, err
  1195. }
  1196. if drop {
  1197. continue
  1198. }
  1199. result = append(result, next)
  1200. }
  1201. return result, false, nil
  1202. case map[string]interface{}:
  1203. shouldDrop, err := shouldPruneObject(value, options, contextJSON)
  1204. if err != nil {
  1205. return nil, false, err
  1206. }
  1207. if shouldDrop && !isRoot {
  1208. return nil, true, nil
  1209. }
  1210. if !options.recursive {
  1211. return value, false, nil
  1212. }
  1213. for key, child := range value {
  1214. next, drop, err := pruneObjectsNode(child, options, contextJSON, false)
  1215. if err != nil {
  1216. return nil, false, err
  1217. }
  1218. if drop {
  1219. delete(value, key)
  1220. continue
  1221. }
  1222. value[key] = next
  1223. }
  1224. return value, false, nil
  1225. default:
  1226. return node, false, nil
  1227. }
  1228. }
  1229. func shouldPruneObject(node map[string]interface{}, options pruneObjectsOptions, contextJSON string) (bool, error) {
  1230. nodeBytes, err := common.Marshal(node)
  1231. if err != nil {
  1232. return false, err
  1233. }
  1234. return checkConditions(string(nodeBytes), contextJSON, options.conditions, options.logic)
  1235. }
  1236. func mergeObjects(jsonStr, path string, value interface{}, keepOrigin bool) (string, error) {
  1237. current := gjson.Get(jsonStr, path)
  1238. var currentMap, newMap map[string]interface{}
  1239. // 解析当前值
  1240. if err := common.Unmarshal([]byte(current.Raw), &currentMap); err != nil {
  1241. return "", err
  1242. }
  1243. // 解析新值
  1244. switch v := value.(type) {
  1245. case map[string]interface{}:
  1246. newMap = v
  1247. default:
  1248. jsonBytes, _ := common.Marshal(v)
  1249. if err := common.Unmarshal(jsonBytes, &newMap); err != nil {
  1250. return "", err
  1251. }
  1252. }
  1253. // 合并
  1254. result := make(map[string]interface{})
  1255. for k, v := range currentMap {
  1256. result[k] = v
  1257. }
  1258. for k, v := range newMap {
  1259. if !keepOrigin || result[k] == nil {
  1260. result[k] = v
  1261. }
  1262. }
  1263. return sjson.Set(jsonStr, path, result)
  1264. }
  1265. // BuildParamOverrideContext 提供 ApplyParamOverride 可用的上下文信息。
  1266. // 目前内置以下字段:
  1267. // - upstream_model/model:始终为通道映射后的上游模型名。
  1268. // - original_model:请求最初指定的模型名。
  1269. // - request_path:请求路径
  1270. // - is_channel_test:是否为渠道测试请求(同 is_test)。
  1271. func BuildParamOverrideContext(info *RelayInfo) map[string]interface{} {
  1272. if info == nil {
  1273. return nil
  1274. }
  1275. ctx := make(map[string]interface{})
  1276. if info.ChannelMeta != nil && info.ChannelMeta.UpstreamModelName != "" {
  1277. ctx["model"] = info.ChannelMeta.UpstreamModelName
  1278. ctx["upstream_model"] = info.ChannelMeta.UpstreamModelName
  1279. }
  1280. if info.OriginModelName != "" {
  1281. ctx["original_model"] = info.OriginModelName
  1282. if _, exists := ctx["model"]; !exists {
  1283. ctx["model"] = info.OriginModelName
  1284. }
  1285. }
  1286. if info.RequestURLPath != "" {
  1287. requestPath := info.RequestURLPath
  1288. if requestPath != "" {
  1289. ctx["request_path"] = requestPath
  1290. }
  1291. }
  1292. ctx[paramOverrideContextRequestHeaders] = buildNormalizedHeaders(info.RequestHeaders)
  1293. ctx[paramOverrideContextRequestHeadersRaw] = buildRawHeaders(info.RequestHeaders)
  1294. headerOverrideSource := getHeaderOverrideMap(info)
  1295. if info.UseRuntimeHeadersOverride {
  1296. headerOverrideSource = info.RuntimeHeadersOverride
  1297. }
  1298. rawHeaderOverride, normalizedHeaderOverride := buildHeaderOverrideContext(headerOverrideSource)
  1299. ctx[paramOverrideContextHeaderOverride] = rawHeaderOverride
  1300. ctx[paramOverrideContextHeaderOverrideNormalized] = normalizedHeaderOverride
  1301. ctx["retry_index"] = info.RetryIndex
  1302. ctx["is_retry"] = info.RetryIndex > 0
  1303. ctx["retry"] = map[string]interface{}{
  1304. "index": info.RetryIndex,
  1305. "is_retry": info.RetryIndex > 0,
  1306. }
  1307. if info.LastError != nil {
  1308. code := string(info.LastError.GetErrorCode())
  1309. errorType := string(info.LastError.GetErrorType())
  1310. lastError := map[string]interface{}{
  1311. "status_code": info.LastError.StatusCode,
  1312. "message": info.LastError.Error(),
  1313. "code": code,
  1314. "error_code": code,
  1315. "type": errorType,
  1316. "error_type": errorType,
  1317. "skip_retry": types.IsSkipRetryError(info.LastError),
  1318. }
  1319. ctx["last_error"] = lastError
  1320. ctx["last_error_status_code"] = info.LastError.StatusCode
  1321. ctx["last_error_message"] = info.LastError.Error()
  1322. ctx["last_error_code"] = code
  1323. ctx["last_error_type"] = errorType
  1324. }
  1325. ctx["is_channel_test"] = info.IsChannelTest
  1326. return ctx
  1327. }