Add gardens CRUD + service-layer conventions (#7)
Establishes the patterns every later backend issue copies: the actor parameter, centralized role checks, and the version-guard/409 sync protocol. The service layer is the seam both REST handlers and future agent tools call, so permissions live here, not in handlers. - service/gardens.go: Service methods take (ctx, actorID, args). requireGardenRole(ctx, actor, gardenID, min) is THE authorization point — owner is implicit via owner_id now; #16 extends it to consult garden_shares. A user with no role gets ErrNotFound (existence masked), not ErrForbidden. Create/Get/List/Update/Delete with input validation (name required, 0 dims default to 10 m on create / rejected on update, negatives always rejected, unit metric|imperial, 100 m cap). - store/gardens.go: version-guarded UPDATE ... WHERE id=? AND version=? RETURNING; a no-match re-reads to return (current row, ErrVersionConflict) vs ErrNotFound. ListGardensForOwner returns a non-nil slice. - api/gardens.go: GET,POST /gardens and GET,PATCH,DELETE /gardens/:id behind requireAuth. writeVersionConflict documents the 409 envelope ({error:{code,message}, current:{...}}) — the contract for every mutable resource. writeResourceError maps ErrNotFound/Forbidden/ InvalidInput/VersionConflict; parseIDParam guards path ids. Tests: service (defaults, validation, owned-only list, version conflict returns current + retry, cross-user ErrNotFound, delete) and api (full CRUD flow, 409 envelope shape, cross-user 404, auth required, create validation). Verified against the running binary: create stores imperial 122x244 cm and list returns it. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||
)
|
||||
|
||||
// Garden sizing bounds. A new garden with no dimensions defaults to a 10 m
|
||||
// square; the max is a generous sanity cap (100 m) that also guards against
|
||||
// absurd or overflow-y values.
|
||||
const (
|
||||
defaultGardenCM = 1000
|
||||
maxGardenCM = 100_000
|
||||
)
|
||||
|
||||
// gardenRole ranks a user's access to a garden. Higher includes lower
|
||||
// (owner can do anything an editor can, etc.). Until sharing (#16), the only
|
||||
// role anyone holds is owner, on their own gardens.
|
||||
type gardenRole int
|
||||
|
||||
const (
|
||||
roleNone gardenRole = iota
|
||||
roleViewer
|
||||
roleEditor
|
||||
roleOwner
|
||||
)
|
||||
|
||||
// GardenInput is the mutable field set for creating or updating a garden.
|
||||
type GardenInput struct {
|
||||
Name string
|
||||
WidthCM float64
|
||||
HeightCM float64
|
||||
UnitPref string
|
||||
Notes string
|
||||
}
|
||||
|
||||
// requireGardenRole loads a garden and enforces that the actor holds at least
|
||||
// min. It is THE place authorization for a garden is decided — REST handlers and
|
||||
// future agent tools both funnel through here, so neither can skip a check.
|
||||
//
|
||||
// A user with no role at all gets ErrNotFound rather than ErrForbidden: we don't
|
||||
// reveal that a garden exists to someone with no access. A user who has some
|
||||
// access but not enough (e.g. a viewer trying to edit, once #16 lands) gets
|
||||
// ErrForbidden. #16 extends effectiveRole to consult garden_shares.
|
||||
func (s *Service) requireGardenRole(ctx context.Context, actorID, gardenID int64, min gardenRole) (*domain.Garden, error) {
|
||||
g, err := s.store.GetGarden(ctx, gardenID)
|
||||
if err != nil {
|
||||
return nil, err // ErrNotFound or a real error
|
||||
}
|
||||
role := effectiveGardenRole(actorID, g)
|
||||
if role == roleNone {
|
||||
return nil, domain.ErrNotFound
|
||||
}
|
||||
if role < min {
|
||||
return nil, domain.ErrForbidden
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
// effectiveGardenRole is the actor's role on a garden. Owner is implicit via
|
||||
// gardens.owner_id; share-based viewer/editor roles are added in #16.
|
||||
func effectiveGardenRole(actorID int64, g *domain.Garden) gardenRole {
|
||||
if g.OwnerID == actorID {
|
||||
return roleOwner
|
||||
}
|
||||
return roleNone
|
||||
}
|
||||
|
||||
// CreateGarden creates a garden owned by the actor. Missing dimensions default
|
||||
// to a 10 m square; unit defaults to metric.
|
||||
func (s *Service) CreateGarden(ctx context.Context, actorID int64, in GardenInput) (*domain.Garden, error) {
|
||||
g, err := gardenFromInput(in, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g.OwnerID = actorID
|
||||
return s.store.CreateGarden(ctx, g)
|
||||
}
|
||||
|
||||
// GetGarden returns a garden the actor may at least view.
|
||||
func (s *Service) GetGarden(ctx context.Context, actorID, gardenID int64) (*domain.Garden, error) {
|
||||
return s.requireGardenRole(ctx, actorID, gardenID, roleViewer)
|
||||
}
|
||||
|
||||
// ListGardens returns the gardens the actor can see. Owned-only until #16.
|
||||
func (s *Service) ListGardens(ctx context.Context, actorID int64) ([]domain.Garden, error) {
|
||||
return s.store.ListGardensForOwner(ctx, actorID)
|
||||
}
|
||||
|
||||
// UpdateGarden applies a version-guarded update; the actor must be at least an
|
||||
// editor. On a version mismatch it returns (current garden, ErrVersionConflict)
|
||||
// so the handler can return the fresh row for the client to rebase.
|
||||
func (s *Service) UpdateGarden(ctx context.Context, actorID, gardenID int64, in GardenInput, version int64) (*domain.Garden, error) {
|
||||
if _, err := s.requireGardenRole(ctx, actorID, gardenID, roleEditor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g, err := gardenFromInput(in, false) // no defaults: an update states every field
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g.ID = gardenID
|
||||
g.Version = version
|
||||
return s.store.UpdateGarden(ctx, g)
|
||||
}
|
||||
|
||||
// DeleteGarden removes a garden; only the owner may.
|
||||
func (s *Service) DeleteGarden(ctx context.Context, actorID, gardenID int64) error {
|
||||
if _, err := s.requireGardenRole(ctx, actorID, gardenID, roleOwner); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.store.DeleteGarden(ctx, gardenID)
|
||||
}
|
||||
|
||||
// gardenFromInput validates and normalizes input into a domain.Garden (without
|
||||
// identity/ownership fields). With applyDefaults, absent dimensions/unit are
|
||||
// filled in (create); without it, every field must be supplied (update).
|
||||
func gardenFromInput(in GardenInput, applyDefaults bool) (*domain.Garden, error) {
|
||||
name := strings.TrimSpace(in.Name)
|
||||
if name == "" {
|
||||
return nil, domain.ErrInvalidInput
|
||||
}
|
||||
|
||||
// 0 means "unset": defaulted on create, rejected on update. A negative value
|
||||
// is always an explicit error (never silently corrected to the default).
|
||||
width, height := in.WidthCM, in.HeightCM
|
||||
if applyDefaults {
|
||||
if width == 0 {
|
||||
width = defaultGardenCM
|
||||
}
|
||||
if height == 0 {
|
||||
height = defaultGardenCM
|
||||
}
|
||||
}
|
||||
if width <= 0 || height <= 0 || width > maxGardenCM || height > maxGardenCM {
|
||||
return nil, domain.ErrInvalidInput
|
||||
}
|
||||
|
||||
unit := in.UnitPref
|
||||
if unit == "" && applyDefaults {
|
||||
unit = domain.UnitMetric
|
||||
}
|
||||
if unit != domain.UnitMetric && unit != domain.UnitImperial {
|
||||
return nil, domain.ErrInvalidInput
|
||||
}
|
||||
|
||||
return &domain.Garden{
|
||||
Name: name,
|
||||
WidthCM: width,
|
||||
HeightCM: height,
|
||||
UnitPref: unit,
|
||||
Notes: strings.TrimSpace(in.Notes),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||
)
|
||||
|
||||
// seedUser registers a local user and returns its id.
|
||||
func seedUser(t *testing.T, s *Service, email string) int64 {
|
||||
t.Helper()
|
||||
u := mustRegister(t, s, email, email, "password123")
|
||||
return u.ID
|
||||
}
|
||||
|
||||
func TestCreateGardenAppliesDefaults(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
owner := seedUser(t, s, "[email protected]")
|
||||
|
||||
g, err := s.CreateGarden(context.Background(), owner, GardenInput{Name: " Backyard "})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateGarden: %v", err)
|
||||
}
|
||||
if g.Name != "Backyard" {
|
||||
t.Errorf("name = %q, want trimmed 'Backyard'", g.Name)
|
||||
}
|
||||
if g.WidthCM != defaultGardenCM || g.HeightCM != defaultGardenCM {
|
||||
t.Errorf("dimensions = %vx%v, want %d default", g.WidthCM, g.HeightCM, defaultGardenCM)
|
||||
}
|
||||
if g.UnitPref != domain.UnitMetric {
|
||||
t.Errorf("unit = %q, want metric", g.UnitPref)
|
||||
}
|
||||
if g.OwnerID != owner {
|
||||
t.Errorf("owner = %d, want %d", g.OwnerID, owner)
|
||||
}
|
||||
if g.Version != 1 {
|
||||
t.Errorf("version = %d, want 1", g.Version)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateGardenValidation(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
owner := seedUser(t, s, "[email protected]")
|
||||
|
||||
cases := []GardenInput{
|
||||
{Name: " "}, // blank name
|
||||
{Name: "X", UnitPref: "furlongs"}, // bad unit
|
||||
{Name: "X", WidthCM: -5}, // non-positive dim (defaults only fill 0)
|
||||
{Name: "X", WidthCM: maxGardenCM + 1}, // over the cap
|
||||
{Name: "X", HeightCM: maxGardenCM * 10}, // over the cap
|
||||
}
|
||||
for i, in := range cases {
|
||||
if _, err := s.CreateGarden(context.Background(), owner, in); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("case %d: err = %v, want ErrInvalidInput", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListGardensOwnedOnly(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
alice := seedUser(t, s, "[email protected]")
|
||||
bob := seedUser(t, s, "[email protected]")
|
||||
|
||||
if _, err := s.CreateGarden(context.Background(), alice, GardenInput{Name: "Alice A"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.CreateGarden(context.Background(), alice, GardenInput{Name: "Alice B"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.CreateGarden(context.Background(), bob, GardenInput{Name: "Bob A"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
aliceGardens, err := s.ListGardens(context.Background(), alice)
|
||||
if err != nil {
|
||||
t.Fatalf("ListGardens: %v", err)
|
||||
}
|
||||
if len(aliceGardens) != 2 {
|
||||
t.Errorf("alice sees %d gardens, want 2", len(aliceGardens))
|
||||
}
|
||||
for _, g := range aliceGardens {
|
||||
if g.OwnerID != alice {
|
||||
t.Errorf("alice's list contains a garden owned by %d", g.OwnerID)
|
||||
}
|
||||
}
|
||||
|
||||
// A user with no gardens gets a non-nil empty list.
|
||||
carol := seedUser(t, s, "[email protected]")
|
||||
if gs, err := s.ListGardens(context.Background(), carol); err != nil || gs == nil || len(gs) != 0 {
|
||||
t.Errorf("carol list = (%v, %v), want empty non-nil", gs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateGardenHappyPathBumpsVersion(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
owner := seedUser(t, s, "[email protected]")
|
||||
g, _ := s.CreateGarden(context.Background(), owner, GardenInput{Name: "Yard"})
|
||||
|
||||
updated, err := s.UpdateGarden(context.Background(), owner, g.ID,
|
||||
GardenInput{Name: "Front Yard", WidthCM: 200, HeightCM: 400, UnitPref: domain.UnitImperial, Notes: "sunny"}, g.Version)
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateGarden: %v", err)
|
||||
}
|
||||
if updated.Name != "Front Yard" || updated.WidthCM != 200 || updated.UnitPref != domain.UnitImperial {
|
||||
t.Errorf("update didn't persist: %+v", updated)
|
||||
}
|
||||
if updated.Version != g.Version+1 {
|
||||
t.Errorf("version = %d, want %d", updated.Version, g.Version+1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateGardenVersionConflictReturnsCurrent(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
owner := seedUser(t, s, "[email protected]")
|
||||
g, _ := s.CreateGarden(context.Background(), owner, GardenInput{Name: "Yard"})
|
||||
|
||||
// First update succeeds and bumps the version to 2.
|
||||
if _, err := s.UpdateGarden(context.Background(), owner, g.ID,
|
||||
GardenInput{Name: "Yard v2", WidthCM: 1000, HeightCM: 1000, UnitPref: domain.UnitMetric}, g.Version); err != nil {
|
||||
t.Fatalf("first update: %v", err)
|
||||
}
|
||||
|
||||
// A second update at the stale version 1 conflicts and returns the current row.
|
||||
current, err := s.UpdateGarden(context.Background(), owner, g.ID,
|
||||
GardenInput{Name: "Yard v3", WidthCM: 1000, HeightCM: 1000, UnitPref: domain.UnitMetric}, g.Version)
|
||||
if !errors.Is(err, domain.ErrVersionConflict) {
|
||||
t.Fatalf("stale update err = %v, want ErrVersionConflict", err)
|
||||
}
|
||||
if current == nil || current.Name != "Yard v2" || current.Version != 2 {
|
||||
t.Errorf("conflict didn't return the current row: %+v", current)
|
||||
}
|
||||
|
||||
// Retrying with the fresh version succeeds.
|
||||
if _, err := s.UpdateGarden(context.Background(), owner, g.ID,
|
||||
GardenInput{Name: "Yard v3", WidthCM: 1000, HeightCM: 1000, UnitPref: domain.UnitMetric}, current.Version); err != nil {
|
||||
t.Errorf("retry with fresh version failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateGardenRejectsMissingDimensions(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
owner := seedUser(t, s, "[email protected]")
|
||||
g, _ := s.CreateGarden(context.Background(), owner, GardenInput{Name: "Yard"})
|
||||
|
||||
// Update states every field; a 0 dimension is invalid (no defaulting on update).
|
||||
if _, err := s.UpdateGarden(context.Background(), owner, g.ID,
|
||||
GardenInput{Name: "Yard", UnitPref: domain.UnitMetric}, g.Version); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("update with 0 dims err = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossUserAccessIsNotFound(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
alice := seedUser(t, s, "[email protected]")
|
||||
bob := seedUser(t, s, "[email protected]")
|
||||
g, _ := s.CreateGarden(context.Background(), alice, GardenInput{Name: "Alice's"})
|
||||
|
||||
// Bob must not learn Alice's garden exists: every access is ErrNotFound.
|
||||
if _, err := s.GetGarden(context.Background(), bob, g.ID); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("bob get err = %v, want ErrNotFound", err)
|
||||
}
|
||||
if _, err := s.UpdateGarden(context.Background(), bob, g.ID,
|
||||
GardenInput{Name: "hijack", WidthCM: 100, HeightCM: 100, UnitPref: domain.UnitMetric}, g.Version); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("bob update err = %v, want ErrNotFound", err)
|
||||
}
|
||||
if err := s.DeleteGarden(context.Background(), bob, g.ID); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("bob delete err = %v, want ErrNotFound", err)
|
||||
}
|
||||
|
||||
// Alice's garden is untouched.
|
||||
if still, err := s.GetGarden(context.Background(), alice, g.ID); err != nil || still.Name != "Alice's" {
|
||||
t.Errorf("alice's garden was affected: %+v %v", still, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteGarden(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
owner := seedUser(t, s, "[email protected]")
|
||||
g, _ := s.CreateGarden(context.Background(), owner, GardenInput{Name: "Yard"})
|
||||
|
||||
if err := s.DeleteGarden(context.Background(), owner, g.ID); err != nil {
|
||||
t.Fatalf("DeleteGarden: %v", err)
|
||||
}
|
||||
if _, err := s.GetGarden(context.Background(), owner, g.ID); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("garden still present after delete: %v", err)
|
||||
}
|
||||
// Deleting again is ErrNotFound.
|
||||
if err := s.DeleteGarden(context.Background(), owner, g.ID); !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Errorf("re-delete err = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user