package websearch import ( "context" "time" "gorm.io/gorm" ) // DBUsage counts each backend's queries per UTC calendar month in // chat_web_search_usage(backend, month, used): Take increments only // while used is below the backend's cap, in one statement, so two // lookups at once can't both take the last query. type DBUsage struct { DB *gorm.DB Caps map[string]int // Now is the clock (time.Now when nil). Now func() time.Time } func (u DBUsage) month() string { now := time.Now if u.Now != nil { now = u.Now } return now().UTC().Format("2006-01") } // Take reserves one query on backend this month, while under its cap. func (u DBUsage) Take(ctx context.Context, backend string) (Reservation, bool, error) { r := Reservation{Backend: backend, Month: u.month()} limit := u.Caps[backend] if limit <= 0 { return r, false, nil } db := u.DB.WithContext(ctx) 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 { return r, false, err } res := db.Exec("UPDATE chat_web_search_usage SET used = used + 1 WHERE backend = ? AND month = ? AND used < ?", r.Backend, r.Month, limit) if res.Error != nil { return r, false, res.Error } return r, res.RowsAffected == 1, nil } // Return refunds r: its own backend and month, whatever month it is now. func (u DBUsage) Return(ctx context.Context, r Reservation) error { 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 }