package postgres import ( "context" "errors" "fmt" "strings" "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" ) var ( errFAQExportNilStore = errors.New("faq export store is unavailable") errFAQCaseIDRequired = errors.New("faq export case id is required") errFAQRecordIDRequired = errors.New("faq export record id is required") errFAQRowsAffected = errors.New("faq export RowsAffected != 1") errFAQFailureCodeInvalid = errors.New("faq export only remote_faq_table_insert_failed is accepted") ) type FAQExportRepository struct{ store *Store } var _ faqtable.ExportRepository = (*FAQExportRepository)(nil) func NewFAQExportRepository(store *Store) (*FAQExportRepository, error) { if store == nil || store.pool == nil { return nil, errFAQExportNilStore } return &FAQExportRepository{store: store}, nil } func (r *FAQExportRepository) Claim(ctx context.Context, limit, maxAttempts int, staleBefore time.Time) ([]faqtable.PendingExport, error) { if r == nil || r.store == nil || r.store.pool == nil { return nil, errFAQExportNilStore } rows, err := r.store.pool.Query(ctx, ` WITH candidates AS ( SELECT sc.id FROM support_cases sc WHERE (sc.faq_export_status = 'pending' OR (sc.faq_export_status = 'export_failed' AND (sc.faq_next_attempt_at IS NULL OR sc.faq_next_attempt_at <= NOW())) OR (sc.faq_export_status = 'exporting' AND sc.faq_last_attempt_at < $3)) AND sc.faq_export_attempts < $2 ORDER BY sc.created_at, sc.id LIMIT $1 FOR UPDATE SKIP LOCKED ), claimed AS ( UPDATE support_cases sc SET faq_export_status = 'exporting', faq_export_attempts = sc.faq_export_attempts + 1, faq_last_attempt_at = NOW(), faq_next_attempt_at = NULL, faq_failure_code = '', updated_at = NOW() FROM candidates c WHERE sc.id = c.id RETURNING sc.id, sc.faq_export_attempts, sc.tenant_key, sc.channel, sc.turn_id, sc.created_at ) SELECT cl.id, cl.faq_export_attempts, t.question, COALESCE(m.actor_name_snapshot, ''), COALESCE(m.actor_union_id_snapshot, '') FROM claimed cl JOIN turns t ON t.id = cl.turn_id AND t.tenant_key = cl.tenant_key AND t.channel = cl.channel JOIN messages m ON m.id = t.request_message_id AND m.tenant_key = cl.tenant_key AND m.channel = cl.channel ORDER BY cl.created_at, cl.id`, limit, maxAttempts, staleBefore) if err != nil { return nil, fmt.Errorf("faq export claim: %w", err) } defer rows.Close() var exports []faqtable.PendingExport for rows.Next() { var id, question, askerName, askerUnionID string var attempts int if err := rows.Scan(&id, &attempts, &question, &askerName, &askerUnionID); err != nil { return nil, fmt.Errorf("faq export claim scan: %w", err) } exports = append(exports, faqtable.PendingExport{ CaseID: id, Attempts: attempts, Row: faqtable.Row{StandardQuestion: question, OriginalQuestion: question, AskerName: askerName, AskerUnionID: askerUnionID}, }) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("faq export claim rows: %w", err) } return exports, nil } func (r *FAQExportRepository) MarkExported(ctx context.Context, caseID, recordID string) error { if strings.TrimSpace(caseID) == "" { return errFAQCaseIDRequired } if strings.TrimSpace(recordID) == "" { return errFAQRecordIDRequired } if r == nil || r.store == nil || r.store.pool == nil { return errFAQExportNilStore } tag, err := r.store.pool.Exec(ctx, ` UPDATE support_cases SET faq_export_status = 'exported', faq_record_id = $2, faq_exported_at = NOW(), faq_failure_code = '', faq_next_attempt_at = NULL, updated_at = NOW() WHERE id = $1 AND faq_export_status = 'exporting'`, caseID, recordID) if err != nil { return fmt.Errorf("faq export mark exported: %w", err) } if tag.RowsAffected() != 1 { return errFAQRowsAffected } return nil } func (r *FAQExportRepository) MarkFailed(ctx context.Context, caseID, failureCode string) error { if strings.TrimSpace(caseID) == "" { return errFAQCaseIDRequired } if failureCode != faqtable.FailureCodeRemoteInsertFailed { return errFAQFailureCodeInvalid } if r == nil || r.store == nil || r.store.pool == nil { return errFAQExportNilStore } tag, err := r.store.pool.Exec(ctx, ` UPDATE support_cases SET faq_export_status = 'export_failed', faq_failure_code = $2, faq_next_attempt_at = NOW() + CASE WHEN faq_export_attempts <= 1 THEN '5 seconds'::interval WHEN faq_export_attempts = 2 THEN '15 seconds'::interval WHEN faq_export_attempts = 3 THEN '45 seconds'::interval ELSE '5 minutes'::interval END, updated_at = NOW() WHERE id = $1 AND faq_export_status = 'exporting'`, caseID, failureCode) if err != nil { return fmt.Errorf("faq export mark failed: %w", err) } if tag.RowsAffected() != 1 { return errFAQRowsAffected } return nil }