Files
dobotai-platform/internal/httpapi/server.go
T
2026-07-21 10:42:28 +08:00

93 lines
3.2 KiB
Go

package httpapi
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
)
type QAService interface {
Ask(context.Context, core.QARequest) (core.QAResult, error)
}
type Server struct {
service QAService
token string
mux *http.ServeMux
}
func New(service QAService, ingressToken string) (*Server, error) {
if service == nil {
return nil, errors.New("QA service is required")
}
if strings.TrimSpace(ingressToken) == "" {
return nil, errors.New("DOBOTAI_INGRESS_TOKEN is required")
}
s := &Server{service: service, token: ingressToken, mux: http.NewServeMux()}
s.mux.HandleFunc("GET /healthz", s.health)
s.mux.HandleFunc("POST /v1/qa", s.authorize(s.ask))
return s, nil
}
func (s *Server) Handler() http.Handler { return s.mux }
func (s *Server) authorize(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
provided := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if len(provided) != len(s.token) || subtle.ConstantTimeCompare([]byte(provided), []byte(s.token)) != 1 {
writeError(w, http.StatusUnauthorized, "unauthorized")
return
}
next(w, r)
}
}
func (s *Server) health(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (s *Server) ask(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
defer r.Body.Close()
var request struct {
TenantKey string `json:"tenant_key"`
Channel string `json:"channel"`
ConversationType core.ConversationType `json:"conversation_type"`
ExternalChatID string `json:"external_chat_id"`
ExternalUserID string `json:"external_user_id"`
ExternalMessageID string `json:"external_message_id"`
SenderName string `json:"sender_name"`
MessageType string `json:"message_type"`
Query string `json:"query"`
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
if errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "request body is required")
} else {
writeError(w, http.StatusBadRequest, "invalid JSON request")
}
return
}
result, err := s.service.Ask(r.Context(), core.QARequest{TenantKey: request.TenantKey, Channel: request.Channel, ConversationType: request.ConversationType, ExternalChatID: request.ExternalChatID, ExternalUserID: request.ExternalUserID, ExternalMessageID: request.ExternalMessageID, SenderName: request.SenderName, MessageType: request.MessageType, Query: request.Query})
if err != nil {
if errors.Is(err, core.ErrTurnInProgress) {
writeError(w, http.StatusConflict, "message is already processing")
return
}
writeError(w, http.StatusBadGateway, "question processing failed")
return
}
writeJSON(w, http.StatusOK, result)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}