89 lines
2.4 KiB
Go
89 lines
2.4 KiB
Go
package ai
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"time"
|
|
|
|
openai "github.com/sashabaranov/go-openai"
|
|
"github.com/tradarr/backend/internal/models"
|
|
)
|
|
|
|
var (
|
|
ErrConnectionUnsupported = errors.New("auth_check_unsupported")
|
|
ErrConnectionAuth = errors.New("auth_rejected")
|
|
ErrConnectionUnavailable = errors.New("unavailable")
|
|
ErrConnectionNotFound = errors.New("not_found")
|
|
ErrConnectionLocal = errors.New("internal_error")
|
|
)
|
|
|
|
type ConnectionRepository interface {
|
|
GetAIProviderByID(string) (*models.AIProvider, error)
|
|
}
|
|
type ConnectionDecryptor interface{ Decrypt(string) (string, error) }
|
|
type ConnectionTester struct {
|
|
repo ConnectionRepository
|
|
enc ConnectionDecryptor
|
|
build func(string, string, string) (Provider, error)
|
|
}
|
|
|
|
func NewConnectionTester(repo ConnectionRepository, enc ConnectionDecryptor, build func(string, string, string) (Provider, error)) *ConnectionTester {
|
|
return &ConnectionTester{repo, enc, build}
|
|
}
|
|
|
|
// Test never propagates provider/configuration errors or model names to callers.
|
|
func (t *ConnectionTester) Test(ctx context.Context, id string) error {
|
|
p, err := t.repo.GetAIProviderByID(id)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return ErrConnectionNotFound
|
|
}
|
|
if err != nil {
|
|
return ErrConnectionLocal
|
|
}
|
|
if p == nil {
|
|
return ErrConnectionNotFound
|
|
}
|
|
key := ""
|
|
if p.APIKeyEncrypted != "" {
|
|
if t.enc == nil {
|
|
return ErrConnectionLocal
|
|
}
|
|
key, err = t.enc.Decrypt(p.APIKeyEncrypted)
|
|
if err != nil {
|
|
return ErrConnectionLocal
|
|
}
|
|
}
|
|
provider, err := t.build(p.Name, key, p.Endpoint)
|
|
if err != nil || provider == nil {
|
|
return ErrConnectionLocal
|
|
}
|
|
// Static model catalogs do not prove authentication. Keep their discovery
|
|
// behavior available to other callers without claiming connection success.
|
|
if capability, ok := provider.(interface{ SupportsAuthCheck() bool }); ok && !capability.SupportsAuthCheck() {
|
|
return ErrConnectionUnsupported
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
|
defer cancel()
|
|
_, err = provider.ListModels(ctx)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var local *summaryHTTPError
|
|
var api *openai.APIError
|
|
var request *openai.RequestError
|
|
status := 0
|
|
switch {
|
|
case errors.As(err, &local):
|
|
status = local.status
|
|
case errors.As(err, &api):
|
|
status = api.HTTPStatusCode
|
|
case errors.As(err, &request):
|
|
status = request.HTTPStatusCode
|
|
}
|
|
if status == 401 || status == 403 {
|
|
return ErrConnectionAuth
|
|
}
|
|
return ErrConnectionUnavailable
|
|
}
|