Repository navigation
feat(go-api): implement connector (data source) management endpoints - #15274
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR implements the ChangesConnector Test Endpoint
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 4❌ Failed checks (3 warnings, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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. Comment |
Port the connector lifecycle endpoints that power the user-setting data source page from Python (api/apps/restful_apis/connector_api.py) to Go. Previously only GET /connectors (list) was implemented. New endpoints under /api/v1/connectors: - POST /connectors create - GET /connectors/:id get one - PATCH /connectors/:id update (config/freqs + reschedule/cancel) - DELETE /connectors/:id delete (cancels sync tasks first) - GET /connectors/:id/logs list sync logs (paginated) - POST /connectors/:id/rebuild schedule a full re-sync - POST /connectors/:id/test validate stored credentials Layering follows the existing handler -> service -> dao pattern: - entity: add SyncLogs.task_type column + ConnectorTaskType/InputType consts - dao: add SyncLogsDAO (list_sync_tasks join, schedule guard, status updates, delete) and Connector2KbDAO; reuse existing ConnectorDAO CRUD - service: add Create/Get/Update/Delete/ListLogs/Rebuild/Test plus the accessible() tenant check and cancel/schedule task helpers mirroring ConnectorService.cancel_tasks / schedule_tasks - router: register the new routes under the /connectors group Known gaps vs. Python (no Go task-worker yet): - rebuild does not delete previously indexed documents (FileService.delete_docs is not ported); it drops sync logs and enqueues a reindex SYNC task. - test only gates on source == rest_api and credential presence; the per-connector validate_config path lives in common.data_source (Python-only). Both are noted in code comments as follow-ups. OAuth web flows (google/gmail/drive/box) remain out of scope per the issue. Refs infiniflow#15273
22c0a13 to
ebd725d
Compare
|
Hi, @JinHai-CN , |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 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 `@internal/handler/connector.go`:
- Around line 358-361: The current branch treats any error that's not
service.ErrConnectorNoAuth or service.ErrConnectorNotFound as a validation error
and returns gin.H{"code": common.CodeDataError, "data": false, ...}, which masks
true server-side failures; change the logic in the connector error handling so
only explicit validation sentinel errors (e.g., a new or existing specific
validation error sentinel like service.ErrConnectorValidation or whatever
validation errors your service returns) map to common.CodeDataError with
data=false, and for any other unknown error delegate to connectorErrorResponse
(preserving its existing server-error handling). Locate the block checking
errors.Is(err, service.ErrConnectorNoAuth) / service.ErrConnectorNotFound and
replace the broad fallback with an explicit validation-errors check, returning
CodeDataError only for those validation sentinels and calling
connectorErrorResponse(c, err) for all other errors.
- Around line 267-278: The page_size query parsing currently allows any positive
integer which can cause heavy DB/load spikes; update the parsing near the
pageSize logic to enforce a server-side maximum (e.g. const maxPageSize = 100)
and clamp the parsed value using something like pageSize = min(parsedPageSize,
maxPageSize) (keep the existing behavior for empty/invalid values and positive
checks), referencing the pageSize variable and c.Query("page_size") so the
handler never uses an unbounded page size.
In `@internal/service/connector.go`:
- Around line 95-98: In the accessible method, don't collapse every
s.connectorDAO.GetByID error into ErrConnectorNotFound; instead call conn, err
:= s.connectorDAO.GetByID(connectorID) and if err != nil use errors.Is(err,
ErrConnectorNotFound) (or compare the DAO's not-found sentinel) to return
(false, ErrConnectorNotFound) only for true not-found cases, and return (false,
err) for any other DB/infra errors so callers can distinguish real errors from
missing-resource cases.
- Around line 402-405: The connector lookup error in cancelTasks and
scheduleTasks is being swallowed—when s.connectorDAO.GetByID(connectorID) fails
the functions return nil (success); change both functions to propagate and
return the lookup error (or a wrapped/contextual error) instead of nil so
callers see the failure; locate the GetByID check in cancelTasks and
scheduleTasks (and the similar check around the other occurrence at the second
block referencing s.connectorDAO.GetByID) and replace the `return nil` with
`return err` (or fmt.Errorf("connector lookup failed: %w", err)) so precheck
failures signal an error to callers.
- Around line 345-350: Before calling s.syncLogsDAO.DeleteByConnectorAndKb and
s.scheduleSync in Rebuild, validate that the given kbID is actually linked to
the connectorID: query the connector-to-KB mapping (e.g., use the connector DAO
or an existing method that returns KBs for a connector) and if kbID is not
present return an error; only then call
s.syncLogsDAO.DeleteByConnectorAndKb(connectorID, kbID) and
s.scheduleSync(connectorID, kbID, true, entity.ConnectorTaskTypeSync). This
prevents deleting/scheduling for KBs not associated with the connector.
🪄 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: c24c56d7-3fdf-41af-8fca-b19c47d430cd
📒 Files selected for processing (6)
internal/dao/connector.gointernal/entity/connector.gointernal/handler/connector.gointernal/router/router.gointernal/service/connector.gointernal/service/connector_test.go
…or-management # Conflicts: # internal/handler/connector.go # internal/router/router.go # internal/service/connector.go
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/handler/connector.go (1)
114-129:⚠️ Potential issue | 🟠 Major | ⚡ Quick winUnify
CreateConnectorvalidation before Gin's required-field binding fires.
ShouldBindJSON(&req)is still binding intoservice.CreateConnectorRequest, which hasbinding:"required"onnameandsourceininternal/service/connector.go:137-145. That means omitted fields still return the 400"Invalid request body"path before these Python-styleCodeDataErrorchecks run, while"config": {}also slips through because empty objects unmarshal to a non-nil map. If this endpoint is meant to mirror the Python validation envelope, bind into a handler-local struct and validate trimmedname/sourcepluslen(config) > 0here.🤖 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/handler/connector.go` around lines 114 - 129, The CreateConnector handler currently uses c.ShouldBindJSON(&service.CreateConnectorRequest) which triggers Gin's binding:"required" checks before your custom CodeDataError paths; instead define a handler-local request struct (matching fields Name, Source, Config) and call c.ShouldBindJSON into that local struct, then perform manual validation: trim Name and Source and return CodeDataError if empty, and ensure Config is non-nil and has len(config) > 0 (reject empty objects), only after these checks map/convert to service.CreateConnectorRequest and continue; update references to ShouldBindJSON, CreateConnector, and service.CreateConnectorRequest accordingly.
🤖 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.
Outside diff comments:
In `@internal/handler/connector.go`:
- Around line 114-129: The CreateConnector handler currently uses
c.ShouldBindJSON(&service.CreateConnectorRequest) which triggers Gin's
binding:"required" checks before your custom CodeDataError paths; instead define
a handler-local request struct (matching fields Name, Source, Config) and call
c.ShouldBindJSON into that local struct, then perform manual validation: trim
Name and Source and return CodeDataError if empty, and ensure Config is non-nil
and has len(config) > 0 (reject empty objects), only after these checks
map/convert to service.CreateConnectorRequest and continue; update references to
ShouldBindJSON, CreateConnector, and service.CreateConnectorRequest accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 45481349-60f2-49cd-9da7-5aef6f4bc061
📒 Files selected for processing (3)
internal/entity/connector.gointernal/handler/connector.gointernal/router/router.go
💤 Files with no reviewable changes (1)
- internal/router/router.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/entity/connector.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @web-dev0521, we have implement in #15300
| Method | Path | Description |
|---|---|---|
/connectors |
Create a connector | |
/connectors/{connector_id} |
Get one connector (config + sync state) | |
/connectors/{connector_id} |
Update config/freqs; reschedule or cancel tasks | |
/connectors/{connector_id} |
Delete (cancels sync tasks first) | |
/connectors/{connector_id}/logs |
List sync logs (paginated) | |
/connectors/{connector_id}/rebuild |
Schedule a full re-sync | |
| POST | /connectors/{connector_id}/test |
Validate stored credentials |
Just keep : /connectors/{connector_id}/test plz
Read #15240 for more info
…ed by infiniflow#15300 Per reviewer request, remove Create, Get, Update, Delete, ListLogs, and Rebuild connector endpoints (already implemented in infiniflow#15300). Keep only POST /:connector_id/test which is not covered there. - handler: remove all methods except ListConnectors and TestConnector; introduce connectorServiceIface for testability; update test to cover TestConnector cases - service: remove CreateConnector, UpdateConnector, DeleteConnector, ListLogs, Rebuild, and all scheduling/task helpers; keep accessible and TestConnector - dao: remove SyncLogsDAO and Connector2KbDAO (no longer used) - entity: remove ConnectorTaskType and ConnectorInputType constants - router: remove all connector routes except GET / and POST /:id/test
|
Hi, @Haruko386 , |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/connector.go (1)
130-133:⚠️ Potential issue | 🟠 Major | ⚡ Quick winAvoid collapsing all connector lookup failures to not-found in
TestConnector.Line 130-133 currently converts any DAO failure into
ErrConnectorNotFound, so transient/storage failures are misreported as missing connectors.🤖 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/service/connector.go` around lines 130 - 133, The code collapses any error from s.connectorDAO.GetByID(connectorID) into ErrConnectorNotFound; change it to distinguish a genuine "not found" from other failures by checking the concrete error (e.g., errors.Is(err, dao.ErrNotFound) or errors.Is(err, sql.ErrNoRows)) and only return ErrConnectorNotFound in that case, otherwise return or wrap the original error (e.g., fmt.Errorf("fetch connector: %w", err)) so transient/storage failures are propagated instead of misreported; ensure you import errors (and dao/sql sentinel) as needed and leave the ErrConnectorNotFound return path only for true missing-connector cases.
🤖 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.
Outside diff comments:
In `@internal/service/connector.go`:
- Around line 130-133: The code collapses any error from
s.connectorDAO.GetByID(connectorID) into ErrConnectorNotFound; change it to
distinguish a genuine "not found" from other failures by checking the concrete
error (e.g., errors.Is(err, dao.ErrNotFound) or errors.Is(err, sql.ErrNoRows))
and only return ErrConnectorNotFound in that case, otherwise return or wrap the
original error (e.g., fmt.Errorf("fetch connector: %w", err)) so
transient/storage failures are propagated instead of misreported; ensure you
import errors (and dao/sql sentinel) as needed and leave the
ErrConnectorNotFound return path only for true missing-connector cases.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d0184934-11c3-4152-84df-570bd24b4b3f
📒 Files selected for processing (6)
internal/dao/connector.gointernal/entity/connector.gointernal/handler/connector.gointernal/handler/connector_test.gointernal/router/router.gointernal/service/connector.go
💤 Files with no reviewable changes (3)
- internal/router/router.go
- internal/entity/connector.go
- internal/dao/connector.go
## Summary - Add Go REST support for `GET /api/v1/system/healthz`. - Return Python-compatible `ok`/`nok` dependency fields for DB, Redis, document engine, and storage. - Return HTTP 200 only when all checks pass; otherwise return HTTP 500 with `_meta` failure details. - Add focused service coverage for the unhealthy dependency response when Go dependencies are not initialized. ## Scope This is a small, isolated slice of #15240. It avoids current open connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs (#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260, #15261, #15262), and the memory-message PR (#15256). Refs #15240
|
Hi, @JinHai-CN , |
| func (dao *ConnectorDAO) DeleteByID(id string) error { | ||
| return DB.Where("id = ?", id).Delete(&entity.Connector{}).Error | ||
| } | ||
|
|
|
Hi, @yingfeng , |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/router/router.go (1)
317-321:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftConnector route surface is incomplete for
/api/v1/connectorsand risks API regression.Line 319–320 only expose list + test. The objective requires create/get/patch/delete/logs/rebuild/test under
/api/v1/connectors. If create/get (and others) were removed here, clients using the Data Source settings APIs will break.Please restore/register the missing connector routes in this group (or keep them until full parity lands in the same release unit).
🤖 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/router/router.go` around lines 317 - 321, The connector route group currently only registers ListConnectors and TestConnector, which removes other required endpoints; update the v1.Group("/connectors") block to register the full surface by adding routes that map POST "/" to r.connectorHandler.CreateConnector, GET "/:connector_id" to r.connectorHandler.GetConnector, PATCH "/:connector_id" to r.connectorHandler.PatchConnector, DELETE "/:connector_id" to r.connectorHandler.DeleteConnector, GET "/:connector_id/logs" to r.connectorHandler.ConnectorLogs, POST "/:connector_id/rebuild" to r.connectorHandler.RebuildConnector, and ensure the existing GET "/" and POST "/:connector_id/test" remain wired to ListConnectors and TestConnector respectively so clients keep full parity.
🤖 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.
Outside diff comments:
In `@internal/router/router.go`:
- Around line 317-321: The connector route group currently only registers
ListConnectors and TestConnector, which removes other required endpoints; update
the v1.Group("/connectors") block to register the full surface by adding routes
that map POST "/" to r.connectorHandler.CreateConnector, GET "/:connector_id" to
r.connectorHandler.GetConnector, PATCH "/:connector_id" to
r.connectorHandler.PatchConnector, DELETE "/:connector_id" to
r.connectorHandler.DeleteConnector, GET "/:connector_id/logs" to
r.connectorHandler.ConnectorLogs, POST "/:connector_id/rebuild" to
r.connectorHandler.RebuildConnector, and ensure the existing GET "/" and POST
"/:connector_id/test" remain wired to ListConnectors and TestConnector
respectively so clients keep full parity.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fde18225-023d-4d68-b202-17d75d410a7b
📒 Files selected for processing (1)
internal/router/router.go
Upstream PR infiniflow#15300 merged the Get/List/Delete/Rebuild/ListLog connector endpoints and our branch keeps only the Test endpoint, so the merge had to interleave handlers, tests, services, and DAO additions. Resolved conflicts by keeping every method from both sides: - internal/router/router.go: keep upstream's GET/POST/DELETE routes plus our POST /:connector_id/test route on the connectors group - internal/handler/connector.go: union the connectorServiceIface methods (ListConnectors, CreateConnector, GetConnector, ListLog, DeleteConnector, RebuildConnector, TestConnector); union the handler functions; consolidate imports (errors, net/http, strconv, strings, common, entity, service) - internal/handler/connector_test.go: union fakeConnectorService fields and methods so it satisfies the wider interface; add the missing CreateConnector method; keep both TestConnectorHandlerTestConnector and the upstream Delete/ListLogs tests - internal/service/connector.go: keep upstream's CreateConnectorRequest, RebuildConnectorRequest, canAccessConnector, cancelConnectorTasks, CreateConnector, GetConnector, DeleteConnector, RebuildConnector, deleteConnectorDocumentChunks, ListLog AND our accessible + TestConnector - internal/dao/connector.go: keep upstream's CancelRunningOrScheduledLogs, ListDocumentsByKBAndSourceType, RebuildConnector, createRebuildSyncLog, ListLogsByConnectorID
The previous merge dropped the `common`, `gorm.io/gorm` imports and the connector constants block (`connectorInputTypePoll`, `connectorStatusUnstarted`, `defaultConnectorFreq`, `defaultConnectorTimeout`) when reconciling our TestConnector additions with upstream's CRUD/log/rebuild additions. The file still references all of them, so `go build cmd/server_main.go` failed in ~8s on the self-hosted CI runner. - Re-add `gorm.io/gorm` and `ragflow/internal/common` imports. - Re-add the connector constants block above the sentinel vars. - Remove the leftover `Rebuild()` panic stub that was superseded by upstream's full `RebuildConnector(...)` method.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15274 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Hi, @JinHai-CN , |
Summary
Ports the connector (data source) management endpoints that power
web/src/pages/user-setting/data-source/from Python(
api/apps/restful_apis/connector_api.py) to Go. Previously onlyGET /connectors(list) was implemented in Go; this adds the rest of the lifecycle.Closes #15273 (subtask of #15240).
Endpoints implemented
All under base path
/api/v1(mirrors the Python routes):/connectors/{connector_id}/testGET /connectors(list) was already present and is unchanged.Implementation
Follows the existing
handler → service → daolayering (per PR #14790):internal/entity/connector.go): added theSyncLogs.task_typecolumn (selected by the Python sync-log query) andConnectorTaskType/InputTypeconstants mirroringcommon.constants.internal/dao/connector.go): addedSyncLogsDAO(join-basedListByConnectorID, aHasScheduledguard, status updates, and delete) andConnector2KbDAO; reuses the existingConnectorDAOCRUD.internal/service/connector.go): addedCreate/Get/Update/Delete/ListLogs/Rebuild/Test, theaccessible()tenantcheck, and
cancelTasks/scheduleTaskshelpers mirroringConnectorService.cancel_tasks/schedule_tasks. Sentinel errors map cleanly to the Python response codes.internal/handler/connector.go): added the seven handlers with the same response shapes/codes as Python (including PATCH's{"data": {...}}envelope unwrap).internal/router/router.go): registered the new routes under the/connectorsgroup.Known gaps vs. Python (no Go task-worker yet)
These are documented in code comments as follow-ups:
SYNCtask, but does not delete previously indexed documents —FileService.delete_docsis not yet ported to Go. The re-sync will re-ingest from the source; stale docsare not removed here.
source == rest_apiand credential presence only. The per-connectorvalidate_configpath lives in the Pythoncommon.data_sourcepackage and has no Go equivalent yet.Provider OAuth web flows (
google/gmail/google-drive/box) remain out of scope ppr the issue and should be a separate subtask.Testing
internal/service/connector_test.gocovering the pure helpers (connectorPruneEnabled,isCancelStatus,isScheduleStatus).go build ./...andgo vet ./...verification is left to CI.