|
| 1 | +package model |
| 2 | + |
| 3 | +import ( |
| 4 | + "time" |
| 5 | + |
| 6 | + "gorm.io/gorm" |
| 7 | +) |
| 8 | + |
| 9 | +type AsyncUsageStatus int |
| 10 | + |
| 11 | +const ( |
| 12 | + AsyncUsageStatusNone AsyncUsageStatus = iota |
| 13 | + AsyncUsageStatusPending |
| 14 | + AsyncUsageStatusCompleted |
| 15 | + AsyncUsageStatusFailed |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + AsyncUsageDefaultPollDelay = 10 * time.Second |
| 20 | + AsyncUsageMaxPollDelay = 3 * time.Minute |
| 21 | +) |
| 22 | + |
| 23 | +type AsyncUsageInfo struct { |
| 24 | + ID int `gorm:"primaryKey" json:"id"` |
| 25 | + RequestID string `gorm:"type:char(16);index" json:"request_id"` |
| 26 | + RequestAt time.Time ` json:"request_at"` |
| 27 | + Mode int `gorm:"index" json:"mode"` |
| 28 | + Model string `gorm:"size:128" json:"model"` |
| 29 | + ChannelID int `gorm:"index" json:"channel_id"` |
| 30 | + BaseURL string `gorm:"type:text" json:"base_url,omitempty"` |
| 31 | + GroupID string `gorm:"size:64;index" json:"group_id"` |
| 32 | + TokenID int `gorm:"index" json:"token_id"` |
| 33 | + TokenName string `gorm:"size:128" json:"token_name,omitempty"` |
| 34 | + Price Price `gorm:"serializer:fastjson;type:text" json:"price"` |
| 35 | + ServiceTier string `gorm:"size:16" json:"service_tier,omitempty"` |
| 36 | + UpstreamID string `gorm:"type:varchar(256);index" json:"upstream_id"` |
| 37 | + Status AsyncUsageStatus `gorm:"index;default:1" json:"status"` |
| 38 | + Usage Usage `gorm:"serializer:fastjson;type:text" json:"usage"` |
| 39 | + Amount Amount `gorm:"embedded" json:"amount,omitempty"` |
| 40 | + Error string `gorm:"type:text" json:"error,omitempty"` |
| 41 | + RetryCount int ` json:"retry_count"` |
| 42 | + DownstreamDone bool ` json:"downstream_done"` |
| 43 | + BalanceConsumed bool ` json:"balance_consumed"` |
| 44 | + NextPollAt time.Time `gorm:"index" json:"next_poll_at"` |
| 45 | + CreatedAt time.Time ` json:"created_at"` |
| 46 | + UpdatedAt time.Time ` json:"updated_at"` |
| 47 | +} |
| 48 | + |
| 49 | +func CreateAsyncUsageInfo(info *AsyncUsageInfo) error { |
| 50 | + info.Status = AsyncUsageStatusPending |
| 51 | + info.CreatedAt = time.Now() |
| 52 | + |
| 53 | + info.UpdatedAt = info.CreatedAt |
| 54 | + if info.NextPollAt.IsZero() { |
| 55 | + info.NextPollAt = info.CreatedAt.Add(AsyncUsageDefaultPollDelay) |
| 56 | + } |
| 57 | + |
| 58 | + return LogDB.Create(info).Error |
| 59 | +} |
| 60 | + |
| 61 | +func GetPendingAsyncUsages(limit int) ([]*AsyncUsageInfo, error) { |
| 62 | + return GetPendingAsyncUsagesDue(limit, time.Now()) |
| 63 | +} |
| 64 | + |
| 65 | +func GetPendingAsyncUsagesDue( |
| 66 | + limit int, |
| 67 | + now time.Time, |
| 68 | +) ([]*AsyncUsageInfo, error) { |
| 69 | + var infos []*AsyncUsageInfo |
| 70 | + |
| 71 | + err := LogDB. |
| 72 | + Where("status = ?", int(AsyncUsageStatusPending)). |
| 73 | + Where( |
| 74 | + LogDB. |
| 75 | + Where("next_poll_at <= ?", now). |
| 76 | + Or("next_poll_at IS NULL"), |
| 77 | + ). |
| 78 | + Order("next_poll_at ASC, updated_at ASC, created_at ASC"). |
| 79 | + Limit(limit). |
| 80 | + Find(&infos).Error |
| 81 | + |
| 82 | + return infos, err |
| 83 | +} |
| 84 | + |
| 85 | +func AsyncUsageBackoffDelay( |
| 86 | + retryCount int, |
| 87 | +) time.Duration { |
| 88 | + if retryCount <= 1 { |
| 89 | + return AsyncUsageDefaultPollDelay |
| 90 | + } |
| 91 | + |
| 92 | + delay := AsyncUsageDefaultPollDelay |
| 93 | + for range retryCount - 1 { |
| 94 | + delay *= 2 |
| 95 | + if delay >= AsyncUsageMaxPollDelay { |
| 96 | + return AsyncUsageMaxPollDelay |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + return delay |
| 101 | +} |
| 102 | + |
| 103 | +func UpdateAsyncUsageInfo(info *AsyncUsageInfo) error { |
| 104 | + info.UpdatedAt = time.Now() |
| 105 | + return LogDB.Save(info).Error |
| 106 | +} |
| 107 | + |
| 108 | +func UpdateLogUsageByRequestID( |
| 109 | + requestID string, |
| 110 | + usage Usage, |
| 111 | + amount Amount, |
| 112 | +) error { |
| 113 | + var logEntry Log |
| 114 | + if err := LogDB.Where("request_id = ?", requestID).First(&logEntry).Error; err != nil { |
| 115 | + return err |
| 116 | + } |
| 117 | + |
| 118 | + logEntry.Usage = usage |
| 119 | + logEntry.Amount.Add(amount) |
| 120 | + logEntry.AsyncUsageStatus = AsyncUsageStatusCompleted |
| 121 | + |
| 122 | + return LogDB.Save(&logEntry).Error |
| 123 | +} |
| 124 | + |
| 125 | +func UpdateLogAsyncUsageStatusByRequestID( |
| 126 | + requestID string, |
| 127 | + status AsyncUsageStatus, |
| 128 | +) error { |
| 129 | + if requestID == "" { |
| 130 | + return nil |
| 131 | + } |
| 132 | + |
| 133 | + tx := LogDB. |
| 134 | + Model(&Log{}). |
| 135 | + Where("request_id = ?", requestID). |
| 136 | + Update("async_usage_status", status) |
| 137 | + if tx.Error != nil { |
| 138 | + return tx.Error |
| 139 | + } |
| 140 | + |
| 141 | + if tx.RowsAffected == 0 { |
| 142 | + return NotFoundError("log") |
| 143 | + } |
| 144 | + |
| 145 | + return nil |
| 146 | +} |
| 147 | + |
| 148 | +func CleanupFinishedAsyncUsages(olderThan time.Duration, batchSize int) error { |
| 149 | + if batchSize <= 0 { |
| 150 | + batchSize = defaultCleanLogBatchSize |
| 151 | + } |
| 152 | + |
| 153 | + cutoff := time.Now().Add(-olderThan) |
| 154 | + |
| 155 | + subQuery := LogDB. |
| 156 | + Model(&AsyncUsageInfo{}). |
| 157 | + Where( |
| 158 | + "status IN (?) AND updated_at < ?", |
| 159 | + []AsyncUsageStatus{AsyncUsageStatusCompleted, AsyncUsageStatusFailed}, |
| 160 | + cutoff, |
| 161 | + ). |
| 162 | + Limit(batchSize). |
| 163 | + Select("id") |
| 164 | + |
| 165 | + return LogDB. |
| 166 | + Session(&gorm.Session{SkipDefaultTransaction: true}). |
| 167 | + Where("id IN (?)", subQuery). |
| 168 | + Delete(&AsyncUsageInfo{}).Error |
| 169 | +} |
0 commit comments