cache.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package model
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math/rand"
  7. "one-api/common"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. var (
  15. TokenCacheSeconds = common.SyncFrequency
  16. UserId2GroupCacheSeconds = common.SyncFrequency
  17. UserId2QuotaCacheSeconds = common.SyncFrequency
  18. UserId2StatusCacheSeconds = common.SyncFrequency
  19. )
  20. // 仅用于定时同步缓存
  21. var token2UserId = make(map[string]int)
  22. var token2UserIdLock sync.RWMutex
  23. func cacheSetToken(token *Token) error {
  24. jsonBytes, err := json.Marshal(token)
  25. if err != nil {
  26. return err
  27. }
  28. err = common.RedisSet(fmt.Sprintf("token:%s", token.Key), string(jsonBytes), time.Duration(TokenCacheSeconds)*time.Second)
  29. if err != nil {
  30. common.SysError(fmt.Sprintf("failed to set token %s to redis: %s", token.Key, err.Error()))
  31. return err
  32. }
  33. token2UserIdLock.Lock()
  34. defer token2UserIdLock.Unlock()
  35. token2UserId[token.Key] = token.UserId
  36. return nil
  37. }
  38. // CacheGetTokenByKey 从缓存中获取 token 并续期时间,如果缓存中不存在,则从数据库中获取
  39. func CacheGetTokenByKey(key string) (*Token, error) {
  40. if !common.RedisEnabled {
  41. return GetTokenByKey(key)
  42. }
  43. var token *Token
  44. tokenObjectString, err := common.RedisGet(fmt.Sprintf("token:%s", key))
  45. if err != nil {
  46. // 如果缓存中不存在,则从数据库中获取
  47. token, err = GetTokenByKey(key)
  48. if err != nil {
  49. return nil, err
  50. }
  51. err = cacheSetToken(token)
  52. return token, nil
  53. }
  54. // 如果缓存中存在,则续期时间
  55. err = common.RedisExpire(fmt.Sprintf("token:%s", key), time.Duration(TokenCacheSeconds)*time.Second)
  56. err = json.Unmarshal([]byte(tokenObjectString), &token)
  57. return token, err
  58. }
  59. func SyncTokenCache(frequency int) {
  60. for {
  61. time.Sleep(time.Duration(frequency) * time.Second)
  62. common.SysLog("syncing tokens from database")
  63. token2UserIdLock.Lock()
  64. // 从token2UserId中获取所有的key
  65. var copyToken2UserId = make(map[string]int)
  66. for s, i := range token2UserId {
  67. copyToken2UserId[s] = i
  68. }
  69. token2UserId = make(map[string]int)
  70. token2UserIdLock.Unlock()
  71. for key := range copyToken2UserId {
  72. token, err := GetTokenByKey(key)
  73. if err != nil {
  74. // 如果数据库中不存在,则删除缓存
  75. common.SysError(fmt.Sprintf("failed to get token %s from database: %s", key, err.Error()))
  76. //delete redis
  77. err := common.RedisDel(fmt.Sprintf("token:%s", key))
  78. if err != nil {
  79. common.SysError(fmt.Sprintf("failed to delete token %s from redis: %s", key, err.Error()))
  80. }
  81. } else {
  82. // 如果数据库中存在,先检查redis
  83. _, err = common.RedisGet(fmt.Sprintf("token:%s", key))
  84. if err != nil {
  85. // 如果redis中不存在,则跳过
  86. continue
  87. }
  88. err = cacheSetToken(token)
  89. if err != nil {
  90. common.SysError(fmt.Sprintf("failed to update token %s to redis: %s", key, err.Error()))
  91. }
  92. }
  93. }
  94. }
  95. }
  96. func CacheGetUserGroup(id int) (group string, err error) {
  97. if !common.RedisEnabled {
  98. return GetUserGroup(id)
  99. }
  100. group, err = common.RedisGet(fmt.Sprintf("user_group:%d", id))
  101. if err != nil {
  102. group, err = GetUserGroup(id)
  103. if err != nil {
  104. return "", err
  105. }
  106. err = common.RedisSet(fmt.Sprintf("user_group:%d", id), group, time.Duration(UserId2GroupCacheSeconds)*time.Second)
  107. if err != nil {
  108. common.SysError("Redis set user group error: " + err.Error())
  109. }
  110. }
  111. return group, err
  112. }
  113. func CacheGetUsername(id int) (username string, err error) {
  114. if !common.RedisEnabled {
  115. return GetUsernameById(id)
  116. }
  117. username, err = common.RedisGet(fmt.Sprintf("user_name:%d", id))
  118. if err != nil {
  119. username, err = GetUsernameById(id)
  120. if err != nil {
  121. return "", err
  122. }
  123. err = common.RedisSet(fmt.Sprintf("user_name:%d", id), username, time.Duration(UserId2GroupCacheSeconds)*time.Second)
  124. if err != nil {
  125. common.SysError("Redis set user group error: " + err.Error())
  126. }
  127. }
  128. return username, err
  129. }
  130. func CacheGetUserQuota(id int) (quota int, err error) {
  131. if !common.RedisEnabled {
  132. return GetUserQuota(id)
  133. }
  134. quotaString, err := common.RedisGet(fmt.Sprintf("user_quota:%d", id))
  135. if err != nil {
  136. quota, err = GetUserQuota(id)
  137. if err != nil {
  138. return 0, err
  139. }
  140. err = common.RedisSet(fmt.Sprintf("user_quota:%d", id), fmt.Sprintf("%d", quota), time.Duration(UserId2QuotaCacheSeconds)*time.Second)
  141. if err != nil {
  142. common.SysError("Redis set user quota error: " + err.Error())
  143. }
  144. return quota, err
  145. }
  146. quota, err = strconv.Atoi(quotaString)
  147. return quota, err
  148. }
  149. func CacheUpdateUserQuota(id int) error {
  150. if !common.RedisEnabled {
  151. return nil
  152. }
  153. quota, err := GetUserQuota(id)
  154. if err != nil {
  155. return err
  156. }
  157. return cacheSetUserQuota(id, quota)
  158. }
  159. func cacheSetUserQuota(id int, quota int) error {
  160. err := common.RedisSet(fmt.Sprintf("user_quota:%d", id), fmt.Sprintf("%d", quota), time.Duration(UserId2QuotaCacheSeconds)*time.Second)
  161. return err
  162. }
  163. func CacheDecreaseUserQuota(id int, quota int) error {
  164. if !common.RedisEnabled {
  165. return nil
  166. }
  167. err := common.RedisDecrease(fmt.Sprintf("user_quota:%d", id), int64(quota))
  168. return err
  169. }
  170. func CacheIsUserEnabled(userId int) (bool, error) {
  171. if !common.RedisEnabled {
  172. return IsUserEnabled(userId)
  173. }
  174. enabled, err := common.RedisGet(fmt.Sprintf("user_enabled:%d", userId))
  175. if err == nil {
  176. return enabled == "1", nil
  177. }
  178. userEnabled, err := IsUserEnabled(userId)
  179. if err != nil {
  180. return false, err
  181. }
  182. enabled = "0"
  183. if userEnabled {
  184. enabled = "1"
  185. }
  186. err = common.RedisSet(fmt.Sprintf("user_enabled:%d", userId), enabled, time.Duration(UserId2StatusCacheSeconds)*time.Second)
  187. if err != nil {
  188. common.SysError("Redis set user enabled error: " + err.Error())
  189. }
  190. return userEnabled, err
  191. }
  192. var group2model2channels map[string]map[string][]*Channel
  193. var channelsIDM map[int]*Channel
  194. var channelSyncLock sync.RWMutex
  195. func InitChannelCache() {
  196. newChannelId2channel := make(map[int]*Channel)
  197. var channels []*Channel
  198. DB.Where("status = ?", common.ChannelStatusEnabled).Find(&channels)
  199. for _, channel := range channels {
  200. newChannelId2channel[channel.Id] = channel
  201. }
  202. var abilities []*Ability
  203. DB.Find(&abilities)
  204. groups := make(map[string]bool)
  205. for _, ability := range abilities {
  206. groups[ability.Group] = true
  207. }
  208. newGroup2model2channels := make(map[string]map[string][]*Channel)
  209. newChannelsIDM := make(map[int]*Channel)
  210. for group := range groups {
  211. newGroup2model2channels[group] = make(map[string][]*Channel)
  212. }
  213. for _, channel := range channels {
  214. newChannelsIDM[channel.Id] = channel
  215. groups := strings.Split(channel.Group, ",")
  216. for _, group := range groups {
  217. models := strings.Split(channel.Models, ",")
  218. for _, model := range models {
  219. if _, ok := newGroup2model2channels[group][model]; !ok {
  220. newGroup2model2channels[group][model] = make([]*Channel, 0)
  221. }
  222. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel)
  223. }
  224. }
  225. }
  226. // sort by priority
  227. for group, model2channels := range newGroup2model2channels {
  228. for model, channels := range model2channels {
  229. sort.Slice(channels, func(i, j int) bool {
  230. return channels[i].GetPriority() > channels[j].GetPriority()
  231. })
  232. newGroup2model2channels[group][model] = channels
  233. }
  234. }
  235. channelSyncLock.Lock()
  236. group2model2channels = newGroup2model2channels
  237. channelsIDM = newChannelsIDM
  238. channelSyncLock.Unlock()
  239. common.SysLog("channels synced from database")
  240. }
  241. func SyncChannelCache(frequency int) {
  242. for {
  243. time.Sleep(time.Duration(frequency) * time.Second)
  244. common.SysLog("syncing channels from database")
  245. InitChannelCache()
  246. }
  247. }
  248. func CacheGetRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  249. if strings.HasPrefix(model, "gpt-4-gizmo") {
  250. model = "gpt-4-gizmo-*"
  251. }
  252. // if memory cache is disabled, get channel directly from database
  253. if !common.MemoryCacheEnabled {
  254. return GetRandomSatisfiedChannel(group, model, retry)
  255. }
  256. channelSyncLock.RLock()
  257. defer channelSyncLock.RUnlock()
  258. channels := group2model2channels[group][model]
  259. if len(channels) == 0 {
  260. return nil, errors.New("channel not found")
  261. }
  262. uniquePriorities := make(map[int]bool)
  263. for _, channel := range channels {
  264. uniquePriorities[int(channel.GetPriority())] = true
  265. }
  266. var sortedUniquePriorities []int
  267. for priority := range uniquePriorities {
  268. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  269. }
  270. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  271. if retry >= len(uniquePriorities) {
  272. retry = len(uniquePriorities) - 1
  273. }
  274. targetPriority := int64(sortedUniquePriorities[retry])
  275. // get the priority for the given retry number
  276. var targetChannels []*Channel
  277. for _, channel := range channels {
  278. if channel.GetPriority() == targetPriority {
  279. targetChannels = append(targetChannels, channel)
  280. }
  281. }
  282. // 平滑系数
  283. smoothingFactor := 10
  284. // Calculate the total weight of all channels up to endIdx
  285. totalWeight := 0
  286. for _, channel := range targetChannels {
  287. totalWeight += channel.GetWeight() + smoothingFactor
  288. }
  289. // Generate a random value in the range [0, totalWeight)
  290. randomWeight := rand.Intn(totalWeight)
  291. // Find a channel based on its weight
  292. for _, channel := range targetChannels {
  293. randomWeight -= channel.GetWeight() + smoothingFactor
  294. if randomWeight < 0 {
  295. return channel, nil
  296. }
  297. }
  298. // return null if no channel is not found
  299. return nil, errors.New("channel not found")
  300. }
  301. func CacheGetChannel(id int) (*Channel, error) {
  302. if !common.MemoryCacheEnabled {
  303. return GetChannelById(id, true)
  304. }
  305. channelSyncLock.RLock()
  306. defer channelSyncLock.RUnlock()
  307. c, ok := channelsIDM[id]
  308. if !ok {
  309. return nil, errors.New(fmt.Sprintf("当前渠道# %d,已不存在", id))
  310. }
  311. return c, nil
  312. }