mirror of
https://github.com/PerpetualSoftware/pad.git
synced 2026-09-24 11:26:34 +00:00
e7f4448028
- Add /health/live (liveness) and /health/ready (readiness with DB check) endpoints - Add Store.Ping() for database connectivity verification - Create internal/logging package using stdlib log/slog - Support PAD_LOG_LEVEL (debug/info/warn/error) and PAD_LOG_FORMAT (text/json) env vars - Add structured request logging middleware replacing chi's default Logger - Migrate all log.Printf calls to slog with proper levels and key-value attrs - Exempt health probe endpoints from auth middleware
273 lines
7.2 KiB
Go
273 lines
7.2 KiB
Go
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/xarmian/pad/internal/collections"
|
|
"github.com/xarmian/pad/internal/events"
|
|
"github.com/xarmian/pad/internal/models"
|
|
)
|
|
|
|
func normalizeWorkspaceInput(input *models.WorkspaceCreate) error {
|
|
if input == nil {
|
|
return nil
|
|
}
|
|
|
|
settings, err := models.NormalizeWorkspaceSettings(input.Settings)
|
|
if err != nil {
|
|
return fmt.Errorf("invalid settings JSON: %w", err)
|
|
}
|
|
if input.Context != nil {
|
|
settings, err = models.ApplyWorkspaceContext(settings, input.Context)
|
|
if err != nil {
|
|
return fmt.Errorf("invalid workspace context: %w", err)
|
|
}
|
|
}
|
|
input.Settings = settings
|
|
return nil
|
|
}
|
|
|
|
func normalizeWorkspaceUpdateInput(input *models.WorkspaceUpdate) error {
|
|
if input == nil {
|
|
return nil
|
|
}
|
|
|
|
if input.Settings != nil {
|
|
settings, err := models.NormalizeWorkspaceSettings(*input.Settings)
|
|
if err != nil {
|
|
return fmt.Errorf("invalid settings JSON: %w", err)
|
|
}
|
|
input.Settings = &settings
|
|
}
|
|
|
|
if input.Context != nil {
|
|
base := "{}"
|
|
if input.Settings != nil {
|
|
base = *input.Settings
|
|
}
|
|
settings, err := models.ApplyWorkspaceContext(base, input.Context)
|
|
if err != nil {
|
|
return fmt.Errorf("invalid workspace context: %w", err)
|
|
}
|
|
input.Settings = &settings
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|
resp := map[string]string{"status": "ok"}
|
|
if s.version != "" {
|
|
resp["version"] = s.version
|
|
}
|
|
if s.commit != "" {
|
|
resp["commit"] = s.commit
|
|
}
|
|
if s.buildTime != "" {
|
|
resp["build_time"] = s.buildTime
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
// handleHealthLive is a lightweight liveness probe — always returns 200 if the
|
|
// process is running. Kubernetes uses this to decide whether to restart the pod.
|
|
func (s *Server) handleHealthLive(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
|
}
|
|
|
|
// handleHealthReady is a readiness probe — returns 200 only when the service
|
|
// can accept traffic (DB connection healthy). Kubernetes uses this to decide
|
|
// whether to route traffic to the pod.
|
|
func (s *Server) handleHealthReady(w http.ResponseWriter, r *http.Request) {
|
|
if err := s.store.Ping(); err != nil {
|
|
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
|
"status": "not ready",
|
|
"error": "database unavailable",
|
|
})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ready"})
|
|
}
|
|
|
|
func (s *Server) handleListTemplates(w http.ResponseWriter, r *http.Request) {
|
|
type templateInfo struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Collections []string `json:"collections"`
|
|
}
|
|
templates := collections.ListTemplates()
|
|
result := make([]templateInfo, 0, len(templates))
|
|
for _, t := range templates {
|
|
colls := make([]string, 0, len(t.Collections))
|
|
for _, c := range t.Collections {
|
|
colls = append(colls, c.Icon+" "+c.Name)
|
|
}
|
|
result = append(result, templateInfo{
|
|
Name: t.Name,
|
|
Description: t.Description,
|
|
Collections: colls,
|
|
})
|
|
}
|
|
writeJSON(w, http.StatusOK, result)
|
|
}
|
|
|
|
func (s *Server) handleListWorkspaces(w http.ResponseWriter, r *http.Request) {
|
|
user := currentUser(r)
|
|
|
|
// If a user is authenticated and is not an admin, scope to their memberships.
|
|
if user != nil && user.Role != "admin" {
|
|
workspaces, err := s.store.GetUserWorkspaces(user.ID)
|
|
if err != nil {
|
|
writeInternalError(w, err)
|
|
return
|
|
}
|
|
if workspaces == nil {
|
|
workspaces = []models.Workspace{}
|
|
}
|
|
writeJSON(w, http.StatusOK, workspaces)
|
|
return
|
|
}
|
|
|
|
// Admin users (or fresh-install with no users) see all workspaces.
|
|
workspaces, err := s.store.ListWorkspaces()
|
|
if err != nil {
|
|
writeInternalError(w, err)
|
|
return
|
|
}
|
|
if workspaces == nil {
|
|
workspaces = []models.Workspace{}
|
|
}
|
|
writeJSON(w, http.StatusOK, workspaces)
|
|
}
|
|
|
|
func (s *Server) handleCreateWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
var input models.WorkspaceCreate
|
|
if err := decodeJSON(r, &input); err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return
|
|
}
|
|
|
|
if input.Name == "" {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "Name is required")
|
|
return
|
|
}
|
|
if err := normalizeWorkspaceInput(&input); err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return
|
|
}
|
|
|
|
ws, err := s.store.CreateWorkspace(input)
|
|
if err != nil {
|
|
writeInternalError(w, err)
|
|
return
|
|
}
|
|
|
|
// Seed collections for the new workspace using the requested template
|
|
if err := s.store.SeedCollectionsFromTemplate(ws.ID, input.Template); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "Workspace created but failed to seed collections: "+err.Error())
|
|
return
|
|
}
|
|
|
|
// Add the creator as workspace owner
|
|
if userID := currentUserID(r); userID != "" {
|
|
_ = s.store.AddWorkspaceMember(ws.ID, userID, "owner")
|
|
}
|
|
|
|
writeJSON(w, http.StatusCreated, ws)
|
|
}
|
|
|
|
func (s *Server) handleGetWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
slug := chi.URLParam(r, "slug")
|
|
ws, err := s.store.GetWorkspaceBySlug(slug)
|
|
if err != nil {
|
|
writeInternalError(w, err)
|
|
return
|
|
}
|
|
if ws == nil {
|
|
writeError(w, http.StatusNotFound, "not_found", "Workspace not found")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, ws)
|
|
}
|
|
|
|
func (s *Server) handleUpdateWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
if !requireMinRole(w, r, "owner") {
|
|
return
|
|
}
|
|
slug := chi.URLParam(r, "slug")
|
|
|
|
var input models.WorkspaceUpdate
|
|
if err := decodeJSON(r, &input); err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return
|
|
}
|
|
if err := normalizeWorkspaceUpdateInput(&input); err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
|
|
return
|
|
}
|
|
|
|
ws, err := s.store.UpdateWorkspace(slug, input)
|
|
if err != nil {
|
|
writeInternalError(w, err)
|
|
return
|
|
}
|
|
if ws == nil {
|
|
writeError(w, http.StatusNotFound, "not_found", "Workspace not found")
|
|
return
|
|
}
|
|
|
|
s.publishEvent(events.WorkspaceUpdated, ws.ID, "", ws.Name, "", "", "")
|
|
|
|
writeJSON(w, http.StatusOK, ws)
|
|
}
|
|
|
|
func (s *Server) handleDeleteWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
if !requireMinRole(w, r, "owner") {
|
|
return
|
|
}
|
|
slug := chi.URLParam(r, "slug")
|
|
err := s.store.DeleteWorkspace(slug)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "not_found", "Workspace not found")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (s *Server) handleExportWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
if !requireMinRole(w, r, "owner") {
|
|
return
|
|
}
|
|
slug := chi.URLParam(r, "slug")
|
|
export, err := s.store.ExportWorkspace(slug)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "not_found", err.Error())
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s-export.json"`, slug))
|
|
writeJSON(w, http.StatusOK, export)
|
|
}
|
|
|
|
func (s *Server) handleImportWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
var data models.WorkspaceExport
|
|
if err := decodeJSON(r, &data); err != nil {
|
|
writeError(w, http.StatusBadRequest, "bad_request", "invalid export data: "+err.Error())
|
|
return
|
|
}
|
|
|
|
// Optional: override workspace name via query param
|
|
newName := r.URL.Query().Get("name")
|
|
|
|
ws, err := s.store.ImportWorkspace(&data, newName)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "import_failed", err.Error())
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusCreated, ws)
|
|
}
|