Files
ragflow/internal/ingestion/component/document_storage.go

147 lines
4.0 KiB
Go
Raw Normal View History

//
// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package component
import (
"context"
"fmt"
"ragflow/internal/dao"
"ragflow/internal/entity"
"ragflow/internal/storage"
)
// DocumentStorageRef is the resolved backing storage location for a document.
// It is exported so higher-level integration tests can inject doc_id resolution
// without reaching into DAO state.
type DocumentStorageRef struct {
Name string
Bucket string
Path string
}
// ResolveDocumentStorageOverride is the narrow test seam for doc_id-driven
// storage resolution. Production leaves this nil and uses DAO-backed lookup.
var ResolveDocumentStorageOverride func(docID string) (*DocumentStorageRef, error)
feat(agent): Go ingestion pipeline progress mirroring and DeepDOC parser hardening (#16795) feat(ingestion): mirror Go pipeline progress into the document table; harden resume guards - pipeline: bind the owning document via WithDocumentID; after each TrackProgress event aggregate ingestion_task_log progress and mirror progress/run/progress_msg back into the document table, so GET /api/v1/datasets/{dataset_id}/documents reflects live Go pipeline progress without a bespoke endpoint. - canvas: extend the S3 resume guard to reject legacy no-op nodes (e.g. ExitLoop) so component_total equals the count of progress-reporting components and the aggregate percent can reach 100%. - runtime/canvas: route progress through TrackProgress; add interrupt test coverage (r3_interrupt_test.go). - dao/entity: add IngestionTask.DocumentID column and AggregateProgress support used by the mirror; IngestionTaskLog keeps a Checkpoint column alongside the progress fields. feat(deepdoc): cache DocAnalyzer inference results in Redis (1h TTL) - Redis-backed DocAnalyzerCache decorator over inference.Client; cache key = "ddoc:cache:<method>:" + sha256 of the JPEG-encoded image bytes (deterministic). - TTL = 1h; hits skip the inner HTTP call and return cached JSON; inner errors are not cached. refactor(deepdoc): align figure cropping with Python cropout + bounded page caches - CropSectionByDLA mirrors Python cropout: best-overlap DLA figure/equation region, fallback to section bbox per page, vertical concat on gray background. - sliding-window page-image cache bounds peak memory to the recent window instead of the whole PDF. - rename DLADebug -> DLARegions across parser/chunker/tests. refactor(parser): drop lib_type selector; align NewXxxParser with NewPDFParser - remove config["lib_type"] lookup and the libType param/field/switch from all nine constructors; surface the CGO-required error at ParseWithResult time instead of construction time; drop resolveLibType, its test, and the four lib_type constants. feat(utility): add a reusable workerpool for bounded concurrent execution - internal/utility/workerpool.go (+ tests). refactor: translate Chinese prose comments to English in non-harness Go files. chore: upgrade github.com/cloudwego/eino from v0.9.9 to v0.9.12.
2026-07-10 10:36:10 +08:00
// FetchBinary downloads the raw object stored at (bucket, path). It is
// exported so downstream components (e.g. the chunker, which re-acquires
// the source PDF to crop section images on demand) can reuse the same
// storage resolution the Parser uses.
func FetchBinary(ctx context.Context, bucket, path string) ([]byte, error) {
stg := resolveStorage()
if stg == nil {
return nil, fmt.Errorf("no storage backend registered")
}
type result struct {
data []byte
err error
}
done := make(chan result, 1)
go func() {
data, err := stg.Get(bucket, path)
done <- result{data: data, err: err}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case r := <-done:
if r.err != nil {
return nil, fmt.Errorf("storage.Get(%q, %q): %w", bucket, path, r.err)
}
return r.data, nil
}
}
func resolveStorage() storage.Storage {
if SetStorageFactoryOverride != nil {
if s := SetStorageFactoryOverride(); s != nil {
return s
}
}
return storage.GetStorageFactory().GetStorage()
}
feat(agent): Go ingestion pipeline progress mirroring and DeepDOC parser hardening (#16795) feat(ingestion): mirror Go pipeline progress into the document table; harden resume guards - pipeline: bind the owning document via WithDocumentID; after each TrackProgress event aggregate ingestion_task_log progress and mirror progress/run/progress_msg back into the document table, so GET /api/v1/datasets/{dataset_id}/documents reflects live Go pipeline progress without a bespoke endpoint. - canvas: extend the S3 resume guard to reject legacy no-op nodes (e.g. ExitLoop) so component_total equals the count of progress-reporting components and the aggregate percent can reach 100%. - runtime/canvas: route progress through TrackProgress; add interrupt test coverage (r3_interrupt_test.go). - dao/entity: add IngestionTask.DocumentID column and AggregateProgress support used by the mirror; IngestionTaskLog keeps a Checkpoint column alongside the progress fields. feat(deepdoc): cache DocAnalyzer inference results in Redis (1h TTL) - Redis-backed DocAnalyzerCache decorator over inference.Client; cache key = "ddoc:cache:<method>:" + sha256 of the JPEG-encoded image bytes (deterministic). - TTL = 1h; hits skip the inner HTTP call and return cached JSON; inner errors are not cached. refactor(deepdoc): align figure cropping with Python cropout + bounded page caches - CropSectionByDLA mirrors Python cropout: best-overlap DLA figure/equation region, fallback to section bbox per page, vertical concat on gray background. - sliding-window page-image cache bounds peak memory to the recent window instead of the whole PDF. - rename DLADebug -> DLARegions across parser/chunker/tests. refactor(parser): drop lib_type selector; align NewXxxParser with NewPDFParser - remove config["lib_type"] lookup and the libType param/field/switch from all nine constructors; surface the CGO-required error at ParseWithResult time instead of construction time; drop resolveLibType, its test, and the four lib_type constants. feat(utility): add a reusable workerpool for bounded concurrent execution - internal/utility/workerpool.go (+ tests). refactor: translate Chinese prose comments to English in non-harness Go files. chore: upgrade github.com/cloudwego/eino from v0.9.9 to v0.9.12.
2026-07-10 10:36:10 +08:00
// ResolveDocumentStorage maps a document ID to its backing storage
// location. It is exported so downstream components can re-acquire the
// source PDF without threading the raw bytes across the component
// boundary.
func ResolveDocumentStorage(docID string) (*DocumentStorageRef, error) {
if ResolveDocumentStorageOverride != nil {
return ResolveDocumentStorageOverride(docID)
}
doc, err := dao.NewDocumentDAO().GetByID(docID)
if err != nil {
return nil, err
}
ref := &DocumentStorageRef{Name: documentNameOrID(doc)}
mappings, err := dao.NewFile2DocumentDAO().GetByDocumentID(doc.ID)
if err != nil {
return nil, err
}
if len(mappings) > 0 && mappings[0].FileID != nil && *mappings[0].FileID != "" {
file, err := dao.NewFileDAO().GetByID(*mappings[0].FileID)
if err != nil {
return nil, err
}
if file.SourceType == "" || entity.FileSource(file.SourceType) == entity.FileSourceLocal {
if file.Location == nil || *file.Location == "" {
return nil, fmt.Errorf("file location is empty")
}
ref.Bucket = file.ParentID
ref.Path = *file.Location
return ref, nil
}
}
if doc.Location == nil || *doc.Location == "" {
return nil, fmt.Errorf("document location is empty")
}
ref.Bucket = doc.KbID
ref.Path = *doc.Location
return ref, nil
}
func resolveDocumentName(docID string) (string, error) {
if ResolveDocumentStorageOverride != nil {
ref, err := ResolveDocumentStorageOverride(docID)
if err != nil {
return "", err
}
if ref != nil && ref.Name != "" {
return ref.Name, nil
}
}
doc, err := dao.NewDocumentDAO().GetByID(docID)
if err != nil {
return "", err
}
return documentNameOrID(doc), nil
}
func documentNameOrID(doc *entity.Document) string {
if doc != nil && doc.Name != nil && *doc.Name != "" {
return *doc.Name
}
if doc != nil {
return doc.ID
}
return ""
}