chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)
This commit is contained in:
commit
9097ee699d
5769 files changed
+1446466
No files matched your search
@@ -0,0 +1,615 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource"
|
||||
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// DriveConnector implements the datasource.Connector (and StreamingConnector)
|
||||
// interface for Feishu/Lark Drive (云盘) mode. It shares core.Client/core.Config/core.Region
|
||||
// and the export/download logic with the wiki Connector; only resource
|
||||
// enumeration and Fetch dispatch differ. See 飞书云盘数据源设计.md and
|
||||
// ADR-0001..0004.
|
||||
type DriveConnector struct {
|
||||
region core.Region
|
||||
}
|
||||
|
||||
// NewDriveConnector creates a Drive connector for the given region
|
||||
// (RegionFeishuDrive or RegionLarkDrive).
|
||||
func NewDriveConnector(region core.Region) *DriveConnector {
|
||||
return &DriveConnector{region: region}
|
||||
}
|
||||
|
||||
// Drive supports resumable streaming sync; the service prefers FetchStream over
|
||||
// FetchAll/FetchIncremental when a connector implements StreamingConnector.
|
||||
var _ datasource.StreamingConnector = (*DriveConnector)(nil)
|
||||
var _ datasource.FullStreamingConnector = (*DriveConnector)(nil)
|
||||
|
||||
// Type returns the connector type identifier.
|
||||
func (c *DriveConnector) Type() string {
|
||||
return c.region.ConnectorType
|
||||
}
|
||||
|
||||
// Validate verifies that the Drive configuration is valid by testing
|
||||
// connectivity. It does not validate folder_token here - that is done in
|
||||
// ListResources when the user loads the tree root. Mirrors the wiki Connector.
|
||||
func (c *DriveConnector) Validate(ctx context.Context, config *types.DataSourceConfig) error {
|
||||
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client := core.NewClient(feishuConfig)
|
||||
if err := client.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("%s connection failed: %w", c.region.Label, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListResources lists Feishu Drive resources for selection, loading the tree
|
||||
// lazily one level at a time. Mirrors the wiki Connector.ListResources shape
|
||||
// but with the Drive difference that the root is user-supplied (config.
|
||||
// ResourceIDs[0]) rather than enumerated via ListWikiSpaces.
|
||||
//
|
||||
// - parentID == "" -> return the user-supplied root
|
||||
// folder (from config.ResourceIDs[0]) as the single root resource
|
||||
// (HasChildren=true). Drive has no "space list" API, so the root is
|
||||
// user-supplied. folder_token == "" is rejected (ADR-0004).
|
||||
// - parentID == folderToken -> ListDriveFiles(folderToken)
|
||||
// returns the direct children.
|
||||
// - parentID == "folderToken:subFolderToken" -> ListDriveFiles(subFolderToken)
|
||||
// returns that sub-folder's direct children.
|
||||
//
|
||||
// Each core.DriveFile becomes a Resource: folder HasChildren=true, others false.
|
||||
// resourceID encoding: root = folderToken; child = folderToken + ":" + fileToken
|
||||
// (reuses core.FeishuWikiNodeResourceSeparator). See ADR-0001 §3.4.
|
||||
func (c *DriveConnector) ListResources(
|
||||
ctx context.Context, config *types.DataSourceConfig, parentID string,
|
||||
) ([]types.Resource, error) {
|
||||
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client := core.NewClient(feishuConfig)
|
||||
|
||||
if parentID == "" {
|
||||
// Root load: read the user-supplied folder_token from config.ResourceIDs.
|
||||
rootFolderToken := driveRootFolderToken(config)
|
||||
if rootFolderToken == "" {
|
||||
return nil, fmt.Errorf("folder_token is required; specify a Drive folder token")
|
||||
}
|
||||
// Validate access by listing the root's direct children (also lazy-loads
|
||||
// the first level for the picker). Reuse the list call rather than a
|
||||
// separate ping.
|
||||
files, err := client.ListDriveFilesAllPages(ctx, rootFolderToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list feishu drive folder %s: %w", rootFolderToken, err)
|
||||
}
|
||||
_ = files // children returned via the parentID == rootFolderToken branch below
|
||||
// Resolve the root folder's human-readable name via the folder meta API.
|
||||
// Best-effort: on failure (no permission / not found) fall back to the
|
||||
// folder_token so the picker still renders something usable.
|
||||
folderName := rootFolderToken
|
||||
if meta, mErr := client.GetDriveFolderMeta(ctx, rootFolderToken); mErr != nil {
|
||||
logger.Warnf(ctx, "[FeishuDrive] resolve root folder name failed: %v (falling back to token)", mErr)
|
||||
} else if meta.Data.Name != "" {
|
||||
folderName = meta.Data.Name
|
||||
}
|
||||
return []types.Resource{c.driveFolderToResource(rootFolderToken, "", rootFolderToken, folderName)}, nil
|
||||
}
|
||||
|
||||
// Lazy load: list only the direct children of the given folder.
|
||||
rootFolderToken, folderToken := parseDriveResourceID(parentID)
|
||||
if folderToken == "" {
|
||||
// parentID is a bare root folder token -> list its children.
|
||||
folderToken = rootFolderToken
|
||||
}
|
||||
files, err := client.ListDriveFilesAllPages(ctx, folderToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list feishu drive files under %s: %w", parentID, err)
|
||||
}
|
||||
|
||||
resources := make([]types.Resource, 0, len(files))
|
||||
for _, f := range files {
|
||||
resources = append(resources, c.driveFileToResource(rootFolderToken, f))
|
||||
}
|
||||
return resources, nil
|
||||
}
|
||||
|
||||
// ResolveResourceAncestors returns the resource IDs of every parent folder that
|
||||
// has to be expanded so the lazily-loaded picker can reveal each selection.
|
||||
//
|
||||
// The wiki connector walks up via GetWikiNode (parent_node_token) in O(depth)
|
||||
// single-node queries. Drive has no single-file parent query API (verified -
|
||||
// metas/batch_query does not return parent), so we walk top-down from the root
|
||||
// folder with ListDriveFiles and share the traversal across all selections in
|
||||
// the same root. Best-effort: a broken path just stays collapsed. See ADR-0003.
|
||||
func (c *DriveConnector) ResolveResourceAncestors(
|
||||
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
|
||||
) ([]string, error) {
|
||||
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := core.NewClient(feishuConfig)
|
||||
|
||||
seen := make(map[string]bool)
|
||||
ancestors := make([]string, 0)
|
||||
add := func(id string) {
|
||||
if id != "" && !seen[id] {
|
||||
seen[id] = true
|
||||
ancestors = append(ancestors, id)
|
||||
}
|
||||
}
|
||||
|
||||
// Group selections by root folder so one shared traversal covers them all.
|
||||
type selection struct {
|
||||
fileToken string
|
||||
}
|
||||
rootSelections := make(map[string][]selection)
|
||||
for _, rid := range resourceIDs {
|
||||
rootFolderToken, fileToken := parseDriveResourceID(rid)
|
||||
if fileToken == "" {
|
||||
// A root-level selection is already a top-level node; nothing to reveal.
|
||||
continue
|
||||
}
|
||||
add(rootFolderToken)
|
||||
rootSelections[rootFolderToken] = append(rootSelections[rootFolderToken], selection{fileToken})
|
||||
}
|
||||
|
||||
// For each root, BFS from the root: at each folder, ListDriveFiles and check
|
||||
// which selections are direct children (record their parent chain) and which
|
||||
// sub-folders may still contain selections (enqueue). Shared traversal means
|
||||
// selections in the same subtree reuse list calls.
|
||||
for rootFolderToken, sels := range rootSelections {
|
||||
remaining := make(map[string]bool, len(sels))
|
||||
for _, s := range sels {
|
||||
remaining[s.fileToken] = true
|
||||
}
|
||||
// parentChain[fileToken] = resourceID of its parent folder
|
||||
parentChain := make(map[string]string)
|
||||
|
||||
queue := []string{rootFolderToken}
|
||||
for len(queue) > 0 && len(remaining) > 0 {
|
||||
cur := queue[0]
|
||||
queue = queue[1:]
|
||||
|
||||
files, err := client.ListDriveFilesAllPages(ctx, cur)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[FeishuDrive] resolve ancestors: list %s: %v", cur, err)
|
||||
break // best-effort: stop this root's traversal
|
||||
}
|
||||
for _, f := range files {
|
||||
if remaining[f.Token] {
|
||||
delete(remaining, f.Token)
|
||||
// Record the parent chain from root down to this file's parent.
|
||||
chain := buildDriveAncestorChain(rootFolderToken, cur, parentChain)
|
||||
for _, a := range chain {
|
||||
add(a)
|
||||
}
|
||||
}
|
||||
if f.Type == "folder" {
|
||||
parentChain[f.Token] = makeDriveResourceID(rootFolderToken, cur)
|
||||
queue = append(queue, f.Token)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ancestors, nil
|
||||
}
|
||||
|
||||
// buildDriveAncestorChain walks the parentChain map from cur up to root,
|
||||
// returning the resourceIDs (root, ... , cur's parent) in root-first order.
|
||||
func buildDriveAncestorChain(rootFolderToken, cur string, parentChain map[string]string) []string {
|
||||
var chain []string
|
||||
node := cur
|
||||
for node != "" && node != rootFolderToken {
|
||||
parent, ok := parentChain[node]
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
chain = append([]string{parent}, chain...)
|
||||
_, parentFolderToken := parseDriveResourceID(parent)
|
||||
node = parentFolderToken
|
||||
}
|
||||
return chain
|
||||
}
|
||||
|
||||
// FetchAll performs a full sync of all documents from the selected Drive
|
||||
// folders. Defensive fallback path - the service prefers FetchStream when the
|
||||
// connector implements StreamingConnector.
|
||||
func (c *DriveConnector) FetchAll(
|
||||
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
|
||||
) ([]types.FetchedItem, error) {
|
||||
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := core.NewClient(feishuConfig)
|
||||
return core.FetchAllEngine(ctx, client, config, resourceIDs,
|
||||
&driveOps{region: c.region, parseMode: feishuConfig.ParseMode})
|
||||
}
|
||||
|
||||
// FetchIncremental performs an incremental sync by comparing file modified_time
|
||||
// against the previously recorded state. Defensive fallback path - the service
|
||||
// prefers FetchStream. Routed through the same engine as FetchStream, so the
|
||||
// #2136 failure-doesn't-advance-cursor semantics apply here too.
|
||||
func (c *DriveConnector) FetchIncremental(
|
||||
ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor,
|
||||
) ([]types.FetchedItem, *types.SyncCursor, error) {
|
||||
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
client := core.NewClient(feishuConfig)
|
||||
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
|
||||
if len(config.ResourceIDs) == 0 {
|
||||
return nil, nil, errors.New(ops.EmptyResourceIDsError())
|
||||
}
|
||||
return core.FetchIncrementalEngine(ctx, client, config, cursor, ops)
|
||||
}
|
||||
|
||||
// FetchStream performs a resumable, memory-bounded sync. It unifies the full
|
||||
// and incremental paths: with cursor == nil it fetches everything, and with a
|
||||
// cursor it skips files whose recorded modified_time is unchanged - the same
|
||||
// mechanism that lets a sync which timed out mid-traversal resume from the last
|
||||
// checkpoint instead of restarting (Tencent/WeKnora#2136).
|
||||
//
|
||||
// The per-node loop lives in the shared engine (engine.go); this shell only
|
||||
// wires the Drive NodeOps adapter.
|
||||
func (c *DriveConnector) FetchStream(
|
||||
ctx context.Context, config *types.DataSourceConfig,
|
||||
cursor *types.SyncCursor, h datasource.StreamHandler,
|
||||
) (*types.SyncCursor, error) {
|
||||
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := core.NewClient(feishuConfig)
|
||||
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
|
||||
if len(config.ResourceIDs) == 0 {
|
||||
return nil, errors.New(ops.EmptyResourceIDsError())
|
||||
}
|
||||
return core.FetchStreamEngine(ctx, client, config, cursor, h, ops)
|
||||
}
|
||||
|
||||
// FetchFullStream refetches content without discarding the deletion baseline.
|
||||
func (c *DriveConnector) FetchFullStream(
|
||||
ctx context.Context, config *types.DataSourceConfig,
|
||||
cursor *types.SyncCursor, h datasource.StreamHandler,
|
||||
) (*types.SyncCursor, error) {
|
||||
feishuConfig, err := core.ParseFeishuConfig(config, c.region)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := core.NewClient(feishuConfig)
|
||||
ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
|
||||
if len(config.ResourceIDs) == 0 {
|
||||
return nil, errors.New(ops.EmptyResourceIDsError())
|
||||
}
|
||||
return core.FetchFullStreamEngine(ctx, client, config, cursor, h, ops)
|
||||
}
|
||||
|
||||
// driveOps adapts the Drive DriveConnector to the generic sync engine. It
|
||||
// carries the region (for channel + URL), encodes/decodes the Drive cursor
|
||||
// wire format (core.FeishuDriveCursor / file_times), and holds the per-run
|
||||
// directory mapping state (P1): folderNames caches resolved folder display
|
||||
// names, dirPaths maps folder token → cleaned directory path for the resource
|
||||
// being synced. List builds the state; Fetch reads it. runSync processes one
|
||||
// resource at a time, so the mutation is race-free.
|
||||
type driveOps struct {
|
||||
region core.Region
|
||||
parseMode string
|
||||
folderNames map[string]string
|
||||
dirPaths map[string]string
|
||||
rootEntries map[string][]core.DriveFile // successful shallow listings, per run
|
||||
}
|
||||
|
||||
func (o *driveOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.DriveFile, error, error) {
|
||||
files, err := o.listDriveFilesForResource(ctx, client, resourceID)
|
||||
if err == nil {
|
||||
return files, nil, nil
|
||||
}
|
||||
var partial *core.PartialDriveFileListError
|
||||
if errors.As(err, &partial) {
|
||||
return files, err, nil
|
||||
}
|
||||
return files, nil, err
|
||||
}
|
||||
|
||||
func (o *driveOps) Token(n core.DriveFile) string { return n.Token }
|
||||
func (o *driveOps) Title(n core.DriveFile) string { return n.Name }
|
||||
func (o *driveOps) ObjType(n core.DriveFile) string { return n.Type }
|
||||
func (o *driveOps) EditTime(n core.DriveFile) string {
|
||||
return core.DocxChangeKey(n.ModifiedTime, n.Type, o.parseMode)
|
||||
}
|
||||
|
||||
func (o *driveOps) Fetch(
|
||||
ctx context.Context, client *core.Client, n core.DriveFile, resourceID string,
|
||||
) ([]*types.FetchedItem, error) {
|
||||
items, err := fetchDriveFileContent(ctx, client, n, resourceID, o.region, o.parseMode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// P1 directory mapping: prefix the FileName with the containing folder's
|
||||
// cleaned directory path so ingestion derives the KB folder_path from it.
|
||||
qualifyItemFileNames(items, o.dirPaths[n.ParentToken])
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (o *driveOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
|
||||
var pe *core.PartialDriveFileListError
|
||||
if errors.As(partial, &pe) {
|
||||
return appendDriveFileListFailureItems(nil, resourceID, o.channel(), pe.Failures)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *driveOps) channel() string {
|
||||
if o.region.ConnectorType == types.ConnectorTypeLarkDrive {
|
||||
return types.ChannelLarkDrive
|
||||
}
|
||||
return types.ChannelFeishuDrive
|
||||
}
|
||||
|
||||
func (o *driveOps) ResourceNoun() string { return "files" }
|
||||
func (o *driveOps) EmptyResourceIDsError() string {
|
||||
return "no resource IDs (Drive folder tokens) configured"
|
||||
}
|
||||
func (o *driveOps) LogTag() string { return "[FeishuDrive]" }
|
||||
|
||||
func (o *driveOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
|
||||
var prev core.FeishuDriveCursor
|
||||
b, _ := json.Marshal(m)
|
||||
_ = json.Unmarshal(b, &prev)
|
||||
return prev.FileTimes
|
||||
}
|
||||
|
||||
func (o *driveOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
|
||||
fc := core.FeishuDriveCursor{LastSyncTime: lastSync, FileTimes: times}
|
||||
m := make(map[string]interface{})
|
||||
b, _ := json.Marshal(fc)
|
||||
_ = json.Unmarshal(b, &m)
|
||||
return &types.SyncCursor{LastSyncTime: lastSync, ConnectorCursor: m}
|
||||
}
|
||||
|
||||
// fetchDriveFileContent fetches the content of a single Drive file and converts
|
||||
// it to FetchedItems. Dispatches by file.Type, mirroring the wiki
|
||||
// fetchNodeContent. Shortcuts have already been expanded to their target by
|
||||
// walkDriveTree, so this only sees the target type.
|
||||
//
|
||||
// - docx -> blocks API (Markdown) with export fallback; may return attachments/images
|
||||
// - doc/sheet/bitable -> ExportAndDownload -> docx/xlsx
|
||||
// - file -> DownloadDriveFile -> original file
|
||||
// - mindnote/slides/board -> Skip (no API), returns (nil, nil)
|
||||
func fetchDriveFileContent(
|
||||
ctx context.Context, client *core.Client, file core.DriveFile,
|
||||
resourceID string, region core.Region, parseMode string,
|
||||
) ([]*types.FetchedItem, error) {
|
||||
if !core.IsSupportedDocType(file.Type) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
editTime := core.ParseFeishuTimestamp(file.ModifiedTime)
|
||||
createTime := core.ParseFeishuTimestamp(file.CreatedTime)
|
||||
// Channel marks the knowledge "source" label. Drive uses its own channel
|
||||
// (feishu_drive / lark_drive) so Drive docs show "飞书云盘" / "Lark 云盘"
|
||||
// distinct from the wiki connector's "飞书".
|
||||
channel := types.ChannelFeishuDrive
|
||||
if region.ConnectorType == types.ConnectorTypeLarkDrive {
|
||||
channel = types.ChannelLarkDrive
|
||||
}
|
||||
baseMeta := map[string]string{
|
||||
"obj_token": file.Token,
|
||||
"obj_type": file.Type,
|
||||
"file_token": file.Token,
|
||||
"folder_token": file.ParentToken,
|
||||
"channel": channel,
|
||||
}
|
||||
|
||||
switch file.Type {
|
||||
case "docx":
|
||||
return core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
|
||||
DocToken: file.Token,
|
||||
ObjToken: file.Token,
|
||||
Title: file.Name,
|
||||
URL: file.URL,
|
||||
ResourceID: resourceID,
|
||||
EditTime: editTime,
|
||||
CreateTime: createTime,
|
||||
ParseMode: parseMode,
|
||||
BaseMeta: baseMeta,
|
||||
})
|
||||
|
||||
case "doc", "sheet", "bitable":
|
||||
data, fileName, err := client.ExportAndDownload(ctx, file.Token, file.Type)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("export %s (%s): %w", file.Name, file.Type, err)
|
||||
}
|
||||
|
||||
ext := core.ExportFileExtToSuffix[core.ObjTypeToExportFileExtension[file.Type]]
|
||||
if fileName == "" {
|
||||
fileName = core.SanitizeFileName(file.Name) + ext
|
||||
} else if !strings.HasSuffix(strings.ToLower(fileName), ext) {
|
||||
fileName = core.SanitizeFileName(fileName) + ext
|
||||
}
|
||||
|
||||
return []*types.FetchedItem{{
|
||||
ExternalID: file.Token,
|
||||
Title: file.Name,
|
||||
Content: data,
|
||||
ContentType: "application/octet-stream",
|
||||
FileName: fileName,
|
||||
URL: file.URL,
|
||||
UpdatedAt: editTime,
|
||||
CreatedAt: createTime,
|
||||
SourceResourceID: resourceID,
|
||||
Metadata: baseMeta,
|
||||
}}, nil
|
||||
|
||||
case "file":
|
||||
data, err := client.DownloadDriveFile(ctx, file.Token)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download file %s (%s): %w", file.Name, file.Token, err)
|
||||
}
|
||||
|
||||
fileName := core.SanitizeFileName(file.Name)
|
||||
if fileName == "" {
|
||||
fileName = file.Token
|
||||
}
|
||||
|
||||
return []*types.FetchedItem{{
|
||||
ExternalID: file.Token,
|
||||
Title: file.Name,
|
||||
Content: data,
|
||||
ContentType: "application/octet-stream",
|
||||
FileName: fileName,
|
||||
URL: file.URL,
|
||||
UpdatedAt: editTime,
|
||||
CreatedAt: createTime,
|
||||
SourceResourceID: resourceID,
|
||||
Metadata: baseMeta,
|
||||
}}, nil
|
||||
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
// makeDriveResourceID encodes a Drive ResourceID: "folderToken" (root) or
|
||||
// "folderToken:fileToken" (child). Reuses core.FeishuWikiNodeResourceSeparator.
|
||||
func makeDriveResourceID(rootFolderToken, fileToken string) string {
|
||||
if fileToken == "" {
|
||||
return rootFolderToken
|
||||
}
|
||||
return rootFolderToken + core.FeishuWikiNodeResourceSeparator + fileToken
|
||||
}
|
||||
|
||||
// parseDriveResourceID splits a Drive resourceID into (rootFolderToken, fileToken).
|
||||
// Mirrors parseWikiResourceID.
|
||||
func parseDriveResourceID(resourceID string) (rootFolderToken, fileToken string) {
|
||||
rootFolderToken, fileToken, _ = strings.Cut(resourceID, core.FeishuWikiNodeResourceSeparator)
|
||||
return rootFolderToken, fileToken
|
||||
}
|
||||
|
||||
// isDriveNotFolderError reports whether err indicates the token was not a
|
||||
// folder (1061002 params error from the list API when a file token is passed).
|
||||
func isDriveNotFolderError(err error) bool {
|
||||
s := strings.ToLower(err.Error())
|
||||
return strings.Contains(s, "1061002") || strings.Contains(s, "params error")
|
||||
}
|
||||
|
||||
// filterDriveFileByToken returns only the entries whose Token matches token.
|
||||
func filterDriveFileByToken(files []core.DriveFile, token string) []core.DriveFile {
|
||||
var out []core.DriveFile
|
||||
for _, f := range files {
|
||||
if f.Token == token {
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// driveRootFolderToken extracts the user-supplied root folder_token from the
|
||||
// data source config (ResourceIDs[0]).
|
||||
func driveRootFolderToken(config *types.DataSourceConfig) string {
|
||||
if config == nil || len(config.ResourceIDs) == 0 {
|
||||
return ""
|
||||
}
|
||||
root, _ := parseDriveResourceID(config.ResourceIDs[0])
|
||||
return root
|
||||
}
|
||||
|
||||
// driveFolderToResource builds the root Resource for a Drive folder. The root
|
||||
// folder's name is resolved via GetDriveFolderMeta by the caller (best-effort,
|
||||
// falling back to the token). For sub-folders, use driveFileToResource instead -
|
||||
// the list API returns each child folder's Name.
|
||||
//
|
||||
// The root folder's ExternalID is the bare rootFolderToken (no ":fileToken"
|
||||
// suffix) so it matches the resource_id the user saved in
|
||||
// form.config.resource_ids = [folderToken]. A "token:token" encoding would
|
||||
// break selection matching on edit.
|
||||
func (c *DriveConnector) driveFolderToResource(rootFolderToken, parentToken, folderToken, name string) types.Resource {
|
||||
if name == "" {
|
||||
name = folderToken
|
||||
}
|
||||
return types.Resource{
|
||||
ExternalID: rootFolderToken,
|
||||
Name: name,
|
||||
Type: "drive_folder",
|
||||
URL: c.region.DriveFolderURL(folderToken),
|
||||
HasChildren: true,
|
||||
Metadata: map[string]interface{}{
|
||||
"folder_token": folderToken,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// driveFileToResource converts a core.DriveFile (list result) into a picker Resource.
|
||||
// The ParentID must match the parent folder's ExternalID: the root folder's
|
||||
// ExternalID is the bare rootFolderToken (see driveFolderToResource), while any
|
||||
// sub-folder's ExternalID is "rootFolderToken:folderToken". Direct children of
|
||||
// the root have file.ParentToken == rootFolderToken, so their ParentID is the
|
||||
// bare rootFolderToken; deeper descendants use the encoded form.
|
||||
func (c *DriveConnector) driveFileToResource(rootFolderToken string, file core.DriveFile) types.Resource {
|
||||
name := file.Name
|
||||
if name == "" {
|
||||
name = file.Token
|
||||
}
|
||||
|
||||
modifiedAt := core.ParseFeishuTimestamp(file.ModifiedTime)
|
||||
|
||||
parentID := makeDriveResourceID(rootFolderToken, file.ParentToken)
|
||||
if file.ParentToken == rootFolderToken || file.ParentToken == "" {
|
||||
// Direct child of the root folder: parent is the root, whose
|
||||
// ExternalID is the bare rootFolderToken (no ":token" suffix).
|
||||
parentID = rootFolderToken
|
||||
}
|
||||
|
||||
return types.Resource{
|
||||
ExternalID: makeDriveResourceID(rootFolderToken, file.Token),
|
||||
Name: name,
|
||||
Type: file.Type,
|
||||
URL: file.URL,
|
||||
ParentID: parentID,
|
||||
HasChildren: file.Type == "folder",
|
||||
ModifiedAt: modifiedAt,
|
||||
Metadata: map[string]interface{}{
|
||||
"file_token": file.Token,
|
||||
"obj_type": file.Type,
|
||||
"folder_token": file.ParentToken,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// appendDriveFileListFailureItems converts Drive listing failures into error
|
||||
// FetchedItems so the sync log surfaces which sub-folders could not be listed.
|
||||
// Mirrors appendWikiNodeListFailureItems.
|
||||
func appendDriveFileListFailureItems(items []types.FetchedItem, resourceID, channel string, failures []core.DriveFileListFailure) []types.FetchedItem {
|
||||
for _, failure := range failures {
|
||||
items = append(items, types.FetchedItem{
|
||||
ExternalID: failure.FolderToken,
|
||||
Title: failure.FolderToken,
|
||||
SourceResourceID: resourceID,
|
||||
Metadata: core.FeishuErrorItemMeta(failure.Err, map[string]string{
|
||||
"channel": channel,
|
||||
"folder_token": failure.FolderToken,
|
||||
"failure_stage": "list_children",
|
||||
}),
|
||||
})
|
||||
}
|
||||
return items
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
// P1 directory mapping tests for the Drive connector: path-qualified
|
||||
// FileName, deletion mirroring, partial-listing suppression, move following.
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
// fakeDriveTree serves a mutable Drive folder tree keyed by folder_token.
|
||||
// folders maps folder token → direct children (folders recurse, files sync);
|
||||
// failing folders return HTTP 500 to model a partial listing; metaNames maps
|
||||
// folder token → display name for the folder meta endpoint (absent = error).
|
||||
type fakeDriveTree struct {
|
||||
folders map[string][]core.DriveFile
|
||||
failing map[string]bool
|
||||
metaNames map[string]string
|
||||
// listCalls / metaCalls count API hits per token, so tests can assert a
|
||||
// file token is never probed with folder APIs.
|
||||
listCalls map[string]int
|
||||
metaCalls map[string]int
|
||||
ts *httptest.Server
|
||||
cfg *core.Config
|
||||
}
|
||||
|
||||
func newFakeDriveTree(t *testing.T, folders map[string][]core.DriveFile) *fakeDriveTree {
|
||||
t.Helper()
|
||||
f := &fakeDriveTree{
|
||||
folders: folders, failing: map[string]bool{},
|
||||
listCalls: map[string]int{}, metaCalls: map[string]int{},
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal",
|
||||
func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, core.TokenResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
TenantAccessToken: "fake-token", Expire: 7200,
|
||||
})
|
||||
})
|
||||
// Folder listing (paged endpoint, exact path) and file download (subtree).
|
||||
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, r *http.Request) {
|
||||
token := r.URL.Query().Get("folder_token")
|
||||
f.listCalls[token]++
|
||||
if f.failing[token] {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte(`{"code":1663,"msg":"internal error"}`))
|
||||
return
|
||||
}
|
||||
writeJSON(w, core.DriveFileListResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.DriveFileListData{Files: f.folders[token]},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/open-apis/drive/v1/files/", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasSuffix(r.URL.Path, "/download") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
_, _ = w.Write([]byte("fake-drive-file-content"))
|
||||
})
|
||||
mux.HandleFunc("/open-apis/drive/explorer/v2/folder/", func(w http.ResponseWriter, r *http.Request) {
|
||||
// path: /open-apis/drive/explorer/v2/folder/<token>/meta
|
||||
p := strings.TrimPrefix(r.URL.Path, "/open-apis/drive/explorer/v2/folder/")
|
||||
token := strings.TrimSuffix(p, "/meta")
|
||||
f.metaCalls[token]++
|
||||
name, ok := f.metaNames[token]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"code":1061004,"msg":"not found"}`))
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{"name": name},
|
||||
})
|
||||
})
|
||||
|
||||
f.ts = httptest.NewServer(mux)
|
||||
t.Cleanup(f.ts.Close)
|
||||
f.cfg = &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: f.ts.URL}
|
||||
return f
|
||||
}
|
||||
|
||||
// driveFile builds a regular file entry; folder builds a folder entry.
|
||||
func driveFile(token, name, parent string, modified string) core.DriveFile {
|
||||
return core.DriveFile{Token: token, Name: name, Type: "file", ParentToken: parent, ModifiedTime: modified}
|
||||
}
|
||||
|
||||
func driveFolder(token, name, parent string) core.DriveFile {
|
||||
return core.DriveFile{Token: token, Name: name, Type: "folder", ParentToken: parent}
|
||||
}
|
||||
|
||||
// fetchedByToken indexes emitted non-deleted items by external_id.
|
||||
func fetchedByToken(items []types.FetchedItem) map[string]types.FetchedItem {
|
||||
m := make(map[string]types.FetchedItem, len(items))
|
||||
for _, it := range items {
|
||||
if !it.IsDeleted {
|
||||
m[it.ExternalID] = it
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func deletedIDs(items []types.FetchedItem) []string {
|
||||
var ids []string
|
||||
for _, it := range items {
|
||||
if it.IsDeleted {
|
||||
ids = append(ids, it.ExternalID)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// TestDriveFetchIncremental_PathQualifiedMultiLevel anchors the directory
|
||||
// mapping: the selected root folder mirrors as a top-level KB folder named
|
||||
// after it, so paths are <根名>/<子目录...>/<文件名>, Chinese names kept,
|
||||
// "/" in a folder name sanitised to "_", multi-level nesting resolved from
|
||||
// the same walk.
|
||||
func TestDriveFetchIncremental_PathQualifiedMultiLevel(t *testing.T) {
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{
|
||||
"fold-root": {
|
||||
driveFolder("fold-spec", "规格", "fold-root"),
|
||||
driveFolder("fold-bad", "a/b", "fold-root"), // "/" in the name → "_"
|
||||
driveFile("f-root", "说明.pdf", "fold-root", "100"),
|
||||
},
|
||||
"fold-spec": {driveFile("f-spec", "详细.pdf", "fold-spec", "200")},
|
||||
"fold-bad": {driveFile("f-bad", "child.pdf", "fold-bad", "300")},
|
||||
})
|
||||
f.metaNames = map[string]string{"fold-root": "团队资料"}
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
items, _, err := c.FetchIncremental(context.Background(), makeDriveConfig(f.cfg, []string{"fold-root"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchIncremental() error: %v", err)
|
||||
}
|
||||
|
||||
want := map[string]string{
|
||||
// The selected root folder mirrors as a top-level KB folder ("团队资料"
|
||||
// via the meta mock): every item's path starts with the root name,
|
||||
// deeper ones then carry the sub-directory path.
|
||||
"f-root": "团队资料/说明.pdf",
|
||||
"f-spec": "团队资料/规格/详细.pdf",
|
||||
"f-bad": "团队资料/a_b/child.pdf",
|
||||
}
|
||||
got := fetchedByToken(items)
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %d items (%v), want %d", len(got), got, len(want))
|
||||
}
|
||||
for id, wantPath := range want {
|
||||
if got[id].FileName != wantPath {
|
||||
t.Errorf("FileName for %s = %q, want %q", id, got[id].FileName, wantPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestDriveFetchIncremental_DeletionMirror anchors the deletion engine: a
|
||||
// second full listing that misses a previously synced token emits exactly one
|
||||
// IsDeleted item for it; the first sync (no cursor) emits none.
|
||||
func TestDriveFetchIncremental_DeletionMirror(t *testing.T) {
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{
|
||||
"fold-root": {
|
||||
driveFile("f-a", "a.pdf", "fold-root", "100"),
|
||||
driveFile("f-b", "b.pdf", "fold-root", "200"),
|
||||
},
|
||||
})
|
||||
f.metaNames = map[string]string{"fold-root": "团队资料"}
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
|
||||
|
||||
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync error: %v", err)
|
||||
}
|
||||
if ids := deletedIDs(items1); len(ids) != 0 {
|
||||
t.Errorf("first sync emitted IsDeleted items %v — deletion must be suppressed without a prior cursor", ids)
|
||||
}
|
||||
|
||||
// f-a disappears from the tree.
|
||||
f.folders["fold-root"] = []core.DriveFile{driveFile("f-b", "b.pdf", "fold-root", "200")}
|
||||
|
||||
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync error: %v", err)
|
||||
}
|
||||
ids := deletedIDs(items2)
|
||||
if len(ids) != 1 || ids[0] != "f-a" {
|
||||
t.Errorf("second sync deleted ids = %v, want [f-a]", ids)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDriveFetchIncremental_PartialListingDoesNotDelete anchors the partial
|
||||
// safety: when a sub-folder cannot be listed, deletion detection is suppressed
|
||||
// even though a previously seen token is missing from the (incomplete) listing.
|
||||
func TestDriveFetchIncremental_PartialListingDoesNotDelete(t *testing.T) {
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{
|
||||
"fold-root": {
|
||||
driveFolder("fold-doomed", "doomed", "fold-root"),
|
||||
driveFile("f-a", "a.pdf", "fold-root", "100"),
|
||||
},
|
||||
"fold-doomed": {driveFile("f-deep", "deep.pdf", "fold-doomed", "300")},
|
||||
})
|
||||
f.metaNames = map[string]string{"fold-root": "团队资料"}
|
||||
f.failing["fold-doomed"] = true
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
|
||||
|
||||
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync error: %v", err)
|
||||
}
|
||||
if _, ok := fetchedByToken(items1)["f-a"]; !ok {
|
||||
t.Fatalf("first sync missing f-a: %+v", items1)
|
||||
}
|
||||
|
||||
// f-a disappears while the sub-folder listing stays broken: the listing is
|
||||
// partial, so the missing token must NOT be reported as deleted.
|
||||
f.folders["fold-root"] = []core.DriveFile{driveFolder("fold-doomed", "doomed", "fold-root")}
|
||||
|
||||
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync error: %v", err)
|
||||
}
|
||||
if ids := deletedIDs(items2); len(ids) != 0 {
|
||||
t.Errorf("partial listing emitted IsDeleted items %v — deletion must be suppressed on a partial listing", ids)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDriveFetchIncremental_MoveFollowsNewPath anchors the move story at the
|
||||
// connector level: the same external_id re-fetched after being moved between
|
||||
// folders comes back with the NEW path-qualified FileName (ingestion's
|
||||
// update=delete+recreate then lands it in the new folder_path).
|
||||
func TestDriveFetchIncremental_MoveFollowsNewPath(t *testing.T) {
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{
|
||||
"fold-root": {
|
||||
driveFolder("fold-a", "目录A", "fold-root"),
|
||||
},
|
||||
"fold-a": {driveFile("f-doc", "文档.pdf", "fold-a", "100")},
|
||||
})
|
||||
f.metaNames = map[string]string{"fold-root": "团队资料"}
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
|
||||
|
||||
items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync error: %v", err)
|
||||
}
|
||||
if got := fetchedByToken(items1)["f-doc"].FileName; got != "团队资料/目录A/文档.pdf" {
|
||||
t.Fatalf("first sync f-doc FileName = %q, want 团队资料/目录A/文档.pdf", got)
|
||||
}
|
||||
|
||||
// Move f-doc to a new folder 目录B and bump its modified time.
|
||||
f.folders["fold-root"] = []core.DriveFile{
|
||||
driveFolder("fold-a", "目录A", "fold-root"),
|
||||
driveFolder("fold-b", "目录B", "fold-root"),
|
||||
}
|
||||
f.folders["fold-b"] = []core.DriveFile{driveFile("f-doc", "文档.pdf", "fold-b", "200")}
|
||||
|
||||
items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync error: %v", err)
|
||||
}
|
||||
moved, ok := fetchedByToken(items2)["f-doc"]
|
||||
if !ok {
|
||||
t.Fatalf("moved file not re-fetched on second sync: %+v", items2)
|
||||
}
|
||||
if moved.FileName != "团队资料/目录B/文档.pdf" {
|
||||
t.Errorf("moved file FileName = %q, want 团队资料/目录B/文档.pdf (same external_id, new folder)", moved.FileName)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDriveFetchIncremental_SingleFileSelectionSkipsFolderProbes anchors the
|
||||
// sub-selection fix: a selected file's kind is read off the root subtree
|
||||
// listing, so no folder meta/list API is ever called with the file token —
|
||||
// probing used to fail with 91202/1061002 and log API errors on every sync.
|
||||
func TestDriveFetchIncremental_SingleFileSelectionSkipsFolderProbes(t *testing.T) {
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{
|
||||
"fold-root": {driveFile("f-doc", "文档.docx", "fold-root", "100")},
|
||||
})
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
items, _, err := c.FetchIncremental(context.Background(), makeDriveConfig(f.cfg, []string{"fold-root:f-doc"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchIncremental() error: %v", err)
|
||||
}
|
||||
|
||||
got := fetchedByToken(items)
|
||||
if len(got) != 1 || got["f-doc"].FileName != "文档.docx" {
|
||||
t.Fatalf("got %d items (%v), want exactly f-doc with its own name", len(got), got)
|
||||
}
|
||||
if f.listCalls["f-doc"] != 0 {
|
||||
t.Errorf("folder list probed the file token %d time(s)", f.listCalls["f-doc"])
|
||||
}
|
||||
if f.metaCalls["f-doc"] != 0 {
|
||||
t.Errorf("folder meta probed the file token %d time(s)", f.metaCalls["f-doc"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestDriveFetchIncremental_SubFolderSelection pins the sub-folder semantics:
|
||||
// only the selected subtree syncs, prefixed with the sub-folder's own name.
|
||||
func TestDriveFetchIncremental_SubFolderSelection(t *testing.T) {
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{
|
||||
"fold-root": {
|
||||
driveFolder("fold-spec", "规格", "fold-root"),
|
||||
driveFile("f-root", "说明.pdf", "fold-root", "100"),
|
||||
},
|
||||
"fold-spec": {driveFile("f-spec", "详细.pdf", "fold-spec", "200")},
|
||||
})
|
||||
f.metaNames = map[string]string{"fold-spec": "规格"}
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
items, _, err := c.FetchIncremental(
|
||||
context.Background(), makeDriveConfig(f.cfg, []string{"fold-root:fold-spec"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchIncremental() error: %v", err)
|
||||
}
|
||||
|
||||
got := fetchedByToken(items)
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("got %d items (%v), want only the selected subtree", len(got), got)
|
||||
}
|
||||
if got["f-spec"].FileName != "规格/详细.pdf" {
|
||||
t.Errorf("FileName for f-spec = %q, want %q", got["f-spec"].FileName, "规格/详细.pdf")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveSubfolderDoesNotWalkUnselectedSiblings(t *testing.T) {
|
||||
for _, nested := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "direct", true: "nested"}[nested], func(t *testing.T) {
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{
|
||||
"root": {
|
||||
driveFolder("selected", "Selected", "root"), driveFolder("unselected", "Unselected", "root"),
|
||||
},
|
||||
"selected": {driveFile("doc", "doc.pdf", "selected", "100")},
|
||||
})
|
||||
if nested {
|
||||
f.folders["root"] = []core.DriveFile{driveFolder("unselected", "Unselected", "root")}
|
||||
}
|
||||
f.metaNames = map[string]string{"root": "Root", "selected": "Selected"}
|
||||
// A failure in an unrelated folder must not add retries or partial errors.
|
||||
f.failing["unselected"] = true
|
||||
conn := NewDriveConnector(core.RegionFeishuDrive)
|
||||
cfg := makeDriveConfig(f.cfg, []string{"root:selected"})
|
||||
items, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 || items[0].FileName != "Root/Selected/doc.pdf" {
|
||||
t.Fatalf("unexpected items: %+v", items)
|
||||
}
|
||||
if f.listCalls["unselected"] != 0 || f.listCalls["selected"] != 1 {
|
||||
t.Fatalf("unexpected list calls: %v", f.listCalls)
|
||||
}
|
||||
f.folders["selected"] = nil
|
||||
items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ids := deletedIDs(items); len(ids) != 1 || ids[0] != "doc" {
|
||||
t.Fatalf("selected deletion lost: %+v", items)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveSelectionsShareShallowRootListing(t *testing.T) {
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{
|
||||
"root": {
|
||||
driveFolder("a", "A", "root"), driveFolder("b", "B", "root"), driveFile("doc", "root.pdf", "root", "100"),
|
||||
},
|
||||
"a": {driveFile("doc-a", "a.pdf", "a", "100")},
|
||||
"b": {driveFile("doc-b", "b.pdf", "b", "100")},
|
||||
})
|
||||
f.metaNames = map[string]string{"root": "Root"}
|
||||
conn := NewDriveConnector(core.RegionFeishuDrive)
|
||||
cfg := makeDriveConfig(f.cfg, []string{"root:a", "root:b", "root:doc"})
|
||||
items, _, err := conn.FetchIncremental(context.Background(), cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 3 {
|
||||
t.Fatalf("items=%+v", items)
|
||||
}
|
||||
if f.listCalls["root"] != 1 || f.listCalls["a"] != 1 || f.listCalls["b"] != 1 || f.listCalls["doc"] != 0 {
|
||||
t.Fatalf("unexpected calls: %v", f.listCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveSelectedShortcutKeepsDisplayNameAndTarget(t *testing.T) {
|
||||
for _, selected := range []string{"shortcut", "target"} {
|
||||
t.Run(selected, func(t *testing.T) {
|
||||
var shortcut core.DriveFile
|
||||
raw := `{"token":"shortcut","type":"shortcut","name":"reference.pdf","modified_time":"100",
|
||||
"shortcut_info":{"target_token":"target","target_type":"file"}}`
|
||||
if err := json.Unmarshal([]byte(raw), &shortcut); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := newFakeDriveTree(t, map[string][]core.DriveFile{"root": {shortcut}})
|
||||
f.metaNames = map[string]string{"root": "Root"}
|
||||
conn := NewDriveConnector(core.RegionFeishuDrive)
|
||||
cfg := makeDriveConfig(f.cfg, []string{"root:" + selected})
|
||||
items, _, err := conn.FetchIncremental(context.Background(), cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 || items[0].ExternalID != "target" || items[0].FileName != "Root/reference.pdf" {
|
||||
t.Fatalf("unexpected shortcut item: %+v", items)
|
||||
}
|
||||
if f.listCalls["target"] != 0 || f.listCalls["shortcut"] != 0 || f.listCalls["root"] != 1 {
|
||||
t.Fatalf("shortcut must not trigger folder probes: %v", f.listCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
|
||||
)
|
||||
|
||||
// TestDriveCursorRoundTrip verifies driveOps.EncodeCursor/DecodeCursorTimes
|
||||
// survive a JSON marshal/unmarshal cycle (snapshot isolation), mirroring the
|
||||
// wiki TestFeishuCursorRoundTrip. Design §3.2: driveOps is new code that
|
||||
// previously had no direct test.
|
||||
func TestDriveCursorRoundTrip(t *testing.T) {
|
||||
ops := driveOps{region: core.RegionFeishuDrive}
|
||||
times := map[string]map[string]string{
|
||||
"folder1": {"fdoc1": "100", "fdoc2": "200"},
|
||||
"folder1:fdoc1": {"fdoc1": "100"},
|
||||
"folder2:subA": {"fdoc3": "300"},
|
||||
}
|
||||
cur := ops.EncodeCursor(times, time.Unix(1000, 0))
|
||||
if cur == nil {
|
||||
t.Fatal("EncodeCursor returned nil")
|
||||
}
|
||||
|
||||
got := ops.DecodeCursorTimes(cur.ConnectorCursor)
|
||||
if len(got) != len(times) {
|
||||
t.Fatalf("decoded %d resources, want %d", len(got), len(times))
|
||||
}
|
||||
for rid, files := range times {
|
||||
gotFiles, ok := got[rid]
|
||||
if !ok {
|
||||
t.Errorf("resource %q missing from decoded cursor", rid)
|
||||
continue
|
||||
}
|
||||
for tok, mt := range files {
|
||||
if gotFiles[tok] != mt {
|
||||
t.Errorf("decoded[%q][%q] = %q, want %q", rid, tok, gotFiles[tok], mt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// makeDriveConfig builds a DataSourceConfig for the Drive connector, mirroring
|
||||
// makeConfig but with the drive connector type.
|
||||
func makeDriveConfig(cfg *core.Config, resourceIDs []string) *types.DataSourceConfig {
|
||||
c := makeConfig(cfg, resourceIDs)
|
||||
c.Type = types.ConnectorTypeFeishuDrive
|
||||
return c
|
||||
}
|
||||
|
||||
// fakeFeishuDriveDocx serves the Drive list endpoint plus the docx blocks /
|
||||
// media / export endpoints. blocksMode controls the blocks API behaviour:
|
||||
// - "ok": serve the given blocks
|
||||
// - "fail": HTTP 500 (missing scope) → exercises the export fallback
|
||||
// - "empty": serve only a page block → empty Markdown → export fallback
|
||||
//
|
||||
// The export trio is always registered so both fallback modes can complete.
|
||||
func fakeFeishuDriveDocx(t *testing.T, files []core.DriveFile, docToken string,
|
||||
blocks []core.DocxBlock, blocksMode string, mediaContent []byte,
|
||||
) (*httptest.Server, *core.Config) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, core.TokenResponse{ApiResponse: core.ApiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200})
|
||||
})
|
||||
|
||||
// Drive file listing (single page).
|
||||
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, core.DriveFileListResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.DriveFileListData{Files: files},
|
||||
})
|
||||
})
|
||||
|
||||
// Blocks API for the given docx document.
|
||||
blocksPath := "/open-apis/docx/v1/documents/" + docToken + "/blocks"
|
||||
switch blocksMode {
|
||||
case "fail":
|
||||
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte(`{"code":99991400,"msg":"insufficient scope"}`))
|
||||
})
|
||||
case "empty":
|
||||
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, core.DocxBlocksResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.DocxBlocksData{Items: []core.DocxBlock{{BlockID: "b1", BlockType: core.BlockTypePage}}},
|
||||
})
|
||||
})
|
||||
default: // "ok"
|
||||
mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, core.DocxBlocksResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.DocxBlocksData{Items: blocks},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Media download for File/Image block tokens.
|
||||
mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, "/download") {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
_, _ = w.Write(mediaContent)
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
})
|
||||
|
||||
// Export trio for the fallback path.
|
||||
mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, core.ExportTaskCreateResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.ExportTaskCreateData{Ticket: "ticket-drv"},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/open-apis/drive/v1/export_tasks/ticket-drv", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, core.ExportTaskStatusResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.ExportTaskStatusData{
|
||||
Result: core.ExportTaskResult{FileToken: "ft-export-drv", FileSize: 512, JobStatus: 0, FileName: "drive-fallback.docx"},
|
||||
},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/open-apis/drive/v1/export_tasks/file/ft-export-drv/download", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
_, _ = w.Write([]byte("fake-drive-export-binary"))
|
||||
})
|
||||
|
||||
ts := httptest.NewServer(mux)
|
||||
t.Cleanup(ts.Close)
|
||||
return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
|
||||
}
|
||||
|
||||
func driveDocxBlocks(attToken, attName string) []core.DocxBlock {
|
||||
return []core.DocxBlock{
|
||||
{BlockID: "b1", BlockType: core.BlockTypePage},
|
||||
{BlockID: "b2", BlockType: core.BlockTypeText, Text: &core.BlockText{
|
||||
Elements: []core.TextElement{{TextRun: &core.TextRun{Content: "Hello drive"}}},
|
||||
}},
|
||||
{BlockID: "b3", BlockType: core.BlockTypeFile, File: &core.BlockFileRef{Token: attToken, Name: attName}},
|
||||
}
|
||||
}
|
||||
|
||||
const driveDocxFileToken = "fdoc1"
|
||||
|
||||
func driveDocxFile() core.DriveFile {
|
||||
return core.DriveFile{
|
||||
Token: driveDocxFileToken,
|
||||
Type: "docx",
|
||||
Name: "Drive Doc",
|
||||
ModifiedTime: "500",
|
||||
ParentToken: "folder1",
|
||||
URL: "https://example.feishu.cn/file/" + driveDocxFileToken,
|
||||
}
|
||||
}
|
||||
|
||||
// A drive docx goes through the blocks path: main Markdown item (external_id =
|
||||
// file token, channel = feishu_drive) plus the attachment sub-item.
|
||||
func TestDriveFetchStream_DocxBlocksMultiItem(t *testing.T) {
|
||||
const (
|
||||
attToken = "ft-drv-att"
|
||||
attName = "report.pdf"
|
||||
)
|
||||
attContent := bytes.Repeat([]byte("x"), core.MinAttachmentBytes+1)
|
||||
|
||||
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
|
||||
driveDocxBlocks(attToken, attName), "ok", attContent)
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
h := &recordingHandler{}
|
||||
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchStream() error: %v", err)
|
||||
}
|
||||
|
||||
if len(h.emitted) != 2 {
|
||||
t.Fatalf("expected 2 emitted items (attachment + main doc), got %d: %+v", len(h.emitted), h.emitted)
|
||||
}
|
||||
|
||||
// P3 contract: sub-items are emitted BEFORE the parent document.
|
||||
att := h.emitted[0]
|
||||
wantAttID := driveDocxFileToken + "#file#" + attToken
|
||||
if att.ExternalID != wantAttID {
|
||||
t.Errorf("items[0].ExternalID = %q, want %q", att.ExternalID, wantAttID)
|
||||
}
|
||||
if att.Metadata["attachment"] != "true" {
|
||||
t.Errorf("items[0].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
|
||||
}
|
||||
if att.Metadata["parent_doc_id"] != driveDocxFileToken {
|
||||
t.Errorf("items[0].Metadata[parent_doc_id] = %q, want %q", att.Metadata["parent_doc_id"], driveDocxFileToken)
|
||||
}
|
||||
|
||||
main := h.emitted[1]
|
||||
if main.ExternalID != driveDocxFileToken {
|
||||
t.Errorf("items[1].ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
|
||||
}
|
||||
if main.ContentType != "text/markdown" {
|
||||
t.Errorf("items[1].ContentType = %q, want text/markdown", main.ContentType)
|
||||
}
|
||||
if !main.ReplacesSubtree {
|
||||
t.Errorf("items[1].ReplacesSubtree = false, want true")
|
||||
}
|
||||
if main.Metadata["channel"] != types.ChannelFeishuDrive {
|
||||
t.Errorf("items[1].Metadata[channel] = %q, want %q", main.Metadata["channel"], types.ChannelFeishuDrive)
|
||||
}
|
||||
if main.URL != "https://example.feishu.cn/file/"+driveDocxFileToken {
|
||||
t.Errorf("items[1].URL = %q, want drive file URL passthrough", main.URL)
|
||||
}
|
||||
if !strings.Contains(string(main.Content), "Hello drive") {
|
||||
t.Errorf("items[1].Content missing expected text; got %q", string(main.Content))
|
||||
}
|
||||
}
|
||||
|
||||
// Blocks API failure falls back to export: exactly one octet-stream item, no
|
||||
// ReplacesSubtree (must not sweep good prior children on a transient failure).
|
||||
func TestDriveFetchStream_DocxBlocksFailFallsBackToExport(t *testing.T) {
|
||||
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, nil, "fail", nil)
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
h := &recordingHandler{}
|
||||
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchStream() error: %v", err)
|
||||
}
|
||||
|
||||
if len(h.emitted) != 1 {
|
||||
t.Fatalf("expected 1 emitted item (export fallback), got %d: %+v", len(h.emitted), h.emitted)
|
||||
}
|
||||
item := h.emitted[0]
|
||||
if item.ExternalID != driveDocxFileToken {
|
||||
t.Errorf("item.ExternalID = %q, want %q", item.ExternalID, driveDocxFileToken)
|
||||
}
|
||||
if item.ContentType != "application/octet-stream" {
|
||||
t.Errorf("item.ContentType = %q, want application/octet-stream", item.ContentType)
|
||||
}
|
||||
if !strings.HasSuffix(item.FileName, ".docx") {
|
||||
t.Errorf("item.FileName = %q, want .docx suffix", item.FileName)
|
||||
}
|
||||
if item.ReplacesSubtree {
|
||||
t.Error("export-fallback item must not set ReplacesSubtree")
|
||||
}
|
||||
}
|
||||
|
||||
// Blocks rendering to empty Markdown also falls back to export (a blank page
|
||||
// would otherwise ingest as a login-gated URL core.Fetch and fail).
|
||||
func TestDriveFetchStream_DocxBlocksEmptyFallsBackToExport(t *testing.T) {
|
||||
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, nil, "empty", nil)
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
h := &recordingHandler{}
|
||||
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchStream() error: %v", err)
|
||||
}
|
||||
|
||||
if len(h.emitted) != 1 {
|
||||
t.Fatalf("expected 1 emitted item (export fallback), got %d: %+v", len(h.emitted), h.emitted)
|
||||
}
|
||||
item := h.emitted[0]
|
||||
if item.ContentType != "application/octet-stream" {
|
||||
t.Errorf("item.ContentType = %q, want application/octet-stream", item.ContentType)
|
||||
}
|
||||
if item.ReplacesSubtree {
|
||||
t.Error("export-fallback item must not set ReplacesSubtree")
|
||||
}
|
||||
}
|
||||
|
||||
// Image items are unconditional (not gated by the KB multimodal switch): the
|
||||
// download produces a PNG sub-item, the parent's Markdown carries the numbered
|
||||
// marker, and the external_id stays in SubtreeKeep.
|
||||
func TestDriveFetchStream_DocxImageEmitted(t *testing.T) {
|
||||
const imgToken = "img-drv-1"
|
||||
blocks := []core.DocxBlock{
|
||||
{BlockID: "b1", BlockType: core.BlockTypePage},
|
||||
{BlockID: "b2", BlockType: core.BlockTypeText, Text: &core.BlockText{
|
||||
Elements: []core.TextElement{{TextRun: &core.TextRun{Content: "has image"}}},
|
||||
}},
|
||||
{BlockID: "b3", BlockType: core.BlockTypeImage, Image: &core.BlockTokenRef{Token: imgToken}},
|
||||
}
|
||||
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
|
||||
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", png)
|
||||
|
||||
c := NewDriveConnector(core.RegionFeishuDrive)
|
||||
h := &recordingHandler{}
|
||||
_, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchStream() error: %v", err)
|
||||
}
|
||||
|
||||
// Orthodox flow: the image rides inline in the parent markdown as a base64
|
||||
// data URI — one emitted item, no image sub-item, no image_map.
|
||||
if len(h.emitted) != 1 {
|
||||
t.Fatalf("expected 1 emitted item (main only), got %d: %+v", len(h.emitted), h.emitted)
|
||||
}
|
||||
main := h.emitted[0]
|
||||
if main.ExternalID != driveDocxFileToken {
|
||||
t.Errorf("main ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
|
||||
}
|
||||
wantURI := " + ")"
|
||||
if !strings.Contains(string(main.Content), wantURI) {
|
||||
t.Errorf("image not inlined as base64 data URI:\n%s", main.Content)
|
||||
}
|
||||
if main.Metadata["image_map"] != "" {
|
||||
t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveParseModeChangeRefetchesExistingDocument(t *testing.T) {
|
||||
ts, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
|
||||
driveDocxBlocks("", ""), "ok", nil)
|
||||
defer ts.Close()
|
||||
conf := makeDriveConfig(cfg, []string{"folder1"})
|
||||
conf.Settings = map[string]interface{}{"parse_mode": "export"}
|
||||
c := NewDriveConnector(core.RegionFeishu)
|
||||
items, cursor, err := c.FetchIncremental(context.Background(), conf, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("initial sync: %d items", len(items))
|
||||
}
|
||||
for _, mode := range []string{"blocks", "export"} {
|
||||
conf.Settings["parse_mode"] = mode
|
||||
items, cursor, err = c.FetchIncremental(context.Background(), conf, cursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("mode %s: want one refreshed document, got %d", mode, len(items))
|
||||
}
|
||||
items, _, err = c.FetchIncremental(context.Background(), conf, cursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 0 {
|
||||
t.Fatalf("unchanged mode %s unexpectedly refetched", mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Image-heavy documents must take the native export path, whose ImageRefs do
|
||||
// not have the Markdown data-URI count limit. In particular, no excess base64
|
||||
// may be persisted as searchable document text.
|
||||
func TestDriveImageBudgetFallsBackToNativeExport(t *testing.T) {
|
||||
for _, count := range []int{types.MaxInlineDocumentImages, types.MaxInlineDocumentImages + 1, 61} {
|
||||
t.Run(strconv.Itoa(count), func(t *testing.T) {
|
||||
blocks := []core.DocxBlock{{BlockID: "page", BlockType: core.BlockTypePage}}
|
||||
for i := 0; i < count; i++ {
|
||||
blocks = append(blocks, core.DocxBlock{
|
||||
BlockID: fmt.Sprintf("img%d", i), BlockType: core.BlockTypeImage,
|
||||
Image: &core.BlockTokenRef{Token: "img"},
|
||||
})
|
||||
}
|
||||
data := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
|
||||
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", data)
|
||||
items, err := core.FetchDocxWithBlocks(context.Background(), core.NewClient(cfg), core.DocxFetchInput{
|
||||
DocToken: driveDocxFileToken, ObjToken: driveDocxFileToken, Title: "Images",
|
||||
BaseMeta: map[string]string{}, ParseMode: core.ParseModeBlocks,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("want one document, got %d", len(items))
|
||||
}
|
||||
if count <= types.MaxInlineDocumentImages {
|
||||
if n := strings.Count(string(items[0].Content), "data:image/png;base64,"); n != count {
|
||||
t.Fatalf("inline images=%d, want %d", n, count)
|
||||
}
|
||||
} else {
|
||||
if !strings.HasSuffix(items[0].FileName, ".docx") ||
|
||||
string(items[0].Content) != "fake-drive-export-binary" {
|
||||
t.Fatalf("image-heavy document was not exported: %s", items[0].FileName)
|
||||
}
|
||||
if !items[0].ReplacesSubtree {
|
||||
t.Fatal("complete blocks listing must retain attachment reconciliation")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveImageBudgetPreservesAttachmentsAndExportFailures(t *testing.T) {
|
||||
for _, failExport := range []bool{false, true} {
|
||||
t.Run(strconv.FormatBool(failExport), func(t *testing.T) {
|
||||
blocks := driveDocxBlocks("attachment", "report.pdf")
|
||||
for i := 0; i < 61; i++ {
|
||||
blocks = append(blocks, core.DocxBlock{
|
||||
BlockID: fmt.Sprintf("img%d", i), BlockType: core.BlockTypeImage,
|
||||
Image: &core.BlockTokenRef{Token: "img"},
|
||||
})
|
||||
}
|
||||
ts, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
|
||||
blocks, "ok", bytes.Repeat([]byte("pdf"), 1024))
|
||||
handler := ts.Config.Handler
|
||||
var mediaDownloads atomic.Int32
|
||||
ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.Contains(r.URL.Path, "/medias/") {
|
||||
mediaDownloads.Add(1)
|
||||
}
|
||||
if failExport && r.URL.Path == "/open-apis/drive/v1/export_tasks" {
|
||||
writeJSON(w, core.ApiResponse{Code: 1, Msg: "export unavailable"})
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
})
|
||||
items, err := core.FetchDocxWithBlocks(context.Background(), core.NewClient(cfg), core.DocxFetchInput{
|
||||
DocToken: driveDocxFileToken, ObjToken: driveDocxFileToken, Title: "Images",
|
||||
BaseMeta: map[string]string{}, ParseMode: core.ParseModeBlocks,
|
||||
})
|
||||
if failExport {
|
||||
if err == nil || len(items) != 0 {
|
||||
t.Fatalf("failed export must remain retryable: err=%v items=%d", err, len(items))
|
||||
}
|
||||
if mediaDownloads.Load() != 0 {
|
||||
t.Fatal("media downloaded despite failed parent export")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("want attachment and exported parent, got %d", len(items))
|
||||
}
|
||||
parent := items[1]
|
||||
childID := types.SubtreeChildID(driveDocxFileToken, "file", "attachment")
|
||||
if items[0].ExternalID != childID || items[0].Metadata["parent_doc_id"] != parent.ExternalID {
|
||||
t.Fatal("lost attachment association")
|
||||
}
|
||||
if !parent.ReplacesSubtree || len(parent.SubtreeKeep) != 1 || parent.SubtreeKeep[0] != childID ||
|
||||
!strings.Contains(parent.Metadata["attachment_ids"], childID) {
|
||||
t.Fatalf("lost attachment keep list: %+v", parent)
|
||||
}
|
||||
if mediaDownloads.Load() != 1 {
|
||||
t.Fatalf("want only attachment download, got %d", mediaDownloads.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, v interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func makeConfig(cfg *core.Config, resourceIDs []string) *types.DataSourceConfig {
|
||||
creds := map[string]interface{}{
|
||||
"app_id": cfg.AppID,
|
||||
"app_secret": cfg.AppSecret,
|
||||
"base_url": cfg.BaseURL,
|
||||
}
|
||||
return &types.DataSourceConfig{
|
||||
Type: types.ConnectorTypeFeishu,
|
||||
Credentials: creds,
|
||||
ResourceIDs: resourceIDs,
|
||||
}
|
||||
}
|
||||
|
||||
type recordingHandler struct {
|
||||
emitted []types.FetchedItem
|
||||
checkpoints []core.FeishuDriveCursor
|
||||
emitErr func(item types.FetchedItem) error
|
||||
}
|
||||
|
||||
func (h *recordingHandler) Emit(_ context.Context, item types.FetchedItem) error {
|
||||
if h.emitErr != nil {
|
||||
if err := h.emitErr(item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
h.emitted = append(h.emitted, item)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *recordingHandler) Checkpoint(_ context.Context, cursor *types.SyncCursor) error {
|
||||
var fc core.FeishuDriveCursor
|
||||
b, _ := json.Marshal(cursor.ConnectorCursor)
|
||||
_ = json.Unmarshal(b, &fc)
|
||||
h.checkpoints = append(h.checkpoints, fc)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
|
||||
)
|
||||
|
||||
// TestClientDriveListFilesPagination is the Drive (云盘) counterpart of the wiki
|
||||
// test added in #3645 (TestClientWikiPaginationRejectsRepeatedPageToken):
|
||||
// ListDriveFilesAllPages used to stop only on an empty next_page_token, so a
|
||||
// repeated token (or has_more=false with a stale token) made it re-request the
|
||||
// same page forever. Each case runs under a short deadline so a regression
|
||||
// fails fast instead of hanging the suite.
|
||||
func TestClientDriveListFilesPagination(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
response func(page int) core.DriveFileListResponse
|
||||
wantErr string
|
||||
wantRequests int
|
||||
wantFiles []string
|
||||
}{
|
||||
{
|
||||
// Feishu can hand back has_more=true with a token it already
|
||||
// returned; that is exactly what #3645 hit on the wiki endpoints.
|
||||
name: "repeated page token",
|
||||
response: func(page int) core.DriveFileListResponse {
|
||||
return core.DriveFileListResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.DriveFileListData{
|
||||
Files: []core.DriveFile{{Token: fmt.Sprintf("file-%d", page)}},
|
||||
HasMore: true,
|
||||
NextPageToken: "repeated-token",
|
||||
},
|
||||
}
|
||||
},
|
||||
wantErr: "repeated page token",
|
||||
wantRequests: 2,
|
||||
},
|
||||
{
|
||||
// has_more=false is the authoritative stop signal: a residual
|
||||
// non-empty token must not trigger another round trip.
|
||||
name: "has_more false with stale token",
|
||||
response: func(int) core.DriveFileListResponse {
|
||||
return core.DriveFileListResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.DriveFileListData{
|
||||
Files: []core.DriveFile{{Token: "file-1"}},
|
||||
HasMore: false,
|
||||
NextPageToken: "stale-token",
|
||||
},
|
||||
}
|
||||
},
|
||||
wantRequests: 1,
|
||||
wantFiles: []string{"file-1"},
|
||||
},
|
||||
{
|
||||
// The guard must not truncate a genuinely paginated folder.
|
||||
name: "two real pages are still merged",
|
||||
response: func(page int) core.DriveFileListResponse {
|
||||
if page == 1 {
|
||||
return core.DriveFileListResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.DriveFileListData{
|
||||
Files: []core.DriveFile{{Token: "file-1"}},
|
||||
HasMore: true,
|
||||
NextPageToken: "token-2",
|
||||
},
|
||||
}
|
||||
}
|
||||
return core.DriveFileListResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
Data: core.DriveFileListData{
|
||||
Files: []core.DriveFile{{Token: "file-2"}},
|
||||
HasMore: false,
|
||||
NextPageToken: "",
|
||||
},
|
||||
}
|
||||
},
|
||||
wantRequests: 2,
|
||||
wantFiles: []string{"file-1", "file-2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
authPath := "/open-apis/auth/v3/tenant_access_token/internal"
|
||||
mux.HandleFunc(authPath, func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, core.TokenResponse{
|
||||
ApiResponse: core.ApiResponse{Code: 0},
|
||||
TenantAccessToken: "fake-token",
|
||||
Expire: 7200,
|
||||
})
|
||||
})
|
||||
var requests atomic.Int64
|
||||
mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, tt.response(int(requests.Add(1))))
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
client := core.NewClient(&core.Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
files, err := client.ListDriveFilesAllPages(ctx, "folder1")
|
||||
if ctx.Err() != nil {
|
||||
t.Fatalf("pagination never terminated (requests=%d, err=%v)", requests.Load(), err)
|
||||
}
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("ListDriveFilesAllPages() error = %v, want nil", err)
|
||||
}
|
||||
} else if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("ListDriveFilesAllPages() error = %v, want error containing %q", err, tt.wantErr)
|
||||
}
|
||||
if got := int(requests.Load()); got != tt.wantRequests {
|
||||
t.Fatalf("drive list requests = %d, want %d", got, tt.wantRequests)
|
||||
}
|
||||
|
||||
gotFiles := make([]string, 0, len(files))
|
||||
seen := make(map[string]bool, len(files))
|
||||
for _, f := range files {
|
||||
if seen[f.Token] {
|
||||
t.Fatalf("file token %q was appended more than once", f.Token)
|
||||
}
|
||||
seen[f.Token] = true
|
||||
gotFiles = append(gotFiles, f.Token)
|
||||
}
|
||||
if tt.wantFiles != nil && !reflect.DeepEqual(gotFiles, tt.wantFiles) {
|
||||
t.Fatalf("files = %v, want %v", gotFiles, tt.wantFiles)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package drive
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// This file implements the P1 directory mapping for the Drive connector:
|
||||
// FetchedItem.FileName becomes "<根文件夹名>/<子目录...>/<文件名>" rooted at
|
||||
// the selected sync root's own display name (the root folder = a top-level KB
|
||||
// folder) so ingestion's types.SplitKnowledgeRelativePath derives the KB
|
||||
// folder_path. The recursive
|
||||
// walk itself is core.WalkDriveTree (the Drive connector's single walker,
|
||||
// shared with core): DFS order, shortcut expansion, partial-failure
|
||||
// aggregation — plus a folder-token → cleaned directory path table built in
|
||||
// the same pass, so no extra API calls are made. This file only resolves the
|
||||
// per-resource root and feeds the walk results into Fetch.
|
||||
|
||||
// driveFolderName resolves a folder's display name via GetDriveFolderMeta,
|
||||
// one call per token per sync run (cached on success only — a failure is not
|
||||
// cached, so the next resource in the same run retries). resolved is false
|
||||
// when the meta call failed or returned no name — that folder's path prefix
|
||||
// segment (root or sub-folder) is then skipped.
|
||||
func (o *driveOps) driveFolderName(
|
||||
ctx context.Context, client *core.Client, folderToken string,
|
||||
) (name string, resolved bool) {
|
||||
if o.folderNames == nil {
|
||||
o.folderNames = make(map[string]string)
|
||||
}
|
||||
if name, ok := o.folderNames[folderToken]; ok {
|
||||
return name, true
|
||||
}
|
||||
meta, err := client.GetDriveFolderMeta(ctx, folderToken)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[FeishuDrive] resolve folder name for %s: %v (falling back)", folderToken, err)
|
||||
return "", false
|
||||
}
|
||||
if meta.Data.Name == "" {
|
||||
return "", false
|
||||
}
|
||||
name = core.SanitizeFileName(meta.Data.Name)
|
||||
o.folderNames[folderToken] = name
|
||||
return name, true
|
||||
}
|
||||
|
||||
// listDriveFilesForResource lists the files to sync for a resourceID and
|
||||
// records the directory-path table for Fetch. A resourceID is either a bare
|
||||
// rootFolderToken (sync the whole subtree) or "rootFolderToken:fileToken"
|
||||
// (sync a single selected file or sub-folder). Every walk is rooted at the
|
||||
// root folder's own display name, so the synced folder appears as a top-level
|
||||
// KB folder holding its subtree (an unresolved root name falls back to no
|
||||
// prefix, mirroring pre-root-mirror behaviour).
|
||||
func (o *driveOps) listDriveFilesForResource(
|
||||
ctx context.Context, client *core.Client, resourceID string,
|
||||
) ([]core.DriveFile, error) {
|
||||
rootFolderToken, fileToken := parseDriveResourceID(resourceID)
|
||||
|
||||
rootBase := ""
|
||||
if rootName, ok := o.driveFolderName(ctx, client, rootFolderToken); ok {
|
||||
rootBase = rootName
|
||||
}
|
||||
|
||||
if fileToken == "" {
|
||||
// The selected root folder maps to a top-level KB folder named after
|
||||
// it: documents directly under it land in folder_path "<根名>".
|
||||
files, dirPaths, failures := core.WalkDriveTree(ctx, client, rootFolderToken, rootBase)
|
||||
o.dirPaths = dirPaths
|
||||
return files, partialDriveError(failures)
|
||||
}
|
||||
|
||||
// A shallow root listing identifies direct files without probing them with
|
||||
// folder APIs, and direct folders without visiting unselected siblings.
|
||||
if o.rootEntries == nil {
|
||||
o.rootEntries = make(map[string][]core.DriveFile)
|
||||
}
|
||||
entries, cached := o.rootEntries[rootFolderToken]
|
||||
if !cached {
|
||||
if listed, err := client.ListDriveFilesAllPages(ctx, rootFolderToken); err == nil {
|
||||
entries = listed
|
||||
o.rootEntries[rootFolderToken] = listed
|
||||
}
|
||||
}
|
||||
base := rootBase
|
||||
folderFound := false
|
||||
for _, entry := range entries {
|
||||
f, ok := core.ExpandDriveShortcut(entry)
|
||||
if !ok || (entry.Token != fileToken && f.Token != fileToken) {
|
||||
continue
|
||||
}
|
||||
if f.Type != "folder" {
|
||||
// Some list responses omit parent_token; the listing itself tells
|
||||
// us the containing directory.
|
||||
f.ParentToken = rootFolderToken
|
||||
o.dirPaths = map[string]string{rootFolderToken: rootBase}
|
||||
return []core.DriveFile{f}, nil
|
||||
}
|
||||
folderFound = true
|
||||
base = joinDriveDir(rootBase, core.SanitizeFileName(f.Name))
|
||||
break
|
||||
}
|
||||
if !folderFound {
|
||||
// A nested selected folder can be walked directly, even when the
|
||||
// caller cannot list its parent. No full-root discovery is needed.
|
||||
if subName, ok := o.driveFolderName(ctx, client, fileToken); ok {
|
||||
base = joinDriveDir(rootBase, subName)
|
||||
}
|
||||
}
|
||||
files, dirPaths, failures := core.WalkDriveTree(ctx, client, fileToken, base)
|
||||
for _, failure := range failures {
|
||||
if failure.FolderToken == fileToken && isDriveNotFolderError(failure.Err) {
|
||||
// Only nested single files need the legacy root search: Drive
|
||||
// exposes no single-file parent query. Never use this fallback for
|
||||
// permission/transport failures, which must retain the old cursor.
|
||||
rootFiles, rootDirs, rootFailures := core.WalkDriveTree(ctx, client, rootFolderToken, rootBase)
|
||||
o.dirPaths = rootDirs
|
||||
return filterDriveFileByToken(rootFiles, fileToken), partialDriveError(rootFailures)
|
||||
}
|
||||
}
|
||||
o.dirPaths = dirPaths
|
||||
return files, partialDriveError(failures)
|
||||
}
|
||||
|
||||
func joinDriveDir(parent, name string) string {
|
||||
if parent == "" {
|
||||
return name
|
||||
}
|
||||
if name == "" {
|
||||
return parent
|
||||
}
|
||||
return parent + "/" + name
|
||||
}
|
||||
|
||||
// partialDriveError wraps collected failures into a
|
||||
// *core.PartialDriveFileListError (nil when there are none).
|
||||
func partialDriveError(failures []core.DriveFileListFailure) error {
|
||||
if len(failures) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &core.PartialDriveFileListError{Failures: failures}
|
||||
}
|
||||
|
||||
// qualifyItemFileNames prefixes every fetched item's FileName with dir so
|
||||
// ingestion derives the KB folder path. The prefix applies to the main item
|
||||
// and to attachment/image sub-items alike — they all live in the same folder.
|
||||
// An empty dir (parent folder not in the current walk) or FileName is untouched.
|
||||
func qualifyItemFileNames(items []*types.FetchedItem, dir string) {
|
||||
if dir == "" {
|
||||
return
|
||||
}
|
||||
for _, it := range items {
|
||||
if it != nil && it.FileName != "" {
|
||||
it.FileName = dir + "/" + it.FileName
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user