diff --git a/.sdlc/features/user-preferences/manifest.yaml b/.sdlc/features/user-preferences/manifest.yaml index 8637890..159f93b 100644 --- a/.sdlc/features/user-preferences/manifest.yaml +++ b/.sdlc/features/user-preferences/manifest.yaml @@ -1,7 +1,7 @@ slug: user-preferences title: User Preferences API created: 2026-02-09T03:07:55.541048432Z -phase: ready +phase: implementation phase_history: - phase: draft entered: 2026-02-09T03:07:55.541048432Z @@ -14,6 +14,9 @@ phase_history: exited: 2026-02-09T03:20:30.611901038Z - phase: ready entered: 2026-02-09T03:20:30.611901038Z + exited: 2026-02-09T03:22:37.766271477Z + - phase: implementation + entered: 2026-02-09T03:22:37.766271477Z artifacts: audit: status: pending @@ -45,25 +48,40 @@ artifacts: approved_by: user approved_at: 2026-02-09T03:18:20.547304636Z total: 7 + completed: 7 tasks: - id: task-001 title: Domain layer - UserPreferences model and domain errors - status: pending + status: complete + started_at: 2026-02-09T03:22:45.05034374Z + done_at: 2026-02-09T03:23:09.596316012Z - id: task-002 title: Port layer - PreferenceRepository interface - status: pending + status: complete + started_at: 2026-02-09T03:23:15.366917585Z + done_at: 2026-02-09T03:23:28.228255343Z - id: task-003 title: Service layer - PreferenceService with validation logic and tests - status: pending + status: complete + started_at: 2026-02-09T03:23:34.579590762Z + done_at: 2026-02-09T03:24:56.650842143Z - id: task-004 title: Database migration and PostgreSQL adapter - status: pending + status: complete + started_at: 2026-02-09T03:25:05.810659873Z + done_at: 2026-02-09T03:25:35.931875082Z - id: task-005 title: HTTP handlers - GET and PUT preference endpoints with tests - status: pending + status: complete + started_at: 2026-02-09T03:25:41.767966428Z + done_at: 2026-02-09T03:27:06.980076413Z - id: task-006 title: Routes, OpenAPI spec, and main.go wiring - status: pending + status: complete + started_at: 2026-02-09T03:27:14.505352647Z + done_at: 2026-02-09T03:28:39.057928335Z - id: task-007 title: Cleanup - Remove example scaffolding files - status: pending + status: complete + started_at: 2026-02-09T03:28:46.479063131Z + done_at: 2026-02-09T03:29:25.590171477Z diff --git a/.sdlc/state.yaml b/.sdlc/state.yaml index 6240e3f..18bfc72 100644 --- a/.sdlc/state.yaml +++ b/.sdlc/state.yaml @@ -4,10 +4,10 @@ project: active_work: features: - slug: user-preferences - phase: ready + phase: implementation blocked: [] -last_updated: 2026-02-09T03:20:30.626836394Z -last_action: TRANSITION +last_updated: 2026-02-09T03:29:25.591047245Z +last_action: COMPLETE_TASK last_actor: cli history: - timestamp: 2026-02-09T03:07:55.541429198Z @@ -50,3 +50,43 @@ history: feature: user-preferences actor: cli result: success + - timestamp: 2026-02-09T03:22:37.76692675Z + action: TRANSITION + feature: user-preferences + actor: cli + result: success + - timestamp: 2026-02-09T03:23:09.597746864Z + action: COMPLETE_TASK + feature: user-preferences + actor: cli + result: success + - timestamp: 2026-02-09T03:23:28.229040239Z + action: COMPLETE_TASK + feature: user-preferences + actor: cli + result: success + - timestamp: 2026-02-09T03:24:56.651563771Z + action: COMPLETE_TASK + feature: user-preferences + actor: cli + result: success + - timestamp: 2026-02-09T03:25:35.93266556Z + action: COMPLETE_TASK + feature: user-preferences + actor: cli + result: success + - timestamp: 2026-02-09T03:27:06.98073376Z + action: COMPLETE_TASK + feature: user-preferences + actor: cli + result: success + - timestamp: 2026-02-09T03:28:39.058628874Z + action: COMPLETE_TASK + feature: user-preferences + actor: cli + result: success + - timestamp: 2026-02-09T03:29:25.591045923Z + action: COMPLETE_TASK + feature: user-preferences + actor: cli + result: success diff --git a/go.work b/go.work index f7aade6..b0d70de 100644 --- a/go.work +++ b/go.work @@ -1,5 +1,9 @@ -go 1.23 +go 1.24.0 + +toolchain go1.24.13 use ./pkg + use ./services/preferences-api + // Component modules will be added below diff --git a/services/preferences-api/cmd/server/main.go b/services/preferences-api/cmd/server/main.go index 8746e83..1bc3792 100644 --- a/services/preferences-api/cmd/server/main.go +++ b/services/preferences-api/cmd/server/main.go @@ -2,17 +2,24 @@ package main import ( + "context" + "embed" "flag" "fmt" "os" "git.threesix.ai/jordan/slack5-1770606136/pkg/app" + "git.threesix.ai/jordan/slack5-1770606136/pkg/config" + "git.threesix.ai/jordan/slack5-1770606136/pkg/database" "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/adapter/memory" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/adapter/postgres" "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/api" "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service" ) +//go:embed migrations/*.sql +var migrationsFS embed.FS + func main() { // Parse flags exportOpenAPI := flag.Bool("export-openapi", false, "Export OpenAPI spec to stdout and exit") @@ -33,17 +40,29 @@ func main() { // Create logger logger := logging.Default() + // Connect to PostgreSQL + dbCfg := config.ReadDatabaseConfig() + pool := database.MustConnect(context.Background(), dbCfg.URL, database.Options{ + MaxOpenConns: dbCfg.MaxOpenConns, + MaxIdleConns: dbCfg.MaxIdleConns, + ConnMaxLifetime: dbCfg.ConnMaxLifetime, + }) + defer pool.Close() + + // Run migrations + database.MustRunMigrations(context.Background(), pool, migrationsFS, "migrations") + // Create adapters (repositories) - exampleRepo := memory.NewExampleRepository() + prefRepo := postgres.NewPreferenceRepository(pool.DB) // Create services (business logic) - exampleService := service.NewExampleService(exampleRepo, logger) + prefService := service.NewPreferenceService(prefRepo, logger) // Create application application := app.New("preferences-api", app.WithDefaultPort(8001)) // Register routes with dependency injection - api.RegisterRoutes(application, exampleService) + api.RegisterRoutes(application, prefService) // Start server application.Run() diff --git a/services/preferences-api/cmd/server/migrations/001_create_preferences.sql b/services/preferences-api/cmd/server/migrations/001_create_preferences.sql new file mode 100644 index 0000000..c4baf93 --- /dev/null +++ b/services/preferences-api/cmd/server/migrations/001_create_preferences.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS preferences ( + user_id UUID PRIMARY KEY, + preferences JSONB NOT NULL DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_preferences_updated_at ON preferences (updated_at); diff --git a/services/preferences-api/go.mod b/services/preferences-api/go.mod index 95a0948..f81dfa6 100644 --- a/services/preferences-api/go.mod +++ b/services/preferences-api/go.mod @@ -1,8 +1,12 @@ module git.threesix.ai/jordan/slack5-1770606136/services/preferences-api -go 1.23 +go 1.24.0 + +toolchain go1.24.13 require git.threesix.ai/jordan/slack5-1770606136/pkg v0.0.0 +require golang.org/x/text v0.33.0 // indirect + // Use local workspace modules (for Docker builds without go.work) replace git.threesix.ai/jordan/slack5-1770606136/pkg => ../../pkg diff --git a/services/preferences-api/go.sum b/services/preferences-api/go.sum index e69de29..62a1313 100644 --- a/services/preferences-api/go.sum +++ b/services/preferences-api/go.sum @@ -0,0 +1,2 @@ +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= diff --git a/services/preferences-api/internal/adapter/memory/example.go b/services/preferences-api/internal/adapter/memory/example.go deleted file mode 100644 index 78cfc27..0000000 --- a/services/preferences-api/internal/adapter/memory/example.go +++ /dev/null @@ -1,106 +0,0 @@ -// Package memory provides in-memory implementations of repository interfaces. -// Useful for development, testing, and prototyping. -package memory - -import ( - "context" - "sync" - - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port" -) - -// Compile-time verification that ExampleRepository implements port.ExampleRepository. -var _ port.ExampleRepository = (*ExampleRepository)(nil) - -// ExampleRepository is a thread-safe in-memory implementation of port.ExampleRepository. -type ExampleRepository struct { - mu sync.RWMutex - examples map[domain.ExampleID]*domain.Example -} - -// NewExampleRepository creates a new in-memory example repository. -func NewExampleRepository() *ExampleRepository { - return &ExampleRepository{ - examples: make(map[domain.ExampleID]*domain.Example), - } -} - -// List returns all examples. -func (r *ExampleRepository) List(ctx context.Context) ([]domain.Example, error) { - r.mu.RLock() - defer r.mu.RUnlock() - - result := make([]domain.Example, 0, len(r.examples)) - for _, e := range r.examples { - result = append(result, *e) - } - return result, nil -} - -// Get returns an example by ID. -// Returns domain.ErrExampleNotFound if not found. -func (r *ExampleRepository) Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) { - r.mu.RLock() - defer r.mu.RUnlock() - - e, ok := r.examples[id] - if !ok { - return nil, domain.ErrExampleNotFound - } - // Return a copy to prevent external mutation - copy := *e - return ©, nil -} - -// Create stores a new example. -func (r *ExampleRepository) Create(ctx context.Context, example *domain.Example) error { - r.mu.Lock() - defer r.mu.Unlock() - - // Store a copy to prevent external mutation - copy := *example - r.examples[example.ID] = © - return nil -} - -// Update modifies an existing example. -// Returns domain.ErrExampleNotFound if not found. -func (r *ExampleRepository) Update(ctx context.Context, example *domain.Example) error { - r.mu.Lock() - defer r.mu.Unlock() - - if _, ok := r.examples[example.ID]; !ok { - return domain.ErrExampleNotFound - } - // Store a copy to prevent external mutation - copy := *example - r.examples[example.ID] = © - return nil -} - -// Delete removes an example by ID. -// Returns domain.ErrExampleNotFound if not found. -func (r *ExampleRepository) Delete(ctx context.Context, id domain.ExampleID) error { - r.mu.Lock() - defer r.mu.Unlock() - - if _, ok := r.examples[id]; !ok { - return domain.ErrExampleNotFound - } - delete(r.examples, id) - return nil -} - -// ExistsByName checks if an example with the given name exists. -func (r *ExampleRepository) ExistsByName(ctx context.Context, name string) (bool, error) { - r.mu.RLock() - defer r.mu.RUnlock() - - for _, e := range r.examples { - if e.Name == name { - return true, nil - } - } - return false, nil -} diff --git a/services/preferences-api/internal/adapter/postgres/preference.go b/services/preferences-api/internal/adapter/postgres/preference.go new file mode 100644 index 0000000..a9f1a7a --- /dev/null +++ b/services/preferences-api/internal/adapter/postgres/preference.go @@ -0,0 +1,80 @@ +package postgres + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "time" + + "github.com/jmoiron/sqlx" + + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port" +) + +// PreferenceRepository implements port.PreferenceRepository using PostgreSQL. +type PreferenceRepository struct { + db *sqlx.DB +} + +// Compile-time interface verification. +var _ port.PreferenceRepository = (*PreferenceRepository)(nil) + +// NewPreferenceRepository creates a new PostgreSQL preference repository. +func NewPreferenceRepository(db *sqlx.DB) *PreferenceRepository { + return &PreferenceRepository{db: db} +} + +// preferenceRow represents a database row from the preferences table. +type preferenceRow struct { + UserID string `db:"user_id"` + Preferences []byte `db:"preferences"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` +} + +// Get returns preferences for a user. +// Returns nil, nil when no row exists. +func (r *PreferenceRepository) Get(ctx context.Context, userID string) (*domain.UserPreferences, error) { + var row preferenceRow + err := r.db.GetContext(ctx, &row, + `SELECT user_id, preferences, created_at, updated_at FROM preferences WHERE user_id = $1`, + userID, + ) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return nil, err + } + + prefs := make(map[string]any) + if err := json.Unmarshal(row.Preferences, &prefs); err != nil { + return nil, err + } + + return &domain.UserPreferences{ + UserID: row.UserID, + Preferences: prefs, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + }, nil +} + +// Upsert creates or updates preferences for a user. +func (r *PreferenceRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error { + prefsJSON, err := json.Marshal(prefs.Preferences) + if err != nil { + return err + } + + _, err = r.db.ExecContext(ctx, + `INSERT INTO preferences (user_id, preferences, updated_at) + VALUES ($1, $2, NOW()) + ON CONFLICT (user_id) DO UPDATE + SET preferences = $2, updated_at = NOW()`, + prefs.UserID, prefsJSON, + ) + return err +} diff --git a/services/preferences-api/internal/api/handlers/example.go b/services/preferences-api/internal/api/handlers/example.go deleted file mode 100644 index c41b791..0000000 --- a/services/preferences-api/internal/api/handlers/example.go +++ /dev/null @@ -1,170 +0,0 @@ -package handlers - -import ( - "errors" - "net/http" - - "github.com/go-chi/chi/v5" - "github.com/google/uuid" - - "git.threesix.ai/jordan/slack5-1770606136/pkg/app" - "git.threesix.ai/jordan/slack5-1770606136/pkg/httperror" - "git.threesix.ai/jordan/slack5-1770606136/pkg/httpresponse" - "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service" -) - -// Example handles HTTP requests for example resources. -type Example struct { - svc *service.ExampleService - logger *logging.Logger -} - -// NewExample creates a new Example handler with injected dependencies. -func NewExample(svc *service.ExampleService, logger *logging.Logger) *Example { - return &Example{ - svc: svc, - logger: logger.WithComponent("ExampleHandler"), - } -} - -// CreateRequest is the request body for creating an example. -type CreateRequest struct { - Name string `json:"name" validate:"required,min=1,max=100"` - Description string `json:"description" validate:"max=500"` -} - -// UpdateRequest is the request body for updating an example. -type UpdateRequest struct { - Name string `json:"name" validate:"required,min=1,max=100"` - Description string `json:"description" validate:"max=500"` -} - -// ExampleResponse is the response for an example resource. -type ExampleResponse struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` -} - -// toResponse converts a domain example to an API response. -func toResponse(e *domain.Example) ExampleResponse { - return ExampleResponse{ - ID: e.ID.String(), - Name: e.Name, - Description: e.Description, - CreatedAt: e.CreatedAt.Format("2006-01-02T15:04:05Z"), - UpdatedAt: e.UpdatedAt.Format("2006-01-02T15:04:05Z"), - } -} - -// List returns all examples. -func (h *Example) List(w http.ResponseWriter, r *http.Request) error { - examples, err := h.svc.List(r.Context()) - if err != nil { - return err - } - - result := make([]ExampleResponse, len(examples)) - for i, e := range examples { - result[i] = toResponse(&e) - } - - httpresponse.OK(w, r, result) - return nil -} - -// Get returns an example by ID. -func (h *Example) Get(w http.ResponseWriter, r *http.Request) error { - id := chi.URLParam(r, "id") - - // Validate UUID format - if _, err := uuid.Parse(id); err != nil { - return httperror.BadRequest("invalid id format") - } - - example, err := h.svc.Get(r.Context(), domain.ExampleID(id)) - if err != nil { - return mapDomainError(err) - } - - httpresponse.OK(w, r, toResponse(example)) - return nil -} - -// Create creates a new example. -func (h *Example) Create(w http.ResponseWriter, r *http.Request) error { - var req CreateRequest - if err := app.BindAndValidate(r, &req); err != nil { - return err - } - - example, err := h.svc.Create(r.Context(), service.CreateInput{ - Name: req.Name, - Description: req.Description, - }) - if err != nil { - return mapDomainError(err) - } - - httpresponse.Created(w, r, toResponse(example)) - return nil -} - -// Update updates an existing example. -func (h *Example) Update(w http.ResponseWriter, r *http.Request) error { - id := chi.URLParam(r, "id") - - if _, err := uuid.Parse(id); err != nil { - return httperror.BadRequest("invalid id format") - } - - var req UpdateRequest - if err := app.BindAndValidate(r, &req); err != nil { - return err - } - - example, err := h.svc.Update(r.Context(), domain.ExampleID(id), service.UpdateInput{ - Name: req.Name, - Description: req.Description, - }) - if err != nil { - return mapDomainError(err) - } - - httpresponse.OK(w, r, toResponse(example)) - return nil -} - -// Delete removes an example by ID. -func (h *Example) Delete(w http.ResponseWriter, r *http.Request) error { - id := chi.URLParam(r, "id") - - if _, err := uuid.Parse(id); err != nil { - return httperror.BadRequest("invalid id format") - } - - if err := h.svc.Delete(r.Context(), domain.ExampleID(id)); err != nil { - return mapDomainError(err) - } - - httpresponse.NoContent(w) - return nil -} - -// mapDomainError converts domain errors to HTTP errors. -func mapDomainError(err error) error { - switch { - case errors.Is(err, domain.ErrExampleNotFound): - return httperror.NotFound("example not found") - case errors.Is(err, domain.ErrDuplicateExample): - return httperror.Conflict("example with this name already exists") - case errors.Is(err, domain.ErrInvalidExampleName): - return httperror.BadRequest("invalid example name") - default: - return err - } -} diff --git a/services/preferences-api/internal/api/handlers/example_test.go b/services/preferences-api/internal/api/handlers/example_test.go deleted file mode 100644 index 8fd3951..0000000 --- a/services/preferences-api/internal/api/handlers/example_test.go +++ /dev/null @@ -1,402 +0,0 @@ -package handlers - -import ( - "bytes" - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "sync" - "testing" - - "github.com/go-chi/chi/v5" - - "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service" -) - -// mockExampleRepository implements port.ExampleRepository for testing. -type mockExampleRepository struct { - mu sync.RWMutex - examples map[domain.ExampleID]*domain.Example -} - -var _ port.ExampleRepository = (*mockExampleRepository)(nil) - -func newMockExampleRepository() *mockExampleRepository { - return &mockExampleRepository{ - examples: make(map[domain.ExampleID]*domain.Example), - } -} - -func (m *mockExampleRepository) List(ctx context.Context) ([]domain.Example, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - result := make([]domain.Example, 0, len(m.examples)) - for _, e := range m.examples { - result = append(result, *e) - } - return result, nil -} - -func (m *mockExampleRepository) Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - e, ok := m.examples[id] - if !ok { - return nil, domain.ErrExampleNotFound - } - copy := *e - return ©, nil -} - -func (m *mockExampleRepository) Create(ctx context.Context, example *domain.Example) error { - m.mu.Lock() - defer m.mu.Unlock() - - copy := *example - m.examples[example.ID] = © - return nil -} - -func (m *mockExampleRepository) Update(ctx context.Context, example *domain.Example) error { - m.mu.Lock() - defer m.mu.Unlock() - - if _, ok := m.examples[example.ID]; !ok { - return domain.ErrExampleNotFound - } - copy := *example - m.examples[example.ID] = © - return nil -} - -func (m *mockExampleRepository) Delete(ctx context.Context, id domain.ExampleID) error { - m.mu.Lock() - defer m.mu.Unlock() - - if _, ok := m.examples[id]; !ok { - return domain.ErrExampleNotFound - } - delete(m.examples, id) - return nil -} - -func (m *mockExampleRepository) ExistsByName(ctx context.Context, name string) (bool, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - for _, e := range m.examples { - if e.Name == name { - return true, nil - } - } - return false, nil -} - -func newTestHandler() (*Example, *mockExampleRepository) { - repo := newMockExampleRepository() - svc := service.NewExampleService(repo, logging.Nop()) - handler := NewExample(svc, logging.Nop()) - return handler, repo -} - -func TestExample_List(t *testing.T) { - handler, repo := newTestHandler() - - // Seed data - ex, _ := domain.NewExample("test-id-1", "Test Example", "Description") - _ = repo.Create(context.Background(), ex) - - r := chi.NewRouter() - r.Get("/api/v1/examples", func(w http.ResponseWriter, r *http.Request) { - if err := handler.List(w, r); err != nil { - t.Fatalf("unexpected error: %v", err) - } - }) - - req := httptest.NewRequest(http.MethodGet, "/api/v1/examples", nil) - w := httptest.NewRecorder() - r.ServeHTTP(w, req) - - if w.Code != http.StatusOK { - t.Errorf("expected status 200, got %d", w.Code) - } - - var resp map[string]any - if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { - t.Fatalf("failed to decode response: %v", err) - } - - data, ok := resp["data"] - if !ok { - t.Fatal("expected 'data' field in response") - } - - items, ok := data.([]any) - if !ok { - t.Fatal("expected 'data' to be an array") - } - - if len(items) != 1 { - t.Errorf("expected 1 item, got %d", len(items)) - } -} - -func TestExample_Get(t *testing.T) { - handler, repo := newTestHandler() - - // Seed data - ex, _ := domain.NewExample("550e8400-e29b-41d4-a716-446655440000", "Test Example", "Description") - _ = repo.Create(context.Background(), ex) - - tests := []struct { - name string - id string - wantStatus int - }{ - { - name: "valid uuid - found", - id: "550e8400-e29b-41d4-a716-446655440000", - wantStatus: http.StatusOK, - }, - { - name: "valid uuid - not found", - id: "550e8400-e29b-41d4-a716-446655440001", - wantStatus: http.StatusNotFound, - }, - { - name: "invalid uuid", - id: "not-a-uuid", - wantStatus: http.StatusBadRequest, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := chi.NewRouter() - r.Get("/api/v1/examples/{id}", func(w http.ResponseWriter, r *http.Request) { - if err := handler.Get(w, r); err != nil { - // Map error to status for testing - switch tt.wantStatus { - case http.StatusNotFound: - w.WriteHeader(http.StatusNotFound) - case http.StatusBadRequest: - w.WriteHeader(http.StatusBadRequest) - default: - w.WriteHeader(http.StatusInternalServerError) - } - return - } - }) - - req := httptest.NewRequest(http.MethodGet, "/api/v1/examples/"+tt.id, nil) - w := httptest.NewRecorder() - r.ServeHTTP(w, req) - - if w.Code != tt.wantStatus { - t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code) - } - }) - } -} - -func TestExample_Create(t *testing.T) { - handler, repo := newTestHandler() - - // Seed existing data for duplicate test - ex, _ := domain.NewExample("existing-id", "Existing Name", "") - _ = repo.Create(context.Background(), ex) - - tests := []struct { - name string - body any - wantStatus int - }{ - { - name: "valid request", - body: CreateRequest{ - Name: "New Example", - Description: "A test description", - }, - wantStatus: http.StatusCreated, - }, - { - name: "empty body", - body: nil, - wantStatus: http.StatusBadRequest, - }, - { - name: "duplicate name", - body: CreateRequest{ - Name: "Existing Name", - Description: "Conflict", - }, - wantStatus: http.StatusConflict, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := chi.NewRouter() - r.Post("/api/v1/examples", func(w http.ResponseWriter, r *http.Request) { - if err := handler.Create(w, r); err != nil { - switch tt.wantStatus { - case http.StatusBadRequest: - w.WriteHeader(http.StatusBadRequest) - case http.StatusConflict: - w.WriteHeader(http.StatusConflict) - default: - w.WriteHeader(http.StatusInternalServerError) - } - return - } - }) - - var body []byte - if tt.body != nil { - var err error - body, err = json.Marshal(tt.body) - if err != nil { - t.Fatalf("failed to marshal body: %v", err) - } - } - - req := httptest.NewRequest(http.MethodPost, "/api/v1/examples", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - r.ServeHTTP(w, req) - - if w.Code != tt.wantStatus { - t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code) - } - }) - } -} - -func TestExample_Delete(t *testing.T) { - handler, repo := newTestHandler() - - // Seed data - ex, _ := domain.NewExample("550e8400-e29b-41d4-a716-446655440000", "To Delete", "") - _ = repo.Create(context.Background(), ex) - - tests := []struct { - name string - id string - wantStatus int - }{ - { - name: "existing example", - id: "550e8400-e29b-41d4-a716-446655440000", - wantStatus: http.StatusNoContent, - }, - { - name: "non-existent example", - id: "550e8400-e29b-41d4-a716-446655440001", - wantStatus: http.StatusNotFound, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := chi.NewRouter() - r.Delete("/api/v1/examples/{id}", func(w http.ResponseWriter, r *http.Request) { - if err := handler.Delete(w, r); err != nil { - if tt.wantStatus == http.StatusNotFound { - w.WriteHeader(http.StatusNotFound) - } else { - w.WriteHeader(http.StatusBadRequest) - } - return - } - }) - - req := httptest.NewRequest(http.MethodDelete, "/api/v1/examples/"+tt.id, nil) - w := httptest.NewRecorder() - r.ServeHTTP(w, req) - - if w.Code != tt.wantStatus { - t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code) - } - }) - } -} - -func TestExample_Update(t *testing.T) { - handler, repo := newTestHandler() - - // Seed data - ex1, _ := domain.NewExample("550e8400-e29b-41d4-a716-446655440000", "Example 1", "") - _ = repo.Create(context.Background(), ex1) - ex2, _ := domain.NewExample("550e8400-e29b-41d4-a716-446655440001", "Example 2", "") - _ = repo.Create(context.Background(), ex2) - - tests := []struct { - name string - id string - body UpdateRequest - wantStatus int - }{ - { - name: "valid update", - id: "550e8400-e29b-41d4-a716-446655440000", - body: UpdateRequest{ - Name: "Updated Name", - Description: "Updated", - }, - wantStatus: http.StatusOK, - }, - { - name: "name conflict", - id: "550e8400-e29b-41d4-a716-446655440000", - body: UpdateRequest{ - Name: "Example 2", - Description: "Conflict", - }, - wantStatus: http.StatusConflict, - }, - { - name: "not found", - id: "550e8400-e29b-41d4-a716-446655440099", - body: UpdateRequest{ - Name: "Whatever", - Description: "", - }, - wantStatus: http.StatusNotFound, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := chi.NewRouter() - r.Put("/api/v1/examples/{id}", func(w http.ResponseWriter, r *http.Request) { - if err := handler.Update(w, r); err != nil { - switch tt.wantStatus { - case http.StatusNotFound: - w.WriteHeader(http.StatusNotFound) - case http.StatusConflict: - w.WriteHeader(http.StatusConflict) - default: - w.WriteHeader(http.StatusBadRequest) - } - return - } - }) - - body, _ := json.Marshal(tt.body) - req := httptest.NewRequest(http.MethodPut, "/api/v1/examples/"+tt.id, bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - r.ServeHTTP(w, req) - - if w.Code != tt.wantStatus { - t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code) - } - }) - } -} diff --git a/services/preferences-api/internal/api/handlers/preference.go b/services/preferences-api/internal/api/handlers/preference.go new file mode 100644 index 0000000..5157c1c --- /dev/null +++ b/services/preferences-api/internal/api/handlers/preference.go @@ -0,0 +1,122 @@ +package handlers + +import ( + "errors" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + + "git.threesix.ai/jordan/slack5-1770606136/pkg/app" + "git.threesix.ai/jordan/slack5-1770606136/pkg/httperror" + "git.threesix.ai/jordan/slack5-1770606136/pkg/httpresponse" + "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service" +) + +// Preference handles HTTP requests for user preference resources. +type Preference struct { + svc *service.PreferenceService + logger *logging.Logger +} + +// NewPreference creates a new Preference handler with injected dependencies. +func NewPreference(svc *service.PreferenceService, logger *logging.Logger) *Preference { + return &Preference{ + svc: svc, + logger: logger.WithComponent("PreferenceHandler"), + } +} + +// UpdatePreferencesRequest is the request body for updating preferences. +type UpdatePreferencesRequest struct { + Preferences map[string]any `json:"preferences"` +} + +// PreferenceResponse is the response for a preference resource. +type PreferenceResponse struct { + UserID string `json:"user_id"` + Preferences map[string]any `json:"preferences"` + UpdatedAt string `json:"updated_at"` +} + +// Get returns preferences for a user. +func (h *Preference) Get(w http.ResponseWriter, r *http.Request) error { + userID := chi.URLParam(r, "user_id") + + if _, err := uuid.Parse(userID); err != nil { + return httperror.BadRequest("invalid user_id format") + } + + prefs, err := h.svc.Get(r.Context(), userID) + if err != nil { + return err + } + + if prefs == nil { + httpresponse.OK(w, r, PreferenceResponse{ + UserID: userID, + Preferences: map[string]any{}, + UpdatedAt: time.Now().UTC().Format(time.RFC3339), + }) + return nil + } + + httpresponse.OK(w, r, toPreferenceResponse(prefs)) + return nil +} + +// Upsert creates or updates preferences for a user. +func (h *Preference) Upsert(w http.ResponseWriter, r *http.Request) error { + userID := chi.URLParam(r, "user_id") + + if _, err := uuid.Parse(userID); err != nil { + return httperror.BadRequest("invalid user_id format") + } + + var req UpdatePreferencesRequest + if err := app.Bind(r, &req); err != nil { + return err + } + + if req.Preferences == nil { + return httperror.BadRequest("preferences field is required") + } + + result, err := h.svc.Upsert(r.Context(), service.UpsertInput{ + UserID: userID, + Preferences: req.Preferences, + }) + if err != nil { + return mapPreferenceDomainError(err) + } + + httpresponse.OK(w, r, toPreferenceResponse(result)) + return nil +} + +// toPreferenceResponse converts a domain UserPreferences to an API response. +func toPreferenceResponse(p *domain.UserPreferences) PreferenceResponse { + return PreferenceResponse{ + UserID: p.UserID, + Preferences: p.Preferences, + UpdatedAt: p.UpdatedAt.Format(time.RFC3339), + } +} + +// mapPreferenceDomainError converts domain errors to HTTP errors. +func mapPreferenceDomainError(err error) error { + if errors.Is(err, domain.ErrInvalidPreferenceValue) { + var valErr *service.ValidationError + if errors.As(err, &valErr) { + return httperror.WithDetails( + httperror.Validation("Invalid preference values"), + valErr.Details, + ) + } + return httperror.BadRequest("invalid preference value") + } + return err +} diff --git a/services/preferences-api/internal/api/handlers/preference_test.go b/services/preferences-api/internal/api/handlers/preference_test.go new file mode 100644 index 0000000..c6503e4 --- /dev/null +++ b/services/preferences-api/internal/api/handlers/preference_test.go @@ -0,0 +1,272 @@ +package handlers + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/go-chi/chi/v5" + + "git.threesix.ai/jordan/slack5-1770606136/pkg/httperror" + "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service" +) + +// mockPreferenceRepository implements port.PreferenceRepository for handler testing. +type mockPreferenceRepository struct { + mu sync.RWMutex + prefs map[string]*domain.UserPreferences +} + +var _ port.PreferenceRepository = (*mockPreferenceRepository)(nil) + +func newMockPrefRepository() *mockPreferenceRepository { + return &mockPreferenceRepository{ + prefs: make(map[string]*domain.UserPreferences), + } +} + +func (m *mockPreferenceRepository) Get(ctx context.Context, userID string) (*domain.UserPreferences, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + p, ok := m.prefs[userID] + if !ok { + return nil, nil + } + cp := *p + cpPrefs := make(map[string]any) + for k, v := range p.Preferences { + cpPrefs[k] = v + } + cp.Preferences = cpPrefs + return &cp, nil +} + +func (m *mockPreferenceRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error { + m.mu.Lock() + defer m.mu.Unlock() + + cp := *prefs + cpPrefs := make(map[string]any) + for k, v := range prefs.Preferences { + cpPrefs[k] = v + } + cp.Preferences = cpPrefs + m.prefs[prefs.UserID] = &cp + return nil +} + +func newTestPreferenceHandler() (*Preference, *mockPreferenceRepository) { + repo := newMockPrefRepository() + svc := service.NewPreferenceService(repo, logging.Nop()) + handler := NewPreference(svc, logging.Nop()) + return handler, repo +} + +func TestPreference_Get(t *testing.T) { + handler, repo := newTestPreferenceHandler() + + // Seed data + repo.prefs["550e8400-e29b-41d4-a716-446655440000"] = &domain.UserPreferences{ + UserID: "550e8400-e29b-41d4-a716-446655440000", + Preferences: map[string]any{"theme": "dark"}, + } + + tests := []struct { + name string + userID string + wantStatus int + checkBody func(t *testing.T, body map[string]any) + }{ + { + name: "returns existing preferences", + userID: "550e8400-e29b-41d4-a716-446655440000", + wantStatus: http.StatusOK, + checkBody: func(t *testing.T, body map[string]any) { + data, ok := body["data"].(map[string]any) + if !ok { + t.Fatal("expected 'data' field in response") + } + prefs, ok := data["preferences"].(map[string]any) + if !ok { + t.Fatal("expected 'preferences' field in data") + } + if prefs["theme"] != "dark" { + t.Errorf("expected theme 'dark', got '%v'", prefs["theme"]) + } + }, + }, + { + name: "returns empty preferences for unknown user", + userID: "550e8400-e29b-41d4-a716-446655440001", + wantStatus: http.StatusOK, + checkBody: func(t *testing.T, body map[string]any) { + data, ok := body["data"].(map[string]any) + if !ok { + t.Fatal("expected 'data' field in response") + } + prefs, ok := data["preferences"].(map[string]any) + if !ok { + t.Fatal("expected 'preferences' field in data") + } + if len(prefs) != 0 { + t.Errorf("expected empty preferences, got %v", prefs) + } + }, + }, + { + name: "returns 400 for invalid UUID", + userID: "not-a-uuid", + wantStatus: http.StatusBadRequest, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := chi.NewRouter() + r.Get("/preferences/{user_id}", func(w http.ResponseWriter, r *http.Request) { + if err := handler.Get(w, r); err != nil { + // Write error status for test verification + httpErr, ok := err.(*httperror.HTTPError) + if ok { + w.WriteHeader(httpErr.Status) + } else { + w.WriteHeader(http.StatusInternalServerError) + } + return + } + }) + + req := httptest.NewRequest(http.MethodGet, "/preferences/"+tt.userID, nil) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + if w.Code != tt.wantStatus { + t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code) + } + + if tt.checkBody != nil && w.Code == http.StatusOK { + var body map[string]any + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Fatalf("failed to decode response: %v", err) + } + tt.checkBody(t, body) + } + }) + } +} + +func TestPreference_Upsert(t *testing.T) { + handler, _ := newTestPreferenceHandler() + + tests := []struct { + name string + userID string + body any + wantStatus int + checkBody func(t *testing.T, body map[string]any) + }{ + { + name: "creates preferences successfully", + userID: "550e8400-e29b-41d4-a716-446655440000", + body: UpdatePreferencesRequest{ + Preferences: map[string]any{ + "theme": "dark", + "language": "en", + }, + }, + wantStatus: http.StatusOK, + checkBody: func(t *testing.T, body map[string]any) { + data, ok := body["data"].(map[string]any) + if !ok { + t.Fatal("expected 'data' field in response") + } + prefs := data["preferences"].(map[string]any) + if prefs["theme"] != "dark" { + t.Errorf("expected theme 'dark', got '%v'", prefs["theme"]) + } + if data["user_id"] != "550e8400-e29b-41d4-a716-446655440000" { + t.Errorf("expected user_id in response, got '%v'", data["user_id"]) + } + }, + }, + { + name: "returns 400 for invalid theme", + userID: "550e8400-e29b-41d4-a716-446655440000", + body: UpdatePreferencesRequest{ + Preferences: map[string]any{ + "theme": "neon", + }, + }, + wantStatus: http.StatusBadRequest, + }, + { + name: "returns 400 for missing preferences field", + userID: "550e8400-e29b-41d4-a716-446655440000", + body: map[string]any{}, + wantStatus: http.StatusBadRequest, + }, + { + name: "returns 400 for invalid UUID", + userID: "not-a-uuid", + body: UpdatePreferencesRequest{Preferences: map[string]any{"theme": "dark"}}, + wantStatus: http.StatusBadRequest, + }, + { + name: "returns 400 for empty body", + userID: "550e8400-e29b-41d4-a716-446655440000", + body: nil, + wantStatus: http.StatusBadRequest, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := chi.NewRouter() + r.Put("/preferences/{user_id}", func(w http.ResponseWriter, r *http.Request) { + if err := handler.Upsert(w, r); err != nil { + httpErr, ok := err.(*httperror.HTTPError) + if ok { + w.WriteHeader(httpErr.Status) + } else { + w.WriteHeader(http.StatusInternalServerError) + } + return + } + }) + + var bodyBytes []byte + if tt.body != nil { + var err error + bodyBytes, err = json.Marshal(tt.body) + if err != nil { + t.Fatalf("failed to marshal body: %v", err) + } + } + + req := httptest.NewRequest(http.MethodPut, "/preferences/"+tt.userID, bytes.NewReader(bodyBytes)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + if w.Code != tt.wantStatus { + t.Errorf("expected status %d, got %d (body: %s)", tt.wantStatus, w.Code, w.Body.String()) + } + + if tt.checkBody != nil && w.Code == http.StatusOK { + var body map[string]any + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Fatalf("failed to decode response: %v", err) + } + tt.checkBody(t, body) + } + }) + } +} diff --git a/services/preferences-api/internal/api/routes.go b/services/preferences-api/internal/api/routes.go index b40390f..62bc654 100644 --- a/services/preferences-api/internal/api/routes.go +++ b/services/preferences-api/internal/api/routes.go @@ -3,9 +3,7 @@ package api import ( "git.threesix.ai/jordan/slack5-1770606136/pkg/app" - "git.threesix.ai/jordan/slack5-1770606136/pkg/auth" "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/api/handlers" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/config" "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service" ) @@ -13,14 +11,13 @@ import ( // Routes are mounted under /api/preferences-api to match the ingress path routing. // This allows the monorepo to expose multiple services under a single domain: // - https://domain/api/preferences-api/health -// - https://domain/api/preferences-api/examples -func RegisterRoutes(application *app.App, exampleService *service.ExampleService) { +// - https://domain/api/preferences-api/preferences/{user_id} +func RegisterRoutes(application *app.App, prefService *service.PreferenceService) { logger := application.Logger() - cfg := config.Load() // Initialize handlers with injected services healthHandler := handlers.NewHealth(logger) - exampleHandler := handlers.NewExample(exampleService, logger) + prefHandler := handlers.NewPreference(prefService, logger) // Build and mount OpenAPI spec spec := NewServiceSpec() @@ -31,24 +28,8 @@ func RegisterRoutes(application *app.App, exampleService *service.ExampleService application.Route("/api/preferences-api", func(r app.Router) { r.Get("/health", healthHandler.Check) - // Public routes (no auth required) - r.Get("/examples", app.Wrap(exampleHandler.List)) - r.Get("/examples/{id}", app.Wrap(exampleHandler.Get)) - - // Protected routes (auth required when enabled) - r.Group(func(r app.Router) { - if cfg.AuthEnabled { - r.Use(auth.Middleware(auth.MiddlewareConfig{ - Validator: auth.NewJWTValidator(auth.JWTConfig{ - Secret: []byte(cfg.JWTSecret), - Issuer: "slack5-1770606136", - }), - })) - } - - r.Post("/examples", app.Wrap(exampleHandler.Create)) - r.Put("/examples/{id}", app.Wrap(exampleHandler.Update)) - r.Delete("/examples/{id}", app.Wrap(exampleHandler.Delete)) - }) + // Preference routes (auth out of scope per spec; can be layered on later) + r.Get("/preferences/{user_id}", app.Wrap(prefHandler.Get)) + r.Put("/preferences/{user_id}", app.Wrap(prefHandler.Upsert)) }) } diff --git a/services/preferences-api/internal/api/spec.go b/services/preferences-api/internal/api/spec.go index 0abf116..22c523a 100644 --- a/services/preferences-api/internal/api/spec.go +++ b/services/preferences-api/internal/api/spec.go @@ -5,29 +5,20 @@ import "git.threesix.ai/jordan/slack5-1770606136/pkg/openapi" // NewServiceSpec builds the OpenAPI specification for the preferences-api service. func NewServiceSpec() *openapi.OpenAPISpec { spec := openapi.NewOpenAPISpec("preferences-api API", "1.0.0"). - WithDescription("REST API for the preferences-api service"). - WithBearerSecurity("bearer", "JWT authentication token"). + WithDescription("REST API for the preferences-api service - manages user preferences"). WithTag("Health", "Service health endpoints"). - WithTag("Examples", "Example CRUD endpoints") + WithTag("Preferences", "User preference endpoints") // Define reusable schemas - spec.WithSchema("Example", openapi.Object(map[string]openapi.Schema{ - "id": openapi.UUID().WithDescription("Unique identifier"), - "name": openapi.String().WithDescription("Name of the example").WithExample("My Example"), - "description": openapi.String().WithDescription("Optional description").WithExample("A description"), - "created_at": openapi.DateTime().WithDescription("Creation timestamp"), + spec.WithSchema("UserPreferences", openapi.Object(map[string]openapi.Schema{ + "user_id": openapi.UUID().WithDescription("User identifier"), + "preferences": openapi.Object(map[string]openapi.Schema{}).WithDescription("Key-value preference pairs"), "updated_at": openapi.DateTime().WithDescription("Last update timestamp"), - }, "id", "name")) + }, "user_id", "preferences", "updated_at")) - spec.WithSchema("CreateExampleRequest", openapi.Object(map[string]openapi.Schema{ - "name": openapi.StringWithMinMax(1, 100).WithDescription("Name of the example"), - "description": openapi.StringWithMinMax(0, 500).WithDescription("Optional description"), - }, "name")) - - spec.WithSchema("UpdateExampleRequest", openapi.Object(map[string]openapi.Schema{ - "name": openapi.StringWithMinMax(1, 100).WithDescription("Updated name"), - "description": openapi.StringWithMinMax(0, 500).WithDescription("Updated description"), - })) + spec.WithSchema("UpdatePreferencesRequest", openapi.Object(map[string]openapi.Schema{ + "preferences": openapi.Object(map[string]openapi.Schema{}).WithDescription("Key-value preference pairs to set"), + }, "preferences")) // Health spec.AddPath("/api/preferences-api/health", "get", map[string]any{ @@ -41,70 +32,28 @@ func NewServiceSpec() *openapi.OpenAPISpec { }, }) - // List examples - spec.AddPath("/api/preferences-api/examples", "get", map[string]any{ - "summary": "List examples", - "description": "Returns a paginated list of examples.", - "tags": []string{"Examples"}, - "parameters": []any{openapi.PageParam(), openapi.PerPageParam()}, + // Get preferences + spec.AddPath("/api/preferences-api/preferences/{user_id}", "get", map[string]any{ + "summary": "Get user preferences", + "description": "Returns all preferences for a user. Returns empty preferences object if user has none.", + "tags": []string{"Preferences"}, + "parameters": []any{openapi.PathParam("user_id", "User UUID")}, "responses": map[string]any{ - "200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.RefArray("Example"))), + "200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.Ref("UserPreferences"))), + "400": openapi.OpResponse("Invalid user_id format", openapi.ErrorResponseSchema()), }, }) - // Get example - spec.AddPath("/api/preferences-api/examples/{id}", "get", map[string]any{ - "summary": "Get example by ID", - "tags": []string{"Examples"}, - "parameters": []any{openapi.IDParam()}, + // Update preferences + spec.AddPath("/api/preferences-api/preferences/{user_id}", "put", map[string]any{ + "summary": "Update user preferences", + "description": "Creates or updates preferences for a user. Merges with existing preferences.", + "tags": []string{"Preferences"}, + "parameters": []any{openapi.PathParam("user_id", "User UUID")}, + "requestBody": openapi.RequestBody(openapi.Ref("UpdatePreferencesRequest"), true), "responses": map[string]any{ - "200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.Ref("Example"))), - "404": openapi.OpResponse("Not found", openapi.ErrorResponseSchema()), - }, - }) - - // Create example - spec.AddPath("/api/preferences-api/examples", "post", map[string]any{ - "summary": "Create example", - "description": "Creates a new example. Requires authentication.", - "tags": []string{"Examples"}, - "security": []map[string][]string{{"bearer": {}}}, - "requestBody": openapi.RequestBody(openapi.Ref("CreateExampleRequest"), true), - "responses": map[string]any{ - "201": openapi.OpResponse("Created", openapi.ResponseSchema(openapi.Ref("Example"))), - "400": openapi.OpResponse("Bad request", openapi.ErrorResponseSchema()), - "401": openapi.OpResponse("Unauthorized", openapi.ErrorResponseSchema()), - "422": openapi.OpResponse("Validation error", openapi.ErrorResponseSchema()), - }, - }) - - // Update example - spec.AddPath("/api/preferences-api/examples/{id}", "put", map[string]any{ - "summary": "Update example", - "description": "Updates an existing example. Requires authentication.", - "tags": []string{"Examples"}, - "security": []map[string][]string{{"bearer": {}}}, - "parameters": []any{openapi.IDParam()}, - "requestBody": openapi.RequestBody(openapi.Ref("UpdateExampleRequest"), true), - "responses": map[string]any{ - "200": openapi.OpResponse("Updated", openapi.ResponseSchema(openapi.Ref("Example"))), - "400": openapi.OpResponse("Bad request", openapi.ErrorResponseSchema()), - "401": openapi.OpResponse("Unauthorized", openapi.ErrorResponseSchema()), - "404": openapi.OpResponse("Not found", openapi.ErrorResponseSchema()), - }, - }) - - // Delete example - spec.AddPath("/api/preferences-api/examples/{id}", "delete", map[string]any{ - "summary": "Delete example", - "description": "Deletes an example by ID. Requires authentication.", - "tags": []string{"Examples"}, - "security": []map[string][]string{{"bearer": {}}}, - "parameters": []any{openapi.IDParam()}, - "responses": map[string]any{ - "204": openapi.OpResponseNoContent(), - "401": openapi.OpResponse("Unauthorized", openapi.ErrorResponseSchema()), - "404": openapi.OpResponse("Not found", openapi.ErrorResponseSchema()), + "200": openapi.OpResponse("Updated", openapi.ResponseSchema(openapi.Ref("UserPreferences"))), + "400": openapi.OpResponse("Validation error", openapi.ErrorResponseSchema()), }, }) diff --git a/services/preferences-api/internal/domain/errors.go b/services/preferences-api/internal/domain/errors.go index d4ffe10..720edff 100644 --- a/services/preferences-api/internal/domain/errors.go +++ b/services/preferences-api/internal/domain/errors.go @@ -7,15 +7,9 @@ import "errors" // Domain errors - these are business-level errors that should be translated // to appropriate HTTP status codes by the handler layer. var ( - // ErrNotFound indicates a requested resource does not exist. - ErrNotFound = errors.New("not found") + // ErrInvalidUserID indicates the user ID is invalid. + ErrInvalidUserID = errors.New("invalid user ID") - // ErrExampleNotFound indicates the requested example does not exist. - ErrExampleNotFound = errors.New("example not found") - - // ErrDuplicateExample indicates an example with the same name already exists. - ErrDuplicateExample = errors.New("example with this name already exists") - - // ErrInvalidExampleName indicates the example name is invalid. - ErrInvalidExampleName = errors.New("invalid example name") + // ErrInvalidPreferenceValue indicates one or more preference values are invalid. + ErrInvalidPreferenceValue = errors.New("invalid preference value") ) diff --git a/services/preferences-api/internal/domain/example.go b/services/preferences-api/internal/domain/example.go deleted file mode 100644 index 4ee48e9..0000000 --- a/services/preferences-api/internal/domain/example.go +++ /dev/null @@ -1,89 +0,0 @@ -package domain - -import ( - "time" - "unicode/utf8" -) - -// ExampleID is a strongly-typed identifier for examples. -type ExampleID string - -// String returns the string representation of the ID. -func (id ExampleID) String() string { - return string(id) -} - -// IsZero returns true if the ID is empty. -func (id ExampleID) IsZero() bool { - return id == "" -} - -// Example name constraints. -const ( - MinExampleNameLen = 1 - MaxExampleNameLen = 100 - MaxDescriptionLen = 500 -) - -// Example represents an example domain entity. -// This is a pure domain model with no external dependencies. -type Example struct { - ID ExampleID - Name string - Description string - CreatedAt time.Time - UpdatedAt time.Time -} - -// NewExample creates a new Example with validation. -// Returns ErrInvalidExampleName if the name is invalid. -func NewExample(id ExampleID, name, description string) (*Example, error) { - if err := validateExampleName(name); err != nil { - return nil, err - } - if err := validateDescription(description); err != nil { - return nil, err - } - - now := time.Now().UTC() - return &Example{ - ID: id, - Name: name, - Description: description, - CreatedAt: now, - UpdatedAt: now, - }, nil -} - -// Update modifies the example's mutable fields with validation. -// Returns ErrInvalidExampleName if the name is invalid. -func (e *Example) Update(name, description string) error { - if err := validateExampleName(name); err != nil { - return err - } - if err := validateDescription(description); err != nil { - return err - } - - e.Name = name - e.Description = description - e.UpdatedAt = time.Now().UTC() - return nil -} - -// validateExampleName validates an example name. -func validateExampleName(name string) error { - length := utf8.RuneCountInString(name) - if length < MinExampleNameLen || length > MaxExampleNameLen { - return ErrInvalidExampleName - } - return nil -} - -// validateDescription validates a description. -func validateDescription(desc string) error { - if utf8.RuneCountInString(desc) > MaxDescriptionLen { - return ErrInvalidExampleName - } - return nil -} diff --git a/services/preferences-api/internal/domain/preference.go b/services/preferences-api/internal/domain/preference.go new file mode 100644 index 0000000..b103cc0 --- /dev/null +++ b/services/preferences-api/internal/domain/preference.go @@ -0,0 +1,11 @@ +package domain + +import "time" + +// UserPreferences represents a user's stored preferences. +type UserPreferences struct { + UserID string + Preferences map[string]any + CreatedAt time.Time + UpdatedAt time.Time +} diff --git a/services/preferences-api/internal/port/example.go b/services/preferences-api/internal/port/example.go deleted file mode 100644 index 7622609..0000000 --- a/services/preferences-api/internal/port/example.go +++ /dev/null @@ -1,37 +0,0 @@ -// Package port defines interfaces (ports) for external dependencies. -// These interfaces define the contracts between the application core and -// infrastructure adapters, enabling testability and flexibility. -package port - -import ( - "context" - - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" -) - -// ExampleRepository defines the interface for example persistence operations. -// Implementations may use databases, in-memory storage, or external services. -type ExampleRepository interface { - // List returns all examples. - List(ctx context.Context) ([]domain.Example, error) - - // Get returns an example by ID. - // Returns domain.ErrExampleNotFound if not found. - Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) - - // Create stores a new example. - // The example must have a valid ID set. - Create(ctx context.Context, example *domain.Example) error - - // Update modifies an existing example. - // Returns domain.ErrExampleNotFound if not found. - Update(ctx context.Context, example *domain.Example) error - - // Delete removes an example by ID. - // Returns domain.ErrExampleNotFound if not found. - Delete(ctx context.Context, id domain.ExampleID) error - - // ExistsByName checks if an example with the given name exists. - // Used for duplicate detection. - ExistsByName(ctx context.Context, name string) (bool, error) -} diff --git a/services/preferences-api/internal/port/preference.go b/services/preferences-api/internal/port/preference.go new file mode 100644 index 0000000..ab100a1 --- /dev/null +++ b/services/preferences-api/internal/port/preference.go @@ -0,0 +1,18 @@ +package port + +import ( + "context" + + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" +) + +// PreferenceRepository defines the interface for preference persistence operations. +type PreferenceRepository interface { + // Get returns preferences for a user. + // Returns nil, nil when no row exists for the given userID. + Get(ctx context.Context, userID string) (*domain.UserPreferences, error) + + // Upsert creates or updates preferences for a user. + // Uses ON CONFLICT to handle both insert and update atomically. + Upsert(ctx context.Context, prefs *domain.UserPreferences) error +} diff --git a/services/preferences-api/internal/service/example.go b/services/preferences-api/internal/service/example.go deleted file mode 100644 index bd8270c..0000000 --- a/services/preferences-api/internal/service/example.go +++ /dev/null @@ -1,137 +0,0 @@ -// Package service provides business logic / use cases for the application. -// Services orchestrate domain operations using port interfaces. -package service - -import ( - "context" - "errors" - - "github.com/google/uuid" - - "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port" -) - -// ExampleService handles example-related business logic. -type ExampleService struct { - repo port.ExampleRepository - logger *logging.Logger -} - -// NewExampleService creates a new example service. -func NewExampleService(repo port.ExampleRepository, logger *logging.Logger) *ExampleService { - return &ExampleService{ - repo: repo, - logger: logger.WithService("ExampleService"), - } -} - -// List returns all examples. -func (s *ExampleService) List(ctx context.Context) ([]domain.Example, error) { - return s.repo.List(ctx) -} - -// Get returns an example by ID. -// Returns domain.ErrExampleNotFound if not found. -func (s *ExampleService) Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) { - return s.repo.Get(ctx, id) -} - -// CreateInput contains the data needed to create an example. -type CreateInput struct { - Name string - Description string -} - -// Create creates a new example with duplicate detection. -// Returns domain.ErrDuplicateExample if name already exists. -// Returns domain.ErrInvalidExampleName if name is invalid. -func (s *ExampleService) Create(ctx context.Context, input CreateInput) (*domain.Example, error) { - // Check for duplicates - exists, err := s.repo.ExistsByName(ctx, input.Name) - if err != nil { - return nil, err - } - if exists { - return nil, domain.ErrDuplicateExample - } - - // Generate new ID - id := domain.ExampleID(uuid.New().String()) - - // Create domain entity (validates name) - example, err := domain.NewExample(id, input.Name, input.Description) - if err != nil { - return nil, err - } - - // Persist - if err := s.repo.Create(ctx, example); err != nil { - return nil, err - } - - s.logger.Info("example created", "id", id, "name", input.Name) - return example, nil -} - -// UpdateInput contains the data needed to update an example. -type UpdateInput struct { - Name string - Description string -} - -// Update modifies an existing example. -// Returns domain.ErrExampleNotFound if not found. -// Returns domain.ErrDuplicateExample if new name conflicts with another example. -// Returns domain.ErrInvalidExampleName if name is invalid. -func (s *ExampleService) Update(ctx context.Context, id domain.ExampleID, input UpdateInput) (*domain.Example, error) { - // Fetch existing - example, err := s.repo.Get(ctx, id) - if err != nil { - return nil, err - } - - // Check for name conflicts (only if name changed) - if example.Name != input.Name { - exists, err := s.repo.ExistsByName(ctx, input.Name) - if err != nil { - return nil, err - } - if exists { - return nil, domain.ErrDuplicateExample - } - } - - // Update domain entity (validates name) - if err := example.Update(input.Name, input.Description); err != nil { - return nil, err - } - - // Persist - if err := s.repo.Update(ctx, example); err != nil { - return nil, err - } - - s.logger.Info("example updated", "id", id, "name", input.Name) - return example, nil -} - -// Delete removes an example by ID. -// Returns domain.ErrExampleNotFound if not found. -func (s *ExampleService) Delete(ctx context.Context, id domain.ExampleID) error { - // Verify exists before delete - if _, err := s.repo.Get(ctx, id); err != nil { - if errors.Is(err, domain.ErrExampleNotFound) { - return domain.ErrExampleNotFound - } - return err - } - - if err := s.repo.Delete(ctx, id); err != nil { - return err - } - - s.logger.Info("example deleted", "id", id) - return nil -} diff --git a/services/preferences-api/internal/service/example_test.go b/services/preferences-api/internal/service/example_test.go deleted file mode 100644 index 1ca906e..0000000 --- a/services/preferences-api/internal/service/example_test.go +++ /dev/null @@ -1,282 +0,0 @@ -package service - -import ( - "context" - "sync" - "testing" - - "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" - "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port" -) - -// mockExampleRepository implements port.ExampleRepository for testing. -type mockExampleRepository struct { - mu sync.RWMutex - examples map[domain.ExampleID]*domain.Example -} - -var _ port.ExampleRepository = (*mockExampleRepository)(nil) - -func newMockExampleRepository() *mockExampleRepository { - return &mockExampleRepository{ - examples: make(map[domain.ExampleID]*domain.Example), - } -} - -func (m *mockExampleRepository) List(ctx context.Context) ([]domain.Example, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - result := make([]domain.Example, 0, len(m.examples)) - for _, e := range m.examples { - result = append(result, *e) - } - return result, nil -} - -func (m *mockExampleRepository) Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - e, ok := m.examples[id] - if !ok { - return nil, domain.ErrExampleNotFound - } - // Return a copy to avoid mutation - copy := *e - return ©, nil -} - -func (m *mockExampleRepository) Create(ctx context.Context, example *domain.Example) error { - m.mu.Lock() - defer m.mu.Unlock() - - // Store a copy - copy := *example - m.examples[example.ID] = © - return nil -} - -func (m *mockExampleRepository) Update(ctx context.Context, example *domain.Example) error { - m.mu.Lock() - defer m.mu.Unlock() - - if _, ok := m.examples[example.ID]; !ok { - return domain.ErrExampleNotFound - } - // Store a copy - copy := *example - m.examples[example.ID] = © - return nil -} - -func (m *mockExampleRepository) Delete(ctx context.Context, id domain.ExampleID) error { - m.mu.Lock() - defer m.mu.Unlock() - - if _, ok := m.examples[id]; !ok { - return domain.ErrExampleNotFound - } - delete(m.examples, id) - return nil -} - -func (m *mockExampleRepository) ExistsByName(ctx context.Context, name string) (bool, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - for _, e := range m.examples { - if e.Name == name { - return true, nil - } - } - return false, nil -} - -func TestExampleService_Create(t *testing.T) { - repo := newMockExampleRepository() - svc := NewExampleService(repo, logging.Nop()) - - t.Run("creates example successfully", func(t *testing.T) { - example, err := svc.Create(context.Background(), CreateInput{ - Name: "Test Example", - Description: "A test description", - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if example.Name != "Test Example" { - t.Errorf("expected name 'Test Example', got '%s'", example.Name) - } - if example.ID.IsZero() { - t.Error("expected non-empty ID") - } - }) - - t.Run("rejects duplicate name", func(t *testing.T) { - _, err := svc.Create(context.Background(), CreateInput{ - Name: "Test Example", - Description: "Another description", - }) - if err != domain.ErrDuplicateExample { - t.Errorf("expected ErrDuplicateExample, got %v", err) - } - }) - - t.Run("rejects empty name", func(t *testing.T) { - _, err := svc.Create(context.Background(), CreateInput{ - Name: "", - Description: "Description", - }) - if err != domain.ErrInvalidExampleName { - t.Errorf("expected ErrInvalidExampleName, got %v", err) - } - }) -} - -func TestExampleService_Get(t *testing.T) { - repo := newMockExampleRepository() - svc := NewExampleService(repo, logging.Nop()) - - // Create an example first - created, _ := svc.Create(context.Background(), CreateInput{ - Name: "Get Test", - Description: "Description", - }) - - t.Run("returns existing example", func(t *testing.T) { - example, err := svc.Get(context.Background(), created.ID) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if example.Name != "Get Test" { - t.Errorf("expected name 'Get Test', got '%s'", example.Name) - } - }) - - t.Run("returns not found for missing example", func(t *testing.T) { - _, err := svc.Get(context.Background(), "nonexistent-id") - if err != domain.ErrExampleNotFound { - t.Errorf("expected ErrExampleNotFound, got %v", err) - } - }) -} - -func TestExampleService_Update(t *testing.T) { - repo := newMockExampleRepository() - svc := NewExampleService(repo, logging.Nop()) - - // Create examples - example1, _ := svc.Create(context.Background(), CreateInput{ - Name: "Update Test 1", - Description: "Original", - }) - _, _ = svc.Create(context.Background(), CreateInput{ - Name: "Update Test 2", - Description: "Other", - }) - - t.Run("updates example successfully", func(t *testing.T) { - updated, err := svc.Update(context.Background(), example1.ID, UpdateInput{ - Name: "Updated Name", - Description: "Updated description", - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if updated.Name != "Updated Name" { - t.Errorf("expected name 'Updated Name', got '%s'", updated.Name) - } - }) - - t.Run("allows same name on same example", func(t *testing.T) { - _, err := svc.Update(context.Background(), example1.ID, UpdateInput{ - Name: "Updated Name", - Description: "Same name", - }) - if err != nil { - t.Errorf("unexpected error updating with same name: %v", err) - } - }) - - t.Run("rejects name conflict", func(t *testing.T) { - _, err := svc.Update(context.Background(), example1.ID, UpdateInput{ - Name: "Update Test 2", - Description: "Conflict", - }) - if err != domain.ErrDuplicateExample { - t.Errorf("expected ErrDuplicateExample, got %v", err) - } - }) - - t.Run("returns not found for missing example", func(t *testing.T) { - _, err := svc.Update(context.Background(), "nonexistent-id", UpdateInput{ - Name: "Anything", - Description: "", - }) - if err != domain.ErrExampleNotFound { - t.Errorf("expected ErrExampleNotFound, got %v", err) - } - }) -} - -func TestExampleService_Delete(t *testing.T) { - repo := newMockExampleRepository() - svc := NewExampleService(repo, logging.Nop()) - - // Create an example first - created, _ := svc.Create(context.Background(), CreateInput{ - Name: "Delete Test", - Description: "To be deleted", - }) - - t.Run("deletes example successfully", func(t *testing.T) { - err := svc.Delete(context.Background(), created.ID) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // Verify deleted - _, err = svc.Get(context.Background(), created.ID) - if err != domain.ErrExampleNotFound { - t.Errorf("expected ErrExampleNotFound after delete, got %v", err) - } - }) - - t.Run("returns not found for missing example", func(t *testing.T) { - err := svc.Delete(context.Background(), "nonexistent-id") - if err != domain.ErrExampleNotFound { - t.Errorf("expected ErrExampleNotFound, got %v", err) - } - }) -} - -func TestExampleService_List(t *testing.T) { - repo := newMockExampleRepository() - svc := NewExampleService(repo, logging.Nop()) - - t.Run("returns empty list initially", func(t *testing.T) { - examples, err := svc.List(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if len(examples) != 0 { - t.Errorf("expected 0 examples, got %d", len(examples)) - } - }) - - // Create some examples - _, _ = svc.Create(context.Background(), CreateInput{Name: "List Test 1", Description: ""}) - _, _ = svc.Create(context.Background(), CreateInput{Name: "List Test 2", Description: ""}) - - t.Run("returns all examples", func(t *testing.T) { - examples, err := svc.List(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if len(examples) != 2 { - t.Errorf("expected 2 examples, got %d", len(examples)) - } - }) -} diff --git a/services/preferences-api/internal/service/preference.go b/services/preferences-api/internal/service/preference.go new file mode 100644 index 0000000..e501622 --- /dev/null +++ b/services/preferences-api/internal/service/preference.go @@ -0,0 +1,133 @@ +package service + +import ( + "context" + "fmt" + "time" + + "golang.org/x/text/language" + + "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port" +) + +// ValidationError carries per-field validation details. +// It wraps domain.ErrInvalidPreferenceValue for errors.Is() matching. +type ValidationError struct { + Details map[string]string +} + +func (e *ValidationError) Error() string { return "invalid preference values" } +func (e *ValidationError) Unwrap() error { return domain.ErrInvalidPreferenceValue } + +// validThemes is the set of allowed values for the "theme" preference. +var validThemes = map[string]bool{ + "light": true, + "dark": true, + "system": true, +} + +// PreferenceService handles preference-related business logic. +type PreferenceService struct { + repo port.PreferenceRepository + logger *logging.Logger +} + +// NewPreferenceService creates a new preference service. +func NewPreferenceService(repo port.PreferenceRepository, logger *logging.Logger) *PreferenceService { + return &PreferenceService{ + repo: repo, + logger: logger.WithService("PreferenceService"), + } +} + +// Get returns preferences for a user. +// Returns nil when no preferences exist. +func (s *PreferenceService) Get(ctx context.Context, userID string) (*domain.UserPreferences, error) { + return s.repo.Get(ctx, userID) +} + +// UpsertInput contains the data needed to upsert preferences. +type UpsertInput struct { + UserID string + Preferences map[string]any +} + +// Upsert validates and stores preferences for a user. +// Known keys are validated; unknown keys are accepted as-is. +// Incoming keys are merged on top of existing preferences. +func (s *PreferenceService) Upsert(ctx context.Context, input UpsertInput) (*domain.UserPreferences, error) { + // Validate known preference keys + if err := validatePreferences(input.Preferences); err != nil { + return nil, err + } + + // Fetch existing preferences for merge + existing, err := s.repo.Get(ctx, input.UserID) + if err != nil { + return nil, err + } + + merged := make(map[string]any) + if existing != nil { + for k, v := range existing.Preferences { + merged[k] = v + } + } + for k, v := range input.Preferences { + merged[k] = v + } + + now := time.Now().UTC() + prefs := &domain.UserPreferences{ + UserID: input.UserID, + Preferences: merged, + UpdatedAt: now, + } + if existing != nil { + prefs.CreatedAt = existing.CreatedAt + } else { + prefs.CreatedAt = now + } + + if err := s.repo.Upsert(ctx, prefs); err != nil { + return nil, err + } + + s.logger.Info("preferences upserted", "user_id", input.UserID) + return prefs, nil +} + +// validatePreferences checks known preference keys against their allowed values. +func validatePreferences(prefs map[string]any) error { + details := make(map[string]string) + + for key, value := range prefs { + switch key { + case "theme": + s, ok := value.(string) + if !ok || !validThemes[s] { + details[key] = "must be one of: light, dark, system" + } + case "language": + s, ok := value.(string) + if !ok { + details[key] = "must be a valid BCP-47 language tag" + continue + } + if _, err := language.Parse(s); err != nil { + details[key] = fmt.Sprintf("must be a valid BCP-47 language tag") + } + case "notifications_enabled": + if _, ok := value.(bool); !ok { + details[key] = "must be a boolean" + } + } + } + + if len(details) > 0 { + return &ValidationError{Details: details} + } + return nil +} diff --git a/services/preferences-api/internal/service/preference_test.go b/services/preferences-api/internal/service/preference_test.go new file mode 100644 index 0000000..7e28efd --- /dev/null +++ b/services/preferences-api/internal/service/preference_test.go @@ -0,0 +1,268 @@ +package service + +import ( + "context" + "errors" + "sync" + "testing" + + "git.threesix.ai/jordan/slack5-1770606136/pkg/logging" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain" + "git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port" +) + +// mockPreferenceRepository implements port.PreferenceRepository for testing. +type mockPreferenceRepository struct { + mu sync.RWMutex + prefs map[string]*domain.UserPreferences +} + +var _ port.PreferenceRepository = (*mockPreferenceRepository)(nil) + +func newMockPreferenceRepository() *mockPreferenceRepository { + return &mockPreferenceRepository{ + prefs: make(map[string]*domain.UserPreferences), + } +} + +func (m *mockPreferenceRepository) Get(ctx context.Context, userID string) (*domain.UserPreferences, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + p, ok := m.prefs[userID] + if !ok { + return nil, nil + } + // Return a copy + cp := *p + cpPrefs := make(map[string]any) + for k, v := range p.Preferences { + cpPrefs[k] = v + } + cp.Preferences = cpPrefs + return &cp, nil +} + +func (m *mockPreferenceRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error { + m.mu.Lock() + defer m.mu.Unlock() + + cp := *prefs + cpPrefs := make(map[string]any) + for k, v := range prefs.Preferences { + cpPrefs[k] = v + } + cp.Preferences = cpPrefs + m.prefs[prefs.UserID] = &cp + return nil +} + +func TestPreferenceService_Get(t *testing.T) { + repo := newMockPreferenceRepository() + svc := NewPreferenceService(repo, logging.Nop()) + + t.Run("returns nil for non-existent user", func(t *testing.T) { + result, err := svc.Get(context.Background(), "user-1") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if result != nil { + t.Error("expected nil result for non-existent user") + } + }) + + t.Run("returns existing preferences", func(t *testing.T) { + _, _ = svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-2", + Preferences: map[string]any{"theme": "dark"}, + }) + + result, err := svc.Get(context.Background(), "user-2") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if result == nil { + t.Fatal("expected non-nil result") + } + if result.Preferences["theme"] != "dark" { + t.Errorf("expected theme 'dark', got '%v'", result.Preferences["theme"]) + } + }) +} + +func TestPreferenceService_Upsert(t *testing.T) { + repo := newMockPreferenceRepository() + svc := NewPreferenceService(repo, logging.Nop()) + + t.Run("creates preferences for new user", func(t *testing.T) { + result, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-1", + Preferences: map[string]any{ + "theme": "dark", + "language": "en", + }, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if result.Preferences["theme"] != "dark" { + t.Errorf("expected theme 'dark', got '%v'", result.Preferences["theme"]) + } + if result.Preferences["language"] != "en" { + t.Errorf("expected language 'en', got '%v'", result.Preferences["language"]) + } + }) + + t.Run("merges preferences with existing", func(t *testing.T) { + result, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-1", + Preferences: map[string]any{ + "notifications_enabled": true, + }, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + // Existing keys should be preserved + if result.Preferences["theme"] != "dark" { + t.Errorf("expected theme 'dark' preserved, got '%v'", result.Preferences["theme"]) + } + if result.Preferences["language"] != "en" { + t.Errorf("expected language 'en' preserved, got '%v'", result.Preferences["language"]) + } + // New key should be added + if result.Preferences["notifications_enabled"] != true { + t.Errorf("expected notifications_enabled true, got '%v'", result.Preferences["notifications_enabled"]) + } + }) + + t.Run("overwrites existing key", func(t *testing.T) { + result, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-1", + Preferences: map[string]any{ + "theme": "light", + }, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if result.Preferences["theme"] != "light" { + t.Errorf("expected theme 'light', got '%v'", result.Preferences["theme"]) + } + // Other keys preserved + if result.Preferences["language"] != "en" { + t.Errorf("expected language 'en' preserved, got '%v'", result.Preferences["language"]) + } + }) + + t.Run("accepts unknown keys without validation", func(t *testing.T) { + result, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-2", + Preferences: map[string]any{ + "custom_setting": "anything", + "sidebar_width": 42.0, + }, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if result.Preferences["custom_setting"] != "anything" { + t.Errorf("expected custom_setting 'anything', got '%v'", result.Preferences["custom_setting"]) + } + }) + + t.Run("rejects invalid theme", func(t *testing.T) { + _, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-3", + Preferences: map[string]any{ + "theme": "neon", + }, + }) + if err == nil { + t.Fatal("expected error for invalid theme") + } + if !errors.Is(err, domain.ErrInvalidPreferenceValue) { + t.Errorf("expected ErrInvalidPreferenceValue, got %v", err) + } + var valErr *ValidationError + if !errors.As(err, &valErr) { + t.Fatal("expected ValidationError type") + } + if valErr.Details["theme"] == "" { + t.Error("expected details for theme key") + } + }) + + t.Run("rejects invalid language", func(t *testing.T) { + _, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-3", + Preferences: map[string]any{ + "language": "not-a-language-!!!", + }, + }) + if err == nil { + t.Fatal("expected error for invalid language") + } + var valErr *ValidationError + if !errors.As(err, &valErr) { + t.Fatal("expected ValidationError type") + } + if valErr.Details["language"] == "" { + t.Error("expected details for language key") + } + }) + + t.Run("rejects non-boolean notifications_enabled", func(t *testing.T) { + _, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-3", + Preferences: map[string]any{ + "notifications_enabled": "yes", + }, + }) + if err == nil { + t.Fatal("expected error for non-boolean notifications_enabled") + } + var valErr *ValidationError + if !errors.As(err, &valErr) { + t.Fatal("expected ValidationError type") + } + if valErr.Details["notifications_enabled"] == "" { + t.Error("expected details for notifications_enabled key") + } + }) + + t.Run("collects multiple validation errors", func(t *testing.T) { + _, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-3", + Preferences: map[string]any{ + "theme": "invalid", + "notifications_enabled": "not-bool", + }, + }) + if err == nil { + t.Fatal("expected error for multiple invalid values") + } + var valErr *ValidationError + if !errors.As(err, &valErr) { + t.Fatal("expected ValidationError type") + } + if len(valErr.Details) != 2 { + t.Errorf("expected 2 validation errors, got %d", len(valErr.Details)) + } + }) + + t.Run("accepts valid BCP-47 tags", func(t *testing.T) { + validTags := []string{"en", "fr", "es", "de", "ja", "zh-Hans", "pt-BR"} + for _, tag := range validTags { + _, err := svc.Upsert(context.Background(), UpsertInput{ + UserID: "user-lang-" + tag, + Preferences: map[string]any{ + "language": tag, + }, + }) + if err != nil { + t.Errorf("expected no error for valid BCP-47 tag '%s', got %v", tag, err) + } + } + }) +} diff --git a/services/preferences-api/server b/services/preferences-api/server new file mode 100755 index 0000000..154119f Binary files /dev/null and b/services/preferences-api/server differ