commit a9674ce14e436dd8a405c212c36c0ae86e680fd4 Author: hermes Date: Wed Sep 9 14:21:52 2026 +0000 DDD Meilisearch showcase: domain/app/infra/interfaces, Taskfile, tests diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3151624 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +bin/ +.meili-data/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..a7e4113 --- /dev/null +++ b/README.md @@ -0,0 +1,121 @@ +# meilisearch-showcase + +A small, production-shaped Go demo of [Meilisearch](https://www.meilisearch.com/): +full-text search with typo tolerance, prefix search, filters, facets and +highlighting — wrapped in a **Domain-Driven Design** layout and driven by +[Task](https://taskfile.dev). + +## Why it is structured this way + +The interesting part of a search demo is not the SDK calls, it is keeping the +search engine out of your business code. Meilisearch is an infrastructure +detail behind a port: + +``` +cmd/ process entrypoints (api, seed) +internal/ + domain/catalog/ entities, value objects, invariants, PORTS + movie.go Movie aggregate + MovieID value object + search.go Query/Results value objects + MovieIndex port + app/ use cases (import, search, get, delete) + infra/ + meili/ DRIVEN adapter: MovieIndex -> Meilisearch + config/ env configuration + interfaces/http/ DRIVING adapter: HTTP -> use cases +test/ integration tests against a live Meilisearch +``` + +Dependencies point inwards only. `internal/domain` and `internal/app` import +nothing from Meilisearch — `go list -deps` proves it. Swapping in Elastic or a +plain `map` means writing one new adapter, not touching the domain. + +The domain speaks `catalog.Query{Genre, MinYear, MinRating}`; the adapter +translates that into Meilisearch filter syntax (`internal/infra/meili/filter.go`). +Documents indexed in Meilisearch use a separate persistence model +(`meili.document`) that is mapped to/from the aggregate, so the read model can +change without breaking invariants. + +## Requirements + +- Go 1.27+ +- Docker (for `task meili:up`) — or any reachable Meilisearch, set `MEILI_HOST` +- [Task](https://taskfile.dev/installation/) + +## Quick start + +```bash +task meili:up # Meilisearch v1.24 on :7700 +task seed # create index, apply settings, load data/movies.json +task run # API on :8080 +# in another shell: +task query # runs scripts/demo-queries.sh +``` + +`task demo` chains up + seed + queries in one go. `task --list` shows everything. + +## API + +| Method | Path | Description | +|--------|----------------|----------------------------------------------| +| GET | `/healthz` | liveness | +| GET | `/search` | `q, genre, min_year, max_year, min_rating, limit, offset` | +| GET | `/movies/{id}` | single document | +| POST | `/movies` | JSON array of movies, validated then indexed | +| DELETE | `/movies/{id}` | remove a document | + +```bash +curl 'localhost:8080/search?q=matrx' # typo tolerance +curl 'localhost:8080/search?q=spid' # prefix search +curl 'localhost:8080/search?q=dream' # searches overviews +curl 'localhost:8080/search?q=&genre=Sci-Fi&min_rating=8' # filter + facets +curl 'localhost:8080/search?q=&limit=5' # browse, ranked by rating +``` + +Response: + +```json +{ + "hits": [ + {"id":"1","title":"The Matrix","genres":["Sci-Fi","Action"],"year":1999, + "rating":8.7,"match":"The Matrix"} + ], + "estimatedTotal": 1, + "processingMs": 0, + "genres": [{"value":"Sci-Fi","count":6}] +} +``` + +## What the index settings do + +`internal/infra/meili/index.go` `EnsureSchema` is idempotent and sets: + +- `searchableAttributes: title, overview, genres` — ranked in that order +- `filterableAttributes: genres, year, rating` — enables filters and facets +- `sortableAttributes: year, rating` +- a custom ranking rule `rating:desc` as the final tie-breaker + +## Tests + +```bash +task test # unit tests, fake index, no Meilisearch needed +task meili:up +task test:integration # real engine: typo tolerance, filters, facets, 404s +``` + +Unit tests use an in-memory `MovieIndex` fake — that is the payoff of the port. + +## Configuration + +| Env | Default | +|--------------------|-------------------------| +| `MEILI_HOST` | `http://localhost:7700` | +| `MEILI_MASTER_KEY` | *(empty)* | +| `MEILI_INDEX` | `movies` | +| `HTTP_ADDR` | `:8080` | +| `SEED_FILE` | `data/movies.json` | + +## Scope + +Deliberately skipped: auth on the demo API, pagination beyond limit/offset, +tenant tokens, embedders/vector search, and a UI. Each would live in its own +adapter without touching `internal/domain`. diff --git a/Taskfile.yml b/Taskfile.yml new file mode 100644 index 0000000..4cc63a3 --- /dev/null +++ b/Taskfile.yml @@ -0,0 +1,100 @@ +version: "3" + +env: + MEILI_HOST: http://localhost:7700 + MEILI_MASTER_KEY: masterKey + MEILI_INDEX: movies + HTTP_ADDR: ":8080" + +vars: + MEILI_DATA: .meili-data + +tasks: + default: + desc: List available tasks + cmds: [task --list] + + tidy: + desc: Sync go.mod/go.sum + cmds: [go mod tidy] + + fmt: + desc: Format the code + cmds: [go fmt ./...] + + vet: + desc: Run go vet + cmds: [go vet ./...] + + test: + desc: Run unit tests (no Meilisearch required) + cmds: [go test ./...] + + test:integration: + desc: Run integration tests against a live Meilisearch (needs meili:up) + cmds: [go test -tags=integration -count=1 ./test/...] + + build: + desc: Build both binaries into bin/ + cmds: + - go build -o bin/api ./cmd/api + - go build -o bin/seed ./cmd/seed + + meili:up: + desc: Start Meilisearch in Docker on :7700 + cmds: + - docker run -d --name meili-showcase -p 7700:7700 + -e MEILI_MASTER_KEY=$MEILI_MASTER_KEY -e MEILI_ENV=development + -v "$PWD/{{.MEILI_DATA}}:/meili_data" getmeili/meilisearch:v1.24 + status: + - docker ps --filter name=meili-showcase --filter status=running --format '{{"{{"}}.Names{{"}}"}}' | grep -q meili-showcase + + meili:down: + desc: Stop and remove the Meilisearch container + cmds: + - docker rm -f meili-showcase + + meili:wait: + desc: Block until Meilisearch answers /health + cmds: + - | + for i in $(seq 1 60); do + curl -fsS "$MEILI_HOST/health" >/dev/null 2>&1 && exit 0 + sleep 0.5 + done + echo "meilisearch did not become healthy" >&2; exit 1 + + seed: + desc: Create the index, apply settings and load data/movies.json + deps: [meili:wait] + cmds: [go run ./cmd/seed] + + run: + desc: Run the HTTP API on $HTTP_ADDR + deps: [meili:wait] + cmds: [go run ./cmd/api] + + demo: + desc: One-shot showcase - start Meilisearch, seed, run example queries + cmds: + - task: meili:up + - task: meili:wait + - task: seed + - task: query + + query: + desc: Run a few example searches against the running API or Meilisearch directly + cmds: + - ./scripts/demo-queries.sh + + clean: + desc: Remove build artifacts and local index data + cmds: + - rm -rf bin {{.MEILI_DATA}} + + ci: + desc: fmt + vet + test + cmds: + - task: fmt + - task: vet + - task: test diff --git a/cmd/api/main.go b/cmd/api/main.go new file mode 100644 index 0000000..9d9893e --- /dev/null +++ b/cmd/api/main.go @@ -0,0 +1,59 @@ +// Command api serves the catalog HTTP API backed by Meilisearch. +package main + +import ( + "context" + "errors" + "log/slog" + stdhttp "net/http" + "os" + "os/signal" + "syscall" + "time" + + "git.jokresner.de/johannes/meilisearch-showcase/internal/app" + "git.jokresner.de/johannes/meilisearch-showcase/internal/infra/config" + "git.jokresner.de/johannes/meilisearch-showcase/internal/infra/meili" + httpiface "git.jokresner.de/johannes/meilisearch-showcase/internal/interfaces/http" +) + +func main() { + log := slog.New(slog.NewTextHandler(os.Stdout, nil)) + cfg := config.Load() + + idx := meili.NewMovieIndex(cfg.MeiliHost, cfg.MeiliKey, cfg.IndexUID) + defer idx.Close() + svc := app.NewCatalogService(idx) + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + setupCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + if err := svc.Setup(setupCtx); err != nil { + log.Error("index setup failed", "err", err) + os.Exit(1) + } + + srv := &stdhttp.Server{ + Addr: cfg.HTTPAddr, + Handler: httpiface.NewHandler(svc, log).Routes(), + ReadHeaderTimeout: 5 * time.Second, + } + + go func() { + log.Info("listening", "addr", cfg.HTTPAddr, "meili", cfg.MeiliHost, "index", cfg.IndexUID) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, stdhttp.ErrServerClosed) { + log.Error("server failed", "err", err) + os.Exit(1) + } + }() + + <-ctx.Done() + shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelShutdown() + if err := srv.Shutdown(shutdownCtx); err != nil { + log.Error("shutdown", "err", err) + } + log.Info("stopped") +} diff --git a/cmd/seed/main.go b/cmd/seed/main.go new file mode 100644 index 0000000..a8de8a5 --- /dev/null +++ b/cmd/seed/main.go @@ -0,0 +1,48 @@ +// Command seed loads the demo dataset into Meilisearch. +package main + +import ( + "context" + "encoding/json" + "log/slog" + "os" + "time" + + "git.jokresner.de/johannes/meilisearch-showcase/internal/app" + "git.jokresner.de/johannes/meilisearch-showcase/internal/infra/config" + "git.jokresner.de/johannes/meilisearch-showcase/internal/infra/meili" +) + +func main() { + log := slog.New(slog.NewTextHandler(os.Stdout, nil)) + cfg := config.Load() + + raw, err := os.ReadFile(cfg.SeedFile) + if err != nil { + log.Error("read seed file", "file", cfg.SeedFile, "err", err) + os.Exit(1) + } + var in []app.MovieInput + if err := json.Unmarshal(raw, &in); err != nil { + log.Error("parse seed file", "err", err) + os.Exit(1) + } + + idx := meili.NewMovieIndex(cfg.MeiliHost, cfg.MeiliKey, cfg.IndexUID) + defer idx.Close() + svc := app.NewCatalogService(idx) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + if err := svc.Setup(ctx); err != nil { + log.Error("setup", "err", err) + os.Exit(1) + } + n, err := svc.ImportMovies(ctx, in) + if err != nil { + log.Error("import", "err", err) + os.Exit(1) + } + log.Info("seeded", "movies", n, "index", cfg.IndexUID) +} diff --git a/data/movies.json b/data/movies.json new file mode 100644 index 0000000..8426bf5 --- /dev/null +++ b/data/movies.json @@ -0,0 +1,222 @@ +[ + { + "id": "1", + "title": "The Matrix", + "overview": "A hacker discovers reality is a simulation and joins a rebellion against the machines.", + "genres": [ + "Sci-Fi", + "Action" + ], + "year": 1999, + "rating": 8.7 + }, + { + "id": "2", + "title": "Alien", + "overview": "The crew of a commercial towing ship answers a distress call and brings aboard a lethal organism.", + "genres": [ + "Sci-Fi", + "Horror" + ], + "year": 1979, + "rating": 8.5 + }, + { + "id": "3", + "title": "Blade Runner", + "overview": "A blade runner hunts replicants in a rain-soaked, neon-lit Los Angeles.", + "genres": [ + "Sci-Fi", + "Thriller" + ], + "year": 1982, + "rating": 8.1 + }, + { + "id": "4", + "title": "Arrival", + "overview": "A linguist is recruited to communicate with alien visitors and learns to perceive time differently.", + "genres": [ + "Sci-Fi", + "Drama" + ], + "year": 2016, + "rating": 7.9 + }, + { + "id": "5", + "title": "Spirited Away", + "overview": "A girl trapped in a spirit world must work in a bathhouse to free her parents.", + "genres": [ + "Animation", + "Fantasy" + ], + "year": 2001, + "rating": 8.6 + }, + { + "id": "6", + "title": "Parasite", + "overview": "A poor family schemes their way into the household of a wealthy one.", + "genres": [ + "Drama", + "Thriller" + ], + "year": 2019, + "rating": 8.5 + }, + { + "id": "7", + "title": "Mad Max: Fury Road", + "overview": "On a desert road, a drifter and a rebel commander flee a warlord in a convoy chase.", + "genres": [ + "Action", + "Adventure" + ], + "year": 2015, + "rating": 8.1 + }, + { + "id": "8", + "title": "The Grand Budapest Hotel", + "overview": "A legendary concierge and his lobby boy are entangled in the theft of a priceless painting.", + "genres": [ + "Comedy", + "Adventure" + ], + "year": 2014, + "rating": 8.1 + }, + { + "id": "9", + "title": "Whiplash", + "overview": "A young drummer is pushed to his limits by a ruthless conservatory instructor.", + "genres": [ + "Drama", + "Music" + ], + "year": 2014, + "rating": 8.5 + }, + { + "id": "10", + "title": "Inception", + "overview": "A thief who steals corporate secrets through dream-sharing is offered a chance to plant an idea.", + "genres": [ + "Sci-Fi", + "Action" + ], + "year": 2010, + "rating": 8.8 + }, + { + "id": "11", + "title": "Spider-Man: Into the Spider-Verse", + "overview": "Miles Morales meets Spider-people from other dimensions.", + "genres": [ + "Animation", + "Action" + ], + "year": 2018, + "rating": 8.4 + }, + { + "id": "12", + "title": "Everything Everywhere All at Once", + "overview": "A laundromat owner must connect with parallel-universe versions of herself to save existence.", + "genres": [ + "Sci-Fi", + "Comedy" + ], + "year": 2022, + "rating": 7.8 + }, + { + "id": "13", + "title": "Seven Samurai", + "overview": "A village hires seven masterless samurai to defend it against bandits.", + "genres": [ + "Drama", + "Action" + ], + "year": 1954, + "rating": 8.6 + }, + { + "id": "14", + "title": "Amelie", + "overview": "A shy Parisian waitress secretly orchestrates small acts of kindness.", + "genres": [ + "Comedy", + "Romance" + ], + "year": 2001, + "rating": 8.3 + }, + { + "id": "15", + "title": "The Thing", + "overview": "An Antarctic research team is infiltrated by a shapeshifting alien.", + "genres": [ + "Horror", + "Sci-Fi" + ], + "year": 1982, + "rating": 8.2 + }, + { + "id": "16", + "title": "Your Name", + "overview": "Two teenagers discover they are mysteriously swapping bodies across time.", + "genres": [ + "Animation", + "Romance" + ], + "year": 2016, + "rating": 8.4 + }, + { + "id": "17", + "title": "Heat", + "overview": "A career criminal and an obsessive detective circle each other across Los Angeles.", + "genres": [ + "Crime", + "Thriller" + ], + "year": 1995, + "rating": 8.3 + }, + { + "id": "18", + "title": "Dune", + "overview": "The heir of a noble house is drawn into a war for control of the desert planet Arrakis.", + "genres": [ + "Sci-Fi", + "Adventure" + ], + "year": 2021, + "rating": 8.0 + }, + { + "id": "19", + "title": "Portrait of a Lady on Fire", + "overview": "A painter falls for the woman whose wedding portrait she was hired to paint in secret.", + "genres": [ + "Drama", + "Romance" + ], + "year": 2019, + "rating": 8.1 + }, + { + "id": "20", + "title": "Groundhog Day", + "overview": "A cynical weatherman relives the same day until he changes.", + "genres": [ + "Comedy", + "Fantasy" + ], + "year": 1993, + "rating": 8.0 + } +] diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5415d6a --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module git.jokresner.de/johannes/meilisearch-showcase + +go 1.24.0 + +require github.com/meilisearch/meilisearch-go v0.34.1 + +require ( + github.com/andybalholm/brotli v1.1.1 // indirect + github.com/golang-jwt/jwt/v4 v4.5.2 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..f09828c --- /dev/null +++ b/go.sum @@ -0,0 +1,16 @@ +github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= +github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= +github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/meilisearch/meilisearch-go v0.34.1 h1:tIPRWZ3GCsq6fnW7hxryNI7EejBWmTIZ9+YOwTho4PA= +github.com/meilisearch/meilisearch-go v0.34.1/go.mod h1:cUVJZ2zMqTvvwIMEEAdsWH+zrHsrLpAw6gm8Lt1MXK0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= +github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/catalog.go b/internal/app/catalog.go new file mode 100644 index 0000000..b56b484 --- /dev/null +++ b/internal/app/catalog.go @@ -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"` +} diff --git a/internal/app/catalog_test.go b/internal/app/catalog_test.go new file mode 100644 index 0000000..85e95b3 --- /dev/null +++ b/internal/app/catalog_test.go @@ -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") + } +} diff --git a/internal/domain/catalog/movie.go b/internal/domain/catalog/movie.go new file mode 100644 index 0000000..93d1421 --- /dev/null +++ b/internal/domain/catalog/movie.go @@ -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 +} diff --git a/internal/domain/catalog/movie_test.go b/internal/domain/catalog/movie_test.go new file mode 100644 index 0000000..746534a --- /dev/null +++ b/internal/domain/catalog/movie_test.go @@ -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") + } +} diff --git a/internal/domain/catalog/search.go b/internal/domain/catalog/search.go new file mode 100644 index 0000000..bb92fe0 --- /dev/null +++ b/internal/domain/catalog/search.go @@ -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) +} diff --git a/internal/infra/config/config.go b/internal/infra/config/config.go new file mode 100644 index 0000000..06209d7 --- /dev/null +++ b/internal/infra/config/config.go @@ -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 +} diff --git a/internal/infra/meili/filter.go b/internal/infra/meili/filter.go new file mode 100644 index 0000000..db3654d --- /dev/null +++ b/internal/infra/meili/filter.go @@ -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 +} diff --git a/internal/infra/meili/filter_test.go b/internal/infra/meili/filter_test.go new file mode 100644 index 0000000..ec4745c --- /dev/null +++ b/internal/infra/meili/filter_test.go @@ -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") + } +} diff --git a/internal/infra/meili/index.go b/internal/infra/meili/index.go new file mode 100644 index 0000000..08ba295 --- /dev/null +++ b/internal/infra/meili/index.go @@ -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: "", + HighlightPostTag: "", + } + 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") diff --git a/internal/interfaces/http/dto.go b/internal/interfaces/http/dto.go new file mode 100644 index 0000000..d2af20d --- /dev/null +++ b/internal/interfaces/http/dto.go @@ -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 +} diff --git a/internal/interfaces/http/router.go b/internal/interfaces/http/router.go new file mode 100644 index 0000000..44b6cb0 --- /dev/null +++ b/internal/interfaces/http/router.go @@ -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 +} diff --git a/internal/interfaces/http/router_test.go b/internal/interfaces/http/router_test.go new file mode 100644 index 0000000..b2a6e79 --- /dev/null +++ b/internal/interfaces/http/router_test.go @@ -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) + } +} diff --git a/scripts/demo-queries.sh b/scripts/demo-queries.sh new file mode 100755 index 0000000..ab37369 --- /dev/null +++ b/scripts/demo-queries.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Example queries showing off Meilisearch behaviour through the demo API. +# Requires the API to be running (task run) and the index seeded (task seed). +set -euo pipefail + +API="${API:-http://localhost:8080}" + +show() { + echo + echo "=== $1" + shift + curl -fsS "$@" | (command -v jq >/dev/null && jq . || cat) +} + +show "typo tolerance: 'matrx' still finds The Matrix" "$API/search?q=matrx&limit=3" +show "prefix search while typing: 'spid'" "$API/search?q=spid&limit=3" +show "full-text over the overview field: 'dream'" "$API/search?q=dream&limit=3" +show "facet + filter: sci-fi after 2000, rating >= 8" "$API/search?q=&genre=Sci-Fi&min_year=2000&min_rating=8" +show "empty query: facets + ranking rule rating:desc" "$API/search?q=&limit=5" +show "single document by id" "$API/movies/1" diff --git a/test/integration_test.go b/test/integration_test.go new file mode 100644 index 0000000..c0e5590 --- /dev/null +++ b/test/integration_test.go @@ -0,0 +1,86 @@ +//go:build integration + +// Package test exercises the real Meilisearch adapter. Run with: +// +// task meili:up && task test:integration +package test + +import ( + "context" + "os" + "testing" + "time" + + "git.jokresner.de/johannes/meilisearch-showcase/internal/app" + "git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog" + "git.jokresner.de/johannes/meilisearch-showcase/internal/infra/meili" +) + +func newService(t *testing.T) (*app.CatalogService, context.Context) { + t.Helper() + host := os.Getenv("MEILI_HOST") + if host == "" { + host = "http://localhost:7700" + } + idx := meili.NewMovieIndex(host, os.Getenv("MEILI_MASTER_KEY"), "movies_test") + t.Cleanup(idx.Close) + + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + t.Cleanup(cancel) + + svc := app.NewCatalogService(idx) + if err := svc.Setup(ctx); err != nil { + t.Fatalf("setup: %v", err) + } + if _, err := svc.ImportMovies(ctx, seed); err != nil { + t.Fatalf("import: %v", err) + } + return svc, ctx +} + +var seed = []app.MovieInput{ + {ID: "1", Title: "The Matrix", Overview: "A hacker learns reality is a simulation.", Genres: []string{"Sci-Fi", "Action"}, Year: 1999, Rating: 8.7}, + {ID: "2", Title: "Alien", Overview: "A lethal organism aboard a towing ship.", Genres: []string{"Sci-Fi", "Horror"}, Year: 1979, Rating: 8.5}, + {ID: "3", Title: "Whiplash", Overview: "A drummer pushed to his limits.", Genres: []string{"Drama", "Music"}, Year: 2014, Rating: 8.5}, +} + +func TestTypoTolerance(t *testing.T) { + svc, ctx := newService(t) + res, err := svc.Search(ctx, catalog.Query{Text: "matrx"}) + if err != nil { + t.Fatal(err) + } + if len(res.Hits) == 0 || res.Hits[0].Movie.Title() != "The Matrix" { + t.Fatalf("typo search failed: %+v", res.Hits) + } + if res.Hits[0].Formatted == "" { + t.Fatal("expected highlighted title") + } +} + +func TestFilterAndFacets(t *testing.T) { + svc, ctx := newService(t) + res, err := svc.Search(ctx, catalog.Query{Genre: "Sci-Fi", MinYear: 1990}) + if err != nil { + t.Fatal(err) + } + if len(res.Hits) != 1 || res.Hits[0].Movie.Title() != "The Matrix" { + t.Fatalf("filter failed: %+v", res.Hits) + } + if len(res.Genres) == 0 { + t.Fatal("expected genre facets") + } +} + +func TestGetAndDelete(t *testing.T) { + svc, ctx := newService(t) + if _, err := svc.Get(ctx, "2"); err != nil { + t.Fatalf("get: %v", err) + } + if err := svc.Delete(ctx, "2"); err != nil { + t.Fatalf("delete: %v", err) + } + if _, err := svc.Get(ctx, "2"); err != catalog.ErrNotFound { + t.Fatalf("want ErrNotFound, got %v", err) + } +}