165 lines
3.8 KiB
Go
165 lines
3.8 KiB
Go
package creator
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"database/sql"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
_ "github.com/jackc/pgx/v5/stdlib"
|
|
)
|
|
|
|
// Creator migrations use their own history table. Phase-a and hub retain a
|
|
// shared schema_migration table for their schemas, but their numeric versions
|
|
// overlap with the creator migration files and must not suppress one another.
|
|
type SecretReference struct {
|
|
ID string
|
|
Provider string
|
|
}
|
|
|
|
type SecretBridge interface {
|
|
Store(context.Context, SecretReference, string, string) error
|
|
Delete(context.Context, SecretReference, string) error
|
|
}
|
|
|
|
type Store struct {
|
|
db *sql.DB
|
|
coverDirectory string
|
|
secrets SecretBridge
|
|
// Automatic writes for one execution account stay serialized while event
|
|
// ingestion and unrelated accounts remain concurrent.
|
|
automaticLocks sync.Map // map[string]*sync.Mutex
|
|
}
|
|
|
|
func Open(ctx context.Context, databaseURL string) (*Store, error) {
|
|
db, err := sql.Open("pgx", databaseURL)
|
|
if err != nil {
|
|
return nil, errors.New("open creator database")
|
|
}
|
|
db.SetMaxOpenConns(10)
|
|
db.SetMaxIdleConns(2)
|
|
db.SetConnMaxIdleTime(5 * time.Minute)
|
|
if err := db.PingContext(ctx); err != nil {
|
|
_ = db.Close()
|
|
return nil, errors.New("connect to creator database")
|
|
}
|
|
directory := os.Getenv("CREATOR_COVER_DIR")
|
|
if directory == "" {
|
|
directory = filepath.Join(".data", "covers")
|
|
}
|
|
absolute, err := filepath.Abs(directory)
|
|
if err != nil {
|
|
_ = db.Close()
|
|
return nil, fmt.Errorf("resolve creator cover directory: %w", err)
|
|
}
|
|
store := &Store{db: db, coverDirectory: absolute}
|
|
return store, nil
|
|
}
|
|
|
|
func (s *Store) Close() error { return s.db.Close() }
|
|
|
|
func (s *Store) Ping(ctx context.Context) error { return s.db.PingContext(ctx) }
|
|
|
|
func (s *Store) SetSecretBridge(bridge SecretBridge) { s.secrets = bridge }
|
|
|
|
func (s *Store) automaticExecutionLock(accountID string) *sync.Mutex {
|
|
lock, _ := s.automaticLocks.LoadOrStore(accountID, &sync.Mutex{})
|
|
return lock.(*sync.Mutex)
|
|
}
|
|
|
|
func (s *Store) acquireAutomaticExecutionLock(ctx context.Context, accountID string) (func(), error) {
|
|
conn, err := s.db.Conn(ctx)
|
|
if err != nil {
|
|
return nil, databaseError(err)
|
|
}
|
|
if _, err := conn.ExecContext(ctx, `SELECT pg_advisory_lock(hashtextextended($1, 0))`, accountID); err != nil {
|
|
_ = conn.Close()
|
|
return nil, databaseError(err)
|
|
}
|
|
return func() { _ = conn.Close() }, nil
|
|
}
|
|
|
|
func newID(prefix string) string {
|
|
var bytes [12]byte
|
|
if _, err := rand.Read(bytes[:]); err != nil {
|
|
panic(fmt.Sprintf("generate creator id: %v", err))
|
|
}
|
|
return prefix + "-" + hex.EncodeToString(bytes[:])
|
|
}
|
|
|
|
func databaseError(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
switch pgErr.Code {
|
|
case "23505":
|
|
return ErrConflict
|
|
case "23503", "23514", "22P02":
|
|
return ErrInvalid
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
func rowError(err error) error {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return ErrNotFound
|
|
}
|
|
return databaseError(err)
|
|
}
|
|
|
|
func jsonText(value any) (string, error) {
|
|
encoded, err := json.Marshal(value)
|
|
if err != nil {
|
|
return "", fmt.Errorf("encode creator json: %w", err)
|
|
}
|
|
return string(encoded), nil
|
|
}
|
|
|
|
func decodeStringList(encoded []byte) ([]string, error) {
|
|
if len(encoded) == 0 {
|
|
return []string{}, nil
|
|
}
|
|
var result []string
|
|
if err := json.Unmarshal(encoded, &result); err != nil {
|
|
return nil, fmt.Errorf("decode creator string list: %w", err)
|
|
}
|
|
if result == nil {
|
|
result = []string{}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func nullableString(value string) any {
|
|
if value == "" {
|
|
return nil
|
|
}
|
|
return value
|
|
}
|
|
|
|
func nullableTime(value sql.NullTime) *time.Time {
|
|
if !value.Valid {
|
|
return nil
|
|
}
|
|
result := value.Time.UTC()
|
|
return &result
|
|
}
|
|
|
|
func nullableInt64(value sql.NullInt64) *int64 {
|
|
if !value.Valid {
|
|
return nil
|
|
}
|
|
result := value.Int64
|
|
return &result
|
|
}
|