DDD Meilisearch showcase: domain/app/infra/interfaces, Taskfile, tests
This commit is contained in:
commit
a9674ce14e
22 files changed
+1584
No files matched your search
@@ -0,0 +1,74 @@
|
||||
// Package app is the application layer: use cases that orchestrate the domain
|
||||
// and the ports. No business rules live here, and no HTTP/Meili types either.
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
)
|
||||
|
||||
// CatalogService exposes the use cases of the catalog bounded context.
|
||||
type CatalogService struct {
|
||||
index catalog.MovieIndex
|
||||
}
|
||||
|
||||
func NewCatalogService(index catalog.MovieIndex) *CatalogService {
|
||||
return &CatalogService{index: index}
|
||||
}
|
||||
|
||||
// Setup prepares the read model (index settings). Idempotent.
|
||||
func (s *CatalogService) Setup(ctx context.Context) error {
|
||||
return s.index.EnsureSchema(ctx)
|
||||
}
|
||||
|
||||
// ImportMovies validates raw input into aggregates and indexes them.
|
||||
func (s *CatalogService) ImportMovies(ctx context.Context, in []MovieInput) (int, error) {
|
||||
movies := make([]*catalog.Movie, 0, len(in))
|
||||
for i, r := range in {
|
||||
id, err := catalog.NewMovieID(r.ID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("record %d: %w", i, err)
|
||||
}
|
||||
m, err := catalog.NewMovie(id, r.Title, r.Overview, r.Genres, r.Year, r.Rating)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("record %d: %w", i, err)
|
||||
}
|
||||
movies = append(movies, m)
|
||||
}
|
||||
if err := s.index.Index(ctx, movies); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(movies), nil
|
||||
}
|
||||
|
||||
func (s *CatalogService) Search(ctx context.Context, q catalog.Query) (catalog.Results, error) {
|
||||
return s.index.Search(ctx, q.Normalize())
|
||||
}
|
||||
|
||||
func (s *CatalogService) Get(ctx context.Context, rawID string) (*catalog.Movie, error) {
|
||||
id, err := catalog.NewMovieID(rawID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.index.Get(ctx, id)
|
||||
}
|
||||
|
||||
func (s *CatalogService) Delete(ctx context.Context, rawID string) error {
|
||||
id, err := catalog.NewMovieID(rawID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.index.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// MovieInput is the unvalidated shape crossing into the application layer.
|
||||
type MovieInput struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Overview string `json:"overview"`
|
||||
Genres []string `json:"genres"`
|
||||
Year int `json:"year"`
|
||||
Rating float64 `json:"rating"`
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package app_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/app"
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
)
|
||||
|
||||
// fakeIndex is an in-memory MovieIndex: the port makes the use cases testable
|
||||
// without Meilisearch running.
|
||||
type fakeIndex struct {
|
||||
movies map[catalog.MovieID]*catalog.Movie
|
||||
schema bool
|
||||
}
|
||||
|
||||
func newFake() *fakeIndex { return &fakeIndex{movies: map[catalog.MovieID]*catalog.Movie{}} }
|
||||
|
||||
func (f *fakeIndex) EnsureSchema(context.Context) error { f.schema = true; return nil }
|
||||
func (f *fakeIndex) Index(_ context.Context, ms []*catalog.Movie) error {
|
||||
for _, m := range ms {
|
||||
f.movies[m.ID()] = m
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (f *fakeIndex) Get(_ context.Context, id catalog.MovieID) (*catalog.Movie, error) {
|
||||
m, ok := f.movies[id]
|
||||
if !ok {
|
||||
return nil, catalog.ErrNotFound
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
func (f *fakeIndex) Delete(_ context.Context, id catalog.MovieID) error {
|
||||
delete(f.movies, id)
|
||||
return nil
|
||||
}
|
||||
func (f *fakeIndex) Search(_ context.Context, q catalog.Query) (catalog.Results, error) {
|
||||
var r catalog.Results
|
||||
for _, m := range f.movies {
|
||||
r.Hits = append(r.Hits, catalog.Hit{Movie: m})
|
||||
}
|
||||
r.EstimatedTotal = int64(len(r.Hits))
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func TestImportRejectsInvalidRecord(t *testing.T) {
|
||||
svc := app.NewCatalogService(newFake())
|
||||
_, err := svc.ImportMovies(context.Background(), []app.MovieInput{
|
||||
{ID: "1", Title: "Alien", Year: 1979, Rating: 8.5},
|
||||
{ID: "2", Title: "", Year: 1999, Rating: 7},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("want validation error for record 1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportThenGet(t *testing.T) {
|
||||
f := newFake()
|
||||
svc := app.NewCatalogService(f)
|
||||
n, err := svc.ImportMovies(context.Background(), []app.MovieInput{{ID: "1", Title: "Alien", Year: 1979, Rating: 8.5}})
|
||||
if err != nil || n != 1 {
|
||||
t.Fatalf("import: n=%d err=%v", n, err)
|
||||
}
|
||||
m, err := svc.Get(context.Background(), "1")
|
||||
if err != nil || m.Title() != "Alien" {
|
||||
t.Fatalf("get: %v %v", m, err)
|
||||
}
|
||||
if _, err := svc.Get(context.Background(), " "); err == nil {
|
||||
t.Fatal("want invalid id error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Package catalog is the domain layer: entities, value objects, invariants.
|
||||
// It has no knowledge of Meilisearch, HTTP or any other infrastructure.
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Errors returned by the domain. Application/interface layers map these to
|
||||
// transport-specific results (HTTP status codes, exit codes, ...).
|
||||
var (
|
||||
ErrInvalidMovie = errors.New("catalog: invalid movie")
|
||||
ErrNotFound = errors.New("catalog: movie not found")
|
||||
)
|
||||
|
||||
// MovieID is a value object: a non-empty identifier of a movie.
|
||||
type MovieID string
|
||||
|
||||
func NewMovieID(s string) (MovieID, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return "", fmt.Errorf("%w: empty id", ErrInvalidMovie)
|
||||
}
|
||||
return MovieID(s), nil
|
||||
}
|
||||
|
||||
func (id MovieID) String() string { return string(id) }
|
||||
|
||||
// Movie is the aggregate root of this (deliberately tiny) bounded context.
|
||||
type Movie struct {
|
||||
id MovieID
|
||||
title string
|
||||
overview string
|
||||
genres []string
|
||||
year int
|
||||
rating float64
|
||||
}
|
||||
|
||||
// NewMovie enforces the aggregate invariants. There is no other way to build a
|
||||
// valid Movie, so an existing *Movie is always valid.
|
||||
func NewMovie(id MovieID, title, overview string, genres []string, year int, rating float64) (*Movie, error) {
|
||||
if id == "" {
|
||||
return nil, fmt.Errorf("%w: empty id", ErrInvalidMovie)
|
||||
}
|
||||
title = strings.TrimSpace(title)
|
||||
if title == "" {
|
||||
return nil, fmt.Errorf("%w: empty title", ErrInvalidMovie)
|
||||
}
|
||||
if year < 1888 { // Roundhay Garden Scene, the oldest surviving film.
|
||||
return nil, fmt.Errorf("%w: year %d predates cinema", ErrInvalidMovie, year)
|
||||
}
|
||||
if rating < 0 || rating > 10 {
|
||||
return nil, fmt.Errorf("%w: rating %.1f out of range [0,10]", ErrInvalidMovie, rating)
|
||||
}
|
||||
clean := make([]string, 0, len(genres))
|
||||
for _, g := range genres {
|
||||
if g = strings.TrimSpace(g); g != "" {
|
||||
clean = append(clean, g)
|
||||
}
|
||||
}
|
||||
return &Movie{id: id, title: title, overview: strings.TrimSpace(overview), genres: clean, year: year, rating: rating}, nil
|
||||
}
|
||||
|
||||
func (m *Movie) ID() MovieID { return m.id }
|
||||
func (m *Movie) Title() string { return m.title }
|
||||
func (m *Movie) Overview() string { return m.overview }
|
||||
func (m *Movie) Genres() []string { return append([]string(nil), m.genres...) }
|
||||
func (m *Movie) Year() int { return m.year }
|
||||
func (m *Movie) Rating() float64 { return m.rating }
|
||||
|
||||
// Rate replaces the rating, keeping the aggregate consistent.
|
||||
func (m *Movie) Rate(rating float64) error {
|
||||
if rating < 0 || rating > 10 {
|
||||
return fmt.Errorf("%w: rating %.1f out of range [0,10]", ErrInvalidMovie, rating)
|
||||
}
|
||||
m.rating = rating
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package catalog_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
)
|
||||
|
||||
func TestNewMovieInvariants(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
id catalog.MovieID
|
||||
title string
|
||||
year int
|
||||
rating float64
|
||||
wantErr bool
|
||||
}{
|
||||
{"ok", "1", "Alien", 1979, 8.5, false},
|
||||
{"empty id", "", "Alien", 1979, 8.5, true},
|
||||
{"blank title", "1", " ", 1979, 8.5, true},
|
||||
{"pre-cinema", "1", "Alien", 1800, 8.5, true},
|
||||
{"rating too high", "1", "Alien", 1979, 11, true},
|
||||
{"rating negative", "1", "Alien", 1979, -1, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
m, err := catalog.NewMovie(tc.id, tc.title, "", nil, tc.year, tc.rating)
|
||||
if tc.wantErr {
|
||||
if !errors.Is(err, catalog.ErrInvalidMovie) {
|
||||
t.Fatalf("want ErrInvalidMovie, got %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if m.Title() != "Alien" {
|
||||
t.Fatalf("title not trimmed/kept: %q", m.Title())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenresAreCopied(t *testing.T) {
|
||||
m, err := catalog.NewMovie("1", "Alien", "", []string{"Horror", " ", "SciFi"}, 1979, 8.5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := m.Genres()
|
||||
if len(g) != 2 {
|
||||
t.Fatalf("blank genre not dropped: %v", g)
|
||||
}
|
||||
g[0] = "mutated"
|
||||
if m.Genres()[0] != "Horror" {
|
||||
t.Fatal("Genres() leaked internal slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryNormalize(t *testing.T) {
|
||||
q := catalog.Query{Limit: 0, Offset: -5}.Normalize()
|
||||
if q.Limit != 20 || q.Offset != 0 {
|
||||
t.Fatalf("bad defaults: %+v", q)
|
||||
}
|
||||
if (catalog.Query{Limit: 1000}).Normalize().Limit != 20 {
|
||||
t.Fatal("limit not capped")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package catalog
|
||||
|
||||
import "context"
|
||||
|
||||
// Query is a value object describing a search request in domain terms.
|
||||
// The domain does not know Meilisearch filter syntax; the adapter translates it.
|
||||
type Query struct {
|
||||
Text string
|
||||
Genre string // optional facet filter
|
||||
MinYear int // 0 = unbounded
|
||||
MaxYear int // 0 = unbounded
|
||||
MinRating float64 // 0 = unbounded
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// Normalize applies defaults. Kept in the domain so every caller gets the same
|
||||
// paging rules.
|
||||
func (q Query) Normalize() Query {
|
||||
if q.Limit <= 0 || q.Limit > 100 {
|
||||
q.Limit = 20
|
||||
}
|
||||
if q.Offset < 0 {
|
||||
q.Offset = 0
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// Hit is a movie plus the search metadata produced by the engine.
|
||||
type Hit struct {
|
||||
Movie *Movie
|
||||
Formatted string // highlighted title, may be empty
|
||||
}
|
||||
|
||||
// Facet is one facet value with its document count.
|
||||
type Facet struct {
|
||||
Value string
|
||||
Count int
|
||||
}
|
||||
|
||||
// Results is the outcome of a search: hits, total estimate and facets.
|
||||
type Results struct {
|
||||
Hits []Hit
|
||||
EstimatedTotal int64
|
||||
ProcessingMS int64
|
||||
Genres []Facet
|
||||
}
|
||||
|
||||
// MovieIndex is the driven port (hexagonal "right side"). The infrastructure
|
||||
// layer provides a Meilisearch implementation; tests provide a fake.
|
||||
type MovieIndex interface {
|
||||
// EnsureSchema makes the index searchable/filterable/sortable as this
|
||||
// bounded context requires. Idempotent.
|
||||
EnsureSchema(ctx context.Context) error
|
||||
Index(ctx context.Context, movies []*Movie) error
|
||||
Get(ctx context.Context, id MovieID) (*Movie, error)
|
||||
Delete(ctx context.Context, id MovieID) error
|
||||
Search(ctx context.Context, q Query) (Results, error)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Package config reads process configuration from the environment.
|
||||
package config
|
||||
|
||||
import "os"
|
||||
|
||||
type Config struct {
|
||||
MeiliHost string
|
||||
MeiliKey string
|
||||
IndexUID string
|
||||
HTTPAddr string
|
||||
SeedFile string
|
||||
}
|
||||
|
||||
func Load() Config {
|
||||
return Config{
|
||||
MeiliHost: env("MEILI_HOST", "http://localhost:7700"),
|
||||
MeiliKey: env("MEILI_MASTER_KEY", ""),
|
||||
IndexUID: env("MEILI_INDEX", "movies"),
|
||||
HTTPAddr: env("HTTP_ADDR", ":8080"),
|
||||
SeedFile: env("SEED_FILE", "data/movies.json"),
|
||||
}
|
||||
}
|
||||
|
||||
func env(k, def string) string {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package meili
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/meilisearch/meilisearch-go"
|
||||
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
)
|
||||
|
||||
// buildFilter translates the domain Query into Meilisearch filter syntax.
|
||||
// Returns nil when there is nothing to filter, so the request stays clean.
|
||||
func buildFilter(q catalog.Query) interface{} {
|
||||
var parts []string
|
||||
if g := strings.TrimSpace(q.Genre); g != "" {
|
||||
parts = append(parts, fmt.Sprintf("genres = %q", g))
|
||||
}
|
||||
if q.MinYear > 0 {
|
||||
parts = append(parts, fmt.Sprintf("year >= %d", q.MinYear))
|
||||
}
|
||||
if q.MaxYear > 0 {
|
||||
parts = append(parts, fmt.Sprintf("year <= %d", q.MaxYear))
|
||||
}
|
||||
if q.MinRating > 0 {
|
||||
parts = append(parts, fmt.Sprintf("rating >= %g", q.MinRating))
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return nil
|
||||
}
|
||||
return strings.Join(parts, " AND ")
|
||||
}
|
||||
|
||||
// decodeGenreFacets turns the raw facetDistribution JSON into domain facets,
|
||||
// sorted by count desc then value, so output is deterministic.
|
||||
func decodeGenreFacets(raw json.RawMessage) []catalog.Facet {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
var dist map[string]map[string]int
|
||||
if err := json.Unmarshal(raw, &dist); err != nil {
|
||||
return nil
|
||||
}
|
||||
counts := dist["genres"]
|
||||
facets := make([]catalog.Facet, 0, len(counts))
|
||||
for v, c := range counts {
|
||||
facets = append(facets, catalog.Facet{Value: v, Count: c})
|
||||
}
|
||||
sort.Slice(facets, func(i, j int) bool {
|
||||
if facets[i].Count != facets[j].Count {
|
||||
return facets[i].Count > facets[j].Count
|
||||
}
|
||||
return facets[i].Value < facets[j].Value
|
||||
})
|
||||
return facets
|
||||
}
|
||||
|
||||
// highlightedTitle extracts _formatted.title from a hit, if present.
|
||||
func highlightedTitle(h meilisearch.Hit) string {
|
||||
raw, ok := h["_formatted"]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
var formatted struct {
|
||||
Title string `json:"title"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &formatted); err != nil {
|
||||
return ""
|
||||
}
|
||||
return formatted.Title
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package meili
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
)
|
||||
|
||||
func TestBuildFilter(t *testing.T) {
|
||||
if got := buildFilter(catalog.Query{}); got != nil {
|
||||
t.Fatalf("empty query must not filter, got %v", got)
|
||||
}
|
||||
got := buildFilter(catalog.Query{Genre: "Sci-Fi", MinYear: 1970, MaxYear: 1999, MinRating: 8})
|
||||
want := `genres = "Sci-Fi" AND year >= 1970 AND year <= 1999 AND rating >= 8`
|
||||
if got != want {
|
||||
t.Fatalf("got %v\nwant %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeGenreFacetsSorted(t *testing.T) {
|
||||
raw := json.RawMessage(`{"genres":{"Drama":2,"Action":5,"Comedy":2}}`)
|
||||
f := decodeGenreFacets(raw)
|
||||
if len(f) != 3 || f[0].Value != "Action" || f[1].Value != "Comedy" || f[2].Value != "Drama" {
|
||||
t.Fatalf("unexpected order: %+v", f)
|
||||
}
|
||||
if decodeGenreFacets(nil) != nil {
|
||||
t.Fatal("nil facets expected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Package meili adapts the Meilisearch client to the catalog.MovieIndex port.
|
||||
// This is the only package in the repo that imports the Meilisearch SDK.
|
||||
package meili
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/meilisearch/meilisearch-go"
|
||||
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
)
|
||||
|
||||
// document is the persistence model. It is intentionally separate from the
|
||||
// domain aggregate so index/search concerns never leak into the domain.
|
||||
type document struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Overview string `json:"overview"`
|
||||
Genres []string `json:"genres"`
|
||||
Year int `json:"year"`
|
||||
Rating float64 `json:"rating"`
|
||||
}
|
||||
|
||||
func toDocument(m *catalog.Movie) document {
|
||||
return document{ID: m.ID().String(), Title: m.Title(), Overview: m.Overview(), Genres: m.Genres(), Year: m.Year(), Rating: m.Rating()}
|
||||
}
|
||||
|
||||
func (d document) toDomain() (*catalog.Movie, error) {
|
||||
id, err := catalog.NewMovieID(d.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return catalog.NewMovie(id, d.Title, d.Overview, d.Genres, d.Year, d.Rating)
|
||||
}
|
||||
|
||||
// MovieIndex implements catalog.MovieIndex on top of a Meilisearch index.
|
||||
type MovieIndex struct {
|
||||
client meilisearch.ServiceManager
|
||||
uid string
|
||||
wait time.Duration // polling interval while waiting for async tasks
|
||||
}
|
||||
|
||||
// Compile-time proof that the adapter satisfies the driven port.
|
||||
var _ catalog.MovieIndex = (*MovieIndex)(nil)
|
||||
|
||||
func NewMovieIndex(host, apiKey, uid string) *MovieIndex {
|
||||
var opts []meilisearch.Option
|
||||
if apiKey != "" {
|
||||
opts = append(opts, meilisearch.WithAPIKey(apiKey))
|
||||
}
|
||||
return &MovieIndex{client: meilisearch.New(host, opts...), uid: uid, wait: 50 * time.Millisecond}
|
||||
}
|
||||
|
||||
func (x *MovieIndex) Close() { x.client.Close() }
|
||||
|
||||
// EnsureSchema creates the index if needed and applies the settings the domain
|
||||
// needs: full-text fields, facets/filters and sortable fields.
|
||||
func (x *MovieIndex) EnsureSchema(ctx context.Context) error {
|
||||
task, err := x.client.CreateIndexWithContext(ctx, &meilisearch.IndexConfig{Uid: x.uid, PrimaryKey: "id"})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create index: %w", err)
|
||||
}
|
||||
// Index creation is an async task: an existing index shows up as a failed
|
||||
// task with code index_already_exists, which is the idempotent happy path.
|
||||
if err := x.await(ctx, task); err != nil && !errors.Is(err, errIndexExists) {
|
||||
return err
|
||||
}
|
||||
|
||||
task, err = x.client.Index(x.uid).UpdateSettingsWithContext(ctx, &meilisearch.Settings{
|
||||
SearchableAttributes: []string{"title", "overview", "genres"},
|
||||
FilterableAttributes: []string{"genres", "year", "rating"},
|
||||
SortableAttributes: []string{"year", "rating"},
|
||||
DisplayedAttributes: []string{"id", "title", "overview", "genres", "year", "rating"},
|
||||
RankingRules: []string{"words", "typo", "proximity", "attribute", "sort", "exactness", "rating:desc"},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("update settings: %w", err)
|
||||
}
|
||||
return x.await(ctx, task)
|
||||
}
|
||||
|
||||
func (x *MovieIndex) Index(ctx context.Context, movies []*catalog.Movie) error {
|
||||
if len(movies) == 0 {
|
||||
return nil
|
||||
}
|
||||
docs := make([]document, 0, len(movies))
|
||||
for _, m := range movies {
|
||||
docs = append(docs, toDocument(m))
|
||||
}
|
||||
task, err := x.client.Index(x.uid).AddDocumentsWithContext(ctx, docs, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("add documents: %w", err)
|
||||
}
|
||||
return x.await(ctx, task)
|
||||
}
|
||||
|
||||
func (x *MovieIndex) Get(ctx context.Context, id catalog.MovieID) (*catalog.Movie, error) {
|
||||
var d document
|
||||
if err := x.client.Index(x.uid).GetDocumentWithContext(ctx, id.String(), nil, &d); err != nil {
|
||||
var mErr *meilisearch.Error
|
||||
if errors.As(err, &mErr) && mErr.StatusCode == 404 {
|
||||
return nil, catalog.ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get document: %w", err)
|
||||
}
|
||||
return d.toDomain()
|
||||
}
|
||||
|
||||
func (x *MovieIndex) Delete(ctx context.Context, id catalog.MovieID) error {
|
||||
task, err := x.client.Index(x.uid).DeleteDocumentWithContext(ctx, id.String())
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete document: %w", err)
|
||||
}
|
||||
return x.await(ctx, task)
|
||||
}
|
||||
|
||||
func (x *MovieIndex) Search(ctx context.Context, q catalog.Query) (catalog.Results, error) {
|
||||
req := &meilisearch.SearchRequest{
|
||||
Limit: int64(q.Limit),
|
||||
Offset: int64(q.Offset),
|
||||
Filter: buildFilter(q),
|
||||
Facets: []string{"genres"},
|
||||
AttributesToHighlight: []string{"title"},
|
||||
HighlightPreTag: "<em>",
|
||||
HighlightPostTag: "</em>",
|
||||
}
|
||||
res, err := x.client.Index(x.uid).SearchWithContext(ctx, q.Text, req)
|
||||
if err != nil {
|
||||
return catalog.Results{}, fmt.Errorf("search: %w", err)
|
||||
}
|
||||
|
||||
out := catalog.Results{
|
||||
EstimatedTotal: res.EstimatedTotalHits,
|
||||
ProcessingMS: res.ProcessingTimeMs,
|
||||
Hits: make([]catalog.Hit, 0, len(res.Hits)),
|
||||
}
|
||||
for _, h := range res.Hits {
|
||||
var d document
|
||||
if err := h.DecodeInto(&d); err != nil {
|
||||
return catalog.Results{}, fmt.Errorf("decode hit: %w", err)
|
||||
}
|
||||
m, err := d.toDomain()
|
||||
if err != nil {
|
||||
// A stored document that violates the invariants is a data bug;
|
||||
// surface it rather than silently returning a broken aggregate.
|
||||
return catalog.Results{}, fmt.Errorf("document %q: %w", d.ID, err)
|
||||
}
|
||||
out.Hits = append(out.Hits, catalog.Hit{Movie: m, Formatted: highlightedTitle(h)})
|
||||
}
|
||||
out.Genres = decodeGenreFacets(res.FacetDistribution)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (x *MovieIndex) await(ctx context.Context, task *meilisearch.TaskInfo) error {
|
||||
if task == nil {
|
||||
return nil
|
||||
}
|
||||
t, err := x.client.WaitForTaskWithContext(ctx, task.TaskUID, x.wait)
|
||||
if err != nil {
|
||||
return fmt.Errorf("wait for task %d: %w", task.TaskUID, err)
|
||||
}
|
||||
if t.Status != meilisearch.TaskStatusSucceeded {
|
||||
if t.Error.Code == "index_already_exists" {
|
||||
return errIndexExists
|
||||
}
|
||||
return fmt.Errorf("task %d %s: %s", task.TaskUID, t.Status, t.Error.Message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// errIndexExists is a sentinel for the idempotent create-index path.
|
||||
var errIndexExists = errors.New("meili: index already exists")
|
||||
@@ -0,0 +1,46 @@
|
||||
package http
|
||||
|
||||
import "git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type movieResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Overview string `json:"overview,omitempty"`
|
||||
Genres []string `json:"genres"`
|
||||
Year int `json:"year"`
|
||||
Rating float64 `json:"rating"`
|
||||
Match string `json:"match,omitempty"` // highlighted title
|
||||
}
|
||||
|
||||
type facetResponse struct {
|
||||
Value string `json:"value"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type searchResponse struct {
|
||||
Hits []movieResponse `json:"hits"`
|
||||
EstimatedTotal int64 `json:"estimatedTotal"`
|
||||
ProcessingMS int64 `json:"processingMs"`
|
||||
Genres []facetResponse `json:"genres,omitempty"`
|
||||
}
|
||||
|
||||
func toMovieResponse(m *catalog.Movie) movieResponse {
|
||||
return movieResponse{ID: m.ID().String(), Title: m.Title(), Overview: m.Overview(), Genres: m.Genres(), Year: m.Year(), Rating: m.Rating()}
|
||||
}
|
||||
|
||||
func toSearchResponse(r catalog.Results) searchResponse {
|
||||
out := searchResponse{EstimatedTotal: r.EstimatedTotal, ProcessingMS: r.ProcessingMS, Hits: make([]movieResponse, 0, len(r.Hits))}
|
||||
for _, h := range r.Hits {
|
||||
mr := toMovieResponse(h.Movie)
|
||||
mr.Match = h.Formatted
|
||||
out.Hits = append(out.Hits, mr)
|
||||
}
|
||||
for _, f := range r.Genres {
|
||||
out.Genres = append(out.Genres, facetResponse{Value: f.Value, Count: f.Count})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// Package http is a driving adapter: it turns HTTP requests into use-case
|
||||
// calls and domain results into JSON. No business logic here.
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/app"
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *app.CatalogService
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewHandler(svc *app.CatalogService, log *slog.Logger) *Handler {
|
||||
return &Handler{svc: svc, log: log}
|
||||
}
|
||||
|
||||
func (h *Handler) Routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) })
|
||||
mux.HandleFunc("GET /search", h.search)
|
||||
mux.HandleFunc("GET /movies/{id}", h.get)
|
||||
mux.HandleFunc("POST /movies", h.importMovies)
|
||||
mux.HandleFunc("DELETE /movies/{id}", h.delete)
|
||||
return mux
|
||||
}
|
||||
|
||||
func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
query := catalog.Query{
|
||||
Text: q.Get("q"),
|
||||
Genre: q.Get("genre"),
|
||||
MinYear: atoi(q.Get("min_year")),
|
||||
MaxYear: atoi(q.Get("max_year")),
|
||||
MinRating: atof(q.Get("min_rating")),
|
||||
Limit: atoi(q.Get("limit")),
|
||||
Offset: atoi(q.Get("offset")),
|
||||
}
|
||||
res, err := h.svc.Search(r.Context(), query)
|
||||
if err != nil {
|
||||
h.fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toSearchResponse(res))
|
||||
}
|
||||
|
||||
func (h *Handler) get(w http.ResponseWriter, r *http.Request) {
|
||||
m, err := h.svc.Get(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
h.fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toMovieResponse(m))
|
||||
}
|
||||
|
||||
func (h *Handler) importMovies(w http.ResponseWriter, r *http.Request) {
|
||||
var in []app.MovieInput
|
||||
// Bound the body: this is a trust boundary.
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<20)).Decode(&in); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, errorResponse{Error: "invalid json body"})
|
||||
return
|
||||
}
|
||||
n, err := h.svc.ImportMovies(r.Context(), in)
|
||||
if err != nil {
|
||||
h.fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]int{"indexed": n})
|
||||
}
|
||||
|
||||
func (h *Handler) delete(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.svc.Delete(r.Context(), r.PathValue("id")); err != nil {
|
||||
h.fail(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// fail maps domain errors to status codes; everything unknown is a 500 and is
|
||||
// logged instead of being echoed to the client.
|
||||
func (h *Handler) fail(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, catalog.ErrNotFound):
|
||||
writeJSON(w, http.StatusNotFound, errorResponse{Error: "not found"})
|
||||
case errors.Is(err, catalog.ErrInvalidMovie):
|
||||
writeJSON(w, http.StatusBadRequest, errorResponse{Error: err.Error()})
|
||||
default:
|
||||
h.log.Error("request failed", "err", err)
|
||||
writeJSON(w, http.StatusInternalServerError, errorResponse{Error: "internal error"})
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func atoi(s string) int {
|
||||
n, _ := strconv.Atoi(s)
|
||||
return n
|
||||
}
|
||||
|
||||
func atof(s string) float64 {
|
||||
f, _ := strconv.ParseFloat(s, 64)
|
||||
return f
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package http_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/app"
|
||||
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
|
||||
httpiface "git.jokresner.de/johannes/meilisearch-showcase/internal/interfaces/http"
|
||||
)
|
||||
|
||||
type stubIndex struct {
|
||||
movies map[catalog.MovieID]*catalog.Movie
|
||||
}
|
||||
|
||||
func (s stubIndex) EnsureSchema(context.Context) error { return nil }
|
||||
func (s stubIndex) Index(_ context.Context, ms []*catalog.Movie) error {
|
||||
for _, m := range ms {
|
||||
s.movies[m.ID()] = m
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s stubIndex) Get(_ context.Context, id catalog.MovieID) (*catalog.Movie, error) {
|
||||
m, ok := s.movies[id]
|
||||
if !ok {
|
||||
return nil, catalog.ErrNotFound
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
func (s stubIndex) Delete(context.Context, catalog.MovieID) error { return nil }
|
||||
func (s stubIndex) Search(context.Context, catalog.Query) (catalog.Results, error) {
|
||||
return catalog.Results{EstimatedTotal: 0}, nil
|
||||
}
|
||||
|
||||
func newServer() *httptest.Server {
|
||||
svc := app.NewCatalogService(stubIndex{movies: map[catalog.MovieID]*catalog.Movie{}})
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
return httptest.NewServer(httpiface.NewHandler(svc, log).Routes())
|
||||
}
|
||||
|
||||
func TestImportSearchGetFlow(t *testing.T) {
|
||||
srv := newServer()
|
||||
defer srv.Close()
|
||||
|
||||
body := `[{"id":"1","title":"Alien","genres":["Sci-Fi"],"year":1979,"rating":8.5}]`
|
||||
res, err := srv.Client().Post(srv.URL+"/movies", "application/json", strings.NewReader(body))
|
||||
if err != nil || res.StatusCode != 202 {
|
||||
t.Fatalf("import: %v %v", res.StatusCode, err)
|
||||
}
|
||||
|
||||
res, _ = srv.Client().Get(srv.URL + "/movies/1")
|
||||
if res.StatusCode != 200 {
|
||||
t.Fatalf("get: %d", res.StatusCode)
|
||||
}
|
||||
var m map[string]any
|
||||
json.NewDecoder(res.Body).Decode(&m)
|
||||
if m["title"] != "Alien" {
|
||||
t.Fatalf("payload: %v", m)
|
||||
}
|
||||
|
||||
res, _ = srv.Client().Get(srv.URL + "/movies/404")
|
||||
if res.StatusCode != 404 {
|
||||
t.Fatalf("missing movie must 404, got %d", res.StatusCode)
|
||||
}
|
||||
|
||||
res, _ = srv.Client().Post(srv.URL+"/movies", "application/json", strings.NewReader(`[{"id":"2","title":""}]`))
|
||||
if res.StatusCode != 400 {
|
||||
t.Fatalf("invalid movie must 400, got %d", res.StatusCode)
|
||||
}
|
||||
|
||||
res, _ = srv.Client().Get(srv.URL + "/search?q=alien&genre=Sci-Fi")
|
||||
if res.StatusCode != 200 {
|
||||
t.Fatalf("search: %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user