Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(datasource/gitlab): 修复项目路径编码与连接器单例缓存问题 (#2673)
lyingbug0cc3c335304f
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 18ab05d6a..8d740048b 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -5419,8 +5419,8 @@ export default {credentialsLabel: 'credentials',gitlab: {baseUrl: 'GitLab URL', accessToken: 'Personal access token', projects: 'GitLab projects',- projectsHint: 'Enter a project ID (or URL-encoded project path), with optional branch and directories.',- project: 'Project', projectId: 'Project ID', projectIdPlaceholder: 'For example: 12345 or group%2Fproject',+ projectsHint: 'Enter a project ID or namespace path (for example group/project), with optional branch and directories.',+ project: 'Project', projectId: 'Project ID', projectIdPlaceholder: 'For example: 12345 or group/project',ref: 'Branch', refPlaceholder: 'Leave empty to use the default branch',paths: 'Directories', pathsPlaceholder: 'One directory per line; leave empty to sync the whole project',addProject: 'Add project', projectRequired: 'Add at least one GitLab project',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 14418020c..dcb7047e4 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -585,8 +585,8 @@ export default {credentialsLabel: '자격 증명',gitlab: {baseUrl: 'GitLab URL', accessToken: '개인 액세스 토큰', projects: 'GitLab 프로젝트',- projectsHint: '프로젝트 ID(또는 URL 인코딩된 프로젝트 경로)를 입력하고, 필요에 따라 브랜치와 디렉터리를 지정하세요.',- project: '프로젝트', projectId: '프로젝트 ID', projectIdPlaceholder: '예: 12345 또는 group%2Fproject',+ projectsHint: '프로젝트 ID 또는 네임스페이스 경로(예: group/project)를 입력하고, 필요에 따라 브랜치와 디렉터리를 지정하세요.',+ project: '프로젝트', projectId: '프로젝트 ID', projectIdPlaceholder: '예: 12345 또는 group/project',ref: '브랜치', refPlaceholder: '비워 두면 기본 브랜치를 사용합니다',paths: '디렉터리', pathsPlaceholder: '한 줄에 하나씩 입력하세요. 비워 두면 전체 프로젝트를 동기화합니다',addProject: '프로젝트 추가', projectRequired: 'GitLab 프로젝트를 하나 이상 추가하세요',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex c10b317fb..3947a9b28 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -585,8 +585,8 @@ export default {credentialsLabel: 'учётные данные',gitlab: {baseUrl: 'URL GitLab', accessToken: 'Персональный токен доступа', projects: 'Проекты GitLab',- projectsHint: 'Укажите ID проекта (или URL-кодированный путь к проекту), а также при необходимости ветку и каталоги.',- project: 'Проект', projectId: 'ID проекта', projectIdPlaceholder: 'Например: 12345 или group%2Fproject',+ projectsHint: 'Укажите ID проекта или путь в пространстве имён (например group/project), а также при необходимости ветку и каталоги.',+ project: 'Проект', projectId: 'ID проекта', projectIdPlaceholder: 'Например: 12345 или group/project',ref: 'Ветка', refPlaceholder: 'Оставьте пустым, чтобы использовать ветку по умолчанию',paths: 'Каталоги', pathsPlaceholder: 'По одному каталогу в строке; оставьте пустым для синхронизации всего проекта',addProject: 'Добавить проект', projectRequired: 'Добавьте хотя бы один проект GitLab',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 130d26d30..97f24f3f1 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -587,8 +587,8 @@ export default {baseUrl: 'GitLab 地址',accessToken: '个人访问令牌',projects: 'GitLab 项目',- projectsHint: '填写项目 ID(或 URL 编码后的项目路径),可选指定分支和目录。',- project: '项目', projectId: '项目 ID', projectIdPlaceholder: '例如:12345 或 group%2Fproject',+ projectsHint: '填写项目 ID 或命名空间路径(如 group/project),可选指定分支和目录。',+ project: '项目', projectId: '项目 ID', projectIdPlaceholder: '例如:12345 或 group/project',ref: '分支', refPlaceholder: '留空时使用默认分支',paths: '同步目录', pathsPlaceholder: '每行一个目录;留空同步整个项目',addProject: '添加项目', projectRequired: '请至少添加一个 GitLab 项目',diff --git a/internal/datasource/connector/gitlab/client.go b/internal/datasource/connector/gitlab/client.goindex f598fd7b8..710d51f89 100644--- a/internal/datasource/connector/gitlab/client.go+++ b/internal/datasource/connector/gitlab/client.go@@ -9,6 +9,7 @@ import ("io""net/http""net/url"+ "strconv""strings""time"@@ -44,10 +45,6 @@ type treeEntry struct {Type string `json:"type"`Path string `json:"path"`}-type member struct {- Username string `json:"username"`- State string `json:"state"`-}type comparison struct {Diffs []struct {OldPath string `json:"old_path"`@@ -112,7 +109,33 @@ func (c *client) getRaw(ctx context.Context, endpoint string) ([]byte, error) {}return io.ReadAll(resp.Body)}-func projectPath(id string) string { return url.PathEscape(id) }++// projectPath encodes a GitLab project identifier for URL path segments.+// Numeric IDs are used verbatim. Namespace paths accept either "group/project"+// or a once-encoded "group%2Fproject" without double-encoding percent signs.+func projectPath(id string) string {+ id = strings.TrimSpace(id)+ if id == "" {+ return ""+ }+ if _, err := strconv.ParseInt(id, 10, 64); err == nil {+ return id+ }+ decoded := id+ if strings.Contains(id, "%") {+ if unescaped, err := url.PathUnescape(id); err == nil {+ decoded = unescaped+ }+ }+ if strings.Contains(decoded, "/") {+ parts := strings.Split(decoded, "/")+ for i, part := range parts {+ parts[i] = url.PathEscape(part)+ }+ return strings.Join(parts, "%2F")+ }+ return url.PathEscape(decoded)+}func (c *client) project(ctx context.Context, id string) (*project, error) {var p projecterr := c.get(ctx, "/projects/"+projectPath(id), &p)@@ -133,29 +156,6 @@ func (c *client) ping(ctx context.Context) error {}return c.get(ctx, "/user", &user)}-func (c *client) members(ctx context.Context, id string) ([]member, error) {- var m []member- allEndpoint := "/projects/" + projectPath(id) + "/members/all?per_page=100"- if err := c.get(ctx, allEndpoint, &m); err == nil {- return m, nil- } else {- // Some GitLab deployments do not expose the inherited-members endpoint.- // The standard members endpoint still verifies direct project membership.- allErr := err- m = nil- membersEndpoint := "/projects/" + projectPath(id) + "/members?per_page=100"- if err := c.get(ctx, membersEndpoint, &m); err == nil {- return m, nil- } else {- return nil, fmt.Errorf("members query failed (%v); fallback failed (%w)", allErr, err)- }- }-}-func (c *client) groupMembers(ctx context.Context, id int64) ([]member, error) {- var m []member- err := c.get(ctx, fmt.Sprintf("/groups/%d/members?per_page=100", id), &m)- return m, err-}func (c *client) commitSHA(ctx context.Context, id, ref string) (string, error) {var v struct {ID string `json:"id"`diff --git a/internal/datasource/connector/gitlab/client_test.go b/internal/datasource/connector/gitlab/client_test.goindex 50bf7181e..3654bbdd1 100644--- a/internal/datasource/connector/gitlab/client_test.go+++ b/internal/datasource/connector/gitlab/client_test.go@@ -84,6 +84,66 @@ func TestConnectorValidateRejectsMissingCredentials(t *testing.T) {}}+func TestConnectorValidateRejectsMissingProjectsOnSave(t *testing.T) {+ allowLocalGitLabServer(t)++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/v4/user" {+ http.NotFound(w, r)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"id": 42}`))+ }))+ defer server.Close()++ err := NewConnector().Validate(context.Background(), &types.DataSourceConfig{+ Credentials: map[string]interface{}{+ "base_url": server.URL,+ "access_token": "token",+ },+ Settings: map[string]interface{}{+ "projects": []interface{}{},+ },+ })+ if err == nil {+ t.Fatal("expected missing projects validation error")+ }+}++func TestConnectorConfiguredDoesNotReuseRegistryClient(t *testing.T) {+ allowLocalGitLabServer(t)++ var requestedTokens []string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/v4/user" {+ http.NotFound(w, r)+ return+ }+ requestedTokens = append(requestedTokens, r.Header.Get("PRIVATE-TOKEN"))+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"id": 42}`))+ }))+ defer server.Close()++ connector := NewConnector()+ first := &types.DataSourceConfig{+ Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token-a"},+ }+ second := &types.DataSourceConfig{+ Credentials: map[string]interface{}{"base_url": server.URL, "access_token": "token-b"},+ }+ if err := connector.Validate(context.Background(), first); err != nil {+ t.Fatalf("first validate: %v", err)+ }+ if err := connector.Validate(context.Background(), second); err != nil {+ t.Fatalf("second validate: %v", err)+ }+ if len(requestedTokens) != 2 || requestedTokens[0] != "token-a" || requestedTokens[1] != "token-b" {+ t.Fatalf("requested tokens = %#v", requestedTokens)+ }+}+func TestNewClientNormalizesAPIBaseURL(t *testing.T) {allowLocalGitLabServer(t)@@ -100,27 +160,29 @@ func TestNewClientNormalizesAPIBaseURL(t *testing.T) {}func TestFetchIncrementalSyncsMultipleProjects(t *testing.T) {+ allowLocalGitLabServer(t)+server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")switch r.URL.Path {- case "/projects/1":+ case "/api/v4/projects/1":_, _ = w.Write([]byte(`{"id":1,"name":"project-one","path_with_namespace":"group/project-one","web_url":"https://gitlab.test/group/project-one","default_branch":"master"}`))- case "/projects/2":+ case "/api/v4/projects/2":_, _ = w.Write([]byte(`{"id":2,"name":"project-two","path_with_namespace":"group/project-two","web_url":"https://gitlab.test/group/project-two","default_branch":"master"}`))- case "/projects/1/repository/commits/master":+ case "/api/v4/projects/1/repository/commits/master":_, _ = w.Write([]byte(`{"id":"commit-1"}`))- case "/projects/2/repository/commits/master":+ case "/api/v4/projects/2/repository/commits/master":_, _ = w.Write([]byte(`{"id":"commit-2"}`))- case "/projects/1/repository/tree":+ case "/api/v4/projects/1/repository/tree":_, _ = w.Write([]byte(`[{"name":"one.md","type":"blob","path":"one.md"}]`))- case "/projects/2/repository/tree":+ case "/api/v4/projects/2/repository/tree":_, _ = w.Write([]byte(`[{"name":"two.md","type":"blob","path":"two.md"}]`))default:- if strings.HasPrefix(r.URL.EscapedPath(), "/projects/1/repository/files/one%2Emd/raw") {+ if strings.HasPrefix(r.URL.EscapedPath(), "/api/v4/projects/1/repository/files/one%2Emd/raw") {_, _ = w.Write([]byte("one"))return}- if strings.HasPrefix(r.URL.EscapedPath(), "/projects/2/repository/files/two%2Emd/raw") {+ if strings.HasPrefix(r.URL.EscapedPath(), "/api/v4/projects/2/repository/files/two%2Emd/raw") {_, _ = w.Write([]byte("two"))return}@@ -129,16 +191,18 @@ func TestFetchIncrementalSyncsMultipleProjects(t *testing.T) {}))defer server.Close()- connector := &Connector{- client: &client{baseURL: server.URL, http: server.Client()},- canonicalBase: server.URL,- }- config := &types.DataSourceConfig{Settings: map[string]interface{}{- "projects": []interface{}{- map[string]interface{}{"project_id": "1", "ref": "master", "paths": []interface{}{}},- map[string]interface{}{"project_id": "2", "ref": "master", "paths": []interface{}{}},+ connector := NewConnector()+ config := &types.DataSourceConfig{+ Credentials: map[string]interface{}{+ "base_url": server.URL,+ "access_token": "token",},- }}+ Settings: map[string]interface{}{+ "projects": []interface{}{+ map[string]interface{}{"project_id": "1", "ref": "master", "paths": []interface{}{}},+ map[string]interface{}{"project_id": "2", "ref": "master", "paths": []interface{}{}},+ },+ }}items, cursor, err := connector.FetchIncremental(context.Background(), config, nil)if err != nil {@@ -176,15 +240,17 @@ func (h *gitLabStreamRecorder) Checkpoint(_ context.Context, cursor *types.SyncC}func TestFetchStreamFiltersUnsupportedFilesAndCheckpointsProjects(t *testing.T) {+ allowLocalGitLabServer(t)+var rawRequests []stringserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")switch r.URL.Path {- case "/projects/1":+ case "/api/v4/projects/1":_, _ = w.Write([]byte(`{"id":1,"name":"docs","path_with_namespace":"group/docs","web_url":"https://gitlab.test/group/docs","default_branch":"main"}`))- case "/projects/1/repository/commits/main":+ case "/api/v4/projects/1/repository/commits/main":_, _ = w.Write([]byte(`{"id":"commit-1"}`))- case "/projects/1/repository/tree":+ case "/api/v4/projects/1/repository/tree":_, _ = w.Write([]byte(`[{"name":"README.md","type":"blob","path":"README.md"},{"name":"server.go","type":"blob","path":"server.go"},@@ -201,10 +267,16 @@ func TestFetchStreamFiltersUnsupportedFilesAndCheckpointsProjects(t *testing.T)}))defer server.Close()- connector := &Connector{client: &client{baseURL: server.URL, http: server.Client()}, canonicalBase: server.URL}- config := &types.DataSourceConfig{Settings: map[string]interface{}{- "projects": []interface{}{map[string]interface{}{"project_id": "1", "paths": []interface{}{}}},- }}+ connector := NewConnector()+ config := &types.DataSourceConfig{+ Credentials: map[string]interface{}{+ "base_url": server.URL,+ "access_token": "token",+ },+ Settings: map[string]interface{}{+ "projects": []interface{}{map[string]interface{}{"project_id": "1", "paths": []interface{}{}}},+ },+ }handler := &gitLabStreamRecorder{}next, err := connector.FetchStream(context.Background(), config, nil, handler)if err != nil {@@ -231,6 +303,7 @@ func TestIsSupportedFile(t *testing.T) {want bool}{{file: "docs/guide.MD", want: true},+ {file: "docs/guide.mdx", want: true},{file: "report.pdf", want: true},{file: "src/main.go", want: false},{file: "archive.tar.gz", want: false},@@ -280,55 +353,18 @@ func TestTreeFollowsGitLabPagination(t *testing.T) {}}-func TestDirectoryExistsListsTheTargetPath(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/projects/18296/repository/tree" || r.URL.Query().Get("path") != "docs" {- http.NotFound(w, r)- return- }- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`[{"name":"quickstart.mdx","type":"blob","path":"docs/quickstart.mdx"}]`))- }))- defer server.Close()-- connector := &Connector{client: &client{baseURL: server.URL, http: server.Client()}}- exists, err := connector.directoryExists(context.Background(), "18296", "master", "docs")- if err != nil {- t.Fatal(err)- }- if !exists {- t.Fatal("expected docs directory to exist")- }-}--func TestMembersFallsBackWhenInheritedMembersEndpointIsUnavailable(t *testing.T) {- t.Setenv("SSRF_WHITELIST", "127.0.0.1,::1,localhost")- secutils.ResetSSRFWhitelistForTest()- t.Cleanup(secutils.ResetSSRFWhitelistForTest)-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch r.URL.Path {- case "/api/v4/projects/18724/members/all":- http.NotFound(w, r)- case "/api/v4/projects/18724/members":- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`[{"username":"alice","state":"active"}]`))- default:- http.NotFound(w, r)+func TestProjectPathEncodesNamespaceWithoutDoubleEscaping(t *testing.T) {+ for _, tc := range []struct {+ in, want string+ }{+ {in: "12345", want: "12345"},+ {in: "group/project", want: "group%2Fproject"},+ {in: "group%2Fproject", want: "group%2Fproject"},+ {in: "my group/my project", want: "my%20group%2Fmy%20project"},+ } {+ if got := projectPath(tc.in); got != tc.want {+ t.Errorf("projectPath(%q) = %q, want %q", tc.in, got, tc.want)}- }))- defer server.Close()-- c, err := newClient(server.URL, "token")- if err != nil {- t.Fatal(err)- }- members, err := c.members(context.Background(), "18724")- if err != nil {- t.Fatal(err)- }- if len(members) != 1 || members[0].Username != "alice" {- t.Fatalf("members = %#v", members)}}diff --git a/internal/datasource/connector/gitlab/connector.go b/internal/datasource/connector/gitlab/connector.goindex c82f9d443..ec512e719 100644--- a/internal/datasource/connector/gitlab/connector.go+++ b/internal/datasource/connector/gitlab/connector.go@@ -25,9 +25,6 @@ func NewConnector() *Connector { return &Connector{} }func (c *Connector) Type() string { return types.ConnectorTypeGitLab }func (c *Connector) configured(ds *types.DataSourceConfig) (*Connector, error) {- if c.client != nil {- return c, nil- }if ds == nil {return nil, datasource.ErrInvalidConfig}@@ -41,32 +38,21 @@ func (c *Connector) configured(ds *types.DataSourceConfig) (*Connector, error) {}func (c *Connector) Validate(ctx context.Context, ds *types.DataSourceConfig) error {- var err error- if c, err = c.configured(ds); err != nil {+ configured, err := c.configured(ds)+ if err != nil {return err}- // Connection testing deliberately validates only the GitLab URL and token.- return c.client.ping(ctx)-}--func (c *Connector) directoryExists(ctx context.Context, projectID, ref, dir string) (bool, error) {- entries, err := c.client.tree(ctx, projectID, ref, dir)- if err != nil {- return false, err+ if err := configured.client.ping(ctx); err != nil {+ return err}- // Git does not store empty directories. A successful non-empty listing of- // the target path is therefore a reliable directory existence check and- // avoids deployments that treat path="." as an invalid root path.- return len(entries) > 0, nil-}--func hasActiveMember(members []member, username string) bool {- for _, m := range members {- if m.Username == username && m.State == "active" {- return true+ if ds != nil {+ if _, ok := ds.Settings["projects"]; ok {+ if _, err := parseConfig(ds); err != nil {+ return err+ }}}- return false+ return nil}func (c *Connector) ListResources(ctx context.Context, ds *types.DataSourceConfig, parent string) ([]types.Resource, error) {var err error@@ -198,7 +184,7 @@ func (c *Connector) FetchIncremental(ctx context.Context, ds *types.DataSourceCo// the server. Re-enumerate the configured scope to preserve updates.files, listErr := c.files(ctx, s.ProjectID, ref, s.Paths)if listErr != nil {- return nil, nil, fmt.Errorf("gitlab compare %s: %w", s.ProjectID, err)+ return nil, nil, fmt.Errorf("gitlab list files %s: %w", s.ProjectID, listErr)}for _, f := range files {item, itemErr := c.item(ctx, p, ref, f)@@ -210,15 +196,15 @@ func (c *Connector) FetchIncremental(ctx context.Context, ds *types.DataSourceCo} else {for _, d := range diff.Diffs {if d.DeletedFile {- if c.inScope(d.OldPath, s.Paths) {+ if c.inScope(d.OldPath, s.Paths) && isSupportedFile(d.OldPath) {out = append(out, c.deleted(p, ref, d.OldPath))}continue}- if d.RenamedFile && c.inScope(d.OldPath, s.Paths) {+ if d.RenamedFile && c.inScope(d.OldPath, s.Paths) && isSupportedFile(d.OldPath) {out = append(out, c.deleted(p, ref, d.OldPath))}- if c.inScope(d.NewPath, s.Paths) {+ if c.inScope(d.NewPath, s.Paths) && isSupportedFile(d.NewPath) {item, err := c.item(ctx, p, ref, d.NewPath)if err != nil {return nil, nil, err@@ -406,7 +392,7 @@ func isSupportedFile(file string) bool {// GitLab exposes arbitrary repository blobs, unlike document-centric sources.var gitLabSupportedFileExtensions = map[string]struct{}{".pdf": {}, ".txt": {}, ".docx": {}, ".doc": {}, ".epub": {},- ".html": {}, ".htm": {}, ".mhtml": {}, ".md": {}, ".markdown": {},+ ".html": {}, ".htm": {}, ".mhtml": {}, ".md": {}, ".markdown": {}, ".mdx": {},".png": {}, ".jpg": {}, ".jpeg": {}, ".gif": {},".csv": {}, ".xlsx": {}, ".xls": {}, ".pptx": {}, ".ppt": {}, ".json": {},".mp3": {}, ".wav": {}, ".m4a": {}, ".flac": {}, ".ogg": {},diff --git a/internal/datasource/connector/gitlab/types_test.go b/internal/datasource/connector/gitlab/types_test.goindex 1b01cf148..449613ca0 100644--- a/internal/datasource/connector/gitlab/types_test.go+++ b/internal/datasource/connector/gitlab/types_test.go@@ -45,13 +45,3 @@ func TestKnowledgeRelativePathPreservesRepositoryTreeBelowProjectAndBranch(t *tet.Fatalf("knowledge relative path = %q", got)}}--func TestHasActiveMember(t *testing.T) {- members := []member{{Username: "liguowei", State: "active"}, {Username: "disabled", State: "blocked"}}- if !hasActiveMember(members, "liguowei") {- t.Fatal("expected active member to match")- }- if hasActiveMember(members, "disabled") {- t.Fatal("blocked member must not match")- }-}