feat(knowledge): offload manual processing to async tasks
This commit is contained in:
@@ -3,14 +3,22 @@ package docparser
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -156,11 +164,188 @@ func extFromMime(mime string) string {
|
||||
}
|
||||
|
||||
// isProviderScheme checks if the path uses a provider:// scheme (local://, minio://, cos://, tos://).
|
||||
func isProviderScheme(path string) bool {
|
||||
func isProviderScheme(p string) bool {
|
||||
for _, prefix := range []string{"local://", "minio://", "cos://", "tos://"} {
|
||||
if strings.HasPrefix(path, prefix) {
|
||||
if strings.HasPrefix(p, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Remote image resolution (for manual / web-clipped markdown content)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const (
|
||||
// maxRemoteImageSize is the maximum allowed size for a single remote image download.
|
||||
maxRemoteImageSize = 10 * 1024 * 1024 // 10 MB
|
||||
// maxRemoteImages is the maximum number of remote images to process per document.
|
||||
maxRemoteImages = 30
|
||||
// remoteImageFetchTimeout is the per-image HTTP request timeout.
|
||||
remoteImageFetchTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
// imgMarkdownPattern matches Markdown image syntax: 
|
||||
var imgMarkdownPattern = regexp.MustCompile(`!\[([^\]]*)\]\(([^)\s]+)\)`)
|
||||
|
||||
// ResolveRemoteImages scans a Markdown string for image references whose URL
|
||||
// is http:// or https://, downloads each one through an SSRF-safe HTTP client,
|
||||
// uploads the bytes via fileSvc, and replaces the original URL with the
|
||||
// provider:// serving URL.
|
||||
//
|
||||
// Images that fail SSRF validation, exceed size limits, or cannot be downloaded
|
||||
// are left unchanged (the original URL is preserved).
|
||||
//
|
||||
// Returns the updated Markdown and a list of successfully stored images.
|
||||
func (r *ImageResolver) ResolveRemoteImages(
|
||||
ctx context.Context,
|
||||
markdown string,
|
||||
fileSvc interfaces.FileService,
|
||||
tenantID uint64,
|
||||
) (updatedMarkdown string, images []StoredImage, err error) {
|
||||
matches := imgMarkdownPattern.FindAllStringSubmatchIndex(markdown, -1)
|
||||
if len(matches) == 0 {
|
||||
return markdown, nil, nil
|
||||
}
|
||||
|
||||
// Build a shared SSRF-safe HTTP client for all downloads.
|
||||
httpClient := secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{
|
||||
Timeout: remoteImageFetchTimeout,
|
||||
MaxRedirects: 5,
|
||||
})
|
||||
|
||||
processed := 0
|
||||
|
||||
// Process in reverse order so that earlier indices stay valid after replacements.
|
||||
for i := len(matches) - 1; i >= 0; i-- {
|
||||
if processed >= maxRemoteImages {
|
||||
break
|
||||
}
|
||||
m := matches[i]
|
||||
imgURL := markdown[m[4]:m[5]] // group 2: the URL
|
||||
|
||||
// Only process remote http(s) URLs.
|
||||
if !strings.HasPrefix(imgURL, "http://") && !strings.HasPrefix(imgURL, "https://") {
|
||||
continue
|
||||
}
|
||||
|
||||
// Already a provider scheme — skip.
|
||||
if isProviderScheme(imgURL) {
|
||||
continue
|
||||
}
|
||||
|
||||
// --- SSRF check ---
|
||||
if safe, reason := secutils.IsSSRFSafeURL(imgURL); !safe {
|
||||
log.Printf("WARN: remote image blocked by SSRF check (%s): %s", reason, imgURL)
|
||||
continue
|
||||
}
|
||||
|
||||
// --- Download ---
|
||||
data, mimeType, dlErr := downloadImage(ctx, httpClient, imgURL)
|
||||
if dlErr != nil {
|
||||
log.Printf("WARN: failed to download remote image %s: %v", imgURL, dlErr)
|
||||
continue
|
||||
}
|
||||
|
||||
// Filter out icons / tiny decorative images.
|
||||
if isIconImage(data) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Determine file extension.
|
||||
ext := extFromMime(mimeType)
|
||||
if ext == "" {
|
||||
ext = extFromURLPath(imgURL)
|
||||
}
|
||||
if ext == "" {
|
||||
ext = ".png" // safe default
|
||||
}
|
||||
|
||||
// --- Upload to storage ---
|
||||
fileName := uuid.New().String() + ext
|
||||
servingURL, saveErr := fileSvc.SaveBytes(ctx, data, tenantID, fileName, false)
|
||||
if saveErr != nil {
|
||||
log.Printf("WARN: failed to save remote image %s: %v", imgURL, saveErr)
|
||||
continue
|
||||
}
|
||||
|
||||
images = append(images, StoredImage{
|
||||
OriginalRef: imgURL,
|
||||
ServingURL: servingURL,
|
||||
MimeType: mimeType,
|
||||
})
|
||||
|
||||
// Replace URL in markdown.
|
||||
markdown = markdown[:m[4]] + servingURL + markdown[m[5]:]
|
||||
processed++
|
||||
}
|
||||
|
||||
return markdown, images, nil
|
||||
}
|
||||
|
||||
// downloadImage fetches an image from remoteURL using the provided SSRF-safe
|
||||
// client. It validates Content-Type and enforces maxRemoteImageSize.
|
||||
func downloadImage(ctx context.Context, client *http.Client, remoteURL string) (data []byte, mimeType string, err error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, remoteURL, nil)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
// Some CDNs require a browser-like User-Agent.
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; WeKnora/1.0)")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("HTTP GET: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, "", fmt.Errorf("unexpected status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Determine MIME type from Content-Type header.
|
||||
ct := resp.Header.Get("Content-Type")
|
||||
mimeType, _, _ = mime.ParseMediaType(ct)
|
||||
if mimeType == "" {
|
||||
mimeType = "application/octet-stream"
|
||||
}
|
||||
|
||||
// Only allow image content types (or octet-stream which we sniff later).
|
||||
if !strings.HasPrefix(mimeType, "image/") && mimeType != "application/octet-stream" {
|
||||
return nil, "", fmt.Errorf("non-image content type: %s", mimeType)
|
||||
}
|
||||
|
||||
// Read body with size limit.
|
||||
limited := io.LimitReader(resp.Body, maxRemoteImageSize+1)
|
||||
body, err := io.ReadAll(limited)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("read body: %w", err)
|
||||
}
|
||||
if len(body) > maxRemoteImageSize {
|
||||
return nil, "", fmt.Errorf("image exceeds %d bytes limit", maxRemoteImageSize)
|
||||
}
|
||||
|
||||
// If MIME was octet-stream, sniff the real type from body.
|
||||
if mimeType == "application/octet-stream" {
|
||||
detected := http.DetectContentType(body)
|
||||
if strings.HasPrefix(detected, "image/") {
|
||||
mimeType = detected
|
||||
} else {
|
||||
return nil, "", fmt.Errorf("downloaded data is not an image (sniffed: %s)", detected)
|
||||
}
|
||||
}
|
||||
|
||||
return body, mimeType, nil
|
||||
}
|
||||
|
||||
// extFromURLPath extracts the image file extension from the URL path segment.
|
||||
func extFromURLPath(rawURL string) string {
|
||||
p := path.Ext(path.Base(rawURL))
|
||||
switch strings.ToLower(p) {
|
||||
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg":
|
||||
return strings.ToLower(p)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// mockFileService is a minimal FileService implementation for testing.
|
||||
type mockFileService struct {
|
||||
saved []savedEntry
|
||||
}
|
||||
|
||||
type savedEntry struct {
|
||||
Data []byte
|
||||
TenantID uint64
|
||||
FileName string
|
||||
}
|
||||
|
||||
func (m *mockFileService) CheckConnectivity(ctx context.Context) error { return nil }
|
||||
func (m *mockFileService) SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
func (m *mockFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
|
||||
m.saved = append(m.saved, savedEntry{Data: data, TenantID: tenantID, FileName: fileName})
|
||||
return fmt.Sprintf("local://images/%s", fileName), nil
|
||||
}
|
||||
func (m *mockFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *mockFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
|
||||
return filePath, nil
|
||||
}
|
||||
func (m *mockFileService) DeleteFile(ctx context.Context, filePath string) error { return nil }
|
||||
|
||||
func TestResolveRemoteImages_NormalDownload(t *testing.T) {
|
||||
// Create a test HTTP server that serves a real PNG image.
|
||||
pngData := createTestPNG(200, 200)
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(pngData)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
markdown := fmt.Sprintf("# Hello\n\n\n\nSome text", ts.URL)
|
||||
|
||||
resolver := NewImageResolver()
|
||||
fSvc := &mockFileService{}
|
||||
|
||||
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 42)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(images) != 1 {
|
||||
t.Fatalf("expected 1 stored image, got %d", len(images))
|
||||
}
|
||||
|
||||
// URL should have been replaced.
|
||||
if strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("original URL should have been replaced in markdown, got: %s", updated)
|
||||
}
|
||||
if !strings.Contains(updated, "local://images/") {
|
||||
t.Errorf("expected local:// URL in markdown, got: %s", updated)
|
||||
}
|
||||
|
||||
// Verify saved data.
|
||||
if len(fSvc.saved) != 1 {
|
||||
t.Fatalf("expected 1 saved entry, got %d", len(fSvc.saved))
|
||||
}
|
||||
if fSvc.saved[0].TenantID != 42 {
|
||||
t.Errorf("expected tenantID 42, got %d", fSvc.saved[0].TenantID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_SSRFBlocked(t *testing.T) {
|
||||
// URLs pointing to private IPs should be blocked by SSRF check.
|
||||
markdown := "\n\n"
|
||||
|
||||
resolver := NewImageResolver()
|
||||
fSvc := &mockFileService{}
|
||||
|
||||
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Both images should be left unchanged (SSRF blocked).
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected 0 stored images (SSRF blocked), got %d", len(images))
|
||||
}
|
||||
if updated != markdown {
|
||||
t.Errorf("markdown should be unchanged when SSRF blocked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_NonImageContentType(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("<html>not an image</html>"))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
markdown := fmt.Sprintf("", ts.URL)
|
||||
|
||||
resolver := NewImageResolver()
|
||||
fSvc := &mockFileService{}
|
||||
|
||||
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected 0 images for non-image content type, got %d", len(images))
|
||||
}
|
||||
// Original URL should be preserved.
|
||||
if !strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("original URL should be preserved for non-image content")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_ProviderSchemeSkipped(t *testing.T) {
|
||||
markdown := "\n"
|
||||
|
||||
resolver := NewImageResolver()
|
||||
fSvc := &mockFileService{}
|
||||
|
||||
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected 0 images for provider:// URLs, got %d", len(images))
|
||||
}
|
||||
if updated != markdown {
|
||||
t.Errorf("markdown should be unchanged for provider:// URLs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_MultipleImages(t *testing.T) {
|
||||
pngData := createTestPNG(256, 256)
|
||||
callCount := 0
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
callCount++
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(pngData)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
markdown := fmt.Sprintf("\n\ntext\n\n\n\n",
|
||||
ts.URL, ts.URL, ts.URL)
|
||||
|
||||
resolver := NewImageResolver()
|
||||
fSvc := &mockFileService{}
|
||||
|
||||
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(images) != 3 {
|
||||
t.Fatalf("expected 3 stored images, got %d", len(images))
|
||||
}
|
||||
if callCount != 3 {
|
||||
t.Errorf("expected 3 HTTP requests, got %d", callCount)
|
||||
}
|
||||
if strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("all original URLs should have been replaced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_NoImages(t *testing.T) {
|
||||
markdown := "# Just text\n\nNo images here."
|
||||
|
||||
resolver := NewImageResolver()
|
||||
fSvc := &mockFileService{}
|
||||
|
||||
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected 0 images, got %d", len(images))
|
||||
}
|
||||
if updated != markdown {
|
||||
t.Errorf("markdown should be unchanged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRemoteImages_Server404(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
markdown := fmt.Sprintf("", ts.URL)
|
||||
|
||||
resolver := NewImageResolver()
|
||||
fSvc := &mockFileService{}
|
||||
|
||||
updated, images, err := resolver.ResolveRemoteImages(context.Background(), markdown, fSvc, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(images) != 0 {
|
||||
t.Errorf("expected 0 images for 404, got %d", len(images))
|
||||
}
|
||||
// Original URL preserved on failure.
|
||||
if !strings.Contains(updated, ts.URL) {
|
||||
t.Errorf("original URL should be preserved on download failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtFromURLPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
url string
|
||||
expect string
|
||||
}{
|
||||
{"https://example.com/photo.jpg", ".jpg"},
|
||||
{"https://example.com/photo.JPEG", ".jpeg"},
|
||||
{"https://example.com/photo.png?v=2", ""}, // query param — path.Ext won't catch it cleanly but that's ok
|
||||
{"https://example.com/photo.gif", ".gif"},
|
||||
{"https://example.com/photo.webp", ".webp"},
|
||||
{"https://example.com/photo.bmp", ".bmp"},
|
||||
{"https://example.com/photo.svg", ".svg"},
|
||||
{"https://example.com/photo.pdf", ""},
|
||||
{"https://example.com/noext", ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.url, func(t *testing.T) {
|
||||
got := extFromURLPath(tt.url)
|
||||
if got != tt.expect {
|
||||
t.Errorf("extFromURLPath(%q) = %q, want %q", tt.url, got, tt.expect)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user