Skip to content

feat[Go]: implement create_connector API - #15285

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main
May 27, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

implement create_connector API

Verified from POSTMAN

image

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a POST /api/v1/connectors/ endpoint: service DTO and defaults, handler JSON validation and service call, custom Connector JSON marshaling, router registration, and updated handler test doubles.

Changes

Connector creation endpoint

Layer / File(s) Summary
Service contract and defaults
internal/service/connector.go
Introduces CreateConnectorRequest, connector constants (polling input type, unstarted status, defaults), and implements ConnectorService.CreateConnector to apply defaults, persist, and return the created connector.
Entity JSON marshaling
internal/entity/connector.go
Adds Connector.MarshalJSON and a time-format helper to emit create_time/create_date/update_time/update_date and indexing_start as formatted strings or null.
Handler validation and service interface
internal/handler/connector.go
Extends connectorService interface, imports strings, and adds CreateConnector handler that binds JSON, trims/validates Name/Source and Config, calls service, and returns structured JSON responses.
Route registration
internal/router/router.go
Registers protected POST /api/v1/connectors/ routed to connectorHandler.CreateConnector; includes non-functional reformatting of tenant internal routes.
Handler test double updates
internal/handler/connector_test.go
Adds fakeConnectorService.CreateConnector, standardizes UpdateConnector error propagation, and removes a duplicated GetConnector block to align the test double with handler usage.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Router
  participant ConnectorHandler
  participant ConnectorService
  participant ConnectorDAO
  Client->>Router: POST /api/v1/connectors/
  Router->>ConnectorHandler: CreateConnector(ctx)
  ConnectorHandler->>ConnectorHandler: Bind JSON, trim/validate Name/Source, check Config
  ConnectorHandler->>ConnectorService: CreateConnector(userID, req)
  ConnectorService->>ConnectorService: Apply default refresh/prune/timeout
  ConnectorService->>ConnectorDAO: Create(entity.Connector)
  ConnectorDAO-->>ConnectorService: persisted ID
  ConnectorService->>ConnectorDAO: GetByID(id)
  ConnectorDAO-->>ConnectorService: connector entity
  ConnectorService-->>ConnectorHandler: connector entity
  ConnectorHandler-->>Client: HTTP 200 + connector JSON
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15259: Extends connector handler/service with new operations and corresponding HTTP endpoints in the same codebase layer.

Suggested labels

size:M

Poem

A rabbit trims strings with nimble care,
Crafts connectors with defaults to share,
Marshals timestamps, wires the new route,
Tests updated, no logic left out,
Hopping home with a payload fair. 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 summarizes the main change: implementing a create_connector API endpoint in Go, which aligns with the changeset across handler, router, service, and entity layers.
Description check ✅ Passed The description follows the required template with both sections completed: 'What problem does this PR solve?' is addressed and the 'Type of change' checkbox for 'New Feature' is marked. The problem statement is minimal but present, and verification via POSTMAN is documented.
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.

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

@Haruko386 Haruko386 added the ci Continue Integration label May 27, 2026
@Haruko386
Haruko386 marked this pull request as draft May 27, 2026 06:30
@Haruko386
Haruko386 marked this pull request as ready for review May 27, 2026 06:30

@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/handler/connector.go`:
- Around line 117-119: Update the Swagger comment above the CreateConnector
handler: change the response type from service.ListConnectorsResponse to the
correct create response type used by the service (e.g.,
service.CreateConnectorResponse or service.ConnectorResponse used for
single-connector returns) and change the documented route from `/connector/
[post]` to the actual router path `/api/v1/connectors/ [post]` so the annotation
on the CreateConnector function matches the router and response shape.

In `@internal/service/connector.go`:
- Around line 83-87: The Connector is being persisted with TenantID set to
userID which breaks tenant-scoped reads (ListConnectors); change the assignment
so Connector.TenantID is the actual tenant identifier used by ListConnectors
(e.g., tenantID from the request or context) instead of userID—update the struct
construction in the connector creation (entity.Connector with field TenantID) to
use the correct tenant variable and ensure any upstream variable (where userID
is currently used) is replaced or supplemented so ownership is stored by tenant
ID.
🪄 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: 2ddebe7b-62ba-485a-8464-994e12e147f0

📥 Commits

Reviewing files that changed from the base of the PR and between ae88578 and 966abd9.

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

Comment on lines +117 to +119
// @Success 200 {object} service.ListConnectorsResponse
// @Router /connector/ [post]
func (h *ConnectorHandler) CreateConnector(c *gin.Context) {

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix Swagger contract: wrong response type and route path.

Line 117 uses service.ListConnectorsResponse for a create endpoint, and Line 118 documents /connector/ [post] while the router exposes POST /api/v1/connectors/ (internal/router/router.go Line 311). This will generate inaccurate API docs.

🤖 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 117 - 119, Update the Swagger
comment above the CreateConnector handler: change the response type from
service.ListConnectorsResponse to the correct create response type used by the
service (e.g., service.CreateConnectorResponse or service.ConnectorResponse used
for single-connector returns) and change the documented route from `/connector/
[post]` to the actual router path `/api/v1/connectors/ [post]` so the annotation
on the CreateConnector function matches the router and response shape.

Comment on lines +83 to +87
connector := &entity.Connector{
ID: common.GenerateUUID(),
TenantID: userID,
Name: req.Name,
Source: req.Source,

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Persist connector ownership by tenant ID, not raw userID.

At Line 85, TenantID is set to userID, but ListConnectors reads by tenant ID (Lines 136-154). For users whose tenant ID differs from user ID, created connectors can become invisible in list results and won’t align with tenant-scoped access.

Suggested fix
 func (s *ConnectorService) CreateConnector(userID string, req *CreateConnectorRequest) (*entity.Connector, error) {
+	tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
+	if err != nil {
+		return nil, err
+	}
+	tenantID := userID
+	if len(tenantIDs) > 0 {
+		tenantID = tenantIDs[0]
+	}
+
 	refreshFreq := int64(defaultConnectorFreq)
 	if req.RefreshFreq != nil {
 		refreshFreq = *req.RefreshFreq
 	}
@@
 	connector := &entity.Connector{
 		ID:          common.GenerateUUID(),
-		TenantID:    userID,
+		TenantID:    tenantID,
 		Name:        req.Name,
 		Source:      req.Source,
📝 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
connector := &entity.Connector{
ID: common.GenerateUUID(),
TenantID: userID,
Name: req.Name,
Source: req.Source,
func (s *ConnectorService) CreateConnector(userID string, req *CreateConnectorRequest) (*entity.Connector, error) {
tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
if err != nil {
return nil, err
}
tenantID := userID
if len(tenantIDs) > 0 {
tenantID = tenantIDs[0]
}
refreshFreq := int64(defaultConnectorFreq)
if req.RefreshFreq != nil {
refreshFreq = *req.RefreshFreq
}
connector := &entity.Connector{
ID: common.GenerateUUID(),
TenantID: tenantID,
Name: req.Name,
Source: req.Source,
🤖 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 83 - 87, The Connector is being
persisted with TenantID set to userID which breaks tenant-scoped reads
(ListConnectors); change the assignment so Connector.TenantID is the actual
tenant identifier used by ListConnectors (e.g., tenantID from the request or
context) instead of userID—update the struct construction in the connector
creation (entity.Connector with field TenantID) to use the correct tenant
variable and ensure any upstream variable (where userID is currently used) is
replaced or supplemented so ownership is stored by tenant ID.

@codecov

codecov Bot commented May 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (ae88578) to head (1cf9ecd).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15285   +/-   ##
=======================================
  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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

🧹 Nitpick comments (2)
internal/entity/connector.go (1)

45-90: ⚡ Quick win

Add a JSON contract test for Connector.MarshalJSON.

This method now defines the handler-facing response shape, but the exact 2006-01-02T15:04:05 layout and nil vs omitted behavior are unpinned. A small table-driven marshal test would make future contract drift obvious.

🤖 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/entity/connector.go` around lines 45 - 90, Add a table-driven unit
test that verifies the JSON contract produced by Connector.MarshalJSON (and
indirectly formatConnectorTime): create multiple Connector cases (with populated
times, nil times, and edge values) and assert the marshaled JSON matches the
exact field names and time layout "2006-01-02T15:04:05", and that nil time
fields are omitted or serialized as null exactly per current behavior; include
checks for CreateTime/CreateDate and UpdateTime/UpdateDate, comparing both
presence/absence and string formatting so any future contract drift is caught.
internal/handler/connector_test.go (1)

28-44: ⚡ Quick win

Add handler coverage for CreateConnector.

This file still only exercises GetConnector, so the new POST /connectors/ flow's request validation and response envelope are not locked down here. A success case plus a couple invalid-payload cases would give this fake a purpose beyond compile-time interface coverage.

🤖 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 28 - 44, Tests currently
only exercise GetConnector so CreateConnector request validation and response
envelope are untested; add unit tests that POST to the handler's CreateConnector
path using the fakeConnectorService (the fakeConnectorService.CreateConnector
method) covering at least a successful creation (valid JSON payload -> expect
201 and proper response envelope containing the created entity) and a couple
invalid-payload cases (malformed JSON and missing required fields -> expect 400
with validation error envelope). In each test, construct the HTTP request to the
POST /connectors/ handler, inject a fakeConnectorService configured to return
the desired connector or error, assert response status codes, and decode the
response body to verify the envelope structure and error codes match the handler
behavior.
🤖 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_test.go`:
- Around line 28-30: The fakeConnectorService.CreateConnector method currently
returns s.connector even when s.err is non-nil; change CreateConnector (on type
fakeConnectorService) to return (nil, s.err) when s.err is set so it mirrors
GetConnector and UpdateConnector behavior and avoids exposing a partial-success
state in tests.

---

Nitpick comments:
In `@internal/entity/connector.go`:
- Around line 45-90: Add a table-driven unit test that verifies the JSON
contract produced by Connector.MarshalJSON (and indirectly formatConnectorTime):
create multiple Connector cases (with populated times, nil times, and edge
values) and assert the marshaled JSON matches the exact field names and time
layout "2006-01-02T15:04:05", and that nil time fields are omitted or serialized
as null exactly per current behavior; include checks for CreateTime/CreateDate
and UpdateTime/UpdateDate, comparing both presence/absence and string formatting
so any future contract drift is caught.

In `@internal/handler/connector_test.go`:
- Around line 28-44: Tests currently only exercise GetConnector so
CreateConnector request validation and response envelope are untested; add unit
tests that POST to the handler's CreateConnector path using the
fakeConnectorService (the fakeConnectorService.CreateConnector method) covering
at least a successful creation (valid JSON payload -> expect 201 and proper
response envelope containing the created entity) and a couple invalid-payload
cases (malformed JSON and missing required fields -> expect 400 with validation
error envelope). In each test, construct the HTTP request to the POST
/connectors/ handler, inject a fakeConnectorService configured to return the
desired connector or error, assert response status codes, and decode the
response body to verify the envelope structure and error codes match the handler
behavior.
🪄 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: 56c2ec6a-266a-4eed-b72b-c8cc5cd26f31

📥 Commits

Reviewing files that changed from the base of the PR and between 966abd9 and 1cf9ecd.

📒 Files selected for processing (2)
  • internal/entity/connector.go
  • internal/handler/connector_test.go

Comment on lines +28 to +30
func (s fakeConnectorService) CreateConnector(string, *service.CreateConnectorRequest) (*entity.Connector, error) {
return s.connector, s.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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Make CreateConnector fail like the other fake methods.

Line 29 returns s.connector even when s.err is set, which gives tests a partial-success state the real service should not expose. Returning nil on error keeps this fake aligned with GetConnector and UpdateConnector and avoids masking handler bugs.

Suggested fix
 func (s fakeConnectorService) CreateConnector(string, *service.CreateConnectorRequest) (*entity.Connector, error) {
-	return s.connector, s.err
+	if s.err != nil {
+		return nil, s.err
+	}
+	return s.connector, nil
 }
📝 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 (s fakeConnectorService) CreateConnector(string, *service.CreateConnectorRequest) (*entity.Connector, error) {
return s.connector, s.err
}
func (s fakeConnectorService) CreateConnector(string, *service.CreateConnectorRequest) (*entity.Connector, error) {
if s.err != nil {
return nil, s.err
}
return s.connector, 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/handler/connector_test.go` around lines 28 - 30, The
fakeConnectorService.CreateConnector method currently returns s.connector even
when s.err is non-nil; change CreateConnector (on type fakeConnectorService) to
return (nil, s.err) when s.err is set so it mirrors GetConnector and
UpdateConnector behavior and avoids exposing a partial-success state in tests.

@JinHai-CN
JinHai-CN merged commit 82318de into infiniflow:main May 27, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants