| 1 | package websearch |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "time" |
| 6 | |
| 7 | "gorm.io/gorm" |
| 8 | ) |
| 9 | |
| 10 | // DBUsage counts each backend's queries per UTC calendar month in |
| 11 | // chat_web_search_usage(backend, month, used): Take increments only |
| 12 | // while used is below the backend's cap, in one statement, so two |
| 13 | // lookups at once can't both take the last query. |
| 14 | type DBUsage struct { |
| 15 | DB *gorm.DB |
| 16 | Caps map[string]int |
| 17 | // Now is the clock (time.Now when nil). |
| 18 | Now func() time.Time |
| 19 | } |
| 20 | |
| 21 | func (u DBUsage) month() string { |
| 22 | now := time.Now |
| 23 | if u.Now != nil { |
| 24 | now = u.Now |
| 25 | } |
| 26 | return now().UTC().Format("2006-01") |
| 27 | } |
| 28 | |
| 29 | // Take reserves one query on backend this month, while under its cap. |
| 30 | func (u DBUsage) Take(ctx context.Context, backend string) (Reservation, bool, error) { |
| 31 | r := Reservation{Backend: backend, Month: u.month()} |
| 32 | limit := u.Caps[backend] |
| 33 | if limit <= 0 { |
| 34 | return r, false, nil |
| 35 | } |
| 36 | db := u.DB.WithContext(ctx) |
| 37 | if err := db.Exec("INSERT INTO chat_web_search_usage (backend, month, used) VALUES (?, ?, 0) ON CONFLICT DO NOTHING", r.Backend, r.Month).Error; err != nil { |
| 38 | return r, false, err |
| 39 | } |
| 40 | res := db.Exec("UPDATE chat_web_search_usage SET used = used + 1 WHERE backend = ? AND month = ? AND used < ?", r.Backend, r.Month, limit) |
| 41 | if res.Error != nil { |
| 42 | return r, false, res.Error |
| 43 | } |
| 44 | return r, res.RowsAffected == 1, nil |
| 45 | } |
| 46 | |
| 47 | // Return refunds r: its own backend and month, whatever month it is now. |
| 48 | func (u DBUsage) Return(ctx context.Context, r Reservation) error { |
| 49 | return u.DB.WithContext(ctx).Exec("UPDATE chat_web_search_usage SET used = used - 1 WHERE backend = ? AND month = ? AND used > 0", r.Backend, r.Month).Error |
| 50 | } |
| 51 | |