A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): add rexctl search reindex (#3617)
Hampus6c9760a693a3
diff --git a/fluxer_docs/src/content/docs/operator/rexctl.mdx b/fluxer_docs/src/content/docs/operator/rexctl.mdxindex 49aee121e..b61e8a6e6 100644--- a/fluxer_docs/src/content/docs/operator/rexctl.mdx+++ b/fluxer_docs/src/content/docs/operator/rexctl.mdx@@ -579,6 +579,22 @@ rexctl rollback [flags]Also restore the database from the backup taken before the upgrade.+## rexctl search++Manage search on your instance.++### rexctl search reindex++Rebuild every search index from your data, with the messages in every channel and DM. Search shows partial results until it finishes. If a rebuild is already running, rexctl follows that one, and stopping rexctl doesn't stop the rebuild.++```sh+rexctl search reindex [flags]+```++- `--no-wait`++ Start the rebuild and return without waiting for it.+## rexctl setupCreate the admin account and finish setup in the terminal.diff --git a/fluxer_rexctl/cmd/root.go b/fluxer_rexctl/cmd/root.goindex 9f2a56587..64cc14aa1 100644--- a/fluxer_rexctl/cmd/root.go+++ b/fluxer_rexctl/cmd/root.go@@ -123,6 +123,7 @@ func newRoot(app *App) *cobra.Command {newRegistrationCmd(app),newEmailCmd(app),newBrandingCmd(app),+ newSearchCmd(app),newConfigCmd(app),newVersionCmd(app),newDocsCmd(app),@@ -158,7 +159,7 @@ const (var commandGroups = map[string][]string{"run": {"install", "setup", "status", "doctor", "logs", "start", "stop", "restart", "upgrade", "rollback", "backup", "restore", "proxy", "takeover", "eject", "uninstall"},- "manage": {"users", "admins", "invites", "registration", "email", "branding", "config"},+ "manage": {"users", "admins", "invites", "registration", "email", "branding", "search", "config"},"other": {"version", "docs"},}diff --git a/fluxer_rexctl/cmd/search.go b/fluxer_rexctl/cmd/search.goindex 34c603776..0d67776fc 100644--- a/fluxer_rexctl/cmd/search.go+++ b/fluxer_rexctl/cmd/search.go@@ -7,16 +7,22 @@ import ("fmt""strconv""strings"+ "time"+ "github.com/spf13/cobra"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui")const (searchService = "meilisearch"searchVolume = "meilisearch-data"+ reindexPoll = 2 * time.Second)func runningImage(ctx context.Context, p *engine.Project, service string) string {@@ -54,7 +60,7 @@ func keepSearchReadable(ctx context.Context, app *App, inst *instance.Instance,return err}app.UI.Warn(fmt.Sprintf("%s can't read the search index that a newer Meilisearch wrote, and no backup has a copy it can read, so rexctl emptied it.", name),- `Rebuild it with the "Reindex" buttons on the admin panel's search index page, and with "Refresh Channel Messages" on each community's page there.`)+ "Run rexctl search reindex to rebuild it.")return p.Up(ctx, engine.UpOptions{Services: []string{searchService}, NoDeps: true})}@@ -87,3 +93,99 @@ func searchVersion(ref string) ([2]int, bool) {}return v, true}++func newSearchCmd(app *App) *cobra.Command {+ c := &cobra.Command{Use: "search", Short: "Manage search on your instance", Args: noArgs}+ var noWait bool+ reindex := &cobra.Command{+ Use: "reindex",+ Short: "Rebuild search from your data",+ Long: "Rebuild every search index from your data, with the messages in every channel and DM. Search shows partial results until it finishes. If a rebuild is already running, rexctl follows that one, and stopping rexctl doesn't stop the rebuild.",+ Args: noArgs,+ }+ reindex.Flags().BoolVar(&noWait, "no-wait", false, "start the rebuild and return without waiting for it")+ reindex.RunE = func(c *cobra.Command, _ []string) error {+ var jobID string+ err := adminWrite(c, app, func(ctx context.Context, api *adminapi.Client, _ *instance.Instance) error {+ id, err := api.ReindexSearch(ctx)+ jobID = id+ return err+ })+ if err != nil {+ return err+ }+ if noWait {+ app.UI.OK("Started rebuilding search. Run rexctl search reindex to follow it.")+ return nil+ }+ return adminRead(c, app, func(ctx context.Context, api *adminapi.Client, _ *instance.Instance) error {+ return followReindex(ctx, app, api, jobID)+ })+ }+ c.AddCommand(reindex)+ return c+}++func followReindex(ctx context.Context, app *App, api *adminapi.Client, jobID string) error {+ return app.UI.Step(ctx, "Rebuilding search", func(ctx context.Context, s *ui.Step) error {+ for {+ st, err := api.SearchReindexStatus(ctx, jobID)+ if err != nil {+ return err+ }+ switch st.Status {+ case "completed":+ s.Done("Rebuilt search.")+ return nil+ case "failed":+ msg := "Rebuilding search failed."+ if st.Error != "" {+ msg = "Rebuilding search failed. " + sentenceOf(st.Error)+ }+ return ui.Failed(msg, "Run rexctl logs worker to see why, then run rexctl search reindex again.")+ case "not_found":+ return ui.Failed("rexctl lost track of the rebuild.", "Run rexctl search reindex again.")+ }+ s.Title(reindexTitle(st))+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(reindexPoll):+ }+ }+ })+}++func reindexTitle(st *adminapi.SearchReindexStatus) string {+ switch st.Phase {+ case "queued":+ return "Waiting for a worker to start rebuilding search"+ case "guild_members":+ return fmt.Sprintf("Rebuilding search for members, %s of %s communities", thousands(st.Indexed), thousands(st.Total))+ case "threads":+ return fmt.Sprintf("Rebuilding search for threads, %s of %s communities", thousands(st.Indexed), thousands(st.Total))+ case "messages":+ return fmt.Sprintf("Rebuilding search for messages, %s of %s channels", thousands(st.Indexed), thousands(st.Total))+ }+ what, ok := reindexPhases[st.Phase]+ if !ok {+ return "Rebuilding search"+ }+ return fmt.Sprintf("Rebuilding search for %s, %s done", what, thousands(st.Indexed))+}++var reindexPhases = map[string]string{+ "users": "accounts",+ "guilds": "communities",+ "discovery": "Explore",+ "reports": "reports",+ "audit_logs": "the admin audit log",+}++func thousands(n int64) string {+ s := fmt.Sprint(n)+ for i := len(s) - 3; i > 0; i -= 3 {+ s = s[:i] + "," + s[i:]+ }+ return s+}diff --git a/fluxer_rexctl/internal/adminapi/explain.go b/fluxer_rexctl/internal/adminapi/explain.goindex 8b45bade5..f2a17a3ff 100644--- a/fluxer_rexctl/internal/adminapi/explain.go+++ b/fluxer_rexctl/internal/adminapi/explain.go@@ -32,6 +32,10 @@ func Explain(err error) error {switch {case errors.Is(err, ErrSchemaMismatch):return &ui.ExitError{Code: ui.ExitRefused, Msg: "This rexctl and the Fluxer running here don't match.", Fix: "Run rexctl upgrade.", Err: err}+ case errors.Is(err, ErrNoFullReindex):+ return &ui.ExitError{Code: ui.ExitRefused, Msg: "The Fluxer release running here can't rebuild search in one go.", Fix: `Run rexctl upgrade, or use the "Reindex" buttons on the admin panel's search index page and "Refresh Channel Messages" on each community's page there.`, Err: err}+ case errors.Is(err, ErrSearchOff):+ return &ui.ExitError{Code: ui.ExitFailed, Msg: "Search is turned off on this instance.", Fix: "Run rexctl doctor to see what's wrong.", Err: err}case errors.Is(err, ErrNoRelay):return &ui.ExitError{Code: ui.ExitRefused, Msg: "The Fluxer release running here can't take commands from rexctl.", Fix: "Run rexctl upgrade.", Err: err}case errors.As(err, &relay):diff --git a/fluxer_rexctl/internal/adminapi/search.go b/fluxer_rexctl/internal/adminapi/search.gonew file mode 100644index 000000000..68d4d37e1--- /dev/null+++ b/fluxer_rexctl/internal/adminapi/search.go@@ -0,0 +1,48 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package adminapi++import (+ "context"+ "errors"+ "net/http"+ "net/url"+)++type SearchReindexStatus struct {+ Status string `json:"status"`+ Phase string `json:"phase"`+ Total int64 `json:"total"`+ Indexed int64 `json:"indexed"`+ Error string `json:"error"`+}++var (+ ErrNoFullReindex = errors.New("adminapi: this Fluxer release can't rebuild every search index at once")+ ErrSearchOff = errors.New("adminapi: search is turned off")+)++func (c *Client) ReindexSearch(ctx context.Context) (string, error) {+ var resp struct {+ JobID string `json:"job_id"`+ }+ err := c.Call(ctx, http.MethodPost, "/admin/search/indexes/all/refreshes", nil, map[string]any{}, &resp)+ var api *APIError+ switch {+ case errors.As(err, &api) && api.Status == http.StatusBadRequest:+ return "", ErrNoFullReindex+ case errors.As(err, &api) && api.Code == "FEATURE_TEMPORARILY_DISABLED":+ return "", ErrSearchOff+ case err != nil:+ return "", err+ }+ return resp.JobID, nil+}++func (c *Client) SearchReindexStatus(ctx context.Context, jobID string) (*SearchReindexStatus, error) {+ var resp SearchReindexStatus+ if err := c.Call(ctx, http.MethodGet, "/admin/search/index-refreshes/"+url.PathEscape(jobID), nil, nil, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}