datasource

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0, MIT Imports: 17 Imported by: 0

README

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

Feishu request pacing and rate-limit retries

Feishu export creation, export status polling, export downloads, and Wiki node listing each use a separate request budget. Clients using the same API host and App ID share these budgets within one backend process, including concurrent data sources and task retries. Document tokens, export tickets, and query parameters do not create additional budgets.

Environment variable Default Behavior
FEISHU_API_REQUESTS_PER_MINUTE 80 Positive integer; requests to each paced API are evenly spaced (750 ms by default), without accumulating burst capacity.
FEISHU_RATE_LIMIT_RETRY_WAIT 10s Positive Go duration used when the response supplies no valid reset/retry hint.
FEISHU_RATE_LIMIT_MAX_WAIT 5m Positive Go duration capping each cooldown, including response-header hints and the fallback.
FEISHU_EXPORT_MAX_POLLS 30 Positive integer bounding status polls of the same export task; API retries do not consume additional polls.
FEISHU_EXPORT_POLL_INTERVAL 2s Positive Go duration between status polls while the export is still processing.

Invalid values use the defaults. Other Feishu APIs retain their existing request frequency, with reactive cooldowns scoped to the HTTP method and normalized API path template. Document tokens, table IDs, sheet ranges, and query parameters do not split a known API's cooldown. Media downloads, file downloads, docx blocks, raw content, bitable fields/record searches, sheet values, folder metadata, Wiki space listing, and Wiki node lookup use independent cooldowns. Unknown endpoints use their service/version/resource prefix. Check the application's actual API quotas before increasing the configured budget.

JSON requests retry HTTP 429 and HTTP 400/200 responses containing Feishu error code 99991400. Downloads retry HTTP 429 and HTTP 400 with that error code. The wait is the longer valid value from x-ogw-ratelimit-reset and Retry-After; Retry-After also accepts an HTTP date. All hints are clamped to the configured maximum so an unreasonable gateway header cannot indefinitely block later syncs. Without a valid hint, a rate-limit response imposes a 10-second cooldown by default. The three retries add a nominal 30 seconds of cooldown; shared pacing or further rate-limit responses from other clients can extend the total wait. This replaces the original 2/4/8-second backoff with a shared cooldown scoped to the affected API. Only callers of the same API share that cooldown. Requests retain the existing limit of three retries. Even when retries are exhausted, subsequent documents and other clients sharing that API wait for the cooldown. Waiting honors task cancellation. Ordinary permission/validation errors still fail immediately, and download error bodies retain their existing size bounds.

Export polling uses a bounded number of polls rather than a 60-second wall-clock deadline. Shared pacing and cooldown waits therefore do not cause false export timeouts or create replacement tasks within the operation. With the defaults, an export that remains processing is checked up to 30 times, with 2 seconds between polls. The caller's context bounds total elapsed time, including waits and retries. Exhausting the poll budget retains the feishu_timeout failure classification. Tokens are checked again after gate waits; requests needing a token refresh rejoin the gate afterwards, so both JSON requests and downloads remain paced and honor any cooldown imposed during the refresh.

These budgets are process-local. Multiple backend instances or other applications using the same Feishu credentials may still hit the upstream quota; configure their combined traffic accordingly.

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: Extend request pacing to other connectors and coordinate quotas across backend instances
  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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Connector errors
	ErrConnectorNil       = errors.New("connector is nil")
	ErrConnectorTypeEmpty = errors.New("connector type is empty")
	ErrConnectorNotFound  = errors.New("connector type not found in registry")

	// DataSource errors
	ErrDataSourceNotFound  = errors.New("data source not found")
	ErrDataSourceInvalid   = errors.New("data source configuration is invalid")
	ErrDataSourceNotActive = errors.New("data source is not active")

	// Configuration errors
	ErrInvalidConfig      = errors.New("invalid configuration")
	ErrInvalidCredentials = errors.New("invalid credentials")

	// Sync errors
	ErrSyncFailed       = errors.New("sync operation failed")
	ErrSyncCanceled     = errors.New("sync operation was canceled")
	ErrFetchFailed      = errors.New("failed to fetch items from source")
	ErrResourceNotFound = errors.New("resource not found in source system")

	// Knowledge base errors
	ErrKnowledgeBaseNotFound = errors.New("knowledge base not found")

	// Sync log errors
	ErrSyncLogNotFound = errors.New("sync log not found")
)

Error definitions for datasource operations

View Source
var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
	types.ConnectorTypeFeishu: {
		Type:         types.ConnectorTypeFeishu,
		Name:         "Feishu (飞书)",
		Description:  "Sync documents, wikis, and content from Feishu",
		Priority:     0,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental", "deletion_sync"},
	},
	types.ConnectorTypeLark: {
		Type:         types.ConnectorTypeLark,
		Name:         "Lark",
		Description:  "Sync documents, wikis, and content from Lark (Feishu international)",
		Priority:     0,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental", "deletion_sync"},
	},
	types.ConnectorTypeFeishuDrive: {
		Type:         types.ConnectorTypeFeishuDrive,
		Name:         "Feishu Drive (飞书云盘)",
		Description:  "Sync documents and files from a Feishu Drive folder",
		Priority:     0,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental", "deletion_sync"},
	},
	types.ConnectorTypeLarkDrive: {
		Type:         types.ConnectorTypeLarkDrive,
		Name:         "Lark Drive",
		Description:  "Sync documents and files from a Lark Drive folder",
		Priority:     0,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental", "deletion_sync"},
	},
	types.ConnectorTypeNotion: {
		Type:         types.ConnectorTypeNotion,
		Name:         "Notion",
		Description:  "Sync pages and databases from Notion",
		Priority:     1,
		AuthType:     "api_key",
		Capabilities: []string{"incremental"},
	},
	types.ConnectorTypeConfluence: {
		Type:         types.ConnectorTypeConfluence,
		Name:         "Confluence",
		Description:  "Sync spaces and pages from Atlassian Confluence",
		Priority:     2,
		AuthType:     "api_key",
		Capabilities: []string{"incremental", "deletion_sync"},
	},
	types.ConnectorTypeYuque: {
		Type:         types.ConnectorTypeYuque,
		Name:         "Yuque (语雀)",
		Description:  "Sync knowledge bases and documents from Yuque",
		Priority:     3,
		AuthType:     "api_key",
		Capabilities: []string{"incremental"},
	},
	types.ConnectorTypeIMA: {
		Type:         types.ConnectorTypeIMA,
		Name:         "Tencent IMA (ima.qq.com)",
		Description:  "Sync knowledge bases and documents from Tencent IMA",
		Priority:     3,
		AuthType:     "api_key",
		Capabilities: []string{"incremental", "deletion_sync"},
	},
	types.ConnectorTypeGitHub: {
		Type:         types.ConnectorTypeGitHub,
		Name:         "GitHub",
		Description:  "Sync repositories, wikis, and issues from GitHub",
		Priority:     4,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental"},
	},
	types.ConnectorTypeGoogleDrive: {
		Type:         types.ConnectorTypeGoogleDrive,
		Name:         "Google Drive",
		Description:  "Sync documents and files from Google Drive",
		Priority:     5,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental"},
	},
	types.ConnectorTypeOneDrive: {
		Type:         types.ConnectorTypeOneDrive,
		Name:         "OneDrive / SharePoint",
		Description:  "Sync documents and files from Microsoft OneDrive",
		Priority:     6,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental"},
	},
	types.ConnectorTypeDingTalk: {
		Type:         types.ConnectorTypeDingTalk,
		Name:         "DingTalk (钉钉)",
		Description:  "Sync online documents from DingTalk knowledge bases",
		Priority:     7,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental", "deletion_sync"},
	},
	types.ConnectorTypeWebCrawler: {
		Type:         types.ConnectorTypeWebCrawler,
		Name:         "Web Crawler (Sitemap)",
		Description:  "Crawl websites via Sitemap.xml",
		Priority:     9,
		AuthType:     "none",
		Capabilities: []string{},
	},
	types.ConnectorTypeSlack: {
		Type:         types.ConnectorTypeSlack,
		Name:         "Slack",
		Description:  "Sync channel messages and files from Slack",
		Priority:     10,
		AuthType:     "oauth2",
		Capabilities: []string{"incremental"},
	},
	types.ConnectorTypeIMAP: {
		Type:         types.ConnectorTypeIMAP,
		Name:         "Email (IMAP)",
		Description:  "Sync email content from IMAP servers",
		Priority:     11,
		AuthType:     "password",
		Capabilities: []string{},
	},
	types.ConnectorTypeRSS: {
		Type:         types.ConnectorTypeRSS,
		Name:         "RSS / Atom Feed",
		Description:  "Sync articles from RSS/Atom feeds",
		Priority:     12,
		AuthType:     "custom",
		Capabilities: []string{"incremental"},
	},
	types.ConnectorTypeGitLab: {
		Type:         types.ConnectorTypeGitLab,
		Name:         "GitLab",
		Description:  "Sync files from GitLab projects",
		Priority:     8,
		AuthType:     "token",
		Capabilities: []string{"incremental", "hierarchical"},
	},
	types.ConnectorTypeSeafile: {
		Type:         types.ConnectorTypeSeafile,
		Name:         "Seafile",
		Description:  "Sync folders and files from Seafile libraries",
		Priority:     13,
		AuthType:     "token",
		Capabilities: []string{"incremental", "hierarchical", "deletion_sync"},
	},
}

GetConnectorMetadata returns metadata for all available connectors This is used by the frontend to display connector options

Functions

func NewConnectorHTTPClient

func NewConnectorHTTPClient(timeout time.Duration) *http.Client

NewConnectorHTTPClient returns an HTTP client with redirect and dial-time SSRF guards.

func SanitizeFileName

func SanitizeFileName(name string) string

SanitizeFileName replaces filesystem-hostile punctuation and limits a source title to 200 bytes without splitting a UTF-8 rune. Empty titles use "untitled". Whitespace, control characters and extension handling remain the caller's policy; this helper does not validate filenames or repair malformed input.

func ValidateConnectorBaseURL

func ValidateConnectorBaseURL(rawURL string) error

ValidateConnectorBaseURL checks a connector API base URL against the SSRF policy. Empty rawURL is allowed; callers apply their own default before issuing requests.

func ValidateSyncSchedule

func ValidateSyncSchedule(schedule string) error

ValidateSyncSchedule accepts the same syntax as the scheduler. An empty schedule disables automatic sync and remains valid for manual-only sources.

Types

type Connector

type Connector interface {
	// Type returns the connector type identifier (e.g., "feishu", "notion")
	Type() string

	// Validate verifies that the provided configuration is valid by testing connectivity
	// and checking credentials. Returns error if validation fails.
	Validate(ctx context.Context, config *types.DataSourceConfig) error

	// ListResources lists available resources that can be synced (documents, spaces, folders, etc.)
	// Returns a list of Resource objects that the user can select for syncing.
	//
	// parentID controls lazy (on-demand) loading of hierarchical resources:
	//   - parentID == "" → return the top-level resources (e.g. Feishu wiki spaces).
	//   - parentID != "" → return only the direct children of that resource.
	// Connectors whose listing is already flat or returns the full tree in a single
	// call may ignore parentID for the root call and return an empty slice for any
	// non-empty parentID.
	ListResources(ctx context.Context, config *types.DataSourceConfig, parentID string) ([]types.Resource, error)

	// ResolveResourceAncestors resolves, for each of the given resource IDs, the
	// ExternalIDs of every ancestor whose direct children must be loaded so a
	// lazily-loaded picker can reveal a pre-existing (possibly deeply nested)
	// selection. The returned set is deduplicated and unordered.
	//
	// It exists so connectors that load their tree one level at a time (e.g. the
	// Feishu wiki) can expose, in O(depth) per selection, the path back to the
	// root without re-traversing the whole tree. Connectors that already return
	// the full tree (Notion) or a flat list (Yuque) have nothing to reveal and
	// return an empty slice.
	ResolveResourceAncestors(
		ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
	) ([]string, error)

	// FetchAll performs a full sync of the specified resources.
	// Returns all items from the given resource IDs.
	FetchAll(ctx context.Context, config *types.DataSourceConfig, resourceIDs []string) ([]types.FetchedItem, error)

	// FetchIncremental performs an incremental sync based on the provided cursor.
	// Returns items that have changed since the last sync, a new cursor for the next sync,
	// and an error if the operation fails.
	FetchIncremental(ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor) ([]types.FetchedItem, *types.SyncCursor, error)
}

Connector is the interface that all external data source connectors must implement. Each connector (Feishu, Notion, Confluence, etc.) provides an implementation of this interface.

type ConnectorMetadata

type ConnectorMetadata struct {
	Type         string   `json:"type"`
	Name         string   `json:"name"`
	Description  string   `json:"description"`
	Icon         string   `json:"icon,omitempty"`
	Priority     int      `json:"priority"`     // Priority order for UI display (lower = higher priority)
	AuthType     string   `json:"auth_type"`    // "oauth2", "api_key", "token", etc.
	Capabilities []string `json:"capabilities"` // "incremental", "webhook", "deletion_sync", etc.
}

ConnectorMetadata provides metadata about available connectors

func ListAvailableConnectors

func ListAvailableConnectors() []ConnectorMetadata

ListAvailableConnectors returns all available connector metadata sorted by priority

type ConnectorRegistry

type ConnectorRegistry struct {
	// contains filtered or unexported fields
}

ConnectorRegistry manages the registration and lookup of available connectors

func NewConnectorRegistry

func NewConnectorRegistry() *ConnectorRegistry

NewConnectorRegistry creates a new connector registry

func (*ConnectorRegistry) Get

func (r *ConnectorRegistry) Get(connectorType string) (Connector, error)

Get retrieves a connector by type

func (*ConnectorRegistry) List

func (r *ConnectorRegistry) List() []string

List returns all registered connector types

func (*ConnectorRegistry) Register

func (r *ConnectorRegistry) Register(connector Connector) error

Register registers a connector with the registry

type FullStreamingConnector

type FullStreamingConnector interface {
	StreamingConnector

	FetchFullStream(
		ctx context.Context, config *types.DataSourceConfig,
		cursor *types.SyncCursor, h StreamHandler,
	) (*types.SyncCursor, error)
}

FullStreamingConnector lets a streaming connector re-fetch every item while retaining the previous cursor exclusively for safe deletion reconciliation.

type FullSyncWithCursor

type FullSyncWithCursor interface {
	FetchAllFromCursor(
		ctx context.Context,
		config *types.DataSourceConfig,
		resourceIDs []string,
		cursor *types.SyncCursor,
	) ([]types.FetchedItem, *types.SyncCursor, error)
}

FullSyncWithCursor is optional. The batch sync path uses it for ForceFull and sync_mode=full so a connector can re-fetch every document while still reconciling deletions against the previous cursor. Connectors that omit it keep FetchAll's no-cursor behaviour and therefore cannot emit deletions on a full sync.

type PartialFetchError

type PartialFetchError struct {
	Details []string
}

PartialFetchError indicates that some resources were fetched successfully but others failed. The caller should process Items (if any), persist an updated cursor when provided, and surface Details to the user as a partial sync.

func (*PartialFetchError) Error

func (e *PartialFetchError) Error() string

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

Scheduler manages cron-based periodic sync for data sources.

robfig/cron fires at absolute wall-clock times (e.g. "0 0 * * * *" always fires at the top of every hour regardless of when the process started). So multiple instances will fire at the same moment. Dedup is handled by two layers:

  1. HasRunningSync — if a previous sync is still running, skip (prevent overlap).
  2. asynq.TaskID — deterministic ID per (dataSourceID, minute). Redis ensures only one task with a given ID is enqueued. Losers get ErrTaskIDConflict.

func NewScheduler

func NewScheduler(
	dsRepo interfaces.DataSourceRepository,
	syncLogRepo interfaces.SyncLogRepository,
	taskEnqueuer interfaces.TaskEnqueuer,
) *Scheduler

NewScheduler creates a new Scheduler.

func (*Scheduler) AddOrUpdate

func (s *Scheduler) AddOrUpdate(ds *types.DataSource) error

AddOrUpdate registers (or re-registers) a cron entry for the given data source.

func (*Scheduler) EntryCount

func (s *Scheduler) EntryCount() int

EntryCount returns the number of active cron entries (for testing/monitoring).

func (*Scheduler) Remove

func (s *Scheduler) Remove(dataSourceID string)

Remove removes the cron entry for a data source.

func (*Scheduler) Start

func (s *Scheduler) Start(ctx context.Context) error

Start loads all active data sources from the database and registers their cron schedules. Then starts the cron runner in the background.

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop gracefully stops the cron runner and waits for running jobs to finish.

func (*Scheduler) StopWithin

func (s *Scheduler) StopWithin(timeout time.Duration)

StopWithin is Stop with a bound. timeout <= 0 waits until in-flight jobs finish. A positive timeout lets shutdown continue so one long sync cannot hold every later cleanup hook, including child-process reaping.

type StreamHandler

type StreamHandler interface {
	// Emit ingests a single fetched item. Returning an error aborts the
	// stream: the connector stops fetching and propagates the error, since a
	// failed ingest means the sync is failing and further API calls are wasted.
	Emit(ctx context.Context, item types.FetchedItem) error

	// Checkpoint persists the cursor reached so far. The cursor is only valid
	// for the duration of the call (the connector may keep mutating its backing
	// maps afterwards), so implementations must serialize it synchronously.
	//
	// The cursor MUST be a complete resumable snapshot, not a delta: resuming
	// from it must reproduce all progress so far. This is what lets the service
	// treat a checkpoint as a safe restart point and, for a full sync, drop the
	// prior baseline without losing already-synced state.
	Checkpoint(ctx context.Context, cursor *types.SyncCursor) error
}

StreamHandler receives items and progress checkpoints emitted during a streaming fetch. The service implements it to ingest each item as it arrives (bounding memory to one item instead of the whole wiki) and to persist the connector cursor at page boundaries, so a sync that times out mid-traversal resumes from the last checkpoint instead of restarting from scratch (Tencent/WeKnora#2136).

type StreamingConnector

type StreamingConnector interface {
	Connector

	// FetchStream walks the configured resources starting from cursor (nil =
	// from the beginning / full sync), calling h.Emit for each changed item and
	// h.Checkpoint at page boundaries. It returns the final cursor for the next
	// sync. Nodes already recorded in cursor at their current edit time are
	// skipped, which is what makes a resumed sync converge.
	FetchStream(
		ctx context.Context, config *types.DataSourceConfig,
		cursor *types.SyncCursor, h StreamHandler,
	) (*types.SyncCursor, error)
}

StreamingConnector is an optional interface. Connectors that implement it let the service interleave fetch→ingest→checkpoint so a large sync persists incrementally and resumes after a timeout, rather than holding every item in memory and losing all progress on retry. Connectors that do not implement it fall back to FetchAll / FetchIncremental unchanged.

Directories

Path Synopsis
connector
confluence
Package confluence imports Confluence Server/Data Center and Cloud spaces as Markdown.
Package confluence imports Confluence Server/Data Center and Cloud spaces as Markdown.
dingtalk
Package dingtalk implements the DingTalk document data source connector.
Package dingtalk implements the DingTalk document data source connector.
feishu/core
Package feishu implements the Feishu (飞书/Lark) data source connector for WeKnora.
Package feishu implements the Feishu (飞书/Lark) data source connector for WeKnora.
ima
Package ima implements the WeKnora data source connector for Tencent IMA (ima.qq.com), syncing documents and files out of IMA knowledge bases via the /openapi/wiki/v1 OpenAPI.
Package ima implements the WeKnora data source connector for Tencent IMA (ima.qq.com), syncing documents and files out of IMA knowledge bases via the /openapi/wiki/v1 OpenAPI.
notion
Package notion implements the Notion data source connector for WeKnora.
Package notion implements the Notion data source connector for WeKnora.
rss
Package rss implements the RSS/Atom data source connector for WeKnora.
Package rss implements the RSS/Atom data source connector for WeKnora.
seafile
Package seafile implements the WeKnora data source connector for Seafile Server (community edition 10.0.1, api2).
Package seafile implements the WeKnora data source connector for Seafile Server (community edition 10.0.1, api2).
yuque
Package yuque implements the Yuque (语雀) data source connector for WeKnora.
Package yuque implements the Yuque (语雀) data source connector for WeKnora.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL