code.gitea.io/gitea@v1.22.3/modules/indexer/internal/meilisearch/indexer.go (about) 1 // Copyright 2023 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package meilisearch 5 6 import ( 7 "context" 8 "fmt" 9 10 "github.com/meilisearch/meilisearch-go" 11 ) 12 13 // Indexer represents a basic meilisearch indexer implementation 14 type Indexer struct { 15 Client *meilisearch.Client 16 17 url, apiKey string 18 indexName string 19 version int 20 settings *meilisearch.Settings 21 } 22 23 func NewIndexer(url, apiKey, indexName string, version int, settings *meilisearch.Settings) *Indexer { 24 return &Indexer{ 25 url: url, 26 apiKey: apiKey, 27 indexName: indexName, 28 version: version, 29 settings: settings, 30 } 31 } 32 33 // Init initializes the indexer 34 func (i *Indexer) Init(_ context.Context) (bool, error) { 35 if i == nil { 36 return false, fmt.Errorf("cannot init nil indexer") 37 } 38 39 if i.Client != nil { 40 return false, fmt.Errorf("indexer is already initialized") 41 } 42 43 i.Client = meilisearch.NewClient(meilisearch.ClientConfig{ 44 Host: i.url, 45 APIKey: i.apiKey, 46 }) 47 48 _, err := i.Client.GetIndex(i.VersionedIndexName()) 49 if err == nil { 50 return true, nil 51 } 52 _, err = i.Client.CreateIndex(&meilisearch.IndexConfig{ 53 Uid: i.VersionedIndexName(), 54 PrimaryKey: "id", 55 }) 56 if err != nil { 57 return false, err 58 } 59 60 i.checkOldIndexes() 61 62 _, err = i.Client.Index(i.VersionedIndexName()).UpdateSettings(i.settings) 63 return false, err 64 } 65 66 // Ping checks if the indexer is available 67 func (i *Indexer) Ping(ctx context.Context) error { 68 if i == nil { 69 return fmt.Errorf("cannot ping nil indexer") 70 } 71 if i.Client == nil { 72 return fmt.Errorf("indexer is not initialized") 73 } 74 resp, err := i.Client.Health() 75 if err != nil { 76 return err 77 } 78 if resp.Status != "available" { 79 // See https://docs.meilisearch.com/reference/api/health.html#status 80 return fmt.Errorf("status of meilisearch is not available: %s", resp.Status) 81 } 82 return nil 83 } 84 85 // Close closes the indexer 86 func (i *Indexer) Close() { 87 if i == nil { 88 return 89 } 90 i.Client = nil 91 }