248 lines
9.9 KiB
Go
248 lines
9.9 KiB
Go
package models
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"github.com/tradarr/backend/internal/summaryqa"
|
|
"time"
|
|
)
|
|
|
|
// SummarySourceArticle is stored only in the new temporary Q&A tables. It never
|
|
// enters aggregate outcomes, access logs or legacy article/report tables.
|
|
type SummarySourceArticle struct {
|
|
Title, Source, Content, URL string
|
|
PublishedAt *time.Time
|
|
}
|
|
|
|
var ErrInvalidRetention = errors.New("invalid_source_article_retention_days")
|
|
|
|
func ensureQA(ctx context.Context, tx *sql.Tx, owner, summary string) error {
|
|
result, err := tx.ExecContext(ctx, `INSERT INTO summary_qa_conversations(summary_id,user_id,generated_at,source_expires_at,retention_days)
|
|
SELECT s.id,s.user_id,s.generated_at,s.generated_at+make_interval(days=>u.source_article_retention_days),u.source_article_retention_days FROM summaries s JOIN users u ON u.id=s.user_id
|
|
WHERE s.id=$1 AND s.user_id=$2 ON CONFLICT(summary_id) DO NOTHING`, summary, owner)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = result.RowsAffected()
|
|
return err
|
|
}
|
|
func lockQA(ctx context.Context, tx *sql.Tx, owner, summary string) (summaryqa.Conversation, error) {
|
|
c := summaryqa.Conversation{Mode: "stateless", Messages: []summaryqa.Turn{}}
|
|
err := tx.QueryRowContext(ctx, `SELECT c.id,c.summary_id,c.source_expires_at FROM summary_qa_conversations c JOIN summaries s ON s.id=c.summary_id AND s.user_id=c.user_id WHERE c.summary_id=$1 AND c.user_id=$2 FOR UPDATE OF c`, summary, owner).Scan(&c.ID, &c.SummaryID, &c.SourceExpiresAt)
|
|
if err == sql.ErrNoRows {
|
|
return c, summaryqa.ErrNotFound
|
|
}
|
|
return c, err
|
|
}
|
|
func purgeOwnedSources(ctx context.Context, tx *sql.Tx, id string, now time.Time) error {
|
|
_, err := tx.ExecContext(ctx, `DELETE FROM summary_qa_sources a USING summary_qa_conversations c WHERE a.conversation_id=c.id AND c.id=$1 AND c.source_expires_at<=$2`, id, now)
|
|
return err
|
|
}
|
|
func qaTurns(ctx context.Context, tx *sql.Tx, id string) ([]summaryqa.Turn, error) {
|
|
rows, err := tx.QueryContext(ctx, `SELECT id,request_id,passage,question,answer,status,failure_code,created_at FROM summary_qa_turns WHERE conversation_id=$1 ORDER BY ordinal`, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
turns := []summaryqa.Turn{}
|
|
for rows.Next() {
|
|
var t summaryqa.Turn
|
|
if err = rows.Scan(&t.ID, &t.RequestID, &t.Passage, &t.Question, &t.Answer, &t.Status, &t.FailureCode, &t.CreatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
turns = append(turns, t)
|
|
}
|
|
return turns, rows.Err()
|
|
}
|
|
func (r *Repository) GetQAConversation(ctx context.Context, owner, summary string, now time.Time) (summaryqa.Conversation, error) {
|
|
tx, err := r.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return summaryqa.Conversation{}, err
|
|
}
|
|
defer tx.Rollback()
|
|
if err = ensureQA(ctx, tx, owner, summary); err != nil {
|
|
return summaryqa.Conversation{}, err
|
|
}
|
|
c, err := lockQA(ctx, tx, owner, summary)
|
|
if err != nil {
|
|
return c, err
|
|
}
|
|
if err = purgeOwnedSources(ctx, tx, c.ID, now); err != nil {
|
|
return c, err
|
|
}
|
|
c.SourcesExpired = !now.Before(c.SourceExpiresAt)
|
|
// The deadline predicate is mandatory even if physical deletion is delayed.
|
|
if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM summary_qa_sources a JOIN summary_qa_conversations c ON c.id=a.conversation_id WHERE c.id=$1 AND c.source_expires_at>$2`, c.ID, now).Scan(&c.SourceCount); err != nil {
|
|
return c, err
|
|
}
|
|
c.Messages, err = qaTurns(ctx, tx, c.ID)
|
|
if err != nil {
|
|
return c, err
|
|
}
|
|
return c, tx.Commit()
|
|
}
|
|
func (r *Repository) BeginQAQuestion(ctx context.Context, owner, summary string, q summaryqa.Question, now time.Time) (summaryqa.Work, error) {
|
|
tx, err := r.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return summaryqa.Work{}, err
|
|
}
|
|
defer tx.Rollback()
|
|
if err = ensureQA(ctx, tx, owner, summary); err != nil {
|
|
return summaryqa.Work{}, err
|
|
}
|
|
c, err := lockQA(ctx, tx, owner, summary)
|
|
if err != nil {
|
|
return summaryqa.Work{}, err
|
|
}
|
|
if err = purgeOwnedSources(ctx, tx, c.ID, now); err != nil {
|
|
return summaryqa.Work{}, err
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `UPDATE summary_qa_turns SET status='failed',failure_code='qa_provider_failed' WHERE conversation_id=$1 AND status='pending' AND created_at<=$2`, c.ID, now.Add(-summaryqa.PendingLifetime)); err != nil {
|
|
return summaryqa.Work{}, err
|
|
}
|
|
turns, err := qaTurns(ctx, tx, c.ID)
|
|
if err != nil {
|
|
return summaryqa.Work{}, err
|
|
}
|
|
work := summaryqa.Work{Conversation: c, History: []summaryqa.Exchange{}}
|
|
busy := false
|
|
for _, turn := range turns {
|
|
if turn.RequestID == q.RequestID {
|
|
if turn.Passage != q.Passage || turn.Question != q.Question {
|
|
return work, summaryqa.ErrConflict
|
|
}
|
|
if turn.Status == "pending" {
|
|
return work, summaryqa.ErrBusy
|
|
}
|
|
work.Turn = turn
|
|
work.Replay = true
|
|
return work, tx.Commit()
|
|
}
|
|
if turn.Status == "pending" {
|
|
busy = true
|
|
}
|
|
if turn.Status == "answered" {
|
|
work.History = append(work.History, summaryqa.Exchange{Passage: turn.Passage, Question: turn.Question, Answer: turn.Answer})
|
|
}
|
|
}
|
|
if busy {
|
|
return work, summaryqa.ErrBusy
|
|
}
|
|
if len(turns) >= summaryqa.MaxTurns {
|
|
return work, summaryqa.ErrLimit
|
|
}
|
|
if err = tx.QueryRowContext(ctx, `SELECT s.content,u.language FROM summaries s JOIN users u ON u.id=s.user_id WHERE s.id=$1 AND s.user_id=$2`, summary, owner).Scan(&work.Summary, &work.Language); err != nil {
|
|
return work, err
|
|
}
|
|
work.Turn = summaryqa.Turn{RequestID: q.RequestID, Passage: q.Passage, Question: q.Question, Status: "pending", CreatedAt: now}
|
|
err = tx.QueryRowContext(ctx, `INSERT INTO summary_qa_turns(conversation_id,request_id,passage,question,status,created_at,ordinal) VALUES($1,$2,$3,$4,'pending',$5,$6) RETURNING id`, c.ID, q.RequestID, q.Passage, q.Question, now, len(turns)+1).Scan(&work.Turn.ID)
|
|
if err != nil {
|
|
return work, err
|
|
}
|
|
return work, tx.Commit()
|
|
}
|
|
func (r *Repository) FinishQAQuestion(ctx context.Context, owner, summary, turnID, answer, code string, now time.Time) (summaryqa.Turn, error) {
|
|
tx, err := r.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return summaryqa.Turn{}, err
|
|
}
|
|
defer tx.Rollback()
|
|
c, err := lockQA(ctx, tx, owner, summary)
|
|
if err != nil {
|
|
return summaryqa.Turn{}, err
|
|
}
|
|
status := "answered"
|
|
if code != "" {
|
|
status = "failed"
|
|
answer = ""
|
|
}
|
|
var t summaryqa.Turn
|
|
err = tx.QueryRowContext(ctx, `UPDATE summary_qa_turns SET answer=$1,status=$2,failure_code=$3 WHERE id=$4 AND conversation_id=$5 AND status='pending' AND created_at>$6 RETURNING id,request_id,passage,question,answer,status,failure_code,created_at`, answer, status, code, turnID, c.ID, now.Add(-summaryqa.PendingLifetime)).Scan(&t.ID, &t.RequestID, &t.Passage, &t.Question, &t.Answer, &t.Status, &t.FailureCode, &t.CreatedAt)
|
|
if err == sql.ErrNoRows {
|
|
return t, summaryqa.ErrConflict
|
|
}
|
|
if err != nil {
|
|
return t, err
|
|
}
|
|
return t, tx.Commit()
|
|
}
|
|
func (r *Repository) DeleteQAConversation(ctx context.Context, owner, summary string) error {
|
|
tx, err := r.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
var id string
|
|
if err = tx.QueryRowContext(ctx, `SELECT id FROM summaries WHERE id=$1 AND user_id=$2`, summary, owner).Scan(&id); err == sql.ErrNoRows {
|
|
return summaryqa.ErrNotFound
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
// Retain only the immutable identity/deadline metadata. Erasing content must
|
|
// not let a subsequent read extend the generation's captured retention.
|
|
c, lockErr := lockQA(ctx, tx, owner, summary)
|
|
if errors.Is(lockErr, summaryqa.ErrNotFound) {
|
|
return tx.Commit()
|
|
}
|
|
if lockErr != nil {
|
|
return lockErr
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `DELETE FROM summary_qa_sources WHERE conversation_id=$1`, c.ID); err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.ExecContext(ctx, `DELETE FROM summary_qa_turns WHERE conversation_id=$1`, c.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
func (r *Repository) PurgeExpiredQASources(ctx context.Context, now time.Time) error {
|
|
_, err := r.db.ExecContext(ctx, `DELETE FROM summary_qa_sources a USING summary_qa_conversations c WHERE a.conversation_id=c.id AND c.source_expires_at<=$1`, now)
|
|
return err
|
|
}
|
|
func (r *Repository) ResolveQAModel(ctx context.Context, owner, summary string) (ResolvedSummaryModel, error) {
|
|
var m ResolvedSummaryModel
|
|
err := r.db.QueryRowContext(ctx, `SELECT m.id,p.id,p.name,m.model,p.endpoint,p.api_key_encrypted FROM summaries s JOIN ai_provider_models m ON m.id=s.summary_model_id JOIN ai_providers p ON p.id=m.provider_id WHERE s.id=$1 AND s.user_id=$2 AND m.enabled`, summary, owner).Scan(&m.ID, &m.ProviderID, &m.Provider, &m.Model, &m.Endpoint, &m.APIKeyEncrypted)
|
|
if err != nil || m.Model == "" {
|
|
return m, summaryqa.ErrModel
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
func (r *Repository) saveQASources(ctx context.Context, tx *sql.Tx, owner string, s *Summary, sources []SummarySourceArticle, days int) error {
|
|
if days == 0 {
|
|
days = 7
|
|
}
|
|
if days < 1 || days > 30 {
|
|
return ErrInvalidRetention
|
|
}
|
|
// A decrease during generation takes effect; an increase cannot prolong the
|
|
// duration captured by generation input. Serialize with preference updates.
|
|
var current int
|
|
if err := tx.QueryRowContext(ctx, `SELECT source_article_retention_days FROM users WHERE id=$1 FOR SHARE`, owner).Scan(¤t); err != nil {
|
|
return err
|
|
}
|
|
if current < days {
|
|
days = current
|
|
}
|
|
size := 0
|
|
for _, a := range sources {
|
|
size += len(a.Title) + len(a.Content) + len(a.URL) + len(a.Source)
|
|
}
|
|
if len(sources) > 2000 || size > 32<<20 {
|
|
return errors.New("qa_source_storage_limit")
|
|
}
|
|
var conversation string
|
|
err := tx.QueryRowContext(ctx, `INSERT INTO summary_qa_conversations(summary_id,user_id,generated_at,source_expires_at,retention_days) VALUES($1,$2,$3,$3::timestamptz+make_interval(days=>$4),$4) RETURNING id`, s.ID, owner, s.GeneratedAt, days).Scan(&conversation)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for i, a := range sources {
|
|
if _, err = tx.ExecContext(ctx, `INSERT INTO summary_qa_sources(conversation_id,article_index,title,source,content,url,published_at) SELECT $1,$2,$3,$4,$5,$6,$7 WHERE EXISTS(SELECT 1 FROM summary_qa_conversations WHERE id=$1 AND source_expires_at>NOW())`, conversation, i, a.Title, a.Source, a.Content, a.URL, a.PublishedAt); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|