diff --git a/internal/im/content_rewrite_test.go b/internal/im/content_rewrite_test.go index 64c14746..99b82206 100644 --- a/internal/im/content_rewrite_test.go +++ b/internal/im/content_rewrite_test.go @@ -68,60 +68,6 @@ func TestStripImageXMLTags(t *testing.T) { } } -func TestFindIncompleteStorageURL(t *testing.T) { - tests := []struct { - name string - in string - want int // expected return; -1 means no match expected - }{ - { - "complete URL terminated by )", - "![img](local://1/abc/img.png)", - // The URL `local://1/abc/img.png` ends with `)` which is a terminator, - // but the regex [^\s)\]>"]* matches up to `)` — the `)` is NOT included. - // So the URL portion is `local://1/abc/img.png` and `)` terminates it. - // The match does NOT reach end of string → should return -1. - -1, - }, - { - "complete URL terminated by space", - "text local://1/abc/img.png more text", - -1, - }, - { - "truncated URL at end", - "text ![img](local://1/abc/im", - 12, // starts at `l` in `local://` - }, - { - "just scheme at end", - "text minio://", - 5, - }, - { - "partial scoped URL at end", - "text storage://backend-a/co", - 5, - }, - { - "no storage URL", - "just plain text http://example.com", - -1, - }, - { - "URL at very end", - "local://1/img.png", - 0, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := findIncompleteStorageURL(tt.in) - assert.Equal(t, tt.want, got, "findIncompleteStorageURL(%q)", tt.in) - }) - } -} - func TestFindIncompleteXMLTag(t *testing.T) { tests := []struct { name string @@ -237,29 +183,6 @@ func TestRewriteStorageURLs_COSPathNotSignedAsLocalKey(t *testing.T) { } } -func TestFindIncompleteMarkdownImage(t *testing.T) { - tests := []struct { - name string - in string - want int - }{ - {"complete image", "![img](local://1/a.png)", -1}, - {"complete then text", "![img](local://1/a.png) trailing", -1}, - {"truncated provider URL in image", `![知识助理"知识库"管理视图界面](minio://wizard-test/10000/exports/c91cf852`, 0}, - {"open paren only", "text ![alt](", 5}, - {"bare provider suffix without markdown", "text minio://wizard-test/10000/exp", -1}, - {"two images complete", "![a](local://1/a.png) ![b](local://1/b.png)", -1}, - {"first complete second incomplete", "![a](local://1/a.png) ![b](minio://part", 22}, - {"bracket inside alt text", "![a[b]](minio://wizard-test/10000/part", 0}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := findIncompleteMarkdownImage(tt.in) - assert.Equal(t, tt.want, got, "findIncompleteMarkdownImage(%q)", tt.in) - }) - } -} - func TestHoldbackCutoff(t *testing.T) { tests := []struct { name string diff --git a/internal/im/im_file_service_test.go b/internal/im/im_file_service_test.go index 81948777..aaae77d4 100644 --- a/internal/im/im_file_service_test.go +++ b/internal/im/im_file_service_test.go @@ -79,11 +79,11 @@ func TestIMFileServiceResolver_CachesPerProvider(t *testing.T) { } r := newIMFileServiceResolver(tenant, stub) - svc1 := r.resolve("minio://wizard-test/10000/a.png") - svc2 := r.resolve("minio://wizard-test/10000/b.png") + svc1 := r.ResolveFileService("minio://wizard-test/10000/a.png") + svc2 := r.ResolveFileService("minio://wizard-test/10000/b.png") assert.Same(t, svc1, svc2, "same provider should reuse cached FileService") - svc3 := r.resolve("local://10000/c.png") + svc3 := r.ResolveFileService("local://10000/c.png") assert.NotSame(t, svc1, svc3, "different provider should use a different service") } diff --git a/internal/im/service.go b/internal/im/service.go index 4eea47b3..6e570052 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -18,7 +18,6 @@ import ( "time" agenttools "github.com/Tencent/WeKnora/internal/agent/tools" - filesvc "github.com/Tencent/WeKnora/internal/application/service/file" "github.com/Tencent/WeKnora/internal/config" apperrors "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/event" @@ -26,6 +25,7 @@ import ( mcppkg "github.com/Tencent/WeKnora/internal/mcp" "github.com/Tencent/WeKnora/internal/models/chat" "github.com/Tencent/WeKnora/internal/ratelimit" + "github.com/Tencent/WeKnora/internal/storageurl" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/google/uuid" @@ -80,112 +80,22 @@ func stripImageXMLTags(s string) string { }) } -// storageSchemeRe matches both legacy provider:// URLs and canonical -// storage:///provider:// URLs. -var storageSchemeRe = regexp.MustCompile( - `\b(?:resource://[0-9A-Za-z_-]+|` + - `(?:storage://[0-9A-Za-z_-]+/)?` + - `(?:local|minio|s3|cos|tos|oss|obs|ks3)://[^\s)\]>"]+)`, -) - -// isHTTPResolvedURL reports whether s is an http(s) URL — the only form an IM -// client can fetch; any provider:// scheme (oss://, local://, …) is not. -// Scheme match is case-insensitive per RFC 3986 §3.1: a backend may emit an -// operator-configured host (e.g. OBS_PROXY_DOMAIN) with an uppercase scheme. -func isHTTPResolvedURL(s string) bool { - return len(s) >= 7 && strings.EqualFold(s[:7], "http://") || - len(s) >= 8 && strings.EqualFold(s[:8], "https://") -} - -// rewriteStorageURLs replaces all provider:// URLs in content with HTTP URLs -// obtained from fileService.GetFileURL. URLs that are already HTTP or cannot -// be resolved are left unchanged. -// -// Logging policy: -// - Successful rewrite logs at INFO with the full signed URL so operators -// can copy it out of logs and verify public reachability directly. The -// trade-off: anyone with log access can use a signed URL until it -// expires (WeKnora 2h, MinIO 24h). Acceptable for diagnosability. -// - Failure or no-op rewrite logs at WARN. The no-op case typically means -// APP_EXTERNAL_URL is not configured (local backend, or resource:// content -// that must be served via /r/), the most common cause of "image broken in -// IM" reports. -func rewriteStorageURLs(ctx context.Context, content string, resolver *imFileServiceResolver) string { +// rewriteStorageURLs replaces all storage references in content with HTTP URLs +// so IM clients — which cannot attach WeKnora credentials to an image fetch — +// can render them. See internal/storageurl for the shared implementation. +func rewriteStorageURLs(ctx context.Context, content string, resolver *storageurl.FileServiceResolver) string { if resolver == nil { return content } - return storageSchemeRe.ReplaceAllStringFunc(content, func(match string) string { - fileSvc := resolver.resolve(match) - if fileSvc == nil { - logger.Warnf(ctx, "[IM] rewriteStorageURLs: no file service for src=%s", match) - return match - } - httpURL, err := fileSvc.GetFileURL(ctx, match) - if err != nil { - logger.Warnf(ctx, "[IM] rewriteStorageURLs failed: src=%s err=%v", match, err) - return match - } - // A non-http(s) result cannot be rendered by an IM client — covers both the - // unchanged no-op and a resource:// alias left as an internal storage:// path - // (APP_EXTERNAL_URL unset / nginx not proxying /r/). - if !isHTTPResolvedURL(httpURL) { - logger.Warnf(ctx, - "[IM] rewriteStorageURLs no-op (resolved to non-HTTP URL %q; for local/private storage set APP_EXTERNAL_URL and ensure nginx proxies /r/): src=%s", - httpURL, match) - return match - } - logger.Infof(ctx, "[IM] rewriteStorageURLs: src=%s dst=%s", match, httpURL) - return httpURL - }) + return storageurl.Rewrite(ctx, content, resolver, "IM") } // ── Streaming holdback helpers ── -// During streaming, content is flushed in 300ms batches. A provider:// URL or +// During streaming, content is flushed in 300ms batches. A storage reference or // an XML tag may be split across two batches. These helpers detect incomplete // patterns at the end of a chunk so the caller can hold them back until the // next flush completes them. -// incompleteURLSuffixRe matches a provider:// URL that reaches the end of the -// string — it may continue in the next chunk. -var incompleteURLSuffixRe = regexp.MustCompile( - `\b(?:resource|storage|local|minio|s3|cos|tos|oss|obs|ks3)://[^\s)\]>"]*$`, -) - -// findIncompleteStorageURL returns the byte offset of a potentially truncated -// provider:// URL at the tail of s, or -1 if none. -func findIncompleteStorageURL(s string) int { - loc := incompleteURLSuffixRe.FindStringIndex(s) - if loc == nil { - return -1 - } - return loc[0] -} - -// incompleteMarkdownImageSuffixRe matches a Markdown image whose destination URL -// (the parenthesized part) is not yet closed — e.g. "![alt](minio://part" or "![alt](". -// Holding back only from "minio://" would flush "![alt](" to the IM client and break -// the image once the URL arrives in the next chunk. -var incompleteMarkdownImageSuffixRe = regexp.MustCompile(`!\[[^\]]*\]\([^)]*$`) - -// findIncompleteMarkdownImage returns the byte offset of an unclosed ![alt](url -// suffix at the end of s, or -1 if none. -func findIncompleteMarkdownImage(s string) int { - // Prefer pairing a trailing provider:// fragment with the nearest preceding ![…]( - // so alt text may contain ']' (e.g. ![a[b]](minio://part). - if urlIdx := findIncompleteStorageURL(s); urlIdx >= 0 { - if imgIdx := strings.LastIndex(s[:urlIdx], "!["); imgIdx >= 0 { - if strings.Contains(s[imgIdx:urlIdx], "](") { - return imgIdx - } - } - } - loc := incompleteMarkdownImageSuffixRe.FindStringIndex(s) - if loc == nil { - return -1 - } - return loc[0] -} - // incompleteXMLTagRe matches the opening of an , , or tag // that reaches the end of the string without a closing '>'. var incompleteXMLTagRe = regexp.MustCompile( @@ -205,12 +115,7 @@ func findIncompleteXMLTag(s string) int { // holdbackCutoff returns the earliest incomplete-pattern offset at the tail of // chunk, or len(chunk) if the chunk is safe to flush entirely. func holdbackCutoff(chunk string) int { - cutoff := len(chunk) - if idx := findIncompleteMarkdownImage(chunk); idx >= 0 && idx < cutoff { - cutoff = idx - } else if idx := findIncompleteStorageURL(chunk); idx >= 0 && idx < cutoff { - cutoff = idx - } + cutoff := storageurl.HoldbackCutoff(chunk) if idx := findIncompleteXMLTag(chunk); idx >= 0 && idx < cutoff { cutoff = idx } @@ -229,109 +134,37 @@ func formatIMOutboundAnswer(ctx context.Context, raw string, tenant *types.Tenan func cleanIMContent(ctx context.Context, content string, tenant *types.Tenant, defaultFileSvc interfaces.FileService, storageResolvers ...interfaces.StorageBackendResolver) string { content = stripImageXMLTags(content) content = stripIMCitationTags(content) - resolver := newIMFileServiceResolver(tenant, defaultFileSvc, storageResolvers...) - resolver.ctx = ctx + resolver := newIMFileServiceResolver(tenant, defaultFileSvc, storageResolvers...).WithContext(ctx) content = rewriteStorageURLs(ctx, content, resolver) return content } func imLocalStorageBaseDir() string { - baseDir := strings.TrimSpace(os.Getenv("LOCAL_STORAGE_BASE_DIR")) - if baseDir == "" { - baseDir = "/data/files" - } - return baseDir + return storageurl.LocalStorageBaseDir() } -// imFileServiceResolver resolves and caches FileService instances per storage provider -// for the lifetime of one cleanIMContent / outbound message (avoids re-creating SDK clients -// for every URL in a long answer). -type imFileServiceResolver struct { - tenant *types.Tenant - defaultSvc interfaces.FileService - storageResolver interfaces.StorageBackendResolver - ctx context.Context - cache map[string]interfaces.FileService +// newIMFileServiceResolver builds a per-message storage backend resolver. The +// cache lives for one cleanIMContent / outbound message so a long answer does +// not re-create an SDK client for every reference. +func newIMFileServiceResolver( + tenant *types.Tenant, + defaultSvc interfaces.FileService, + storageResolvers ...interfaces.StorageBackendResolver, +) *storageurl.FileServiceResolver { + return storageurl.NewFileServiceResolver(tenant, defaultSvc, storageResolvers...) } -func newIMFileServiceResolver(tenant *types.Tenant, defaultSvc interfaces.FileService, storageResolvers ...interfaces.StorageBackendResolver) *imFileServiceResolver { - resolver := &imFileServiceResolver{ - tenant: tenant, - defaultSvc: defaultSvc, - ctx: context.Background(), - cache: make(map[string]interfaces.FileService), - } - if len(storageResolvers) > 0 { - resolver.storageResolver = storageResolvers[0] - } - return resolver -} - -func (r *imFileServiceResolver) resolve(filePath string) interfaces.FileService { - if _, ok := types.ParseResourcePath(filePath); ok { - return r.defaultSvc - } - backendID, _, _ := types.ParseStorageBackendPath(filePath) - provider := types.ParseProviderScheme(filePath) - if provider == "" { - if r.tenant != nil && r.tenant.StorageEngineConfig != nil { - provider = strings.ToLower(strings.TrimSpace(r.tenant.StorageEngineConfig.DefaultProvider)) - } - if provider == "" { - return nil - } - } - cacheKey := backendID + ":" + provider - if svc, ok := r.cache[cacheKey]; ok { - return svc - } - if r.storageResolver != nil && r.tenant != nil { - svc, _, err := r.storageResolver.ResolveFileService(r.ctx, r.tenant, backendID, provider, imLocalStorageBaseDir()) - if err == nil { - r.cache[cacheKey] = svc - return svc - } - logger.Warnf(r.ctx, "[IM] resolve storage backend failed: backend_id=%s provider=%s err=%v", backendID, provider, err) - } - svc := buildIMFileServiceForProvider(r.tenant, provider, r.defaultSvc) - if svc != nil { - r.cache[cacheKey] = svc - } - return svc -} - -// buildIMFileServiceForProvider selects the FileService for a storage provider. -// filePath scheme wins over tenant DefaultProvider. Falls back to the process-wide -// default FileService (STORAGE_TYPE / env) when tenant config is missing — mirrors -// ImageMultimodalService.resolveFileServiceForPayload (issue #1282). func buildIMFileServiceForProvider( tenant *types.Tenant, provider string, defaultSvc interfaces.FileService, ) interfaces.FileService { - baseDir := imLocalStorageBaseDir() - var sec *types.StorageEngineConfig - if tenant != nil { - sec = tenant.StorageEngineConfig - } - - svc, _, err := filesvc.NewFileServiceFromStorageConfig(provider, sec, baseDir) - if err == nil { - return svc - } - if provider == "local" { - externalURL := strings.TrimSpace(os.Getenv("APP_EXTERNAL_URL")) - return filesvc.NewLocalFileService(baseDir, externalURL) - } - if defaultSvc != nil { - return defaultSvc - } - return nil + return storageurl.BuildFileServiceForProvider(tenant, provider, defaultSvc) } // resolveIMFileServiceForPath is a test/helper entry point without caching. func resolveIMFileServiceForPath(tenant *types.Tenant, filePath string, defaultSvc interfaces.FileService) interfaces.FileService { - return newIMFileServiceResolver(tenant, defaultSvc).resolve(filePath) + return newIMFileServiceResolver(tenant, defaultSvc).ResolveFileService(filePath) } const ( diff --git a/internal/storageurl/mode.go b/internal/storageurl/mode.go new file mode 100644 index 00000000..759a29a9 --- /dev/null +++ b/internal/storageurl/mode.go @@ -0,0 +1,40 @@ +package storageurl + +import ( + "fmt" + "strings" +) + +// Mode selects how stored files are referenced in an API response. +type Mode string + +const ( + // ModeHandle returns the internal `resource://` reference. Clients + // must fetch the bytes through the authenticated `/files` proxy. This is the + // default and the only mode that never depends on external reachability. + ModeHandle Mode = "handle" + // ModePublic returns a time-limited HTTP(S) URL the client can load + // directly, so third-party apps can render images without a second + // authenticated call. References that cannot be turned into an HTTP URL are + // left as handles. + ModePublic Mode = "public" +) + +// QueryParam is the request query parameter that selects the mode per call. +const QueryParam = "resource_urls" + +// ParseMode validates a mode supplied by a client or by configuration. An empty +// value yields ModeHandle so an unset parameter or setting keeps the default. +func ParseMode(raw string) (Mode, error) { + switch Mode(strings.ToLower(strings.TrimSpace(raw))) { + case "": + return ModeHandle, nil + case ModeHandle: + return ModeHandle, nil + case ModePublic: + return ModePublic, nil + default: + return ModeHandle, fmt.Errorf( + "invalid %s value %q: expected %q or %q", QueryParam, raw, ModeHandle, ModePublic) + } +} diff --git a/internal/storageurl/resolver.go b/internal/storageurl/resolver.go new file mode 100644 index 00000000..550552ca --- /dev/null +++ b/internal/storageurl/resolver.go @@ -0,0 +1,130 @@ +package storageurl + +import ( + "context" + "os" + "strings" + + filesvc "github.com/Tencent/WeKnora/internal/application/service/file" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// LocalStorageBaseDir is the on-disk root used when a reference resolves to the +// local provider. +func LocalStorageBaseDir() string { + baseDir := strings.TrimSpace(os.Getenv("LOCAL_STORAGE_BASE_DIR")) + if baseDir == "" { + baseDir = "/data/files" + } + return baseDir +} + +// FileServiceResolver resolves and caches one FileService per storage provider. +// The cache is scoped to a single request or outbound message so a long answer +// with many images does not re-create an SDK client per reference. +// +// Not safe for concurrent use; Rewriter drives it from one goroutine at a time. +type FileServiceResolver struct { + tenant *types.Tenant + defaultSvc interfaces.FileService + storageResolver interfaces.StorageBackendResolver + ctx context.Context + cache map[string]interfaces.FileService +} + +// NewFileServiceResolver builds a resolver for tenant. defaultSvc is the +// process-wide FileService used for `resource://` handles and as the fallback +// when tenant storage config is missing. +func NewFileServiceResolver( + tenant *types.Tenant, + defaultSvc interfaces.FileService, + storageResolvers ...interfaces.StorageBackendResolver, +) *FileServiceResolver { + resolver := &FileServiceResolver{ + tenant: tenant, + defaultSvc: defaultSvc, + ctx: context.Background(), + cache: make(map[string]interfaces.FileService), + } + if len(storageResolvers) > 0 { + resolver.storageResolver = storageResolvers[0] + } + return resolver +} + +// WithContext sets the context used for backend lookups and their logs. +func (r *FileServiceResolver) WithContext(ctx context.Context) *FileServiceResolver { + if ctx != nil { + r.ctx = ctx + } + return r +} + +// ResolveFileService implements Resolver. +func (r *FileServiceResolver) ResolveFileService(filePath string) interfaces.FileService { + if _, ok := types.ParseResourcePath(filePath); ok { + return r.defaultSvc + } + backendID, _, _ := types.ParseStorageBackendPath(filePath) + provider := types.ParseProviderScheme(filePath) + if provider == "" { + if r.tenant != nil && r.tenant.StorageEngineConfig != nil { + provider = strings.ToLower(strings.TrimSpace(r.tenant.StorageEngineConfig.DefaultProvider)) + } + if provider == "" { + return nil + } + } + cacheKey := backendID + ":" + provider + if svc, ok := r.cache[cacheKey]; ok { + return svc + } + if r.storageResolver != nil && r.tenant != nil { + svc, _, err := r.storageResolver.ResolveFileService(r.ctx, r.tenant, backendID, provider, LocalStorageBaseDir()) + if err == nil { + r.cache[cacheKey] = svc + return svc + } + logger.Warnf(r.ctx, "resolve storage backend failed: backend_id=%s provider=%s err=%v", + backendID, provider, err) + } + svc := BuildFileServiceForProvider(r.tenant, provider, r.defaultSvc) + if svc != nil { + r.cache[cacheKey] = svc + } + return svc +} + +// BuildFileServiceForProvider selects the FileService for a storage provider. +// The reference's own scheme wins over the tenant DefaultProvider. It falls back +// to the process-wide default FileService (STORAGE_TYPE / env) when tenant +// config is missing — mirrors ImageMultimodalService.resolveFileServiceForPayload +// (issue #1282). +func BuildFileServiceForProvider( + tenant *types.Tenant, + provider string, + defaultSvc interfaces.FileService, +) interfaces.FileService { + baseDir := LocalStorageBaseDir() + var sec *types.StorageEngineConfig + if tenant != nil { + sec = tenant.StorageEngineConfig + } + + svc, _, err := filesvc.NewFileServiceFromStorageConfig(provider, sec, baseDir) + if err == nil { + return svc + } + if provider == "local" { + externalURL := strings.TrimSpace(os.Getenv("APP_EXTERNAL_URL")) + return filesvc.NewLocalFileService(baseDir, externalURL) + } + if defaultSvc != nil { + return defaultSvc + } + return nil +} + +var _ Resolver = (*FileServiceResolver)(nil) diff --git a/internal/storageurl/storageurl.go b/internal/storageurl/storageurl.go new file mode 100644 index 00000000..e1e1dd28 --- /dev/null +++ b/internal/storageurl/storageurl.go @@ -0,0 +1,157 @@ +// Package storageurl converts internal storage references into HTTP(S) URLs an +// external client can load directly. +// +// WeKnora persists files behind two internal reference forms: the stable +// `resource://` application identity and legacy/canonical provider +// paths (`local://…`, `minio://…`, `storage:///cos://…`). Neither is +// fetchable by a browser or a third-party app, which must otherwise call the +// authenticated `/files` proxy for every image. +// +// This package is the single implementation of the "give me a loadable link" +// translation. It is used by the IM channels (which have no way to attach +// WeKnora credentials to an image fetch) and, opt-in, by the HTTP API so +// integrators receive ready-to-render URLs. +package storageurl + +import ( + "context" + "regexp" + "strings" + "sync" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// Pattern matches every internal storage reference form: `resource://` handles, +// legacy `provider://` paths, and canonical `storage:///provider://` +// paths. The trailing character class stops at Markdown/HTML delimiters so a +// reference inside `![alt](…)` or `src="…"` is matched without them. +var Pattern = regexp.MustCompile( + `\b(?:resource://[0-9A-Za-z_-]+|` + + `(?:storage://[0-9A-Za-z_-]+/)?` + + `(?:local|minio|s3|cos|tos|oss|obs|ks3)://[^\s)\]>"]+)`, +) + +// IsHTTPURL reports whether s is an http(s) URL — the only form an external +// client can fetch; any provider scheme (oss://, local://, …) is not. Scheme +// match is case-insensitive per RFC 3986 §3.1: a backend may emit an +// operator-configured host (e.g. OBS_PROXY_DOMAIN) with an uppercase scheme. +func IsHTTPURL(s string) bool { + return len(s) >= 7 && strings.EqualFold(s[:7], "http://") || + len(s) >= 8 && strings.EqualFold(s[:8], "https://") +} + +// Resolver maps one storage reference to the FileService that owns it. A +// reference carries its own provider scheme and optional storage backend id, so +// a single answer may span several backends. +type Resolver interface { + // ResolveFileService returns nil when no backend can serve ref. + ResolveFileService(ref string) interfaces.FileService +} + +// Rewriter replaces storage references with loadable HTTP URLs. +// +// Resolutions are memoised for the Rewriter's lifetime. Create one per request +// or per outbound message: a `resource://` handle costs one access-grant row per +// resolution, and a streamed answer repeats the same image across many chunks. +// +// Logging policy: +// - A successful rewrite logs at INFO with the full signed URL so operators +// can copy it out of logs and verify public reachability directly. The +// trade-off: anyone with log access can use a signed URL until it expires +// (WeKnora grants 2h, MinIO 24h). Acceptable for diagnosability. +// - Failure or no-op logs at WARN. The no-op case usually means +// APP_EXTERNAL_URL is unset, the most common cause of "image broken in the +// IM channel / in my app" reports. +type Rewriter struct { + resolver Resolver + logPrefix string + + mu sync.Mutex + memo map[string]string +} + +// NewRewriter returns a Rewriter that resolves references through r. logPrefix +// tags log lines with the calling surface (for example "IM" or "API"). A nil +// resolver yields a Rewriter that leaves content unchanged. +func NewRewriter(r Resolver, logPrefix string) *Rewriter { + return &Rewriter{resolver: r, logPrefix: logPrefix, memo: make(map[string]string)} +} + +// Enabled reports whether this Rewriter can actually rewrite anything. +func (w *Rewriter) Enabled() bool { + return w != nil && w.resolver != nil +} + +// String replaces every storage reference in content with an HTTP URL. +// References that are already HTTP, that no backend claims, or that resolve to +// a non-HTTP location are left untouched so the caller degrades to the +// authenticated file proxy rather than emitting an unfetchable URL. +func (w *Rewriter) String(ctx context.Context, content string) string { + if !w.Enabled() || content == "" { + return content + } + return Pattern.ReplaceAllStringFunc(content, func(ref string) string { + return w.ref(ctx, ref) + }) +} + +// Ref rewrites a value that is a bare storage reference rather than prose +// containing one — for example `MessageImage.URL`. +func (w *Rewriter) Ref(ctx context.Context, ref string) string { + if !w.Enabled() || ref == "" { + return ref + } + if !Pattern.MatchString(ref) { + return ref + } + return w.String(ctx, ref) +} + +func (w *Rewriter) ref(ctx context.Context, ref string) string { + w.mu.Lock() + cached, ok := w.memo[ref] + w.mu.Unlock() + if ok { + return cached + } + + resolved := w.resolve(ctx, ref) + + w.mu.Lock() + w.memo[ref] = resolved + w.mu.Unlock() + return resolved +} + +func (w *Rewriter) resolve(ctx context.Context, ref string) string { + fileSvc := w.resolver.ResolveFileService(ref) + if fileSvc == nil { + logger.Warnf(ctx, "[%s] storage URL rewrite: no file service for src=%s", w.logPrefix, ref) + return ref + } + httpURL, err := fileSvc.GetFileURL(ctx, ref) + if err != nil { + logger.Warnf(ctx, "[%s] storage URL rewrite failed: src=%s err=%v", w.logPrefix, ref, err) + return ref + } + // A non-http(s) result cannot be fetched by the client — this covers both an + // unchanged no-op and a resource:// alias left as an internal storage:// + // path (APP_EXTERNAL_URL unset / nginx not proxying /r/). + if !IsHTTPURL(httpURL) { + logger.Warnf(ctx, + "[%s] storage URL rewrite no-op (resolved to non-HTTP URL %q; for local/private storage set "+ + "APP_EXTERNAL_URL and ensure nginx proxies /r/): src=%s", + w.logPrefix, httpURL, ref) + return ref + } + logger.Infof(ctx, "[%s] storage URL rewrite: src=%s dst=%s", w.logPrefix, ref, httpURL) + return httpURL +} + +// Rewrite is the one-shot form of Rewriter.String for callers that translate a +// single self-contained message. +func Rewrite(ctx context.Context, content string, r Resolver, logPrefix string) string { + return NewRewriter(r, logPrefix).String(ctx, content) +} diff --git a/internal/storageurl/storageurl_test.go b/internal/storageurl/storageurl_test.go new file mode 100644 index 00000000..24b3c2cc --- /dev/null +++ b/internal/storageurl/storageurl_test.go @@ -0,0 +1,184 @@ +package storageurl + +import ( + "context" + "errors" + "io" + "mime/multipart" + "testing" + + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// stubFileService implements interfaces.FileService; only GetFileURL matters here. +type stubFileService struct { + getFileURL func(ctx context.Context, filePath string) (string, error) + calls int +} + +func (s *stubFileService) CheckConnectivity(context.Context) error { return nil } + +func (s *stubFileService) SaveFile(context.Context, *multipart.FileHeader, uint64, string) (string, error) { + return "", nil +} + +func (s *stubFileService) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) { + return "", nil +} + +func (s *stubFileService) GetFile(context.Context, string) (io.ReadCloser, error) { return nil, nil } + +func (s *stubFileService) GetFileURL(ctx context.Context, filePath string) (string, error) { + s.calls++ + if s.getFileURL != nil { + return s.getFileURL(ctx, filePath) + } + return "https://cdn.example.com/" + filePath, nil +} + +func (s *stubFileService) DeleteFile(context.Context, string) error { return nil } + +func (s *stubFileService) CopyFile(context.Context, string, uint64, string) (string, error) { + return "", nil +} + +// fixedResolver returns the same FileService for every reference. +type fixedResolver struct{ svc interfaces.FileService } + +func (r fixedResolver) ResolveFileService(string) interfaces.FileService { return r.svc } + +func stubResolver(url string) Resolver { + return fixedResolver{svc: &stubFileService{ + getFileURL: func(context.Context, string) (string, error) { return url, nil }, + }} +} + +func TestRewriter_RewritesEveryReferenceForm(t *testing.T) { + svc := &stubFileService{ + getFileURL: func(context.Context, string) (string, error) { + return "https://cdn.example.com/signed.png", nil + }, + } + w := NewRewriter(fixedResolver{svc: svc}, "TEST") + + in := "handle ![a](resource://xifDo7NTSL300Lp1goVutw) " + + "legacy ![b](minio://bucket/10000/exports/b.png) " + + "scoped ![c](storage://backend-a/cos://bucket/ap/10000/exports/c.png)" + out := w.String(context.Background(), in) + + assert.NotContains(t, out, "resource://") + assert.NotContains(t, out, "minio://") + assert.NotContains(t, out, "storage://") + assert.Equal(t, 3, svc.calls) +} + +// An already-public URL in the answer must be left alone. +func TestRewriter_LeavesHTTPURLsAlone(t *testing.T) { + w := NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST") + in := "![a](https://example.com/a.png) and ![b](http://example.com/b.png)" + assert.Equal(t, in, w.String(context.Background(), in)) +} + +// Emitting an unfetchable URL is worse than leaving the handle: the client can +// still fall back to the authenticated /files proxy for a handle. +func TestRewriter_NonHTTPResultIsNoOp(t *testing.T) { + w := NewRewriter(stubResolver("storage://7cb970a6/oss://bucket/10000/exports/a.png"), "TEST") + in := "![img](resource://xifDo7NTSL300Lp1goVutw)" + assert.Equal(t, in, w.String(context.Background(), in)) +} + +func TestRewriter_ResolveFailureIsNoOp(t *testing.T) { + w := NewRewriter(fixedResolver{svc: &stubFileService{ + getFileURL: func(context.Context, string) (string, error) { + return "", errors.New("backend unreachable") + }, + }}, "TEST") + in := "![img](resource://xifDo7NTSL300Lp1goVutw)" + assert.Equal(t, in, w.String(context.Background(), in)) +} + +func TestRewriter_UnknownBackendIsNoOp(t *testing.T) { + w := NewRewriter(fixedResolver{svc: nil}, "TEST") + in := "![img](resource://xifDo7NTSL300Lp1goVutw)" + assert.Equal(t, in, w.String(context.Background(), in)) +} + +// Uppercase schemes are valid per RFC 3986 §3.1 (e.g. an OBS_PROXY_DOMAIN +// configured as HTTPS://…) and must be substituted, not dropped. +func TestRewriter_UppercaseSchemeIsSubstituted(t *testing.T) { + w := NewRewriter(stubResolver("HTTPS://cdn.example.com/x.png"), "TEST") + out := w.String(context.Background(), "![img](resource://xifDo7NTSL300Lp1goVutw)") + assert.Contains(t, out, "HTTPS://cdn.example.com/x.png") + assert.NotContains(t, out, "resource://") +} + +// Each resource:// resolution writes an access-grant row, so a repeated image +// must be resolved once per request. +func TestRewriter_MemoisesRepeatedReferences(t *testing.T) { + svc := &stubFileService{} + w := NewRewriter(fixedResolver{svc: svc}, "TEST") + ctx := context.Background() + + ref := "resource://xifDo7NTSL300Lp1goVutw" + first := w.String(ctx, "![a]("+ref+")") + second := w.String(ctx, "![b]("+ref+")") + + assert.Equal(t, 1, svc.calls, "the same reference must resolve once per Rewriter") + assert.Equal(t, "https://cdn.example.com/"+ref, first[5:len(first)-1]) + assert.Contains(t, second, "https://cdn.example.com/"+ref) +} + +func TestRewriter_DisabledWithoutResolver(t *testing.T) { + w := NewRewriter(nil, "TEST") + in := "![img](resource://xifDo7NTSL300Lp1goVutw)" + assert.False(t, w.Enabled()) + assert.Equal(t, in, w.String(context.Background(), in)) + assert.Equal(t, in, w.Ref(context.Background(), in)) +} + +// Ref handles a bare reference such as MessageImage.URL, and must not touch a +// value that is not a reference at all. +func TestRewriter_Ref(t *testing.T) { + w := NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST") + ctx := context.Background() + + assert.Equal(t, "https://cdn.example.com/x.png", + w.Ref(ctx, "resource://xifDo7NTSL300Lp1goVutw")) + assert.Equal(t, "", w.Ref(ctx, "")) + assert.Equal(t, "data:image/png;base64,AAAA", w.Ref(ctx, "data:image/png;base64,AAAA")) +} + +func TestIsHTTPURL(t *testing.T) { + for _, s := range []string{"http://a", "https://a", "HTTP://a", "HTTPS://a"} { + assert.True(t, IsHTTPURL(s), s) + } + for _, s := range []string{"", "ftp://a", "resource://abc", "local://1/a.png", "http:/"} { + assert.False(t, IsHTTPURL(s), s) + } +} + +func TestParseMode(t *testing.T) { + tests := []struct { + in string + want Mode + wantErr bool + }{ + {"", ModeHandle, false}, + {"handle", ModeHandle, false}, + {"public", ModePublic, false}, + {" PUBLIC ", ModePublic, false}, + {"true", ModeHandle, true}, + {"signed", ModeHandle, true}, + } + for _, tt := range tests { + got, err := ParseMode(tt.in) + if tt.wantErr { + require.Error(t, err, "ParseMode(%q)", tt.in) + } else { + require.NoError(t, err, "ParseMode(%q)", tt.in) + } + assert.Equal(t, tt.want, got, "ParseMode(%q)", tt.in) + } +} diff --git a/internal/storageurl/stream.go b/internal/storageurl/stream.go new file mode 100644 index 00000000..0eec1454 --- /dev/null +++ b/internal/storageurl/stream.go @@ -0,0 +1,155 @@ +package storageurl + +import ( + "context" + "regexp" + "strings" + "sync" +) + +// ── Incomplete-reference detection ── +// +// Content is delivered to clients in chunks (SSE answer deltas, or the IM +// channel's 300ms flush batches). A storage reference may be split across two +// chunks, so a rewrite that only sees one chunk would leave a broken fragment. +// These helpers locate an incomplete pattern at the tail of a chunk so the +// caller can hold it back until the next chunk completes it. + +// incompleteRefSuffixRe matches a storage reference that reaches the end of the +// string — it may continue in the next chunk. +var incompleteRefSuffixRe = regexp.MustCompile( + `\b(?:resource|storage|local|minio|s3|cos|tos|oss|obs|ks3)://[^\s)\]>"]*$`, +) + +// FindIncompleteRef returns the byte offset of a potentially truncated storage +// reference at the tail of s, or -1 if none. +func FindIncompleteRef(s string) int { + loc := incompleteRefSuffixRe.FindStringIndex(s) + if loc == nil { + return -1 + } + return loc[0] +} + +// incompleteMarkdownImageSuffixRe matches a Markdown image whose destination URL +// (the parenthesized part) is not yet closed — e.g. "![alt](minio://part" or +// "![alt](". Holding back only from "minio://" would flush "![alt](" to the +// client and break the image once the URL arrives in the next chunk. +var incompleteMarkdownImageSuffixRe = regexp.MustCompile(`!\[[^\]]*\]\([^)]*$`) + +// FindIncompleteMarkdownImage returns the byte offset of an unclosed +// `![alt](url` suffix at the end of s, or -1 if none. +func FindIncompleteMarkdownImage(s string) int { + // Prefer pairing a trailing reference fragment with the nearest preceding + // `![…](` so alt text may itself contain ']' (e.g. `![a[b]](minio://part`). + if urlIdx := FindIncompleteRef(s); urlIdx >= 0 { + if imgIdx := strings.LastIndex(s[:urlIdx], "!["); imgIdx >= 0 { + if strings.Contains(s[imgIdx:urlIdx], "](") { + return imgIdx + } + } + } + loc := incompleteMarkdownImageSuffixRe.FindStringIndex(s) + if loc == nil { + return -1 + } + return loc[0] +} + +// HoldbackCutoff returns the offset at which chunk stops being safe to flush, +// or len(chunk) when the whole chunk can be emitted. +func HoldbackCutoff(chunk string) int { + cutoff := len(chunk) + if idx := FindIncompleteMarkdownImage(chunk); idx >= 0 && idx < cutoff { + return idx + } + if idx := FindIncompleteRef(chunk); idx >= 0 && idx < cutoff { + return idx + } + return cutoff +} + +// maxHeldBytes bounds the per-key holdback buffer. A storage reference plus its +// Markdown alt text is far shorter than this; the cap only stops a pathological +// stream (for example an unclosed "![" that never terminates) from buffering an +// entire answer. +const maxHeldBytes = 4096 + +// StreamRewriter rewrites storage references in a stream of content deltas. +// +// Each logical stream is identified by a key (WeKnora uses the SSE event id, the +// same key clients accumulate on). Push returns only the prefix that is safe to +// emit now, retaining any tail that may be an incomplete reference until the +// next Push for that key. +// +// Safe for concurrent use. +type StreamRewriter struct { + rewriter *Rewriter + + mu sync.Mutex + held map[string]string +} + +// NewStreamRewriter wraps rewriter with per-stream holdback state. +func NewStreamRewriter(rewriter *Rewriter) *StreamRewriter { + return &StreamRewriter{rewriter: rewriter, held: make(map[string]string)} +} + +// Enabled reports whether this StreamRewriter can rewrite anything. +func (s *StreamRewriter) Enabled() bool { + return s != nil && s.rewriter.Enabled() +} + +// Push feeds the next chunk of the stream identified by key and returns the +// rewritten content that is ready to emit. Set flush on the stream's terminal +// chunk to release any held tail. +func (s *StreamRewriter) Push(ctx context.Context, key, chunk string, flush bool) string { + if !s.Enabled() { + return chunk + } + + s.mu.Lock() + pending := s.held[key] + chunk + cutoff := len(pending) + if !flush { + cutoff = HoldbackCutoff(pending) + // Never buffer without bound: release the excess even though it may + // contain a partial reference, which is what an un-rewritten stream + // would have shown anyway. + if len(pending)-cutoff > maxHeldBytes { + cutoff = len(pending) - maxHeldBytes + } + } + emit := pending[:cutoff] + if remainder := pending[cutoff:]; remainder == "" { + delete(s.held, key) + } else { + s.held[key] = remainder + } + s.mu.Unlock() + + return s.rewriter.String(ctx, emit) +} + +// FlushAll releases every held tail, rewritten, keyed by stream. Callers use it +// when a stream ends without a terminal chunk (for example a client +// disconnect) so buffered content is not silently dropped. +func (s *StreamRewriter) FlushAll(ctx context.Context) map[string]string { + if !s.Enabled() { + return nil + } + s.mu.Lock() + if len(s.held) == 0 { + s.mu.Unlock() + return nil + } + pending := s.held + s.held = make(map[string]string) + s.mu.Unlock() + + out := make(map[string]string, len(pending)) + for key, content := range pending { + out[key] = s.rewriter.String(ctx, content) + } + return out +} diff --git a/internal/storageurl/stream_test.go b/internal/storageurl/stream_test.go new file mode 100644 index 00000000..7ca7552f --- /dev/null +++ b/internal/storageurl/stream_test.go @@ -0,0 +1,179 @@ +package storageurl + +import ( + "context" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestFindIncompleteRef(t *testing.T) { + tests := []struct { + name string + in string + want int // expected return; -1 means no match expected + }{ + { + "complete URL terminated by )", + "![img](local://1/abc/img.png)", + // The URL `local://1/abc/img.png` ends with `)` which is a terminator, + // but the regex [^\s)\]>"]* matches up to `)` — the `)` is NOT included. + // So the URL portion is `local://1/abc/img.png` and `)` terminates it. + // The match does NOT reach end of string → should return -1. + -1, + }, + { + "complete URL terminated by space", + "text local://1/abc/img.png more text", + -1, + }, + { + "truncated URL at end", + "text ![img](local://1/abc/im", + 12, // starts at `l` in `local://` + }, + { + "just scheme at end", + "text minio://", + 5, + }, + { + "partial scoped URL at end", + "text storage://backend-a/co", + 5, + }, + { + "no storage URL", + "just plain text http://example.com", + -1, + }, + { + "URL at very end", + "local://1/img.png", + 0, + }, + { + "truncated resource handle at end", + "see ![img](resource://xifDo7NTSL", + 11, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, FindIncompleteRef(tt.in), "FindIncompleteRef(%q)", tt.in) + }) + } +} + +func TestFindIncompleteMarkdownImage(t *testing.T) { + tests := []struct { + name string + in string + want int + }{ + {"complete image", "![img](local://1/a.png)", -1}, + {"complete then text", "![img](local://1/a.png) trailing", -1}, + {"truncated provider URL in image", `![知识助理"知识库"管理视图界面](minio://wizard-test/10000/exports/c91cf852`, 0}, + {"open paren only", "text ![alt](", 5}, + {"bare provider suffix without markdown", "text minio://wizard-test/10000/exp", -1}, + {"two images complete", "![a](local://1/a.png) ![b](local://1/b.png)", -1}, + {"first complete second incomplete", "![a](local://1/a.png) ![b](minio://part", 22}, + {"bracket inside alt text", "![a[b]](minio://wizard-test/10000/part", 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, FindIncompleteMarkdownImage(tt.in), "FindIncompleteMarkdownImage(%q)", tt.in) + }) + } +} + +func TestHoldbackCutoff(t *testing.T) { + tests := []struct { + name string + in string + want int // -1 means "expect len(in)", i.e. no holdback + }{ + {"no holdback needed", "plain text with complete ![img](local://1/img.png) content", -1}, + {"truncated URL inside markdown image", "text ![img](local://1/abc/im", 5}, + {"bare truncated reference", "text local://1/abc/im", 5}, + {"unopened image destination", "prefix ![alt](", 7}, + {"empty chunk", "", -1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + want := tt.want + if want == -1 { + want = len(tt.in) + } + assert.Equal(t, want, HoldbackCutoff(tt.in), "HoldbackCutoff(%q)", tt.in) + }) + } +} + +// A reference split across two deltas must be held back and rewritten once +// complete, never emitted as a broken fragment. +func TestStreamRewriter_HoldsSplitReference(t *testing.T) { + sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) + ctx := context.Background() + + first := sr.Push(ctx, "answer-1", "here it is: ![img](resource://xifDo7", false) + assert.Equal(t, "here it is: ", first, "the incomplete image must be held back") + + second := sr.Push(ctx, "answer-1", "NTSL300Lp1goVutw) done", false) + assert.Equal(t, "![img](https://cdn.example.com/x.png) done", second) + + assert.Empty(t, sr.Push(ctx, "answer-1", "", true)) + assert.Empty(t, sr.FlushAll(ctx), "nothing should remain held") +} + +// Streams are keyed independently so interleaved events do not corrupt each +// other's holdback buffers. +func TestStreamRewriter_KeysAreIndependent(t *testing.T) { + sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) + ctx := context.Background() + + assert.Empty(t, sr.Push(ctx, "a", "![x](resource://aaaa", false)) + assert.Equal(t, "plain b", sr.Push(ctx, "b", "plain b", false)) + assert.Equal(t, + "![x](https://cdn.example.com/x.png)", + sr.Push(ctx, "a", "bbbbccccdddddd)", false), + ) +} + +// A stream that ends without a terminal chunk must not silently drop the tail. +func TestStreamRewriter_FlushAllReleasesHeldTail(t *testing.T) { + sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) + ctx := context.Background() + + assert.Equal(t, "tail ", sr.Push(ctx, "answer-1", "tail ![img](resource://partial", false)) + assert.Equal(t, + map[string]string{"answer-1": "![img](https://cdn.example.com/x.png"}, + sr.FlushAll(ctx), + "the held tail must still reach the client, rewritten where possible", + ) +} + +// Holdback must be bounded so a stream that never closes a Markdown image +// cannot buffer the whole answer. +func TestStreamRewriter_HoldbackIsBounded(t *testing.T) { + sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) + ctx := context.Background() + + var emitted strings.Builder + emitted.WriteString(sr.Push(ctx, "answer-1", "![never closed](", false)) + for i := 0; i < 20; i++ { + emitted.WriteString(sr.Push(ctx, "answer-1", strings.Repeat("x", 1024), false)) + } + assert.Greater(t, emitted.Len(), 0, "bounded holdback must release the excess") + assert.LessOrEqual(t, len(sr.held["answer-1"]), maxHeldBytes) +} + +// A disabled rewriter is a pass-through: the default API mode must not add +// latency or buffering. +func TestStreamRewriter_DisabledIsPassThrough(t *testing.T) { + sr := NewStreamRewriter(NewRewriter(nil, "TEST")) + in := "![img](resource://xifDo7" + assert.Equal(t, in, sr.Push(context.Background(), "answer-1", in, false)) + assert.False(t, sr.Enabled()) +}