override.go 45 KB

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