override.go 46 KB

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