This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package poolapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/pool"
|
||||
"github.com/itworx/pulse/internal/problem"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
Provider pool.Provider
|
||||
MaxPageSize int
|
||||
}
|
||||
|
||||
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || (r.URL.Path != "/api/v1/pools" && !strings.HasPrefix(r.URL.Path, "/api/v1/pools/")) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if _, ok := auth.PrincipalFromContext(r.Context()); !ok {
|
||||
problem.Write(w, r, http.StatusUnauthorized, "UNAUTHORIZED", "Authentication required", "Authentication is required to read pools.", nil)
|
||||
return
|
||||
}
|
||||
if err := r.Context().Err(); err != nil {
|
||||
return
|
||||
}
|
||||
snapshot, err := h.snapshot(r)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "POOLS_UNAVAILABLE", "Poolgegevens niet beschikbaar", "De poolgegevens konden niet worden gelezen.", nil)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/pools/") {
|
||||
id := strings.TrimPrefix(r.URL.Path, "/api/v1/pools/")
|
||||
item, ok := pool.PoolByID(snapshot, id)
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
writeJSON(w, struct {
|
||||
Source pool.Source `json:"source"`
|
||||
Pool pool.Pool `json:"pool"`
|
||||
}{snapshot.Source, item})
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
if value := r.URL.Query().Get("limit"); value != "" {
|
||||
parsed, parseErr := strconv.Atoi(value)
|
||||
if parseErr != nil {
|
||||
problem.Write(w, r, http.StatusBadRequest, "POOL_QUERY_INVALID", "Invalid pool query", "De poollimiet is ongeldig.", nil)
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
max := h.MaxPageSize
|
||||
if max == 0 {
|
||||
max = 100
|
||||
}
|
||||
if limit < 1 || limit > max {
|
||||
problem.Write(w, r, http.StatusBadRequest, "POOL_QUERY_INVALID", "Invalid pool query", "De poollimiet is ongeldig.", nil)
|
||||
return
|
||||
}
|
||||
if limit < len(snapshot.Pools) {
|
||||
snapshot.Pools = snapshot.Pools[:limit]
|
||||
}
|
||||
writeJSON(w, snapshot)
|
||||
}
|
||||
func (h Handler) snapshot(r *http.Request) (pool.Snapshot, error) {
|
||||
if h.Provider == nil {
|
||||
return pool.UnknownSnapshot(time.Now().UTC(), "pools", "unraid", "source_unavailable"), nil
|
||||
}
|
||||
return h.Provider.Snapshot(r.Context())
|
||||
}
|
||||
func writeJSON(w http.ResponseWriter, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "private, max-age=5")
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package poolapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/pool"
|
||||
)
|
||||
|
||||
type provider struct{ snapshot pool.Snapshot }
|
||||
|
||||
func (p provider) Snapshot(context.Context) (pool.Snapshot, error) { return p.snapshot, nil }
|
||||
|
||||
func authenticatedRequest(method, path string) *http.Request {
|
||||
request := httptest.NewRequest(method, path, nil)
|
||||
return request.WithContext(auth.WithPrincipal(request.Context(), auth.Principal{Subject: "viewer", Role: auth.RoleViewer}))
|
||||
}
|
||||
|
||||
func TestHandlerRequiresAuthenticationAndReturnsUnknown(t *testing.T) {
|
||||
unauthenticated := httptest.NewRecorder()
|
||||
Handler{}.ServeHTTP(unauthenticated, httptest.NewRequest(http.MethodGet, "/api/v1/pools", nil))
|
||||
if unauthenticated.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status=%d", unauthenticated.Code)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
Handler{}.ServeHTTP(response, authenticatedRequest(http.MethodGet, "/api/v1/pools"))
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"state":"unknown"`) {
|
||||
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerReturnsListAndDetailAndRejectsMutations(t *testing.T) {
|
||||
snapshot := pool.Snapshot{ContractVersion: pool.ContractVersion, Source: pool.Source{ID: "fixture-pool", Type: "fixture", Freshness: pool.Fresh, State: pool.StateHealthy}, Pools: []pool.Pool{{ID: "cache", Name: "Cache", Filesystem: "btrfs", State: pool.StateDegraded}}, Total: 1, ObservedAt: time.Date(2026, 8, 1, 12, 0, 0, 0, time.UTC)}
|
||||
list := httptest.NewRecorder()
|
||||
Handler{Provider: provider{snapshot: snapshot}}.ServeHTTP(list, authenticatedRequest(http.MethodGet, "/api/v1/pools?limit=10"))
|
||||
if list.Code != http.StatusOK || !strings.Contains(list.Body.String(), `"id":"cache"`) {
|
||||
t.Fatalf("status=%d body=%s", list.Code, list.Body.String())
|
||||
}
|
||||
detail := httptest.NewRecorder()
|
||||
Handler{Provider: provider{snapshot: snapshot}}.ServeHTTP(detail, authenticatedRequest(http.MethodGet, "/api/v1/pools/cache"))
|
||||
if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), `"name":"Cache"`) {
|
||||
t.Fatalf("status=%d body=%s", detail.Code, detail.Body.String())
|
||||
}
|
||||
mutation := httptest.NewRecorder()
|
||||
Handler{}.ServeHTTP(mutation, httptest.NewRequest(http.MethodPost, "/api/v1/pools", nil))
|
||||
if mutation.Code != http.StatusNotFound {
|
||||
t.Fatalf("mutation status=%d", mutation.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user