Compare commits

..
Author SHA1 Message Date
Michal Klos d9b566d0b5 feat: [OCSIDEV-1441] feedback when a large upload fails postprocessing, review
Signed-off-by: Michal Klos <michal.klos@kiteworks.com>
2026-10-30 18:56:08 +01:00
Michal Klos db54ca993f feat: [OCSIDEV-1441] feedback when a large upload fails postprocessing
# Conflicts:
#	web/packages/web-runtime/tests/unit/container/sse/files.spec.ts
2026-10-30 18:56:07 +01:00
26 changed files with 223 additions and 754 deletions

No files matched your search

+1 -8
View File
@@ -235,11 +235,6 @@ jobs:
# collaboration (needs WOPI)
- apiCollaboration
- apiVault
include:
# same suite against the Tika 4.x line (the default entry above uses 3.x)
- suite: apiSearchContent-tika4
behat_suite: apiSearchContent
tika_image: apache/tika:4.2.0-full
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -304,9 +299,7 @@ jobs:
- name: Run ${{ matrix.suite }}
run: |
mkdir -p "$GOCOVERDIR"
BEHAT_SUITES=${{ matrix.behat_suite || matrix.suite }} python3 tests/acceptance/run-github.py
env:
TIKA_IMAGE: ${{ matrix.tika_image }}
BEHAT_SUITES=${{ matrix.suite }} python3 tests/acceptance/run-github.py
- name: Upload raw coverage data
if: always()
@@ -0,0 +1,5 @@
Enhancement: Notify the user when an upload fails to finalize
When an async blob commit fails after postprocessing and the node is reverted, the uploading user now receives a persisted "Upload failed" notification identifying the file, and the stale upload row is removed from the file list instead of the failure being silent.
https://github.com/owncloud/ocis/pull/12987
@@ -1,16 +0,0 @@
Enhancement: Support Apache Tika 4.x in content extraction
The search service can now extract content from an Apache Tika 4.x server in
addition to Tika 3.x. Tika 4.0 renamed the `X-TIKA:content` metadata key to
`tk:content`, replaced the `/language/string` endpoint with `/language` and
reports the GPS altitude as `geo:alt` instead of `GPS:GPS Altitude`. Without
support for these changes, a 4.x server would return no content for oCIS, so file
contents were no longer searchable, stop word cleaning was skipped and the
altitude of photos was missing.
The extractor now reads `tk:content` and falls back to `X-TIKA:content`, reads
the altitude from both `geo:alt` and `GPS:GPS Altitude`, and picks the language
endpoint from the version the Tika server reports at startup. Both Tika 3.x and
4.x servers are supported.
https://github.com/owncloud/ocis/pull/13279
@@ -1,31 +0,0 @@
Bugfix: Reindex no longer aborts on unresolvable files; threshold configurable
`IndexSpace` aborted the walk after 5 consecutive files failed, on the assumption
that the content extractor was down. Two things made that fire on healthy
systems:
1. A file the walker listed but that could not be stat'ed by its path (a node
whose stored name no longer matched its directory entry) counted as an
extraction failure. The extractor was never involved.
2. The counter only ever saw files that actually needed work. On a space that
was already almost fully indexed, five problem files scattered anywhere in
walk order looked "consecutive", the walk aborted at the same point every
time, and nothing after that point was indexed until the files were fixed
by hand.
The walk still resolves each file by its path. When Stat by path does not find
a file, the walk tries again with the ID it listed, so such a node is indexed.
A healthy file costs no extra GetPath call. A file that Stat or GetPath does not find (CODE_NOT_FOUND, deleted
since it was listed) is skipped without counting; auth, gateway, transport and
deadline failures still count. Because the gateway also answers NOT_FOUND when
it cannot reach a storage provider, a walk in which at least 5 files, and more
than half of the files that needed work, were not found ends with an error
instead of reporting the space as indexed. Already-indexed, unchanged files
reset the counter, a cancelled or timed-out walk (including its retry waits)
stops with an error, and each walk logs a summary of indexed, unchanged, failed
and not-found files. The threshold became configurable with
`SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES` (default 5, unchanged; 0 never
aborts and logs a warning at startup; negative values are rejected).
https://github.com/owncloud/ocis/pull/13034
https://github.com/owncloud/ocis/issues/13033
+9
View File
@@ -1,5 +1,12 @@
package service
type PostprocessingOutcome string
const (
OutcomeSuccess PostprocessingOutcome = ""
OutcomeFailed PostprocessingOutcome = "failed"
)
// FileEvent is emitted when a file is uploaded/renamed/deleted/...
type FileEvent struct {
ParentItemID string `json:"parentitemid"`
@@ -8,6 +15,8 @@ type FileEvent struct {
InitiatorID string `json:"initiatorid"`
Etag string `json:"etag"`
Outcome PostprocessingOutcome `json:"outcome,omitempty"`
// Only in case of sharing (refactor this into separate struct when more fields are needed)
AffectedUserIDs []string `json:"affecteduserids"`
}
+10 -2
View File
@@ -143,8 +143,16 @@ func (cl *ClientlogService) processEvent(event events.Event) {
err = errors.New("unhandled event")
case events.UploadReady:
if e.Failed {
// we don't inform about failed uploads yet
return
// node reverted, resource gone: build the payload from the event, not the gateway.
evType = "postprocessing-finished"
users = []string{e.ExecutingUser.GetId().GetOpaqueId()}
data = FileEvent{
ItemID: storagespace.FormatResourceID(e.ResourceID),
SpaceID: storagespace.FormatStorageID(e.ResourceID.GetStorageId(), e.ResourceID.GetSpaceId()),
InitiatorID: event.InitiatorID,
Outcome: OutcomeFailed,
}
break
}
fileEv("postprocessing-finished", e.FileRef)
case events.ItemTrashed:
+1 -1
View File
@@ -65,7 +65,7 @@ This extractor is the most simple one and just uses the resource information pro
### Tika Extractor
This extractor is more advanced compared to the [Basic extractor](#basic-extractor). The main difference is that this extractor is able to search file contents. However, [Apache Tika](https://tika.apache.org/) is required for this task. Read the [Apache Tika Server documentation](https://tika.apache.org/docs/4.2.x/using-tika/server/index.html) guide on how to install and run Tika or use a ready to run [Tika container](https://hub.docker.com/r/apache/tika). See the [Tika container usage document](https://github.com/apache/tika-docker#usage) for a quickstart. Note that at the time of writing, containers are only available for the amd64 platform.
This extractor is more advanced compared to the [Basic extractor](#basic-extractor). The main difference is that this extractor is able to search file contents. However, [Apache Tika](https://tika.apache.org/) is required for this task. Read the [Getting Started with Apache Tika](https://tika.apache.org/3.2.0/gettingstarted.html) guide on how to install and run Tika or use a ready to run [Tika container](https://hub.docker.com/r/apache/tika). See the [Tika container usage document](https://github.com/apache/tika-docker#usage) for a quickstart. Note that at the time of writing, containers are only available for the amd64 platform.
As soon as Tika is installed and accessible, the search service must be configured for the use with Tika. The following settings must be set:
-2
View File
@@ -5,8 +5,6 @@ type Extractor struct {
Type string `yaml:"type" env:"SEARCH_EXTRACTOR_TYPE" desc:"Defines the content extraction engine. Defaults to 'basic'. Supported values are: 'basic' and 'tika'." introductionVersion:"pre5.0"`
CS3AllowInsecure bool `yaml:"cs3_allow_insecure" env:"OCIS_INSECURE;SEARCH_EXTRACTOR_CS3SOURCE_INSECURE" desc:"Ignore untrusted SSL certificates when connecting to the CS3 source." introductionVersion:"pre5.0"`
Tika ExtractorTika `yaml:"tika"`
MaxConsecutiveFailures int `yaml:"max_consecutive_failures" env:"SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES" desc:"Abort a space (re)index walk after this many files in a row fail content extraction, which usually means the extraction service is down. Files that cannot be resolved at all are logged and skipped without counting towards this limit. Set to 0 to never abort." introductionVersion:"9.0.0"`
}
// ExtractorTika configures the Tika extractor
@@ -9,10 +9,6 @@ import (
"github.com/owncloud/ocis/v2/services/search/pkg/config"
)
// defaultMaxConsecutiveFailures is the number of consecutive extraction
// failures after which a space (re)index walk gives up on the extractor.
const defaultMaxConsecutiveFailures = 5
// FullDefaultConfig returns a fully initialized default configuration
func FullDefaultConfig() *config.Config {
cfg := DefaultConfig()
@@ -50,7 +46,6 @@ func DefaultConfig() *config.Config {
TikaURL: "http://127.0.0.1:9998",
CleanStopWords: true,
},
MaxConsecutiveFailures: defaultMaxConsecutiveFailures,
},
Events: config.Events{
Endpoint: "127.0.0.1:9233",
@@ -2,7 +2,6 @@ package parser
import (
"errors"
"fmt"
ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
@@ -45,10 +44,6 @@ func Validate(cfg *config.Config) error {
if cfg.ServiceAccount.ServiceAccountSecret == "" {
return shared.MissingServiceAccountSecret(cfg.Service.Name)
}
if cfg.Extractor.MaxConsecutiveFailures < 0 {
return fmt.Errorf("%s: SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES must be 0 (never abort) or greater, got %d",
cfg.Service.Name, cfg.Extractor.MaxConsecutiveFailures)
}
return nil
}
@@ -1,44 +0,0 @@
package parser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/owncloud/ocis/v2/services/search/pkg/config"
"github.com/owncloud/ocis/v2/services/search/pkg/config/defaults"
)
func validConfig() *config.Config {
cfg := defaults.DefaultConfig()
cfg.TokenManager = &config.TokenManager{JWTSecret: "secret"}
cfg.ServiceAccount = config.ServiceAccount{ServiceAccountID: "id", ServiceAccountSecret: "secret"}
return cfg
}
func TestDefaultMaxConsecutiveFailures(t *testing.T) {
assert.Equal(t, 5, defaults.DefaultConfig().Extractor.MaxConsecutiveFailures)
}
func TestValidateMaxConsecutiveFailures(t *testing.T) {
for _, tc := range []struct {
name string
value int
wantErr bool
}{
{name: "default", value: 5},
{name: "never abort", value: 0},
{name: "negative", value: -1, wantErr: true},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := validConfig()
cfg.Extractor.MaxConsecutiveFailures = tc.value
err := Validate(cfg)
if tc.wantErr {
assert.ErrorContains(t, err, "SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES")
return
}
assert.NoError(t, err)
})
}
}
+6 -63
View File
@@ -5,8 +5,6 @@ import (
"fmt"
"io"
"math"
"net/http"
"regexp"
"strconv"
"strings"
"time"
@@ -21,21 +19,12 @@ import (
"github.com/owncloud/ocis/v2/services/search/pkg/config"
)
// tikaMajorVersion matches the major version in the tika server version string, e.g. "Apache Tika 4.2.0".
var tikaMajorVersion = regexp.MustCompile(`(\d+)\.\d+`)
// Tika 4.x renamed the X-TIKA:content metadata key to tk:content. We accept both
// so that tika 3.x and 4.x servers can be used.
var tikaContentKeys = []string{"tk:content", "X-TIKA:content"}
// Tika is used to extract content from a resource,
// it uses apache tika to retrieve all the data.
type Tika struct {
*Basic
Retriever
tika *tika.Client
tikaURL string
languagePath string
ContentExtractionSizeLimit uint64
CleanStopWords bool
}
@@ -57,9 +46,7 @@ func NewTikaExtractor(gatewaySelector pool.Selectable[gateway.GatewayAPIClient],
return &Tika{
Basic: basic,
Retriever: newCS3Retriever(gatewaySelector, logger, cfg.Extractor.CS3AllowInsecure),
tika: tk,
tikaURL: strings.TrimSuffix(cfg.Extractor.Tika.TikaURL, "/"),
languagePath: tikaLanguagePath(tkv),
tika: tika.NewClient(nil, cfg.Extractor.Tika.TikaURL),
ContentExtractionSizeLimit: cfg.ContentExtractionSizeLimit,
CleanStopWords: cfg.Extractor.Tika.CleanStopWords,
}, nil
@@ -109,11 +96,8 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
doc.Title = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Title, title))
}
for _, key := range tikaContentKeys {
if content, err := getFirstValue(meta, key); err == nil {
doc.Content = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Content, content))
break
}
if content, err := getFirstValue(meta, "X-TIKA:content"); err == nil {
doc.Content = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Content, content))
}
doc.Location = t.getLocation(meta)
@@ -125,48 +109,13 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
}
}
if langCode, _ := t.detectLanguage(ctx, doc.Content); langCode != "" && t.CleanStopWords {
if langCode, _ := t.tika.LanguageString(ctx, doc.Content); langCode != "" && t.CleanStopWords {
doc.Content = CleanString(doc.Content, langCode)
}
return doc, nil
}
// tikaLanguagePath returns the language detection endpoint of the tika server with the given
// version. Tika 4.x replaced /language/string with /language, which go-tika doesn't know about.
func tikaLanguagePath(version string) string {
if m := tikaMajorVersion.FindStringSubmatch(version); m != nil {
if major, err := strconv.Atoi(m[1]); err == nil && major >= 4 {
return "/language"
}
}
return "/language/string"
}
// detectLanguage returns the language code tika detects for the given text.
func (t Tika) detectLanguage(ctx context.Context, text string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPut, t.tikaURL+t.languagePath, strings.NewReader(text))
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("tika language detection failed: %s", resp.Status)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(b), nil
}
func (t Tika) getImage(meta map[string][]string) *libregraph.Image {
var image *libregraph.Image
initImage := func() {
@@ -200,20 +149,14 @@ func (t Tika) getLocation(meta map[string][]string) *libregraph.GeoCoordinates {
}
}
// Tika 4.x reports the altitude as geo:alt, tika 3.x as "GPS:GPS Altitude"
// which is returned as "227.4 metres" - extract the numeric portion
for _, key := range []string{"geo:alt", "GPS:GPS Altitude"} {
v, err := getFirstValue(meta, key)
if err != nil {
continue
}
// GPS Altitude is returned as "227.4 metres" - extract the numeric portion
if v, err := getFirstValue(meta, "GPS:GPS Altitude"); err == nil {
// Parse altitude value - remove " metres" suffix if present
altStr := strings.TrimSuffix(v, " metres")
altStr = strings.TrimSuffix(altStr, " m")
if alt, err := strconv.ParseFloat(strings.TrimSpace(altStr), 64); err == nil {
initLocation()
location.SetAltitude(alt)
break
}
}
+2 -75
View File
@@ -28,7 +28,6 @@ var _ = Describe("Tika", func() {
fullResponse string
language string
version string
tika4 bool
srv *httptest.Server
tika *content.Tika
)
@@ -36,46 +35,26 @@ var _ = Describe("Tika", func() {
BeforeEach(func() {
body = ""
language = ""
version = "Apache Tika 3.2.2"
tika4 = false
version = ""
fullResponse = ""
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
out := ""
switch req.URL.Path {
case "/version":
out = version
// tika 3.x serves /language/string, tika 4.x only /language
case "/language/string":
if tika4 {
w.WriteHeader(http.StatusNotFound)
return
}
out = language
case "/language":
if !tika4 {
w.WriteHeader(http.StatusNotFound)
return
}
out = language
case "/rmeta/text":
// tika 4.x renamed X-TIKA:content to tk:content
contentKey := "X-TIKA:content"
if tika4 {
contentKey = "tk:content"
}
if fullResponse != "" {
out = fullResponse
} else {
out = fmt.Sprintf(`[{"%s":"%s"}]`, contentKey, body)
out = fmt.Sprintf(`[{"X-TIKA:content":"%s"}]`, body)
}
}
_, _ = w.Write([]byte(out))
}))
})
JustBeforeEach(func() {
cfg := conf.DefaultConfig()
cfg.Extractor.Tika.TikaURL = srv.URL
cfg.Extractor.Tika.CleanStopWords = true
@@ -184,28 +163,6 @@ var _ = Describe("Tika", func() {
Expect(location.Longitude).To(Equal(libregraph.PtrFloat64(11.103870357204285)))
})
It("adds the altitude reported by tika 4.x as geo:alt", func() {
fullResponse = `[{"geo:lat": "43.467157", "geo:long": "11.885395", "geo:alt": "100"}]`
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 1,
})
Expect(err).ToNot(HaveOccurred())
Expect(doc.Location).ToNot(BeNil())
Expect(doc.Location.Altitude).To(Equal(libregraph.PtrFloat64(100)))
})
It("adds the altitude reported by tika 3.x as GPS:GPS Altitude", func() {
fullResponse = `[{"geo:lat": "43.467157", "geo:long": "11.885395", "GPS:GPS Altitude": "227.4 metres"}]`
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 1,
})
Expect(err).ToNot(HaveOccurred())
Expect(doc.Location).ToNot(BeNil())
Expect(doc.Location.Altitude).To(Equal(libregraph.PtrFloat64(227.4)))
})
It("adds image content", func() {
fullResponse = `[
{
@@ -321,36 +278,6 @@ var _ = Describe("Tika", func() {
Expect(doc.Content).To(Equal("body test stop words!!!"))
})
Context("with tika 4.x", func() {
BeforeEach(func() {
tika4 = true
version = "Apache Tika 4.2.0"
})
It("adds content", func() {
body = "any body"
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 1,
})
Expect(err).ToNot(HaveOccurred())
Expect(doc.Content).To(Equal(body))
})
It("removes stop words", func() {
body = "body to test stop words!!! against almost everyone"
language = "en"
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 1,
})
Expect(err).ToNot(HaveOccurred())
Expect(doc.Content).To(Equal("body test stop words!!!"))
})
})
It("keeps stop words", func() {
body = "body to test stop words!!! against almost everyone"
language = "en"
@@ -1,9 +0,0 @@
package search
import "time"
// SetExtractionRetryDelay shortens the delay between extraction retries for a
// test.
func (s *Service) SetExtractionRetryDelay(d time.Duration) {
s.extractionRetryDelay = d
}
+9 -25
View File
@@ -23,17 +23,6 @@ import (
var scopeRegex = regexp.MustCompile(`scope:\s*([^" "\n\r]*)`)
var vaultRegex = regexp.MustCompile(`vault:\s*(\S+)`)
// errResourceNotFound is returned by statResource when Stat answers
// CODE_NOT_FOUND: the resource was deleted or moved since it was listed. The
// gateway also answers NOT_FOUND when it cannot reach the storage provider, so
// a run of them can mean an outage (see IndexSpace).
var errResourceNotFound = errors.New("resource not found")
// errPathNotResolved is returned by ResolveReference when GetPath answers with
// a non-OK status. When the status is CODE_NOT_FOUND, the error also matches
// errResourceNotFound.
var errPathNotResolved = errors.New("could not resolve the resource's path")
// ResolveReference makes sure the path is relative to the space root
func ResolveReference(ctx context.Context, ref *provider.Reference, ri *provider.ResourceInfo, gatewaySelector pool.Selectable[gateway.GatewayAPIClient]) (*provider.Reference, error) {
if ref.GetResourceId().GetOpaqueId() == ref.GetResourceId().GetSpaceId() {
@@ -48,16 +37,9 @@ func ResolveReference(ctx context.Context, ref *provider.Reference, ri *provider
gpRes, err := gatewayClient.GetPath(ctx, &provider.GetPathRequest{
ResourceId: ri.GetId(),
})
if err != nil {
if err != nil || gpRes.GetStatus().GetCode() != rpc.Code_CODE_OK {
return nil, err
}
if code := gpRes.GetStatus().GetCode(); code != rpc.Code_CODE_OK {
if code == rpc.Code_CODE_NOT_FOUND {
// Deleted since the Stat, like a Stat that answers NOT_FOUND.
return nil, fmt.Errorf("%w: %w: %s", errPathNotResolved, errResourceNotFound, gpRes.GetStatus().GetMessage())
}
return nil, fmt.Errorf("%w: %s %s", errPathNotResolved, code, gpRes.GetStatus().GetMessage())
}
return &provider.Reference{
ResourceId: &provider.ResourceId{
StorageId: ref.GetResourceId().GetStorageId(),
@@ -98,7 +80,7 @@ func getAuthContext(ctx context.Context, serviceAccountID string, gatewaySelecto
return utils.GetServiceUserContextWithContext(ctx, gatewayClient, serviceAccountID, secret)
}
func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector pool.Selectable[gateway.GatewayAPIClient]) (*provider.StatResponse, error) {
func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], logger log.Logger) (*provider.StatResponse, error) {
gatewayClient, err := gatewaySelector.Next()
if err != nil {
return nil, err
@@ -106,17 +88,19 @@ func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector
res, err := gatewayClient.Stat(ctx, &provider.StatRequest{Ref: ref})
if err != nil {
logger.Error().Err(err).Msg("failed to stat the moved resource")
return nil, err
}
switch code := res.GetStatus().GetCode(); code {
switch res.GetStatus().GetCode() {
case rpc.Code_CODE_OK:
return res, nil
case rpc.Code_CODE_NOT_FOUND:
// Moved or deleted in the meantime, or a backend the gateway could
// not reach: the gateway answers NOT_FOUND for both.
return nil, errResourceNotFound
// Resource was moved or deleted in the meantime. ignore.
return nil, err
default:
return nil, fmt.Errorf("stat failed: %s %s", code, res.GetStatus().GetMessage())
err := errors.New("failed to stat the moved resource")
logger.Error().Interface("res", res).Msg(err.Error())
return nil, err
}
}
+27 -145
View File
@@ -24,7 +24,6 @@ import (
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/tags"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/fieldmaskpb"
@@ -76,12 +75,6 @@ type Service struct {
serviceAccountID string
serviceAccountSecret string
// maxConsecutiveFailures aborts an IndexSpace walk after this many
// consecutive extraction failures. 0 disables the abort.
maxConsecutiveFailures int
// extractionRetryDelay is the pause between extraction retries in IndexSpace.
extractionRetryDelay time.Duration
}
var errSkipSpace error
@@ -96,13 +89,6 @@ func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng e
serviceAccountID: cfg.ServiceAccount.ServiceAccountID,
serviceAccountSecret: cfg.ServiceAccount.ServiceAccountSecret,
maxConsecutiveFailures: cfg.Extractor.MaxConsecutiveFailures,
extractionRetryDelay: _extractionRetryDelay,
}
if s.maxConsecutiveFailures == 0 {
s.logger.Warn().Msg("SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES is 0: a space reindex never aborts, even when the content extractor is down")
}
return s
@@ -469,15 +455,11 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest,
return res, nil
}
// Retry and outage constants for IndexSpace.
// Retry constants for IndexSpace extraction failure handling.
const (
_extractionRetries = 5 // max retry attempts per file
_extractionRetryDelay = 1 * time.Second // default delay between retries
// A walk in which at least _missingMinCount files were not found, and they
// are more than half of the files that needed work, fails at the end: the
// gateway answers NOT_FOUND when it cannot reach the storage provider, and
// that must not report the space as indexed.
_missingMinCount = 5
_extractionRetryDelay = 1 * time.Second // delay between retries
_consecutiveAbort = 5 // abort walk after this many consecutive file failures
)
// IndexSpace (re)indexes all resources of a given space.
@@ -498,14 +480,7 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
}
rootID.OpaqueId = rootID.SpaceId
// failures counts extraction failures in a row. A file that was indexed or
// was already indexed and unchanged resets it; a file that is not found
// (deleted since it was listed) neither counts nor resets it.
var (
failures int
indexedCount, unchangedCount, failedCount int
missingCount int
)
failures := 0
w := walker.NewWalker(s.gatewaySelector)
err = w.Walk(ownerCtx, &rootID, func(wd string, info *provider.ResourceInfo, err error) error {
@@ -518,22 +493,17 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
return nil
}
// A cancelled or timed-out walk must stop with an error, not carry on
// with failing lookups.
if err := ownerCtx.Err(); err != nil {
return fmt.Errorf("index walk stopped: %w", err)
}
relPath := utils.MakeRelativePath(filepath.Join(wd, info.Path))
if slices.Contains(_skipPathDirs, relPath) {
s.logger.Info().Str("path", relPath).Msg("skipping directory from being indexed")
return filepath.SkipDir
}
if slices.Contains(_skipPathNames, relPath) {
return nil // the space root itself is never indexed
}
s.logger.Debug().Str("path", relPath).Msg("Walking tree")
ref := &provider.Reference{
Path: relPath,
ResourceId: &rootID,
}
s.logger.Debug().Str("path", ref.Path).Msg("Walking tree")
// Skip nodes still in postprocessing — their blob isn't in the
// blobstore yet. Their own UploadReady will re-trigger IndexSpace.
if utils.ReadPlainFromOpaque(info.Opaque, "status") == "processing" {
@@ -553,72 +523,32 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
// With O(1) DocID lookups the cost is negligible.
return nil
}
s.logger.Debug().Str("path", relPath).Msg("element hasn't changed. Skipping.")
unchangedCount++
failures = 0
s.logger.Debug().Str("path", ref.Path).Msg("element hasn't changed. Skipping.")
return nil
}
}
// Resolve the node by its path. A stale node fails a Stat by path but
// the ID the walker listed still finds it. So retry by ID only after
// a not-found: a healthy file costs no extra GetPath call.
ref := &provider.Reference{Path: relPath, ResourceId: &rootID}
err = s.upsertItem(ownerCtx, ref, _extractionRetries)
if errors.Is(err, errResourceNotFound) && info.GetId() != nil {
s.logger.Debug().Str("path", relPath).Msg("resource not found by path, retrying by ID")
err = s.upsertItem(ownerCtx, &provider.Reference{ResourceId: info.GetId()}, _extractionRetries)
}
if err != nil {
if errors.Is(err, errResourceNotFound) {
missingCount++
s.logger.Debug().Err(err).Str("path", relPath).Msg("skipping resource that no longer exists")
return nil
}
if err := s.upsertItem(ownerCtx, ref, _extractionRetries); err != nil {
failures++
failedCount++
s.logger.Warn().Err(err).
Int("failures", failures).
Str("path", relPath).
Str("path", ref.Path).
Msg("extraction failed after retries")
if s.maxConsecutiveFailures > 0 && failures >= s.maxConsecutiveFailures {
if failures >= _consecutiveAbort {
return fmt.Errorf("aborting index walk: %d consecutive extraction failures, last error: %w", failures, err)
}
return nil
}
indexedCount++
failures = 0
return nil
})
// The context check comes first: a walk cut short reports that, whatever
// the last file's error was.
if ctxErr := ownerCtx.Err(); ctxErr != nil {
return fmt.Errorf("index walk stopped: %w", ctxErr)
}
level := zerolog.InfoLevel
if failedCount > 0 || missingCount > 0 {
level = zerolog.WarnLevel
}
s.logger.WithLevel(level).Str("space", spaceID.GetOpaqueId()).
Int("indexed", indexedCount).
Int("unchanged", unchangedCount).
Int("failed", failedCount).
Int("not_found", missingCount).
Msg("index walk finished")
if err != nil {
return err
}
if attempted := indexedCount + failedCount + missingCount; missingCount >= _missingMinCount && missingCount*2 > attempted {
return fmt.Errorf("index walk incomplete: %d of %d files were not found, which suggests the storage provider was unreachable", missingCount, attempted)
}
logDocCount(s.engine, s.logger)
return nil
@@ -634,12 +564,7 @@ func (s *Service) TrashItem(_ context.Context, rID *provider.ResourceId) {
// UpsertItem indexes or stores Resource data fields.
func (s *Service) UpsertItem(ctx context.Context, ref *provider.Reference) {
err := s.upsertItem(ctx, ref, 0)
switch {
case err == nil:
case errors.Is(err, errResourceNotFound):
s.logger.Debug().Err(err).Msg("resource to upsert no longer exists")
default:
if err := s.upsertItem(ctx, ref, 0); err != nil {
s.logger.Error().Err(err).Msg("failed to upsert resource")
}
}
@@ -647,9 +572,9 @@ func (s *Service) UpsertItem(ctx context.Context, ref *provider.Reference) {
// upsertItem is the core extraction-and-index method. When retries > 0,
// a failed extraction is retried up to that many times with a fixed delay.
func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retries int) error {
ctx2, stat, path, err := s.resolve(ctx, ref)
if err != nil {
return fmt.Errorf("could not resolve resource info for %s: %w", refString(ref), err)
ctx2, stat, path := s.resInfo(ctx, ref)
if ctx2 == nil || stat == nil || path == "" {
return fmt.Errorf("could not resolve resource info for %s", ref.GetPath())
}
if slices.Contains(_skipPathNames, path) || slices.Contains(_skipPathDirs, path) {
@@ -667,6 +592,7 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
resourceID := storagespace.FormatResourceID(stat.Info.Id)
var doc content.Document
var err error
for attempt := range retries + 1 {
doc, err = s.extractor.Extract(ctx2, stat.Info)
if err == nil {
@@ -675,19 +601,13 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
if attempt < retries {
s.logger.Debug().Err(err).
Int("attempt", attempt+1).
Str("path", path).
Str("path", ref.Path).
Msg("extraction attempt failed, retrying")
t := time.NewTimer(s.extractionRetryDelay)
select {
case <-ctx.Done():
t.Stop()
return fmt.Errorf("extraction for %s stopped: %w", path, ctx.Err())
case <-t.C:
}
time.Sleep(_extractionRetryDelay)
}
}
if err != nil {
return fmt.Errorf("extraction failed for %s: %w", path, err)
return fmt.Errorf("extraction failed for %s: %w", ref.Path, err)
}
r := engine.Resource{
@@ -709,7 +629,7 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
}
if err = s.engine.Upsert(r.ID, r); err != nil {
return fmt.Errorf("index upsert for %s: %w", path, err)
return fmt.Errorf("index upsert for %s: %w", ref.Path, err)
}
logDocCount(s.engine, s.logger)
@@ -875,59 +795,21 @@ func (s *Service) MoveItem(ctx context.Context, ref *provider.Reference) {
}
}
// resInfo is resolve for the event handlers (UpdateTags, RestoreItem, MoveItem).
// It logs a failure once and returns nils, except when only the path could not
// be resolved: then it still returns the Stat result with an empty path, as
// before, so UpdateTags (which needs only the Stat result) still works.
func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (context.Context, *provider.StatResponse, string) {
ctx2, stat, path, err := s.resolve(ctx, ref)
switch {
case err == nil:
return ctx2, stat, path
case errors.Is(err, errPathNotResolved):
s.logger.Debug().Err(err).Str("ref", refString(ref)).Msg("could not resolve the resource's path")
return ctx2, stat, ""
case errors.Is(err, errResourceNotFound):
s.logger.Debug().Err(err).Str("ref", refString(ref)).Msg("resource no longer exists")
default:
s.logger.Warn().Err(err).Str("ref", refString(ref)).Msg("could not resolve resource info")
}
return nil, nil, ""
}
// resolve returns the auth context, Stat response and space-relative path of
// ref. Stat CODE_NOT_FOUND is errResourceNotFound and a non-OK GetPath is
// errPathNotResolved (with the Stat result still returned); every other
// failure (auth, gateway, transport, deadline) is returned as its own error.
func (s *Service) resolve(ctx context.Context, ref *provider.Reference) (context.Context, *provider.StatResponse, string, error) {
ownerCtx, err := getAuthContext(ctx, s.serviceAccountID, s.gatewaySelector, s.serviceAccountSecret, s.logger)
if err != nil {
return nil, nil, "", fmt.Errorf("auth context: %w", err)
return nil, nil, ""
}
statRes, err := statResource(ownerCtx, ref, s.gatewaySelector)
statRes, err := statResource(ownerCtx, ref, s.gatewaySelector, s.logger)
if err != nil {
return nil, nil, "", err
return nil, nil, ""
}
r, err := ResolveReference(ownerCtx, ref, statRes.GetInfo(), s.gatewaySelector)
if err != nil {
if errors.Is(err, errPathNotResolved) {
return ownerCtx, statRes, "", err
}
return nil, nil, "", fmt.Errorf("get path: %w", err)
}
if r.GetPath() == "" {
return ownerCtx, statRes, "", errPathNotResolved
return nil, nil, ""
}
return ownerCtx, statRes, r.GetPath(), nil
}
// refString describes ref for logs and errors: its path, or its resource ID.
func refString(ref *provider.Reference) string {
if p := ref.GetPath(); p != "" {
return p
}
return storagespace.FormatResourceID(ref.GetResourceId())
return ownerCtx, statRes, r.GetPath()
}
+5 -321
View File
@@ -9,7 +9,6 @@ import (
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
collaborationv1beta1 "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
sprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
@@ -27,7 +26,6 @@ import (
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/utils"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
@@ -173,7 +171,7 @@ var _ = Describe("Searchprovider", func() {
indexClient.On("Lookup", mock.Anything).Return(nil, engine.ErrResourceNotFound)
gatewayClient.On("Stat", mock.Anything, mock.MatchedBy(func(sreq *sprovider.StatRequest) bool {
return sreq.Ref.ResourceId.StorageId == "storageid" &&
(sreq.Ref.ResourceId.OpaqueId == "spaceid" || sreq.Ref.ResourceId.OpaqueId == ri.Id.OpaqueId) &&
sreq.Ref.ResourceId.OpaqueId == "spaceid" &&
sreq.Ref.ResourceId.SpaceId == "spaceid"
})).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
@@ -181,7 +179,6 @@ var _ = Describe("Searchprovider", func() {
}, nil)
err := s.IndexSpace(context.Background(), &sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"})
Expect(err).ShouldNot(HaveOccurred())
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", 1)
})
It("walks the space skipping .space directory", func() {
@@ -259,21 +256,11 @@ var _ = Describe("Searchprovider", func() {
}
}
// Build ID-to-fileInfo and ID-to-path maps for O(1) Stat and GetPath dispatch.
fileInfoByID := make(map[string]*sprovider.ResourceInfo, numDirs)
filePathByID := make(map[string]string, numDirs)
// Build path-to-fileInfo map for O(1) Stat dispatch.
fileInfoByPath := make(map[string]*sprovider.ResourceInfo, numDirs)
for dirID, fi := range fileInfoByDir {
fileInfoByID[fi.Id.OpaqueId] = fi
filePathByID[fi.Id.OpaqueId] = "/" + dirID + "/" + fi.Path
fileInfoByPath["./"+dirID+"/"+fi.Path] = fi
}
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return fileInfoByID[req.GetResourceId().GetOpaqueId()] != nil
})).Return(
func(_ context.Context, req *sprovider.GetPathRequest, _ ...grpc.CallOption) *sprovider.GetPathResponse {
return &sprovider.GetPathResponse{Status: status.NewOK(context.Background()), Path: filePathByID[req.GetResourceId().GetOpaqueId()]}
},
func(_ context.Context, _ *sprovider.GetPathRequest, _ ...grpc.CallOption) error { return nil },
)
// Single Stat mock dispatching via map — avoids 10k separate matchers.
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
@@ -284,7 +271,7 @@ var _ = Describe("Searchprovider", func() {
Info: rootInfo,
}
}
if fi, ok := fileInfoByID[sreq.Ref.GetResourceId().GetOpaqueId()]; ok {
if fi, ok := fileInfoByPath[sreq.Ref.Path]; ok {
return &sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: fi,
@@ -395,280 +382,6 @@ var _ = Describe("Searchprovider", func() {
})
})
Describe("IndexSpace abort threshold", func() {
// A root container listing numFiles files. Stat by ID answers per the
// missing/statBroken sets, Stat by path per staleByPath; Lookup finds only
// the files in indexed, so every other file is attempted.
const numFiles = 6
var (
rootInfo *sprovider.ResourceInfo
fileInfos []*sprovider.ResourceInfo
missing map[string]bool // Stat answers NOT_FOUND
statBroken map[string]bool // Stat answers with an internal error
staleByPath map[string]bool // Stat by path answers NOT_FOUND, Stat by ID works
pathMissing map[string]bool // GetPath answers NOT_FOUND
pathBroken map[string]bool // GetPath answers with an internal error
indexed map[string]bool // already indexed and unchanged
newService = func(maxConsecutiveFailures int) *search.Service {
cfg := &config.Config{}
cfg.Extractor.MaxConsecutiveFailures = maxConsecutiveFailures
s := search.NewService(gatewaySelector, indexClient, extractor, logger, cfg)
s.SetExtractionRetryDelay(time.Millisecond)
return s
}
spaceID = &sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}
)
BeforeEach(func() {
missing = map[string]bool{}
statBroken = map[string]bool{}
staleByPath = map[string]bool{}
pathMissing = map[string]bool{}
pathBroken = map[string]bool{}
indexed = map[string]bool{}
gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{
Status: status.NewOK(context.Background()),
User: user,
}, nil)
rootInfo = &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
Path: ".",
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
fileInfos = make([]*sprovider.ResourceInfo, numFiles)
byID := map[string]*sprovider.ResourceInfo{}
for i := range fileInfos {
fileInfos[i] = &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: fmt.Sprintf("file-%d", i)},
ParentId: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
Path: fmt.Sprintf("file-%d.pdf", i),
Size: 1024,
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
byID[fileInfos[i].Id.OpaqueId] = fileInfos[i]
}
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
func(_ context.Context, sreq *sprovider.StatRequest, _ ...grpc.CallOption) *sprovider.StatResponse {
id := sreq.GetRef().GetResourceId().GetOpaqueId()
if p := sreq.GetRef().GetPath(); p != "" && p != "." {
// By path, relative to the space root.
for _, fi := range fileInfos {
if "./"+fi.Path == p && !staleByPath[fi.Id.OpaqueId] {
id = fi.Id.OpaqueId
break
}
id = ""
}
}
switch {
case id == "spaceid":
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: rootInfo}
case statBroken[id]:
return &sprovider.StatResponse{Status: status.NewInternal(context.Background(), "storage unavailable")}
case missing[id] || byID[id] == nil:
return &sprovider.StatResponse{Status: status.NewNotFound(context.Background(), id)}
}
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: byID[id]}
},
func(_ context.Context, _ *sprovider.StatRequest, _ ...grpc.CallOption) error { return nil },
)
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return byID[req.GetResourceId().GetOpaqueId()] != nil
})).Return(
func(_ context.Context, req *sprovider.GetPathRequest, _ ...grpc.CallOption) *sprovider.GetPathResponse {
id := req.GetResourceId().GetOpaqueId()
switch {
case pathMissing[id]:
return &sprovider.GetPathResponse{Status: status.NewNotFound(context.Background(), id)}
case pathBroken[id]:
return &sprovider.GetPathResponse{Status: status.NewInternal(context.Background(), "storage unavailable")}
}
return &sprovider.GetPathResponse{Status: status.NewOK(context.Background()), Path: "/" + byID[id].Path}
},
func(_ context.Context, _ *sprovider.GetPathRequest, _ ...grpc.CallOption) error { return nil },
)
gatewayClient.On("ListContainer", mock.Anything, mock.Anything).Return(&sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: fileInfos,
}, nil)
indexClient.On("Lookup", mock.Anything).Return(
func(id string) *engine.Resource {
if indexed[id] {
return &engine.Resource{ID: id, Extracted: true, Document: content.Document{Mtime: time.Unix(6000, 0).UTC().Format(time.RFC3339Nano)}}
}
return nil
},
func(id string) error {
if indexed[id] {
return nil
}
return engine.ErrResourceNotFound
},
)
indexClient.On("Upsert", mock.Anything, mock.Anything).Return(nil)
})
It("does not count a file that no longer exists towards the abort threshold", func() {
missing["file-0"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "a file deleted since it was listed is skipped, never counted")
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles-1)
})
It("keeps the failure count across a file that no longer exists", func() {
// Only file-0 and file-2 fail extraction. file-1 is gone between them.
// It neither counts nor resets the counter, so a threshold of 2
// aborts at file-2, before the healthy file-3 could reset it.
missing["file-1"] = true
extractor.On("Extract", mock.Anything, mock.MatchedBy(func(ri *sprovider.ResourceInfo) bool {
return ri.GetId().GetOpaqueId() == "file-0" || ri.GetId().GetOpaqueId() == "file-2"
}), mock.Anything).Return(content.Document{}, errors.New("extractor down"))
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
})
It("fails the walk when most files are not found, as in a storage provider outage", func() {
// The gateway answers NOT_FOUND when it cannot reach the provider.
for _, fi := range fileInfos {
missing[fi.Id.OpaqueId] = true
}
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "an outage must not report the space as indexed")
Expect(err.Error()).To(ContainSubstring(fmt.Sprintf("index walk incomplete: %d of %d files were not found", numFiles, numFiles)))
extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
})
It("indexes a stale node that Stat cannot find by its path but can by its ID", func() {
staleByPath["file-1"] = true
var extracted []string
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
extracted = append(extracted, args.Get(1).(*sprovider.ResourceInfo).GetId().GetOpaqueId())
}).Return(content.Document{}, nil)
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred())
Expect(extracted).To(ConsistOf("file-0", "file-1", "file-2", "file-3", "file-4", "file-5"))
gatewayClient.AssertNumberOfCalls(GinkgoT(), "GetPath", 1) // only the stale node needs the ID fallback
})
It("does not count a file that is gone between the Stat and the GetPath", func() {
staleByPath["file-1"] = true // forces the lookup by ID, which calls GetPath
pathMissing["file-1"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "a vanished file is not an extraction failure")
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles-1)
})
It("counts a GetPath failure other than not-found", func() {
staleByPath["file-1"] = true
pathBroken["file-1"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "a storage failure must not look like a deleted file")
Expect(err.Error()).To(ContainSubstring("aborting index walk: 1 consecutive extraction failures"))
})
It("resolves healthy files by path, without a GetPath call", func() {
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred())
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles)
gatewayClient.AssertNotCalled(GinkgoT(), "GetPath", mock.Anything, mock.Anything)
})
It("aborts after the configured number of consecutive extraction failures", func() {
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("extractor down"))
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything)
})
It("never aborts when the threshold is 0", func() {
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
}).Return(content.Document{}, errors.New("extractor down"))
err := newService(0).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "with the abort disabled the walk finishes despite failures")
Expect(int(extractCalls.Load())).To(Equal(numFiles*6), "every file was attempted, each with all retries")
})
It("counts a Stat failure other than not-found towards the abort threshold", func() {
for _, fi := range fileInfos {
statBroken[fi.Id.OpaqueId] = true
}
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "a storage or auth error must not look like a deleted file")
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
})
It("stops with an error when the walk's context ends, instead of skipping the rest", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
cancel() // e.g. the index command's request timeout fires during the walk
}).Return(content.Document{}, nil)
err := newService(0).IndexSpace(ctx, spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("index walk stopped"))
Expect(int(extractCalls.Load())).To(Equal(1), "no file after the cancellation was attempted")
})
It("stops retrying a failed extraction as soon as the context ends", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
cancel()
}).Return(content.Document{}, errors.New("extractor down"))
s := newService(0)
s.SetExtractionRetryDelay(time.Hour)
done := make(chan error, 1)
go func() { done <- s.IndexSpace(ctx, spaceID) }()
var err error
Eventually(done, 5*time.Second).Should(Receive(&err), "the retry wait must end with the context, not after an hour")
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("index walk stopped"))
Expect(int(extractCalls.Load())).To(Equal(1))
})
It("resets the counter on an already indexed, unchanged file", func() {
// Failing files 0, 2 and 4 are each followed by an indexed one.
for i := 1; i < numFiles; i += 2 {
indexed[storagespace.FormatResourceID(fileInfos[i].Id)] = true
}
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("cannot extract"))
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "failures separated by a healthy file are not consecutive")
})
})
Describe("UpdateTags", func() {
BeforeEach(func() {
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{
@@ -717,35 +430,6 @@ var _ = Describe("Searchprovider", func() {
})
})
Describe("UpdateTags when GetPath fails", func() {
for name, getPathStatus := range map[string]func() *rpcv1beta1.Status{
"with an internal error": func() *rpcv1beta1.Status { return status.NewInternal(context.Background(), "no path") },
"with not found": func() *rpcv1beta1.Status { return status.NewNotFound(context.Background(), "no path") },
} {
It("still updates the tags from the Stat result, GetPath answering "+name, func() {
noPathID := &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "nopath"}
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: &sprovider.ResourceInfo{
Id: noPathID,
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
ArbitraryMetadata: &sprovider.ArbitraryMetadata{
Metadata: map[string]string{"tags": "important"},
},
},
}, nil)
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return req.GetResourceId().GetOpaqueId() == "nopath"
})).Return(&sprovider.GetPathResponse{Status: getPathStatus()}, nil)
indexClient.On("Update", "storageid$spaceid!nopath", mock.Anything).Return(nil)
s.UpdateTags(context.Background(), &sprovider.Reference{ResourceId: noPathID})
indexClient.AssertCalled(GinkgoT(), "Update", "storageid$spaceid!nopath", mock.Anything)
})
}
})
Describe("Search", func() {
It("fails when an empty query is given", func() {
res, err := s.Search(ctx, &searchsvc.SearchRequest{
+1
View File
@@ -33,6 +33,7 @@ import (
var _registeredEvents = []events.Unmarshaller{
// file related
events.PostprocessingStepFinished{},
events.UploadReady{},
// space related
events.SpaceDisabled{},
@@ -97,6 +97,8 @@ func (c *Converter) ConvertEvent(eventid string, event interface{}) (OC10Notific
default:
return OC10Notification{}, fmt.Errorf("unknown postprocessing step: %s", ev.FinishedStep)
}
case events.UploadReady:
return c.uploadFailedMessage(eventid, UploadFailed, ev.ExecutingUser, ev.ResourceID, ev.Filename, utils.TSToTime(ev.Timestamp))
// space related
case events.SpaceDisabled:
@@ -390,6 +392,36 @@ func (c *Converter) policiesMessage(eventid string, nt NotificationTemplate, exe
}, nil
}
func (c *Converter) uploadFailedMessage(eventid string, nt NotificationTemplate, executant *user.User, rid *storageprovider.ResourceId, filename string, ts time.Time) (OC10Notification, error) {
// node reverted: compose from the event's filename, not a gateway lookup.
subj, subjraw, msg, msgraw, err := composeMessage(nt, c.locale, c.defaultLanguage, c.translationPath, map[string]interface{}{
"resourcename": filename,
})
if err != nil {
return OC10Notification{}, err
}
dets := map[string]interface{}{
"resource": map[string]string{
"name": filename,
},
}
return OC10Notification{
EventID: eventid,
Service: c.serviceName,
UserName: executant.GetUsername(),
Timestamp: ts.Format(time.RFC3339Nano),
ResourceID: storagespace.FormatResourceID(rid),
ResourceType: _resourceTypeResource,
Subject: subj,
SubjectRaw: subjraw,
Message: msg,
MessageRaw: msgraw,
MessageDetails: dets,
}, nil
}
func (c *Converter) deprovisionMessage(nt NotificationTemplate, deproDate string) (OC10Notification, error) {
subj, subjraw, msg, msgraw, err := composeMessage(nt, c.locale, c.defaultLanguage, c.translationPath, map[string]interface{}{
"date": deproDate,
@@ -0,0 +1,49 @@
package service_test
import (
"context"
"testing"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/ocis/v2/services/userlog/pkg/service"
)
// nil gateway selector proves the notification is built without a lookup.
func TestConvertEventUploadFailed(t *testing.T) {
c := service.NewConverter(context.Background(), "en", nil, "userlog", "", "en")
ev := events.UploadReady{
Failed: true,
Filename: "big-upload.iso",
ExecutingUser: &user.User{
Id: &user.UserId{OpaqueId: "user-1"},
Username: "einstein",
},
ResourceID: &provider.ResourceId{
StorageId: "storage-1",
SpaceId: "space-1",
OpaqueId: "item-1",
},
}
n, err := c.ConvertEvent("event-1", ev)
if err != nil {
t.Fatalf("ConvertEvent returned error: %v", err)
}
if n.Subject != "Upload failed" {
t.Errorf("unexpected subject: %q", n.Subject)
}
if want := "The upload of big-upload.iso could not be finalized. Please try again."; n.Message != want {
t.Errorf("unexpected message: got %q want %q", n.Message, want)
}
if n.UserName != "einstein" {
t.Errorf("unexpected username: %q", n.UserName)
}
if n.ResourceID != "storage-1$space-1!item-1" {
t.Errorf("unexpected resource id: %q", n.ResourceID)
}
}
+5
View File
@@ -162,6 +162,11 @@ func (ul *UserlogService) processEvent(event events.Event) {
default:
return
}
case events.UploadReady:
if !e.Failed {
return
}
users = append(users, e.ExecutingUser.GetId().GetOpaqueId())
// space related // TODO: how to find spaceadmins?
case events.SpaceDisabled:
@@ -14,6 +14,11 @@ var (
Message: l10n.Template("File {resource} was deleted because it violates the policies"),
}
UploadFailed = NotificationTemplate{
Subject: l10n.Template("Upload failed"),
Message: l10n.Template("The upload of {resource} could not be finalized. Please try again."),
}
SpaceShared = NotificationTemplate{
Subject: l10n.Template("Space shared"),
Message: l10n.Template("{user} added you to Space {space}"),
+1 -1
View File
@@ -485,7 +485,7 @@ def main() -> int:
if cfg["tikaNeeded"]:
print("Starting tika...")
run(["docker", "run", "-d", "--name", "tika", "--network", "host",
os.environ.get("TIKA_IMAGE") or "apache/tika:3.2.2.0-full"])
"apache/tika:3.2.2.0-full"])
wait_for(tika_healthy, 120, "tika")
print("tika ready.")
@@ -77,6 +77,15 @@ export const onSSEProcessingFinishedEvent = async ({
previewService,
processedItems
}: SSEEventOptions) => {
// finalize failed, node reverted: drop the optimistic row (incl. on the initiator).
if (sseData.outcome === 'failed') {
const failedResource = resourcesStore.resources.find((f) => f.id === sseData.itemid)
if (failedResource) {
resourcesStore.removeResources([failedResource])
}
return
}
if (!isItemInCurrentFolder({ resourcesStore, parentFolderId: sseData.parentitemid })) {
return false
}
@@ -19,7 +19,8 @@ export const eventSchema = z.object({
spaceid: z.string().optional(),
initiatorid: z.string().optional(),
etag: z.string().optional(),
affecteduserids: z.array(z.string()).optional().nullable()
affecteduserids: z.array(z.string()).optional().nullable(),
outcome: z.enum(['failed']).optional()
})
export type EventSchemaType = z.infer<typeof eventSchema>
@@ -120,6 +120,50 @@ describe('file events', () => {
expect(mocks.resourcesStore.upsertResource).not.toHaveBeenCalled()
})
})
describe('onSSEProcessingFinishedEvent', () => {
it('removes the resource when the upload failed to finalize', async () => {
const failedResource = mock<Resource>({
id: 'file1',
storageId: 'space1',
parentFolderId: 'currenFolder!currentFolder'
})
const mocks = getMocks({ resources: [failedResource] })
const sseData = mock<EventSchemaType>({
itemid: failedResource.id,
spaceid: failedResource.storageId,
outcome: 'failed'
})
await onSSEProcessingFinishedEvent({ sseData, ...mocks })
expect(mocks.resourcesStore.removeResources).toHaveBeenCalledWith([failedResource])
expect(mocks.messageStore.showMessage).not.toHaveBeenCalled()
})
it('removes the failed resource even when initiated by the current client', async () => {
const failedResource = mock<Resource>({
id: 'file1',
storageId: 'space1',
parentFolderId: 'currenFolder!currentFolder'
})
const mocks = getMocks({ resources: [failedResource] })
const sseData = mock<EventSchemaType>({
itemid: failedResource.id,
spaceid: failedResource.storageId,
initiatorid: 'local1',
outcome: 'failed'
})
await onSSEProcessingFinishedEvent({ sseData, ...mocks })
expect(mocks.resourcesStore.removeResources).toHaveBeenCalledWith([failedResource])
})
it('does not remove anything when the failed resource is not in the store', async () => {
const mocks = getMocks()
const sseData = mock<EventSchemaType>({
itemid: 'filesomewhereelse',
spaceid: 'space1',
outcome: 'failed'
})
await onSSEProcessingFinishedEvent({ sseData, ...mocks })
expect(mocks.resourcesStore.removeResources).not.toHaveBeenCalled()
})
})
describe('onSSEItemTrashedEvent', () => {
it('calls "removeResources" when resource has been trashed', async () => {
const resourceToTrash = mock<Resource>({