override.go 49 KB

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