Skip to content

Go: add more commands and GCS supports - #16741

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix529
Jul 8, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix529

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

  1. GCS supports
  2. More commands
RAGFlow(admin)> ping store;
SUCCESS
RAGFlow(admin)> ping engine;
SUCCESS
RAGFlow(admin)> ping cache;
SUCCESS

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 8, 2026
@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a GCS storage backend implementing the Storage interface (extended with ListObjects and Close), wires GCS config through environment/file loading and the storage factory, adds admin/CLI ping commands for store/cache/engine plus a bucket-listing command, makes startup storage/MQ init non-fatal, and includes an ES TLS change, a NATS fix, and dependency bumps.

Changes

Storage lifecycle, GCS backend, and admin tooling

Layer / File(s) Summary
Storage interface contract additions
internal/storage/types.go
Storage interface gains ListObjects(bucket, ...tenantID) ([]string, error) and Close() error.
Backend implementations of ListObjects/Close
internal/storage/memory.go, internal/storage/minio.go, internal/storage/oss.go, internal/storage/s3.go, internal/service/chunk/chunk_test.go, internal/service/document_test.go, internal/service/file_test.go
Memory, Minio, OSS, and S3 storage backends implement ListObjects and Close; test doubles (chunkImageStorage, fakeUploadStorage, fakeStorage) are updated with matching stub methods.
GCS storage backend implementation
internal/storage/gcs.go
New GCSStorage type implements Put, Get, Remove, ObjExist, ListObjects, GetPresignedURL, BucketExists, RemoveBucket, Copy, Move, Health, and Close against a GCS client.
GCS config wiring and startup lifecycle
internal/server/config.go, internal/storage/storage_factory.go, conf/service_conf.yaml, docker/service_conf.yaml.template, go.mod, cmd/ragflow_server.go
Adds GCSConfig/StorageGCS, environment and config-file parsing for gcs, StorageFactory.initGCS, exported CloseStorage(), GCS config templates, cloud.google.com/go/storage dependency, and changes server startup to log storage/MQ init failures non-fatally while deferring CloseStorage().
Admin ping endpoints
internal/admin/handler.go, internal/admin/router.go
New PingStore, PingCache, PingEngine handlers and /store, /cache, /engine admin routes for health checks.
CLI ping/list-bucket commands
internal/cli/admin_command.go, internal/cli/admin_parser.go, internal/cli/lexer.go, internal/cli/types.go, internal/cli/cli_http.go, internal/cli/common_command.go
Adds CLI ping commands for store/engine/mq/cache, AdminListBucketObjects, parser/lexer support for ENGINE/CACHE tokens, dispatch wiring, and renames PingByCommand to PingServerByCommand.
Unrelated ES/NATS/dependency changes
internal/engine/elasticsearch/client.go, internal/engine/nats/nats.go, go.mod
Elasticsearch client sets InsecureSkipVerify: true; NATS ShowMessageQueue skips consumer-metric population instead of erroring on lookup failure; numerous indirect go.mod dependencies bumped.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • infiniflow/ragflow#15327: Both PRs modify startup initialization of the message-queue engine to log/continue on failure rather than aborting the process.
  • infiniflow/ragflow#16213: Both PRs modify admin CLI "PING" command parsing/dispatch in internal/cli/admin_parser.go and internal/cli/cli_http.go.

Poem

A rabbit hops through clouds of storage, GCS,
Pinging store and cache with joyful ease,
New tokens click, ENGINE and CACHE in tow,
CloseStorage waves goodbye before we go. 🐇☁️
Bucket by bucket, objects line up neat—
A tidy warren for every byte we keep!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is clearly related to the main changes: added commands and GCS support.
Description check ✅ Passed The description includes the required Summary section and briefly states the PR's purpose.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 8, 2026 08:32
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 8, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 8, 2026 08:32
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 8, 2026 08:32
Signed-off-by: Jin Hai <[email protected]>
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 8, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 8, 2026 08:44
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 8, 2026 08:44

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

♻️ Duplicate comments (1)
internal/storage/s3.go (1)

267-286: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

ListObjects silently truncates results beyond 1000 objects.

Same issue as OSSStorage.ListObjects — ListObjectsV2 caps at 1000 keys per response. Without a paginator, large buckets return incomplete results silently. See the paginator-based fix proposed on oss.go.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/s3.go` around lines 267 - 286, `S3Storage.ListObjects`
currently calls `ListObjectsV2` only once, so it will silently return at most
1000 keys for large buckets. Update this method to use the AWS paginator for
`ListObjectsV2` and accumulate keys across all pages before returning, matching
the paginator-based approach used in `OSSStorage.ListObjects`. Keep the existing
`bucket` and `tenantID` handling intact and ensure all objects from every page
are appended to the result slice.
🧹 Nitpick comments (5)
internal/engine/nats/nats.go (1)

126-136: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider setting default values for consumer metrics when consumer lookup fails.

When n.stream.Consumer() returns an error (e.g., consumer doesn't exist yet), the four consumer metric keys are absent from the result map. The admin API returns HTTP 200 with no indication that consumer info is missing. Setting these to "0" or "N/A" in the else branch would make the response more predictable for callers and UI consumers.

♻️ Proposed improvement: populate default values
 	consumer, err := n.stream.Consumer(ctx, "RAGFLOW_CONSUMER")
 	if err == nil {
 		var consumerInfo *jetstream.ConsumerInfo
 		consumerInfo, err = consumer.Info(ctx)
 		if err != nil {
 			return nil, fmt.Errorf("failed to get consumer info: %w", err)
 		}
 		result["pending_count"] = strconv.FormatUint(consumerInfo.NumPending, 10)
 		result["waiting_count"] = strconv.Itoa(consumerInfo.NumWaiting)
 		result["ack_pending_count"] = strconv.Itoa(consumerInfo.NumAckPending)
 		result["redelivered_count"] = strconv.Itoa(consumerInfo.NumRedelivered)
+	} else {
+		result["pending_count"] = "0"
+		result["waiting_count"] = "0"
+		result["ack_pending_count"] = "0"
+		result["redelivered_count"] = "0"
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/nats/nats.go` around lines 126 - 136, The consumer metrics
block in the NATS status logic only populates values after a successful consumer
lookup, so when n.stream.Consumer() fails the result map is missing those keys.
Update the consumer info handling in the relevant function in nats.go to set
default values for pending_count, waiting_count, ack_pending_count, and
redelivered_count in the error path or else branch, using a consistent fallback
like "0" or "N/A" so callers always receive the same fields.
internal/admin/handler.go (1)

1279-1289: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Use request context and consistent error code in PingEngine.

Two issues: (1) context.Background() ignores client cancellation — prefer c.Request.Context() so the ping is cancelled if the client disconnects. (2) Hardcoded 500 is inconsistent with PingStore/PingCache which use int(common.CodeServerError).

♻️ Proposed fixes for context and error code
 func (h *Handler) PingEngine(c *gin.Context) {
 	docEngine := engine.Get()
 	if docEngine == nil {
 		common.ErrorWithCode(c, int(common.CodeServerError), "engine not initialized")
 		return
 	}
-	ctx := context.Background()
+	ctx := c.Request.Context()
 	if err := docEngine.Ping(ctx); err != nil {
-		common.ErrorWithCode(c, 500, err.Error())
+		common.ErrorWithCode(c, int(common.CodeServerError), "engine health check failed")
 		return
 	}
 	common.SuccessNoMessage(c, "SUCCESS")
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/handler.go` around lines 1279 - 1289, PingEngine currently
ignores request cancellation and uses a hardcoded error status. Update the
PingEngine handler to use c.Request.Context() instead of context.Background()
when calling docEngine.Ping, and replace the literal 500 in common.ErrorWithCode
with int(common.CodeServerError) to match PingStore and PingCache. Keep the fix
localized to PingEngine and preserve the existing success response behavior.
internal/storage/storage_factory.go (1)

164-196: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Create method is missing a StorageGCS case.

Create handles StorageMinio, StorageAWSS3, and StorageOSS, but not StorageGCS. Calling Create(StorageGCS) falls through to the default error. Add a GCS case for consistency with the other backends.

♻️ Proposed addition
 	case StorageOSS:
 		if f.config.OSS != nil {
 			storage, err = NewOSSStorage(f.config.OSS)
 		} else {
 			return nil, fmt.Errorf("OSS config not available")
 		}
+	case StorageGCS:
+		if f.config.GCS != nil {
+			storage, err = NewGCSStorage(f.config.GCS)
+		} else {
+			return nil, fmt.Errorf("GCS config not available")
+		}
 	default:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/storage_factory.go` around lines 164 - 196, The Create
method in StorageFactory is missing support for StorageGCS, so requests for that
backend currently hit the unsupported default path. Add a StorageGCS case in the
switch alongside StorageMinio, StorageAWSS3, and StorageOSS, following the same
pattern of checking the corresponding config on f.config and constructing the
backend with a matching NewGCSStorage helper. Keep the existing error handling
and return flow in Create consistent with the other storage types.
internal/storage/gcs.go (1)

224-248: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Copy silently swallows errors — Move loses all error context when Copy fails.

When Copy returns false, Move returns false without any log. No error information reaches the caller or logs, making production data-movement failures very difficult to diagnose.

🔊 Proposed fix: log the copy error before returning false
 func (m *GCSStorage) Copy(srcBucket, srcObject, destBucket, destObject string) bool {
 	ctx := context.Background()
 	src := m.client.Bucket(srcBucket).Object(srcObject)
 	dst := m.client.Bucket(destBucket).Object(destObject)
 	copier := dst.CopierFrom(src)
 	_, err := copier.Run(ctx)
 	if err != nil {
+		common.Warn("Failed to copy object",
+			zap.String("srcBucket", srcBucket),
+			zap.String("srcObject", srcObject),
+			zap.String("destBucket", destBucket),
+			zap.String("destObject", destObject),
+			zap.Error(err))
 		return false
 	}
 	return true
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/gcs.go` around lines 224 - 248, `GCSStorage.Copy` is
swallowing the underlying copy failure, so `GCSStorage.Move` has no error
context when copy fails. Update `Copy` to log the `copier.Run(ctx)` error with
bucket/object details before returning false, and keep `Move` using `Copy` so
failures surface in logs; use the existing `Copy`, `Move`, and
`common.Warn`/`zap.Error` symbols to locate the fix.
internal/storage/oss.go (1)

259-278: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

ListObjects is identical to S3Storage.ListObjects — extract shared logic.

Both OSSStorage.ListObjects and S3Storage.ListObjects are line-for-line identical. Since both wrap the same s3.Client, consider extracting a shared helper (e.g., in a common file or embedded struct) to eliminate the duplication and ensure pagination fixes apply to both backends simultaneously.

♻️ Suggested shared helper
// internal/storage/s3_common.go
func listObjectsV2(client *s3.Client, bucket string) ([]string, error) {
	ctx := context.Background()
	var objects []string
	paginator := s3.NewListObjectsV2Paginator(client, &s3.ListObjectsV2Input{
		Bucket: aws.String(bucket),
	})
	for paginator.HasMorePages() {
		result, err := paginator.NextPage(ctx)
		if err != nil {
			return nil, err
		}
		for _, obj := range result.Contents {
			objects = append(objects, *obj.Key)
		}
	}
	return objects, nil
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/oss.go` around lines 259 - 278, OSSStorage.ListObjects is
duplicated in S3Storage.ListObjects, so move the shared listing logic into a
common helper or embedded method (for example a shared listObjectsV2 helper used
by both storage types). Update OSSStorage.ListObjects to delegate to that shared
function so pagination and future fixes are applied consistently across both
backends, and use the existing s3.Client-based implementation symbols to keep
the refactor easy to locate.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/ragflow_server.go`:
- Around line 357-363: The startup flow in the server initialization currently
treats storage and message queue setup as non-fatal for every mode, which can
leave `api`, `ingestor`, and `syncer` running with nil dependencies. Update the
initialization around `storage.InitStorageFactory()` and
`engine.InitMessageQueueEngine()` so the relaxed error handling is scoped to
admin mode only, or otherwise ensure all downstream storage/MQ consumers are
nil-safe. Also guard the unconditional `defer storage.CloseStorage()` in this
startup path so it is only registered after successful storage initialization,
or relies on a nil-safe `CloseStorage()` implementation.

In `@internal/admin/handler.go`:
- Around line 1270-1289: Add nil guards in PingCache and PingEngine before
calling methods on redis.Get() and engine.Get(), since startup can now leave
these dependencies unset. In PingCache, check the Redis client returned by
redis.Get() for nil before calling Health(), and return the same server error
path if it is unavailable; in PingEngine, check the DocEngine from engine.Get()
for nil before creating the context or calling Ping(), and fail gracefully with
common.ErrorWithCode. Use PingStore’s existing nil-check pattern as the
reference for the Handler methods.

In `@internal/cli/admin_command.go`:
- Around line 2677-2696: The AdminListBucketObjects command builds the admin
objects endpoint by inserting bucketID directly into the path, so special
characters can break routing; update the AdminListBucketObjects method to
path-escape bucketID before formatting the endpoint, and ensure the admin router
in internal/admin/router.go registers the matching
/admin/bucket/:bucket_id/objects route if this command is meant to be supported.

In `@internal/cli/admin_parser.go`:
- Around line 93-94: The default error returned from the PING parsing branch
still mentions only a semicolon, which is now misleading because the parser also
accepts STORE, ENGINE, MQ, and CACHE. Update the error text in the PING handling
logic in the admin parser to describe the valid tokens after PING, so cases like
PING FOO produce an accurate message.

In `@internal/engine/elasticsearch/client.go`:
- Line 63: The Elasticsearch TLS config is hardcoding certificate verification
off, which makes every connection insecure; update the client setup in the
Elasticsearch client initializer to read a configurable flag from
ElasticsearchConfig instead of always setting TLSClientConfig with
InsecureSkipVerify enabled. Add or wire an InsecureSkipVerify option through
ElasticsearchConfig, and apply it in the code path used by both engine.Init and
getESClusterStats so the default remains secure and skip-verify is only enabled
intentionally for dev/self-signed setups.

In `@internal/storage/gcs.go`:
- Around line 52-69: The GCS client initialization path in GCSStorage.connect is
terminating the process via common.Fatal instead of returning the
storage.NewClient error to the caller. Update connect() to return the error on
client creation failure so NewGCSStorage and storage_factory can propagate it,
and adjust reconnect() to handle the returned error without exiting; if
reconnect() remains in use, ensure any existing m.client is closed before
assigning the new client.
- Around line 159-173: In GetPresignedURL on GCSStorage, the signed URL is being
generated with the wrong object identifier and an incorrect expiration
calculation. Update the BucketHandle.SignedURL call to use the object name
directly from fnm instead of composing bucket/fnm, and change the
SignedURLOptions Expires value to use time.Now().Add(expires) so the provided
time.Duration is applied as-is.

In `@internal/storage/oss.go`:
- Around line 259-278: ListObjects currently calls OSS ListObjectsV2 only once,
so it returns only the first page of keys for large buckets. Update
OSSStorage.ListObjects to use a paginator over the ListObjectsV2 API and append
keys from each page until exhausted, keeping the existing bucket/tenantID
signature and ensuring all object keys are returned.

In `@internal/storage/s3.go`:
- Around line 267-272: `S3Storage` is not using the configured defaults because
`NewS3Storage` leaves `s.bucket` and `s.prefixPath` unset, so
`resolveBucketAndPath` never applies them. Update `NewS3Storage` to wire
`server.S3Config.Bucket` and `server.S3Config.PrefixPath` into the `S3Storage`
instance, and verify the S3 helpers that depend on `resolveBucketAndPath`
(including `ListObjects`) now pick up the default bucket/prefix when callers do
not pass overrides.

In `@internal/storage/storage_factory.go`:
- Around line 132-147: initGCS currently calls NewGCSStorage without validating
gcsConfig, so add a nil guard at the start of StorageFactory.initGCS to return a
clear error when no GCS config is present. Mirror the existing nil-check pattern
used in StorageFactory.Create before constructing storage, and keep the rest of
the initialization path unchanged for the valid-config case.
- Around line 63-70: CloseStorage() can panic when storage initialization failed
and factory.storage was never set, so add a nil guard before calling Close() in
CloseStorage and return nil (or the appropriate no-op result) when there is no
storage instance. Use the GetStorageFactory() and factory.storage access in
internal/storage/storage_factory.go to locate the fix, and keep the mutex
lock/unlock behavior intact while making shutdown safe after a failed init path.

---

Duplicate comments:
In `@internal/storage/s3.go`:
- Around line 267-286: `S3Storage.ListObjects` currently calls `ListObjectsV2`
only once, so it will silently return at most 1000 keys for large buckets.
Update this method to use the AWS paginator for `ListObjectsV2` and accumulate
keys across all pages before returning, matching the paginator-based approach
used in `OSSStorage.ListObjects`. Keep the existing `bucket` and `tenantID`
handling intact and ensure all objects from every page are appended to the
result slice.

---

Nitpick comments:
In `@internal/admin/handler.go`:
- Around line 1279-1289: PingEngine currently ignores request cancellation and
uses a hardcoded error status. Update the PingEngine handler to use
c.Request.Context() instead of context.Background() when calling docEngine.Ping,
and replace the literal 500 in common.ErrorWithCode with
int(common.CodeServerError) to match PingStore and PingCache. Keep the fix
localized to PingEngine and preserve the existing success response behavior.

In `@internal/engine/nats/nats.go`:
- Around line 126-136: The consumer metrics block in the NATS status logic only
populates values after a successful consumer lookup, so when n.stream.Consumer()
fails the result map is missing those keys. Update the consumer info handling in
the relevant function in nats.go to set default values for pending_count,
waiting_count, ack_pending_count, and redelivered_count in the error path or
else branch, using a consistent fallback like "0" or "N/A" so callers always
receive the same fields.

In `@internal/storage/gcs.go`:
- Around line 224-248: `GCSStorage.Copy` is swallowing the underlying copy
failure, so `GCSStorage.Move` has no error context when copy fails. Update
`Copy` to log the `copier.Run(ctx)` error with bucket/object details before
returning false, and keep `Move` using `Copy` so failures surface in logs; use
the existing `Copy`, `Move`, and `common.Warn`/`zap.Error` symbols to locate the
fix.

In `@internal/storage/oss.go`:
- Around line 259-278: OSSStorage.ListObjects is duplicated in
S3Storage.ListObjects, so move the shared listing logic into a common helper or
embedded method (for example a shared listObjectsV2 helper used by both storage
types). Update OSSStorage.ListObjects to delegate to that shared function so
pagination and future fixes are applied consistently across both backends, and
use the existing s3.Client-based implementation symbols to keep the refactor
easy to locate.

In `@internal/storage/storage_factory.go`:
- Around line 164-196: The Create method in StorageFactory is missing support
for StorageGCS, so requests for that backend currently hit the unsupported
default path. Add a StorageGCS case in the switch alongside StorageMinio,
StorageAWSS3, and StorageOSS, following the same pattern of checking the
corresponding config on f.config and constructing the backend with a matching
NewGCSStorage helper. Keep the existing error handling and return flow in Create
consistent with the other storage types.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fdd8a22c-d497-45e2-8c01-496b8c00ce31

📥 Commits

Reviewing files that changed from the base of the PR and between 5baf408 and 18bc086.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (25)
  • cmd/ragflow_server.go
  • conf/service_conf.yaml
  • docker/service_conf.yaml.template
  • go.mod
  • internal/admin/handler.go
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/cli/common_command.go
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/engine/elasticsearch/client.go
  • internal/engine/nats/nats.go
  • internal/server/config.go
  • internal/service/chunk/chunk_test.go
  • internal/service/document_test.go
  • internal/service/file_test.go
  • internal/storage/gcs.go
  • internal/storage/memory.go
  • internal/storage/minio.go
  • internal/storage/oss.go
  • internal/storage/s3.go
  • internal/storage/storage_factory.go
  • internal/storage/types.go

Comment thread cmd/ragflow_server.go
Comment on lines 357 to +363
if err = storage.InitStorageFactory(); err != nil {
common.Fatal("Failed to initialize storage factory", zap.Error(err))
common.Error("Failed to initialize storage factory", err)
}
defer storage.CloseStorage()

if err = engine.InitMessageQueueEngine(config.TaskExecutor.MessageQueueType); err != nil {
common.Fatal("Failed to initialize message queue engine", zap.Error(err))
common.Error("Failed to initialize message queue engine", err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Non-fatal storage/MQ init applies to all server modes, risking runtime panics.

Making storage and MQ init errors non-fatal allows the admin server to start for ping diagnostics, but this also applies to api, ingestor, and syncer modes. Those modes will nil-panic on any storage or MQ operation. Consider scoping the non-fatal behavior to admin mode only, or ensure all storage/MQ consumers handle nil safely.

Additionally, defer storage.CloseStorage() (line 360) is registered unconditionally — if init fails, this will panic on shutdown. See the CloseStorage() nil-guard fix in internal/storage/storage_factory.go.

💡 Proposed mode-scoped approach
 if err = storage.InitStorageFactory(); err != nil {
-	common.Error("Failed to initialize storage factory", err)
+	if *arguments.mode == "admin" {
+		common.Error("Failed to initialize storage factory", err)
+	} else {
+		common.Fatal("Failed to initialize storage factory", zap.Error(err))
+	}
 }
-defer storage.CloseStorage()
+if factory := storage.GetStorageFactory(); factory.GetStorage() != nil {
+	defer storage.CloseStorage()
+}

 if err = engine.InitMessageQueueEngine(config.TaskExecutor.MessageQueueType); err != nil {
-	common.Error("Failed to initialize message queue engine", err)
+	if *arguments.mode == "admin" {
+		common.Error("Failed to initialize message queue engine", err)
+	} else {
+		common.Fatal("Failed to initialize message queue engine", zap.Error(err))
+	}
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err = storage.InitStorageFactory(); err != nil {
common.Fatal("Failed to initialize storage factory", zap.Error(err))
common.Error("Failed to initialize storage factory", err)
}
defer storage.CloseStorage()
if err = engine.InitMessageQueueEngine(config.TaskExecutor.MessageQueueType); err != nil {
common.Fatal("Failed to initialize message queue engine", zap.Error(err))
common.Error("Failed to initialize message queue engine", err)
if err = storage.InitStorageFactory(); err != nil {
if *arguments.mode == "admin" {
common.Error("Failed to initialize storage factory", err)
} else {
common.Fatal("Failed to initialize storage factory", zap.Error(err))
}
}
if factory := storage.GetStorageFactory(); factory.GetStorage() != nil {
defer storage.CloseStorage()
}
if err = engine.InitMessageQueueEngine(config.TaskExecutor.MessageQueueType); err != nil {
if *arguments.mode == "admin" {
common.Error("Failed to initialize message queue engine", err)
} else {
common.Fatal("Failed to initialize message queue engine", zap.Error(err))
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/ragflow_server.go` around lines 357 - 363, The startup flow in the server
initialization currently treats storage and message queue setup as non-fatal for
every mode, which can leave `api`, `ingestor`, and `syncer` running with nil
dependencies. Update the initialization around `storage.InitStorageFactory()`
and `engine.InitMessageQueueEngine()` so the relaxed error handling is scoped to
admin mode only, or otherwise ensure all downstream storage/MQ consumers are
nil-safe. Also guard the unconditional `defer storage.CloseStorage()` in this
startup path so it is only registered after successful storage initialization,
or relies on a nil-safe `CloseStorage()` implementation.

Comment thread internal/admin/handler.go
Comment on lines +1270 to +1289
func (h *Handler) PingCache(c *gin.Context) {
redisClient := redis.Get()
if redisClient.Health() {
common.SuccessNoMessage(c, "SUCCESS")
} else {
common.ErrorWithCode(c, int(common.CodeServerError), "cache health check failed")
}
}

func (h *Handler) PingEngine(c *gin.Context) {

docEngine := engine.Get()
ctx := context.Background()
if err := docEngine.Ping(ctx); err != nil {
common.ErrorWithCode(c, 500, err.Error())
return
}

common.SuccessNoMessage(c, "SUCCESS")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add nil checks in PingCache and PingEngine to prevent panics.

PingStore nil-checks storageImpl before calling Health(), but PingCache and PingEngine call methods on redis.Get() and engine.Get() without nil checks. Since this PR makes startup initialization non-fatal, these dependencies can be nil at runtime. RedisClient.Health() dereferences r.client (panics if r is nil), and calling Ping() on a nil DocEngine interface also panics.

🛡️ Proposed nil guard fixes
 func (h *Handler) PingCache(c *gin.Context) {
 	redisClient := redis.Get()
+	if redisClient == nil {
+		common.ErrorWithCode(c, int(common.CodeServerError), "cache not initialized")
+		return
+	}
 	if redisClient.Health() {
 		common.SuccessNoMessage(c, "SUCCESS")
 	} else {
 		common.ErrorWithCode(c, int(common.CodeServerError), "cache health check failed")
 	}
 }

 func (h *Handler) PingEngine(c *gin.Context) {
 	docEngine := engine.Get()
+	if docEngine == nil {
+		common.ErrorWithCode(c, int(common.CodeServerError), "engine not initialized")
+		return
+	}
 	ctx := context.Background()
 	if err := docEngine.Ping(ctx); err != nil {
 		common.ErrorWithCode(c, 500, err.Error())
 		return
 	}
 	common.SuccessNoMessage(c, "SUCCESS")
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (h *Handler) PingCache(c *gin.Context) {
redisClient := redis.Get()
if redisClient.Health() {
common.SuccessNoMessage(c, "SUCCESS")
} else {
common.ErrorWithCode(c, int(common.CodeServerError), "cache health check failed")
}
}
func (h *Handler) PingEngine(c *gin.Context) {
docEngine := engine.Get()
ctx := context.Background()
if err := docEngine.Ping(ctx); err != nil {
common.ErrorWithCode(c, 500, err.Error())
return
}
common.SuccessNoMessage(c, "SUCCESS")
}
func (h *Handler) PingCache(c *gin.Context) {
redisClient := redis.Get()
if redisClient == nil {
common.ErrorWithCode(c, int(common.CodeServerError), "cache not initialized")
return
}
if redisClient.Health() {
common.SuccessNoMessage(c, "SUCCESS")
} else {
common.ErrorWithCode(c, int(common.CodeServerError), "cache health check failed")
}
}
func (h *Handler) PingEngine(c *gin.Context) {
docEngine := engine.Get()
if docEngine == nil {
common.ErrorWithCode(c, int(common.CodeServerError), "engine not initialized")
return
}
ctx := context.Background()
if err := docEngine.Ping(ctx); err != nil {
common.ErrorWithCode(c, 500, err.Error())
return
}
common.SuccessNoMessage(c, "SUCCESS")
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/handler.go` around lines 1270 - 1289, Add nil guards in
PingCache and PingEngine before calling methods on redis.Get() and engine.Get(),
since startup can now leave these dependencies unset. In PingCache, check the
Redis client returned by redis.Get() for nil before calling Health(), and return
the same server error path if it is unavailable; in PingEngine, check the
DocEngine from engine.Get() for nil before creating the context or calling
Ping(), and fail gracefully with common.ErrorWithCode. Use PingStore’s existing
nil-check pattern as the reference for the Handler methods.

Comment on lines +2677 to +2696
func (c *CLI) AdminListBucketObjects(cmd *Command) (ResponseIf, error) {

if c.Config.CLIMode != AdminMode {
return nil, fmt.Errorf("this command is only allowed in ADMIN mode or already login")
}

bucketID, ok := cmd.Params["bucket_id"].(string)
if !ok {
return nil, fmt.Errorf("bucket_id not provided")
}

endPoint := fmt.Sprintf("/admin/bucket/%s/objects", bucketID)

resp, err := c.AdminServerClient.Request("GET", endPoint, "web", nil, nil)
if err != nil {
return nil, fmt.Errorf("failed to get bucket objects: %w", err)
}

return HandleCommonResponse(resp, fmt.Sprintf("get bucket objects"))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Search for bucket-related routes in the admin router and beyond.

rg -n 'bucket' --type go internal/admin/
rg -n 'bucket' --type go internal/ -g '!**/cli/**'

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the CLI method and admin router definitions.
rg -n "AdminListBucketObjects|/admin/bucket|bucket_id" internal/cli/admin_command.go internal/admin/router.go internal -g '!**/vendor/**'

# Show the relevant method and nearby route definitions with line numbers.
sed -n '2660,2710p' internal/cli/admin_command.go
printf '\n--- router ---\n'
sed -n '1,260p' internal/admin/router.go

Repository: infiniflow/ragflow

Length of output: 12736


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find any bucket-object route/handler and trace where bucket IDs come from.
rg -n 'bucket_id|/bucket/.*/objects|ListBucketObjects|objects"' internal -g '!**/vendor/**'

printf '\n--- admin client request implementation ---\n'
sed -n '1,220p' internal/cli/cli_http.go

printf '\n--- bucket id references ---\n'
rg -n 'bucketID|bucket_id' internal -g '!**/vendor/**'

Repository: infiniflow/ragflow

Length of output: 9750


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the admin client request path handling to see whether it escapes path segments.
rg -n "func \(.*\) Request\(" internal/cli -g '*.go'

# Show the implementation(s) around the Request method.
for f in $(rg -l "func \(.*\) Request\(" internal/cli -g '*.go'); do
  echo "--- $f ---"
  sed -n '1,260p' "$f"
done

Repository: infiniflow/ragflow

Length of output: 6949


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the exact Request implementation and any helpers that build URLs.
rg -n "func \(.*\) Request\(" internal/cli -g '*.go'
rg -n "PathEscape|QueryEscape|JoinPath|url\.Parse|http.NewRequest" internal/cli -g '*.go'

Repository: infiniflow/ragflow

Length of output: 2387


URL-encode bucketID and add the matching admin route bucketID is inserted directly into the path, so values containing /, ?, or # can break the request or hit the wrong endpoint. No matching /admin/bucket/:bucket_id/objects route is registered in internal/admin/router.go; use url.PathEscape(bucketID) and wire up the endpoint if this command should work.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/cli/admin_command.go` around lines 2677 - 2696, The
AdminListBucketObjects command builds the admin objects endpoint by inserting
bucketID directly into the path, so special characters can break routing; update
the AdminListBucketObjects method to path-escape bucketID before formatting the
endpoint, and ensure the admin router in internal/admin/router.go registers the
matching /admin/bucket/:bucket_id/objects route if this command is meant to be
supported.

Comment on lines +93 to +94
default:
return nil, fmt.Errorf("expected semicolon after PING")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Update error message to reflect valid tokens after PING.

The default case still says "expected semicolon after PING" but the function now also accepts STORE, ENGINE, MQ, and CACHE. Users who type e.g. PING FOO will see a misleading message.

✏️ Proposed fix for error message
 	default:
-		return nil, fmt.Errorf("expected semicolon after PING")
+		return nil, fmt.Errorf("expected STORE, ENGINE, MQ, CACHE, or semicolon after PING")
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
default:
return nil, fmt.Errorf("expected semicolon after PING")
default:
return nil, fmt.Errorf("expected STORE, ENGINE, MQ, CACHE, or semicolon after PING")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/cli/admin_parser.go` around lines 93 - 94, The default error
returned from the PING parsing branch still mentions only a semicolon, which is
now misleading because the parser also accepts STORE, ENGINE, MQ, and CACHE.
Update the error text in the PING handling logic in the admin parser to describe
the valid tokens after PING, so cases like PING FOO produce an accurate message.

Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: 30 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

InsecureSkipVerify: true is hardcoded unconditionally — critical security risk.

This disables TLS certificate verification for every Elasticsearch connection, exposing all traffic to man-in-the-middle attacks. This affects both the runtime engine (via engine.Init) and admin cluster-stats calls (via getESClusterStats).

Make this configurable via ElasticsearchConfig so it defaults to secure behavior and can be opted into only for development environments with self-signed certs.

🔒 Proposed fix: make TLS skip-verify configurable

Add a field to ElasticsearchConfig (e.g., InsecureSkipVerify bool) and use it here:

 		Transport: &http.Transport{
 			MaxIdleConnsPerHost:   10,
 			ResponseHeaderTimeout: 30 * time.Second,
-			TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},
+			TLSClientConfig:       &tls.Config{InsecureSkipVerify: esConfig.InsecureSkipVerify},
 		},

If the config struct cannot be modified in this PR, at minimum gate this behind an environment variable:

 		Transport: &http.Transport{
 			MaxIdleConnsPerHost:   10,
 			ResponseHeaderTimeout: 30 * time.Second,
-			TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},
+			TLSClientConfig: &tls.Config{
+				InsecureSkipVerify: os.Getenv("ES_INSECURE_SKIP_VERIFY") == "true",
+			},
 		},
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSClientConfig: &tls.Config{InsecureSkipVerify: esConfig.InsecureSkipVerify},
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 59-63: This http.Transport is configured with a tls.Config that sets InsecureSkipVerify: true, which disables TLS certificate verification for every request made through the resulting http.Client. The server's certificate chain and host name are not validated, exposing the connection to man-in-the-middle attacks. Remove InsecureSkipVerify (or set it to false) and supply a proper RootCAs pool if you need to trust custom certificates.
Context: http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: 30 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
Note: [CWE-295] Improper Certificate Validation.

(http-transport-tls-skip-verify-go)

🪛 OpenGrep (1.23.0)

[ERROR] 63-63: TLS certificate verification is disabled via InsecureSkipVerify. This allows man-in-the-middle attacks. Remove InsecureSkipVerify or set it to false.

(coderabbit.tls.go-insecure-skip-verify)


[ERROR] 63-63: TLS certificate verification is disabled via InsecureSkipVerify. This allows man-in-the-middle attacks. Remove InsecureSkipVerify or set it to false.

(coderabbit.tls.go-insecure-skip-verify)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/elasticsearch/client.go` at line 63, The Elasticsearch TLS
config is hardcoding certificate verification off, which makes every connection
insecure; update the client setup in the Elasticsearch client initializer to
read a configurable flag from ElasticsearchConfig instead of always setting
TLSClientConfig with InsecureSkipVerify enabled. Add or wire an
InsecureSkipVerify option through ElasticsearchConfig, and apply it in the code
path used by both engine.Init and getESClusterStats so the default remains
secure and skip-verify is only enabled intentionally for dev/self-signed setups.

Source: Linters/SAST tools

Comment thread internal/storage/gcs.go
Comment on lines +159 to +173
// GetPresignedURL generates a presigned URL for accessing an object
func (m *GCSStorage) GetPresignedURL(bucket, fnm string, expires time.Duration, tenantID ...string) (string, error) {

bucketObject := m.client.Bucket(bucket)
objectPath := fmt.Sprintf("%s/%s", bucket, fnm)
opts := &storage.SignedURLOptions{
Method: "GET",
Expires: time.Now().Add(expires * time.Second),
}
url, err := bucketObject.SignedURL(objectPath, opts)
if err != nil {
return "", err
}
return url, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify how other backends interpret the expires parameter in GetPresignedURL
rg -n 'GetPresignedURL' internal/storage/ --type=go -A5

Repository: infiniflow/ragflow

Length of output: 5953


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the GCS storage implementation and related interface/docs.
ast-grep outline internal/storage/gcs.go --view expanded
printf '\n--- types.go ---\n'
ast-grep outline internal/storage/types.go --view expanded
printf '\n--- gcs.go lines 145-190 ---\n'
sed -n '145,190p' internal/storage/gcs.go | cat -n
printf '\n--- types.go lines 70-90 ---\n'
sed -n '70,90p' internal/storage/types.go | cat -n

Repository: infiniflow/ragflow

Length of output: 4789


🌐 Web query:

Google Cloud Storage SignedURL object name path bucket object name expires time.Duration SignedURLOptions documentation

💡 Result:

In the Google Cloud Storage Go client library (cloud.google.com/go/storage), you can generate a signed URL using either the BucketHandle.SignedURL method or the package-level SignedURL function [1][2]. The function signature for generating a signed URL using a bucket handle is: func (b *BucketHandle) SignedURL(object string, opts *SignedURLOptions) (string, error) The parameters and key components are: - object: The name (path) of the object within the bucket [1][2]. - opts: A pointer to a SignedURLOptions struct that defines the configuration for the signed URL [1][2]. SignedURLOptions Configuration The SignedURLOptions struct is used to specify how the URL is signed and its constraints [3][4]. Key fields include: - Method: The HTTP verb (e.g., "GET", "PUT") that the signed URL is authorized to perform [3][4]. This field is required [1][2]. - Expires: A time.Time value indicating when the signed URL will expire [1][2]. This field is required [1][2]. - Scheme: The signing scheme, typically storage.SigningSchemeV4 [3][4]. - GoogleAccessID and PrivateKey: These fields are used to provide the credentials necessary for signing if they are not automatically detected from the client environment [1][2]. Example Usage import ( "context" "time" "cloud.google.com/go/storage") //... assume client is initialized opts:= &storage.SignedURLOptions{ Scheme: storage.SigningSchemeV4, Method: "GET", Expires: time.Now.Add(15 * time.Minute), } url, err:= client.Bucket("bucket-name").SignedURL("object-name", opts) // Handle error and use the url For more detailed information, consult the official Go client library documentation for the cloud.google.com/go/storage package [1][2].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect how GCSStorage handles bucket/object names elsewhere for consistency.
sed -n '1,145p' internal/storage/gcs.go | cat -n
printf '\n--- later methods ---\n'
sed -n '145,260p' internal/storage/gcs.go | cat -n

Repository: infiniflow/ragflow

Length of output: 7792


Use the object key directly and add the duration as-is

  • BucketHandle.SignedURL expects the object name, so bucket/fnm signs a different path than the object written by Put/Get.
  • expires is already a time.Duration; time.Now().Add(expires * time.Second) changes the units and can overflow. Use time.Now().Add(expires).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/gcs.go` around lines 159 - 173, In GetPresignedURL on
GCSStorage, the signed URL is being generated with the wrong object identifier
and an incorrect expiration calculation. Update the BucketHandle.SignedURL call
to use the object name directly from fnm instead of composing bucket/fnm, and
change the SignedURLOptions Expires value to use time.Now().Add(expires) so the
provided time.Duration is applied as-is.

Comment thread internal/storage/oss.go
Comment on lines +259 to +278
func (o *OSSStorage) ListObjects(bucket string, tenantID ...string) ([]string, error) {
ctx := context.Background()

listInput := &s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
}

result, err := o.client.ListObjectsV2(ctx, listInput)
if err != nil {
return nil, err
}

var objects []string

for _, obj := range result.Contents {
objects = append(objects, *obj.Key)
}

return objects, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the storage file and inspect the ListObjects implementation.
ast-grep outline internal/storage/oss.go --view expanded || true
sed -n '230,320p' internal/storage/oss.go

# Find callers and any expectations around pagination/truncation.
rg -n "ListObjects\\(" .
rg -n "ListObjectsV2Paginator|IsTruncated|MaxKeys|bucket-list|list objects|ListObjects" internal cmd . --glob '!**/vendor/**'

# Inspect the command or code path that surfaces the bucket listing, if present.
fd -a ".*" internal cmd . | sed -n '1,200p'

Repository: infiniflow/ragflow

Length of output: 21426


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the S3 and OSS ListObjects implementations side-by-side.
sed -n '250,390p' internal/storage/s3.go
sed -n '250,310p' internal/storage/oss.go

# Find the command/UI path that uses ListObjects for bucket/object listing.
rg -n "ListObjects\\(|BucketExists\\(|ListObjectsV2Paginator|IsTruncated|list all objects|bucket-list|list bucket|bucket listing|admin.*bucket|objects in bucket" internal cmd . --glob '!**/vendor/**'

# Inspect the storage interface and any comments that define ListObjects semantics.
sed -n '70,95p' internal/storage/types.go
sed -n '120,165p' internal/storage/memory.go
sed -n '260,300p' internal/storage/minio.go
sed -n '130,155p' internal/storage/gcs.go

Repository: infiniflow/ragflow

Length of output: 17328


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the admin bucket objects endpoint and its storage call chain.
sed -n '2660,2725p' internal/cli/admin_command.go
sed -n '260,330p' internal/cli/cli_http.go

# Find the server-side handler for admin bucket object listing.
rg -n "admin/bucket/.*/objects|admin_list_bucket_objects|ListObjects\\(" internal --glob '!**/vendor/**'

# If found, inspect the handler implementation around the match.

Repository: infiniflow/ragflow

Length of output: 5244


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the server-side handler for the admin bucket objects API.
rg -n "admin/bucket/.*/objects|admin_list_bucket_objects|ListObjects\\(" internal/api internal/server internal/handlers internal --glob '!**/vendor/**'

# Inspect nearby code for any paging/limit behavior or use of storage.ListObjects.
sed -n '1,260p' internal/cli/cli_http.go

Repository: infiniflow/ragflow

Length of output: 1726


Paginate OSS bucket listings
ListObjectsV2 only returns the first page here, so buckets with more than 1000 objects will be reported incompletely by the admin bucket-object listing. Use a paginator so ListObjects returns all keys.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/oss.go` around lines 259 - 278, ListObjects currently calls
OSS ListObjectsV2 only once, so it returns only the first page of keys for large
buckets. Update OSSStorage.ListObjects to use a paginator over the ListObjectsV2
API and append keys from each page until exhausted, keeping the existing
bucket/tenantID signature and ensuring all object keys are returned.

Comment thread internal/storage/s3.go
Comment on lines +267 to +272
func (s *S3Storage) ListObjects(bucket string, tenantID ...string) ([]string, error) {
ctx := context.Background()

listInput := &s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the target file and inspect the relevant region.
git ls-files 'internal/storage/s3.go'
wc -l internal/storage/s3.go
sed -n '1,360p' internal/storage/s3.go

Repository: infiniflow/ragflow

Length of output: 9120


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the storage interface and all ListObjects usages to see expected semantics.
rg -n "ListObjects\(" -S .
printf '\n--- interface ---\n'
rg -n "type .*interface|ListObjects" internal -g'*.go'

Repository: infiniflow/ragflow

Length of output: 15981


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the storage interface definition and the surrounding methods for S3Storage.
fd -a '*.go' internal | sed -n '1,120p'

Repository: infiniflow/ragflow

Length of output: 440


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect ListObjects implementations in the other storage backends for semantic parity.
for f in internal/storage/oss.go internal/storage/gcs.go internal/storage/minio.go internal/storage/memory.go; do
  echo "--- $f ---"
  sed -n '1,220p' "$f" | rg -n -A20 -B5 "func .*ListObjects|ListObjects"
done

Repository: infiniflow/ragflow

Length of output: 188


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read the relevant ListObjects methods directly to compare behavior.
sed -n '240,320p' internal/storage/oss.go
printf '\n---\n'
sed -n '120,180p' internal/storage/gcs.go
printf '\n---\n'
sed -n '260,340p' internal/storage/minio.go
printf '\n---\n'
sed -n '120,170p' internal/storage/memory.go

Repository: infiniflow/ragflow

Length of output: 6975


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the storage interface, S3Storage fields, and ListObjects call sites to determine intended semantics.
sed -n '1,140p' internal/storage/types.go
printf '\n--- s3 ---\n'
sed -n '1,120p' internal/storage/s3.go
printf '\n--- call sites ---\n'
rg -n "ListObjects\(" internal -g'*.go' -A3 -B3

Repository: infiniflow/ragflow

Length of output: 10608


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check where S3Storage.bucket and prefixPath are assigned or used.
rg -n "s\.bucket|prefixPath|bucket\s*:" internal/storage/s3.go internal/storage -g'*.go'

Repository: infiniflow/ragflow

Length of output: 4130


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "s\.bucket|prefixPath|bucket\s*:" internal/storage/s3.go internal/storage -g'*.go'

Repository: infiniflow/ragflow

Length of output: 4130


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find all assignments/usages of the S3Storage bucket override fields.
rg -n "s\.bucket|prefixPath|\.bucket\s*=|\.prefixPath\s*=" internal/storage -g'*.go'

Repository: infiniflow/ragflow

Length of output: 1909


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the S3 config and any S3Storage construction to see whether bucket/prefix are actually wired in.
sed -n '1,220p' internal/server/s3.go 2>/dev/null || true
sed -n '1,220p' internal/server/config.go 2>/dev/null || true
rg -n "type S3Config|NewS3Storage\(|S3Storage{" internal -g'*.go'

Repository: infiniflow/ragflow

Length of output: 8654


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the S3Config definition and S3Storage construction sites.
rg -n "type S3Config|NewS3Storage\(|S3Storage{" internal -g'*.go'

Repository: infiniflow/ragflow

Length of output: 298


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find S3Config definition and any direct construction or field assignment for S3Storage.
rg -n -F "type S3Config" internal/server internal -g'*.go'
printf '\n---\n'
rg -n -F "NewS3Storage(" internal -g'*.go'
printf '\n---\n'
rg -n -F "S3Storage{" internal -g'*.go'
printf '\n---\n'
rg -n -F ".bucket =" internal -g'*.go'
printf '\n---\n'
rg -n -F ".prefixPath =" internal -g'*.go'

Repository: infiniflow/ragflow

Length of output: 1121


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read the S3 config definition and any S3Storage construction sites.
sed -n '220,320p' internal/server/config.go
printf '\n---\n'
rg -n -F "NewS3Storage(" internal -g'*.go'
printf '\n---\n'
rg -n -F "S3Storage{" internal -g'*.go'

Repository: infiniflow/ragflow

Length of output: 4395


Wire server.S3Config.Bucket and PrefixPath into S3Storage. NewS3Storage leaves s.bucket and s.prefixPath empty, so resolveBucketAndPath is a no-op and the configured defaults are ignored across S3 operations.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/s3.go` around lines 267 - 272, `S3Storage` is not using the
configured defaults because `NewS3Storage` leaves `s.bucket` and `s.prefixPath`
unset, so `resolveBucketAndPath` never applies them. Update `NewS3Storage` to
wire `server.S3Config.Bucket` and `server.S3Config.PrefixPath` into the
`S3Storage` instance, and verify the S3 helpers that depend on
`resolveBucketAndPath` (including `ListObjects`) now pick up the default
bucket/prefix when callers do not pass overrides.

Comment on lines +63 to +70
// CloseStorage closes the storage connection
func CloseStorage() error {
factory := GetStorageFactory()
factory.mu.Lock()
defer factory.mu.Unlock()
return factory.storage.Close()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

CloseStorage() will panic if factory.storage is nil.

The non-fatal error handling in cmd/ragflow_server.go (line 358) allows the server to continue when storage init fails, but defer storage.CloseStorage() (line 360) is registered unconditionally. On shutdown, factory.storage.Close() will nil-pointer panic because factory.storage was never set.

🔒 Proposed fix: add nil guard
 func CloseStorage() error {
 	factory := GetStorageFactory()
 	factory.mu.Lock()
 	defer factory.mu.Unlock()
+	if factory.storage == nil {
+		return nil
+	}
 	return factory.storage.Close()
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// CloseStorage closes the storage connection
func CloseStorage() error {
factory := GetStorageFactory()
factory.mu.Lock()
defer factory.mu.Unlock()
return factory.storage.Close()
}
// CloseStorage closes the storage connection
func CloseStorage() error {
factory := GetStorageFactory()
factory.mu.Lock()
defer factory.mu.Unlock()
if factory.storage == nil {
return nil
}
return factory.storage.Close()
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/storage_factory.go` around lines 63 - 70, CloseStorage() can
panic when storage initialization failed and factory.storage was never set, so
add a nil guard before calling Close() in CloseStorage and return nil (or the
appropriate no-op result) when there is no storage instance. Use the
GetStorageFactory() and factory.storage access in
internal/storage/storage_factory.go to locate the fix, and keep the mutex
lock/unlock behavior intact while making shutdown safe after a failed init path.

Comment on lines +132 to +147
func (f *StorageFactory) initGCS(gcsConfig *server.GCSConfig) error {

storage, err := NewGCSStorage(gcsConfig)
if err != nil {
return fmt.Errorf("failed to create GCS storage: %w", err)
}

f.mu.Lock()
defer f.mu.Unlock()
f.storageType = StorageGCS
f.storage = storage
f.config.GCS = gcsConfig

return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

initGCS should guard against nil gcsConfig.

If STORAGE_IMPL=gcs is set but no gcs config section exists in the config file or environment, f.config.GCS will be nil. NewGCSStorage(nil) may panic depending on the implementation. The Create method (line 170) already follows the pattern of checking for nil config before constructing storage.

🛡️ Proposed fix: add nil check
 func (f *StorageFactory) initGCS(gcsConfig *server.GCSConfig) error {
+	if gcsConfig == nil {
+		return fmt.Errorf("GCS config not available")
+	}
 	storage, err := NewGCSStorage(gcsConfig)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (f *StorageFactory) initGCS(gcsConfig *server.GCSConfig) error {
storage, err := NewGCSStorage(gcsConfig)
if err != nil {
return fmt.Errorf("failed to create GCS storage: %w", err)
}
f.mu.Lock()
defer f.mu.Unlock()
f.storageType = StorageGCS
f.storage = storage
f.config.GCS = gcsConfig
return nil
}
func (f *StorageFactory) initGCS(gcsConfig *server.GCSConfig) error {
if gcsConfig == nil {
return fmt.Errorf("GCS config not available")
}
storage, err := NewGCSStorage(gcsConfig)
if err != nil {
return fmt.Errorf("failed to create GCS storage: %w", err)
}
f.mu.Lock()
defer f.mu.Unlock()
f.storageType = StorageGCS
f.storage = storage
f.config.GCS = gcsConfig
return nil
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/storage/storage_factory.go` around lines 132 - 147, initGCS
currently calls NewGCSStorage without validating gcsConfig, so add a nil guard
at the start of StorageFactory.initGCS to return a clear error when no GCS
config is present. Mirror the existing nil-check pattern used in
StorageFactory.Create before constructing storage, and keep the rest of the
initialization path unchanged for the valid-config case.

@JinHai-CN
JinHai-CN merged commit 2126628 into infiniflow:main Jul 8, 2026
6 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant