Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion hub3/fragments/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,20 @@ func (tq *TreeQuery) GetPreviousScrollIDs(cLevel string, sr *SearchRequest, page
SortBy(fieldSort, idSort).
Size(100).
FetchSource(false).
Query(query)
Query(query).
KeepAlive("1m")

// Clear on every return path, otherwise the scroll context lingers
// until its keepalive expires and counts against
// search.max_open_scroll_context.
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if clearErr := scroll.Clear(ctx); clearErr != nil {
log.Printf("unable to clear tree navigation scroll: %v", clearErr)
}
}()

cursor := 0

Expand Down
114 changes: 92 additions & 22 deletions ikuzo/service/x/bulk/handle_ids.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
package bulk

import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"

c "github.com/delving/hub3/config"
"github.com/delving/hub3/hub3/fragments"
"github.com/delving/hub3/hub3/index"
"github.com/delving/hub3/ikuzo/driver/elasticsearch"
"github.com/go-chi/chi/v5"
"github.com/olivere/elastic/v7"
"github.com/rs/zerolog/log"
)

const indexIDsKeepAlive = "1m"

// handleIndexIDs streams every indexed hubID for a dataset, one per line.
// The consumer (Narthex) diffs this list against its record registry to
// find records that were sent but silently never landed in the index —
// index_verify reports only counts, so which ids are missing can only be
// determined by the party that knows the expected set.
//
// It pages with a point in time and search_after rather than a scroll, so
// it does not count against search.max_open_scroll_context.
func (s *Service) handleIndexIDs(w http.ResponseWriter, r *http.Request) {
orgID := chi.URLParam(r, "orgID")
datasetID := chi.URLParam(r, "datasetID")
Expand All @@ -35,34 +42,98 @@ func (s *Service) handleIndexIDs(w http.ResponseWriter, r *http.Request) {
elastic.NewTermQuery(c.Config.ElasticSearch.OrgIDKey, orgID),
)

es := c.Config.ElasticSearch

pit, err := elasticsearch.NewPITClient(es.Urls, es.UserName, es.Password)
if err != nil {
log.Error().Err(err).Str("orgID", orgID).Str("datasetID", datasetID).
Msg("index-ids unable to create point in time client")
http.Error(w, fmt.Sprintf("search failed: %v", err), http.StatusInternalServerError)

return
}

pitID, err := pit.CreatePIT(r.Context(), es.GetIndexName(orgID), indexIDsKeepAlive)
if err != nil {
log.Error().Err(err).Str("orgID", orgID).Str("datasetID", datasetID).
Msg("index-ids unable to open point in time")
http.Error(w, fmt.Sprintf("search failed: %v", err), http.StatusInternalServerError)

return
}

// Close with a context that survives a client disconnect, so an aborted
// stream does not leave the point in time open until it expires.
defer func() {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 10*time.Second)
defer cancel()

if closeErr := pit.ClosePIT(ctx, pitID); closeErr != nil {
log.Error().Err(closeErr).Str("orgID", orgID).Str("datasetID", datasetID).
Msg("index-ids unable to close point in time")
}
}()

w.Header().Set("Content-Type", "text/plain; charset=utf-8")

scroll := index.ESClient().Scroll(c.Config.ElasticSearch.GetIndexName(orgID)).
Query(q).
FetchSourceContext(elastic.NewFetchSourceContext(true).Include("meta.hubID")).
Size(2500)
defer scroll.Clear(r.Context())
seen, err := writeIndexIDs(w, func(searchAfter []interface{}) ([]*elastic.SearchHit, error) {
search := index.ESClient().Search().
Query(q).
PointInTime(elastic.NewPointInTimeWithKeepAlive(pitID, indexIDsKeepAlive)).
FetchSourceContext(elastic.NewFetchSourceContext(true).Include("meta.hubID")).
Sort("meta.hubID", true).
Size(2500)

seen := 0
if len(searchAfter) > 0 {
search = search.SearchAfter(searchAfter...)
}

for {
res, err := scroll.Do(r.Context())
res, err := search.Do(r.Context())
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, err
}

log.Error().Err(err).Str("orgID", orgID).Str("datasetID", datasetID).
Msg("index-ids scroll failed")
if res.Hits == nil {
return nil, nil
}

if seen == 0 {
http.Error(w, fmt.Sprintf("scroll failed: %v", err), http.StatusInternalServerError)
}
return res.Hits.Hits, nil
})
if err != nil {
log.Error().Err(err).Str("orgID", orgID).Str("datasetID", datasetID).
Msg("index-ids search failed")

return
if seen == 0 {
http.Error(w, fmt.Sprintf("search failed: %v", err), http.StatusInternalServerError)
}

for _, hit := range res.Hits.Hits {
return
}

log.Info().Str("orgID", orgID).Str("datasetID", datasetID).Int("ids", seen).
Msg("index-ids stream served")
}

// writeIndexIDs pages through fetch with search_after until it returns an
// empty page, writing one hubID per line and flushing after every page.
// It returns the number of ids written, also when it fails part way.
func writeIndexIDs(w io.Writer, fetch func(searchAfter []interface{}) ([]*elastic.SearchHit, error)) (int, error) {
var (
seen int
searchAfter []interface{}
)

for {
hits, err := fetch(searchAfter)
if err != nil {
return seen, err
}

if len(hits) == 0 {
return seen, nil
}

for _, hit := range hits {
var doc struct {
Meta struct {
HubID string `json:"hubID"`
Expand All @@ -79,8 +150,7 @@ func (s *Service) handleIndexIDs(w http.ResponseWriter, r *http.Request) {
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}

log.Info().Str("orgID", orgID).Str("datasetID", datasetID).Int("ids", seen).
Msg("index-ids stream served")
searchAfter = hits[len(hits)-1].Sort
}
}
98 changes: 98 additions & 0 deletions ikuzo/service/x/bulk/handle_ids_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package bulk

import (
"encoding/json"
"errors"
"fmt"
"net/http/httptest"
"testing"

"github.com/olivere/elastic/v7"
)

func idHit(hubID string) *elastic.SearchHit {
return &elastic.SearchHit{
Source: json.RawMessage(fmt.Sprintf(`{"meta":{"hubID":%q}}`, hubID)),
Sort: []interface{}{hubID},
}
}

func TestWriteIndexIDs(t *testing.T) {
pages := [][]*elastic.SearchHit{
{idHit("a"), idHit("b")},
{{Source: json.RawMessage(`{"meta":{}}`), Sort: []interface{}{"b2"}}, idHit("c")},
{},
}

var calls [][]interface{}

w := httptest.NewRecorder()

seen, err := writeIndexIDs(w, func(searchAfter []interface{}) ([]*elastic.SearchHit, error) {
calls = append(calls, searchAfter)
page := pages[len(calls)-1]

return page, nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

if seen != 3 {
t.Errorf("seen = %d, want 3", seen)
}

if got, want := w.Body.String(), "a\nb\nc\n"; got != want {
t.Errorf("body = %q, want %q", got, want)
}

if !w.Flushed {
t.Error("expected the response to be flushed")
}

wantAfter := []interface{}{nil, "b", "c"}
if len(calls) != len(wantAfter) {
t.Fatalf("fetch called %d times, want %d", len(calls), len(wantAfter))
}

for i, want := range wantAfter {
if want == nil {
if calls[i] != nil {
t.Errorf("call %d searchAfter = %v, want nil", i, calls[i])
}

continue
}

if len(calls[i]) != 1 || calls[i][0] != want {
t.Errorf("call %d searchAfter = %v, want [%v]", i, calls[i], want)
}
}
}

func TestWriteIndexIDsErrorAfterFirstPage(t *testing.T) {
boom := errors.New("boom")
call := 0

w := httptest.NewRecorder()

seen, err := writeIndexIDs(w, func(_ []interface{}) ([]*elastic.SearchHit, error) {
call++
if call == 1 {
return []*elastic.SearchHit{idHit("a")}, nil
}

return nil, boom
})
if !errors.Is(err, boom) {
t.Fatalf("err = %v, want %v", err, boom)
}

if seen != 1 {
t.Errorf("seen = %d, want 1", seen)
}

if got := w.Body.String(); got != "a\n" {
t.Errorf("body = %q, want %q", got, "a\n")
}
}
Loading