127 lines
4.2 KiB
Go
127 lines
4.2 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
|
)
|
|
|
|
type Store struct{ pool *pgxpool.Pool }
|
|
|
|
func Open(ctx context.Context, databaseURL string) (*Store, error) {
|
|
if databaseURL == "" {
|
|
return nil, errors.New("DATABASE_URL is required")
|
|
}
|
|
pool, err := pgxpool.New(ctx, databaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open postgres: %w", err)
|
|
}
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("ping postgres: %w", err)
|
|
}
|
|
return &Store{pool: pool}, nil
|
|
}
|
|
func (s *Store) Close() {
|
|
if s != nil && s.pool != nil {
|
|
s.pool.Close()
|
|
}
|
|
}
|
|
|
|
func (s *Store) BeginTurn(ctx context.Context, turn core.Turn) (core.Turn, bool, error) {
|
|
media := turn.Media
|
|
if media == nil {
|
|
media = []core.MediaAudit{}
|
|
}
|
|
mediaJSON, err := json.Marshal(media)
|
|
if err != nil {
|
|
return core.Turn{}, false, err
|
|
}
|
|
command, err := s.pool.Exec(ctx, `INSERT INTO turns
|
|
(id, tenant_key, channel, external_message_id, session_key, question, status, media_json)
|
|
VALUES ($1,$2,$3,$4,$5,$6,'processing',$7) ON CONFLICT DO NOTHING`,
|
|
turn.ID, turn.TenantKey, turn.Channel, turn.ExternalMessageID, turn.SessionKey, turn.Question, mediaJSON)
|
|
if err != nil {
|
|
return core.Turn{}, false, err
|
|
}
|
|
if command.RowsAffected() == 1 {
|
|
return turn, true, nil
|
|
}
|
|
stored, err := s.loadTurn(ctx, turn.TenantKey, turn.Channel, turn.ExternalMessageID)
|
|
return stored, false, err
|
|
}
|
|
|
|
func (s *Store) ResolveSession(ctx context.Context, mapping core.SessionMapping, create func(context.Context) (string, error)) (string, error) {
|
|
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, mapping.SessionKey); err != nil {
|
|
return "", err
|
|
}
|
|
var sessionID string
|
|
err = tx.QueryRow(ctx, `SELECT weknora_session_id FROM session_mappings WHERE session_key=$1`, mapping.SessionKey).Scan(&sessionID)
|
|
if err == nil {
|
|
return sessionID, tx.Commit(ctx)
|
|
}
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
return "", err
|
|
}
|
|
sessionID, err = create(ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
_, err = tx.Exec(ctx, `INSERT INTO session_mappings
|
|
(session_key,tenant_key,channel,agent_id,conversation_type,external_subject_id,weknora_session_id)
|
|
VALUES($1,$2,$3,$4,$5,$6,$7)`, mapping.SessionKey, mapping.TenantKey, mapping.Channel, mapping.AgentID, string(mapping.ConversationType), mapping.ExternalSubjectID, sessionID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return sessionID, tx.Commit(ctx)
|
|
}
|
|
|
|
func (s *Store) FinishTurn(ctx context.Context, turn core.Turn) error {
|
|
references, err := json.Marshal(turn.References)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
media := turn.Media
|
|
if media == nil {
|
|
media = []core.MediaAudit{}
|
|
}
|
|
mediaJSON, err := json.Marshal(media)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = s.pool.Exec(ctx, `UPDATE turns SET weknora_session_id=$2,weknora_request_id=$3,answer=$4,references_json=$5,media_json=$6,status=$7,error_message=$8,updated_at=NOW() WHERE id=$1`, turn.ID, turn.WeKnoraSessionID, turn.WeKnoraRequestID, turn.Answer, references, mediaJSON, turn.Status, turn.ErrorMessage)
|
|
return err
|
|
}
|
|
|
|
func (s *Store) loadTurn(ctx context.Context, tenantKey, channel, messageID string) (core.Turn, error) {
|
|
var turn core.Turn
|
|
var references []byte
|
|
var mediaJSON []byte
|
|
err := s.pool.QueryRow(ctx, `SELECT id,tenant_key,channel,external_message_id,session_key,weknora_session_id,weknora_request_id,question,answer,references_json,media_json,status,error_message FROM turns WHERE tenant_key=$1 AND channel=$2 AND external_message_id=$3`, tenantKey, channel, messageID).Scan(&turn.ID, &turn.TenantKey, &turn.Channel, &turn.ExternalMessageID, &turn.SessionKey, &turn.WeKnoraSessionID, &turn.WeKnoraRequestID, &turn.Question, &turn.Answer, &references, &mediaJSON, &turn.Status, &turn.ErrorMessage)
|
|
if err != nil {
|
|
return core.Turn{}, err
|
|
}
|
|
if len(references) > 0 {
|
|
if err := json.Unmarshal(references, &turn.References); err != nil {
|
|
return core.Turn{}, err
|
|
}
|
|
}
|
|
if len(mediaJSON) > 0 {
|
|
if err := json.Unmarshal(mediaJSON, &turn.Media); err != nil {
|
|
return core.Turn{}, err
|
|
}
|
|
}
|
|
return turn, nil
|
|
}
|