feat: implement AI schedule app with multi-device sync
- Qt 6 desktop client with day/month/year views, AI scheduling, and TOML settings\n- Go sync server with SQLite change stream, WebSocket notifications, and Docker deployment\n- Client outbox/LWW sync, offline retry, and dual-client integration tests\n- Linux fcitx5 setup, validation reports, and Windows MinGW preset
This commit is contained in:
@@ -0,0 +1,299 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/misaki/Schedule/server/internal/config"
|
||||
"github.com/misaki/Schedule/server/internal/model"
|
||||
"github.com/misaki/Schedule/server/internal/service"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const deviceContextKey contextKey = "device"
|
||||
|
||||
type Server struct {
|
||||
service *service.SyncService
|
||||
config config.Config
|
||||
hub *Hub
|
||||
logger *slog.Logger
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
func New(svc *service.SyncService, cfg config.Config, logger *slog.Logger) *Server {
|
||||
s := &Server{
|
||||
service: svc,
|
||||
config: cfg,
|
||||
hub: NewHub(logger),
|
||||
logger: logger,
|
||||
mux: http.NewServeMux(),
|
||||
}
|
||||
s.routes()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return s.loggingMiddleware(s.recoverMiddleware(s.mux))
|
||||
}
|
||||
|
||||
func (s *Server) routes() {
|
||||
s.mux.HandleFunc("GET /healthz", s.handleHealth)
|
||||
s.mux.HandleFunc("POST /v1/devices/register", s.handleRegister)
|
||||
s.mux.Handle("POST /v1/changes/push", s.auth(s.handlePush))
|
||||
s.mux.Handle("GET /v1/changes/pull", s.auth(s.handlePull))
|
||||
s.mux.Handle("GET /v1/export", s.auth(s.handleExport))
|
||||
s.mux.HandleFunc("GET /v1/stream", s.handleStream)
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
|
||||
}
|
||||
|
||||
type registerRequest struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type registerResponse struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Token string `json:"token"`
|
||||
LatestSeq int64 `json:"latest_seq"`
|
||||
}
|
||||
|
||||
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
var request registerRequest
|
||||
if err := decodeJSON(w, r, &request, 1<<20); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
device, token, latest, err := s.service.RegisterDevice(r.Context(), request.DeviceID, request.Name)
|
||||
if err != nil {
|
||||
s.logger.Error("register device failed", "error", err)
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, registerResponse{DeviceID: device.ID, Token: token, LatestSeq: latest})
|
||||
}
|
||||
|
||||
type pushRequest struct {
|
||||
Changes []model.ChangeInput `json:"changes"`
|
||||
}
|
||||
|
||||
type pushResponse struct {
|
||||
Accepted int `json:"accepted"`
|
||||
LastSeq int64 `json:"last_seq"`
|
||||
}
|
||||
|
||||
func (s *Server) handlePush(w http.ResponseWriter, r *http.Request) {
|
||||
device := deviceFromContext(r.Context())
|
||||
var request pushRequest
|
||||
if err := decodeJSON(w, r, &request, 16<<20); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if len(request.Changes) == 0 {
|
||||
writeJSON(w, http.StatusOK, pushResponse{Accepted: 0})
|
||||
return
|
||||
}
|
||||
if len(request.Changes) > s.config.MaxBatch {
|
||||
writeError(w, http.StatusBadRequest, "too many changes in one batch")
|
||||
return
|
||||
}
|
||||
lastSeq, err := s.service.Push(r.Context(), device.ID, request.Changes)
|
||||
if err != nil {
|
||||
status := http.StatusBadRequest
|
||||
if strings.Contains(err.Error(), "append changes") {
|
||||
status = http.StatusInternalServerError
|
||||
}
|
||||
s.logger.Error("push changes failed", "error", err)
|
||||
writeError(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
s.hub.Broadcast(lastSeq, device.ID)
|
||||
writeJSON(w, http.StatusOK, pushResponse{Accepted: len(request.Changes), LastSeq: lastSeq})
|
||||
}
|
||||
|
||||
type pullResponse struct {
|
||||
Changes []model.Change `json:"changes"`
|
||||
LatestSeq int64 `json:"latest_seq"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
func (s *Server) handlePull(w http.ResponseWriter, r *http.Request) {
|
||||
since := int64(0)
|
||||
if value := r.URL.Query().Get("since_seq"); value != "" {
|
||||
parsed, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || parsed < 0 {
|
||||
writeError(w, http.StatusBadRequest, "invalid since_seq")
|
||||
return
|
||||
}
|
||||
since = parsed
|
||||
}
|
||||
limit := 200
|
||||
if value := r.URL.Query().Get("limit"); value != "" {
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "invalid limit")
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
changes, latest, hasMore, err := s.service.Pull(r.Context(), since, limit)
|
||||
if err != nil {
|
||||
s.logger.Error("pull changes failed", "error", err)
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, pullResponse{Changes: changes, LatestSeq: latest, HasMore: hasMore})
|
||||
}
|
||||
|
||||
func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := s.service.Export(r.Context())
|
||||
if err != nil {
|
||||
s.logger.Error("export failed", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "export failed")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, data)
|
||||
}
|
||||
|
||||
func (s *Server) handleStream(w http.ResponseWriter, r *http.Request) {
|
||||
token := r.URL.Query().Get("token")
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "missing token")
|
||||
return
|
||||
}
|
||||
device, err := s.service.Authenticate(r.Context(), token)
|
||||
if errors.Is(err, service.ErrInvalidToken) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid token")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "auth failed")
|
||||
return
|
||||
}
|
||||
if !websocket.IsWebSocketUpgrade(r) {
|
||||
writeError(w, http.StatusBadRequest, "websocket upgrade required")
|
||||
return
|
||||
}
|
||||
s.hub.ServeWS(w, r, device.ID)
|
||||
}
|
||||
|
||||
func (s *Server) auth(next http.HandlerFunc) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "missing bearer token")
|
||||
return
|
||||
}
|
||||
device, err := s.service.Authenticate(r.Context(), token)
|
||||
if errors.Is(err, service.ErrInvalidToken) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid token")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.logger.Error("auth lookup failed", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "auth failed")
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), deviceContextKey, device)
|
||||
next(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func deviceFromContext(ctx context.Context) model.Device {
|
||||
device, _ := ctx.Value(deviceContextKey).(model.Device)
|
||||
return device
|
||||
}
|
||||
|
||||
func bearerToken(header string) (string, bool) {
|
||||
const prefix = "Bearer "
|
||||
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(header[len(prefix):])
|
||||
return token, token != ""
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, target any, limit int64) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return errors.New("invalid JSON body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]any{"error": message})
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Flush() {
|
||||
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func (w *statusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
hijacker, ok := w.ResponseWriter.(http.Hijacker)
|
||||
if !ok {
|
||||
return nil, nil, errors.New("underlying response writer does not support hijacking")
|
||||
}
|
||||
return hijacker.Hijack()
|
||||
}
|
||||
|
||||
func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(writer, r)
|
||||
s.logger.Info("http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", writer.status,
|
||||
"duration", time.Since(start).String())
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) recoverMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.logger.Error("panic in handler", "panic", recovered)
|
||||
writeError(w, http.StatusInternalServerError, "internal server error")
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func formatInt(value int64) string {
|
||||
return strconv.FormatInt(value, 10)
|
||||
}
|
||||
Reference in New Issue
Block a user