WeKnora/internal/datasource
linus-liu-web bcbd65a459
fix(datasource/dingtalk): Validate 不再因为某个工作区读不到就整库判失败 (#3782)
* fix(datasource/dingtalk): 多工作区租户里一个工作区读不到就整库判失败

Validate 原来在第一个读不到的工作区或文档上直接 return err。租户的
listWorkspaces 会返回组织内的全部工作区,而 operator 通常只被授权其中
一部分,于是"知识库里混了多个工作区、其中一个没权限"会被判成"凭据
错误",整库都建不起来,哪怕另一个工作区完全可读。

改为在循环里累计 lastErr / workspaceFail / sawDocument:某个工作区列不出
节点、或某个文档读不到,都只记录原因并 continue,不再中断;循环结束后
只有"一个能读的都没有"才报错。一个文档都没暴露的租户仍然放行——没有
可读之物就无法证伪凭据,只有"存在却读不到"才算问题。

文档探测抽成 verifyDocument,后续接入上传文件、表格时在这里加分支。

验证:
- 容器内 go build ./internal/...(仅第三方 sqlite-vec cgo 因环境缺
  sqlite3.h 失败)+ go test ./internal/datasource/... 全部通过
- 反向验证:把 Validate 还原成"第一个失败即返回"后,
  TestValidateSkipsWorkspacesTheOperatorCannotRead 与
  TestValidateSurvivesWorkspaceListingFailure 立即失败

* test(datasource/dingtalk): 钉住 Validate 收紧路径并修正 verifyDocument 注释

Validate 改成继续遍历所有工作区后,多出一条比改动前更严的失败路径:
"工作区 1 只有文件夹(可读)+ 工作区 2 有一个本 operator 读不到的文档"
这种配置,改动前在第一个工作区末尾就 return nil,现在会报错。这条路径是
有意的——存在却读不到的文档意味着数据源同步不出任何东西,不是无关工作区
的权限噪音——但之前没有任何测试。

新增 TestValidateRejectsTenantWhoseOnlyDocumentIsUnreadable 固定该行为与
意图;并给既有的"全部文档都读不到"用例补上"错误必须带工作区名/文档名"的
断言(原先只 Contains("no permission"))。

顺带把 verifyDocument 的注释从"上传文件与表格目前不可摄取、永远到不了
这个函数"改成描述不变量:只有 isDocument 接受的原生类型才会进入该函数,
一个类型获得摄取路径时同时成为 document、获得同步读路径并在该函数获得
探测,上传文件与表格随各自的摄取路径一起接入。原措辞在表格/上传 PR 合并
后即失效。

验证:
- go test ./internal/datasource/connector/dingtalk/... -count=1 通过
- 反向验证:把 Validate 换回改动前的实现(首个工作区无文档即 return nil)
  后,新用例失败并报 "Validate must fail";恢复后通过

* fix(datasource/dingtalk): Validate 每个工作区只探 1 个文档,并给探测总数加上限

应用缺少文档读权限时每次探测都会失败,原先会把每个工作区根目录下的每个文档
都串行探一遍,大租户里一次校验就是几百次调用。改为探测失败后直接跳到下一个
工作区,并且最多探测 maxValidateProbes(5) 个文档后返回最后一个错误。

* fix(datasource/dingtalk): Validate 进入文件夹找文档,根目录只有文件夹的工作区不再被误判

根目录只有文件夹、文件夹里有可读文档的工作区,原先会被另一个读不到的工作区拖累,
整体判失败(main 上这种情况是通过的)。Validate 现在按 scanWorkspace 的走法对
每个工作区做广度优先查找,取第一个文档探测;子文件夹列举共用 20 次额度,额度用尽
仍有文件夹没看完时视为无法证伪,直接通过。

* fix(datasource/dingtalk): Validate 子文件夹列举失败不再当空目录,并按页限额、防环

- 非根文件夹列举失败时把本次校验记为无法确定(放行),不再当成空目录导致
  另一个工作区的不可读文档把整库判死;取消/超时错误直接返回,不再被当成
  凭据有效,也不会被之前记下的 inconclusive 吞掉。
- BFS 加 visited 集合,子节点 ID 等于祖先或工作区根时不再无限列举。
- 新增 listNodesPage 单页列举,Validate 的列举额度按实际 HTTP 分页计数:
  节点列举请求最多 len(workspaces) + maxValidateListings 次(另加客户端重试)。

* fix(datasource/dingtalk): Validate 先翻完同层分页再进子文件夹,重复 nextToken 时停下

子文件夹排在父目录下一页之前时,根目录第一页全是文件夹、文档在第二页的
工作区会把列举额度花在子文件夹上,第二页的文档永远探不到。现在每个文件夹
先翻完自己的分页再下钻,和 listNodes 给 scanWorkspace 的顺序一致;同一
文件夹重复返回 nextToken 时停下并按无法确定处理。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: 🏠 <linus@192.168.10.6>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 15:20:27 +08:00
..
connector fix(datasource/dingtalk): Validate 不再因为某个工作区读不到就整库判失败 (#3782) 2026-10-08 15:20:27 +08:00
CONNECTOR_IMPLEMENTATION_GUIDE.md revert: take the plugin system back out of main 2026-09-26 14:58:18 +08:00
README.md feat(datasource): implement data source management functionality 2026-03-30 20:46:07 +08:00
connector.go revert: take the plugin system back out of main 2026-09-26 14:58:18 +08:00
connector_test.go fix(datasource): align Feishu connector capabilities 2026-06-04 15:33:03 +08:00
errors.go fix(datasource): optimize RSS incremental sync and surface partial failures 2026-06-23 17:30:38 +08:00
filename.go refactor(datasource): share connector filename sanitization 2026-09-17 16:18:52 +08:00
filename_test.go refactor(datasource): share connector filename sanitization 2026-09-17 16:18:52 +08:00
httpclient.go fix(security): harden web_fetch and datasource connector SSRF paths 2026-07-02 12:27:48 +08:00
httpclient_test.go fix(security): harden web_fetch and datasource connector SSRF paths 2026-07-02 12:27:48 +08:00
scheduler.go fix(server): run ResourceCleaner on signal shutdown instead of racing Fatalf exit (#3804) 2026-09-28 23:37:36 +08:00
scheduler_test.go fix(datasource): validate cron schedules and persist manual-only mode (#3653) 2026-09-25 22:23:18 +08:00

README.md

WeKnora Data Source Sync Framework

Overview

The data source sync framework enables WeKnora to automatically import and synchronize content from external platforms (Feishu, Notion, Confluence, etc.) into knowledge bases. This is the foundational layer upon which all specific connectors are built.

Architecture

Core Components

┌─────────────────────────────────────────────────────────────┐
│                     External Data Sources                  │
│     (Feishu, Notion, Confluence, GitHub, Google Drive...) │
└─────────────┬───────────────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────────┐
│                  Connector Registry & Adapters              │
│    Each platform (feishu/, notion/, confluence/, etc)     │
│           implements the Connector interface               │
└─────────────┬───────────────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────────┐
│            DataSourceService (Business Logic)               │
│  ├─ CreateDataSource / UpdateDataSource                    │
│  ├─ ManualSync / ListAvailableResources                    │
│  ├─ ValidateConnection / PauseDataSource                   │
│  └─ ProcessSync (asynq task handler)                       │
└─────────────┬───────────────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────────┐
│        HTTP Handler & API Routes (/api/v1/datasource)      │
│      REST endpoints for UI/programmatic access             │
└─────────────┬───────────────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────────┐
│              Database (MySQL / PostgreSQL)                  │
│  ├─ data_sources (configuration & state)                   │
│  └─ sync_logs (history & metadata)                         │
└─────────────────────────────────────────────────────────────┘

Task Flow

Manual Trigger or Scheduled Job (cron)
        ↓
  Scheduler enqueues asynq Task
        ↓
  ProcessSync (task handler) executes
        ↓
  Connector.Fetch* methods pull data
        ↓
  Diff engine identifies changes (new/update/delete)
        ↓
  KnowledgeService creates/updates Knowledge entries
        ↓
  Documents parsed → chunks → vectors → indexed

File Structure

internal/datasource/
├── connector.go          # Connector interface & registry
├── errors.go            # Error definitions
└── README.md            # This file

internal/types/
├── datasource.go        # Data models (DataSource, SyncLog, etc)
└── interfaces/datasource.go  # Service interfaces

internal/application/
├── repository/datasource_repo.go  # Database access layer
└── service/datasource_service.go  # Business logic

internal/handler/
└── datasource.go        # HTTP request handlers

internal/router/
├── router.go           # Route registration
├── task.go             # Asynq task registration
└── sync_task.go        # Lite mode task registration

migrations/versioned/
└── 000028_datasource_tables.up/down.sql  # Database schema

Data Models

DataSource

Represents a configured external data source:

  • ID: Unique identifier
  • Type: Connector type (feishu, notion, confluence, etc)
  • Config: Encrypted credentials and configuration (JSON)
  • SyncSchedule: Cron expression (e.g., "0 */6 * * *")
  • SyncMode: "incremental" or "full"
  • Status: active | paused | error
  • ConflictStrategy: overwrite | skip
  • SyncDeletions: Whether to sync deletions from source
  • LastSyncAt: Timestamp of last successful sync
  • LastSyncCursor: State for incremental sync
  • LastSyncResult: Summary of last sync

SyncLog

Tracks execution of each sync operation:

  • Status: running | success | partial | failed | canceled
  • StartedAt/FinishedAt: Execution timestamps
  • Items*: Counters (total, created, updated, deleted, skipped, failed)
  • ErrorMessage: Error details if failed
  • Result: Detailed sync result (JSON)

Connector Interface

All external data sources implement this interface:

type Connector interface {
    Type() string
    Validate(ctx, config) error
    ListResources(ctx, config) ([]Resource, error)
    FetchAll(ctx, config, resourceIDs) ([]FetchedItem, error)
    FetchIncremental(ctx, config, cursor) ([]FetchedItem, *SyncCursor, error)
}

API Endpoints

Data Source Management

POST   /api/v1/datasource              # Create
GET    /api/v1/datasource              # List (by kb_id)
GET    /api/v1/datasource/:id          # Get
PUT    /api/v1/datasource/:id          # Update
DELETE /api/v1/datasource/:id          # Delete

Operations

POST   /api/v1/datasource/:id/validate      # Test connection
GET    /api/v1/datasource/:id/resources     # List available resources
POST   /api/v1/datasource/:id/sync          # Trigger manual sync
POST   /api/v1/datasource/:id/pause         # Pause
POST   /api/v1/datasource/:id/resume        # Resume

Logs

GET    /api/v1/datasource/:id/logs          # List sync logs
GET    /api/v1/datasource/logs/:log_id      # Get specific log

Metadata

GET    /api/v1/datasource/types             # Available connectors

Implementation Guide

Adding a New Connector

  1. Create the connector package in internal/datasource/connector/<type>/

    // connector/<type>/client.go - API client
    // connector/<type>/connector.go - Implements Connector interface
    // connector/<type>/types.go - Type-specific models
    
  2. Implement the Connector interface

    type YourConnector struct {
        // fields
    }
    
    func (c *YourConnector) Type() string {
        return types.ConnectorTypeYourType
    }
    
    func (c *YourConnector) Validate(ctx, config) error {
        // Test connectivity and credentials
    }
    
    func (c *YourConnector) ListResources(ctx, config) ([]types.Resource, error) {
        // List available resources (documents, spaces, etc)
    }
    
    func (c *YourConnector) FetchAll(ctx, config, resourceIDs) ([]types.FetchedItem, error) {
        // Full sync - fetch all items from specified resources
    }
    
    func (c *YourConnector) FetchIncremental(ctx, config, cursor) ([]types.FetchedItem, *types.SyncCursor, error) {
        // Incremental sync - fetch only changed items since cursor
    }
    
  3. Register the connector in the container (in container.go)

    container.Provide(func() datasource.Connector {
        return yourconnector.NewConnector()
    })
    
  4. Add metadata in connector.go

    types.ConnectorTypeYourType: {
        Type: types.ConnectorTypeYourType,
        Name: "Your Platform",
        AuthType: "oauth2",
        // ...
    }
    

Database Schema

data_sources table

  • Stores data source configurations
  • Indexes: tenant_id, knowledge_base_id, type, status
  • Encrypted config field (AES-256-GCM)

sync_logs table

  • Stores sync operation history
  • Indexes: data_source_id, tenant_id, status, started_at
  • Foreign key to data_sources with cascade delete

Key Design Decisions

  1. Adapter Pattern: Each connector is a separate implementation, easy to add new ones
  2. Async Task Queue: Syncs are non-blocking, using asynq (or sync mode in Lite)
  3. Incremental Sync: Supports cursor-based incremental syncs to minimize API calls
  4. Encryption: API keys/tokens stored encrypted with AES-256-GCM
  5. Multi-tenant: All operations are tenant-isolated
  6. Channel Tracking: Knowledge.Channel field tracks data source type for origin tracking

Future Enhancements

  1. Webhook Support: Real-time push from platforms that support webhooks
  2. Conflict Resolution: Advanced merge/conflict strategies for overlapping content
  3. Rate Limiting: Per-connector rate limiting and backoff strategies
  4. Scheduling: Full cron scheduler with time zone support
  5. Monitoring: Metrics, alerting, and sync health dashboards
  6. Filtering: User-defined filters for selective syncing (by title, date, tags, etc)
  7. Transformation: Content transformation pipelines (e.g., extract tables, summarize)
  8. Deduplication: Smart deduplication across multiple sources

Testing

The framework is designed to be testable:

  • Mock connectors can be created for testing
  • No external dependencies required for core logic
  • Database operations isolated and mockable

Error Handling

All operations return detailed error information:

  • Connection failures are captured and status updated
  • Partial failures are logged (some items succeed, some fail)
  • Error messages stored in DataSource for user troubleshooting