From 0b424fe95e252ad68bf374a2b46553ff32c99e0e Mon Sep 17 00:00:00 2001 From: kolaente Date: Thu, 11 Jul 2024 12:07:22 +0200 Subject: [PATCH] fix(typesense): do not crash after creating a project when tasks are not yet indexed Before this fix, creating a project with Typesense enabled would fail with an error because the tasks it fetches as part of that process do not have the task position property in their index. We now fall back to using the db for searching in that case. In the long run, we should use typesense joins for the task position to make this more efficient. --- pkg/models/task_position.go | 3 ++- pkg/models/tasks.go | 22 +++++++++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/pkg/models/task_position.go b/pkg/models/task_position.go index c00445ae6..92383cf66 100644 --- a/pkg/models/task_position.go +++ b/pkg/models/task_position.go @@ -19,6 +19,7 @@ package models import ( "math" + "code.vikunja.io/api/pkg/events" "code.vikunja.io/web" "xorm.io/xorm" ) @@ -137,7 +138,7 @@ func RecalculateTaskPositions(s *xorm.Session, view *ProjectView, a web.Auth) (e allTasks, _, _, err := getRawTasksForProjects(s, projects, a, opts) if err != nil { - return err + return } if len(allTasks) == 0 { return diff --git a/pkg/models/tasks.go b/pkg/models/tasks.go index 17aceded0..9fc115ce3 100644 --- a/pkg/models/tasks.go +++ b/pkg/models/tasks.go @@ -17,6 +17,7 @@ package models import ( + "errors" "math" "regexp" "sort" @@ -24,6 +25,8 @@ import ( "strings" "time" + "github.com/typesense/typesense-go/typesense" + "code.vikunja.io/api/pkg/config" "code.vikunja.io/api/pkg/events" "code.vikunja.io/api/pkg/log" @@ -289,20 +292,29 @@ func getRawTasksForProjects(s *xorm.Session, projects []*Project, a web.Auth, op }) } - var searcher taskSearcher = &dbTaskSearcher{ + opts.search = strings.TrimSpace(opts.search) + + var dbSearcher taskSearcher = &dbTaskSearcher{ s: s, a: a, hasFavoritesProject: hasFavoritesProject, } if config.TypesenseEnabled.GetBool() { - searcher = &typesenseTaskSearcher{ + var tsSearcher taskSearcher = &typesenseTaskSearcher{ s: s, } + tasks, totalItems, err = tsSearcher.Search(opts) + // It is possible that project views are not yet in Typesnse's index. This causes the query here to fail. + // To avoid crashing everything, we fall back to the db search in that case. + var tsErr = &typesense.HTTPError{} + if err != nil && errors.As(err, &tsErr) && tsErr.Status == 404 { + log.Warningf("Unable to fetch tasks from Typesense, error was '%v'. Falling back to db.", err) + tasks, totalItems, err = dbSearcher.Search(opts) + } + } else { + tasks, totalItems, err = dbSearcher.Search(opts) } - opts.search = strings.TrimSpace(opts.search) - - tasks, totalItems, err = searcher.Search(opts) return tasks, len(tasks), totalItems, err }