Backend Phase C: Sync-Kern + Caddy behind-proxy
Sync-Kern:
- internal/sync/hlc.go: Hybrid Logical Clock (wall_ms<<16|counter)
Tick/Now/After, global mutex, strikt monoton + kausal korrekt
- internal/sync/hlc_test.go: Unit-Tests (monoton, kausal, keine Duplikate)
Store-Schicht:
- internal/store/opstore.go: AppendOps idempotent via UNIQUE(client_id,
client_seq) ON CONFLICT DO NOTHING; LWW-Projektion (list_create/
rename/delete, item_add/update/remove) in derselben Transaktion;
PullOps mit Cursor (seq > since, 500er Pages)
- internal/store/liststore.go: CreateList / GetLists / GetList
- internal/store/itemstore.go: GetItems (nicht-gelöschte Items)
- internal/store/suggeststore.go: Search (pg_trgm + LIKE-fallback, 10)
HTTP-Handler:
- internal/httpapi/lists.go: GET/POST /api/lists, GET /api/lists/{id}
- internal/httpapi/ops.go: POST /api/lists/{id}/ops (Push),
GET /api/lists/{id}/ops (Pull ?since=)
- internal/httpapi/suggest.go: GET /api/suggestions?q=
- internal/httpapi/api.go: alle Routen verdrahtet (RequireAuth)
Deployment:
- deploy/Caddyfile.behind-proxy: auto_https off, trusted_proxies
- deploy/Caddyfile: X-Forwarded-Proto hinzugefügt, Kommentar aktualisiert
- deploy/docker-compose.yml: CADDY_HTTP_PORT + CADDY_HTTPS_PORT
- deploy/.env.example: Caddy-Port-Variablen dokumentiert
go build ./... && go vet ./... && go test ./... ✅
HLC-Tests: monoton, kausal, keine Duplikate ✅
AGENTS.md: Phase C vollständig ✅
This commit is contained in:
parent
a5ef8cf3ba
commit
895725b5e5
15 changed files with 1257 additions and 51 deletions
|
|
@ -7,36 +7,48 @@ import (
|
|||
|
||||
"github.com/mitbringsl/backend/internal/auth"
|
||||
"github.com/mitbringsl/backend/internal/config"
|
||||
"github.com/mitbringsl/backend/internal/store"
|
||||
)
|
||||
|
||||
// API bundles all handler groups and wires the router.
|
||||
// Handler groups are added in subsequent phases (lists, items, suggestions).
|
||||
type API struct {
|
||||
cfg *config.Config
|
||||
pool *pgxpool.Pool
|
||||
|
||||
health *HealthHandler
|
||||
auth *AuthHandler
|
||||
health *HealthHandler
|
||||
auth *AuthHandler
|
||||
lists *ListHandler
|
||||
ops *OpsHandler
|
||||
suggest *SuggestHandler
|
||||
}
|
||||
|
||||
// NewAPI constructs the API with all handler groups.
|
||||
func NewAPI(cfg *config.Config, pool *pgxpool.Pool) *API {
|
||||
// Auth stores
|
||||
users := auth.NewUserStore(pool)
|
||||
sessions := auth.NewSessionStore(pool, auth.SessionConfig{
|
||||
TokenBytes: cfg.SessionTokenBytes,
|
||||
TTL: cfg.SessionTokenTTL,
|
||||
})
|
||||
oidcSvc := auth.NewOIDCService(buildProviders(cfg))
|
||||
// When no provider is enabled, pass nil so the endpoint returns a clear
|
||||
// "OIDC disabled" message instead of "unknown provider" for every request.
|
||||
if len(oidcSvc.Providers()) == 0 {
|
||||
oidcSvc = nil
|
||||
}
|
||||
|
||||
// Sync stores
|
||||
listStore := store.NewListStore(pool)
|
||||
itemStore := store.NewItemStore(pool)
|
||||
opStore := store.NewOpStore(pool)
|
||||
suggestStore := store.NewSuggestStore(pool)
|
||||
|
||||
return &API{
|
||||
cfg: cfg,
|
||||
pool: pool,
|
||||
health: &HealthHandler{Pool: pool},
|
||||
auth: NewAuthHandler(users, sessions, oidcSvc, cfg),
|
||||
cfg: cfg,
|
||||
pool: pool,
|
||||
health: &HealthHandler{Pool: pool},
|
||||
auth: NewAuthHandler(users, sessions, oidcSvc, cfg),
|
||||
lists: NewListHandler(listStore, itemStore),
|
||||
ops: NewOpsHandler(opStore, listStore),
|
||||
suggest: NewSuggestHandler(suggestStore),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -67,11 +79,13 @@ func (a *API) Handler() http.Handler {
|
|||
mux.HandleFunc("POST /auth/oidc", a.auth.OIDC)
|
||||
mux.HandleFunc("POST /auth/logout", a.auth.Logout)
|
||||
|
||||
// --- authenticated API endpoints (added in Phase C) ---
|
||||
// mux.HandleFunc("GET /api/lists", a.RequireAuth(http.HandlerFunc(a.lists.List)))
|
||||
// mux.HandleFunc("GET /api/lists/{id}/ops", a.RequireAuth(http.HandlerFunc(a.items.PullOps)))
|
||||
// mux.HandleFunc("POST /api/lists/{id}/ops", a.RequireAuth(http.HandlerFunc(a.items.PushOps)))
|
||||
// mux.HandleFunc("GET /api/suggestions", a.RequireAuth(http.HandlerFunc(a.suggest.Suggest)))
|
||||
// --- authenticated API endpoints ---
|
||||
mux.Handle("GET /api/lists", a.RequireAuth(http.HandlerFunc(a.lists.List)))
|
||||
mux.Handle("POST /api/lists", a.RequireAuth(http.HandlerFunc(a.lists.Create)))
|
||||
mux.Handle("GET /api/lists/{id}", a.RequireAuth(http.HandlerFunc(a.lists.Get)))
|
||||
mux.Handle("POST /api/lists/{id}/ops", a.RequireAuth(http.HandlerFunc(a.ops.Push)))
|
||||
mux.Handle("GET /api/lists/{id}/ops", a.RequireAuth(http.HandlerFunc(a.ops.Pull)))
|
||||
mux.Handle("GET /api/suggestions", a.RequireAuth(http.HandlerFunc(a.suggest.Search)))
|
||||
|
||||
return Chain(
|
||||
mux,
|
||||
|
|
|
|||
162
backend/internal/httpapi/lists.go
Normal file
162
backend/internal/httpapi/lists.go
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/mitbringsl/backend/internal/store"
|
||||
)
|
||||
|
||||
// ListHandler handles the /api/lists endpoints.
|
||||
type ListHandler struct {
|
||||
lists *store.ListStore
|
||||
items *store.ItemStore
|
||||
}
|
||||
|
||||
// NewListHandler creates a ListHandler with the given stores.
|
||||
func NewListHandler(lists *store.ListStore, items *store.ItemStore) *ListHandler {
|
||||
return &ListHandler{lists: lists, items: items}
|
||||
}
|
||||
|
||||
// --- request / response types -----------------------------------------------
|
||||
|
||||
type createListRequest struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type listDTO struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
HLCTS int64 `json:"hlc_ts"`
|
||||
}
|
||||
|
||||
type listDetailDTO struct {
|
||||
listDTO
|
||||
Items []store.Item `json:"items"`
|
||||
}
|
||||
|
||||
type listListResponse struct {
|
||||
Lists []listDTO `json:"lists"`
|
||||
}
|
||||
|
||||
// --- handlers ---------------------------------------------------------------
|
||||
|
||||
// List returns all non-deleted lists for the authenticated user.
|
||||
// GET /api/lists
|
||||
func (h *ListHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := userIDFromCtx(r)
|
||||
if !ok {
|
||||
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
|
||||
return
|
||||
}
|
||||
|
||||
ls, err := h.lists.GetLists(r.Context(), userID)
|
||||
if err != nil {
|
||||
slog.Error("list lists failed", "error", err, "user_id", userID)
|
||||
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load lists.")
|
||||
return
|
||||
}
|
||||
|
||||
dtos := make([]listDTO, len(ls))
|
||||
for i, l := range ls {
|
||||
dtos[i] = listDTO{
|
||||
ID: l.ID.String(),
|
||||
Name: l.Name,
|
||||
UpdatedAt: l.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
HLCTS: l.HLCTS,
|
||||
}
|
||||
}
|
||||
renderJSON(w, http.StatusOK, listListResponse{Lists: dtos})
|
||||
}
|
||||
|
||||
// Create creates a new list for the authenticated user.
|
||||
// POST /api/lists
|
||||
func (h *ListHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := userIDFromCtx(r)
|
||||
if !ok {
|
||||
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
|
||||
return
|
||||
}
|
||||
|
||||
var req createListRequest
|
||||
if !decodeJSON(w, r, &req) {
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(req.Name)
|
||||
if name == "" {
|
||||
renderError(w, http.StatusBadRequest, "Bad request", "List name must not be empty.")
|
||||
return
|
||||
}
|
||||
|
||||
l, err := h.lists.CreateList(r.Context(), userID, name)
|
||||
if err != nil {
|
||||
slog.Error("create list failed", "error", err, "user_id", userID)
|
||||
renderError(w, http.StatusInternalServerError, "Internal error", "Could not create list.")
|
||||
return
|
||||
}
|
||||
renderJSON(w, http.StatusCreated, listDTO{
|
||||
ID: l.ID.String(),
|
||||
Name: l.Name,
|
||||
UpdatedAt: l.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
HLCTS: l.HLCTS,
|
||||
})
|
||||
}
|
||||
|
||||
// Get returns a single list with its items.
|
||||
// GET /api/lists/{id}
|
||||
func (h *ListHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := userIDFromCtx(r)
|
||||
if !ok {
|
||||
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
|
||||
return
|
||||
}
|
||||
|
||||
listID, err := uuid.Parse(r.PathValue("id"))
|
||||
if err != nil {
|
||||
renderError(w, http.StatusBadRequest, "Bad request", "Invalid list ID.")
|
||||
return
|
||||
}
|
||||
|
||||
l, err := h.lists.GetList(r.Context(), listID, userID)
|
||||
if err != nil {
|
||||
if !apiError(w, err) {
|
||||
slog.Error("get list failed", "error", err, "list_id", listID)
|
||||
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load list.")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
its, err := h.items.GetItems(r.Context(), listID)
|
||||
if err != nil {
|
||||
slog.Error("get items failed", "error", err, "list_id", listID)
|
||||
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load items.")
|
||||
return
|
||||
}
|
||||
if its == nil {
|
||||
its = []store.Item{}
|
||||
}
|
||||
|
||||
renderJSON(w, http.StatusOK, listDetailDTO{
|
||||
listDTO: listDTO{
|
||||
ID: l.ID.String(),
|
||||
Name: l.Name,
|
||||
UpdatedAt: l.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
HLCTS: l.HLCTS,
|
||||
},
|
||||
Items: its,
|
||||
})
|
||||
}
|
||||
|
||||
// userIDFromCtx extracts the user UUID from the request context (set by RequireAuth).
|
||||
func userIDFromCtx(r *http.Request) (uuid.UUID, bool) {
|
||||
v := r.Context().Value(ctxKeyUserID)
|
||||
if v == nil {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
id, ok := v.(uuid.UUID)
|
||||
return id, ok
|
||||
}
|
||||
147
backend/internal/httpapi/ops.go
Normal file
147
backend/internal/httpapi/ops.go
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/mitbringsl/backend/internal/store"
|
||||
)
|
||||
|
||||
// OpsHandler handles push and pull of op_log entries.
|
||||
type OpsHandler struct {
|
||||
ops *store.OpStore
|
||||
lists *store.ListStore
|
||||
}
|
||||
|
||||
// NewOpsHandler creates an OpsHandler with the given stores.
|
||||
func NewOpsHandler(ops *store.OpStore, lists *store.ListStore) *OpsHandler {
|
||||
return &OpsHandler{ops: ops, lists: lists}
|
||||
}
|
||||
|
||||
// --- request / response types -----------------------------------------------
|
||||
|
||||
type pushRequest struct {
|
||||
ClientID uuid.UUID `json:"client_id"`
|
||||
Ops []store.IncomingOp `json:"ops"`
|
||||
}
|
||||
|
||||
type pushResponse struct {
|
||||
Results []store.OpResult `json:"results"`
|
||||
}
|
||||
|
||||
type pullResponse struct {
|
||||
Ops []store.Op `json:"ops"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
// --- handlers ---------------------------------------------------------------
|
||||
|
||||
// Push accepts a batch of ops from the client, inserts them idempotently into
|
||||
// op_log, applies the LWW projection, and returns the server-assigned seq+hlc
|
||||
// for each op.
|
||||
//
|
||||
// POST /api/lists/{id}/ops
|
||||
func (h *OpsHandler) Push(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := userIDFromCtx(r)
|
||||
if !ok {
|
||||
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
|
||||
return
|
||||
}
|
||||
|
||||
listID, err := uuid.Parse(r.PathValue("id"))
|
||||
if err != nil {
|
||||
renderError(w, http.StatusBadRequest, "Bad request", "Invalid list ID.")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the user owns (or is a member of) the list.
|
||||
if _, err := h.lists.GetList(r.Context(), listID, userID); err != nil {
|
||||
if !apiError(w, err) {
|
||||
renderError(w, http.StatusNotFound, "Not found", "List not found.")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var req pushRequest
|
||||
if !decodeJSON(w, r, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.ClientID == uuid.Nil {
|
||||
renderError(w, http.StatusBadRequest, "Bad request", "client_id must be a non-nil UUID.")
|
||||
return
|
||||
}
|
||||
if len(req.Ops) == 0 {
|
||||
renderJSON(w, http.StatusOK, pushResponse{Results: []store.OpResult{}})
|
||||
return
|
||||
}
|
||||
maxBatch := store.MaxPushBatch()
|
||||
if len(req.Ops) > maxBatch {
|
||||
renderError(w, http.StatusBadRequest, "Bad request",
|
||||
fmt.Sprintf("Too many ops in a single request (max %d).", maxBatch))
|
||||
return
|
||||
}
|
||||
|
||||
results, err := h.ops.AppendOps(r.Context(), listID, userID, req.ClientID, req.Ops)
|
||||
if err != nil {
|
||||
slog.Error("push ops failed", "error", err, "list_id", listID, "user_id", userID)
|
||||
renderError(w, http.StatusInternalServerError, "Internal error", "Could not store ops.")
|
||||
return
|
||||
}
|
||||
renderJSON(w, http.StatusOK, pushResponse{Results: results})
|
||||
}
|
||||
|
||||
// Pull returns ops for a list since a given server seq cursor.
|
||||
//
|
||||
// GET /api/lists/{id}/ops?since=0
|
||||
func (h *OpsHandler) Pull(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := userIDFromCtx(r)
|
||||
if !ok {
|
||||
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
|
||||
return
|
||||
}
|
||||
|
||||
listID, err := uuid.Parse(r.PathValue("id"))
|
||||
if err != nil {
|
||||
renderError(w, http.StatusBadRequest, "Bad request", "Invalid list ID.")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify list access.
|
||||
if _, err := h.lists.GetList(r.Context(), listID, userID); err != nil {
|
||||
if !apiError(w, err) {
|
||||
renderError(w, http.StatusNotFound, "Not found", "List not found.")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
since := int64(0)
|
||||
if s := r.URL.Query().Get("since"); s != "" {
|
||||
v, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil || v < 0 {
|
||||
renderError(w, http.StatusBadRequest, "Bad request", "since must be a non-negative integer.")
|
||||
return
|
||||
}
|
||||
since = v
|
||||
}
|
||||
|
||||
ops, err := h.ops.PullOps(r.Context(), listID, since)
|
||||
if err != nil {
|
||||
slog.Error("pull ops failed", "error", err, "list_id", listID, "since", since)
|
||||
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load ops.")
|
||||
return
|
||||
}
|
||||
if ops == nil {
|
||||
ops = []store.Op{}
|
||||
}
|
||||
|
||||
// has_more is true when we returned exactly the page-size limit.
|
||||
// The client should pull again with the last returned seq.
|
||||
hasMore := len(ops) == 500 // pullPageSize is 500 in opstore.go
|
||||
|
||||
renderJSON(w, http.StatusOK, pullResponse{Ops: ops, HasMore: hasMore})
|
||||
}
|
||||
47
backend/internal/httpapi/suggest.go
Normal file
47
backend/internal/httpapi/suggest.go
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/mitbringsl/backend/internal/store"
|
||||
)
|
||||
|
||||
// SuggestHandler handles the /api/suggestions endpoint.
|
||||
type SuggestHandler struct {
|
||||
suggest *store.SuggestStore
|
||||
}
|
||||
|
||||
// NewSuggestHandler creates a SuggestHandler backed by the given store.
|
||||
func NewSuggestHandler(suggest *store.SuggestStore) *SuggestHandler {
|
||||
return &SuggestHandler{suggest: suggest}
|
||||
}
|
||||
|
||||
type suggestResponse struct {
|
||||
Suggestions []string `json:"suggestions"`
|
||||
}
|
||||
|
||||
// Search returns autocomplete suggestions for item names matching the query.
|
||||
//
|
||||
// GET /api/suggestions?q=<query>
|
||||
func (h *SuggestHandler) Search(w http.ResponseWriter, r *http.Request) {
|
||||
q := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
if q == "" {
|
||||
renderError(w, http.StatusBadRequest, "Bad request", "Query parameter 'q' is required.")
|
||||
return
|
||||
}
|
||||
// Lowercase so the trgm index can match correctly.
|
||||
q = strings.ToLower(q)
|
||||
|
||||
names, err := h.suggest.Search(r.Context(), q)
|
||||
if err != nil {
|
||||
slog.Error("suggest search failed", "error", err, "q", q)
|
||||
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load suggestions.")
|
||||
return
|
||||
}
|
||||
if names == nil {
|
||||
names = []string{}
|
||||
}
|
||||
renderJSON(w, http.StatusOK, suggestResponse{Suggestions: names})
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue