176 lines
5.8 KiB
Go
176 lines
5.8 KiB
Go
// 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")
|