Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(datasource): add DingTalk Docs integration with safe sync and localization (#2313)
DEMO5d3114fc9e57
diff --git a/README.md b/README.mdindex cc51996dd..7664b5c89 100644--- a/README.md+++ b/README.md@@ -57,7 +57,7 @@ https://github.com/user-attachments/assets/19b28ce2-a62f-4f54-b289-c983576259bc*2:25 · 1080p · English narration & captions.*-It is organized around three core capabilities: **RAG-based Quick Q&A** for everyday lookups, a **ReAct Agent** that autonomously orchestrates retrieval, MCP tools, a **tenant skill catalog**, session-persistent **Docker / E2B / Cube sandboxes** and web search to handle complex multi-step tasks, and a brand-new **Wiki Mode** in which agents distill raw documents into a self-maintaining, interlinked markdown knowledge base with an interactive knowledge graph, complete with manual editing, revision history and one-click rollback. **Cross-session long-term memory** remembers who you are and what you keep asking about. Knowledge curation is equally hands-on: a **tree-structured folder view** preserves the directory layout of uploads, and **chunk editing with revision history** lets retrieval chunks be edited, diffed and reverted like documents. Combined with multi-source ingestion (Feishu wiki / Feishu Drive / GitLab / Tencent IMA / Notion / Yuque / RSS, and growing), **website embed widgets** for publishing agents to external sites, **scoped API keys with a principal model** for programmatic integrations, **multi-instance storage backends** per workspace for flexible data placement, 20+ LLM provider integrations (including LiteLLM), full Langfuse observability plus a **runtime task-queue dashboard with worker-pool governance**, **enterprise-ready multi-workspace RBAC** (4-tier role matrix + per-resource ownership + per-workspace audit log), and a fully self-hostable modular architecture, WeKnora turns scattered documents into a queryable, reasoning-capable, continuously evolving knowledge asset.+It is organized around three core capabilities: **RAG-based Quick Q&A** for everyday lookups, a **ReAct Agent** that autonomously orchestrates retrieval, MCP tools, a **tenant skill catalog**, session-persistent **Docker / E2B / Cube sandboxes** and web search to handle complex multi-step tasks, and a brand-new **Wiki Mode** in which agents distill raw documents into a self-maintaining, interlinked markdown knowledge base with an interactive knowledge graph, complete with manual editing, revision history and one-click rollback. **Cross-session long-term memory** remembers who you are and what you keep asking about. Knowledge curation is equally hands-on: a **tree-structured folder view** preserves the directory layout of uploads, and **chunk editing with revision history** lets retrieval chunks be edited, diffed and reverted like documents. Combined with multi-source ingestion (Feishu wiki / Feishu Drive / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS, and growing), **website embed widgets** for publishing agents to external sites, **scoped API keys with a principal model** for programmatic integrations, **multi-instance storage backends** per workspace for flexible data placement, 20+ LLM provider integrations (including LiteLLM), full Langfuse observability plus a **runtime task-queue dashboard with worker-pool governance**, **enterprise-ready multi-workspace RBAC** (4-tier role matrix + per-resource ownership + per-workspace audit log), and a fully self-hostable modular architecture, WeKnora turns scattered documents into a queryable, reasoning-capable, continuously evolving knowledge asset.The framework supports auto-syncing knowledge from Feishu, GitLab, Tencent IMA, Notion, and Yuque (more data sources coming soon), handles 10+ document formats including PDF, Word, images, Excel and XMind, and can serve Q&A directly through IM channels like WeCom, Feishu, Slack, and Telegram. It is compatible with major LLM providers including OpenAI, DeepSeek, Qwen (Alibaba Cloud), Zhipu, Hunyuan, Gemini, MiniMax, NVIDIA, LiteLLM, and Ollama. Office files can be parsed in-process with **anydoc**. Its fully modular design allows swapping LLMs, vector databases, and storage backends, with support for local and private cloud deployment ensuring complete data sovereignty. WeKnora also integrates with **Langfuse** for comprehensive observability into agent reasoning, token usage, and pipeline tracing.@@ -145,7 +145,7 @@ Fully modular pipeline from document parsing, vectorization, and retrieval to LL| Chunk Editing & Revisions | Edit retrieval chunks directly in the UI with per-version snapshots, diff and one-click rollback, and automatic reindexing after an edit; generated questions can be added, edited, deleted and regenerated; custom document metadata supported || Per-Upload Process Config | Override parser, chunking, multimodal (VLM / ASR), graph extraction, and question generation per upload batch via upload-confirm dialog or `process_config` API; reparse with new settings || Batch Reparse | Re-queue parsing for multiple documents at once with optional per-batch `process_config` |-| Data Source Import | Auto-sync from Feishu wiki / Feishu Drive / Lark / GitLab / Tencent IMA / Notion / Yuque / RSS feeds (more data sources coming soon); incremental and full sync |+| Data Source Import | Auto-sync from Feishu wiki / Feishu Drive / Lark / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS feeds (more data sources coming soon); incremental and full sync || Document Formats | PDF / Word / Txt / Markdown / HTML / EPUB / MHTML / Images / CSV / Excel / PPT / JSON / XMind || Auto-Tagging | After parse, pick matching tags from the knowledge base's existing set without creating tags or overwriting manual ones || Retrieval Strategies | BM25 sparse / Dense retrieval / GraphRAG / parent-child chunking / HNSW-accelerated pgvector (1024-dim) / multi-dimensional indexing |diff --git a/README_CN.md b/README_CN.mdindex fc7984eee..1d9c26e02 100644--- a/README_CN.md+++ b/README_CN.md@@ -57,7 +57,7 @@ https://github.com/user-attachments/assets/2819598d-3140-4623-814a-8162a22b653c*2 分 25 秒 · 1080p · 英文旁白,中英字幕。*-框架围绕三大核心能力构建:**RAG 快速问答**适合日常知识查询,**ReAct Agent 智能推理**自主编排知识检索、MCP 工具、**技能目录**、会话级 **Docker / E2B / Cube 沙箱**与网络搜索完成复杂多步任务,全新的 **Wiki 模式**则让 Agent 从原始文档中自治生成相互链接的 Markdown 知识库与可视化知识图谱,并支持人工编辑、版本历史与一键回滚。**跨会话长期记忆**会记住你是谁、你常问什么。知识加工环节也完全可控:**树形文件夹**保留上传目录结构,**分块编辑与版本历史**让检索片段可以像文档一样被修改、比对与回滚。结合多源数据接入(飞书知识库 / 飞书云盘 / GitLab / 腾讯 IMA / Notion / 语雀 / RSS,更多持续接入中)、**网站嵌入 Widget** 将智能体发布到外部站点、**权限范围 API Key 与 Principal 模型**面向程序化集成、**每空间多实例存储后端**灵活编排数据落地、二十余家主流模型厂商集成(含 LiteLLM)、Langfuse 全链路可观测性与**运行时任务队列面板 + Worker 池治理**、**企业级多空间 RBAC(四级角色矩阵 + 资源归属 + 空间审计日志)**,以及完全可私有化部署的模块化架构,WeKnora 帮助团队把分散文档沉淀为可查询、可推理、可持续演进的专属知识资产。+框架围绕三大核心能力构建:**RAG 快速问答**适合日常知识查询,**ReAct Agent 智能推理**自主编排知识检索、MCP 工具、**技能目录**、会话级 **Docker / E2B / Cube 沙箱**与网络搜索完成复杂多步任务,全新的 **Wiki 模式**则让 Agent 从原始文档中自治生成相互链接的 Markdown 知识库与可视化知识图谱,并支持人工编辑、版本历史与一键回滚。**跨会话长期记忆**会记住你是谁、你常问什么。知识加工环节也完全可控:**树形文件夹**保留上传目录结构,**分块编辑与版本历史**让检索片段可以像文档一样被修改、比对与回滚。结合多源数据接入(飞书知识库 / 飞书云盘 / GitLab / 腾讯 IMA / Notion / 语雀 / 钉钉文档 / RSS,更多持续接入中)、**网站嵌入 Widget** 将智能体发布到外部站点、**权限范围 API Key 与 Principal 模型**面向程序化集成、**每空间多实例存储后端**灵活编排数据落地、二十余家主流模型厂商集成(含 LiteLLM)、Langfuse 全链路可观测性与**运行时任务队列面板 + Worker 池治理**、**企业级多空间 RBAC(四级角色矩阵 + 资源归属 + 空间审计日志)**,以及完全可私有化部署的模块化架构,WeKnora 帮助团队把分散文档沉淀为可查询、可推理、可持续演进的专属知识资产。框架支持从飞书、GitLab、腾讯 IMA、Notion 及语雀等外部平台自动同步知识(更多数据源持续接入中),覆盖 PDF、Word、图片、Excel、XMind 等十余种文档格式,并可通过企业微信、飞书、Slack、Telegram 等 IM 频道直接提供问答服务。模型层面兼容 OpenAI、DeepSeek、Qwen(阿里云)、智谱、混元、Gemini、MiniMax、NVIDIA、LiteLLM、Ollama 等主流厂商。Office 文档可由 **anydoc** 在 Go 进程内解析。全流程模块化设计,大模型、向量数据库、存储等组件均可灵活替换,支持本地与私有云部署,数据完全自主可控。WeKnora 还无缝集成了 **Langfuse**,为 Agent 运行、Token 使用及任务流水线提供了全面的可观测性追踪。@@ -144,7 +144,7 @@ https://github.com/user-attachments/assets/2819598d-3140-4623-814a-8162a22b653c| 分块编辑与版本历史 | 在界面直接编辑检索分块,保留逐版本快照,支持 diff 与一键回滚,编辑后自动重建索引;生成问题可增删改与重新生成;支持文档自定义元数据 || 按批次解析配置 | 上传确认对话框或 `process_config` API 覆盖解析引擎、分块、多模态(VLM / ASR)、图谱抽取与问题生成;支持 reparse 时调整配置 || 批量重新解析 | 一次为多篇文档重新排队解析,可携带批次级 `process_config` |-| 数据源导入 | 飞书知识库 / 飞书云盘 / Lark / GitLab / 腾讯 IMA / Notion / 语雀 / RSS 订阅自动同步(更多数据源开发中),支持增量与全量同步 |+| 数据源导入 | 飞书知识库 / 飞书云盘 / Lark / GitLab / 腾讯 IMA / Notion / 语雀 / 钉钉文档 / RSS 订阅自动同步(更多数据源开发中),支持增量与全量同步 || 文档格式 | PDF / Word / Txt / Markdown / HTML / EPUB / MHTML / 图片 / CSV / Excel / PPT / JSON / XMind || 自动打标签 | 解析完成后从知识库已有标签中选择匹配项增量关联,不创建新标签、不覆盖人工标签 || 检索策略 | BM25 稀疏召回 / Dense 稠密召回 / GraphRAG 图谱增强 / 父子分块 / pgvector HNSW 加速(1024 维)/ 多维度索引 |diff --git a/README_JA.md b/README_JA.mdindex f90a04271..47d9bf94e 100644--- a/README_JA.md+++ b/README_JA.md@@ -53,7 +53,7 @@[**WeKnora(ウィーノラ)**](https://weknora.weixin.qq.com) は、大規模言語モデル(LLM)をベースとしたオープンソースのナレッジフレームワークで、エンタープライズ級の文書理解、セマンティック検索、自律推論シナリオ向けに設計されています。-本フレームワークは **3 つのコア能力** を中心に構築されています:日常的な検索に最適な **RAG ベースのクイック Q&A**、ナレッジ検索・MCP ツール・**スキルカタログ**・セッション永続の **Docker / E2B / Cube サンドボックス**・Web 検索を自律的にオーケストレーションし複雑なマルチステップタスクを処理する **ReAct Agent 推論**、そして Agent が生のドキュメントから相互リンクされた Markdown ナレッジベースとインタラクティブなナレッジグラフを自律生成・維持する全く新しい **Wiki モード**(手動編集・バージョン履歴・ワンクリックロールバック対応)。**クロスセッション長期メモリ**は「あなたが誰で、何を繰り返し尋ねるか」を覚えます。ナレッジの整備も細かく制御可能で、**ツリー型フォルダー**がアップロード時のディレクトリ構造を保持し、**チャンク編集とバージョン履歴**により検索チャンクをドキュメントと同様に編集・差分比較・ロールバックできます。さらに、多様なデータソース連携(Feishu ナレッジベース / Feishu クラウドドライブ / GitLab / Tencent IMA / Notion / Yuque / RSS、随時拡充中)、**ウェブサイト埋め込み Widget** による外部サイトへのエージェント公開、プログラム連携向けの**スコープ付き API キーと Principal モデル**、ワークスペースごとの**マルチインスタンスストレージバックエンド**、20 以上の LLM プロバイダー統合(LiteLLM 含む)、Langfuse による全体可観測性と**ランタイムタスクキューダッシュボード + Worker プール統治**、**エンタープライズ向けマルチテナント RBAC(4 階層ロールマトリクス + リソース所有権 + テナント監査ログ)**、完全セルフホスト可能なモジュラーアーキテクチャと組み合わせることで、WeKnora は散在する文書を「検索可能・推論可能・継続的に進化する」専用ナレッジ資産へと昇華させます。+本フレームワークは **3 つのコア能力** を中心に構築されています:日常的な検索に最適な **RAG ベースのクイック Q&A**、ナレッジ検索・MCP ツール・**スキルカタログ**・セッション永続の **Docker / E2B / Cube サンドボックス**・Web 検索を自律的にオーケストレーションし複雑なマルチステップタスクを処理する **ReAct Agent 推論**、そして Agent が生のドキュメントから相互リンクされた Markdown ナレッジベースとインタラクティブなナレッジグラフを自律生成・維持する全く新しい **Wiki モード**(手動編集・バージョン履歴・ワンクリックロールバック対応)。**クロスセッション長期メモリ**は「あなたが誰で、何を繰り返し尋ねるか」を覚えます。ナレッジの整備も細かく制御可能で、**ツリー型フォルダー**がアップロード時のディレクトリ構造を保持し、**チャンク編集とバージョン履歴**により検索チャンクをドキュメントと同様に編集・差分比較・ロールバックできます。さらに、多様なデータソース連携(Feishu ナレッジベース / Feishu クラウドドライブ / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS、随時拡充中)、**ウェブサイト埋め込み Widget** による外部サイトへのエージェント公開、プログラム連携向けの**スコープ付き API キーと Principal モデル**、ワークスペースごとの**マルチインスタンスストレージバックエンド**、20 以上の LLM プロバイダー統合(LiteLLM 含む)、Langfuse による全体可観測性と**ランタイムタスクキューダッシュボード + Worker プール統治**、**エンタープライズ向けマルチテナント RBAC(4 階層ロールマトリクス + リソース所有権 + テナント監査ログ)**、完全セルフホスト可能なモジュラーアーキテクチャと組み合わせることで、WeKnora は散在する文書を「検索可能・推論可能・継続的に進化する」専用ナレッジ資産へと昇華させます。Feishu、GitLab、Tencent IMA、Notion、Yuqueなどの外部プラットフォームからのナレッジ自動同期(他のデータソースも順次対応中)に対応し、PDF、Word、画像、Excel、XMindなど10以上の文書フォーマットをサポート。WeChat Work、Feishu、Slack、TelegramなどのIMチャネルから直接Q&Aサービスを提供できます。モデル層ではOpenAI、DeepSeek、Qwen(Alibaba Cloud)、Zhipu、Hunyuan、Gemini、MiniMax、NVIDIA、LiteLLM、Ollamaなど主要プロバイダーに対応。Office 文書は **anydoc** でプロセス内解析できます。全プロセスをモジュラー設計し、大規模モデル、ベクトルデータベース、ストレージなどのコンポーネントを柔軟に差し替え可能。ローカルおよびプライベートクラウドデプロイに対応し、データは完全に自己管理可能です。さらにWeKnoraは **Langfuse** とシームレスに統合され、Agentの推論、トークン消費、パイプラインに対する包括的な可観測性(オブザーバビリティ)を提供します。@@ -141,7 +141,7 @@ Feishu、GitLab、Tencent IMA、Notion、Yuqueなどの外部プラットフォ| チャンク編集とバージョン | UI から検索チャンクを直接編集、バージョン単位のスナップショット・差分・ワンクリックロールバック、編集後のインデックス自動再構築;生成質問の追加・編集・削除・再生成;ドキュメントのカスタムメタデータ対応 || アップロード単位の解析設定 | アップロード確認ダイアログまたは `process_config` API でパーサー・チャンキング・マルチモーダル(VLM / ASR)・グラフ抽出・質問生成をバッチ単位で上書き;reparse 時も設定変更可能 || 一括 reparse | 複数ドキュメントの解析を一度に再キュー、バッチ単位の `process_config` 対応 |-| データソースインポート | Feishu ナレッジベース / Feishu クラウドドライブ / Lark / GitLab / Tencent IMA / Notion / Yuque / RSS フィードの自動同期(他のデータソースも開発中)、増分・全量同期対応 |+| データソースインポート | Feishu ナレッジベース / Feishu クラウドドライブ / Lark / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS フィードの自動同期(他のデータソースも開発中)、増分・全量同期対応 || 文書フォーマット | PDF / Word / Txt / Markdown / HTML / EPUB / MHTML / 画像 / CSV / Excel / PPT / JSON / XMind || 自動タグ付け | 解析後、ナレッジベース既存タグから一致するものを増分付与(新規タグ作成や手動タグの上書きはしない) || 検索戦略 | BM25 疎検索 / Dense 密検索 / GraphRAG グラフ強化 / 親子チャンキング / pgvector HNSW 加速(1024 次元)/ 多次元インデックス |diff --git a/README_KO.md b/README_KO.mdindex 7a9d8dd12..9effadb1b 100644--- a/README_KO.md+++ b/README_KO.md@@ -53,7 +53,7 @@[**WeKnora**](https://weknora.weixin.qq.com)는 엔터프라이즈급 문서 이해, 시맨틱 검색, 자율 추론 시나리오를 위해 설계된 오픈소스 LLM 기반 지식 프레임워크입니다.-본 프레임워크는 **세 가지 핵심 역량**을 중심으로 구성됩니다. 일상 검색에 최적화된 **RAG 기반 빠른 Q&A**, 지식 검색·MCP 도구·**스킬 카탈로그**·세션 지속 **Docker / E2B / Cube 샌드박스**·웹 검색을 자율적으로 오케스트레이션하여 복잡한 다단계 작업을 처리하는 **ReAct Agent 추론**, 그리고 Agent가 원본 문서에서 상호 연결된 마크다운 지식베이스와 인터랙티브 지식 그래프를 스스로 생성·유지하는 완전히 새로운 **Wiki 모드**(수동 편집·버전 이력·원클릭 롤백 지원)입니다. **크로스 세션 장기 메모리**는 당신이 누구이며 무엇을 반복해서 묻는지 기억합니다. 지식 가공 과정도 세밀하게 제어할 수 있습니다. **트리형 폴더**가 업로드 시의 디렉터리 구조를 그대로 유지하고, **청크 편집 및 버전 이력**을 통해 검색 청크를 문서처럼 수정·비교·롤백할 수 있습니다. 다양한 데이터 소스 연동(Feishu 지식베이스 / Feishu 클라우드 드라이브 / GitLab / Tencent IMA / Notion / Yuque / RSS, 지속 확장 중), **웹사이트 임베드 Widget**으로 외부 사이트에 에이전트 게시, 프로그램 연동을 위한 **범위 지정 API 키 및 Principal 모델**, 워크스페이스별 **다중 인스턴스 스토리지 백엔드**, 20개 이상의 LLM 프로바이더 통합(LiteLLM 포함), Langfuse 기반 풀스택 관측 가능성과 **런타임 작업 큐 대시보드 + Worker 풀 거버넌스**, **엔터프라이즈 멀티 테넌트 RBAC(4단계 역할 매트릭스 + 리소스 소유권 + 테넌트 감사 로그)**, 완전 셀프호스팅이 가능한 모듈형 아키텍처를 결합하여, WeKnora는 흩어진 문서를 검색·추론 가능하며 지속적으로 진화하는 전용 지식 자산으로 탈바꿈시킵니다.+본 프레임워크는 **세 가지 핵심 역량**을 중심으로 구성됩니다. 일상 검색에 최적화된 **RAG 기반 빠른 Q&A**, 지식 검색·MCP 도구·**스킬 카탈로그**·세션 지속 **Docker / E2B / Cube 샌드박스**·웹 검색을 자율적으로 오케스트레이션하여 복잡한 다단계 작업을 처리하는 **ReAct Agent 추론**, 그리고 Agent가 원본 문서에서 상호 연결된 마크다운 지식베이스와 인터랙티브 지식 그래프를 스스로 생성·유지하는 완전히 새로운 **Wiki 모드**(수동 편집·버전 이력·원클릭 롤백 지원)입니다. **크로스 세션 장기 메모리**는 당신이 누구이며 무엇을 반복해서 묻는지 기억합니다. 지식 가공 과정도 세밀하게 제어할 수 있습니다. **트리형 폴더**가 업로드 시의 디렉터리 구조를 그대로 유지하고, **청크 편집 및 버전 이력**을 통해 검색 청크를 문서처럼 수정·비교·롤백할 수 있습니다. 다양한 데이터 소스 연동(Feishu 지식베이스 / Feishu 클라우드 드라이브 / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS, 지속 확장 중), **웹사이트 임베드 Widget**으로 외부 사이트에 에이전트 게시, 프로그램 연동을 위한 **범위 지정 API 키 및 Principal 모델**, 워크스페이스별 **다중 인스턴스 스토리지 백엔드**, 20개 이상의 LLM 프로바이더 통합(LiteLLM 포함), Langfuse 기반 풀스택 관측 가능성과 **런타임 작업 큐 대시보드 + Worker 풀 거버넌스**, **엔터프라이즈 멀티 테넌트 RBAC(4단계 역할 매트릭스 + 리소스 소유권 + 테넌트 감사 로그)**, 완전 셀프호스팅이 가능한 모듈형 아키텍처를 결합하여, WeKnora는 흩어진 문서를 검색·추론 가능하며 지속적으로 진화하는 전용 지식 자산으로 탈바꿈시킵니다.Feishu, GitLab, Tencent IMA, Notion, Yuque 등 외부 플랫폼에서 지식 자동 동기화를 지원하며(추가 데이터 소스 개발 중), PDF, Word, 이미지, Excel, XMind 등 10가지 이상의 문서 포맷을 처리합니다. WeChat Work, Feishu, Slack, Telegram 등의 IM 채널을 통해 Q&A 서비스를 직접 제공할 수 있습니다. 모델 레이어에서 OpenAI, DeepSeek, Qwen(Alibaba Cloud), Zhipu, Hunyuan, Gemini, MiniMax, NVIDIA, LiteLLM, Ollama 등 주요 프로바이더를 지원합니다. Office 문서는 **anydoc**으로 프로세스 내 파싱할 수 있습니다. 전체 프로세스가 모듈화 설계되어 LLM, 벡터 DB, 스토리지 등 구성 요소를 유연하게 교체 가능하며, 로컬 및 프라이빗 클라우드 배포를 지원하여 데이터 완전 자체 관리가 가능합니다. 또한 WeKnora는 **Langfuse**와 원활하게 통합되어 Agent 추론, 토큰 사용량 및 파이프라인에 대한 포괄적인 관측 가능성(Observability)을 제공합니다.@@ -150,7 +150,7 @@ Feishu, GitLab, Tencent IMA, Notion, Yuque 등 외부 플랫폼에서 지식 자| 청크 편집 및 버전 | UI에서 검색 청크를 직접 편집하고 버전별 스냅샷·diff·원클릭 롤백, 편집 후 인덱스 자동 재구축; 생성 질문 추가·수정·삭제·재생성; 문서 커스텀 메타데이터 지원 || 업로드 단위 파싱 설정 | 업로드 확인 대화상자 또는 `process_config` API로 파서·청킹·멀티모달(VLM / ASR)·그래프 추출·질문 생성을 배치 단위로 덮어쓰기; reparse 시 설정 변경 지원 || 일괄 reparse | 여러 문서의 파싱을 한 번에 재큐잉, 배치 단위 `process_config` 지원 |-| 데이터 소스 임포트 | Feishu 지식베이스 / Feishu 클라우드 드라이브 / Lark / GitLab / Tencent IMA / Notion / Yuque / RSS 피드 자동 동기화(추가 데이터 소스 개발 중), 증분·전체 동기화 지원 |+| 데이터 소스 임포트 | Feishu 지식베이스 / Feishu 클라우드 드라이브 / Lark / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / RSS 피드 자동 동기화(추가 데이터 소스 개발 중), 증분·전체 동기화 지원 || 문서 포맷 | PDF / Word / Txt / Markdown / HTML / EPUB / MHTML / 이미지 / CSV / Excel / PPT / JSON / XMind || 자동 태깅 | 파싱 후 지식베이스 기존 태그에서 일치 항목을 증분 연결(새 태그 생성·수동 태그 덮어쓰기 없음) || 검색 전략 | BM25 희소 / Dense 밀집 / GraphRAG 그래프 강화 / 부모-자식 청킹 / pgvector HNSW 가속(1024차원) / 다차원 인덱싱 |diff --git "a/docs/wiki/\351\233\206\346\210\220\346\211\251\345\261\225/\346\225\260\346\215\256\346\272\220\345\257\274\345\205\245\345\274\200\345\217\221.md" "b/docs/wiki/\351\233\206\346\210\220\346\211\251\345\261\225/\346\225\260\346\215\256\346\272\220\345\257\274\345\205\245\345\274\200\345\217\221.md"index cdf4e8927..cb6427c04 100644--- "a/docs/wiki/\351\233\206\346\210\220\346\211\251\345\261\225/\346\225\260\346\215\256\346\272\220\345\257\274\345\205\245\345\274\200\345\217\221.md"+++ "b/docs/wiki/\351\233\206\346\210\220\346\211\251\345\261\225/\346\225\260\346\215\256\346\272\220\345\257\274\345\205\245\345\274\200\345\217\221.md"@@ -1,13 +1,13 @@---title: 数据源导入开发-tags: [集成扩展, 数据源, 飞书, 同步, 连接器]+tags: [集成扩展, 数据源, 飞书, 钉钉, 同步, 连接器]aliases: [数据源导入, DataSource, 数据同步]source: 数据源导入开发文档.md---# 数据源导入开发-WeKnora 的数据源导入模块支持从外部平台(飞书、企业微信、Notion、Confluence 等)自动导入和同步内容到知识库。用户可配置数据源连接,选择需要同步的资源,并通过手动触发或定时调度自动完成内容的增量/全量同步。+WeKnora 的数据源导入模块支持从外部平台(飞书、钉钉、企业微信、Notion、Confluence 等)自动导入和同步内容到知识库。用户可配置数据源连接,选择需要同步的资源,并通过手动触发或定时调度自动完成内容的增量/全量同步。数据源绑定到知识库,一个知识库可接入多个数据源。凭证使用 AES-256-GCM 加密存储。@@ -18,6 +18,7 @@ WeKnora 的数据源导入模块支持从外部平台(飞书、企业微信、| 连接器 | 认证方式 | 增量同步 | 删除同步 ||--------|---------|:-:|:-:|| 飞书 (Feishu) | OAuth2 (Tenant Access Token) | ✅ | ✅ |+| 钉钉文档 (DingTalk Docs) | OAuth2 (App Access Token) | ✅ | ✅ |## 快速接入:飞书知识库@@ -29,6 +30,23 @@ WeKnora 的数据源导入模块支持从外部平台(飞书、企业微信、> 注意:飞书国际版(Lark)同样支持,自动适配 `https://open.larksuite.com` 的 API 地址+## 快速接入:钉钉文档++1. 创建并发布钉钉企业内部应用+2. 开通权限:`Wiki.Workspace.Read`、`Wiki.Node.Read`、`Storage.File.Read`+3. 添加“钉钉文档”数据源,填写 Client ID、Client Secret、操作人 Union ID+4. 测试连接,按知识库空间、文件夹或单篇文档选择范围+5. 触发首次同步;当前仅同步 `ALIDOC/adoc` 在线文档++连接器只使用公开 OpenAPI,将文档 Block 转换为 Markdown,不依赖灰度导出接口。增量版本优先使用毫秒 `modifiedTimestamp`;Blocks 接口只返回一级块,空容器会标记 `nested_blocks_unavailable`。测试连接会探测节点列表和样本文档读取。全量同步也会对照上次游标对账删除。目录读取不完整或文档抓取失败时会保留原游标,避免误删并允许下次重试。++同步以所有已选范围的可见文档集合统一判断删除,文档在已选文件夹之间移动不会触发删除。+某个范围不可访问或已选节点失效时,其他正常范围继续同步,失败范围保留旧游标;在所有范围+恢复可完整读取之前,暂缓删除并保留待核对记录。正文抓取失败的文档也会在后续同步重试。+失效的单篇文档或文件夹选择需要检查权限,必要时重新选择资源,不能直接将不可见等同于源端删除。+开启“同步删除”后,确认源端删除的文档会从 WeKnora 知识库移除;关闭该开关则保留本地内容。+钉钉配置和同步失败提示覆盖中文、英语、日语、韩语、俄语。+## 飞书 docx 解析模式与环境变量飞书新版云文档(docx)的解析路径由环境变量 `FEISHU_DOCX_PARSE_MODE` 控制(作用于 app 服务,对飞书知识库和飞书云盘两个连接器同时生效):diff --git "a/docs/\346\225\260\346\215\256\346\272\220\345\257\274\345\205\245\345\274\200\345\217\221\346\226\207\346\241\243.md" "b/docs/\346\225\260\346\215\256\346\272\220\345\257\274\345\205\245\345\274\200\345\217\221\346\226\207\346\241\243.md"index cfb6cd444..19e3a072b 100644--- "a/docs/\346\225\260\346\215\256\346\272\220\345\257\274\345\205\245\345\274\200\345\217\221\346\226\207\346\241\243.md"+++ "b/docs/\346\225\260\346\215\256\346\272\220\345\257\274\345\205\245\345\274\200\345\217\221\346\226\207\346\241\243.md"@@ -130,6 +130,34 @@ Lark 是飞书的国际版。Wiki / docx / drive 接口与飞书一致,**共---+### 钉钉文档接入++1. 在钉钉开放平台创建并发布企业内部应用。+2. 为应用开通 `Wiki.Workspace.Read`、`Wiki.Node.Read`、`Storage.File.Read` 权限。+3. 添加“钉钉文档”数据源,填写 Client ID、Client Secret,以及有权访问目标知识库的操作人 Union ID。+4. 测试连接后,可按知识库空间、文件夹或单篇文档选择同步范围。++连接器通过钉钉公开 OpenAPI 读取知识库节点及文档 Block,并转换为 Markdown;当前只同步+`ALIDOC/adoc` 在线文档。增量同步优先用节点的毫秒 `modifiedTimestamp` 作为版本,避免官方示例中+分钟精度 `modifiedTime`(如 `2023-05-15T11:29Z`)导致同一分钟内的编辑被跳过。目录遍历不完整或+单篇文档读取失败时会保留原游标,避免误删或跳过后续重试。实现不依赖灰度权限、异步导出或回调服务。++钉钉 Blocks 查询接口只返回文档根下的一级块。高亮块等容器若响应内联了 `children` 会继续渲染;+若容器没有子块,连接器会在文档元数据中记录 `nested_blocks_unavailable`,而不是把残缺正文当成+完整导入。列表项若是块级 children 也会尝试展开。++测试连接除列出知识库外,还会读取根节点,并在根下存在在线文档时试读 Blocks,以便在保存前发现+缺少 `Wiki.Node.Read` 或 `Storage.File.Read`。全量同步(含手动 ForceFull)会对照上次游标对账删除。++同步以所有已选范围的可见文档集合统一判断删除,文档在已选文件夹之间移动不会触发删除。+某个范围不可访问或已选节点失效时,其他正常范围继续同步,失败范围保留旧游标;在所有范围+恢复可完整读取之前,暂缓删除并保留待核对记录。正文抓取失败的文档也会在后续同步重试。+失效的单篇文档或文件夹选择需要检查权限,必要时重新选择资源,不能直接将不可见等同于源端删除。+开启“同步删除”后,确认源端删除的文档会从 WeKnora 知识库移除;关闭该开关则保留本地内容。+钉钉配置和同步失败提示覆盖中文、英语、日语、韩语、俄语。++---+## 前端管理数据源在知识库设置页的 **数据源** 标签页中管理。diff --git a/frontend/src/i18n/localeKeyAudit.test.ts b/frontend/src/i18n/localeKeyAudit.test.tsindex 35a0a0af1..1be52f302 100644--- a/frontend/src/i18n/localeKeyAudit.test.ts+++ b/frontend/src/i18n/localeKeyAudit.test.ts@@ -291,3 +291,19 @@ test('locale messages compile with vue-i18n syntax rules', () => {)assert.deepEqual(summary, [], summary.slice(0, 20).join('\n'))})++test('DingTalk configuration and sync failures remain localized after pruning', () => {+ const keys = [+ 'connector.dingtalk', 'connectorDesc.dingtalk',+ 'field.clientId', 'field.clientSecret', 'field.operatorId', 'field.operatorIdHint',+ 'prereqBarText_dingtalk', 'prereqOpenConsole_dingtalk',+ ...[1, 2, 3].flatMap(step => [`prereqStep${step}Brief_dingtalk`, `prereqStep${step}Desc_dingtalk`]),+ 'syncError.dingtalk_document_failed', 'syncError.dingtalk_resource_failed',+ ].map(key => `datasource.${key}`)+ for (const key of keys) {+ assert.ok(referencedKeys.has(key), `pruning would remove ${key}`)+ for (const [locale, bundle] of Object.entries(LOCALE_BUNDLES)) {+ assert.equal(typeof getLocaleValueAtPath(bundle, key), 'string', `${locale}: missing ${key}`)+ }+ }+})diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex b546d3b3a..e5351773c 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -6411,6 +6411,7 @@ export default {lark_drive: 'Lark Drive',notion: 'Notion',yuque: 'Yuque',+ dingtalk: 'DingTalk Docs',rss: 'RSS / Atom Feed',ima: 'Tencent IMA',gitlab: 'GitLab'@@ -6422,6 +6423,7 @@ export default {lark_drive: 'Sync documents, spreadsheets and files from a Lark Drive folder (Feishu international)',notion: 'Sync pages and databases from Notion',yuque: 'Sync documents from Yuque knowledge bases',+ dingtalk: 'Sync online documents from DingTalk knowledge bases',rss: 'Sync articles from RSS / Atom feeds',ima: 'Sync documents, notes and files from Tencent IMA knowledge bases (AI sessions and video parses are not supported)',gitlab: 'Sync files from GitLab projects'@@ -6442,6 +6444,10 @@ export default {field: {appId: 'App ID',appSecret: 'App Secret',+ clientId: 'Client ID',+ clientSecret: 'Client Secret',+ operatorId: 'Operator Union ID',+ operatorIdHint: 'Reads knowledge bases with this user’s permissions. Obtain it from the DingTalk user details API.',integrationToken: 'Integration Token',apiToken: 'API Token',imaClientId: 'IMA ClientID',@@ -6489,6 +6495,14 @@ export default {prereqStep3Brief_lark_drive: 'Configure app permissions',prereqStep3Desc_lark_drive: 'Enable drive:drive:readonly, drive:export:readonly, docx:document:readonly permissions',prereqOpenConsole_yuque: 'Open Yuque Token settings',+ prereqBarText_dingtalk: 'First time? Click to see the DingTalk app setup guide',+ prereqStep1Brief_dingtalk: 'Create an internal enterprise app',+ prereqStep1Desc_dingtalk: 'Create an internal app in DingTalk Open Platform and copy its Client ID and Client Secret.',+ prereqStep2Brief_dingtalk: 'Grant knowledge base read permissions',+ prereqStep2Desc_dingtalk: 'Grant Wiki.Workspace.Read, Wiki.Node.Read, and Storage.File.Read.',+ prereqStep3Brief_dingtalk: 'Enter the operator Union ID',+ prereqStep3Desc_dingtalk: 'Enter the Union ID of a DingTalk user who can access the target knowledge bases.',+ prereqOpenConsole_dingtalk: 'Open DingTalk Developer Console',prereqBarText_ima: 'First time? Click to see the Tencent IMA OpenAPI setup guide',prereqStep1Brief_ima: 'Enable IMA agent OpenAPI access',prereqStep1Desc_ima: 'Sign in to https://ima.qq.com/agent-interface and apply for OpenAPI access',@@ -6529,6 +6543,8 @@ export default {hoursAgo: '{n}h ago',daysAgo: '{n}d ago',syncError: {+ dingtalk_document_failed: 'DingTalk document could not be read; check access and retry the sync.',+ dingtalk_resource_failed: 'DingTalk resource is unavailable; check access and the saved selection, then retry.',deletion_lookup_failed: 'Failed to look up the item before deletion; see server logs',deletion_failed: 'Deletion failed; see server logs',ingest_failed: 'Ingest failed; see server logs'diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex c4ab3dc7a..156a8400e 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -6411,6 +6411,7 @@ export default {lark_drive: 'Lark Drive',notion: 'Notion',yuque: 'Yuque',+ dingtalk: 'DingTalkドキュメント',rss: 'RSS / Atomフィード',ima: 'Tencent IMA',gitlab: 'GitLab'@@ -6422,6 +6423,7 @@ export default {lark_drive: 'Lark Drive(Feishu国際版)のフォルダからドキュメント、スプレッドシート、ファイルを同期します',notion: 'Notionからページとデータベースを同期します',yuque: 'Yuqueのナレッジベースからドキュメントを同期します',+ dingtalk: 'DingTalkナレッジベースのオンラインドキュメントを同期',rss: 'RSS / Atomフィードから記事を同期します',ima: 'Tencent IMAのナレッジベースからドキュメント、ノート、ファイルを同期します(AIセッションと動画の解析は非対応)',gitlab: 'GitLabプロジェクトからファイルを同期します'@@ -6440,6 +6442,10 @@ export default {loadNotFoundHint: 'folder_tokenが存在しないか、削除されています。Feishu DriveのフォルダURLからコピーしたトークンを確認してください。',},field: {+ clientId: 'Client ID',+ clientSecret: 'Client Secret',+ operatorId: '操作ユーザーのUnion ID',+ operatorIdHint: 'このユーザーの権限でナレッジベースを読み取ります。DingTalkのユーザー詳細APIで取得してください。',appId: 'App ID',appSecret: 'App Secret',integrationToken: 'Integration Token',@@ -6489,6 +6495,14 @@ export default {prereqStep3Brief_lark_drive: 'アプリの権限を設定',prereqStep3Desc_lark_drive: 'drive:drive:readonly、drive:export:readonly、docx:document:readonlyの権限を有効にします',prereqOpenConsole_yuque: 'Yuqueのトークン設定を開く',+ prereqBarText_dingtalk: '初めての利用ですか?DingTalkアプリの設定ガイドを確認',+ prereqStep1Brief_dingtalk: '企業内部アプリを作成',+ prereqStep1Desc_dingtalk: 'DingTalk開発者プラットフォームで企業内部アプリを作成し、Client IDとClient Secretを取得します。',+ prereqStep2Brief_dingtalk: 'ナレッジベースの読み取り権限を付与',+ prereqStep2Desc_dingtalk: 'Wiki.Workspace.Read、Wiki.Node.Read、Storage.File.Readを有効にします。',+ prereqStep3Brief_dingtalk: '操作ユーザーのUnion IDを入力',+ prereqStep3Desc_dingtalk: '対象ナレッジベースにアクセスできるDingTalkユーザーのUnion IDを入力します。',+ prereqOpenConsole_dingtalk: 'DingTalk開発者プラットフォームを開く',prereqBarText_ima: '初めてですか?クリックしてTencent IMA OpenAPIの設定ガイドを表示',prereqStep1Brief_ima: 'IMAエージェントのOpenAPI利用を申請',prereqStep1Desc_ima: 'https://ima.qq.com/agent-interfaceにサインインし、OpenAPIの利用を申請します',@@ -6529,6 +6543,8 @@ export default {hoursAgo: '{n}時間前',daysAgo: '{n}日前',syncError: {+ dingtalk_document_failed: 'DingTalkドキュメントを読み取れません。アクセス権限を確認して同期を再試行してください。',+ dingtalk_resource_failed: 'DingTalkリソースを利用できません。アクセス権限と選択したリソースを確認して再試行してください。',deletion_lookup_failed: '削除前の項目の照会に失敗しました。サーバログを確認してください',deletion_failed: '削除に失敗しました。サーバログを確認してください',ingest_failed: '取り込みに失敗しました。サーバログを確認してください'diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 7e7f553b5..259fcf538 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -788,6 +788,14 @@ export default {prereqStep3Brief_lark_drive: "앱 권한 구성",prereqStep3Desc_lark_drive: "drive:drive:readonly, drive:export:readonly, docx:document:readonly 권한 활성화",prereqOpenConsole_yuque: 'Yuque Token 설정으로 이동',+ prereqBarText_dingtalk: '처음 사용하시나요? 클릭하여 DingTalk 앱 설정 가이드를 확인하세요',+ prereqStep1Brief_dingtalk: '기업 내부 앱 생성',+ prereqStep1Desc_dingtalk: 'DingTalk Open Platform에서 기업 내부 앱을 생성하고 Client ID와 Client Secret을 복사하세요.',+ prereqStep2Brief_dingtalk: '지식베이스 읽기 권한 부여',+ prereqStep2Desc_dingtalk: 'Wiki.Workspace.Read, Wiki.Node.Read, Storage.File.Read 권한을 부여하세요.',+ prereqStep3Brief_dingtalk: '운영자 Union ID 입력',+ prereqStep3Desc_dingtalk: '대상 지식베이스에 접근할 수 있는 DingTalk 사용자의 Union ID를 입력하세요.',+ prereqOpenConsole_dingtalk: 'DingTalk 개발자 콘솔 열기',prereqBarText_ima: '처음 사용하시나요? 클릭하여 Tencent IMA OpenAPI 설정 가이드를 확인하세요',prereqStep1Brief_ima: 'IMA 에이전트 OpenAPI 액세스 활성화',prereqStep1Desc_ima: 'https://ima.qq.com/agent-interface 에 로그인하여 OpenAPI 액세스를 신청하세요',@@ -832,6 +840,10 @@ export default {appSecret: 'App Secret',integrationToken: 'Integration Token',apiToken: 'API Token',+ clientId: 'Client ID',+ clientSecret: 'Client Secret',+ operatorId: '운영자 Union ID',+ operatorIdHint: '대상 지식베이스에 접근할 수 있는 DingTalk 사용자의 Union ID를 입력하세요.',imaClientId: 'IMA ClientID',imaApiKey: 'IMA APIKey',baseUrl: 'Base URL',@@ -848,6 +860,7 @@ export default {lark_drive: "Lark 드라이브 폴더에서 문서, 스프레드시트, 파일 동기화",notion: 'Notion에서 페이지 및 데이터베이스 동기화',yuque: '위큐 지식베이스에서 문서 동기화',+ dingtalk: 'DingTalk 지식베이스의 온라인 문서 동기화',ima: 'Tencent IMA 지식베이스에서 문서, 노트 및 파일 동기화 (AI 세션과 동영상 분석은 지원되지 않음)',rss: 'RSS / Atom 피드에서 글 동기화',gitlab: 'GitLab 프로젝트의 파일 동기화'@@ -859,6 +872,7 @@ export default {lark_drive: "Lark 드라이브",notion: 'Notion',yuque: '위큐 (Yuque)',+ dingtalk: 'DingTalk 문서',ima: 'Tencent IMA',rss: 'RSS / Atom 피드',gitlab: 'GitLab'@@ -921,6 +935,8 @@ export default {loadNotFoundHint: "folder_token이 존재하지 않거나 삭제되었습니다. 페이슈 드라이브 폴더 URL에서 복사한 토큰이 맞는지 확인하세요.",},syncError: {+ dingtalk_document_failed: 'DingTalk 문서를 읽을 수 없습니다. 접근 권한을 확인하고 동기화를 다시 시도하세요.',+ dingtalk_resource_failed: 'DingTalk 리소스를 사용할 수 없습니다. 접근 권한과 선택한 리소스를 확인한 후 다시 시도하세요.',deletion_lookup_failed: '삭제 전 항목 조회에 실패했습니다. 서버 로그를 확인하세요',deletion_failed: '삭제에 실패했습니다. 서버 로그를 확인하세요',ingest_failed: '가져오기에 실패했습니다. 서버 로그를 확인하세요'diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex d1a717d8b..e78e1fdc5 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -764,6 +764,14 @@ export default {prereqStep3Brief_yuque: '(Опционально) Для Enterprise укажите Base URL',prereqStep3Desc_yuque: 'Пользователям публичного облака указывать не нужно. Для Yuque Enterprise или приватного развёртывания укажите корпоративный домен',prereqOpenConsole_yuque: 'Перейти к настройкам Yuque Token',+ prereqBarText_dingtalk: 'Используете впервые? Откройте руководство по настройке приложения DingTalk',+ prereqStep1Brief_dingtalk: 'Создайте внутреннее корпоративное приложение',+ prereqStep1Desc_dingtalk: 'Создайте внутреннее приложение в DingTalk Open Platform и скопируйте Client ID и Client Secret.',+ prereqStep2Brief_dingtalk: 'Предоставьте права чтения базы знаний',+ prereqStep2Desc_dingtalk: 'Предоставьте права Wiki.Workspace.Read, Wiki.Node.Read и Storage.File.Read.',+ prereqStep3Brief_dingtalk: 'Укажите Union ID оператора',+ prereqStep3Desc_dingtalk: 'Укажите Union ID пользователя DingTalk, у которого есть доступ к целевым базам знаний.',+ prereqOpenConsole_dingtalk: 'Открыть консоль разработчика DingTalk',prereqBarText_ima: 'В первый раз? Нажмите, чтобы увидеть руководство по настройке Tencent IMA OpenAPI',prereqStep1Brief_ima: 'Включите доступ к IMA agent OpenAPI',prereqStep1Desc_ima: 'Войдите на https://ima.qq.com/agent-interface и подайте заявку на доступ к OpenAPI',@@ -832,6 +840,10 @@ export default {appSecret: 'App Secret',integrationToken: 'Integration Token',apiToken: 'API Token',+ clientId: 'Client ID',+ clientSecret: 'Client Secret',+ operatorId: 'Union ID оператора',+ operatorIdHint: 'Укажите Union ID пользователя DingTalk, у которого есть доступ к целевым базам знаний.',imaClientId: 'IMA ClientID',imaApiKey: 'IMA APIKey',baseUrl: 'Base URL',@@ -848,6 +860,7 @@ export default {lark_drive: 'Синхронизация документов, таблиц и файлов из папки Lark Drive',notion: 'Синхронизация страниц и баз данных из Notion',yuque: 'Синхронизация документов из баз знаний Yuque',+ dingtalk: 'Синхронизация онлайн-документов из баз знаний DingTalk',ima: 'Синхронизация документов, заметок и файлов из баз знаний Tencent IMA (ИИ-сессии и разбор видео не поддерживаются)',rss: 'Синхронизация статей из лент RSS / Atom',gitlab: 'Синхронизация файлов из проектов GitLab'@@ -859,6 +872,7 @@ export default {lark_drive: 'Lark Drive',notion: 'Notion',yuque: 'Yuque (Юйцюэ)',+ dingtalk: 'Документы DingTalk',ima: 'Tencent IMA',rss: 'RSS / Atom лента',gitlab: 'GitLab'@@ -921,6 +935,8 @@ export default {loadNotFoundHint: 'folder_token не существует или удалён. Проверьте токен, скопированный из URL папки Feishu Drive.',},syncError: {+ dingtalk_document_failed: 'Не удалось прочитать документ DingTalk. Проверьте права доступа и повторите синхронизацию.',+ dingtalk_resource_failed: 'Ресурс DingTalk недоступен. Проверьте права доступа и выбранные ресурсы, затем повторите попытку.',deletion_lookup_failed: 'Не удалось найти элемент перед удалением; подробности в журнале сервера',deletion_failed: 'Не удалось удалить элемент; подробности в журнале сервера',ingest_failed: 'Не удалось импортировать элемент; подробности в журнале сервера'diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex d629bc30c..6e30c8480 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -766,6 +766,14 @@ export default {prereqStep3Brief_yuque: '(可选)企业版填写 Base URL',prereqStep3Desc_yuque: '公有云用户无需填写;语雀企业版或私有部署请填写企业域名',prereqOpenConsole_yuque: '前往语雀 Token 设置',+ prereqBarText_dingtalk: '首次使用?点击查看钉钉应用配置指引',+ prereqStep1Brief_dingtalk: '创建企业内部应用',+ prereqStep1Desc_dingtalk: '在钉钉开放平台创建企业内部应用,并获取 Client ID 和 Client Secret',+ prereqStep2Brief_dingtalk: '开通知识库读取权限',+ prereqStep2Desc_dingtalk: '开通 Wiki.Workspace.Read、Wiki.Node.Read 和 Storage.File.Read',+ prereqStep3Brief_dingtalk: '填写操作人 Union ID',+ prereqStep3Desc_dingtalk: '填写有权访问目标知识库的钉钉用户 Union ID',+ prereqOpenConsole_dingtalk: '前往钉钉开放平台配置',prereqBarText_ima: '首次使用?点击查看腾讯 IMA OpenAPI 授权指引',prereqStep1Brief_ima: '开通 IMA 智能体接入',prereqStep1Desc_ima: '登录 https://ima.qq.com/agent-interface 并申请 OpenAPI 接入',@@ -834,6 +842,10 @@ export default {appSecret: 'App Secret',integrationToken: 'Integration Token',apiToken: 'API Token',+ clientId: 'Client ID',+ clientSecret: 'Client Secret',+ operatorId: '操作人 Union ID',+ operatorIdHint: '用于按该用户的权限读取知识库,可通过钉钉“查询用户详情”接口获取',imaClientId: 'IMA ClientID',imaApiKey: 'IMA APIKey',baseUrl: 'Base URL(可选)',@@ -850,6 +862,7 @@ export default {lark_drive: "同步 Lark 云盘文件夹中的文档、表格、文件(飞书国际版)",notion: '同步 Notion 中的页面和数据库',yuque: '同步语雀知识库中的文档',+ dingtalk: '同步钉钉知识库中的在线文档',ima: '同步腾讯 IMA 知识库中的文档、笔记与文件(暂不支持 AI 会话与视频解析)',rss: '同步 RSS / Atom 订阅源中的文章',gitlab: '同步 GitLab 项目中的文件'@@ -861,6 +874,7 @@ export default {lark_drive: "Lark 云盘",notion: 'Notion',yuque: '语雀',+ dingtalk: '钉钉文档',ima: '腾讯 IMA',rss: 'RSS / Atom 订阅',gitlab: 'GitLab'@@ -923,6 +937,8 @@ export default {loadNotFoundHint: "folder_token 不存在或已删除,请确认从飞书云盘文件夹 URL 复制的 token 正确。",},syncError: {+ dingtalk_document_failed: '无法读取钉钉文档,请检查访问权限后重试同步。',+ dingtalk_resource_failed: '钉钉资源不可用,请检查访问权限和已选资源后重试。',deletion_lookup_failed: '删除前查找文档失败,请查看服务器日志',deletion_failed: '删除失败,请查看服务器日志',ingest_failed: '导入失败,请查看服务器日志'diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vueindex d01833a55..d7bc046d5 100644--- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue+++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue@@ -600,6 +600,23 @@ const connectorDefs = computed<ConnectorDef[]>(() => [{ key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://www.yuque.com', optional: true, hintKey: 'datasource.field.baseUrlHint' },],},+ {+ type: 'dingtalk',+ available: true,+ docUrl: 'https://open.dingtalk.com/document/development/knowledge-base-overview',+ permissionDocUrl: 'https://open.dingtalk.com/document/development/get-knowledge-base-list',+ permissionPageUrl: 'https://open-dev.dingtalk.com/',+ requiredPermissions: [+ 'Wiki.Workspace.Read',+ 'Wiki.Node.Read',+ 'Storage.File.Read',+ ],+ fields: [+ { key: 'client_id', labelKey: 'datasource.field.clientId', placeholder: 'dingxxxxxxxx' },+ { key: 'client_secret', labelKey: 'datasource.field.clientSecret', placeholder: '', secret: true },+ { key: 'operator_id', labelKey: 'datasource.field.operatorId', placeholder: '', hintKey: 'datasource.field.operatorIdHint' },+ ],+ },{// Tencent IMA (ima.qq.com). Uses the OpenAPI at /openapi/wiki/v1 with two// static headers (ima-openapi-clientid + ima-openapi-apikey); no OAuth.diff --git a/frontend/src/views/knowledge/settings/datasourceIcons.ts b/frontend/src/views/knowledge/settings/datasourceIcons.tsindex fed001b97..967cc7785 100644--- a/frontend/src/views/knowledge/settings/datasourceIcons.ts+++ b/frontend/src/views/knowledge/settings/datasourceIcons.ts@@ -4,6 +4,7 @@ import larkIcon from '@/assets/img/datasource-lark.svg'import notionIcon from '@/assets/img/datasource-notion.ico'import yuqueIcon from '@/assets/img/datasource-yuque.ico'import rssIcon from '@/assets/img/datasource-rss.svg'+import dingtalkIcon from '@/assets/img/im/dingtalk.svg'import imaIcon from '@/assets/img/datasource-ima.png'export const datasourceIconMap: Record<string, string> = {@@ -14,6 +15,7 @@ export const datasourceIconMap: Record<string, string> = {lark_drive: larkIcon,notion: notionIcon,yuque: yuqueIcon,+ dingtalk: dingtalkIcon,rss: rssIcon,gitlab: gitlabIcon,ima: imaIcon,diff --git a/internal/application/service/datasource_service.go b/internal/application/service/datasource_service.goindex 950c0aa39..85ccc7954 100644--- a/internal/application/service/datasource_service.go+++ b/internal/application/service/datasource_service.go@@ -684,8 +684,12 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) evar fetchErr errorif payload.ForceFull || ds.SyncMode == types.SyncModeFull {- // Full sync- items, fetchErr = connector.FetchAll(ctx, config, config.ResourceIDs)+ if full, ok := connector.(datasource.FullSyncWithCursor); ok {+ cursor, _ := ds.ParseSyncCursor()+ items, nextCursor, fetchErr = full.FetchAllFromCursor(ctx, config, config.ResourceIDs, cursor)+ } else {+ items, fetchErr = connector.FetchAll(ctx, config, config.ResourceIDs)+ }logger.Infof(ctx, "full sync fetched %d items", len(items))} else {// Incremental syncdiff --git a/internal/container/container.go b/internal/container/container.goindex da74bcd3f..d6b4b225b 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -56,6 +56,7 @@ import ("github.com/Tencent/WeKnora/internal/config""github.com/Tencent/WeKnora/internal/database""github.com/Tencent/WeKnora/internal/datasource"+ dingtalkConnector "github.com/Tencent/WeKnora/internal/datasource/connector/dingtalk""github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core""github.com/Tencent/WeKnora/internal/datasource/connector/feishu/drive""github.com/Tencent/WeKnora/internal/datasource/connector/feishu/wiki"@@ -1701,6 +1702,9 @@ func initConnectorRegistry() (*datasource.ConnectorRegistry, error) {if err := registry.Register(yuqueConnector.NewConnector()); err != nil {errs = errors.Join(errs, fmt.Errorf("register yuque connector: %w", err))}+ if err := registry.Register(dingtalkConnector.NewConnector()); err != nil {+ errs = errors.Join(errs, fmt.Errorf("register dingtalk connector: %w", err))+ }if err := registry.Register(imaConnector.NewConnector()); err != nil {errs = errors.Join(errs, fmt.Errorf("register ima connector: %w", err))}diff --git a/internal/container/datasource_registry_test.go b/internal/container/datasource_registry_test.gonew file mode 100644index 000000000..afb94bba7--- /dev/null+++ b/internal/container/datasource_registry_test.go@@ -0,0 +1,21 @@+package container++import (+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+)++func TestConnectorRegistryIncludesDingTalk(t *testing.T) {+ registry, err := initConnectorRegistry()+ if err != nil {+ t.Fatalf("initConnectorRegistry() error = %v", err)+ }+ connector, err := registry.Get(types.ConnectorTypeDingTalk)+ if err != nil {+ t.Fatalf("DingTalk connector is not registered: %v", err)+ }+ if connector.Type() != types.ConnectorTypeDingTalk {+ t.Fatalf("connector.Type() = %q", connector.Type())+ }+}diff --git a/internal/datasource/connector.go b/internal/datasource/connector.goindex c7c51baab..01f72477f 100644--- a/internal/datasource/connector.go+++ b/internal/datasource/connector.go@@ -93,6 +93,20 @@ type StreamingConnector interface {) (*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 FullSyncWithCursor interface {+ FetchAllFromCursor(+ ctx context.Context,+ config *types.DataSourceConfig,+ resourceIDs []string,+ cursor *types.SyncCursor,+ ) ([]types.FetchedItem, *types.SyncCursor, error)+}+// ConnectorRegistry manages the registration and lookup of available connectorstype ConnectorRegistry struct {connectors map[string]Connector@@ -240,10 +254,10 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{types.ConnectorTypeDingTalk: {Type: types.ConnectorTypeDingTalk,Name: "DingTalk (钉钉)",- Description: "Sync documents and content from DingTalk",+ Description: "Sync online documents from DingTalk knowledge bases",Priority: 7,- AuthType: "api_key",- Capabilities: []string{"incremental"},+ AuthType: "oauth2",+ Capabilities: []string{"incremental", "deletion_sync"},},types.ConnectorTypeWebCrawler: {Type: types.ConnectorTypeWebCrawler,diff --git a/internal/datasource/connector/dingtalk/client.go b/internal/datasource/connector/dingtalk/client.gonew file mode 100644index 000000000..f2f34e88f--- /dev/null+++ b/internal/datasource/connector/dingtalk/client.go@@ -0,0 +1,524 @@+// Package dingtalk implements the DingTalk document data source connector.+package dingtalk++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strconv"+ "strings"+ "time"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/types"+)++const (+ apiBaseURL = "https://api.dingtalk.com"+ apiTimeout = 30 * time.Second+ maxResponseBytes = 16 << 20+ maxPages = 1000+ maxAttempts = 3+)++type config struct {+ ClientID string `json:"client_id"`+ ClientSecret string `json:"client_secret"`+ OperatorID string `json:"operator_id"`+}++func parseConfig(dataSourceConfig *types.DataSourceConfig) (*config, error) {+ if dataSourceConfig == nil {+ return nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig)+ }++ raw, err := json.Marshal(dataSourceConfig.Credentials)+ if err != nil {+ return nil, fmt.Errorf("%w: marshal DingTalk credentials: %v",+ datasource.ErrInvalidCredentials, err)+ }+ var cfg config+ if err := json.Unmarshal(raw, &cfg); err != nil {+ return nil, fmt.Errorf("%w: decode DingTalk credentials: %v",+ datasource.ErrInvalidCredentials, err)+ }+ cfg.ClientID = strings.TrimSpace(cfg.ClientID)+ cfg.ClientSecret = strings.TrimSpace(cfg.ClientSecret)+ cfg.OperatorID = strings.TrimSpace(cfg.OperatorID)++ switch {+ case cfg.ClientID == "":+ return nil, fmt.Errorf("%w: client_id is required", datasource.ErrInvalidCredentials)+ case cfg.ClientSecret == "":+ return nil, fmt.Errorf("%w: client_secret is required", datasource.ErrInvalidCredentials)+ case cfg.OperatorID == "":+ return nil, fmt.Errorf("%w: operator_id is required", datasource.ErrInvalidCredentials)+ }+ return &cfg, nil+}++type workspace struct {+ ID string `json:"workspaceId"`+ RootNodeID string `json:"rootNodeId"`+ Name string `json:"name"`+ Description string `json:"description"`+ URL string `json:"url"`+ ModifiedTime string `json:"modifiedTime"`+}++type node struct {+ ID string `json:"nodeId"`+ WorkspaceID string `json:"workspaceId"`+ Name string `json:"name"`+ Type string `json:"type"`+ Category string `json:"category"`+ Extension string `json:"extension"`+ URL string `json:"url"`+ ModifiedTime string `json:"modifiedTime"`+ ModifiedTimestamp int64 `json:"modifiedTimestamp"`+ HasChildren bool `json:"hasChildren"`+}++func (n node) isFolder() bool {+ return strings.EqualFold(n.Type, "FOLDER")+}++func (n node) isDocument() bool {+ return strings.EqualFold(n.Type, "FILE") &&+ strings.EqualFold(n.Category, "ALIDOC") &&+ strings.EqualFold(n.Extension, "adoc")+}++func (n node) title() string {+ if title := strings.TrimSpace(n.Name); title != "" {+ return title+ }+ return n.ID+}++func (n node) revision() string {+ // Prefer the millisecond timestamp when present. Official node listings+ // also return modifiedTime at minute precision (e.g. 2023-05-15T11:29Z),+ // which would skip same-minute edits during incremental sync.+ if n.ModifiedTimestamp > 0 {+ return strconv.FormatInt(n.ModifiedTimestamp, 10)+ }+ return strings.TrimSpace(n.ModifiedTime)+}++func (n node) modifiedAt() time.Time {+ if n.ModifiedTimestamp > 0 {+ return time.UnixMilli(n.ModifiedTimestamp)+ }+ return parseDingTalkTime(n.ModifiedTime)+}++type dingTalkAPI interface {+ listWorkspaces(context.Context) ([]workspace, error)+ listNodes(context.Context, string) ([]node, error)+ documentBlocks(context.Context, string) ([]json.RawMessage, error)+}++type client struct {+ baseURL string+ operator string+ appKey string+ appSecret string+ http *http.Client+ sleep func(context.Context, time.Duration) error++ token string+ tokenExpiry time.Time+}++func newClient(cfg *config) *client {+ return &client{+ baseURL: apiBaseURL,+ operator: cfg.OperatorID,+ appKey: cfg.ClientID,+ appSecret: cfg.ClientSecret,+ http: datasource.NewConnectorHTTPClient(apiTimeout),+ sleep: sleepContext,+ }+}++type accessTokenResponse struct {+ AccessToken string `json:"accessToken"`+ ExpireIn int64 `json:"expireIn"`+}++func (c *client) accessToken(ctx context.Context) (string, error) {+ if c.token != "" && time.Now().Before(c.tokenExpiry) {+ return c.token, nil+ }++ var response accessTokenResponse+ err := c.doJSON(ctx, http.MethodPost, "/v1.0/oauth2/accessToken", map[string]string{+ "appKey": c.appKey,+ "appSecret": c.appSecret,+ }, false, &response)+ if err != nil {+ return "", fmt.Errorf("get DingTalk access token: %w", err)+ }+ response.AccessToken = strings.TrimSpace(response.AccessToken)+ if response.AccessToken == "" {+ return "", fmt.Errorf("%w: DingTalk returned an empty access token", datasource.ErrInvalidCredentials)+ }++ ttl := time.Duration(response.ExpireIn) * time.Second+ if ttl <= 0 {+ ttl = 90 * time.Minute+ }+ if ttl > 5*time.Minute {+ ttl -= 5 * time.Minute+ }+ c.token = response.AccessToken+ c.tokenExpiry = time.Now().Add(ttl)+ return c.token, nil+}++func (c *client) doJSON(+ ctx context.Context,+ method, path string,+ requestBody any,+ authenticated bool,+ result any,+) error {+ var payload []byte+ var err error+ if requestBody != nil {+ payload, err = json.Marshal(requestBody)+ if err != nil {+ return fmt.Errorf("encode DingTalk request: %w", err)+ }+ }++ refreshed := false+ retryAttempt := 0+ for {+ var body io.Reader+ if payload != nil {+ body = bytes.NewReader(payload)+ }+ req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)+ if err != nil {+ return fmt.Errorf("create DingTalk request: %w", err)+ }+ req.Header.Set("Accept", "application/json")+ req.Header.Set("Content-Type", "application/json")++ var token string+ if authenticated {+ token, err = c.accessToken(ctx)+ if err != nil {+ return err+ }+ req.Header.Set("x-acs-dingtalk-access-token", token)+ }++ resp, err := c.http.Do(req)+ if err != nil {+ requestErr := redactRequestError(err)+ if retryAttempt+1 < maxAttempts && !isContextError(requestErr) {+ delay := retryDelay(retryAttempt)+ retryAttempt+++ if err := c.wait(ctx, delay); err != nil {+ return err+ }+ continue+ }+ return fmt.Errorf("execute DingTalk request: %w", requestErr)+ }++ responseBody, readErr := readBody(resp.Body)+ _ = resp.Body.Close()+ if readErr != nil {+ return fmt.Errorf("read DingTalk response: %w", readErr)+ }++ if authenticated && resp.StatusCode == http.StatusUnauthorized && !refreshed {+ if c.token == token {+ c.token = ""+ c.tokenExpiry = time.Time{}+ }+ refreshed = true+ continue+ }++ if isTransient(resp.StatusCode) {+ apiErr := c.redactAPIError(decodeAPIError(resp.StatusCode, responseBody))+ if retryAttempt+1 < maxAttempts {+ delay := retryDelay(retryAttempt)+ if resp.StatusCode == http.StatusTooManyRequests {+ delay = parseRetryAfter(resp.Header.Get("Retry-After"), delay)+ }+ retryAttempt+++ if err := c.wait(ctx, delay); err != nil {+ return err+ }+ continue+ }+ return apiErr+ }++ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {+ apiErr := c.redactAPIError(decodeAPIError(resp.StatusCode, responseBody))+ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ return fmt.Errorf("%w: %w", datasource.ErrInvalidCredentials, apiErr)+ }+ return apiErr+ }+ if result != nil && len(responseBody) > 0 {+ if err := json.Unmarshal(responseBody, result); err != nil {+ return fmt.Errorf("decode DingTalk response: %w", err)+ }+ }+ return nil+ }+}++func (c *client) redactAPIError(err error) error {+ message := err.Error()+ for _, sensitive := range []string{c.appKey, c.appSecret, c.operator, c.token} {+ if sensitive != "" {+ message = strings.ReplaceAll(message, sensitive, "[REDACTED]")+ }+ }+ return errors.New(message)+}++func (c *client) listWorkspaces(ctx context.Context) ([]workspace, error) {+ var all []workspace+ nextToken := ""+ seenTokens := make(map[string]struct{})++ for page := 0; page < maxPages; page++ {+ query := url.Values{+ "maxResults": {"30"},+ "operatorId": {c.operator},+ }+ if nextToken != "" {+ query.Set("nextToken", nextToken)+ }+ var response struct {+ Workspaces []workspace `json:"workspaces"`+ NextToken string `json:"nextToken"`+ }+ if err := c.doJSON(+ ctx, http.MethodGet, "/v2.0/wiki/workspaces?"+query.Encode(), nil, true, &response,+ ); err != nil {+ return nil, fmt.Errorf("list DingTalk workspaces: %w", err)+ }+ all = append(all, response.Workspaces...)+ nextToken = strings.TrimSpace(response.NextToken)+ if nextToken == "" {+ return all, nil+ }+ if _, exists := seenTokens[nextToken]; exists {+ return nil, errors.New("DingTalk workspace pagination repeated nextToken")+ }+ seenTokens[nextToken] = struct{}{}+ }+ return nil, fmt.Errorf("DingTalk workspace pagination exceeded %d pages", maxPages)+}++func (c *client) listNodes(ctx context.Context, parentNodeID string) ([]node, error) {+ var all []node+ nextToken := ""+ seenTokens := make(map[string]struct{})++ for page := 0; page < maxPages; page++ {+ query := url.Values{+ "maxResults": {"50"},+ "operatorId": {c.operator},+ "parentNodeId": {parentNodeID},+ }+ if nextToken != "" {+ query.Set("nextToken", nextToken)+ }+ var response struct {+ Nodes []node `json:"nodes"`+ NextToken string `json:"nextToken"`+ }+ if err := c.doJSON(+ ctx, http.MethodGet, "/v2.0/wiki/nodes?"+query.Encode(), nil, true, &response,+ ); err != nil {+ return nil, fmt.Errorf("list DingTalk nodes: %w", err)+ }+ all = append(all, response.Nodes...)+ nextToken = strings.TrimSpace(response.NextToken)+ if nextToken == "" {+ return all, nil+ }+ if _, exists := seenTokens[nextToken]; exists {+ return nil, errors.New("DingTalk node pagination repeated nextToken")+ }+ seenTokens[nextToken] = struct{}{}+ }+ return nil, fmt.Errorf("DingTalk node pagination exceeded %d pages", maxPages)+}++func (c *client) documentBlocks(ctx context.Context, documentID string) ([]json.RawMessage, error) {+ const pageSize = 100+ var all []json.RawMessage++ for page := 0; page < maxPages; page++ {+ start := page * pageSize+ query := url.Values{+ "endIndex": {strconv.Itoa(start + pageSize - 1)},+ "operatorId": {c.operator},+ "startIndex": {strconv.Itoa(start)},+ }+ var response struct {+ Success *bool `json:"success"`+ Result *struct {+ Data []json.RawMessage `json:"data"`+ } `json:"result"`+ }+ path := "/v1.0/doc/suites/documents/" + url.PathEscape(documentID) ++ "/blocks?" + query.Encode()+ if err := c.doJSON(ctx, http.MethodGet, path, nil, true, &response); err != nil {+ return nil, fmt.Errorf("query DingTalk document blocks: %w", err)+ }+ if response.Success == nil || !*response.Success || response.Result == nil {+ return nil, errors.New("DingTalk document blocks request was unsuccessful")+ }+ all = append(all, response.Result.Data...)+ if len(response.Result.Data) < pageSize {+ return all, nil+ }+ }+ return nil, fmt.Errorf("DingTalk document block pagination exceeded %d pages", maxPages)+}++type apiError struct {+ status int+ code string+ message string+}++func (e *apiError) Error() string {+ switch {+ case e.code != "" && e.message != "":+ return fmt.Sprintf("DingTalk API status=%d code=%s message=%s", e.status, e.code, e.message)+ case e.code != "":+ return fmt.Sprintf("DingTalk API status=%d code=%s", e.status, e.code)+ default:+ return fmt.Sprintf("DingTalk API status=%d", e.status)+ }+}++func decodeAPIError(status int, body []byte) error {+ var response struct {+ Code json.RawMessage `json:"code"`+ ErrCode json.RawMessage `json:"errcode"`+ Message string `json:"message"`+ ErrMsg string `json:"errmsg"`+ }+ _ = json.Unmarshal(body, &response)+ code := rawValue(response.Code)+ if code == "" {+ code = rawValue(response.ErrCode)+ }+ message := strings.TrimSpace(response.Message)+ if message == "" {+ message = strings.TrimSpace(response.ErrMsg)+ }+ return &apiError{status: status, code: code, message: message}+}++func rawValue(value json.RawMessage) string {+ if len(value) == 0 || string(value) == "null" {+ return ""+ }+ var text string+ if err := json.Unmarshal(value, &text); err == nil {+ return strings.TrimSpace(text)+ }+ return strings.TrimSpace(string(value))+}++func readBody(body io.Reader) ([]byte, error) {+ data, err := io.ReadAll(io.LimitReader(body, maxResponseBytes+1))+ if err != nil {+ return nil, err+ }+ if len(data) > maxResponseBytes {+ return nil, fmt.Errorf("response exceeds %d bytes", maxResponseBytes)+ }+ return data, nil+}++func isTransient(status int) bool {+ return status == http.StatusTooManyRequests || status >= http.StatusInternalServerError+}++func retryDelay(attempt int) time.Duration {+ if attempt < 0 {+ attempt = 0+ }+ if attempt > 4 {+ attempt = 4+ }+ return time.Duration(1<<attempt) * 250 * time.Millisecond+}++func parseRetryAfter(value string, fallback time.Duration) time.Duration {+ const maximum = 30 * time.Second+ delay := fallback+ if seconds, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && value != "" {+ if seconds <= 0 {+ delay = 100 * time.Millisecond+ } else {+ delay = time.Duration(seconds) * time.Second+ }+ } else if parsed, err := http.ParseTime(value); err == nil {+ delay = time.Until(parsed)+ if delay <= 0 {+ delay = 100 * time.Millisecond+ }+ }+ if delay > maximum {+ return maximum+ }+ return delay+}++func (c *client) wait(ctx context.Context, delay time.Duration) error {+ if c.sleep == nil {+ return sleepContext(ctx, delay)+ }+ return c.sleep(ctx, delay)+}++func sleepContext(ctx context.Context, delay time.Duration) error {+ timer := time.NewTimer(delay)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ return nil+ }+}++func isContextError(err error) bool {+ return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)+}++func redactRequestError(err error) error {+ for {+ var requestErr *url.Error+ if !errors.As(err, &requestErr) || requestErr.Err == nil {+ return err+ }+ // url.Error includes the full request URL. DingTalk puts operatorId in+ // the query string, so retain the cause without persisting that ID.+ err = requestErr.Err+ }+}diff --git a/internal/datasource/connector/dingtalk/client_test.go b/internal/datasource/connector/dingtalk/client_test.gonew file mode 100644index 000000000..7b56ded13--- /dev/null+++ b/internal/datasource/connector/dingtalk/client_test.go@@ -0,0 +1,308 @@+package dingtalk++import (+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"+)++type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {+ return f(request)+}++func testClient(server *httptest.Server) *client {+ return &client{+ baseURL: server.URL,+ operator: "union/user",+ appKey: "app",+ appSecret: "secret",+ http: server.Client(),+ sleep: func(context.Context, time.Duration) error { return nil },+ }+}++func TestClientUsesOfficialEndpointsAndPaginates(t *testing.T) {+ var mu sync.Mutex+ requests := make([]string, 0, 5)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ requests = append(requests, r.Method+" "+r.URL.RequestURI())+ mu.Unlock()++ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case "/v1.0/oauth2/accessToken":+ body, _ := io.ReadAll(r.Body)+ if !strings.Contains(string(body), `"appKey":"app"`) ||+ !strings.Contains(string(body), `"appSecret":"secret"`) {+ t.Errorf("token request body = %s", body)+ }+ _, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`))+ case "/v2.0/wiki/workspaces":+ if r.Header.Get("x-acs-dingtalk-access-token") != "token" ||+ r.URL.Query().Get("operatorId") != "union/user" ||+ r.URL.Query().Get("maxResults") != "30" {+ t.Errorf("workspace request = %#v, headers = %#v", r.URL.Query(), r.Header)+ }+ if r.URL.Query().Get("nextToken") == "" {+ _, _ = w.Write([]byte(`{+ "workspaces":[{"workspaceId":"a","rootNodeId":"root-a","name":"A"}],+ "nextToken":"page 2"+ }`))+ } else {+ _, _ = w.Write([]byte(`{+ "workspaces":[{"workspaceId":"b","rootNodeId":"root-b","name":"B"}]+ }`))+ }+ case "/v2.0/wiki/nodes":+ if r.URL.Query().Get("parentNodeId") != "root/a" ||+ r.URL.Query().Get("maxResults") != "50" {+ t.Errorf("node request query = %#v", r.URL.Query())+ }+ _, _ = w.Write([]byte(`{"nodes":[{"nodeId":"doc","type":"FILE","category":"ALIDOC","extension":"adoc"}]}`))+ case "/v1.0/doc/suites/documents/doc/key/blocks":+ if !strings.Contains(r.URL.EscapedPath(), "doc%2Fkey") {+ t.Errorf("document key was not path-escaped: %s", r.URL.EscapedPath())+ }+ if r.URL.Query().Get("startIndex") != "0" ||+ r.URL.Query().Get("endIndex") != "99" {+ t.Errorf("block request query = %#v", r.URL.Query())+ }+ _, _ = w.Write([]byte(`{"success":true,"result":{"data":[{"blockType":"paragraph"}]}}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ client := testClient(server)+ workspaces, err := client.listWorkspaces(context.Background())+ if err != nil || len(workspaces) != 2 {+ t.Fatalf("listWorkspaces() = %#v, %v", workspaces, err)+ }+ nodes, err := client.listNodes(context.Background(), "root/a")+ if err != nil || len(nodes) != 1 {+ t.Fatalf("listNodes() = %#v, %v", nodes, err)+ }+ blocks, err := client.documentBlocks(context.Background(), "doc/key")+ if err != nil || len(blocks) != 1 {+ t.Fatalf("documentBlocks() = %#v, %v", blocks, err)+ }++ tokenRequests := 0+ for _, request := range requests {+ if request == "POST /v1.0/oauth2/accessToken" {+ tokenRequests+++ }+ }+ if tokenRequests != 1 {+ t.Fatalf("access token requested %d times, requests = %#v", tokenRequests, requests)+ }+}++func TestClientRefreshesUnauthorizedTokenAndRetriesRateLimit(t *testing.T) {+ tokenRequests, workspaceRequests, nodeRequests, waits := 0, 0, 0, 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case "/v1.0/oauth2/accessToken":+ tokenRequests+++ _, _ = w.Write([]byte(`{"accessToken":"token-` + string(rune('0'+tokenRequests)) + `","expireIn":7200}`))+ case "/v2.0/wiki/workspaces":+ workspaceRequests+++ if workspaceRequests == 1 {+ w.WriteHeader(http.StatusUnauthorized)+ _, _ = w.Write([]byte(`{"code":"InvalidToken","message":"expired"}`))+ return+ }+ if r.Header.Get("x-acs-dingtalk-access-token") != "token-2" {+ t.Errorf("refreshed token header = %q", r.Header.Get("x-acs-dingtalk-access-token"))+ }+ _, _ = w.Write([]byte(`{"workspaces":[]}`))+ case "/v2.0/wiki/nodes":+ nodeRequests+++ if nodeRequests == 1 {+ w.Header().Set("Retry-After", "0")+ w.WriteHeader(http.StatusTooManyRequests)+ _, _ = w.Write([]byte(`{"code":"TooManyRequests"}`))+ return+ }+ _, _ = w.Write([]byte(`{"nodes":[]}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ client := testClient(server)+ client.sleep = func(context.Context, time.Duration) error {+ waits+++ return nil+ }+ if _, err := client.listWorkspaces(context.Background()); err != nil {+ t.Fatalf("listWorkspaces() error = %v", err)+ }+ if _, err := client.listNodes(context.Background(), "root"); err != nil {+ t.Fatalf("listNodes() error = %v", err)+ }+ if tokenRequests != 2 || workspaceRequests != 2 || nodeRequests != 2 || waits != 1 {+ t.Fatalf(+ "requests token=%d workspace=%d nodes=%d waits=%d",+ tokenRequests, workspaceRequests, nodeRequests, waits,+ )+ }+}++func TestDecodeAPIErrorDoesNotExposeUnstructuredBody(t *testing.T) {+ body, _ := json.Marshal(map[string]string{"unexpected": "credential=secret"})+ err := decodeAPIError(http.StatusBadRequest, body)+ if strings.Contains(err.Error(), "secret") {+ t.Fatalf("decodeAPIError() leaked response body: %v", err)+ }+}++func TestClientDoesNotExposeQueryValuesInTransportErrors(t *testing.T) {+ client := &client{+ baseURL: "https://api.dingtalk.com",+ http: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {+ return nil, errors.New("dial failed")+ })},+ sleep: func(context.Context, time.Duration) error { return nil },+ }+ err := client.doJSON(+ context.Background(),+ http.MethodGet,+ "/v2.0/wiki/nodes?operatorId=sensitive-union-id",+ nil,+ false,+ nil,+ )+ if err == nil || strings.Contains(err.Error(), "sensitive-union-id") {+ t.Fatalf("doJSON() error = %v", err)+ }+}++func TestClientRejectsRepeatedPaginationTokens(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case "/v2.0/wiki/workspaces":+ _, _ = w.Write([]byte(`{"workspaces":[],"nextToken":"same"}`))+ case "/v2.0/wiki/nodes":+ _, _ = w.Write([]byte(`{"nodes":[],"nextToken":"same"}`))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ client := testClient(server)+ client.token = "cached"+ client.tokenExpiry = time.Now().Add(time.Hour)++ if _, err := client.listWorkspaces(context.Background()); err == nil ||+ !strings.Contains(err.Error(), "repeated nextToken") {+ t.Fatalf("listWorkspaces() error = %v", err)+ }+ if _, err := client.listNodes(context.Background(), "root"); err == nil ||+ !strings.Contains(err.Error(), "repeated nextToken") {+ t.Fatalf("listNodes() error = %v", err)+ }+}++func TestClientRedactsCredentialsFromStructuredAPIErrors(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{+ "code":"Forbidden",+ "message":"app-key app-secret operator-union cached-token"+ }`))+ }))+ defer server.Close()++ client := testClient(server)+ client.appKey = "app-key"+ client.appSecret = "app-secret"+ client.operator = "operator-union"+ client.token = "cached-token"+ client.tokenExpiry = time.Now().Add(time.Hour)++ err := client.doJSON(context.Background(), http.MethodGet, "/forbidden", nil, true, nil)+ if err == nil {+ t.Fatal("doJSON() error = nil")+ }+ for _, sensitive := range []string{+ client.appKey, client.appSecret, client.operator, client.token,+ } {+ if strings.Contains(err.Error(), sensitive) {+ t.Fatalf("doJSON() leaked %q: %v", sensitive, err)+ }+ }+}++func TestReadBodyRejectsOversizedResponses(t *testing.T) {+ body := strings.NewReader(strings.Repeat("x", maxResponseBytes+1))+ if _, err := readBody(body); err == nil ||+ !strings.Contains(err.Error(), "response exceeds") {+ t.Fatalf("readBody() error = %v", err)+ }+}++func TestDocumentBlocksRejectsIncompleteResponse(t *testing.T) {+ for _, body := range []string{`{}`, `{"success":false}`, `{"success":true}`, `{"success":true,"result":null}`} {+ t.Run(body, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(body))+ }))+ defer server.Close()+ c := testClient(server)+ c.token = "cached"+ c.tokenExpiry = time.Now().Add(time.Hour)+ blocks, err := c.documentBlocks(context.Background(), "doc")+ if err == nil || len(blocks) != 0 {+ t.Fatalf("invalid response accepted: %#v, %v", blocks, err)+ }+ })+ }+}++func TestDocumentBlocksReadsMultiplePagesAndAcceptsEmptyDocument(t *testing.T) {+ calls := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls+++ var blocks []json.RawMessage+ if r.URL.Query().Get("startIndex") == "0" && strings.Contains(r.URL.Path, "/long/") {+ for i := 0; i < 100; i++ {+ blocks = append(blocks, json.RawMessage(`{"blockType":"paragraph","paragraph":{"text":"first page"}}`))+ }+ } else if strings.Contains(r.URL.Path, "/long/") {+ if r.URL.Query().Get("startIndex") != "100" {+ t.Errorf("unexpected page: %s", r.URL.RawQuery)+ }+ blocks = []json.RawMessage{json.RawMessage(`{"blockType":"paragraph","paragraph":{"text":"last page"}}`)}+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "result": map[string]any{"data": blocks}})+ }))+ defer server.Close()+ c := testClient(server)+ c.token = "cached"+ c.tokenExpiry = time.Now().Add(time.Hour)+ blocks, err := c.documentBlocks(context.Background(), "long")+ if err != nil || len(blocks) != 101 || calls != 2 {+ t.Fatalf("long document: %d blocks, %d calls, %v", len(blocks), calls, err)+ }+ blocks, err = c.documentBlocks(context.Background(), "empty")+ if err != nil || len(blocks) != 0 {+ t.Fatalf("empty document: %#v, %v", blocks, err)+ }+}diff --git a/internal/datasource/connector/dingtalk/connector.go b/internal/datasource/connector/dingtalk/connector.gonew file mode 100644index 000000000..1a8f3b83e--- /dev/null+++ b/internal/datasource/connector/dingtalk/connector.go@@ -0,0 +1,930 @@+package dingtalk++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/url"+ "sort"+ "strings"+ "time"+ "unicode"+ "unicode/utf8"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/types"+)++const (+ cursorVersion = 2+ maxTraversalNodes = 1_000_000+)++var (+ _ datasource.Connector = (*Connector)(nil)+ _ datasource.FullSyncWithCursor = (*Connector)(nil)+)++type apiFactory func(*config) dingTalkAPI++// Connector imports native DingTalk documents through the Wiki and Blocks APIs.+type Connector struct {+ newAPI apiFactory+}++// NewConnector creates a DingTalk data source connector.+func NewConnector() *Connector {+ return &Connector{newAPI: func(cfg *config) dingTalkAPI { return newClient(cfg) }}+}++func (c *Connector) api(cfg *config) dingTalkAPI {+ if c != nil && c.newAPI != nil {+ return c.newAPI(cfg)+ }+ return newClient(cfg)+}++// Type returns the registered data source type.+func (c *Connector) Type() string {+ return types.ConnectorTypeDingTalk+}++// Validate checks the application credentials and operator access, including+// node listing and a sample document read when one is visible at the workspace root.+func (c *Connector) Validate(ctx context.Context, dataSourceConfig *types.DataSourceConfig) error {+ cfg, err := parseConfig(dataSourceConfig)+ if err != nil {+ return err+ }+ api := c.api(cfg)+ workspaces, err := api.listWorkspaces(ctx)+ if err != nil {+ return fmt.Errorf("validate DingTalk data source: %w", err)+ }+ for _, item := range workspaces {+ rootNodeID := strings.TrimSpace(item.RootNodeID)+ if rootNodeID == "" {+ continue+ }+ children, err := api.listNodes(ctx, rootNodeID)+ if err != nil {+ return fmt.Errorf("validate DingTalk data source: %w", err)+ }+ for _, child := range children {+ if !child.isDocument() {+ continue+ }+ if _, err := api.documentBlocks(ctx, child.ID); err != nil {+ return fmt.Errorf("validate DingTalk data source: %w", err)+ }+ return nil+ }+ return nil+ }+ return nil+}++// ListResources lazily lists selectable workspaces, folders and documents.+func (c *Connector) ListResources(+ ctx context.Context,+ dataSourceConfig *types.DataSourceConfig,+ parentID string,+) ([]types.Resource, error) {+ cfg, err := parseConfig(dataSourceConfig)+ if err != nil {+ return nil, err+ }+ api := c.api(cfg)+ if strings.TrimSpace(parentID) == "" {+ workspaces, err := api.listWorkspaces(ctx)+ if err != nil {+ return nil, err+ }+ resources := make([]types.Resource, 0, len(workspaces))+ for _, item := range workspaces {+ if strings.TrimSpace(item.ID) == "" {+ continue+ }+ resourceID, err := encodeResourceReference(resourceReference{WorkspaceID: item.ID})+ if err != nil {+ return nil, err+ }+ name := strings.TrimSpace(item.Name)+ if name == "" {+ name = item.ID+ }+ resources = append(resources, types.Resource{+ ExternalID: resourceID,+ Name: name,+ Type: "wiki_space",+ Description: item.Description,+ URL: item.URL,+ ModifiedAt: parseDingTalkTime(item.ModifiedTime),+ HasChildren: strings.TrimSpace(item.RootNodeID) != "",+ Metadata: map[string]interface{}{+ "workspace_id": item.ID,+ },+ })+ }+ sortResources(resources)+ return resources, nil+ }++ parentRef, err := decodeResourceReference(parentID)+ if err != nil {+ return nil, err+ }+ parentNodeID := parentRef.NodeID+ if parentNodeID == "" {+ workspaces, err := api.listWorkspaces(ctx)+ if err != nil {+ return nil, err+ }+ item, exists := workspaceByID(workspaces, parentRef.WorkspaceID)+ if !exists {+ return nil, fmt.Errorf("%w: DingTalk workspace %q is unavailable",+ datasource.ErrResourceNotFound, parentRef.WorkspaceID)+ }+ parentNodeID = strings.TrimSpace(item.RootNodeID)+ if parentNodeID == "" {+ return []types.Resource{}, nil+ }+ } else {+ workspaces, err := api.listWorkspaces(ctx)+ if err != nil {+ return nil, err+ }+ scopes, failures, err := resolveSyncScopes(ctx, api, workspaces, []string{parentID})+ if err != nil {+ return nil, err+ }+ if failure := failures[parentID]; failure != nil {+ return nil, failure+ }+ if len(scopes) != 1 || scopes[0].Document != nil {+ return nil, fmt.Errorf("%w: DingTalk resource %q is not an expandable folder",+ datasource.ErrResourceNotFound, parentID)+ }+ parentNodeID = scopes[0].StartNodeID+ }++ children, err := api.listNodes(ctx, parentNodeID)+ if err != nil {+ return nil, err+ }+ resources := make([]types.Resource, 0, len(children))+ for _, child := range children {+ if !child.isFolder() && !child.isDocument() {+ continue+ }+ if child.WorkspaceID != "" && child.WorkspaceID != parentRef.WorkspaceID {+ return nil, fmt.Errorf("DingTalk node %q belongs to a different workspace", child.ID)+ }+ childRef := parentRef.child(child.ID)+ resourceID, err := encodeResourceReference(childRef)+ if err != nil {+ return nil, err+ }+ resourceType := "document"+ if child.isFolder() {+ resourceType = "folder"+ }+ resources = append(resources, types.Resource{+ ExternalID: resourceID,+ Name: child.title(),+ Type: resourceType,+ URL: child.URL,+ ModifiedAt: child.modifiedAt(),+ ParentID: parentID,+ HasChildren: child.isFolder(),+ Metadata: map[string]interface{}{+ "workspace_id": parentRef.WorkspaceID,+ "node_id": child.ID,+ "category": child.Category,+ "extension": child.Extension,+ },+ })+ }+ sortResources(resources)+ return resources, nil+}++// ResolveResourceAncestors restores the paths embedded in saved selections.+func (c *Connector) ResolveResourceAncestors(+ ctx context.Context,+ dataSourceConfig *types.DataSourceConfig,+ resourceIDs []string,+) ([]string, error) {+ if _, err := parseConfig(dataSourceConfig); err != nil {+ return nil, err+ }+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ seen := make(map[string]struct{})+ var ancestors []string+ for _, resourceID := range resourceIDs {+ ref, err := decodeResourceReference(resourceID)+ if err != nil {+ return nil, err+ }+ ids, err := resourceAncestorIDs(ref)+ if err != nil {+ return nil, err+ }+ for _, id := range ids {+ if _, exists := seen[id]; exists {+ continue+ }+ seen[id] = struct{}{}+ ancestors = append(ancestors, id)+ }+ }+ return ancestors, nil+}++func sortResources(resources []types.Resource) {+ sort.SliceStable(resources, func(i, j int) bool {+ left, right := strings.ToLower(resources[i].Name), strings.ToLower(resources[j].Name)+ if left == right {+ return resources[i].ExternalID < resources[j].ExternalID+ }+ return left < right+ })+}++func workspaceByID(workspaces []workspace, workspaceID string) (workspace, bool) {+ for _, item := range workspaces {+ if item.ID == workspaceID {+ return item, true+ }+ }+ return workspace{}, false+}++// FetchAll reads every supported document in the selected scopes.+func (c *Connector) FetchAll(+ ctx context.Context,+ dataSourceConfig *types.DataSourceConfig,+ resourceIDs []string,+) ([]types.FetchedItem, error) {+ items, _, err := c.sync(ctx, dataSourceConfig, resourceIDs, nil, syncMode{})+ return items, err+}++// FetchAllFromCursor re-fetches every document and reconciles deletions against+// the previous cursor so a scheduled full sync still honours deletion_sync.+func (c *Connector) FetchAllFromCursor(+ ctx context.Context,+ dataSourceConfig *types.DataSourceConfig,+ resourceIDs []string,+ cursor *types.SyncCursor,+) ([]types.FetchedItem, *types.SyncCursor, error) {+ if dataSourceConfig == nil {+ return nil, nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig)+ }+ previous, err := decodeCursor(cursor)+ if err != nil {+ return nil, nil, err+ }+ return c.syncAndEncodeCursor(+ ctx, dataSourceConfig, resourceIDs, previous,+ syncMode{reconcileDeletions: true},+ )+}++// FetchIncremental reads changed documents and reconciles complete selections.+func (c *Connector) FetchIncremental(+ ctx context.Context,+ dataSourceConfig *types.DataSourceConfig,+ cursor *types.SyncCursor,+) ([]types.FetchedItem, *types.SyncCursor, error) {+ if dataSourceConfig == nil {+ return nil, nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig)+ }+ previous, err := decodeCursor(cursor)+ if err != nil {+ return nil, nil, err+ }+ return c.syncAndEncodeCursor(+ ctx, dataSourceConfig, dataSourceConfig.ResourceIDs, previous,+ syncMode{skipUnchanged: true, reconcileDeletions: true},+ )+}++func (c *Connector) syncAndEncodeCursor(+ ctx context.Context,+ dataSourceConfig *types.DataSourceConfig,+ resourceIDs []string,+ previous *cursorState,+ mode syncMode,+) ([]types.FetchedItem, *types.SyncCursor, error) {+ items, next, syncErr := c.sync(ctx, dataSourceConfig, resourceIDs, previous, mode)+ if next == nil {+ return items, nil, syncErr+ }+ encoded, err := encodeCursor(next)+ if err != nil {+ return nil, nil, err+ }+ return items, &types.SyncCursor{+ LastSyncTime: next.SyncedAt,+ ConnectorCursor: encoded,+ }, syncErr+}++type cursorState struct {+ Version int `json:"version"`+ SyncedAt time.Time `json:"synced_at"`+ Resources map[string]map[string]string `json:"resources"`+ Workspaces map[string]map[string]string `json:"workspaces,omitempty"`+}++type syncMode struct {+ skipUnchanged bool+ reconcileDeletions bool+}++type syncScope struct {+ ResourceID string+ Reference resourceReference+ StartNodeID string+ Document *node+}++func (s syncScope) contains(candidate syncScope) bool {+ if s.Reference.WorkspaceID != candidate.Reference.WorkspaceID {+ return false+ }+ if s.Reference.NodeID == "" {+ return true+ }+ if s.Document != nil {+ return s.Reference.NodeID == candidate.Reference.NodeID+ }+ if s.Reference.NodeID == candidate.Reference.NodeID {+ return true+ }+ for _, ancestor := range candidate.Reference.Ancestors {+ if ancestor == s.Reference.NodeID {+ return true+ }+ }+ return false+}++func (c *Connector) sync(+ ctx context.Context,+ dataSourceConfig *types.DataSourceConfig,+ resourceIDs []string,+ previous *cursorState,+ mode syncMode,+) ([]types.FetchedItem, *cursorState, error) {+ cfg, err := parseConfig(dataSourceConfig)+ if err != nil {+ return nil, nil, err+ }+ selected := uniqueIDs(resourceIDs)+ if len(selected) == 0 {+ return nil, nil, errors.New("no DingTalk resources selected")+ }++ api := c.api(cfg)+ workspaces, err := api.listWorkspaces(ctx)+ if err != nil {+ return nil, nil, err+ }+ scopes, failures, err := resolveSyncScopes(ctx, api, workspaces, selected)+ if err != nil {+ return nil, nil, err+ }++ next := &cursorState{+ Version: cursorVersion,+ SyncedAt: time.Now().UTC(),+ Resources: make(map[string]map[string]string, len(scopes)),+ }+ var items []types.FetchedItem+ failedDocuments := 0+ complete := len(failures) == 0+ seenDocuments := make(map[string]struct{})+ type deletionCandidate struct {+ resourceID string+ documentID string+ revision string+ }+ var deletions []deletionCandidate+ for _, resourceID := range selected {+ if failure := failures[resourceID]; failure != nil {+ if previous != nil {+ next.Resources[resourceID] = cloneRevisions(previous.Resources[resourceID])+ }+ items = append(items, failedResource(resourceID, failure))+ }+ }++ for _, scope := range scopes {+ oldRevisions := map[string]string{}+ if previous != nil {+ if stored := previous.Resources[scope.ResourceID]; stored != nil {+ oldRevisions = stored+ }+ }+ documents, err := scanScope(ctx, api, scope)+ if err != nil {+ if isContextError(err) {+ return nil, nil, err+ }+ // Never infer deletions from an incomplete tree. Other independent+ // selections may still complete, while this scope keeps its previous+ // cursor and is retried on the next run.+ complete = false+ next.Resources[scope.ResourceID] = cloneRevisions(oldRevisions)+ items = append(items, failedResource(scope.ResourceID, err))+ continue+ }+ newRevisions := make(map[string]string, len(documents))+ currentDocuments := make(map[string]struct{}, len(documents))++ for _, document := range documents {+ if document.ID == "" {+ continue+ }+ seenDocuments[document.ID] = struct{}{}+ currentDocuments[document.ID] = struct{}{}+ revision := document.revision()+ oldRevision, existed := oldRevisions[document.ID]+ if mode.skipUnchanged && revision != "" && existed && revision == oldRevision {+ newRevisions[document.ID] = revision+ continue+ }++ blocks, err := api.documentBlocks(ctx, document.ID)+ if err != nil {+ if isContextError(err) {+ return nil, nil, err+ }+ items = append(items, failedDocument(+ scope.ResourceID, scope.Reference.WorkspaceID, document, err,+ ))+ failedDocuments+++ if existed {+ // Do not advance failed documents. The next incremental run+ // must retry them even if modifiedTime remains unchanged.+ newRevisions[document.ID] = oldRevision+ }+ continue+ }+ rendered := renderDocument(document.title(), blocks)+ items = append(items, fetchedDocument(+ scope.ResourceID, scope.Reference.WorkspaceID, document, rendered,+ ))+ newRevisions[document.ID] = revision+ }++ if mode.reconcileDeletions {+ for documentID, revision := range oldRevisions {+ if _, exists := currentDocuments[documentID]; exists {+ continue+ }+ deletions = append(deletions, deletionCandidate{scope.ResourceID, documentID, revision})+ }+ }+ next.Resources[scope.ResourceID] = newRevisions+ }++ // Reconcile the union of all selections. Moving a document between two+ // selected folders must never generate both an upsert and a deletion.+ // An unavailable scope could contain a moved document, so defer deletions+ // and retain their revisions until every scope can be scanned again.+ sort.Slice(deletions, func(i, j int) bool { return deletions[i].documentID < deletions[j].documentID })+ deleted := make(map[string]struct{})+ for _, candidate := range deletions {+ if _, visible := seenDocuments[candidate.documentID]; visible {+ continue+ }+ if !complete {+ next.Resources[candidate.resourceID][candidate.documentID] = candidate.revision+ continue+ }+ if _, exists := deleted[candidate.documentID]; exists {+ continue+ }+ deleted[candidate.documentID] = struct{}{}+ items = append(items, types.FetchedItem{+ ExternalID: candidate.documentID, IsDeleted: true, SourceResourceID: candidate.resourceID,+ })+ }+ if !mode.skipUnchanged && !mode.reconcileDeletions {+ next = nil+ }+ if !complete || failedDocuments > 0 {+ // Failure items carry localized reason codes. Returning the same raw+ // diagnostics in Details would duplicate them as untranslated UI text.+ return items, next, &datasource.PartialFetchError{}+ }+ return items, next, nil+}++func resolveSyncScopes(+ ctx context.Context,+ api dingTalkAPI,+ workspaces []workspace,+ resourceIDs []string,+) ([]syncScope, map[string]error, error) {+ byID := make(map[string]workspace, len(workspaces))+ for _, item := range workspaces {+ byID[item.ID] = item+ }+ childrenCache := make(map[string][]node)+ listChildren := func(parentNodeID string) ([]node, error) {+ if cached, exists := childrenCache[parentNodeID]; exists {+ return cached, nil+ }+ children, err := api.listNodes(ctx, parentNodeID)+ if err != nil {+ return nil, err+ }+ childrenCache[parentNodeID] = children+ return children, nil+ }++ resolve := func(resourceID string) (syncScope, error) {+ ref, err := decodeResourceReference(resourceID)+ if err != nil {+ return syncScope{}, err+ }+ canonicalID, err := encodeResourceReference(ref)+ if err != nil {+ return syncScope{}, err+ }+ item, exists := byID[ref.WorkspaceID]+ if !exists {+ return syncScope{}, fmt.Errorf("%w: DingTalk workspace %q is unavailable",+ datasource.ErrResourceNotFound, ref.WorkspaceID)+ }+ rootNodeID := strings.TrimSpace(item.RootNodeID)+ if rootNodeID == "" {+ return syncScope{}, fmt.Errorf("DingTalk workspace %q has no root node", ref.WorkspaceID)+ }+ if ref.NodeID == "" {+ return syncScope{+ ResourceID: canonicalID, Reference: ref, StartNodeID: rootNodeID,+ }, nil+ }++ parentNodeID := rootNodeID+ for _, ancestorID := range ref.Ancestors {+ children, err := listChildren(parentNodeID)+ if err != nil {+ return syncScope{}, fmt.Errorf("resolve DingTalk resource path: %w", err)+ }+ ancestor, exists := childByID(children, ancestorID)+ if !exists || !ancestor.isFolder() {+ return syncScope{}, fmt.Errorf("%w: DingTalk ancestor %q is unavailable",+ datasource.ErrResourceNotFound, ancestorID)+ }+ if ancestor.WorkspaceID != "" && ancestor.WorkspaceID != ref.WorkspaceID {+ return syncScope{}, fmt.Errorf("DingTalk ancestor %q belongs to a different workspace", ancestorID)+ }+ parentNodeID = ancestor.ID+ }+ children, err := listChildren(parentNodeID)+ if err != nil {+ return syncScope{}, fmt.Errorf("resolve DingTalk resource: %w", err)+ }+ selectedNode, exists := childByID(children, ref.NodeID)+ if !exists {+ return syncScope{}, fmt.Errorf("%w: DingTalk node %q is unavailable",+ datasource.ErrResourceNotFound, ref.NodeID)+ }+ if selectedNode.WorkspaceID != "" && selectedNode.WorkspaceID != ref.WorkspaceID {+ return syncScope{}, fmt.Errorf("DingTalk node %q belongs to a different workspace", ref.NodeID)+ }+ switch {+ case selectedNode.isFolder():+ return syncScope{+ ResourceID: canonicalID, Reference: ref, StartNodeID: selectedNode.ID,+ }, nil+ case selectedNode.isDocument():+ document := selectedNode+ return syncScope{+ ResourceID: canonicalID, Reference: ref, Document: &document,+ }, nil+ default:+ return syncScope{}, fmt.Errorf("DingTalk node %q is not a supported online document or folder",+ ref.NodeID)+ }+ }+ var scopes []syncScope+ failures := make(map[string]error)+ for _, resourceID := range resourceIDs {+ scope, err := resolve(resourceID)+ if err != nil {+ if isContextError(err) {+ return nil, nil, err+ }+ failures[resourceID] = err+ continue+ }+ scopes = append(scopes, scope)+ }++ sort.SliceStable(scopes, func(i, j int) bool {+ leftDepth := len(scopes[i].Reference.Ancestors)+ rightDepth := len(scopes[j].Reference.Ancestors)+ if scopes[i].Reference.NodeID != "" {+ leftDepth+++ }+ if scopes[j].Reference.NodeID != "" {+ rightDepth+++ }+ if leftDepth == rightDepth {+ return scopes[i].ResourceID < scopes[j].ResourceID+ }+ return leftDepth < rightDepth+ })+ compacted := make([]syncScope, 0, len(scopes))+ for _, scope := range scopes {+ covered := false+ for _, parent := range compacted {+ if parent.contains(scope) {+ covered = true+ break+ }+ }+ if !covered {+ compacted = append(compacted, scope)+ }+ }+ return compacted, failures, nil+}++func childByID(children []node, nodeID string) (node, bool) {+ for _, child := range children {+ if child.ID == nodeID {+ return child, true+ }+ }+ return node{}, false+}++func scanScope(ctx context.Context, api dingTalkAPI, scope syncScope) ([]node, error) {+ if scope.Document != nil {+ return []node{*scope.Document}, nil+ }+ return scanWorkspace(ctx, api, scope.Reference.WorkspaceID, scope.StartNodeID)+}++func scanWorkspace(+ ctx context.Context,+ api dingTalkAPI,+ workspaceID string,+ rootNodeID string,+) ([]node, error) {+ queue := []string{rootNodeID}+ visitedParents := make(map[string]struct{})+ seenNodes := make(map[string]struct{})+ var documents []node++ for len(queue) > 0 {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ parentID := queue[0]+ queue = queue[1:]+ if _, visited := visitedParents[parentID]; visited {+ continue+ }+ visitedParents[parentID] = struct{}{}++ children, err := api.listNodes(ctx, parentID)+ if err != nil {+ return nil, err+ }+ for _, child := range children {+ if child.ID == "" {+ continue+ }+ if child.WorkspaceID != "" && child.WorkspaceID != workspaceID {+ return nil, fmt.Errorf("DingTalk node %q belongs to a different workspace", child.ID)+ }+ if _, seen := seenNodes[child.ID]; seen {+ continue+ }+ seenNodes[child.ID] = struct{}{}+ if len(seenNodes) > maxTraversalNodes {+ return nil, fmt.Errorf("DingTalk workspace exceeds %d nodes", maxTraversalNodes)+ }+ if child.isDocument() {+ documents = append(documents, child)+ }+ if child.isFolder() || child.HasChildren {+ queue = append(queue, child.ID)+ }+ }+ }+ sort.SliceStable(documents, func(i, j int) bool {+ return documents[i].ID < documents[j].ID+ })+ return documents, nil+}++func cloneRevisions(revisions map[string]string) map[string]string {+ cloned := make(map[string]string, len(revisions))+ for documentID, revision := range revisions {+ cloned[documentID] = revision+ }+ return cloned+}++type renderResult struct {+ Markdown string+ UnknownTypes []string+}++func fetchedDocument(+ sourceResourceID string,+ workspaceID string,+ document node,+ rendered renderResult,+) types.FetchedItem {+ metadata := map[string]string{+ "channel": types.ChannelDingtalk,+ "workspace_id": workspaceID,+ "node_id": document.ID,+ "category": document.Category,+ "extension": document.Extension,+ }+ if len(rendered.UnknownTypes) > 0 {+ metadata["unknown_block_types"] = strings.Join(rendered.UnknownTypes, ",")+ }+ documentURL := strings.TrimSpace(document.URL)+ if documentURL == "" {+ documentURL = "https://alidocs.dingtalk.com/i/nodes/" + url.PathEscape(document.ID)+ }+ return types.FetchedItem{+ ExternalID: document.ID,+ Title: document.title(),+ Content: []byte(rendered.Markdown),+ ContentType: "text/markdown",+ FileName: sanitizeFilename(document.title()) + ".md",+ URL: documentURL,+ UpdatedAt: document.modifiedAt(),+ Metadata: metadata,+ SourceResourceID: sourceResourceID,+ }+}++func failedDocument(+ sourceResourceID string,+ workspaceID string,+ document node,+ err error,+) types.FetchedItem {+ return types.FetchedItem{+ ExternalID: document.ID,+ Title: document.title(),+ SourceResourceID: sourceResourceID,+ Metadata: map[string]string{+ "channel": types.ChannelDingtalk,+ "workspace_id": workspaceID,+ "node_id": document.ID,+ "error": err.Error(),+ "error_reason_code": "dingtalk_document_failed",+ "error_reason": "DingTalk document could not be read; retry on the next sync",+ },+ }+}++func failedResource(resourceID string, err error) types.FetchedItem {+ return types.FetchedItem{+ ExternalID: "dingtalk-resource:" + resourceID,+ SourceResourceID: resourceID,+ Metadata: map[string]string{+ "channel": types.ChannelDingtalk,+ "error": err.Error(),+ "error_reason_code": "dingtalk_resource_failed",+ "error_reason": "DingTalk resource is unavailable; check access and the saved selection, then retry",+ },+ }+}++func decodeCursor(cursor *types.SyncCursor) (*cursorState, error) {+ empty := &cursorState{+ Version: cursorVersion,+ Resources: make(map[string]map[string]string),+ }+ if cursor == nil || cursor.ConnectorCursor == nil {+ return empty, nil+ }+ raw, err := json.Marshal(cursor.ConnectorCursor)+ if err != nil {+ return nil, fmt.Errorf("marshal DingTalk cursor: %w", err)+ }+ var decoded cursorState+ if err := json.Unmarshal(raw, &decoded); err != nil {+ return nil, fmt.Errorf("decode DingTalk cursor: %w", err)+ }+ switch decoded.Version {+ case 1:+ decoded.Resources = make(map[string]map[string]string, len(decoded.Workspaces))+ for workspaceID, revisions := range decoded.Workspaces {+ decoded.Resources[workspaceID] = cloneRevisions(revisions)+ }+ decoded.Workspaces = nil+ decoded.Version = cursorVersion+ case cursorVersion:+ default:+ return nil, fmt.Errorf("unsupported DingTalk cursor version %d", decoded.Version)+ }+ if decoded.Resources == nil {+ decoded.Resources = make(map[string]map[string]string)+ }+ return &decoded, nil+}++func encodeCursor(cursor *cursorState) (map[string]interface{}, error) {+ raw, err := json.Marshal(cursor)+ if err != nil {+ return nil, fmt.Errorf("marshal DingTalk cursor: %w", err)+ }+ var encoded map[string]interface{}+ if err := json.Unmarshal(raw, &encoded); err != nil {+ return nil, fmt.Errorf("encode DingTalk cursor: %w", err)+ }+ return encoded, nil+}++func uniqueIDs(ids []string) []string {+ seen := make(map[string]struct{}, len(ids))+ out := make([]string, 0, len(ids))+ for _, id := range ids {+ id = strings.TrimSpace(id)+ if id == "" {+ continue+ }+ if _, exists := seen[id]; exists {+ continue+ }+ seen[id] = struct{}{}+ out = append(out, id)+ }+ return out+}++func parseDingTalkTime(value string) time.Time {+ value = strings.TrimSpace(value)+ if value == "" {+ return time.Time{}+ }+ for _, layout := range []string{+ time.RFC3339Nano,+ time.RFC3339,+ "2006-01-02T15:04:05Z07:00",+ "2006-01-02T15:04Z07:00",+ "2006-01-02T15:04:05Z",+ "2006-01-02T15:04Z",+ } {+ if parsed, err := time.Parse(layout, value); err == nil {+ return parsed+ }+ }+ return time.Time{}+}++func sanitizeFilename(name string) string {+ name = strings.TrimSpace(name)+ name = strings.Map(func(value rune) rune {+ if unicode.IsControl(value) {+ return '_'+ }+ return value+ }, name)+ name = strings.NewReplacer(+ "/", "_", "\\", "_", ":", "_", "*", "_", "?", "_",+ "\"", "_", "<", "_", ">", "_", "|", "_",+ ).Replace(name)+ name = strings.Trim(name, " ._")+ if name == "" {+ return "untitled"+ }++ const maxBytes = 200+ if len(name) > maxBytes {+ name = name[:maxBytes]+ for len(name) > 0 {+ r, size := utf8.DecodeLastRuneInString(name)+ if r != utf8.RuneError || size != 1 {+ break+ }+ name = name[:len(name)-1]+ }+ name = strings.Trim(name, " ._")+ }+ if name == "" {+ return "untitled"+ }+ return name+}diff --git a/internal/datasource/connector/dingtalk/connector_test.go b/internal/datasource/connector/dingtalk/connector_test.gonew file mode 100644index 000000000..915d37191--- /dev/null+++ b/internal/datasource/connector/dingtalk/connector_test.go@@ -0,0 +1,443 @@+package dingtalk++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/types"+)++type fakeAPI struct {+ workspaces []workspace+ nodes map[string][]node+ blocks map[string][]json.RawMessage+ nodeErrors map[string]error+ blockErrors map[string]error+ blockCalls map[string]int+}++func (f *fakeAPI) listWorkspaces(context.Context) ([]workspace, error) {+ return f.workspaces, nil+}++func (f *fakeAPI) listNodes(_ context.Context, parentID string) ([]node, error) {+ if err := f.nodeErrors[parentID]; err != nil {+ return nil, err+ }+ return f.nodes[parentID], nil+}++func (f *fakeAPI) documentBlocks(_ context.Context, documentID string) ([]json.RawMessage, error) {+ if f.blockCalls == nil {+ f.blockCalls = make(map[string]int)+ }+ f.blockCalls[documentID]+++ if err := f.blockErrors[documentID]; err != nil {+ return nil, err+ }+ return f.blocks[documentID], nil+}++func testConnector(api dingTalkAPI) *Connector {+ return &Connector{newAPI: func(*config) dingTalkAPI { return api }}+}++func testConfig(resources ...string) *types.DataSourceConfig {+ return &types.DataSourceConfig{+ Type: types.ConnectorTypeDingTalk,+ Credentials: map[string]interface{}{+ "client_id": "ding-app",+ "client_secret": "secret",+ "operator_id": "union-id",+ },+ ResourceIDs: resources,+ }+}++func rawJSON(value string) json.RawMessage {+ return json.RawMessage(value)+}++func TestConnectorListsWorkspacesAndFetchesNestedDocuments(t *testing.T) {+ api := &fakeAPI{+ workspaces: []workspace{+ {ID: "b", RootNodeID: "root-b", Name: "Beta"},+ {ID: "a", RootNodeID: "root-a", Name: "Alpha", Description: "Team docs"},+ },+ nodes: map[string][]node{+ "root-a": {+ {ID: "folder", Type: "FOLDER"},+ {ID: "ignored", Type: "FILE", Category: "FILE", Extension: "pdf"},+ },+ "folder": {+ {+ ID: "doc-1", Type: "FILE", Category: "ALIDOC", Extension: "adoc",+ Name: "Roadmap", WorkspaceID: "a", ModifiedTime: "2026-07-25T08:00:00Z",+ },+ },+ },+ blocks: map[string][]json.RawMessage{+ "doc-1": {rawJSON(`{+ "blockType":"paragraph",+ "children":[{"elementType":"text","text":"Q3 goals","bold":true}]+ }`)},+ },+ nodeErrors: make(map[string]error),+ blockErrors: make(map[string]error),+ }+ connector := testConnector(api)++ resources, err := connector.ListResources(context.Background(), testConfig(), "")+ if err != nil {+ t.Fatalf("ListResources() error = %v", err)+ }+ if len(resources) != 2 || resources[0].ExternalID != "a" || resources[1].ExternalID != "b" {+ t.Fatalf("ListResources() = %#v, want workspaces sorted by name", resources)+ }+ if !resources[0].HasChildren {+ t.Fatalf("workspace resource = %#v, want expandable", resources[0])+ }+ children, err := connector.ListResources(context.Background(), testConfig(), "a")+ if err != nil || len(children) != 1 || children[0].Type != "folder" {+ t.Fatalf("workspace children = %#v, %v; want one folder", children, err)+ }+ folderID := children[0].ExternalID+ documents, err := connector.ListResources(context.Background(), testConfig(), folderID)+ if err != nil || len(documents) != 1 || documents[0].Type != "document" {+ t.Fatalf("folder children = %#v, %v; want one document", documents, err)+ }+ if _, err := connector.ListResources(+ context.Background(), testConfig(), documents[0].ExternalID,+ ); !errors.Is(err, datasource.ErrResourceNotFound) {+ t.Fatalf("expanding a document error = %v, want ErrResourceNotFound", err)+ }+ ancestors, err := connector.ResolveResourceAncestors(+ context.Background(), testConfig(), []string{documents[0].ExternalID},+ )+ if err != nil || len(ancestors) != 2 || ancestors[0] != "a" || ancestors[1] != folderID {+ t.Fatalf("ResolveResourceAncestors() = %#v, %v", ancestors, err)+ }++ items, err := connector.FetchAll(context.Background(), testConfig("a"), []string{"a"})+ if err != nil {+ t.Fatalf("FetchAll() error = %v", err)+ }+ if len(items) != 1 {+ t.Fatalf("FetchAll() returned %d items, want 1", len(items))+ }+ item := items[0]+ if item.ExternalID != "doc-1" || item.Title != "Roadmap" ||+ string(item.Content) != "# Roadmap\n\n**Q3 goals**\n" {+ t.Fatalf("FetchAll() item = %#v", item)+ }+ if item.ContentType != "text/markdown" || item.SourceResourceID != "a" ||+ item.Metadata["channel"] != types.ChannelDingtalk {+ t.Fatalf("FetchAll() metadata = %#v", item)+ }+}++func TestIncrementalSyncRetriesFailuresAndReportsDeletions(t *testing.T) {+ api := &fakeAPI{+ workspaces: []workspace{{ID: "space", RootNodeID: "root", Name: "Space"}},+ nodes: map[string][]node{+ "root": {+ {ID: "unchanged", Type: "FILE", Category: "ALIDOC", Extension: "adoc", ModifiedTime: "r1"},+ {ID: "changed", Type: "FILE", Category: "ALIDOC", Extension: "adoc", ModifiedTime: "r2"},+ {ID: "broken", Type: "FILE", Category: "ALIDOC", Extension: "adoc", ModifiedTime: "r2"},+ },+ },+ blocks: map[string][]json.RawMessage{+ "changed": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"updated"}}`)},+ },+ nodeErrors: make(map[string]error),+ blockErrors: map[string]error{"broken": errors.New("permission denied")},+ }+ connector := testConnector(api)+ cursorMap, err := encodeCursor(&cursorState{+ Version: cursorVersion,+ Resources: map[string]map[string]string{+ "space": {+ "unchanged": "r1",+ "changed": "r1",+ "broken": "r1",+ "deleted": "r1",+ },+ },+ })+ if err != nil {+ t.Fatal(err)+ }++ items, next, syncErr := connector.FetchIncremental(+ context.Background(),+ testConfig("space"),+ &types.SyncCursor{ConnectorCursor: cursorMap},+ )+ var partial *datasource.PartialFetchError+ if !errors.As(syncErr, &partial) {+ t.Fatalf("FetchIncremental() error = %v, want PartialFetchError", syncErr)+ }+ if next == nil {+ t.Fatal("FetchIncremental() returned nil cursor")+ }+ if api.blockCalls["unchanged"] != 0 || api.blockCalls["changed"] != 1 ||+ api.blockCalls["broken"] != 1 {+ t.Fatalf("document block calls = %#v", api.blockCalls)+ }++ byID := make(map[string]types.FetchedItem, len(items))+ for _, item := range items {+ byID[item.ExternalID] = item+ }+ if len(byID) != 3 || !byID["deleted"].IsDeleted {+ t.Fatalf("FetchIncremental() items = %#v", items)+ }+ if byID["broken"].Metadata["error"] == "" {+ t.Fatalf("failed item metadata = %#v", byID["broken"].Metadata)+ }++ decoded, err := decodeCursor(next)+ if err != nil {+ t.Fatal(err)+ }+ revisions := decoded.Resources["space"]+ if revisions["unchanged"] != "r1" || revisions["changed"] != "r2" ||+ revisions["broken"] != "r1" {+ t.Fatalf("next cursor revisions = %#v", revisions)+ }+ if _, exists := revisions["deleted"]; exists {+ t.Fatalf("deleted document remained in cursor: %#v", revisions)+ }+}++func TestIncrementalSyncDoesNotInferDeletionsFromIncompleteTree(t *testing.T) {+ api := &fakeAPI{+ workspaces: []workspace{{ID: "space", RootNodeID: "root"}},+ nodes: map[string][]node{+ "root": {{ID: "folder", Type: "FOLDER"}},+ },+ nodeErrors: map[string]error{"folder": errors.New("temporary failure")},+ blockErrors: make(map[string]error),+ }+ cursorMap, err := encodeCursor(&cursorState{+ Version: cursorVersion,+ Resources: map[string]map[string]string{+ "space": {"existing": "r1"},+ },+ })+ if err != nil {+ t.Fatal(err)+ }++ items, next, err := testConnector(api).FetchIncremental(+ context.Background(),+ testConfig("space"),+ &types.SyncCursor{ConnectorCursor: cursorMap},+ )+ var partial *datasource.PartialFetchError+ if !errors.As(err, &partial) {+ t.Fatalf("FetchIncremental() error = %v, want PartialFetchError", err)+ }+ if len(items) != 1 || items[0].Metadata["error_reason_code"] != "dingtalk_resource_failed" || next == nil {+ t.Fatalf("FetchIncremental() = %#v, %#v; want preserved cursor", items, next)+ }+ decoded, decodeErr := decodeCursor(next)+ if decodeErr != nil {+ t.Fatal(decodeErr)+ }+ if decoded.Resources["space"]["existing"] != "r1" {+ t.Fatalf("preserved cursor = %#v", decoded.Resources)+ }+}++func TestConnectorSupportsFolderAndDocumentScopesWithoutDuplicates(t *testing.T) {+ api := &fakeAPI{+ workspaces: []workspace{{ID: "space", RootNodeID: "root"}},+ nodes: map[string][]node{+ "root": {+ {ID: "folder", WorkspaceID: "space", Type: "FOLDER", Name: "Folder"},+ {+ ID: "standalone", WorkspaceID: "space", Type: "FILE",+ Category: "ALIDOC", Extension: "adoc", Name: "Standalone",+ },+ },+ "folder": {+ {+ ID: "nested", WorkspaceID: "space", Type: "FILE",+ Category: "ALIDOC", Extension: "adoc", Name: "Nested",+ },+ },+ },+ blocks: map[string][]json.RawMessage{+ "standalone": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"one"}}`)},+ "nested": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"two"}}`)},+ },+ nodeErrors: make(map[string]error),+ blockErrors: make(map[string]error),+ }+ connector := testConnector(api)+ folderID, err := encodeResourceReference(resourceReference{+ WorkspaceID: "space", NodeID: "folder",+ })+ if err != nil {+ t.Fatal(err)+ }+ nestedID, err := encodeResourceReference(resourceReference{+ WorkspaceID: "space", NodeID: "nested", Ancestors: []string{"folder"},+ })+ if err != nil {+ t.Fatal(err)+ }+ standaloneID, err := encodeResourceReference(resourceReference{+ WorkspaceID: "space", NodeID: "standalone",+ })+ if err != nil {+ t.Fatal(err)+ }++ items, err := connector.FetchAll(+ context.Background(),+ testConfig(folderID, nestedID, standaloneID),+ []string{folderID, nestedID, standaloneID},+ )+ if err != nil {+ t.Fatal(err)+ }+ if len(items) != 2 || api.blockCalls["nested"] != 1 || api.blockCalls["standalone"] != 1 {+ t.Fatalf("items = %#v, block calls = %#v", items, api.blockCalls)+ }+ byID := make(map[string]types.FetchedItem, len(items))+ for _, item := range items {+ byID[item.ExternalID] = item+ }+ if byID["nested"].SourceResourceID != folderID ||+ byID["standalone"].SourceResourceID != standaloneID {+ t.Fatalf("source resource IDs = %#v", byID)+ }+}++func TestConnectorRejectsCrossWorkspaceResourcePath(t *testing.T) {+ api := &fakeAPI{+ workspaces: []workspace{+ {ID: "space-a", RootNodeID: "root-a"},+ {ID: "space-b", RootNodeID: "root-b"},+ },+ nodes: map[string][]node{+ "root-a": {{+ ID: "foreign", WorkspaceID: "space-b", Type: "FILE",+ Category: "ALIDOC", Extension: "adoc",+ }},+ },+ nodeErrors: make(map[string]error),+ blockErrors: make(map[string]error),+ }+ resourceID, err := encodeResourceReference(resourceReference{+ WorkspaceID: "space-a", NodeID: "foreign",+ })+ if err != nil {+ t.Fatal(err)+ }+ items, err := testConnector(api).FetchAll(+ context.Background(), testConfig(resourceID), []string{resourceID},+ )+ var partial *datasource.PartialFetchError+ if !errors.As(err, &partial) || len(items) != 1 ||+ !strings.Contains(items[0].Metadata["error"], "different workspace") || len(api.blockCalls) != 0 {+ t.Fatalf("FetchAll() = %#v, %v; want isolated workspace mismatch", items, err)+ }+}++func TestDecodeCursorMigratesWorkspaceCursorV1(t *testing.T) {+ cursor := &types.SyncCursor{ConnectorCursor: map[string]interface{}{+ "version": 1,+ "workspaces": map[string]interface{}{+ "legacy-space": map[string]interface{}{"document": "revision"},+ },+ }}+ decoded, err := decodeCursor(cursor)+ if err != nil {+ t.Fatal(err)+ }+ if decoded.Version != cursorVersion ||+ decoded.Resources["legacy-space"]["document"] != "revision" {+ t.Fatalf("decoded cursor = %#v", decoded)+ }+}++func TestParseConfigRejectsMissingCredentials(t *testing.T) {+ for _, credentials := range []map[string]interface{}{+ nil,+ {"client_id": "app"},+ {"client_id": "app", "client_secret": "secret"},+ {"client_id": 42, "client_secret": "secret", "operator_id": "operator"},+ } {+ _, err := parseConfig(&types.DataSourceConfig{Credentials: credentials})+ if !errors.Is(err, datasource.ErrInvalidCredentials) {+ t.Fatalf("parseConfig(%#v) error = %v", credentials, err)+ }+ }+}++func TestNodeRevisionPrefersMillisecondTimestamp(t *testing.T) {+ n := node{ModifiedTime: "2023-05-15T11:29Z", ModifiedTimestamp: 1_684_148_940_123}+ if n.revision() != "1684148940123" {+ t.Fatalf("revision() = %q, want millisecond timestamp", n.revision())+ }+ if got := n.modifiedAt(); got.UnixMilli() != 1_684_148_940_123 {+ t.Fatalf("modifiedAt() = %s", got)+ }++ onlyTime := node{ModifiedTime: "2023-05-15T11:29Z"}+ if onlyTime.revision() != "2023-05-15T11:29Z" {+ t.Fatalf("revision() without timestamp = %q", onlyTime.revision())+ }+ if onlyTime.modifiedAt().IsZero() {+ t.Fatal("modifiedAt() rejected documented minute-precision time")+ }+}++func TestParseDingTalkTimeAcceptsMinutePrecision(t *testing.T) {+ parsed := parseDingTalkTime("2023-05-15T11:29Z")+ if parsed.IsZero() || parsed.UTC().Format("2006-01-02T15:04Z") != "2023-05-15T11:29Z" {+ t.Fatalf("parseDingTalkTime() = %s", parsed)+ }+}++func TestValidateProbesNodeAndDocumentAccess(t *testing.T) {+ api := &fakeAPI{+ workspaces: []workspace{{ID: "space", RootNodeID: "root"}},+ nodes: map[string][]node{+ "root": {syncDocument()},+ },+ blocks: map[string][]json.RawMessage{+ "doc": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"ok"}}`)},+ },+ nodeErrors: make(map[string]error),+ blockErrors: make(map[string]error),+ }+ if err := testConnector(api).Validate(context.Background(), testConfig()); err != nil {+ t.Fatalf("Validate() error = %v", err)+ }+ if api.blockCalls["doc"] != 1 {+ t.Fatalf("document probe calls = %#v", api.blockCalls)+ }++ api.blockErrors["doc"] = errors.New("missing Storage.File.Read")+ if err := testConnector(api).Validate(context.Background(), testConfig()); err == nil {+ t.Fatal("Validate() error = nil, want document access failure")+ }++ api = &fakeAPI{+ workspaces: []workspace{{ID: "space", RootNodeID: "root"}},+ nodes: map[string][]node{},+ nodeErrors: map[string]error{"root": errors.New("missing Wiki.Node.Read")},+ blockErrors: make(map[string]error),+ }+ if err := testConnector(api).Validate(context.Background(), testConfig()); err == nil {+ t.Fatal("Validate() error = nil, want node access failure")+ }+}diff --git a/internal/datasource/connector/dingtalk/markdown.go b/internal/datasource/connector/dingtalk/markdown.gonew file mode 100644index 000000000..5eabe61ce--- /dev/null+++ b/internal/datasource/connector/dingtalk/markdown.go@@ -0,0 +1,441 @@+package dingtalk++import (+ "encoding/json"+ "fmt"+ "net/url"+ "sort"+ "strconv"+ "strings"+)++const maxRenderDepth = 32++type block struct {+ BlockType string `json:"blockType"`+ Paragraph textBlock `json:"paragraph"`+ Heading headingBlock `json:"heading"`+ Blockquote textBlock `json:"blockquote"`+ OrderedList listBlock `json:"orderedList"`+ UnorderedList listBlock `json:"unorderedList"`+ Table tableBlock `json:"table"`+ Children []json.RawMessage `json:"children"`+}++type textBlock struct {+ Text string `json:"text"`+}++type headingBlock struct {+ Level flexibleInt `json:"level"`+ Text string `json:"text"`+}++type listBlock struct {+ List struct {+ Level flexibleInt `json:"level"`+ } `json:"list"`+}++type tableBlock struct {+ Cells json.RawMessage `json:"cells"`+}++type inline struct {+ ElementType string `json:"elementType"`+ Text string `json:"text"`+ Bold bool `json:"bold"`+ Italic bool `json:"italic"`+ Strike bool `json:"strike"`+ Stike bool `json:"stike"` // DingTalk payloads have used this misspelling.+ Fonts string `json:"fonts"`+ Properties inlineProperties `json:"properties"`+ Children []json.RawMessage `json:"children"`+}++type inlineProperties struct {+ Code string `json:"code"`+ Src string `json:"src"`+ Href string `json:"href"`+}++func renderDocument(title string, blocks []json.RawMessage) renderResult {+ var builder strings.Builder+ if title = strings.TrimSpace(title); title != "" {+ title = strings.NewReplacer("\r", " ", "\n", " ").Replace(title)+ builder.WriteString("# ")+ builder.WriteString(escapeText(title))+ builder.WriteString("\n\n")+ }++ unknown := make(map[string]struct{})+ for _, raw := range blocks {+ renderBlock(&builder, raw, 0, unknown)+ }++ markdown := strings.TrimSpace(builder.String())+ if markdown != "" {+ markdown += "\n"+ }+ unknownTypes := make([]string, 0, len(unknown))+ for blockType := range unknown {+ unknownTypes = append(unknownTypes, blockType)+ }+ sort.Strings(unknownTypes)+ return renderResult{Markdown: markdown, UnknownTypes: unknownTypes}+}++func renderBlock(+ builder *strings.Builder,+ raw json.RawMessage,+ depth int,+ unknown map[string]struct{},+) {+ if depth > maxRenderDepth {+ unknown["max_depth"] = struct{}{}+ return+ }++ var value block+ if err := json.Unmarshal(raw, &value); err != nil {+ unknown["invalid_json"] = struct{}{}+ return+ }++ blockType := strings.ToLower(strings.TrimSpace(value.BlockType))+ switch blockType {+ case "paragraph":+ text := renderInlines(value.Children, depth+1, unknown)+ if text == "" {+ text = escapeText(value.Paragraph.Text)+ }+ writeParagraph(builder, text)+ case "heading":+ text := renderInlines(value.Children, depth+1, unknown)+ if text == "" {+ text = escapeText(value.Heading.Text)+ }+ if text == "" {+ return+ }+ level := int(value.Heading.Level)+ if level < 1 {+ level = 1+ } else if level > 6 {+ level = 6+ }+ fmt.Fprintf(builder, "%s %s\n\n", strings.Repeat("#", level), text)+ case "blockquote":+ text := renderInlines(value.Children, depth+1, unknown)+ if text == "" {+ text = escapeText(value.Blockquote.Text)+ }+ if text == "" {+ return+ }+ for _, line := range strings.Split(text, "\n") {+ fmt.Fprintf(builder, "> %s\n", line)+ }+ builder.WriteByte('\n')+ case "orderedlist", "unorderedlist":+ text := renderInlines(value.Children, depth+1, unknown)+ if text == "" {+ var nested strings.Builder+ renderChildBlocks(&nested, value.Children, depth, unknown)+ text = strings.Join(strings.Fields(strings.TrimSpace(nested.String())), " ")+ }+ if text == "" {+ return+ }+ level, marker := int(value.UnorderedList.List.Level), "- "+ if blockType == "orderedlist" {+ level, marker = int(value.OrderedList.List.Level), "1. "+ }+ if level < 0 {+ level = 0+ } else if level > maxRenderDepth {+ level = maxRenderDepth+ }+ fmt.Fprintf(builder, "%s%s%s\n", strings.Repeat(" ", level), marker, text)+ case "callout", "columns":+ if len(value.Children) == 0 {+ // The Blocks API only returns first-level blocks. A container with+ // no inlined children is indistinguishable from an empty callout,+ // so surface it instead of silently dropping nested body text.+ unknown["nested_blocks_unavailable"] = struct{}{}+ return+ }+ renderChildBlocks(builder, value.Children, depth, unknown)+ case "table":+ renderTable(builder, parseTableCells(value.Table.Cells))+ case "":+ unknown["missing_block_type"] = struct{}{}+ default:+ unknown[blockType] = struct{}{}+ // Preserve useful content when DingTalk introduces a container block+ // before the connector learns its presentation semantics.+ renderChildBlocks(builder, value.Children, depth, unknown)+ }+}++func renderChildBlocks(+ builder *strings.Builder,+ children []json.RawMessage,+ depth int,+ unknown map[string]struct{},+) {+ for _, child := range children {+ renderBlock(builder, child, depth+1, unknown)+ }+}++func renderInlines(+ children []json.RawMessage,+ depth int,+ unknown map[string]struct{},+) string {+ if depth > maxRenderDepth {+ unknown["inline_max_depth"] = struct{}{}+ return ""+ }++ var builder strings.Builder+ for _, raw := range children {+ var value inline+ if err := json.Unmarshal(raw, &value); err != nil {+ unknown["invalid_inline_json"] = struct{}{}+ continue+ }++ elementType := strings.ToLower(strings.TrimSpace(value.ElementType))+ switch elementType {+ case "", "text":+ builder.WriteString(styleText(value.Text, value))+ case "sticker":+ builder.WriteString(escapeText(value.Properties.Code))+ case "image":+ if src, ok := safeURL(value.Properties.Src); ok {+ fmt.Fprintf(&builder, "", src)+ }+ case "link":+ label := renderInlines(value.Children, depth+1, unknown)+ href, ok := safeURL(value.Properties.Href)+ if !ok {+ builder.WriteString(label)+ } else if label == "" {+ fmt.Fprintf(&builder, "[%s](%s)", escapeLabel(href), href)+ } else {+ fmt.Fprintf(&builder, "[%s](%s)", label, href)+ }+ default:+ unknown["inline_"+elementType] = struct{}{}+ builder.WriteString(escapeText(value.Text))+ }+ }+ return builder.String()+}++func styleText(text string, value inline) string {+ text = strings.ReplaceAll(text, "\x00", "")+ if text == "" {+ return ""+ }+ if strings.EqualFold(value.Fonts, "monospace") {+ text = codeSpan(text)+ } else {+ text = escapeText(text)+ }+ if value.Bold {+ text = "**" + text + "**"+ }+ if value.Italic {+ text = "*" + text + "*"+ }+ if value.Strike || value.Stike {+ text = "~~" + text + "~~"+ }+ return text+}++func safeURL(value string) (string, bool) {+ value = strings.TrimSpace(value)+ parsed, err := url.Parse(value)+ if err != nil || parsed.Scheme == "" {+ return "", false+ }+ switch strings.ToLower(parsed.Scheme) {+ case "http", "https", "mailto":+ return strings.NewReplacer(+ "\\", "%5C",+ " ", "%20",+ "(", "%28",+ ")", "%29",+ "<", "%3C",+ ">", "%3E",+ ).Replace(value), true+ default:+ return "", false+ }+}++func writeParagraph(builder *strings.Builder, text string) {+ if text != "" {+ builder.WriteString(text)+ builder.WriteString("\n\n")+ }+}++func renderTable(builder *strings.Builder, rows [][]string) {+ columns := 0+ for _, row := range rows {+ if len(row) > columns {+ columns = len(row)+ }+ }+ if columns == 0 {+ return+ }++ writeTableRow(builder, normalizeRow(rows[0], columns))+ separator := make([]string, columns)+ for index := range separator {+ separator[index] = "---"+ }+ writeTableRow(builder, separator)+ for _, row := range rows[1:] {+ writeTableRow(builder, normalizeRow(row, columns))+ }+ builder.WriteByte('\n')+}++func normalizeRow(row []string, columns int) []string {+ normalized := make([]string, columns)+ for index := 0; index < len(row) && index < columns; index++ {+ normalized[index] = escapeTableCell(row[index])+ }+ return normalized+}++func writeTableRow(builder *strings.Builder, row []string) {+ fmt.Fprintf(builder, "| %s |\n", strings.Join(row, " | "))+}++func escapeText(value string) string {+ value = strings.ReplaceAll(value, "\x00", "")+ value = strings.ReplaceAll(value, "\\", "\\\\")+ return strings.NewReplacer(+ "`", "\\`",+ "*", "\\*",+ "_", "\\_",+ "{", "\\{",+ "}", "\\}",+ "[", "\\[",+ "]", "\\]",+ "<", "\\<",+ ">", "\\>",+ "#", "\\#",+ "+", "\\+",+ "-", "\\-",+ "!", "\\!",+ ).Replace(value)+}++func escapeLabel(value string) string {+ value = strings.ReplaceAll(value, "\\", "\\\\")+ value = strings.ReplaceAll(value, "[", "\\[")+ return strings.ReplaceAll(value, "]", "\\]")+}++func escapeTableCell(value string) string {+ value = escapeText(value)+ value = strings.ReplaceAll(value, "|", "\\|")+ value = strings.ReplaceAll(value, "\r\n", "<br>")+ return strings.ReplaceAll(value, "\n", "<br>")+}++func codeSpan(value string) string {+ delimiter := "`"+ for strings.Contains(value, delimiter) {+ delimiter += "`"+ }+ if len(delimiter) == 1 {+ return delimiter + value + delimiter+ }+ return delimiter + " " + value + " " + delimiter+}++type flexibleInt int++func (f *flexibleInt) UnmarshalJSON(data []byte) error {+ *f = 0+ if len(data) == 0 || string(data) == "null" {+ return nil+ }+ var n int+ if err := json.Unmarshal(data, &n); err == nil {+ *f = flexibleInt(n)+ return nil+ }+ var s string+ if err := json.Unmarshal(data, &s); err != nil {+ return nil+ }+ s = strings.ToLower(strings.TrimSpace(s))+ s = strings.TrimPrefix(s, "heading-")+ s = strings.TrimPrefix(s, "h")+ n, err := strconv.Atoi(s)+ if err != nil {+ return nil+ }+ *f = flexibleInt(n)+ return nil+}++func parseTableCells(raw json.RawMessage) [][]string {+ if len(raw) == 0 || string(raw) == "null" {+ return nil+ }+ var rows [][]string+ if err := json.Unmarshal(raw, &rows); err == nil {+ return rows+ }+ var generic [][]any+ if err := json.Unmarshal(raw, &generic); err != nil {+ return nil+ }+ out := make([][]string, len(generic))+ for i, row := range generic {+ out[i] = make([]string, len(row))+ for j, cell := range row {+ out[i][j] = tableCellText(cell)+ }+ }+ return out+}++func tableCellText(cell any) string {+ switch value := cell.(type) {+ case nil:+ return ""+ case string:+ return value+ case float64:+ return strconv.FormatFloat(value, 'f', -1, 64)+ case bool:+ return strconv.FormatBool(value)+ case map[string]any:+ if text, ok := value["text"].(string); ok && strings.TrimSpace(text) != "" {+ return text+ }+ if children, ok := value["children"].([]any); ok {+ var builder strings.Builder+ for _, child := range children {+ builder.WriteString(tableCellText(child))+ }+ return builder.String()+ }+ return ""+ default:+ return ""+ }+}diff --git a/internal/datasource/connector/dingtalk/markdown_test.go b/internal/datasource/connector/dingtalk/markdown_test.gonew file mode 100644index 000000000..d90a75217--- /dev/null+++ b/internal/datasource/connector/dingtalk/markdown_test.go@@ -0,0 +1,130 @@+package dingtalk++import (+ "encoding/json"+ "reflect"+ "strings"+ "testing"+)++func TestRenderDocumentSupportsDocumentedBlocks(t *testing.T) {+ blocks := []json.RawMessage{+ rawJSON(`{"blockType":"heading","heading":{"level":2,"text":"Overview"}}`),+ rawJSON(`{+ "blockType":"paragraph",+ "children":[+ {"elementType":"text","text":"bold","bold":true},+ {"elementType":"text","text":" and 2 * 3 "},+ {"elementType":"link","properties":{"href":"https://example.com/a"},+ "children":[{"elementType":"text","text":"link"}]},+ {"elementType":"image","properties":{"src":"https://example.com/image.png"}}+ ]+ }`),+ rawJSON(`{"blockType":"blockquote","blockquote":{"text":"first\nsecond"}}`),+ rawJSON(`{+ "blockType":"orderedList",+ "orderedList":{"list":{"level":1}},+ "children":[{"elementType":"text","text":"nested"}]+ }`),+ rawJSON(`{"blockType":"table","table":{"cells":[["A","B"],["1","x|y"]]}}`),+ rawJSON(`{+ "blockType":"callout",+ "children":[{"blockType":"paragraph","paragraph":{"text":"note"}}]+ }`),+ }++ result := renderDocument("Team | Notes", blocks)+ for _, expected := range []string{+ "# Team | Notes",+ "## Overview",+ "**bold** and 2 \\* 3 [link](https://example.com/a)",+ "> first\n> second",+ " 1. nested",+ "| A | B |\n| --- | --- |\n| 1 | x\\|y |",+ "note",+ } {+ if !strings.Contains(result.Markdown, expected) {+ t.Errorf("Markdown missing %q:\n%s", expected, result.Markdown)+ }+ }+ if len(result.UnknownTypes) != 0 {+ t.Fatalf("UnknownTypes = %#v", result.UnknownTypes)+ }+}++func TestRenderDocumentHandlesUnknownAndUnsafeContent(t *testing.T) {+ result := renderDocument("Doc", []json.RawMessage{+ rawJSON(`{+ "blockType":"futureContainer",+ "children":[{"blockType":"paragraph","paragraph":{"text":"preserved"}}]+ }`),+ rawJSON(`{+ "blockType":"paragraph",+ "children":[+ {"elementType":"link","properties":{"href":"javascript:alert(1)"},+ "children":[{"elementType":"text","text":"safe label"}]},+ {"elementType":"image","properties":{"src":"data:text/html,unsafe"}},+ {"elementType":"futureInline","text":"fallback"}+ ]+ }`),+ json.RawMessage(`{`),+ })++ if strings.Contains(result.Markdown, "javascript:") || strings.Contains(result.Markdown, "data:") {+ t.Fatalf("unsafe URL rendered:\n%s", result.Markdown)+ }+ if !strings.Contains(result.Markdown, "preserved") ||+ !strings.Contains(result.Markdown, "safe labelfallback") {+ t.Fatalf("useful fallback content lost:\n%s", result.Markdown)+ }+ wantUnknown := []string{"futurecontainer", "inline_futureinline", "invalid_json"}+ if !reflect.DeepEqual(result.UnknownTypes, wantUnknown) {+ t.Fatalf("UnknownTypes = %#v, want %#v", result.UnknownTypes, wantUnknown)+ }+}++func TestSanitizeFilenameDoesNotSplitUTF8(t *testing.T) {+ name := strings.Repeat("文", 100) + "/draft"+ sanitized := sanitizeFilename(name)+ if !strings.HasSuffix(sanitized, "文") || len(sanitized) > 200 {+ t.Fatalf("sanitizeFilename() = %q (%d bytes)", sanitized, len(sanitized))+ }+ if sanitized = sanitizeFilename("line\nname"); sanitized != "line_name" {+ t.Fatalf("sanitizeFilename() retained control character: %q", sanitized)+ }+}++func TestRenderDocumentAcceptsOfficialBlockVariants(t *testing.T) {+ result := renderDocument("Doc", []json.RawMessage{+ rawJSON(`{"blockType":"heading","heading":{"level":"heading-3","text":"Section"}}`),+ rawJSON(`{+ "blockType":"paragraph",+ "children":[+ {"elementType":"text","text":"gone","strike":true},+ {"elementType":"text","text":" also","stike":true}+ ]+ }`),+ rawJSON(`{"blockType":"table","table":{"cells":[[{"text":"A"},{"text":"B"}],[{"text":"1"},{"text":"2"}]]}}`),+ rawJSON(`{+ "blockType":"unorderedList",+ "unorderedList":{"list":{"level":"0"}},+ "children":[{"blockType":"paragraph","paragraph":{"text":"item body"}}]+ }`),+ rawJSON(`{"blockType":"callout"}`),+ })+ for _, expected := range []string{+ "### Section",+ "~~gone~~",+ "~~ also~~",+ "| A | B |",+ "| 1 | 2 |",+ "- item body",+ } {+ if !strings.Contains(result.Markdown, expected) {+ t.Errorf("Markdown missing %q:\n%s", expected, result.Markdown)+ }+ }+ if !reflect.DeepEqual(result.UnknownTypes, []string{"nested_blocks_unavailable"}) {+ t.Fatalf("UnknownTypes = %#v", result.UnknownTypes)+ }+}diff --git a/internal/datasource/connector/dingtalk/resource.go b/internal/datasource/connector/dingtalk/resource.gonew file mode 100644index 000000000..4ca6c4094--- /dev/null+++ b/internal/datasource/connector/dingtalk/resource.go@@ -0,0 +1,154 @@+package dingtalk++import (+ "fmt"+ "net/url"+ "strings"+ "unicode"+)++const (+ resourceIDPrefix = "dingtalk:v1?"+ maxResourceIDBytes = 8 * 1024+ maxResourceDepth = 64+)++// resourceReference is embedded in resource picker IDs for folders and+// documents. Workspace IDs remain unchanged for compatibility with data+// sources created by earlier builds of the connector.+type resourceReference struct {+ WorkspaceID string+ NodeID string+ Ancestors []string+}++func (r resourceReference) child(nodeID string) resourceReference {+ ancestors := append([]string(nil), r.Ancestors...)+ if r.NodeID != "" {+ ancestors = append(ancestors, r.NodeID)+ }+ return resourceReference{+ WorkspaceID: r.WorkspaceID,+ NodeID: strings.TrimSpace(nodeID),+ Ancestors: ancestors,+ }+}++func encodeResourceReference(ref resourceReference) (string, error) {+ if err := validateResourceReference(ref); err != nil {+ return "", err+ }+ if ref.NodeID == "" {+ return ref.WorkspaceID, nil+ }++ values := url.Values{}+ values.Set("workspace", ref.WorkspaceID)+ values.Set("node", ref.NodeID)+ for _, ancestor := range ref.Ancestors {+ values.Add("ancestor", ancestor)+ }+ encoded := resourceIDPrefix + values.Encode()+ if len(encoded) > maxResourceIDBytes {+ return "", fmt.Errorf("DingTalk resource ID exceeds %d bytes", maxResourceIDBytes)+ }+ return encoded, nil+}++func decodeResourceReference(raw string) (resourceReference, error) {+ if len(raw) == 0 || len(raw) > maxResourceIDBytes {+ return resourceReference{}, fmt.Errorf("invalid DingTalk resource ID")+ }+ if !strings.HasPrefix(raw, resourceIDPrefix) {+ ref := resourceReference{WorkspaceID: raw}+ if err := validateResourceReference(ref); err != nil {+ return resourceReference{}, err+ }+ return ref, nil+ }++ values, err := url.ParseQuery(strings.TrimPrefix(raw, resourceIDPrefix))+ if err != nil {+ return resourceReference{}, fmt.Errorf("parse DingTalk resource ID: %w", err)+ }+ for key := range values {+ if key != "workspace" && key != "node" && key != "ancestor" {+ return resourceReference{}, fmt.Errorf("DingTalk resource ID contains an unsupported field")+ }+ }+ if len(values["workspace"]) != 1 || len(values["node"]) != 1 {+ return resourceReference{}, fmt.Errorf("DingTalk resource ID has invalid workspace or node fields")+ }+ ref := resourceReference{+ WorkspaceID: values.Get("workspace"),+ NodeID: values.Get("node"),+ Ancestors: append([]string(nil), values["ancestor"]...),+ }+ if err := validateResourceReference(ref); err != nil {+ return resourceReference{}, err+ }+ return ref, nil+}++func validateResourceReference(ref resourceReference) error {+ if err := validateExternalID("workspace", ref.WorkspaceID); err != nil {+ return err+ }+ if ref.NodeID != "" {+ if err := validateExternalID("node", ref.NodeID); err != nil {+ return err+ }+ } else if len(ref.Ancestors) != 0 {+ return fmt.Errorf("DingTalk workspace resource cannot have ancestors")+ }+ if len(ref.Ancestors) > maxResourceDepth {+ return fmt.Errorf("DingTalk resource depth exceeds %d", maxResourceDepth)+ }++ seen := make(map[string]struct{}, len(ref.Ancestors)+1)+ for _, ancestor := range ref.Ancestors {+ if err := validateExternalID("ancestor", ancestor); err != nil {+ return err+ }+ if _, exists := seen[ancestor]; exists {+ return fmt.Errorf("DingTalk resource contains an ancestor cycle")+ }+ seen[ancestor] = struct{}{}+ }+ if _, exists := seen[ref.NodeID]; ref.NodeID != "" && exists {+ return fmt.Errorf("DingTalk resource contains a node cycle")+ }+ return nil+}++func validateExternalID(kind, value string) error {+ if value == "" || value != strings.TrimSpace(value) {+ return fmt.Errorf("DingTalk resource has invalid %s ID", kind)+ }+ for _, r := range value {+ if unicode.IsControl(r) {+ return fmt.Errorf("DingTalk resource has invalid %s ID", kind)+ }+ }+ return nil+}++func resourceAncestorIDs(ref resourceReference) ([]string, error) {+ rootID, err := encodeResourceReference(resourceReference{WorkspaceID: ref.WorkspaceID})+ if err != nil {+ return nil, err+ }+ ancestors := []string{rootID}+ for index, nodeID := range ref.Ancestors {+ id, err := encodeResourceReference(resourceReference{+ WorkspaceID: ref.WorkspaceID,+ NodeID: nodeID,+ Ancestors: append([]string(nil), ref.Ancestors[:index]...),+ })+ if err != nil {+ return nil, err+ }+ ancestors = append(ancestors, id)+ }+ return ancestors, nil+}diff --git a/internal/datasource/connector/dingtalk/resource_test.go b/internal/datasource/connector/dingtalk/resource_test.gonew file mode 100644index 000000000..79f2fd4e2--- /dev/null+++ b/internal/datasource/connector/dingtalk/resource_test.go@@ -0,0 +1,79 @@+package dingtalk++import (+ "strings"+ "testing"+)++func TestResourceReferenceRoundTripAndAncestors(t *testing.T) {+ folder := resourceReference{WorkspaceID: "workspace", NodeID: "folder"}+ document := folder.child("document")+ documentID, err := encodeResourceReference(document)+ if err != nil {+ t.Fatal(err)+ }+ decoded, err := decodeResourceReference(documentID)+ if err != nil {+ t.Fatal(err)+ }+ if decoded.WorkspaceID != "workspace" || decoded.NodeID != "document" ||+ len(decoded.Ancestors) != 1 || decoded.Ancestors[0] != "folder" {+ t.Fatalf("decoded reference = %#v", decoded)+ }++ ancestorIDs, err := resourceAncestorIDs(decoded)+ if err != nil {+ t.Fatal(err)+ }+ folderID, err := encodeResourceReference(folder)+ if err != nil {+ t.Fatal(err)+ }+ if len(ancestorIDs) != 2 || ancestorIDs[0] != "workspace" || ancestorIDs[1] != folderID {+ t.Fatalf("ancestor IDs = %#v", ancestorIDs)+ }+}++func TestResourceReferenceRejectsMalformedOrCyclicIDs(t *testing.T) {+ tooDeep := make([]string, maxResourceDepth+1)+ for index := range tooDeep {+ tooDeep[index] = strings.Repeat("a", index+1)+ }+ for _, ref := range []resourceReference{+ {},+ {WorkspaceID: " workspace"},+ {WorkspaceID: "workspace", Ancestors: []string{"folder"}},+ {WorkspaceID: "workspace", NodeID: "folder", Ancestors: []string{"folder"}},+ {WorkspaceID: "workspace", NodeID: "document", Ancestors: []string{"folder", "folder"}},+ {WorkspaceID: "workspace", NodeID: "document", Ancestors: tooDeep},+ } {+ if _, err := encodeResourceReference(ref); err == nil {+ t.Fatalf("encodeResourceReference(%#v) error = nil", ref)+ }+ }++ for _, raw := range []string{+ resourceIDPrefix + "workspace=space",+ resourceIDPrefix + "node=doc",+ resourceIDPrefix + "workspace=space&workspace=other&node=doc",+ resourceIDPrefix + "workspace=space&node=doc&unexpected=value",+ } {+ if _, err := decodeResourceReference(raw); err == nil {+ t.Fatalf("decodeResourceReference(%q) error = nil", raw)+ }+ }+}++func TestResourceReferenceKeepsWorkspaceIDsBackwardCompatible(t *testing.T) {+ decoded, err := decodeResourceReference("legacy-workspace")+ if err != nil {+ t.Fatal(err)+ }+ if decoded.WorkspaceID != "legacy-workspace" || decoded.NodeID != "" {+ t.Fatalf("decoded legacy workspace = %#v", decoded)+ }+ encoded, err := encodeResourceReference(decoded)+ if err != nil || encoded != "legacy-workspace" {+ t.Fatalf("encoded workspace = %q, %v", encoded, err)+ }+}diff --git a/internal/datasource/connector/dingtalk/sync_safety_test.go b/internal/datasource/connector/dingtalk/sync_safety_test.gonew file mode 100644index 000000000..1f098a379--- /dev/null+++ b/internal/datasource/connector/dingtalk/sync_safety_test.go@@ -0,0 +1,240 @@+package dingtalk++import (+ "context"+ "encoding/json"+ "errors"+ "testing"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/types"+)++func twoFolderFixture(t *testing.T) (*Connector, *fakeAPI, *types.DataSourceConfig, string, string) {+ t.Helper()+ a, err := encodeResourceReference(resourceReference{WorkspaceID: "space", NodeID: "a"})+ if err != nil {+ t.Fatal(err)+ }+ b, err := encodeResourceReference(resourceReference{WorkspaceID: "space", NodeID: "b"})+ if err != nil {+ t.Fatal(err)+ }+ api := &fakeAPI{+ workspaces: []workspace{{ID: "space", RootNodeID: "root"}},+ nodes: map[string][]node{"root": {{ID: "a", Type: "FOLDER"}, {ID: "b", Type: "FOLDER"}}},+ blocks: map[string][]json.RawMessage{+ "doc": {rawJSON(`{"blockType":"paragraph","paragraph":{"text":"content"}}`)},+ },+ nodeErrors: make(map[string]error), blockErrors: make(map[string]error),+ }+ return testConnector(api), api, testConfig(a, b), a, b+}++func syncDocument() node {+ return node{+ ID: "doc", WorkspaceID: "space", Name: "Doc", Type: "FILE",+ Category: "ALIDOC", Extension: "adoc", ModifiedTime: "r1",+ }+}++func assertNoDeletion(t *testing.T, items []types.FetchedItem) {+ t.Helper()+ for _, item := range items {+ if item.IsDeleted {+ t.Fatalf("unexpected deletion: %#v", item)+ }+ }+}++func TestIncrementalMoveBetweenSelectedFolders(t *testing.T) {+ for _, from := range []string{"a", "b"} {+ t.Run(from, func(t *testing.T) {+ c, api, cfg, a, b := twoFolderFixture(t)+ to, fromID, toID := "b", a, b+ if from == "b" {+ to, fromID, toID = "a", b, a+ }+ api.nodes[from] = []node{syncDocument()}+ _, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)+ if err != nil {+ t.Fatal(err)+ }+ api.nodes[from] = nil+ api.nodes[to] = []node{syncDocument()}+ items, next, err := c.FetchIncremental(context.Background(), cfg, cursor)+ if err != nil {+ t.Fatal(err)+ }+ assertNoDeletion(t, items)+ if len(items) != 1 || len(items[0].Content) == 0 {+ t.Fatalf("move result: %#v", items)+ }+ state, err := decodeCursor(next)+ if err != nil {+ t.Fatal(err)+ }+ if _, ok := state.Resources[fromID]["doc"]; ok {+ t.Fatal("old scope retained moved document")+ }+ if state.Resources[toID]["doc"] != "r1" {+ t.Fatalf("destination cursor: %#v", state)+ }+ items, _, err = c.FetchIncremental(context.Background(), cfg, next)+ if err != nil || len(items) != 0 {+ t.Fatalf("unchanged after move: %#v, %v", items, err)+ }+ })+ }+}++func TestIncrementalMoveWithContentFailureRetries(t *testing.T) {+ c, api, cfg, _, b := twoFolderFixture(t)+ api.nodes["a"] = []node{syncDocument()}+ _, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)+ if err != nil {+ t.Fatal(err)+ }+ api.nodes["a"] = nil+ api.nodes["b"] = []node{syncDocument()}+ api.blockErrors["doc"] = errors.New("permission denied")+ items, next, err := c.FetchIncremental(context.Background(), cfg, cursor)+ var partial *datasource.PartialFetchError+ if !errors.As(err, &partial) {+ t.Fatalf("want partial, got %v", err)+ }+ assertNoDeletion(t, items)+ if len(items) != 1 || items[0].Metadata["error_reason_code"] != "dingtalk_document_failed" {+ t.Fatalf("failure result: %#v", items)+ }+ state, _ := decodeCursor(next)+ if _, ok := state.Resources[b]["doc"]; ok {+ t.Fatal("failed destination advanced cursor")+ }+ delete(api.blockErrors, "doc")+ items, _, err = c.FetchIncremental(context.Background(), cfg, next)+ if err != nil || len(items) != 1 || len(items[0].Content) == 0 {+ t.Fatalf("retry result: %#v, %v", items, err)+ }+}++func TestIncrementalDefersDeletionUntilEveryScopeRecovers(t *testing.T) {+ for _, resolveFailure := range []bool{false, true} {+ t.Run(map[bool]string{false: "scan", true: "resolve"}[resolveFailure], func(t *testing.T) {+ c, api, cfg, a, _ := twoFolderFixture(t)+ api.nodes["a"] = []node{syncDocument()}+ _, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)+ if err != nil {+ t.Fatal(err)+ }+ api.nodes["a"] = nil+ if resolveFailure {+ api.nodes["root"] = api.nodes["root"][:1]+ } else {+ api.nodeErrors["b"] = errors.New("temporary failure")+ }+ items, next, err := c.FetchIncremental(context.Background(), cfg, cursor)+ var partial *datasource.PartialFetchError+ if !errors.As(err, &partial) {+ t.Fatalf("want partial, got %v", err)+ }+ assertNoDeletion(t, items)+ state, _ := decodeCursor(next)+ if state.Resources[a]["doc"] != "r1" {+ t.Fatal("deferred deletion lost revision")+ }+ api.nodes["root"] = []node{{ID: "a", Type: "FOLDER"}, {ID: "b", Type: "FOLDER"}}+ delete(api.nodeErrors, "b")+ items, next, err = c.FetchIncremental(context.Background(), cfg, next)+ if err != nil || len(items) != 1 || !items[0].IsDeleted {+ t.Fatalf("recovered deletion: %#v, %v", items, err)+ }+ items, _, err = c.FetchIncremental(context.Background(), cfg, next)+ if err != nil || len(items) != 0 {+ t.Fatalf("duplicate deletion: %#v, %v", items, err)+ }+ })+ }+}++func TestUnavailableSelectionPreservesCursorAndHealthyWork(t *testing.T) {+ c, api, cfg, a, b := twoFolderFixture(t)+ api.nodes["a"] = []node{syncDocument()}+ _, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)+ if err != nil {+ t.Fatal(err)+ }+ // The saved folder no longer resolves, but the other selected folder works.+ api.nodes["root"] = api.nodes["root"][1:]+ healthy := syncDocument()+ healthy.ID = "healthy"+ api.nodes["b"] = []node{healthy}+ api.blocks["healthy"] = api.blocks["doc"]+ items, next, err := c.FetchIncremental(context.Background(), cfg, cursor)+ var partial *datasource.PartialFetchError+ if !errors.As(err, &partial) || len(items) != 2 {+ t.Fatalf("result: %#v, %v", items, err)+ }+ if len(partial.Details) != 0 {+ t.Fatal("raw diagnostics duplicated localized item errors")+ }+ assertNoDeletion(t, items)+ if items[0].Metadata["error_reason_code"] != "dingtalk_resource_failed" ||+ items[1].ExternalID != "healthy" || len(items[1].Content) == 0 {+ t.Fatalf("items: %#v", items)+ }+ state, _ := decodeCursor(next)+ if state.Resources[a]["doc"] != "r1" || state.Resources[b]["healthy"] != "r1" {+ t.Fatalf("cursor: %#v", state)+ }+ // Recovery must retry the old scope instead of dropping its previous state.+ api.nodes["root"] = []node{{ID: "a", Type: "FOLDER"}, {ID: "b", Type: "FOLDER"}}+ changed := syncDocument()+ changed.ModifiedTime = "r2"+ api.nodes["a"] = []node{changed}+ items, _, err = c.FetchIncremental(context.Background(), cfg, next)+ if err != nil || len(items) != 1 || items[0].ExternalID != "doc" {+ t.Fatalf("recovery: %#v, %v", items, err)+ }+ // Full sync isolates the same missing selection too.+ api.nodes["root"] = api.nodes["root"][1:]+ items, err = c.FetchAll(context.Background(), cfg, cfg.ResourceIDs)+ if !errors.As(err, &partial) || len(items) != 2 || items[1].ExternalID != "healthy" {+ t.Fatalf("full sync: %#v, %v", items, err)+ }+}++func TestScopeResolutionCancellationDoesNotProduceCursor(t *testing.T) {+ c, api, cfg, _, _ := twoFolderFixture(t)+ api.nodeErrors["root"] = context.Canceled+ items, next, err := c.FetchIncremental(context.Background(), cfg, nil)+ if !errors.Is(err, context.Canceled) || next != nil || len(items) != 0 {+ t.Fatalf("canceled: %#v, %#v, %v", items, next, err)+ }+}++func TestFetchAllFromCursorReFetchesAndReconcilesDeletions(t *testing.T) {+ c, api, cfg, _, _ := twoFolderFixture(t)+ api.nodes["a"] = []node{syncDocument()}+ _, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)+ if err != nil {+ t.Fatal(err)+ }++ items, next, err := c.FetchAllFromCursor(context.Background(), cfg, cfg.ResourceIDs, cursor)+ if err != nil || next == nil || len(items) != 1 || len(items[0].Content) == 0 {+ t.Fatalf("full re-fetch: %#v, %#v, %v", items, next, err)+ }++ api.nodes["a"] = nil+ items, err = c.FetchAll(context.Background(), cfg, cfg.ResourceIDs)+ if err != nil {+ t.Fatal(err)+ }+ assertNoDeletion(t, items)++ items, _, err = c.FetchAllFromCursor(context.Background(), cfg, cfg.ResourceIDs, next)+ if err != nil || len(items) != 1 || !items[0].IsDeleted {+ t.Fatalf("full sync deletion: %#v, %v", items, err)+ }+}diff --git a/website-docs/03-features/10-datasource.md b/website-docs/03-features/10-datasource.mdindex 0b2a97310..fc18450c1 100644--- a/website-docs/03-features/10-datasource.md+++ b/website-docs/03-features/10-datasource.md@@ -102,6 +102,16 @@- **抓取**(`walk`,全量/增量共用):`ListBookDocs` 列文档 → 过滤 `type != "Doc"`(跳过 Sheet/Thread/Board/Table)与 `status != "1"`(跳过草稿)→ 每次 `GetDocDetail` 之间 sleep 300ms 规避限流 → `format` 为 `markdown`/`lake` 时取 `body` Markdown 原文入库(其他格式如 html 防御性跳过并记 `skip_reason`)。- **增量逻辑**:游标 `yuqueCursor.BookDocTimes`(`bookID → docID → content_updated_at`),一致则跳过。删除检测:游标里有、当前列表没有 → `IsDeleted`。+#### 钉钉文档(`connector/dingtalk/`)++- **认证**:企业内部应用 Client ID、Client Secret 和有目标知识库访问权限的操作人 Union ID;开通 `Wiki.Workspace.Read`、`Wiki.Node.Read`、`Storage.File.Read` 后发布应用。+- **范围**:选择知识库、文件夹或单篇 `ALIDOC/adoc` 在线文档,通过公开 Wiki / Blocks API 转为 Markdown。当前不导入钉钉表格或普通上传附件,也不依赖异步导出回调。+- **同步**:按文档 `modifiedTimestamp`(毫秒)增量读取,缺失时回退 `modifiedTime`;合并重叠选择。全量同步也会对照上次游标对账删除,避免 `sync_mode=full` 漏删。目录遍历不完整时暂缓删除。+- **正文**:公开 Blocks API 只返回文档根下的一级块;高亮块等容器若响应里带有 `children` 会继续渲染,否则在元数据中标记 `nested_blocks_unavailable`,避免把残缺正文当成完整成功。+- **校验**:测试连接会列出知识库、探测根节点列表,并在根下存在在线文档时试读 Blocks,以便尽早发现缺少 `Wiki.Node.Read` / `Storage.File.Read`。+- **失败与恢复**:资源失效不阻断其他范围;失败范围和正文失败文档保留旧版本以便重试。任一范围无法完整扫描时暂缓删除,并保留待核对记录。失效的单独选择需要检查权限或重新选择。+- **删除开关**:开启同步删除才移除确认在源端删除的本地知识;不可访问的资源不会直接视为已删除。+#### RSS / Atom(`connector/rss/`)- **配置**:`feed_urls`(换行/逗号分隔,多条去重)存放在 **Settings**(非机密,UI 可直接编辑);`auth_headers`(`Name: Value` 每行一条,仅附加在 feed 请求上、绝不发给第三方文章页)存放在 **Credentials** 并加密。`HasConfiguredCredentials` 对 RSS 特判:只有 `auth_headers` 才算已配置凭据。@@ -311,7 +321,7 @@ type StreamingConnector interface {}```-任务超时后可从最近的 checkpoint 继续处理。Asynq 同步任务超时为 2 小时,流式路径按条目推进,避免缓存全部文件正文。Feishu/Lark 和 GitLab 连接器均实现了 `StreamingConnector`。+任务超时后可从最近的 checkpoint 继续处理。Asynq 同步任务超时为 2 小时,流式路径按条目推进,避免缓存全部文件正文。Feishu/Lark 和 GitLab 连接器均实现了 `StreamingConnector`。钉钉目前走 batch `FetchAll`/`FetchIncremental`/`FetchAllFromCursor`,超大知识库建议使用增量模式以免一次装入全部 Markdown。#### ConnectorRegistry:注册与查找@@ -320,14 +330,17 @@ type StreamingConnector interface {```goregistry.Register(feishuConnector.NewConnector(feishuConnector.RegionFeishu)) // feishuregistry.Register(feishuConnector.NewConnector(feishuConnector.RegionLark)) // lark(国际版,同一实现不同 Region)+registry.Register(drive.NewDriveConnector(core.RegionFeishuDrive)) // feishu_drive+registry.Register(drive.NewDriveConnector(core.RegionLarkDrive)) // lark_driveregistry.Register(notionConnector.NewConnector()) // notionregistry.Register(yuqueConnector.NewConnector()) // yuque+registry.Register(dingtalkConnector.NewConnector()) // dingtalk+registry.Register(imaConnector.NewConnector()) // imaregistry.Register(rssConnector.NewConnector()) // rssregistry.Register(gitlabConnector.NewConnector()) // gitlab-registry.Register(imaConnector.NewConnector()) // ima```-> 注意:`connector.go` 中的 `ConnectorMetadataRegistry` 为前端展示定义了更多连接器元数据(Confluence、GitHub、Google Drive、OneDrive、DingTalk、Web Crawler、Slack、IMAP 等),但**当前代码库中实际注册可用的连接器有 7 个类型:`feishu`、`lark`、`notion`、`yuque`、`rss`、`gitlab`、`ima`**(其中 feishu/lark 共用同一份实现)。未注册类型在创建数据源时会被 `connectorRegistry.Get()` 以 `ErrConnectorNotFound` 拒绝。+> 注意:`connector.go` 中的 `ConnectorMetadataRegistry` 仍包含尚未实现的连接器(Confluence、GitHub、Google Drive、OneDrive、Web Crawler、Slack、IMAP 等)。当前实际注册可用的类型为:`feishu`、`lark`、`feishu_drive`、`lark_drive`、`notion`、`yuque`、`dingtalk`、`ima`、`rss`、`gitlab`。未注册类型在创建数据源时会被 `connectorRegistry.Get()` 以 `ErrConnectorNotFound` 拒绝。### 数据模型(internal/types/datasource.go)