Skip to content

feat: Implement API of Server(data source connect_id patch) - #15264

Closed
whitepicker wants to merge 4 commits into
infiniflow:mainfrom
whitepicker:feat/dat-source-connect_id-patch
Closed

whitepicker wants to merge 4 commits into
infiniflow:mainfrom
whitepicker:feat/dat-source-connect_id-patch

Conversation

@whitepicker

Copy link
Copy Markdown
Contributor

Summary

Implemented the Go API endpoint:

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

Related Issue

Closes: #15240

Change Type

  • New feature
  • API implementation
  • Bug/build fix
  • Test added
  • Refactor
  • Documentation only
  • Breaking change

Real Behavior Proof

The Go API now supports:

PATCH /api/v1/connectors/{connector_id}
Content-Type: application/json

Example request:

{
  "data": {
    "refresh_freq": 10,
    "prune_freq": 20,
    "timeout_secs": 180,
    "config": {
      "sync_deleted_files": true
    },
    "status": "SCHEDULE"
  }
}

Expected behavior:

  • Validates the current user can access the connector.
  • Updates allowed connector fields only:
    • refresh_freq
    • prune_freq
    • timeout_secs
    • config
  • Schedules or cancels connector sync tasks when requested.
  • Returns the updated connector object.

Checklist

  • Checked whether PATCH /api/v1/connectors/:connector_id already existed in Go.
  • Implemented only the requested connector PATCH API.
  • Matched Python endpoint behavior from connector_api.py.
  • Added request payload compatibility for wrapped data body.
  • Added access validation.
  • Added scheduling/cancel behavior.
  • Added focused test coverage.
  • Ran Go tests.
  • Built Go server binaries.
  • Verified server binary starts with --help.

@dosubot dosubot Bot added the size:L This PR changes 100-499 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

📝 Walkthrough

Walkthrough

This PR implements the connector update feature for the Go API server rewrite. It adds a PATCH /api/v1/connectors/:connector_id endpoint with logic to update connector polling configuration and conditionally reschedule sync/prune tasks. It introduces a TaskType field to the SyncLogs entity, adds connector DAO methods for sync-log and mapping operations, and updates build/CGO configuration to prefer PCRE2 shared library linking. A small error-formatting fix in LLM's SetAPIKey is also included.

Changes

Connector Update Feature

Layer / File(s) Summary
Build and CGO PCRE2 linking
build.sh, internal/binding/rag_analyzer.go
Dependency detection in build.sh now accepts shared library libpcre2-8.so.0 alongside static paths; CGO LDFLAGS updated to link against shared library.
SyncLogs entity model
internal/entity/connector.go
Adds TaskType string field to SyncLogs with GORM metadata (column, non-null, default "sync", indexed) and JSON serialization.
Connector DAO sync-log and mapping operations
internal/dao/connector.go
Introduces DAO methods: ListMappingsByConnectorID, CancelRunningOrScheduledLogs, GetLatestDoneSyncLog, HasScheduledSyncLog, CreateSyncLog, ScheduleSyncLogIfAbsent (atomic transaction with row locking), and IsRecordNotFound helper.
Connector update service with scheduling
internal/service/connector.go
Implements UpdateConnector to validate access, apply partial configuration updates, and conditionally reschedule tasks across mapped datasets. Includes helpers: accessible (tenant-based access), cancelTasks (cancel logs and set status), scheduleTasks (schedule sync/prune per dataset), latestDoneSyncState (fetch latest done sync), scheduleTask (create scheduled logs).
Connector update HTTP handler
internal/handler/connector.go
Adds UpdateConnector PATCH handler with optional top-level data field unwrapping; parses JSON, calls service, returns response or error.

LLM Error Formatting Fix

Layer / File(s) Summary
SetAPIKey error formatting
internal/service/llm.go
Fixes fmt.Errorf call to treat constructed message as string argument rather than format string.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • infiniflow/ragflow#15240: Implements PATCH /api/v1/connectors/:connector_id endpoint, which corresponds to the listed but unchecked connector API endpoint in the Go server rewrite roadmap.

Possibly related PRs

  • infiniflow/ragflow#15009: Also updates PCRE2/libpcre2-8 detection and linking in build.sh and internal/binding/rag_analyzer.go, though targeting different platform configurations.

Suggested labels

ci

Suggested reviewers

  • Haruko386

Poem

🐰 The rabbit hops through code with glee,
New connectors schedule tasks with ease—
From sync to prune, they dance their part,
PCRE2 shared libraries start,
A Go API grows stronger still! 🚀

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive Additional changes to build.sh, rag_analyzer.go, llm.go, and entity/connector.go appear to be supporting modifications, though some (build/binding changes and llm fix) extend beyond the stated connector PATCH API scope. Clarify whether libpcre2 build changes and the llm.go fmt.Errorf fix are prerequisites for this PR or represent scope creep; confirm these dependencies were necessary.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly indicates implementation of a PATCH API endpoint for connectors, which matches the main objective of this PR.
Description check ✅ Passed The PR description includes what problem it solves, related issue, change type selections, real behavior proof with examples, and a comprehensive checklist.
Linked Issues check ✅ Passed The PR implements PATCH /api/v1/connectors/:connector_id from linked issue #15240, matching the objective to port Python API endpoints to Go with proper field validation and task scheduling.

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

🤖 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 99-105: The code currently treats payload["data"] that fails to
unmarshal into map[string]json.RawMessage as a no-op by falling back to
json.Marshal(payload); instead, when the "data" key exists but is not a JSON
object, modify the logic in this block (the code using payload, the "data"
variable, the dataObj map and json.Unmarshal) to return an explicit error
indicating a malformed "data" wrapper rather than returning
json.Marshal(payload). Keep the existing successful path (when json.Unmarshal
into dataObj succeeds) returning data, but if json.Unmarshal returns an error or
dataObj is nil, return a descriptive error (rather than marshalling the whole
payload) so callers can reject invalid client input.

In `@internal/service/connector.go`:
- Around line 197-209: The current latestDoneSyncState function calls
connectorDAO.GetLatestSyncLog(connectorID, datasetID, "sync") which returns the
newest log of any status and then ignores it unless Status == TaskStatusDone,
risking losing an earlier completed checkpoint; change the behaviour to query
for the most recent completed sync log directly (e.g., add or use a DAO method
that filters by status like GetLatestSyncLogByStatus or GetLatestSyncLog with an
explicit status="done" parameter) and return that record's PollRangeEnd and
TotalDocsIndexed in latestDoneSyncState instead of fetching an unfiltered latest
row and discarding non-done entries.
- Around line 212-235: The current flow (HasScheduledSyncLog -> UpdateByID ->
CreateSyncLog) is not atomic and can produce duplicate jobs or leave connector
status updated if CreateSyncLog fails; change this to perform the existence
check, status update (UpdateByID), and sync-log creation (CreateSyncLog) inside
a single database transaction via the connectorDAO transactional API (e.g.,
BeginTx/WithTx) so that on any error the transaction is rolled back;
alternatively implement an atomic upsert or INSERT ... WHERE NOT EXISTS at the
DAO level to ensure CreateSyncLog only succeeds once and UpdateByID is only
committed when the insert succeeds, and make sure errors trigger rollback and
return to the caller.
🪄 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: ed222bbd-c4b0-4397-a88e-0ddb3036d37f

📥 Commits

Reviewing files that changed from the base of the PR and between 8f0632c and 2a51aa0.

📒 Files selected for processing (9)
  • build.sh
  • internal/binding/rag_analyzer.go
  • internal/dao/connector.go
  • internal/entity/connector.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/handler/connector.go Resolved
Comment thread internal/service/connector.go Resolved
Comment thread internal/service/connector.go Resolved

@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.

🧹 Nitpick comments (1)
internal/service/connector.go (1)

116-118: 💤 Low value

Remove redundant id from updates map.

The UpdateByID method already receives connectorID as a parameter and uses it in the WHERE clause. Adding id to the updates map is unnecessary and could cause confusion about whether the ID is being updated.

Suggested fix
 		if len(updates) > 0 {
-			updates["id"] = connectorID
 			if err := s.connectorDAO.UpdateByID(connectorID, updates); err != nil {
 				return nil, common.CodeServerError, 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 `@internal/service/connector.go` around lines 116 - 118, The updates map is
incorrectly being assigned an "id" field before calling
s.connectorDAO.UpdateByID(connectorID, updates); remove the line that sets
updates["id"] = connectorID so the ID is only passed via the connectorID
parameter to UpdateByID (leave the rest of the updates logic and the call to
s.connectorDAO.UpdateByID intact).
🤖 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.

Nitpick comments:
In `@internal/service/connector.go`:
- Around line 116-118: The updates map is incorrectly being assigned an "id"
field before calling s.connectorDAO.UpdateByID(connectorID, updates); remove the
line that sets updates["id"] = connectorID so the ID is only passed via the
connectorID parameter to UpdateByID (leave the rest of the updates logic and the
call to s.connectorDAO.UpdateByID intact).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9554ee4b-9940-4801-baae-1fdabbe11ede

📥 Commits

Reviewing files that changed from the base of the PR and between 2a51aa0 and f02daac.

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

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

Copy link
Copy Markdown
Member

The feature is already implemented.

@JinHai-CN JinHai-CN closed this Sep 2, 2026
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

2 participants