145 lines
5.1 KiB
Go
145 lines
5.1 KiB
Go
package models
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"database/sql/driver"
|
|
"fmt"
|
|
"math"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/tradarr/backend/internal/summaryqa"
|
|
)
|
|
|
|
type qaProviderPermit struct {
|
|
conn *sql.Conn
|
|
key string
|
|
once sync.Once
|
|
}
|
|
|
|
func (p *qaProviderPermit) Release() { p.once.Do(func() { releaseQAConn(p.conn, p.key) }) }
|
|
func releaseQAConn(conn *sql.Conn, key string) {
|
|
if key != "" {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
var unlocked bool
|
|
if err := conn.QueryRowContext(ctx, `SELECT pg_advisory_unlock(hashtextextended($1,0))`, key).Scan(&unlocked); err != nil || !unlocked {
|
|
// A session holding an unconfirmed lock must never return to the pool.
|
|
_ = conn.Raw(func(any) error { return driver.ErrBadConn })
|
|
}
|
|
}
|
|
_ = conn.Close()
|
|
}
|
|
|
|
// AcquireQAProviderCall uses a dedicated connection for the full invocation.
|
|
// Transaction-scoped account serialization makes quota check+insert atomic;
|
|
// session-scoped slots track live calls independently of turn status or TTL.
|
|
func (r *Repository) AcquireQAProviderCall(ctx context.Context, owner, summary, turn string) (summaryqa.ProviderPermit, error) {
|
|
conn, err := r.db.Conn(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
key := ""
|
|
granted := false
|
|
defer func() {
|
|
if !granted {
|
|
releaseQAConn(conn, key)
|
|
}
|
|
}()
|
|
// Re-read committed quota history after the account lock, even if the
|
|
// connection has a stricter default transaction isolation.
|
|
tx, err := conn.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer tx.Rollback()
|
|
var canonicalOwner string
|
|
if err = tx.QueryRowContext(ctx, `SELECT id FROM users WHERE id=$1 FOR UPDATE`, owner).Scan(&canonicalOwner); err == sql.ErrNoRows {
|
|
return nil, summaryqa.ErrNotFound
|
|
} else if err != nil {
|
|
return nil, err
|
|
}
|
|
var valid bool
|
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM summary_qa_turns t JOIN summary_qa_conversations c ON c.id=t.conversation_id JOIN summaries s ON s.id=c.summary_id AND s.user_id=c.user_id WHERE c.user_id=$1 AND c.summary_id=$2 AND t.id=$3 AND t.status='pending' AND t.created_at>clock_timestamp()-interval '2 minutes')`, owner, summary, turn).Scan(&valid); err != nil {
|
|
return nil, err
|
|
}
|
|
if !valid {
|
|
return nil, summaryqa.ErrConflict
|
|
}
|
|
// PostgreSQL's clock is authoritative across application instances. Read it
|
|
// after acquiring the account row, not at transaction start or from the client.
|
|
var now time.Time
|
|
if err = tx.QueryRowContext(ctx, `SELECT clock_timestamp()`).Scan(&now); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `DELETE FROM summary_qa_provider_calls WHERE user_id=$1 AND started_at<=$2`, owner, now.Add(-24*time.Hour)); err != nil {
|
|
return nil, err
|
|
}
|
|
var duplicate bool
|
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM summary_qa_provider_calls WHERE user_id=$1 AND turn_id=$2)`, owner, turn).Scan(&duplicate); err != nil {
|
|
return nil, err
|
|
}
|
|
if duplicate {
|
|
return nil, summaryqa.ErrBusy
|
|
}
|
|
retryAt := now
|
|
for _, window := range []struct {
|
|
length time.Duration
|
|
limit int
|
|
}{{time.Minute, summaryqa.CallsPerMinute}, {24 * time.Hour, summaryqa.CallsPerDay}} {
|
|
var started time.Time
|
|
err = tx.QueryRowContext(ctx, `SELECT started_at FROM summary_qa_provider_calls WHERE user_id=$1 AND started_at>$2 ORDER BY started_at DESC OFFSET $3 LIMIT 1`, owner, now.Add(-window.length), window.limit-1).Scan(&started)
|
|
if err != nil && err != sql.ErrNoRows {
|
|
return nil, err
|
|
}
|
|
if err == nil && started.Add(window.length).After(retryAt) {
|
|
retryAt = started.Add(window.length)
|
|
}
|
|
}
|
|
if retryAt.After(now) {
|
|
return nil, &summaryqa.RateLimitError{RetryAfterSeconds: max(1, int(math.Ceil(retryAt.Sub(now).Seconds())))}
|
|
}
|
|
for slot := 0; slot < summaryqa.ConcurrentCalls; slot++ {
|
|
candidate := fmt.Sprintf("tradarr.summaryqa.provider:%s:%d", canonicalOwner, slot)
|
|
var locked bool
|
|
if err = tx.QueryRowContext(ctx, `SELECT pg_try_advisory_lock(hashtextextended($1,0))`, candidate).Scan(&locked); err != nil {
|
|
return nil, err
|
|
}
|
|
if locked {
|
|
key = candidate
|
|
break
|
|
}
|
|
}
|
|
if key == "" {
|
|
return nil, &summaryqa.RateLimitError{RetryAfterSeconds: 1}
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `INSERT INTO summary_qa_provider_calls(user_id,turn_id,started_at) VALUES($1,$2,$3)`, owner, turn, now); err != nil {
|
|
return nil, err
|
|
}
|
|
if err = tx.Commit(); err != nil {
|
|
return nil, err
|
|
}
|
|
granted = true
|
|
return &qaProviderPermit{conn: conn, key: key}, nil
|
|
}
|
|
|
|
// A denied admission has not invoked the provider. Remove its pending turn so
|
|
// the same request_id can retry and denial cannot exhaust conversation turns.
|
|
func (r *Repository) CancelQAQuestion(ctx context.Context, owner, summary, turn string) error {
|
|
tx, err := r.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
c, err := lockQA(ctx, tx, owner, summary)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.ExecContext(ctx, `DELETE FROM summary_qa_turns t WHERE t.id=$1 AND t.conversation_id=$2 AND t.status='pending' AND NOT EXISTS(SELECT 1 FROM summary_qa_provider_calls p WHERE p.user_id=$3 AND p.turn_id=t.id)`, turn, c.ID, owner)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|