This repository has been archived on 2026-04-03. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
core/server/handlers/apiconfigs.go
2026-02-16 17:00:11 +00:00

443 lines
12 KiB
Go

package handlers
import (
"database/sql"
"encoding/json"
"math"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"git.gobha.me/xcaliber/chat-switchboard/database"
"git.gobha.me/xcaliber/chat-switchboard/providers"
)
// ── Request / Response Types ────────────────
type createAPIConfigRequest struct {
Name string `json:"name" binding:"required,max=100"`
Provider string `json:"provider" binding:"required"`
Endpoint string `json:"endpoint" binding:"required"`
APIKey string `json:"api_key"`
ModelDefault string `json:"model_default,omitempty"`
Config map[string]interface{} `json:"config,omitempty"`
}
type updateAPIConfigRequest struct {
Name *string `json:"name,omitempty"`
Endpoint *string `json:"endpoint,omitempty"`
APIKey *string `json:"api_key,omitempty"`
ModelDefault *string `json:"model_default,omitempty"`
Config map[string]interface{} `json:"config,omitempty"`
IsActive *bool `json:"is_active,omitempty"`
}
type apiConfigResponse struct {
ID string `json:"id"`
UserID *string `json:"user_id"`
Name string `json:"name"`
Provider string `json:"provider"`
Endpoint string `json:"endpoint"`
HasKey bool `json:"has_key"` // Never expose the actual key
ModelDefault *string `json:"model_default"`
Config map[string]interface{} `json:"config"`
IsActive bool `json:"is_active"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// APIConfigHandler holds dependencies.
type APIConfigHandler struct{}
// NewAPIConfigHandler creates a new handler.
func NewAPIConfigHandler() *APIConfigHandler {
return &APIConfigHandler{}
}
// ── List API Configs ────────────────────────
func (h *APIConfigHandler) ListConfigs(c *gin.Context) {
userID := getUserID(c)
page, perPage, offset := parsePagination(c)
// Count: user's configs + global configs
var total int
err := database.DB.QueryRow(
`SELECT COUNT(*) FROM api_configs WHERE user_id = $1 OR user_id IS NULL`,
userID,
).Scan(&total)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to count configs"})
return
}
rows, err := database.DB.Query(`
SELECT id, user_id, name, provider, endpoint, api_key_encrypted,
model_default, config, is_active, created_at, updated_at
FROM api_configs
WHERE user_id = $1 OR user_id IS NULL
ORDER BY user_id NULLS LAST, name ASC
LIMIT $2 OFFSET $3
`, userID, perPage, offset)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list configs"})
return
}
defer rows.Close()
configs := make([]apiConfigResponse, 0)
for rows.Next() {
cfg, err := scanAPIConfig(rows)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to scan config"})
return
}
configs = append(configs, cfg)
}
c.JSON(http.StatusOK, paginatedResponse{
Data: configs,
Page: page,
PerPage: perPage,
Total: total,
TotalPages: int(math.Ceil(float64(total) / float64(perPage))),
})
}
// ── Create API Config ───────────────────────
func (h *APIConfigHandler) CreateConfig(c *gin.Context) {
userID := getUserID(c)
var req createAPIConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate provider exists
if _, err := providers.Get(req.Provider); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "unsupported provider: " + req.Provider,
"supported_providers": providers.List(),
})
return
}
configJSON := "{}"
if req.Config != nil {
b, _ := json.Marshal(req.Config)
configJSON = string(b)
}
var cfg apiConfigResponse
var apiKeyEnc *string
var configRaw string
err := database.DB.QueryRow(`
INSERT INTO api_configs (user_id, name, provider, endpoint, api_key_encrypted, model_default, config)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)
RETURNING id, user_id, name, provider, endpoint, api_key_encrypted,
model_default, config::text, is_active, created_at, updated_at
`, userID, req.Name, req.Provider, req.Endpoint, req.APIKey, req.ModelDefault, configJSON,
).Scan(
&cfg.ID, &cfg.UserID, &cfg.Name, &cfg.Provider, &cfg.Endpoint, &apiKeyEnc,
&cfg.ModelDefault, &configRaw, &cfg.IsActive, &cfg.CreatedAt, &cfg.UpdatedAt,
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create config"})
return
}
cfg.HasKey = apiKeyEnc != nil && *apiKeyEnc != ""
cfg.Config = parseJSONBConfig(configRaw)
c.JSON(http.StatusCreated, cfg)
}
// ── Get API Config ──────────────────────────
func (h *APIConfigHandler) GetConfig(c *gin.Context) {
userID := getUserID(c)
configID := c.Param("id")
row := database.DB.QueryRow(`
SELECT id, user_id, name, provider, endpoint, api_key_encrypted,
model_default, config::text, is_active, created_at, updated_at
FROM api_configs
WHERE id = $1 AND (user_id = $2 OR user_id IS NULL)
`, configID, userID)
var cfg apiConfigResponse
var apiKeyEnc *string
var configRaw string
err := row.Scan(
&cfg.ID, &cfg.UserID, &cfg.Name, &cfg.Provider, &cfg.Endpoint, &apiKeyEnc,
&cfg.ModelDefault, &configRaw, &cfg.IsActive, &cfg.CreatedAt, &cfg.UpdatedAt,
)
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "config not found"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get config"})
return
}
cfg.HasKey = apiKeyEnc != nil && *apiKeyEnc != ""
cfg.Config = parseJSONBConfig(configRaw)
c.JSON(http.StatusOK, cfg)
}
// ── Update API Config ───────────────────────
func (h *APIConfigHandler) UpdateConfig(c *gin.Context) {
userID := getUserID(c)
configID := c.Param("id")
var req updateAPIConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Verify ownership (only owner can update, not global)
var ownerID *string
err := database.DB.QueryRow(`SELECT user_id FROM api_configs WHERE id = $1`, configID).Scan(&ownerID)
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "config not found"})
return
}
if ownerID == nil || *ownerID != userID {
c.JSON(http.StatusForbidden, gin.H{"error": "cannot modify global or other user's config"})
return
}
// Dynamic update
setClauses := []string{}
args := []interface{}{}
argN := 1
addClause := func(col string, val interface{}) {
setClauses = append(setClauses, col+" = $"+strconv.Itoa(argN))
args = append(args, val)
argN++
}
if req.Name != nil {
addClause("name", *req.Name)
}
if req.Endpoint != nil {
addClause("endpoint", *req.Endpoint)
}
if req.APIKey != nil {
addClause("api_key_encrypted", *req.APIKey)
}
if req.ModelDefault != nil {
addClause("model_default", *req.ModelDefault)
}
if req.Config != nil {
b, _ := json.Marshal(req.Config)
addClause("config", string(b))
}
if req.IsActive != nil {
addClause("is_active", *req.IsActive)
}
if len(setClauses) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "no fields to update"})
return
}
query := "UPDATE api_configs SET updated_at = NOW(), "
for i, clause := range setClauses {
if i > 0 {
query += ", "
}
query += clause
}
query += " WHERE id = $" + strconv.Itoa(argN)
args = append(args, configID)
_, err = database.DB.Exec(query, args...)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update config"})
return
}
h.GetConfig(c)
}
// ── Delete API Config ───────────────────────
func (h *APIConfigHandler) DeleteConfig(c *gin.Context) {
userID := getUserID(c)
configID := c.Param("id")
// Only allow deleting own configs
result, err := database.DB.Exec(
`DELETE FROM api_configs WHERE id = $1 AND user_id = $2`,
configID, userID,
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete config"})
return
}
rows, _ := result.RowsAffected()
if rows == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "config not found or cannot delete global config"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "config deleted"})
}
// ── List Models from a Config ───────────────
func (h *APIConfigHandler) ListModels(c *gin.Context) {
userID := getUserID(c)
configID := c.Param("id")
// Load config including API key
var providerID, endpoint string
var apiKey *string
err := database.DB.QueryRow(`
SELECT provider, endpoint, api_key_encrypted
FROM api_configs
WHERE id = $1 AND (user_id = $2 OR user_id IS NULL) AND is_active = true
`, configID, userID).Scan(&providerID, &endpoint, &apiKey)
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "config not found"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load config"})
return
}
provider, err := providers.Get(providerID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
key := ""
if apiKey != nil {
key = *apiKey
}
models, err := provider.ListModels(c.Request.Context(), providers.ProviderConfig{
Endpoint: endpoint,
APIKey: key,
})
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{"error": "failed to fetch models: " + err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"config_id": configID,
"provider": providerID,
"models": models,
})
}
// ── List All Available Models (aggregate) ───
func (h *APIConfigHandler) ListAllModels(c *gin.Context) {
userID := getUserID(c)
rows, err := database.DB.Query(`
SELECT id, name, provider, endpoint, api_key_encrypted
FROM api_configs
WHERE (user_id = $1 OR user_id IS NULL) AND is_active = true
`, userID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list configs"})
return
}
defer rows.Close()
type modelEntry struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
OwnedBy string `json:"owned_by,omitempty"`
ConfigID string `json:"config_id"`
Provider string `json:"provider"`
}
allModels := make([]modelEntry, 0)
for rows.Next() {
var cfgID, name, providerID, endpoint string
var apiKey *string
if err := rows.Scan(&cfgID, &name, &providerID, &endpoint, &apiKey); err != nil {
continue
}
provider, err := providers.Get(providerID)
if err != nil {
continue
}
key := ""
if apiKey != nil {
key = *apiKey
}
models, err := provider.ListModels(c.Request.Context(), providers.ProviderConfig{
Endpoint: endpoint,
APIKey: key,
})
if err != nil {
continue // Skip configs that fail
}
for _, m := range models {
allModels = append(allModels, modelEntry{
ID: m.ID,
Name: m.Name,
OwnedBy: m.OwnedBy,
ConfigID: cfgID,
Provider: providerID,
})
}
}
c.JSON(http.StatusOK, gin.H{"models": allModels})
}
// ── Helpers ─────────────────────────────────
type scannable interface {
Scan(dest ...interface{}) error
}
func scanAPIConfig(row scannable) (apiConfigResponse, error) {
var cfg apiConfigResponse
var apiKeyEnc *string
var configRaw string
err := row.Scan(
&cfg.ID, &cfg.UserID, &cfg.Name, &cfg.Provider, &cfg.Endpoint, &apiKeyEnc,
&cfg.ModelDefault, &configRaw, &cfg.IsActive, &cfg.CreatedAt, &cfg.UpdatedAt,
)
if err != nil {
return cfg, err
}
cfg.HasKey = apiKeyEnc != nil && *apiKeyEnc != ""
cfg.Config = parseJSONBConfig(configRaw)
return cfg, nil
}
func parseJSONBConfig(raw string) map[string]interface{} {
result := make(map[string]interface{})
_ = json.Unmarshal([]byte(raw), &result)
return result
}