ratio_sync.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "strings"
  7. "sync"
  8. "time"
  9. "one-api/common"
  10. "one-api/dto"
  11. "one-api/model"
  12. "one-api/setting/ratio_setting"
  13. "github.com/gin-gonic/gin"
  14. )
  15. const (
  16. defaultTimeoutSeconds = 10
  17. defaultEndpoint = "/api/ratio_config"
  18. maxConcurrentFetches = 8
  19. )
  20. var ratioTypes = []string{"model_ratio", "completion_ratio", "cache_ratio", "model_price"}
  21. type upstreamResult struct {
  22. Name string `json:"name"`
  23. Data map[string]any `json:"data,omitempty"`
  24. Err string `json:"err,omitempty"`
  25. }
  26. func FetchUpstreamRatios(c *gin.Context) {
  27. var req dto.UpstreamRequest
  28. if err := c.ShouldBindJSON(&req); err != nil {
  29. c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": err.Error()})
  30. return
  31. }
  32. if req.Timeout <= 0 {
  33. req.Timeout = defaultTimeoutSeconds
  34. }
  35. var upstreams []dto.UpstreamDTO
  36. if len(req.ChannelIDs) > 0 {
  37. intIds := make([]int, 0, len(req.ChannelIDs))
  38. for _, id64 := range req.ChannelIDs {
  39. intIds = append(intIds, int(id64))
  40. }
  41. dbChannels, err := model.GetChannelsByIds(intIds)
  42. if err != nil {
  43. common.LogError(c.Request.Context(), "failed to query channels: "+err.Error())
  44. c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "查询渠道失败"})
  45. return
  46. }
  47. for _, ch := range dbChannels {
  48. if base := ch.GetBaseURL(); strings.HasPrefix(base, "http") {
  49. upstreams = append(upstreams, dto.UpstreamDTO{
  50. Name: ch.Name,
  51. BaseURL: strings.TrimRight(base, "/"),
  52. Endpoint: "",
  53. })
  54. }
  55. }
  56. }
  57. if len(upstreams) == 0 {
  58. c.JSON(http.StatusOK, gin.H{"success": false, "message": "无有效上游渠道"})
  59. return
  60. }
  61. var wg sync.WaitGroup
  62. ch := make(chan upstreamResult, len(upstreams))
  63. sem := make(chan struct{}, maxConcurrentFetches)
  64. client := &http.Client{Transport: &http.Transport{MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second}}
  65. for _, chn := range upstreams {
  66. wg.Add(1)
  67. go func(chItem dto.UpstreamDTO) {
  68. defer wg.Done()
  69. sem <- struct{}{}
  70. defer func() { <-sem }()
  71. endpoint := chItem.Endpoint
  72. if endpoint == "" {
  73. endpoint = defaultEndpoint
  74. } else if !strings.HasPrefix(endpoint, "/") {
  75. endpoint = "/" + endpoint
  76. }
  77. fullURL := chItem.BaseURL + endpoint
  78. ctx, cancel := context.WithTimeout(c.Request.Context(), time.Duration(req.Timeout)*time.Second)
  79. defer cancel()
  80. httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
  81. if err != nil {
  82. common.LogWarn(c.Request.Context(), "build request failed: "+err.Error())
  83. ch <- upstreamResult{Name: chItem.Name, Err: err.Error()}
  84. return
  85. }
  86. resp, err := client.Do(httpReq)
  87. if err != nil {
  88. common.LogWarn(c.Request.Context(), "http error on "+chItem.Name+": "+err.Error())
  89. ch <- upstreamResult{Name: chItem.Name, Err: err.Error()}
  90. return
  91. }
  92. defer resp.Body.Close()
  93. if resp.StatusCode != http.StatusOK {
  94. common.LogWarn(c.Request.Context(), "non-200 from "+chItem.Name+": "+resp.Status)
  95. ch <- upstreamResult{Name: chItem.Name, Err: resp.Status}
  96. return
  97. }
  98. var body struct {
  99. Success bool `json:"success"`
  100. Data map[string]any `json:"data"`
  101. Message string `json:"message"`
  102. }
  103. if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
  104. common.LogWarn(c.Request.Context(), "json decode failed from "+chItem.Name+": "+err.Error())
  105. ch <- upstreamResult{Name: chItem.Name, Err: err.Error()}
  106. return
  107. }
  108. if !body.Success {
  109. ch <- upstreamResult{Name: chItem.Name, Err: body.Message}
  110. return
  111. }
  112. ch <- upstreamResult{Name: chItem.Name, Data: body.Data}
  113. }(chn)
  114. }
  115. wg.Wait()
  116. close(ch)
  117. localData := ratio_setting.GetExposedData()
  118. var testResults []dto.TestResult
  119. var successfulChannels []struct {
  120. name string
  121. data map[string]any
  122. }
  123. for r := range ch {
  124. if r.Err != "" {
  125. testResults = append(testResults, dto.TestResult{
  126. Name: r.Name,
  127. Status: "error",
  128. Error: r.Err,
  129. })
  130. } else {
  131. testResults = append(testResults, dto.TestResult{
  132. Name: r.Name,
  133. Status: "success",
  134. })
  135. successfulChannels = append(successfulChannels, struct {
  136. name string
  137. data map[string]any
  138. }{name: r.Name, data: r.Data})
  139. }
  140. }
  141. differences := buildDifferences(localData, successfulChannels)
  142. c.JSON(http.StatusOK, gin.H{
  143. "success": true,
  144. "data": gin.H{
  145. "differences": differences,
  146. "test_results": testResults,
  147. },
  148. })
  149. }
  150. func buildDifferences(localData map[string]any, successfulChannels []struct {
  151. name string
  152. data map[string]any
  153. }) map[string]map[string]dto.DifferenceItem {
  154. differences := make(map[string]map[string]dto.DifferenceItem)
  155. allModels := make(map[string]struct{})
  156. for _, ratioType := range ratioTypes {
  157. if localRatioAny, ok := localData[ratioType]; ok {
  158. if localRatio, ok := localRatioAny.(map[string]float64); ok {
  159. for modelName := range localRatio {
  160. allModels[modelName] = struct{}{}
  161. }
  162. }
  163. }
  164. }
  165. for _, channel := range successfulChannels {
  166. for _, ratioType := range ratioTypes {
  167. if upstreamRatio, ok := channel.data[ratioType].(map[string]any); ok {
  168. for modelName := range upstreamRatio {
  169. allModels[modelName] = struct{}{}
  170. }
  171. }
  172. }
  173. }
  174. for modelName := range allModels {
  175. for _, ratioType := range ratioTypes {
  176. var localValue interface{} = nil
  177. if localRatioAny, ok := localData[ratioType]; ok {
  178. if localRatio, ok := localRatioAny.(map[string]float64); ok {
  179. if val, exists := localRatio[modelName]; exists {
  180. localValue = val
  181. }
  182. }
  183. }
  184. upstreamValues := make(map[string]interface{})
  185. hasUpstreamValue := false
  186. hasDifference := false
  187. for _, channel := range successfulChannels {
  188. var upstreamValue interface{} = nil
  189. if upstreamRatio, ok := channel.data[ratioType].(map[string]any); ok {
  190. if val, exists := upstreamRatio[modelName]; exists {
  191. upstreamValue = val
  192. hasUpstreamValue = true
  193. if localValue != nil && localValue != val {
  194. hasDifference = true
  195. } else if localValue == val {
  196. upstreamValue = "same"
  197. }
  198. }
  199. }
  200. if upstreamValue == nil && localValue == nil {
  201. upstreamValue = "same"
  202. }
  203. if localValue == nil && upstreamValue != nil && upstreamValue != "same" {
  204. hasDifference = true
  205. }
  206. upstreamValues[channel.name] = upstreamValue
  207. }
  208. shouldInclude := false
  209. if localValue != nil {
  210. if hasDifference {
  211. shouldInclude = true
  212. }
  213. } else {
  214. if hasUpstreamValue {
  215. shouldInclude = true
  216. }
  217. }
  218. if shouldInclude {
  219. if differences[modelName] == nil {
  220. differences[modelName] = make(map[string]dto.DifferenceItem)
  221. }
  222. differences[modelName][ratioType] = dto.DifferenceItem{
  223. Current: localValue,
  224. Upstreams: upstreamValues,
  225. }
  226. }
  227. }
  228. }
  229. channelHasDiff := make(map[string]bool)
  230. for _, ratioMap := range differences {
  231. for _, item := range ratioMap {
  232. for chName, val := range item.Upstreams {
  233. if val != nil && val != "same" {
  234. channelHasDiff[chName] = true
  235. }
  236. }
  237. }
  238. }
  239. for modelName, ratioMap := range differences {
  240. for ratioType, item := range ratioMap {
  241. for chName := range item.Upstreams {
  242. if !channelHasDiff[chName] {
  243. delete(item.Upstreams, chName)
  244. }
  245. }
  246. differences[modelName][ratioType] = item
  247. }
  248. }
  249. return differences
  250. }
  251. func GetSyncableChannels(c *gin.Context) {
  252. channels, err := model.GetAllChannels(0, 0, true, false)
  253. if err != nil {
  254. c.JSON(http.StatusOK, gin.H{
  255. "success": false,
  256. "message": err.Error(),
  257. })
  258. return
  259. }
  260. var syncableChannels []dto.SyncableChannel
  261. for _, channel := range channels {
  262. if channel.GetBaseURL() != "" {
  263. syncableChannels = append(syncableChannels, dto.SyncableChannel{
  264. ID: channel.Id,
  265. Name: channel.Name,
  266. BaseURL: channel.GetBaseURL(),
  267. Status: channel.Status,
  268. })
  269. }
  270. }
  271. c.JSON(http.StatusOK, gin.H{
  272. "success": true,
  273. "message": "",
  274. "data": syncableChannels,
  275. })
  276. }