override.go 39 KB

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