Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

feat(data-source): add Xquik X search connector (#18714)

Burak Bayır0201c1a55776
diff --git a/api/utils/common.py b/api/utils/common.py
index 1b07783eb6..ed983b0d09 100644
--- a/api/utils/common.py
+++ b/api/utils/common.py
@@ -26,4 +26,4 @@ def bytes_to_string(byte):
# 128 bit = 32 character
def hash128(data: str) -> str:
- return xxhash.xxh128(data).hexdigest()
+ return xxhash.xxh128(string_to_bytes(data)).hexdigest()
diff --git a/common/constants.py b/common/constants.py
index bdb1ccf208..417628089e 100644
--- a/common/constants.py
+++ b/common/constants.py
@@ -145,6 +145,7 @@ class FileSource(StrEnum):
S3 = "s3"
NOTION = "notion"
REST_API = "rest_api"
+ XQUIK = "xquik"
DISCORD = "discord"
CONFLUENCE = "confluence"
GMAIL = "gmail"
diff --git a/common/data_source/__init__.py b/common/data_source/__init__.py
index 165769ef26..909f4c22ae 100644
--- a/common/data_source/__init__.py
+++ b/common/data_source/__init__.py
@@ -66,6 +66,7 @@ from .sharepoint_connector import SharePointConnector
from .slack_connector import SlackConnector
from .teams_connector import TeamsConnector
from .webdav_connector import WebDAVConnector
+from .xquik_connector import XquikConnector
from .zendesk_connector import ZendeskConnector
CONNECTOR_BY_SOURCE: dict[str, type] = {
@@ -100,6 +101,7 @@ CONNECTOR_BY_SOURCE: dict[str, type] = {
FileSource.MYSQL: RDBMSConnector,
FileSource.POSTGRESQL: RDBMSConnector,
FileSource.REST_API: RestAPIConnector,
+ FileSource.XQUIK: XquikConnector,
FileSource.BIGQUERY: BigQueryConnector,
FileSource.ONEDRIVE: OneDriveConnector,
FileSource.OUTLOOK: OutlookConnector,
@@ -120,49 +122,50 @@ def build_connector_for_source(source: str, config: dict[str, Any]) -> Any:
__all__ = [
+ "CONNECTOR_BY_SOURCE",
+ "AirtableConnector",
+ "AsanaConnector",
+ "AzureBlobConnector",
+ "AzureDevOpsConnector",
+ "BasicExpertInfo",
+ "BigQueryConnector",
+ "BitbucketConnector",
"BlobStorageConnector",
- "RSSConnector",
- "SlackConnector",
- "GmailConnector",
- "NotionConnector",
+ "BlobType",
+ "BoxConnector",
"ConfluenceConnector",
+ "ConnectorMissingCredentialError",
+ "ConnectorValidationError",
+ "CredentialExpiredError",
+ "DingTalkAITableConnector",
"DiscordConnector",
+ "Document",
+ "DocumentSource",
"DropboxConnector",
- "GoogleDriveConnector",
- "JiraConnector",
- "SharePointConnector",
"GithubConnector",
"GitlabConnector",
- "BitbucketConnector",
- "AzureDevOpsConnector",
- "BoxConnector",
+ "GmailConnector",
+ "GoogleDriveConnector",
+ "ImageSection",
+ "ImapConnector",
+ "InsufficientPermissionsError",
+ "JiraConnector",
+ "MoodleConnector",
+ "NotionConnector",
"OneDriveConnector",
"OutlookConnector",
+ "RDBMSConnector",
+ "RSSConnector",
+ "RestAPIConnector",
"SalesforceConnector",
- "AzureBlobConnector",
+ "SeaFileConnector",
+ "SharePointConnector",
+ "SlackConnector",
"TeamsConnector",
- "MoodleConnector",
- "BlobType",
- "DocumentSource",
- "Document",
"TextSection",
- "ImageSection",
- "BasicExpertInfo",
- "ConnectorMissingCredentialError",
- "ConnectorValidationError",
- "CredentialExpiredError",
- "InsufficientPermissionsError",
"UnexpectedValidationError",
- "AirtableConnector",
- "AsanaConnector",
- "ImapConnector",
- "ZendeskConnector",
- "SeaFileConnector",
- "RDBMSConnector",
- "BigQueryConnector",
"WebDAVConnector",
- "DingTalkAITableConnector",
- "RestAPIConnector",
- "CONNECTOR_BY_SOURCE",
+ "XquikConnector",
+ "ZendeskConnector",
"build_connector_for_source",
]
diff --git a/common/data_source/config.py b/common/data_source/config.py
index 3561b621fd..46089ff62c 100644
--- a/common/data_source/config.py
+++ b/common/data_source/config.py
@@ -47,6 +47,7 @@ class DocumentSource(str, Enum):
S3 = "s3"
NOTION = "notion"
REST_API = "rest_api"
+ XQUIK = "xquik"
R2 = "r2"
GOOGLE_CLOUD_STORAGE = "google_cloud_storage"
OCI_STORAGE = "oci_storage"
diff --git a/common/data_source/rest_api_connector.py b/common/data_source/rest_api_connector.py
index 68279f205d..60da97cd8f 100644
--- a/common/data_source/rest_api_connector.py
+++ b/common/data_source/rest_api_connector.py
@@ -38,7 +38,7 @@ from common.data_source.utils import rl_requests, retry_builder
from common.ssrf_guard import assert_url_is_safe, pin_dns
try:
- from jsonpath import jsonpath as _jsonpath # type: ignore[import]
+ from jsonpath import search as _jsonpath # type: ignore[import]
except Exception: # pragma: no cover
_jsonpath = None
@@ -498,7 +498,9 @@ class RestAPIConnector(LoadConnector, PollConnector):
if limit <= 0:
limit = per_page
- cursor: Optional[str] = self.pagination_config.get("initial_cursor")
+ initial_cursor = self.pagination_config.get("initial_cursor")
+ cursor: Optional[str] = None if initial_cursor in (None, "") else str(initial_cursor)
+ seen_cursors = {cursor} if cursor is not None else set()
while True:
if page_count >= self.max_pages:
@@ -524,9 +526,9 @@ class RestAPIConnector(LoadConnector, PollConnector):
raise ConnectorValidationError(f"REST API page fetch failed: {exc}") from exc
items = self._extract_items(response_json)
- if not items:
+ has_next_page = self._extract_has_next_page(response_json)
+ if not items and not (self.pagination_type == PaginationType.CURSOR and has_next_page is True):
break
-
for item in items:
if isinstance(item, Mapping):
yield item
@@ -544,9 +546,15 @@ class RestAPIConnector(LoadConnector, PollConnector):
break
offset += limit
elif self.pagination_type == PaginationType.CURSOR:
+ if has_next_page is False:
+ break
next_cursor = self._extract_next_cursor(response_json)
if not next_cursor:
break
+ if next_cursor in seen_cursors:
+ logging.warning("REST API connector received a repeated pagination cursor; stopping.")
+ break
+ seen_cursors.add(next_cursor)
cursor = next_cursor
def _page_iter_for_validation(self) -> Iterable[Mapping[str, Any]]:
@@ -812,7 +820,7 @@ class RestAPIConnector(LoadConnector, PollConnector):
"""Extract the items array from a JSON response."""
if self.items_path and _jsonpath is not None:
try:
- matches = _jsonpath(response_json, self.items_path)
+ matches = _jsonpath(self.items_path, response_json)
except Exception as exc:
raise ConnectorValidationError(f"Failed to apply items JSONPath '{self.items_path}': {exc}") from exc
if not matches:
@@ -839,6 +847,14 @@ class RestAPIConnector(LoadConnector, PollConnector):
return [it for it in items if isinstance(it, Mapping)]
+ def _extract_has_next_page(self, response_json: Any) -> Optional[bool]:
+ """Return an explicit cursor continuation flag when configured."""
+ field = self.pagination_config.get("has_next_page_field")
+ if not field or not isinstance(response_json, Mapping):
+ return None
+ value = response_json.get(field)
+ return value if isinstance(value, bool) else None
+
def _extract_next_cursor(self, response_json: Any) -> Optional[str]:
"""Extract cursor value for cursor-based pagination."""
cursor_path = self.pagination_config.get("next_cursor_path")
@@ -853,7 +869,7 @@ class RestAPIConnector(LoadConnector, PollConnector):
return None
try:
- matches = _jsonpath(response_json, cursor_path)
+ matches = _jsonpath(cursor_path, response_json)
except Exception:
return None
diff --git a/common/data_source/xquik_connector.py b/common/data_source/xquik_connector.py
new file mode 100644
index 0000000000..9afb60673b
--- /dev/null
+++ b/common/data_source/xquik_connector.py
@@ -0,0 +1,154 @@
+"""Xquik search connector built on RAGFlow's REST API connector."""
+
+from __future__ import annotations
+
+import logging
+import math
+from collections.abc import Mapping
+from datetime import datetime
+from typing import Any
+
+from common.data_source.config import DocumentSource
+from common.data_source.exceptions import ConnectorMissingCredentialError, ConnectorValidationError
+from common.data_source.models import Document
+from common.data_source.rest_api_connector import AuthType, PaginationType, RestAPIConnector
+
+XQUIK_SEARCH_URL = "https://xquik.com/api/v1/x/tweets/search"
+XQUIK_DEFAULT_PAGE_SIZE = 100
+XQUIK_DEFAULT_MAX_PAGES = 10
+XQUIK_DEFAULT_BATCH_SIZE = 32
+
+logger = logging.getLogger(__name__)
+
+
+def _positive_int(value: Any, default: int, field: str, maximum: int | None = None) -> int:
+ if value in (None, ""):
+ return default
+ try:
+ parsed = int(value)
+ except (OverflowError, TypeError, ValueError) as exc:
+ raise ConnectorValidationError(f"Xquik connector {field} must be a positive integer") from exc
+ if isinstance(value, bool) or (isinstance(value, float) and not value.is_integer()):
+ raise ConnectorValidationError(f"Xquik connector {field} must be a positive integer")
+ if parsed <= 0 or (maximum is not None and parsed > maximum):
+ suffix = f" from 1 to {maximum}" if maximum is not None else " a positive integer"
+ raise ConnectorValidationError(f"Xquik connector {field} must be{suffix}")
+ return parsed
+
+
+def _non_negative_float(value: Any, default: float, field: str) -> float:
+ if value in (None, ""):
+ return default
+ try:
+ parsed = float(value)
+ except (TypeError, ValueError) as exc:
+ raise ConnectorValidationError(f"Xquik connector {field} must be a non-negative number") from exc
+ if not math.isfinite(parsed) or parsed < 0:
+ raise ConnectorValidationError(f"Xquik connector {field} must be a non-negative number")
+ return parsed
+
+
+class XquikConnector(RestAPIConnector):
+ """Search X posts through Xquik and emit one RAGFlow document per post."""
+
+ search_url = XQUIK_SEARCH_URL
+
+ @classmethod
+ def from_config(
+ cls,
+ config: Mapping[str, Any],
+ *,
+ since_time: datetime | None = None,
+ until_time: datetime | None = None,
+ validation: bool = False,
+ ) -> XquikConnector:
+ query = str(config.get("query") or "").strip()
+ if not query:
+ raise ConnectorValidationError("Xquik connector query is required")
+
+ query_type = str(config.get("query_type") or "Latest").strip().title()
+ if query_type not in {"Latest", "Top"}:
+ raise ConnectorValidationError("Xquik connector query_type must be Latest or Top")
+
+ page_size = _positive_int(config.get("page_size"), XQUIK_DEFAULT_PAGE_SIZE, "page_size", 10_000)
+ max_pages = _positive_int(config.get("max_pages"), XQUIK_DEFAULT_MAX_PAGES, "max_pages", 1_000)
+ batch_size = _positive_int(config.get("batch_size"), XQUIK_DEFAULT_BATCH_SIZE, "batch_size")
+ request_delay = _non_negative_float(config.get("request_delay"), 0.5, "request_delay")
+
+ credentials = config.get("credentials") or {}
+ if not isinstance(credentials, Mapping):
+ credentials = {}
+ api_key = str(credentials.get("xquik_api_key") or "").strip()
+ if not api_key:
+ raise ConnectorMissingCredentialError("Xquik connector requires 'xquik_api_key' in credentials")
+
+ logger.info(
+ "Building Xquik connector: query_type=%s page_size=%d max_pages=%d batch_size=%d request_delay=%s validation=%s",
+ query_type,
+ page_size,
+ max_pages,
+ batch_size,
+ request_delay,
+ validation,
+ )
+
+ query_params = {
+ "q": query,
+ "queryType": query_type,
+ "limit": str(1 if validation else page_size),
+ }
+ if since_time is not None:
+ query_params["sinceTime"] = since_time.isoformat()
+ if until_time is not None:
+ query_params["untilTime"] = until_time.isoformat()
+
+ connector = cls(
+ url=cls.search_url,
+ method="GET",
+ query_params=query_params,
+ auth_type=AuthType.API_KEY_HEADER,
+ auth_config={"header_name": "x-api-key"},
+ items_path="$.tweets",
+ id_field="id",
+ content_fields=["text", "author.username", "createdAt", "url"],
+ metadata_fields=[
+ "id",
+ "createdAt",
+ "url",
+ "lang",
+ "author.id",
+ "author.username",
+ "author.name",
+ "author.verified",
+ "likeCount",
+ "replyCount",
+ "retweetCount",
+ "quoteCount",
+ "viewCount",
+ "bookmarkCount",
+ "media[*].mediaUrl",
+ ],
+ pagination_type=PaginationType.NONE if validation else PaginationType.CURSOR,
+ pagination_config={
+ "cursor_param": "cursor",
+ "next_cursor_field": "next_cursor",
+ "has_next_page_field": "has_next_page",
+ "page_size": page_size,
+ },
+ poll_timestamp_field="createdAt",
+ batch_size=batch_size,
+ max_pages=1 if validation else max_pages,
+ request_delay=request_delay,
+ content_template="Author: @{author_username}\nPublished: {createdAt}\nURL: {url}\n\n{text}",
+ )
+ connector.load_credentials({"api_key": api_key})
+ return connector
+
+ @classmethod
+ def build_connector(cls, config: dict[str, Any]) -> XquikConnector:
+ return cls.from_config(config, validation=True)
+
+ def _item_to_document(self, item: Mapping[str, Any]) -> Document:
+ document = super()._item_to_document(item)
+ document.source = DocumentSource.XQUIK
+ return document
diff --git a/docs/guides/data_source/data_source_categories_and_selection.md b/docs/guides/data_source/data_source_categories_and_selection.md
index 9245c4806d..d5db580887 100644
--- a/docs/guides/data_source/data_source_categories_and_selection.md
+++ b/docs/guides/data_source/data_source_categories_and_selection.md
@@ -24,6 +24,6 @@ RAGFlow supports many data sources. It is recommended to first select a major ca
**Business systems and tables**: Used to synchronize CRM, tickets, online tables, courses, or operation records. This category is suitable for building business ledgers and service knowledge bases. It includes Salesforce, Airtable, Dingtalk AI Table, Zendesk, and Moodle.
-**General APIs and subscriptions**: Used to connect custom APIs or public subscription feeds. This category is suitable for business systems without standard connectors and for collecting public content. It includes REST API and RSS.
+**General APIs and subscriptions**: Used to connect custom APIs, X search results, or public subscription feeds. This category is suitable for business systems without standard connectors and for collecting public content. It includes REST API, Xquik, and RSS.
Account version note: In this manual, **Personal Edition** and **Enterprise Edition** refer to the external system account or service version, not the RAGFlow license. Whether synchronization is available ultimately depends on whether the external system allows the current account to access the target content and API.
diff --git a/docs/guides/data_source/data_source_configuration.md b/docs/guides/data_source/data_source_configuration.md
index a22487acf7..f7f762fea8 100644
--- a/docs/guides/data_source/data_source_configuration.md
+++ b/docs/guides/data_source/data_source_configuration.md
@@ -663,6 +663,26 @@ The REST API data source is used to synchronize data returned by custom business
![REST API](https://raw.githubusercontent.com/infiniflow/ragflow-docs/2ee87008723d56cb6ebf0e9c92f6ef2ad1a45254/images/REST_API.jpg)
+## Xquik
+
+The Xquik data source searches public X posts and syncs each matching post into a RAGFlow knowledge base. Use it to retrieve posts by keyword, hashtag, author, language, or another supported X search operator.
+
+**Permission requirements**: Create an [Xquik API key](https://docs.xquik.com/api-reference/authentication). The key needs access to the Search Tweets API.
+
+**Usage requirements**: Each returned post uses 1 Xquik credit. The page size and maximum page count bound each sync. Xquik is an independent third-party service.
+
+**Configuration parameters**:
+
+- **Name**: Choose a name for this connection.
+- **Xquik API key**: Enter the key in the password field.
+- **X search query**: Enter keywords, hashtags, or operators such as `from:username`.
+- **Result order**: Select **Latest** for chronological results or **Top** for ranked results.
+- **Posts per page**: Set the maximum posts requested per API page.
+- **Max pages**: Stop each sync after this many pages.
+- **Batch size**: Set the number of posts sent to RAGFlow per batch.
+
+RAGFlow sends each incremental sync window to Xquik as inclusive `sinceTime` and exclusive `untilTime` bounds. Cursor pagination continues until no page remains or the configured maximum is reached.
+
## RSS
The RSS data source is used to subscribe public websites, blogs, announcements, or product updates to a RAGFlow knowledge base. After configuration, the knowledge base can continuously obtain new content from the subscription source, making it convenient for users to view and ask questions in a unified way.
diff --git a/internal/syncer/connector/builtin.go b/internal/syncer/connector/builtin.go
index eb4fb352f2..9290d2ebcc 100644
--- a/internal/syncer/connector/builtin.go
+++ b/internal/syncer/connector/builtin.go
@@ -46,6 +46,7 @@ func RegisterBuiltIns(registry *Registry) {
registerBuiltIn(registry, "outlook", NewOutlookConnector)
registerBuiltIn(registry, "notion", NewNotionConnector)
registerBuiltIn(registry, "rest_api", NewRestAPIConnector)
+ registerBuiltIn(registry, "xquik", NewXquikConnector)
registerBuiltIn(registry, "moodle", NewMoodleConnector)
registerBuiltIn(registry, "mysql", NewMySQLConnector)
registerBuiltIn(registry, "postgresql", NewPostgreSQLConnector)
diff --git a/internal/syncer/connector/rest_api.go b/internal/syncer/connector/rest_api.go
index 936975238d..c62b234645 100644
--- a/internal/syncer/connector/rest_api.go
+++ b/internal/syncer/connector/rest_api.go
@@ -1105,18 +1105,19 @@ func (c *RestAPIConnector) applyCursorPagination(params map[string]any, cursor s
// restAPIItemIterator mirrors _iter_items: it walks pages applying the
// configured pagination and stopping when the source reports no more items.
type restAPIItemIterator struct {
- c *RestAPIConnector
- pageCount int
- page int
- offset int
- limit int
- perPage int
- cursor string
- finished bool
+ c *RestAPIConnector
+ pageCount int
+ page int
+ offset int
+ limit int
+ perPage int
+ cursor string
+ seenCursors map[string]struct{}
+ finished bool
}
func newRestAPIItemIterator(c *RestAPIConnector) *restAPIItemIterator {
- it := &restAPIItemIterator{c: c}
+ it := &restAPIItemIterator{c: c, seenCursors: map[string]struct{}{}}
if perPage, err := c.resolvePageSize(); err == nil {
it.perPage = perPage
} else {
@@ -1138,6 +1139,9 @@ func newRestAPIItemIterator(c *RestAPIConnector) *restAPIItemIterator {
it.limit = it.perPage
}
it.cursor = strings.TrimSpace(stringConfig(c.cfg.PaginationConfig["initial_cursor"]))
+ if it.cursor != "" {
+ it.seenCursors[it.cursor] = struct{}{}
+ }
return it
}
@@ -1178,7 +1182,8 @@ func (it *restAPIItemIterator) nextPage(ctx context.Context) ([]map[string]any,
}
items := restAPIExtractItems(response, it.c.cfg.ItemsPath)
- if len(items) == 0 {
+ hasNext, reportsHasNext := restAPIExtractHasNextPage(response, it.c.cfg.PaginationConfig)
+ if len(items) == 0 && !(it.c.cfg.PaginationType == restAPIPaginationCursor && reportsHasNext && hasNext) {
it.finished = true
return nil, nil
}
@@ -1200,10 +1205,17 @@ func (it *restAPIItemIterator) nextPage(ctx context.Context) ([]map[string]any,
it.offset += it.limit
}
case restAPIPaginationCursor:
+ if reportsHasNext && !hasNext {
+ it.finished = true
+ break
+ }
next := restAPIExtractNextCursor(response, it.c.cfg.PaginationConfig)
if next == "" {
it.finished = true
+ } else if _, repeated := it.seenCursors[next]; repeated {
+ it.finished = true
} else {
+ it.seenCursors[next] = struct{}{}
it.cursor = next
}
}
@@ -1279,6 +1291,19 @@ func restAPIExtractItems(response any, itemsPath string) []map[string]any {
return out
}
+func restAPIExtractHasNextPage(response any, paginationConfig map[string]any) (bool, bool) {
+ field := strings.TrimSpace(stringConfig(paginationConfig["has_next_page_field"]))
+ if field == "" {
+ return false, false
+ }
+ dict, ok := response.(map[string]any)
+ if !ok {
+ return false, false
+ }
+ value, ok := dict[field].(bool)
+ return value, ok
+}
+
// restAPIExtractNextCursor mirrors _extract_next_cursor.
func restAPIExtractNextCursor(response any, paginationConfig map[string]any) string {
cursorPath := strings.TrimSpace(stringConfig(paginationConfig["next_cursor_path"]))
diff --git a/internal/syncer/connector/xquik.go b/internal/syncer/connector/xquik.go
new file mode 100644
index 0000000000..71bcbfcfe8
--- /dev/null
+++ b/internal/syncer/connector/xquik.go
@@ -0,0 +1,220 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package connector
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+)
+
+const (
+ xquikSearchURL = "https://xquik.com/api/v1/x/tweets/search"
+ xquikDefaultPageSize = 100
+ xquikDefaultMaxPages = 10
+ xquikDefaultBatchSize = 32
+ xquikMaxPageSize = 10000
+ xquikMaxPages = 1000
+)
+
+type xquikConfig struct {
+ apiKey string
+ query string
+ queryType string
+ pageSize int
+ maxPages int
+ batchSize int
+ requestDelay float64
+}
+
+// XquikConnector searches X posts through Xquik and maps them into RAGFlow documents.
+type XquikConnector struct {
+ cfg xquikConfig
+ baseURL string
+}
+
+// NewXquikConnector creates an Xquik connector from stored settings.
+func NewXquikConnector(config map[string]any) (*XquikConnector, error) {
+ credentials := configAnyMap(config["credentials"])
+ apiKey := strings.TrimSpace(stringConfig(credentials["xquik_api_key"]))
+ if apiKey == "" {
+ return nil, &ConnectorMissingCredentialError{Message: "Xquik connector requires 'xquik_api_key' in credentials"}
+ }
+
+ query := strings.TrimSpace(stringConfig(config["query"]))
+ if query == "" {
+ return nil, &ConnectorValidationError{Message: "Xquik connector query is required"}
+ }
+
+ queryType, err := normalizeXquikQueryType(stringConfig(config["query_type"]))
+ if err != nil {
+ return nil, err
+ }
+ pageSize, err := xquikPositiveInt(config["page_size"], xquikDefaultPageSize, "page_size", xquikMaxPageSize)
+ if err != nil {
+ return nil, err
+ }
+ maxPages, err := xquikPositiveInt(config["max_pages"], xquikDefaultMaxPages, "max_pages", xquikMaxPages)
+ if err != nil {
+ return nil, err
+ }
+ batchSize, err := xquikPositiveInt(config["batch_size"], xquikDefaultBatchSize, "batch_size", 0)
+ if err != nil {
+ return nil, err
+ }
+ requestDelay := restAPIConfigFloat(config["request_delay"])
+ if requestDelay < 0 {
+ if config["request_delay"] != nil && strings.TrimSpace(stringConfig(config["request_delay"])) != "" {
+ return nil, &ConnectorValidationError{Message: "Xquik connector request_delay must be a non-negative number"}
+ }
+ requestDelay = restAPIDefaultRequestDelay
+ }
+
+ return &XquikConnector{
+ cfg: xquikConfig{
+ apiKey: apiKey,
+ query: query,
+ queryType: queryType,
+ pageSize: pageSize,
+ maxPages: maxPages,
+ batchSize: batchSize,
+ requestDelay: requestDelay,
+ },
+ baseURL: xquikSearchURL,
+ }, nil
+}
+
+func normalizeXquikQueryType(value string) (string, error) {
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case "", "latest":
+ return "Latest", nil
+ case "top":
+ return "Top", nil
+ default:
+ return "", &ConnectorValidationError{Message: "Xquik connector query_type must be Latest or Top"}
+ }
+}
+
+func xquikPositiveInt(value any, defaultValue int, field string, maximum int) (int, error) {
+ if value == nil || strings.TrimSpace(stringConfig(value)) == "" {
+ return defaultValue, nil
+ }
+ parsed, ok := restAPIConfigInt(value)
+ if !ok || parsed <= 0 || maximum > 0 && parsed > maximum {
+ rangeText := "a positive integer"
+ if maximum > 0 {
+ rangeText = fmt.Sprintf("from 1 to %d", maximum)
+ }
+ return 0, &ConnectorValidationError{Message: fmt.Sprintf("Xquik connector %s must be %s", field, rangeText)}
+ }
+ return parsed, nil
+}
+
+// Validate checks Xquik settings without network I/O.
+func (c *XquikConnector) Validate(ctx context.Context) error {
+ if c == nil {
+ return &ConnectorValidationError{Message: "Xquik connector is nil"}
+ }
+ if c.cfg.apiKey == "" {
+ return &ConnectorMissingCredentialError{Message: "Xquik connector requires 'xquik_api_key' in credentials"}
+ }
+ return nil
+}
+
+// ValidateConnectorSetting checks credentials with a one-post request.
+func (c *XquikConnector) ValidateConnectorSetting(ctx context.Context, request map[string]any) error {
+ ctx, cancel := context.WithTimeout(ctx, connectorSettingValidationTimeout)
+ defer cancel()
+ delegate, err := c.restConnector(SyncRequest{}, true)
+ if err != nil {
+ return err
+ }
+ return delegate.ValidateLive(ctx)
+}
+
+// OpenSync opens a cursor-paginated Xquik search session.
+func (c *XquikConnector) OpenSync(ctx context.Context, request SyncRequest) (SyncSession, error) {
+ delegate, err := c.restConnector(request, false)
+ if err != nil {
+ return nil, err
+ }
+ return delegate.OpenSync(ctx, request)
+}
+
+// OpenPrune reports that X search cannot enumerate a complete deletion snapshot.
+func (c *XquikConnector) OpenPrune(ctx context.Context, request PruneRequest) (PruneSession, error) {
+ return nil, ErrPruneUnsupported
+}
+
+func (c *XquikConnector) restConnector(request SyncRequest, validation bool) (*RestAPIConnector, error) {
+ limit := c.cfg.pageSize
+ paginationType := restAPIPaginationCursor
+ maxPages := c.cfg.maxPages
+ if validation {
+ limit = 1
+ paginationType = restAPIPaginationNone
+ maxPages = 1
+ }
+
+ queryParams := map[string]any{
+ "q": c.cfg.query,
+ "queryType": c.cfg.queryType,
+ "limit": limit,
+ }
+ if !validation {
+ if !request.FromBeginning && request.WindowStart != nil {
+ queryParams["sinceTime"] = request.WindowStart.UTC().Format(time.RFC3339Nano)
+ }
+ if !request.WindowEnd.IsZero() {
+ queryParams["untilTime"] = request.WindowEnd.UTC().Format(time.RFC3339Nano)
+ }
+ }
+
+ return NewRestAPIConnector(map[string]any{
+ "url": c.baseURL,
+ "method": "GET",
+ "query_params": queryParams,
+ "auth_type": restAPIAuthAPIKeyHeader,
+ "auth_config": map[string]any{
+ "header_name": "x-api-key",
+ },
+ "credentials": map[string]any{
+ "api_key": c.cfg.apiKey,
+ },
+ "items_path": "$.tweets",
+ "id_field": "id",
+ "content_fields": "text,author.username,createdAt,url",
+ "metadata_fields": strings.Join([]string{
+ "id", "createdAt", "url", "lang", "author.id", "author.username", "author.name",
+ "author.verified", "likeCount", "replyCount", "retweetCount", "quoteCount",
+ "viewCount", "bookmarkCount", "media[*].mediaUrl",
+ }, ","),
+ "pagination_type": paginationType,
+ "pagination_config": map[string]any{
+ "cursor_param": "cursor",
+ "next_cursor_field": "next_cursor",
+ "has_next_page_field": "has_next_page",
+ "page_size": c.cfg.pageSize,
+ },
+ "poll_timestamp_field": "createdAt",
+ "batch_size": c.cfg.batchSize,
+ "max_pages": maxPages,
+ "request_delay": c.cfg.requestDelay,
+ "content_template": "Author: @{author_username}\nPublished: {createdAt}\nURL: {url}\n\n{text}",
+ })
+}
diff --git a/internal/syncer/connector/xquik_test.go b/internal/syncer/connector/xquik_test.go
new file mode 100644
index 0000000000..80a5df7d4d
--- /dev/null
+++ b/internal/syncer/connector/xquik_test.go
@@ -0,0 +1,334 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package connector
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+func validXquikConfig() map[string]any {
+ return map[string]any{
+ "query": "ragflow lang:en",
+ "query_type": "Top",
+ "page_size": 2,
+ "max_pages": 5,
+ "batch_size": 2,
+ "request_delay": 0,
+ "credentials": map[string]any{
+ "xquik_api_key": "xq_test_key",
+ },
+ }
+}
+
+func newXquikTestConnector(t *testing.T, config map[string]any) *XquikConnector {
+ t.Helper()
+ connector, err := NewXquikConnector(config)
+ if err != nil {
+ t.Fatalf("NewXquikConnector: %v", err)
+ }
+ return connector
+}
+
+func withXquikTestServer(t *testing.T, connector *XquikConnector, handler http.Handler) *httptest.Server {
+ t.Helper()
+ server := httptest.NewServer(handler)
+ previous := restAPISSRFAllowLoopback
+ restAPISSRFAllowLoopback = true
+ connector.baseURL = server.URL
+ t.Cleanup(func() {
+ restAPISSRFAllowLoopback = previous
+ server.Close()
+ })
+ return server
+}
+
+func TestNewXquikConnectorValidatesConfiguration(t *testing.T) {
+ tests := []struct {
+ name string
+ mutate func(map[string]any)
+ want string
+ }{
+ {name: "missing key", mutate: func(config map[string]any) { config["credentials"] = map[string]any{} }, want: "xquik_api_key"},
+ {name: "missing query", mutate: func(config map[string]any) { config["query"] = " " }, want: "query is required"},
+ {name: "bad query type", mutate: func(config map[string]any) { config["query_type"] = "Popular" }, want: "Latest or Top"},
+ {name: "page size too large", mutate: func(config map[string]any) { config["page_size"] = 10001 }, want: "page_size must be from 1 to 10000"},
+ {name: "max pages too large", mutate: func(config map[string]any) { config["max_pages"] = 1001 }, want: "max_pages must be from 1 to 1000"},
+ {name: "negative delay", mutate: func(config map[string]any) { config["request_delay"] = -1 }, want: "request_delay must be a non-negative number"},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ config := validXquikConfig()
+ test.mutate(config)
+ _, err := NewXquikConnector(config)
+ if err == nil || !strings.Contains(err.Error(), test.want) {
+ t.Fatalf("error = %v, want text %q", err, test.want)
+ }
+ })
+ }
+}
+
+func TestXquikOpenSyncUsesWindowAndResumesCursor(t *testing.T) {
+ connector := newXquikTestConnector(t, validXquikConfig())
+ var (
+ mu sync.Mutex
+ requests []url.Values
+ )
+ withXquikTestServer(t, connector, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("x-api-key"); got != "xq_test_key" {
+ t.Errorf("x-api-key = %q, want test key", got)
+ }
+ mu.Lock()
+ requests = append(requests, r.URL.Query())
+ mu.Unlock()
+
+ response := map[string]any{
+ "tweets": []any{
+ map[string]any{
+ "id": "101",
+ "text": "First post",
+ "createdAt": "2026-08-24T10:15:00Z",
+ "url": "https://x.com/alice/status/101",
+ "lang": "en",
+ "author": map[string]any{
+ "id": "1", "username": "alice", "name": "Alice", "verified": true,
+ },
+ "likeCount": 4,
+ },
+ map[string]any{
+ "id": "102",
+ "text": "Second post",
+ "createdAt": "2026-08-24T11:15:00Z",
+ "url": "https://x.com/bob/status/102",
+ "author": map[string]any{"id": "2", "username": "bob", "name": "Bob"},
+ },
+ },
+ "has_next_page": true,
+ "next_cursor": "cursor-2",
+ }
+ if r.URL.Query().Get("cursor") == "cursor-2" {
+ response = map[string]any{
+ "tweets": []any{
+ map[string]any{
+ "id": "103",
+ "text": "Third post",
+ "createdAt": "2026-08-24T12:15:00Z",
+ "url": "https://x.com/cara/status/103",
+ "author": map[string]any{"id": "3", "username": "cara", "name": "Cara"},
+ },
+ },
+ "has_next_page": false,
+ "next_cursor": "",
+ }
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(response); err != nil {
+ t.Errorf("encode response: %v", err)
+ }
+ }))
+
+ windowStart := time.Date(2026, 8, 24, 10, 0, 0, 0, time.UTC)
+ windowEnd := time.Date(2026, 8, 25, 0, 0, 0, 0, time.UTC)
+ session, err := connector.OpenSync(context.Background(), SyncRequest{
+ WindowStart: &windowStart,
+ WindowEnd: windowEnd,
+ })
+ if err != nil {
+ t.Fatalf("OpenSync: %v", err)
+ }
+ first, err := session.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("NextBatch: %v", err)
+ }
+ if err := session.Close(); err != nil {
+ t.Fatalf("Close: %v", err)
+ }
+ if len(first.Documents) != 2 {
+ t.Fatalf("first documents = %d, want 2", len(first.Documents))
+ }
+ if got := string(first.Documents[0].Blob); got != "Author: @alice\nPublished: 2026-08-24T10:15:00Z\nURL: https://x.com/alice/status/101\n\nFirst post" {
+ t.Fatalf("first document body = %q", got)
+ }
+ if got := first.Documents[0].Metadata["author.username"]; got != "alice" {
+ t.Fatalf("author metadata = %v, want alice", got)
+ }
+ if first.Checkpoint == nil {
+ t.Fatal("first checkpoint is nil")
+ }
+
+ resumed, err := connector.OpenSync(context.Background(), SyncRequest{
+ WindowStart: &windowStart,
+ WindowEnd: windowEnd,
+ Resume: first.Checkpoint,
+ })
+ if err != nil {
+ t.Fatalf("resumed OpenSync: %v", err)
+ }
+ second, err := resumed.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("resumed NextBatch: %v", err)
+ }
+ if err := resumed.Close(); err != nil {
+ t.Fatalf("resumed Close: %v", err)
+ }
+ if len(second.Documents) != 1 || !strings.Contains(string(second.Documents[0].Blob), "Third post") {
+ t.Fatalf("resumed documents = %+v, want third post", second.Documents)
+ }
+
+ mu.Lock()
+ gotRequests := append([]url.Values(nil), requests...)
+ mu.Unlock()
+ if len(gotRequests) != 2 {
+ t.Fatalf("request count = %d, want 2", len(gotRequests))
+ }
+ for _, query := range gotRequests {
+ if query.Get("q") != "ragflow lang:en" || query.Get("queryType") != "Top" || query.Get("limit") != "2" {
+ t.Fatalf("search query = %v", query)
+ }
+ if query.Get("sinceTime") != "2026-08-24T10:00:00Z" || query.Get("untilTime") != "2026-08-25T00:00:00Z" {
+ t.Fatalf("window query = %v", query)
+ }
+ }
+ if gotRequests[0].Get("cursor") != "" || gotRequests[1].Get("cursor") != "cursor-2" {
+ t.Fatalf("cursor sequence = [%q %q]", gotRequests[0].Get("cursor"), gotRequests[1].Get("cursor"))
+ }
+}
+
+func TestXquikValidateConnectorSettingLimitsUsage(t *testing.T) {
+ connector := newXquikTestConnector(t, validXquikConfig())
+ var captured url.Values
+ withXquikTestServer(t, connector, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ captured = r.URL.Query()
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(map[string]any{"tweets": []any{}, "has_next_page": false, "next_cursor": ""}); err != nil {
+ t.Errorf("encode response: %v", err)
+ }
+ }))
+ if err := connector.ValidateConnectorSetting(context.Background(), nil); err != nil {
+ t.Fatalf("ValidateConnectorSetting: %v", err)
+ }
+ if captured.Get("limit") != "1" {
+ t.Fatalf("validation limit = %q, want 1", captured.Get("limit"))
+ }
+ if captured.Get("cursor") != "" || captured.Get("sinceTime") != "" || captured.Get("untilTime") != "" {
+ t.Fatalf("validation query = %v", captured)
+ }
+}
+
+func TestXquikContinuesAfterEmptyPageWhenResponseHasMore(t *testing.T) {
+ connector := newXquikTestConnector(t, validXquikConfig())
+ requests := 0
+ withXquikTestServer(t, connector, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ response := map[string]any{
+ "tweets": []any{},
+ "has_next_page": true,
+ "next_cursor": "cursor-2",
+ }
+ if r.URL.Query().Get("cursor") == "cursor-2" {
+ response = map[string]any{
+ "tweets": []any{map[string]any{
+ "id": "101",
+ "text": "Older post",
+ "createdAt": "2026-08-24T12:00:00Z",
+ }},
+ "has_next_page": false,
+ "next_cursor": "ignored-cursor",
+ }
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(response); err != nil {
+ t.Errorf("encode response: %v", err)
+ }
+ }))
+
+ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true})
+ if err != nil {
+ t.Fatalf("OpenSync: %v", err)
+ }
+ defer func() { _ = session.Close() }()
+ batch, err := session.NextBatch(context.Background())
+ if err != nil {
+ t.Fatalf("NextBatch: %v", err)
+ }
+ if len(batch.Documents) != 1 || !strings.Contains(string(batch.Documents[0].Blob), "Older post") {
+ t.Fatalf("documents = %+v, want older post", batch.Documents)
+ }
+ if _, err = session.NextBatch(context.Background()); !errors.Is(err, io.EOF) {
+ t.Fatalf("second NextBatch error = %v, want EOF", err)
+ }
+ if requests != 2 {
+ t.Fatalf("requests = %d, want 2", requests)
+ }
+}
+
+func TestXquikStopsAfterRepeatedCursor(t *testing.T) {
+ config := validXquikConfig()
+ config["batch_size"] = 1
+ connector := newXquikTestConnector(t, config)
+ requests := 0
+ withXquikTestServer(t, connector, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(map[string]any{
+ "tweets": []any{map[string]any{
+ "id": r.URL.Query().Get("cursor") + "tweet",
+ "text": "Post",
+ "createdAt": "2026-08-24T12:00:00Z",
+ }},
+ "has_next_page": true,
+ "next_cursor": "same-cursor",
+ }); err != nil {
+ t.Errorf("encode response: %v", err)
+ }
+ }))
+
+ session, err := connector.OpenSync(context.Background(), SyncRequest{FromBeginning: true})
+ if err != nil {
+ t.Fatalf("OpenSync: %v", err)
+ }
+ defer func() { _ = session.Close() }()
+ for {
+ _, err = session.NextBatch(context.Background())
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ t.Fatalf("NextBatch: %v", err)
+ }
+ }
+ if requests != 2 {
+ t.Fatalf("requests = %d, want 2 before repeated cursor stops pagination", requests)
+ }
+}
+
+func TestXquikOpenPruneUnsupported(t *testing.T) {
+ connector := newXquikTestConnector(t, validXquikConfig())
+ _, err := connector.OpenPrune(context.Background(), PruneRequest{})
+ if !errors.Is(err, ErrPruneUnsupported) {
+ t.Fatalf("OpenPrune error = %v, want ErrPruneUnsupported", err)
+ }
+}
diff --git a/rag/svr/sync_data_source.py b/rag/svr/sync_data_source.py
index d12aa6873d..1245ecb9dd 100644
--- a/rag/svr/sync_data_source.py
+++ b/rag/svr/sync_data_source.py
@@ -62,6 +62,7 @@ from common.data_source import (
BigQueryConnector,
DingTalkAITableConnector,
RestAPIConnector,
+ XquikConnector,
OneDriveConnector,
OutlookConnector,
AzureBlobConnector,
@@ -2197,6 +2198,24 @@ class REST_API(SyncBase):
return document_generator
+class Xquik(SyncBase):
+ SOURCE_NAME: str = FileSource.XQUIK
+
+ async def _generate(self, task: dict):
+ poll_start = task.get("poll_range_start")
+ end_time = datetime.now(timezone.utc)
+ incremental = task.get("reindex") != "1" and poll_start is not None
+
+ self.connector = XquikConnector.from_config(
+ self.conf,
+ since_time=poll_start if incremental else None,
+ until_time=end_time,
+ )
+ document_generator = self.connector.poll_source(poll_start.timestamp(), end_time.timestamp()) if incremental else self.connector.load_from_state()
+ self.log_connection("Xquik", "X search", task)
+ return document_generator
+
+
func_factory = {
FileSource.RSS: RSS,
FileSource.S3: S3,
@@ -2234,6 +2253,7 @@ func_factory = {
FileSource.BIGQUERY: BigQuery,
FileSource.DINGTALK_AI_TABLE: DingTalkAITable,
FileSource.REST_API: REST_API,
+ FileSource.XQUIK: Xquik,
}
diff --git a/test/unit_test/data_source/test_xquik_connector.py b/test/unit_test/data_source/test_xquik_connector.py
new file mode 100644
index 0000000000..b5708df9c6
--- /dev/null
+++ b/test/unit_test/data_source/test_xquik_connector.py
@@ -0,0 +1,197 @@
+#
+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import logging
+from datetime import UTC, datetime
+from unittest.mock import patch
+
+import pytest
+
+from common.data_source.config import DocumentSource
+from common.data_source.exceptions import ConnectorMissingCredentialError, ConnectorValidationError
+from common.data_source.rest_api_connector import PaginationType, RestAPIConnector
+from common.data_source.xquik_connector import XquikConnector
+
+_MOCK_DNS = [(2, 1, 6, "", ("93.184.216.34", 0))]
+
+
+def _config(**overrides):
+ config = {
+ "query": "ragflow lang:en",
+ "query_type": "Top",
+ "page_size": 50,
+ "max_pages": 4,
+ "batch_size": 8,
+ "request_delay": 0,
+ "credentials": {"xquik_api_key": "xq_test_key"},
+ }
+ config.update(overrides)
+ return config
+
+
+@patch("common.data_source.rest_api_connector.socket.getaddrinfo", return_value=_MOCK_DNS)
+def test_xquik_configures_bounded_search_and_time_window(_dns):
+ start = datetime(2026, 8, 24, 10, 0, tzinfo=UTC)
+ end = datetime(2026, 8, 25, 0, 0, tzinfo=UTC)
+
+ connector = XquikConnector.from_config(_config(), since_time=start, until_time=end)
+
+ assert connector.pagination_type == PaginationType.CURSOR
+ assert connector.max_pages == 4
+ assert connector.batch_size == 8
+ assert connector._explicit_query_params == {
+ "q": "ragflow lang:en",
+ "queryType": "Top",
+ "limit": "50",
+ "sinceTime": "2026-08-24T10:00:00+00:00",
+ "untilTime": "2026-08-25T00:00:00+00:00",
+ }
+ assert connector._auth_headers == {"x-api-key": "xq_test_key"}
+
+
+@patch("common.data_source.rest_api_connector.socket.getaddrinfo", return_value=_MOCK_DNS)
+def test_xquik_validation_fetches_at_most_one_post(_dns):
+ connector = XquikConnector.build_connector(_config(page_size=500, max_pages=50))
+
+ assert connector.pagination_type == PaginationType.NONE
+ assert connector.max_pages == 1
+ assert connector._explicit_query_params["limit"] == "1"
+
+
+@patch("common.data_source.rest_api_connector.socket.getaddrinfo", return_value=_MOCK_DNS)
+def test_xquik_logs_safe_resolved_config(_dns, caplog):
+ caplog.set_level(logging.INFO, logger="common.data_source.xquik_connector")
+
+ XquikConnector.from_config(_config())
+
+ assert "query_type=Top page_size=50 max_pages=4 batch_size=8 request_delay=0.0 validation=False" in caplog.text
+ assert "ragflow lang:en" not in caplog.text
+ assert "xq_test_key" not in caplog.text
+
+
+@patch("common.data_source.rest_api_connector.socket.getaddrinfo", return_value=_MOCK_DNS)
+def test_xquik_maps_post_content_metadata_and_source(_dns):
+ connector = XquikConnector.from_config(_config())
+
+ document = connector._item_to_document(
+ {
+ "id": "101",
+ "text": "First post",
+ "createdAt": "2026-08-24T10:15:00Z",
+ "url": "https://x.com/alice/status/101",
+ "lang": "en",
+ "author": {"id": "1", "username": "alice", "name": "Alice", "verified": True},
+ "likeCount": 4,
+ "media": [{"mediaUrl": "https://pbs.twimg.com/media/example.jpg"}],
+ }
+ )
+
+ assert document.source == DocumentSource.XQUIK
+ assert document.blob.decode() == ("Author: @alice\nPublished: 2026-08-24T10:15:00Z\nURL: https://x.com/alice/status/101\n\nFirst post")
+ assert document.doc_updated_at == datetime(2026, 8, 24, 10, 15, tzinfo=UTC)
+ assert document.metadata["author.username"] == "alice"
+ assert document.metadata["media[*].mediaUrl"] == "https://pbs.twimg.com/media/example.jpg"
+
+
+@patch("common.data_source.rest_api_connector.socket.getaddrinfo", return_value=_MOCK_DNS)
+def test_xquik_continues_after_empty_page_when_response_has_more(_dns):
+ connector = XquikConnector.from_config(_config())
+ responses = iter(
+ [
+ {"tweets": [], "has_next_page": True, "next_cursor": "cursor-2"},
+ {
+ "tweets": [{"id": "101", "text": "Older post"}],
+ "has_next_page": False,
+ "next_cursor": "ignored-cursor",
+ },
+ ]
+ )
+ requests = []
+
+ def fetch_page(params):
+ requests.append(dict(params))
+ return next(responses)
+
+ connector._fetch_page = fetch_page
+
+ items = list(connector._iter_items())
+
+ assert items == [{"id": "101", "text": "Older post"}]
+ assert requests == [{}, {"cursor": "cursor-2"}]
+
+
+ ("override", "error_type", "message"),
+ [
+ ({"query": ""}, ConnectorValidationError, "query is required"),
+ ({"query_type": "Popular"}, ConnectorValidationError, "Latest or Top"),
+ ({"page_size": 1.5}, ConnectorValidationError, "positive integer"),
+ ({"page_size": 10_001}, ConnectorValidationError, "from 1 to 10000"),
+ ({"max_pages": 1_001}, ConnectorValidationError, "from 1 to 1000"),
+ ({"request_delay": -1}, ConnectorValidationError, "non-negative"),
+ ({"request_delay": float("inf")}, ConnectorValidationError, "non-negative"),
+ ({"credentials": {}}, ConnectorMissingCredentialError, "xquik_api_key"),
+ ],
+)
+def test_xquik_rejects_invalid_config(override, error_type, message):
+ with pytest.raises(error_type, match=message):
+ XquikConnector.from_config(_config(**override))
+
+
+@patch("common.data_source.rest_api_connector.socket.getaddrinfo", return_value=_MOCK_DNS)
+def test_rest_api_cursor_stops_when_provider_repeats_cursor(_dns):
+ connector = RestAPIConnector(
+ url="https://api.example.com/items",
+ content_fields=["title"],
+ pagination_type=PaginationType.CURSOR,
+ pagination_config={"next_cursor_field": "next_cursor"},
+ max_pages=20,
+ request_delay=0,
+ )
+ requests = []
+
+ def fetch_page(params):
+ requests.append(dict(params))
+ return {"items": [{"title": "Page"}], "next_cursor": "same-cursor"}
+
+ connector._fetch_page = fetch_page
+
+ items = list(connector._iter_items())
+
+ assert len(items) == 2
+ assert requests == [{}, {"cursor": "same-cursor"}]
+
+
+@patch("common.data_source.rest_api_connector.socket.getaddrinfo", return_value=_MOCK_DNS)
+def test_rest_api_normalizes_numeric_initial_cursor_before_cycle_check(_dns):
+ connector = RestAPIConnector(
+ url="https://api.example.com/items",
+ content_fields=["title"],
+ pagination_type=PaginationType.CURSOR,
+ pagination_config={"initial_cursor": 123, "next_cursor_field": "next_cursor"},
+ max_pages=20,
+ request_delay=0,
+ )
+ requests = []
+
+ def fetch_page(params):
+ requests.append(dict(params))
+ return {"items": [{"title": "Page"}], "next_cursor": 123}
+
+ connector._fetch_page = fetch_page
+
+ assert len(list(connector._iter_items())) == 1
+ assert requests == [{"cursor": "123"}]
diff --git a/test/unit_test/rag/test_sync_data_source.py b/test/unit_test/rag/test_sync_data_source.py
index c8b6db1287..d08210cb4c 100644
--- a/test/unit_test/rag/test_sync_data_source.py
+++ b/test/unit_test/rag/test_sync_data_source.py
@@ -361,6 +361,79 @@ async def test_rdbms_generate_keeps_deleted_file_snapshot_without_timestamp_colu
assert list(document_generator) == [["full-sync"]]
+class _FakeXquikConnector:
+ def __init__(self):
+ self.poll_args = None
+ self.loaded = False
+
+ def poll_source(self, start, end):
+ self.poll_args = (start, end)
+ return iter((["incremental"],))
+
+ def load_from_state(self):
+ self.loaded = True
+ return iter((["full"],))
+
+
+async def test_xquik_generate_applies_incremental_window(monkeypatch):
+ captured = {}
+ fake_connector = _FakeXquikConnector()
+
+ def _from_config(config, **kwargs):
+ captured["config"] = config
+ captured.update(kwargs)
+ return fake_connector
+
+ monkeypatch.setattr(sync_data_source.XquikConnector, "from_config", _from_config)
+ poll_start = datetime(2026, 8, 24, 10, 0, tzinfo=timezone.utc)
+ task = {
+ **_make_task(),
+ "reindex": "0",
+ "poll_range_start": poll_start,
+ "skip_connection_log": True,
+ }
+ config = {
+ "query": "ragflow",
+ "credentials": {"xquik_api_key": "xq_test_key"},
+ }
+
+ generator = await sync_data_source.Xquik(config)._generate(task)
+
+ assert list(generator) == [["incremental"]]
+ assert captured["config"] == config
+ assert captured["since_time"] == poll_start
+ assert captured["until_time"].tzinfo == timezone.utc
+ assert fake_connector.poll_args[0] == poll_start.timestamp()
+ assert fake_connector.poll_args[1] == captured["until_time"].timestamp()
+
+
+async def test_xquik_generate_full_sync_omits_lower_bound(monkeypatch):
+ captured = {}
+ fake_connector = _FakeXquikConnector()
+
+ def _from_config(config, **kwargs):
+ captured.update(kwargs)
+ return fake_connector
+
+ monkeypatch.setattr(sync_data_source.XquikConnector, "from_config", _from_config)
+ task = {
+ **_make_task(),
+ "reindex": "1",
+ "skip_connection_log": True,
+ }
+
+ generator = await sync_data_source.Xquik({"query": "ragflow"})._generate(task)
+
+ assert list(generator) == [["full"]]
+ assert captured["since_time"] is None
+ assert captured["until_time"].tzinfo == timezone.utc
+ assert fake_connector.loaded is True
+
+
@pytest.mark.asyncio
@pytest.mark.p2
async def test_rdbms_cursor_persists_only_after_success(monkeypatch):
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index adbca74b49..7acb52b962 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -1318,6 +1318,10 @@ This auto-tagging feature enhances retrieval by adding another layer of domain-s
dataSourceFieldDiscordBotToken: 'Discord Bot Token',
dataSourceFieldServerIds: 'Server IDs',
dataSourceFieldChannels: 'Channels',
+ dataSourceFieldXquikApiKey: 'Xquik API key',
+ dataSourceFieldXquikQuery: 'X search query',
+ dataSourceFieldXquikQueryType: 'Result order',
+ dataSourceFieldXquikPageSize: 'Posts per page',
dataSourceFieldPrimaryAdminEmail: 'Primary Admin Email',
dataSourceFieldOauthTokenJson: 'OAuth Token JSON',
dataSourceFieldMyDriveEmails: 'My Drive Emails',
@@ -1753,6 +1757,18 @@ Example: Virtual Hosted Style`,
'Optional per-query job timeout in milliseconds.',
rest_apiDescription:
'Connect any REST API endpoint as a data source using a flexible, configuration-driven connector.',
+ xquikDescription:
+ 'Search X posts with Xquik and sync matching posts into a knowledge base.',
+ xquikApiKeyTip:
+ 'Create an Xquik API key and store it only in this password field.',
+ xquikQueryTip:
+ 'Use keywords, hashtags, or X search operators such as from:username.',
+ xquikPageSizeTip:
+ 'Maximum posts requested per API page. Each returned post uses 1 Xquik credit.',
+ xquikMaxPagesTip:
+ 'Stop each sync after this many pages to bound API usage.',
+ xquikPageSizeValidation: 'Posts Per Page must be from 1 to 10000.',
+ xquikMaxPagesValidation: 'Max Pages must be from 1 to 1000.',
onedriveDescription:
'Connect OneDrive or OneDrive for Business to index files and folders via Microsoft Graph delta queries.',
onedriveTenantIdTip:
diff --git a/web/src/pages/user-setting/data-source/constant/index.test.tsx b/web/src/pages/user-setting/data-source/constant/index.test.tsx
new file mode 100644
index 0000000000..af263583d2
--- /dev/null
+++ b/web/src/pages/user-setting/data-source/constant/index.test.tsx
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { TFunction } from 'i18next';
+import { FormFieldType } from '@/components/dynamic-form';
+import {
+ DataSourceFormDefaultValues,
+ DataSourceKey,
+ generateDataSourceInfo,
+ getDataSourceFieldsWithExtras,
+} from './index';
+
+const translate = ((key: string) => key) as TFunction;
+
+describe('Xquik data source', () => {
+ it('registers its catalog entry and defaults', () => {
+ const info = generateDataSourceInfo(translate)[DataSourceKey.XQUIK];
+ const defaults = DataSourceFormDefaultValues[DataSourceKey.XQUIK];
+
+ expect(info.name).toBe('Xquik');
+ expect(info.description).toBe('setting.xquikDescription');
+ expect(defaults).toEqual({
+ name: '',
+ source: 'xquik',
+ config: {
+ query: '',
+ query_type: 'Latest',
+ page_size: 100,
+ max_pages: 10,
+ batch_size: 32,
+ request_delay: 0.5,
+ credentials: { xquik_api_key: '' },
+ },
+ });
+ });
+
+ it('keeps the API key secret and bounds page usage', () => {
+ const fields = getDataSourceFieldsWithExtras(
+ translate,
+ DataSourceKey.XQUIK,
+ ) as Array<{
+ name: string;
+ type?: FormFieldType;
+ required?: boolean;
+ validation?: { min?: number; max?: number };
+ }>;
+ const apiKey = fields.find(
+ (field) => field.name === 'config.credentials.xquik_api_key',
+ );
+ const pageSize = fields.find((field) => field.name === 'config.page_size');
+ const maxPages = fields.find((field) => field.name === 'config.max_pages');
+
+ expect(apiKey?.type).toBe(FormFieldType.Password);
+ expect(apiKey?.required).toBe(true);
+ expect(pageSize?.validation).toMatchObject({ min: 1, max: 10000 });
+ expect(maxPages?.validation).toMatchObject({ min: 1, max: 1000 });
+ });
+});
diff --git a/web/src/pages/user-setting/data-source/constant/index.tsx b/web/src/pages/user-setting/data-source/constant/index.tsx
index 7e4cbb0a01..4932a3263f 100644
--- a/web/src/pages/user-setting/data-source/constant/index.tsx
+++ b/web/src/pages/user-setting/data-source/constant/index.tsx
@@ -18,7 +18,7 @@ import { FormFieldType } from '@/components/dynamic-form';
import { IconFontFill } from '@/components/icon-font';
import SvgIcon from '@/components/svg-icon';
import { TFunction } from 'i18next';
-import { Mail, Rss } from 'lucide-react';
+import { Mail, Rss, Search } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import BoxTokenField from '../component/box-token-field';
@@ -50,6 +50,7 @@ export enum DataSourceKey {
GITHUB = 'github',
MOODLE = 'moodle',
DISCORD = 'discord',
+ XQUIK = 'xquik',
ZENDESK = 'zendesk',
WEBDAV = 'webdav',
AIRTABLE = 'airtable',
@@ -237,6 +238,11 @@ export const generateDataSourceInfo = (t: TFunction) => {
description: t(`setting.${DataSourceKey.DISCORD}Description`),
icon: <SvgIcon name={'data-source/discord'} width={38} />,
},
+ [DataSourceKey.XQUIK]: {
+ name: 'Xquik',
+ description: t(`setting.${DataSourceKey.XQUIK}Description`),
+ icon: <Search className="text-text-primary" size={22} />,
+ },
[DataSourceKey.CONFLUENCE]: {
name: 'Confluence',
description: t(`setting.${DataSourceKey.CONFLUENCE}Description`),
@@ -890,6 +896,73 @@ const generateDataSourceFormFields = (t: TFunction) => ({
required: false,
},
],
+ [DataSourceKey.XQUIK]: [
+ {
+ label: t('setting.dataSourceFieldXquikApiKey'),
+ name: 'config.credentials.xquik_api_key',
+ type: FormFieldType.Password,
+ required: true,
+ tooltip: t('setting.xquikApiKeyTip'),
+ },
+ {
+ label: t('setting.dataSourceFieldXquikQuery'),
+ name: 'config.query',
+ type: FormFieldType.Text,
+ required: true,
+ placeholder: 'ragflow lang:en',
+ tooltip: t('setting.xquikQueryTip'),
+ },
+ {
+ label: t('setting.dataSourceFieldXquikQueryType'),
+ name: 'config.query_type',
+ type: FormFieldType.Select,
+ required: true,
+ options: [
+ { label: 'Latest', value: 'Latest' },
+ { label: 'Top', value: 'Top' },
+ ],
+ defaultValue: 'Latest',
+ },
+ {
+ label: t('setting.dataSourceFieldXquikPageSize'),
+ name: 'config.page_size',
+ type: FormFieldType.Number,
+ required: true,
+ defaultValue: 100,
+ tooltip: t('setting.xquikPageSizeTip'),
+ validation: {
+ min: 1,
+ max: 10000,
+ message: t('setting.xquikPageSizeValidation'),
+ },
+ },
+ {
+ label: t('setting.dataSourceFieldMaxPages'),
+ name: 'config.max_pages',
+ type: FormFieldType.Number,
+ required: true,
+ defaultValue: 10,
+ tooltip: t('setting.xquikMaxPagesTip'),
+ validation: {
+ min: 1,
+ max: 1000,
+ message: t('setting.xquikMaxPagesValidation'),
+ },
+ },
+ {
+ label: t('setting.dataSourceFieldBatchSize'),
+ name: 'config.batch_size',
+ type: FormFieldType.Number,
+ required: false,
+ defaultValue: 32,
+ validation: {
+ min: 1,
+ message: t('setting.dataSourceValidationMinOne', {
+ label: t('setting.dataSourceFieldBatchSize'),
+ }),
+ },
+ },
+ ],
[DataSourceKey.CONFLUENCE]: confluenceConstant(t),
[DataSourceKey.GOOGLE_DRIVE]: [
@@ -2045,6 +2118,21 @@ export const DataSourceFormDefaultValues = {
},
},
},
+ [DataSourceKey.XQUIK]: {
+ name: '',
+ source: DataSourceKey.XQUIK,
+ config: {
+ query: '',
+ query_type: 'Latest',
+ page_size: 100,
+ max_pages: 10,
+ batch_size: 32,
+ request_delay: 0.5,
+ credentials: {
+ xquik_api_key: '',
+ },
+ },
+ },
[DataSourceKey.CONFLUENCE]: {
name: '',
source: DataSourceKey.CONFLUENCE,