Skip to content

feat: data source connector_id GET - #15265

Closed
whitepicker wants to merge 5 commits into
infiniflow:mainfrom
whitepicker:feat/data-source-connector_id-GET
Closed

whitepicker wants to merge 5 commits into
infiniflow:mainfrom
whitepicker:feat/data-source-connector_id-GET

Conversation

@whitepicker

Copy link
Copy Markdown
Contributor

Summary

Implemented the Go API endpoint:

  • GET /api/v1/connectors/:connector_id
    This ports the Python behavior from api/apps/restful_apis/connector_api.py::get_connector into the Go server.

Related Issue

Closes: #15240

Change Type

  • New feature
  • API implementation
  • Test added
  • Build/validation fix
  • Refactor
  • Documentation only
  • Breaking change

Real Behavior Proof

The Go API now supports:

GET /api/v1/connectors/{connector_id}

Expected success response:

{
  "code": 0,
  "data": {
    "id": "conn123",
    "tenant_id": "tenant123",
    "name": "REST source",
    "source": "rest_api",
    "input_type": "poll",
    "config": {
      "url": "https://example.com/feed"
    },
    "refresh_freq": 5,
    "prune_freq": 5,
    "timeout_secs": 1740,
    "status": "0"
  },
  "message": "success"
}

Expected behavior:

  • Validates that the current user can access the connector.
  • Returns No authorization. if the connector is not accessible.
  • Returns Can't find this Connector! if the connector does not exist.
  • Returns the full connector object if accessible.

Checklist

  • Checked whether GET /api/v1/connectors/:connector_id already existed in Go.
  • Implemented only the requested connector GET detail API.
  • Matched Python endpoint behavior from connector_api.py.
  • Added access validation.
  • Added missing-connector error behavior.
  • Added focused test coverage.
  • Ran focused handler test.
  • Ran related Go package tests.
  • Built Go server binaries.
  • Verified server binary starts with --help.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 26, 2026
@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

Failed to post review comments

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds connector GET and PATCH endpoint implementations to the Go API server, updates build infrastructure to recognize PCRE2 shared libraries, and fixes error formatting in LLM service.

Changes

PCRE2 Dependency Management

Layer / File(s) Summary
Build detection and cgo flags
build.sh, internal/binding/rag_analyzer.go
build.sh detects PCRE2 shared object /usr/lib/x86_64-linux-gnu/libpcre2-8.so.0 in both C++ and Go build dependency checks; cgo LDFLAGS updated to link against the shared library instead of static archive.

Connector API implementation

Layer / File(s) Summary
Handler interface and GetConnector endpoint
internal/handler/connector.go
NewConnectorHandler now accepts unexported connectorService interface; GetConnector endpoint resolves current user and delegates to service.GetConnector, returning typed responses via jsonError/jsonResponse.
Service: GetConnector, UpdateConnector, and authorization
internal/service/connector.go
GetConnector and UpdateConnector methods validate inputs, enforce tenant/user authorization via canAccessConnector (grants access when connector.TenantID matches userID or user-tenant relationship exists), build updates map (with status case-insensitive mapping and Reschedule forcing scheduled state), persist via DAO, reload, and return ErrorCode with Connector or error details.
LLM error formatting fix
internal/service/llm.go
SetAPIKey uses fmt.Errorf("%s", msg) to safely format error message, preventing format-string injection when no models are configured.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#15009: Modifies build.sh and rag_analyzer.go to adjust PCRE2 detection and linker flags at the dependency level.
  • infiniflow/ragflow#15259: Implements the same GetConnector service method and handler endpoint for the connector GET API.
  • infiniflow/ragflow#15285: Extends connectorService interface with CreateConnector method and handler integration for POST endpoint.

Suggested reviewers

  • Haruko386

Poem

🐰 A connector learns to know its tenant true,
With shared libraries and endpoints new,
Authorization guards what users may view,
Build flows like carrots—now everyone's through! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: implementing the GET endpoint for retrieving a connector by ID, which is the primary focus of the PR.
Description check ✅ Passed The description follows the template structure, includes detailed problem statement, explicit type of change, real behavior proof, checklist, and closes linked issue #15240.
Linked Issues check ✅ Passed All code changes implement the GET /api/v1/connectors/:connector_id endpoint requirement from #15240, including validation, error handling, and service layer additions.
Out of Scope Changes check ✅ Passed Changes to build.sh and internal/service/llm.go are supporting fixes; all substantive changes directly implement the connector GET endpoint specified in issue #15240.

✏️ 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.

❤️ Share

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

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
build.sh (1)

41-42: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update PCRE2 diagnostics to match accepted shared-library checks.

The script now accepts libpcre2-8.so.0, but warning/error text still says only libpcre2-8.a is missing. Please update the messages so troubleshooting guidance matches actual detection logic.

Also applies to: 101-102

🤖 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 `@build.sh` around lines 41 - 42, Update the user-facing messages that
currently reference "libpcre2-8.a" to reflect the script's actual detection of
the shared library (libpcre2-8.so.0); locate the echo lines that print the
warning and installation hint (the two echo statements showing
"${YELLOW}Warning: libpcre2-8.a not found..." and "  sudo apt-get install
libpcre2-dev") and similar messages around the other occurrences (lines near
101-102), and change the text to mention the shared library (e.g., "Warning:
libpcre2 shared library (libpcre2-8.so.0) not found; you may need to install
libpcre2-dev") so the troubleshooting guidance matches the detection logic.
🧹 Nitpick comments (2)
internal/handler/connector.go (1)

41-45: ⚡ Quick win

Align constructor with the new interface type.

ConnectorHandler now depends on connectorService, but NewConnectorHandler still requires *service.ConnectorService. Accepting the interface here keeps DI consistent and removes the need to bypass the constructor in tests.

Proposed refactor
-func NewConnectorHandler(connectorService *service.ConnectorService, userService *service.UserService) *ConnectorHandler {
+func NewConnectorHandler(connectorService connectorService, userService *service.UserService) *ConnectorHandler {
 	return &ConnectorHandler{
 		connectorService: connectorService,
 		userService:      userService,
 	}
 }
🤖 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 41 - 45, Change
NewConnectorHandler to accept the connector service interface instead of a
concrete pointer: update the constructor signature from
NewConnectorHandler(connectorService *service.ConnectorService, userService
*service.UserService) to NewConnectorHandler(connectorService
service.ConnectorService, userService *service.UserService) and pass that
interface value into the ConnectorHandler.connectorService field so dependency
injection and tests can provide mocks without bypassing the constructor.
internal/handler/connector_test.go (1)

43-85: ⚡ Quick win

Add error-path tests for unauthorized and not-found.

This test only verifies success. Please add cases for "No authorization." and "Can't find this Connector!" to lock the endpoint contract and prevent regressions in service branching.

🤖 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_test.go` around lines 43 - 85, Extend
TestGetConnector to include two additional subtests (or separate tests) covering
the unauthorized and not-found paths: (1) "No authorization.": call the handler
without setting the "user" in the gin context (remove c.Set("user", ...)) and
assert the HTTP status is 401 and resp.Code equals the expected unauthorized
common.ErrorCode; (2) "Can't find this Connector!": configure the
fakeConnectorService to simulate a not-found error (have its GetConnector method
return an appropriate error/flag) then call h.GetConnector and assert the HTTP
status is 404 and resp.Code equals the not-found common.ErrorCode and the
response body contains the not-found message. Use the existing TestGetConnector
setup (ConnectorHandler, fakeConnectorService, route
"/api/v1/connectors/:connector_id", httptest.NewRequest/Recorder) and reuse the
same response unmarshal logic to validate error codes and messages.
🤖 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/binding/rag_analyzer.go`:
- Line 21: The cgo LDFLAGS line currently hardcodes Linux PCRE2 path/SONAME
("-L/usr/lib/x86_64-linux-gnu -l:libpcre2-8.so.0") which is brittle; update the
cgo directive in rag_analyzer.go to remove the explicit -L and
-l:libpcre2-8.so.0 and instead link PCRE2 portably (for example use "-lpcre2-8",
or mirror the CMake approach by referencing "libpcre2-8.a" without a directory,
or use pkg-config to obtain linker flags) so the build works across
distros/architectures.

In `@internal/handler/connector.go`:
- Around line 54-55: GetConnector returns an envelope with fields (code, data,
message) but the Swagger `@Success` currently documents entity.Connector directly;
update the annotation to reference the actual wrapper/envelope schema used by
responses (the type that has code, data, message) and indicate its data field is
entity.Connector so the docs reflect the wrapped JSON format (e.g., change the
`@Success` 200 {object} entity.Connector to the response envelope type that wraps
entity.Connector).

In `@internal/service/connector.go`:
- Around line 81-88: The code checks authorization via s.accessible(connectorID,
userID) before confirming the connector exists, causing missing IDs to surface
as "No authorization."; change GetConnector to first call
s.connectorDAO.GetByID(connectorID) and if err return (nil,
common.CodeDataError, errors.New("Can't find this Connector!")), then call
s.accessible(connectorID, userID) and return (nil,
common.CodeAuthenticationError, errors.New("No authorization.")) if
inaccessible; apply the same reorder/fix for the other occurrence referenced
(lines 92-101) so existence is always validated before authorization.

---

Outside diff comments:
In `@build.sh`:
- Around line 41-42: Update the user-facing messages that currently reference
"libpcre2-8.a" to reflect the script's actual detection of the shared library
(libpcre2-8.so.0); locate the echo lines that print the warning and installation
hint (the two echo statements showing "${YELLOW}Warning: libpcre2-8.a not
found..." and "  sudo apt-get install libpcre2-dev") and similar messages around
the other occurrences (lines near 101-102), and change the text to mention the
shared library (e.g., "Warning: libpcre2 shared library (libpcre2-8.so.0) not
found; you may need to install libpcre2-dev") so the troubleshooting guidance
matches the detection logic.

---

Nitpick comments:
In `@internal/handler/connector_test.go`:
- Around line 43-85: Extend TestGetConnector to include two additional subtests
(or separate tests) covering the unauthorized and not-found paths: (1) "No
authorization.": call the handler without setting the "user" in the gin context
(remove c.Set("user", ...)) and assert the HTTP status is 401 and resp.Code
equals the expected unauthorized common.ErrorCode; (2) "Can't find this
Connector!": configure the fakeConnectorService to simulate a not-found error
(have its GetConnector method return an appropriate error/flag) then call
h.GetConnector and assert the HTTP status is 404 and resp.Code equals the
not-found common.ErrorCode and the response body contains the not-found message.
Use the existing TestGetConnector setup (ConnectorHandler, fakeConnectorService,
route "/api/v1/connectors/:connector_id", httptest.NewRequest/Recorder) and
reuse the same response unmarshal logic to validate error codes and messages.

In `@internal/handler/connector.go`:
- Around line 41-45: Change NewConnectorHandler to accept the connector service
interface instead of a concrete pointer: update the constructor signature from
NewConnectorHandler(connectorService *service.ConnectorService, userService
*service.UserService) to NewConnectorHandler(connectorService
service.ConnectorService, userService *service.UserService) and pass that
interface value into the ConnectorHandler.connectorService field so dependency
injection and tests can provide mocks without bypassing the constructor.
🪄 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: c0d320be-8bde-42a3-b176-d445dc794887

📥 Commits

Reviewing files that changed from the base of the PR and between 8f0632c and 7b0ad04.

📒 Files selected for processing (7)
  • build.sh
  • internal/binding/rag_analyzer.go
  • internal/handler/connector.go
  • internal/handler/connector_test.go
  • internal/router/router.go
  • internal/service/connector.go
  • internal/service/llm.go

Comment thread internal/binding/rag_analyzer.go Resolved
Comment thread internal/handler/connector.go Resolved
Comment thread internal/service/connector.go Resolved
@tmimmanuel tmimmanuel mentioned this pull request May 27, 2026
1 of 6 tasks
@Haruko386

Copy link
Copy Markdown
Member

Hi @jakearmstrong59 your PR is conflicted with #15259

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 27, 2026

@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: 2

🤖 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/service/connector.go`:
- Around line 143-145: The code returns the raw DAO error from
s.connectorDAO.UpdateByID(connectorID, updates); replace this with a sanitized
error message for the client and log the original internal error instead. Change
the return to something like: log the original err (e.g.,
s.logger.Errorf("UpdateByID failed for connector %s: %v", connectorID, err) if
logger exists), then return nil, common.CodeServerError, errors.New("failed to
update connector") (or a package-level sanitized error) so internal DB details
from UpdateByID are not leaked.
- Around line 106-113: In UpdateConnector, the authorization check is performed
before verifying the connector exists which can return "No authorization." for
missing connectors; change the order to first call
s.connectorDAO.GetByID(connectorID) and return the data-not-found error
(common.CodeDataError) if it fails, then call s.accessible(connectorID, userID)
to enforce authorization and only return authentication errors after the
existence check; update the error returns around connectorDAO.GetByID and
accessible() accordingly.
🪄 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: d87effac-201d-4519-82af-54cb6788fb56

📥 Commits

Reviewing files that changed from the base of the PR and between 4371ba6 and 44636b6.

📒 Files selected for processing (4)
  • internal/handler/connector.go
  • internal/handler/connector_test.go
  • internal/router/router.go
  • internal/service/connector.go

Comment thread internal/service/connector.go Resolved
Comment thread internal/service/connector.go Resolved
JinHai-CN pushed a commit that referenced this pull request May 28, 2026
## 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
@JinHai-CN
JinHai-CN requested a review from mkaaad September 2, 2026 06:13
@mkaaad

mkaaad commented Sep 2, 2026

Copy link
Copy Markdown
Member

The main baseline have already implemented this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Implement API of RAGFlow server in Go

3 participants