diff --git a/docs/数据源导入开发文档.md b/docs/数据源导入开发文档.md index 172aaaeb..875880e0 100644 --- a/docs/数据源导入开发文档.md +++ b/docs/数据源导入开发文档.md @@ -54,6 +54,15 @@ WeKnora 的数据源导入模块支持从外部平台(飞书、企业微信、 | `drive:export:readonly` | 导出文档内容(docx/xlsx) | | `docx:document:readonly` | 读取新版文档内容 | +> **docx 内嵌内容下钻权限(可选)** +> +> 若需同步 docx 文档中内嵌的附件和图片,还需额外开通以下权限(缺失时自动回退到导出 docx,不会同步失败,仅无法获取内嵌表格/附件): +> +> - `docx:document:readonly` — 读取文档块(上表已含,此处仅供核对) +> - `drive:drive:readonly` / `docs:document.media:download` — 下载附件、图片 +> - `sheets:spreadsheet:readonly` — 读取内嵌电子表格 +> - `bitable:app:readonly` — 读取内嵌多维表格 + #### 第三步:发布应用 在 **版本管理与发布** 中创建版本并提交审核。审核通过后方可正常调用 API。 diff --git a/internal/application/repository/knowledge.go b/internal/application/repository/knowledge.go index 40d70cd5..c3a06be2 100644 --- a/internal/application/repository/knowledge.go +++ b/internal/application/repository/knowledge.go @@ -581,6 +581,41 @@ func (r *knowledgeRepository) FindByMetadataKey( return &knowledge, nil } +// FindByMetadataKeyPrefix finds knowledge items whose metadata[key] starts with +// the given prefix. Used to sweep an external node's attachment sub-items on re-sync. +func (r *knowledgeRepository) FindByMetadataKeyPrefix( + ctx context.Context, + tenantID uint64, + kbID string, + key string, + prefix string, +) ([]*types.Knowledge, error) { + escaped := escapeLikeKeyword(prefix) + var items []*types.Knowledge + // The JSON key is embedded as a SQL literal (metadata->>'external_id'), NOT a + // bind parameter. PostgreSQL only uses the expression index + // idx_knowledges_kb_metadata_external_id (built on the literal expression + // (metadata->>'external_id')) when that exact expression appears in the query; + // a bound metadata->>$1 is a structurally different expression the planner + // cannot match, so it would silently fall back to a heap scan. key is an + // internal, caller-supplied field name (always "external_id"); single-quotes + // are doubled defensively so the literal is always well-formed. + // + // The prefix pattern stays a bind parameter: an unnamed prepared statement is + // custom-planned with the actual value, so LIKE 'prefix%' still extracts the + // prefix and drives the index. The explicit ESCAPE '\' keeps backslash-escaped + // wildcards (e.g. \_) literal on both PostgreSQL and SQLite. + keyExpr := "metadata->>'" + strings.ReplaceAll(key, "'", "''") + "'" + err := r.db.WithContext(ctx). + Where("tenant_id = ? AND knowledge_base_id = ? AND deleted_at IS NULL", tenantID, kbID). + Where(keyExpr+" LIKE ? ESCAPE ?", escaped+"%", `\`). + Find(&items).Error + if err != nil { + return nil, err + } + return items, nil +} + func (r *knowledgeRepository) SearchKnowledge( ctx context.Context, tenantID uint64, diff --git a/internal/application/repository/knowledge_metadata_prefix_test.go b/internal/application/repository/knowledge_metadata_prefix_test.go new file mode 100644 index 00000000..d3b7e60b --- /dev/null +++ b/internal/application/repository/knowledge_metadata_prefix_test.go @@ -0,0 +1,112 @@ +package repository + +import ( + "context" + "fmt" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestFindByMetadataKeyPrefix verifies that FindByMetadataKeyPrefix returns only +// knowledge items whose metadata["external_id"] starts with the given prefix. +// +// Setup: three rows in the same KB: +// - "nodeA" — the parent document; must NOT be matched by prefix "nodeA#" +// - "nodeA#file#x" — an attachment child; MUST be matched +// - "nodeB" — a sibling document; must NOT be matched +// +// A fourth row in a different KB with a matching external_id is also inserted to +// verify tenant/KB isolation. +func TestFindByMetadataKeyPrefix(t *testing.T) { + db := setupKnowledgeTestDB(t) + repo := NewKnowledgeRepository(db).(*knowledgeRepository) + ctx := context.Background() + + const tenantID uint64 = 42 + kbID := uuid.New().String() + otherKBID := uuid.New().String() + + insertRow := func(tid uint64, kb, extID string) string { + id := uuid.New().String() + metadata := fmt.Sprintf(`{"external_id":%q}`, extID) + require.NoError(t, db.Exec(` + INSERT INTO knowledges + (id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata) + VALUES (?, ?, ?, 'document', ?, 'feishu', 'completed', ?) + `, id, tid, kb, extID, metadata).Error) + return id + } + + _ = insertRow(tenantID, kbID, "nodeA") // parent — must NOT match + childID := insertRow(tenantID, kbID, "nodeA#file#x") // attachment child — MUST match + _ = insertRow(tenantID, kbID, "nodeB") // sibling — must NOT match + _ = insertRow(tenantID, otherKBID, "nodeA#file#y") // different KB — must be excluded + + results, err := repo.FindByMetadataKeyPrefix(ctx, tenantID, kbID, "external_id", "nodeA#") + require.NoError(t, err) + + require.Len(t, results, 1, "only the attachment child should match the prefix 'nodeA#'") + assert.Equal(t, childID, results[0].ID) +} + +// TestFindByMetadataKeyPrefix_DeletedRowsExcluded verifies that soft-deleted rows +// (deleted_at IS NOT NULL) are excluded from the prefix query. +func TestFindByMetadataKeyPrefix_DeletedRowsExcluded(t *testing.T) { + db := setupKnowledgeTestDB(t) + repo := NewKnowledgeRepository(db).(*knowledgeRepository) + ctx := context.Background() + + const tenantID uint64 = 43 + kbID := uuid.New().String() + + id := uuid.New().String() + metadata := fmt.Sprintf(`{"external_id":%q}`, "nodeC#file#z") + require.NoError(t, db.Exec(` + INSERT INTO knowledges + (id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata, deleted_at) + VALUES (?, ?, ?, 'document', 'deleted-child', 'feishu', 'completed', ?, '2026-01-01 00:00:00') + `, id, tenantID, kbID, metadata).Error) + + results, err := repo.FindByMetadataKeyPrefix(ctx, tenantID, kbID, "external_id", "nodeC#") + require.NoError(t, err) + assert.Empty(t, results, "soft-deleted rows must not appear in prefix results") +} + +// TestFindByMetadataKeyPrefix_UnderscoreIsLiteral verifies that an underscore in +// the prefix is treated as a literal character and does NOT act as a SQL LIKE +// wildcard. Without escapeLikeKeyword applied to the prefix, a query for "ab_c#" +// would also match "abXc#file#y" because '_' is a wildcard. +func TestFindByMetadataKeyPrefix_UnderscoreIsLiteral(t *testing.T) { + db := setupKnowledgeTestDB(t) + repo := NewKnowledgeRepository(db).(*knowledgeRepository) + ctx := context.Background() + + const tenantID uint64 = 44 + kbID := uuid.New().String() + + insertRow := func(extID string) string { + id := uuid.New().String() + metadata := fmt.Sprintf(`{"external_id":%q}`, extID) + require.NoError(t, db.Exec(` + INSERT INTO knowledges + (id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata) + VALUES (?, ?, ?, 'document', ?, 'feishu', 'completed', ?) + `, id, tenantID, kbID, extID, metadata).Error) + return id + } + + // The prefix we will search for is "ab_c#". Without escaping, '_' is a + // wildcard that matches any single character, so "abXc#file#y" would also + // be returned. With escaping it must NOT be returned. + targetID := insertRow("ab_c#file#x") // literal underscore — MUST match + _ = insertRow("abXc#file#y") // 'X' instead of '_' — must NOT match + + results, err := repo.FindByMetadataKeyPrefix(ctx, tenantID, kbID, "external_id", "ab_c#") + require.NoError(t, err) + + require.Len(t, results, 1, "underscore in prefix must be treated as literal: only 'ab_c#file#x' should match") + assert.Equal(t, targetID, results[0].ID) +} diff --git a/internal/application/service/datasource_service.go b/internal/application/service/datasource_service.go index bd29d8e6..79522e64 100644 --- a/internal/application/service/datasource_service.go +++ b/internal/application/service/datasource_service.go @@ -9,6 +9,7 @@ import ( "mime/multipart" "net/textproto" "reflect" + "slices" "strings" "time" @@ -615,9 +616,10 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e return nil } - if _, err := s.kbService.GetKnowledgeBaseByID(ctx, ds.KnowledgeBaseID); err != nil { + kb, kbErr := s.kbService.GetKnowledgeBaseByID(ctx, ds.KnowledgeBaseID) + if kbErr != nil { logger.Warnf(ctx, "knowledge base not found (likely deleted), cancelling sync: kb=%s ds=%s err=%v", - ds.KnowledgeBaseID, payload.DataSourceID, err) + ds.KnowledgeBaseID, payload.DataSourceID, kbErr) syncLog.Status = types.SyncLogStatusCanceled syncLog.FinishedAt = timePtr(time.Now().UTC()) syncLog.ErrorMessage = "knowledge base has been deleted" @@ -658,6 +660,9 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e _ = s.dsRepo.Update(ctx, ds) return err } + // Surface the KB's multimodal/VLM state to the connector so it only extracts + // embedded images for OCR when the KB can actually ingest them (never persisted). + config.MultimodalEnabled = kb.IsMultimodalEnabled() // Streaming path: connectors that support it interleave fetch→ingest→ // checkpoint so a large sync bounds memory and resumes after a timeout @@ -860,12 +865,23 @@ func (s *DataSourceService) applyFetchedItem( isUpdate, err := s.ingestItem(ctx, ds, item, tagIDs) if err != nil { - // Duplicate file/URL is not a failure — count as skipped var dupErr *types.DuplicateKnowledgeError - if errors.As(err, &dupErr) { + switch { + case errors.As(err, &dupErr): + // Duplicate file/URL is not a failure — count as skipped. logger.Infof(ctx, "item %q (external_id=%s) already exists, skipping", item.Title, item.ExternalID) result.Skipped++ - } else { + case item.Metadata["embedded_image"] == "true": + // An image extracted from a document for OCR is a best-effort + // enrichment, not the document itself. If the KB cannot ingest it + // (VLM/object-storage not configured for images, or a transient error), + // skip it rather than failing the whole sync: the doc body already + // synced, and the image stays in SubtreeKeep for a later retry once the + // KB is configured. + logger.Infof(ctx, "skipping embedded image %q (external_id=%s), not ingested: %v", + item.Title, item.ExternalID, err) + result.Skipped++ + default: logger.Warnf(ctx, "failed to ingest item %q (external_id=%s): %v", item.Title, item.ExternalID, err) result.Failed++ recordSyncError(result, types.SyncItemError{ @@ -1181,7 +1197,7 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource if err != nil { return isUpdate, fmt.Errorf("build file header: %w", err) } - _, err = s.knowledgeService.CreateKnowledgeFromFile( + if _, err := s.knowledgeService.CreateKnowledgeFromFile( ctx, ds.KnowledgeBaseID, fh, @@ -1191,13 +1207,23 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource tagIDs, // auto-tag from data source channel, nil, - ) - return isUpdate, err + ); err != nil { + var dupErr *types.DuplicateKnowledgeError + if errors.As(err, &dupErr) && dupIsSameNode(dupErr, item) { + // Identical content is already present in the KB under THIS node's + // own external_id, so the parent effectively exists — reconcile the + // subtree so children removed from the doc do not linger. + s.sweepStaleSubtree(ctx, ds, item) + } + return isUpdate, err + } + s.sweepStaleSubtree(ctx, ds, item) + return isUpdate, nil } // Case 2: only a remote URL — let WeKnora handle downloading and parsing if item.URL != "" { - _, err := s.knowledgeService.CreateKnowledgeFromURL( + if _, err := s.knowledgeService.CreateKnowledgeFromURL( ctx, ds.KnowledgeBaseID, item.URL, @@ -1208,13 +1234,89 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource tagIDs, // auto-tag from data source channel, nil, - ) - return isUpdate, err + ); err != nil { + var dupErr *types.DuplicateKnowledgeError + if errors.As(err, &dupErr) && dupIsSameNode(dupErr, item) { + // Identical content is already present in the KB under THIS node's + // own external_id, so the parent effectively exists — reconcile the + // subtree so children removed from the doc do not linger. + s.sweepStaleSubtree(ctx, ds, item) + } + return isUpdate, err + } + s.sweepStaleSubtree(ctx, ds, item) + return isUpdate, nil } return isUpdate, fmt.Errorf("item has neither content nor URL") } +// dupIsSameNode reports whether a duplicate-content error means the parent still +// exists in the KB *under this item's own external_id* — i.e. a content-dedup hit +// against this same node, so reconciling its subtree is safe. Deduplication keys +// on file_hash alone (CheckKnowledgeExists), so an updated node whose rebuilt body +// happens to hash-collide with a DIFFERENT knowledge item (another node, or a +// manually-uploaded file with no external_id) would otherwise sweep this node's +// children even though its own parent row was just deleted for the update and +// never recreated — deleting those children with no parent to replace them. In +// that case the matched row's external_id differs (or is absent), so we skip the +// sweep and leave the children intact. +func dupIsSameNode(dupErr *types.DuplicateKnowledgeError, item *types.FetchedItem) bool { + return dupErr != nil && dupErr.Knowledge != nil && + dupErr.Knowledge.GetMetadata()["external_id"] == item.ExternalID +} + +// sweepStaleSubtree deletes STALE sub-items of item — knowledge whose external_id +// is prefixed with "#" (e.g. attachment children of a docx node) +// that is NOT listed in item.SubtreeKeep, i.e. no longer present in the source. +// +// It runs only AFTER the parent item exists in the KB (freshly (re)created, or +// confirmed present via a duplicate-hash error), so a genuinely failed parent +// write never destroys existing children. Children still present in the source +// are preserved via SubtreeKeep even when they could not be re-ingested this +// cycle (e.g. a transient attachment download failure), so a still-present +// attachment never loses its previously-synced good copy. The "#" prefix +// never matches the parent's own "" external_id, so the parent is never +// self-swept. +func (s *DataSourceService) sweepStaleSubtree(ctx context.Context, ds *types.DataSource, item *types.FetchedItem) { + if !item.ReplacesSubtree || item.ExternalID == "" { + return + } + repo := s.knowledgeService.GetRepository() + children, err := repo.FindByMetadataKeyPrefix(ctx, ds.TenantID, ds.KnowledgeBaseID, "external_id", types.SubtreeChildPrefix(item.ExternalID)) + if err != nil { + logger.Warnf(ctx, "failed to list subtree of external_id=%s: %v", item.ExternalID, err) + return + } + if len(children) == 0 { + return + } + ids := make([]string, 0, len(children)) + for _, child := range children { + // A child still present in the source is preserved even if it could not be + // re-ingested this sync; only children that vanished from the source are + // stale and swept. Every child here was selected by the external_id-prefix + // query, so its external_id is guaranteed present and readable (a malformed + // row could not have matched the SQL predicate), and GetMetadata resolves + // it identically to the keep-set entries the connector built. SubtreeKeep + // holds one entry per still-present sub-item of this node (a small set), so + // a linear scan is cheaper than materializing a lookup map. + if slices.Contains(item.SubtreeKeep, child.GetMetadata()["external_id"]) { + continue + } + ids = append(ids, child.ID) + } + if len(ids) == 0 { + return + } + // Batch the deletion so a node whose attachment set shrank from N pays one + // round of the delete fan-out rather than N sequential ones. + if derr := s.knowledgeService.DeleteKnowledgeList(ctx, ids); derr != nil { + logger.Warnf(ctx, "failed to delete %d stale sub-item(s) of external_id=%s: %v", + len(ids), item.ExternalID, derr) + } +} + // bytesToFileHeader wraps a []byte into a *multipart.FileHeader so it can be // consumed by KnowledgeService.CreateKnowledgeFromFile. func bytesToFileHeader(data []byte, filename string) (*multipart.FileHeader, error) { diff --git a/internal/application/service/datasource_sweep_wiring_test.go b/internal/application/service/datasource_sweep_wiring_test.go new file mode 100644 index 00000000..ffce2ed5 --- /dev/null +++ b/internal/application/service/datasource_sweep_wiring_test.go @@ -0,0 +1,300 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "mime/multipart" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// ── interface-embedding fakes: only the methods ingestItem touches are +// implemented; everything else is nil (never called by this path). ── + +type sweepFakeRepo struct { + interfaces.KnowledgeRepository + prefixCalls []string // recorded prefix arguments + prefixReturn []*types.Knowledge // children to return from FindByMetadataKeyPrefix +} + +func (r *sweepFakeRepo) FindByMetadataKey(ctx context.Context, tenantID uint64, kbID, key, value string) (*types.Knowledge, error) { + return nil, nil // no existing main item → skip the case-1 update delete +} + +func (r *sweepFakeRepo) FindByMetadataKeyPrefix(ctx context.Context, tenantID uint64, kbID, key, prefix string) ([]*types.Knowledge, error) { + r.prefixCalls = append(r.prefixCalls, key+"|"+prefix) + return r.prefixReturn, nil +} + +type sweepFakeKS struct { + interfaces.KnowledgeService + repo *sweepFakeRepo + events []string // ordered log of "delete:" and "create:" + deleted []string + createErr error // if set, CreateKnowledgeFromFile returns it after logging +} + +func (k *sweepFakeKS) GetRepository() interfaces.KnowledgeRepository { return k.repo } + +func (k *sweepFakeKS) DeleteKnowledge(ctx context.Context, id string) error { + k.events = append(k.events, "delete:"+id) + k.deleted = append(k.deleted, id) + return nil +} + +// DeleteKnowledgeList is the batched delete the subtree sweep now uses; record +// each id in order so create-before-delete ordering is still asserted. +func (k *sweepFakeKS) DeleteKnowledgeList(ctx context.Context, ids []string) error { + for _, id := range ids { + k.events = append(k.events, "delete:"+id) + k.deleted = append(k.deleted, id) + } + return nil +} + +func (k *sweepFakeKS) CreateKnowledgeFromFile( + ctx context.Context, kbID string, file *multipart.FileHeader, metadata map[string]string, + enableMultimodel *bool, customFileName string, tagIDs []string, channel string, + processOverrides *types.KnowledgeProcessOverrides, +) (*types.Knowledge, error) { + k.events = append(k.events, "create:"+customFileName) + if k.createErr != nil { + return nil, k.createErr + } + return &types.Knowledge{ID: "new-knowledge"}, nil +} + +// TestIngestItem_ReplacesSubtreeSweepsStaleChildrenAfterCreate verifies the +// orphan-cleanup wiring end-to-end at the service layer: when a re-synced parent +// item carries ReplacesSubtree, ingestItem must (1) query the child subtree by +// the "#" prefix, (2) delete every stale child, and (3) do so only +// AFTER the parent content is written — so a failed/duplicate-skipped parent +// write never destroys existing children (the new children arrive as separate +// items later in the same sync, so the sweep still precedes their creation). +func TestIngestItem_ReplacesSubtreeSweepsStaleChildrenAfterCreate(t *testing.T) { + repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{ + {ID: "stale-child-1"}, + {ID: "stale-child-2"}, + }} + ks := &sweepFakeKS{repo: repo} + s := &DataSourceService{knowledgeService: ks} + + ds := &types.DataSource{ + ID: "ds-1", + Type: "feishu", + TenantID: 7, + KnowledgeBaseID: "kb-1", + } + item := &types.FetchedItem{ + ExternalID: "nt-parent", + Title: "Parent Doc", + Content: []byte("# hello\n"), + ContentType: "text/markdown", + FileName: "parent.md", + ReplacesSubtree: true, + } + + if _, err := s.ingestItem(context.Background(), ds, item, nil); err != nil { + t.Fatalf("ingestItem error: %v", err) + } + + // (1) queried by the correct prefix + if len(repo.prefixCalls) != 1 || repo.prefixCalls[0] != "external_id|nt-parent#" { + t.Fatalf("prefix query = %+v, want [external_id|nt-parent#]", repo.prefixCalls) + } + + // (2) every stale child deleted + if len(ks.deleted) != 2 || ks.deleted[0] != "stale-child-1" || ks.deleted[1] != "stale-child-2" { + t.Fatalf("deleted children = %+v, want [stale-child-1 stale-child-2]", ks.deleted) + } + + // (3) the create precedes all deletes (a failed parent write never sweeps) + wantOrder := []string{"create:parent.md", "delete:stale-child-1", "delete:stale-child-2"} + if len(ks.events) != len(wantOrder) { + t.Fatalf("events = %+v, want %+v", ks.events, wantOrder) + } + for i := range wantOrder { + if ks.events[i] != wantOrder[i] { + t.Fatalf("event[%d] = %q, want %q (full: %+v)", i, ks.events[i], wantOrder[i], ks.events) + } + } +} + +// TestIngestItem_ReplacesSubtreeSweepsOnDuplicateParent verifies that when the +// parent body is a content-dedup hit (CreateKnowledgeFromFile returns a +// DuplicateKnowledgeError), the subtree is still swept: the parent effectively +// exists, so children removed from the doc must not linger. Regression guard for +// the "sweep runs only after a *fresh* create" gap. +func TestIngestItem_ReplacesSubtreeSweepsOnDuplicateParent(t *testing.T) { + repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{{ID: "stale-child-1"}}} + // The dedup hit is THIS node's own row (same external_id) — a genuine + // self-dedup where the parent effectively exists, so the sweep must run. + ks := &sweepFakeKS{ + repo: repo, + createErr: types.NewDuplicateFileError(childWithExternalID("existing-parent", "nt-parent")), + } + s := &DataSourceService{knowledgeService: ks} + + ds := &types.DataSource{ID: "ds-1", Type: "feishu", TenantID: 7, KnowledgeBaseID: "kb-1"} + item := &types.FetchedItem{ + ExternalID: "nt-parent", + Content: []byte("# hello\n"), + FileName: "parent.md", + ReplacesSubtree: true, + } + + // ingestItem surfaces the dup error to the caller (applyFetchedItem counts it + // Skipped), but the sweep must still have run. + _, err := s.ingestItem(context.Background(), ds, item, nil) + var dupErr *types.DuplicateKnowledgeError + if !errors.As(err, &dupErr) { + t.Fatalf("want DuplicateKnowledgeError, got %v", err) + } + if len(ks.deleted) != 1 || ks.deleted[0] != "stale-child-1" { + t.Fatalf("dup parent must still sweep stale children, deleted = %+v", ks.deleted) + } +} + +// TestIngestItem_NoSweepWhenDuplicateIsDifferentNode guards the data-loss path: +// when an updated node's rebuilt body content-hash-collides with a DIFFERENT +// knowledge item (dedup keys on file_hash alone), the parent row under this +// node's external_id no longer exists (it was deleted for the update and never +// recreated), so the subtree must NOT be swept — deleting the children would +// destroy them with no parent to replace them. +func TestIngestItem_NoSweepWhenDuplicateIsDifferentNode(t *testing.T) { + repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{{ID: "would-be-orphaned-child"}}} + // The dedup hit is a DIFFERENT node's row (external_id "nt-other"). A manual + // upload with no external_id at all would behave identically (empty != ours). + ks := &sweepFakeKS{ + repo: repo, + createErr: types.NewDuplicateFileError(childWithExternalID("some-other-doc", "nt-other")), + } + s := &DataSourceService{knowledgeService: ks} + + ds := &types.DataSource{ID: "ds-1", Type: "feishu", TenantID: 7, KnowledgeBaseID: "kb-1"} + item := &types.FetchedItem{ + ExternalID: "nt-parent", + Content: []byte("# hello\n"), + FileName: "parent.md", + ReplacesSubtree: true, + } + + _, err := s.ingestItem(context.Background(), ds, item, nil) + var dupErr *types.DuplicateKnowledgeError + if !errors.As(err, &dupErr) { + t.Fatalf("want DuplicateKnowledgeError, got %v", err) + } + if len(ks.deleted) != 0 { + t.Fatalf("dup against a different node must NOT sweep this node's children, deleted = %+v", ks.deleted) + } +} + +// childWithExternalID builds a stale-child Knowledge row carrying the external_id +// metadata the sweep reads to decide whether the child is still present. +func childWithExternalID(id, externalID string) *types.Knowledge { + b, _ := json.Marshal(map[string]string{"external_id": externalID}) + return &types.Knowledge{ID: id, Metadata: types.JSON(b)} +} + +// TestIngestItem_SubtreeKeepPreservesPresentChild verifies the per-child sweep +// semantics: a child still present in the source (listed in SubtreeKeep) is +// preserved even though the parent carries ReplacesSubtree, while a child that +// vanished from the source is swept. This guards the data-loss fix where a +// still-present attachment that failed to re-ingest this cycle must keep its +// previously-synced good copy instead of being deleted with nothing to replace it. +func TestIngestItem_SubtreeKeepPreservesPresentChild(t *testing.T) { + repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{ + childWithExternalID("child-present", "nt-parent#file#present"), + childWithExternalID("child-gone", "nt-parent#file#gone"), + }} + ks := &sweepFakeKS{repo: repo} + s := &DataSourceService{knowledgeService: ks} + + ds := &types.DataSource{ID: "ds-1", Type: "feishu", TenantID: 7, KnowledgeBaseID: "kb-1"} + item := &types.FetchedItem{ + ExternalID: "nt-parent", + Content: []byte("# hello\n"), + FileName: "parent.md", + ReplacesSubtree: true, + // "present" is still in the doc (kept even if it couldn't re-ingest); + // "gone" was removed from the doc and must be swept. + SubtreeKeep: []string{"nt-parent#file#present"}, + } + + if _, err := s.ingestItem(context.Background(), ds, item, nil); err != nil { + t.Fatalf("ingestItem error: %v", err) + } + if len(ks.deleted) != 1 || ks.deleted[0] != "child-gone" { + t.Fatalf("only the removed child must be swept, deleted = %+v (want [child-gone])", ks.deleted) + } +} + +// TestIngestItem_NoSweepWhenFlagUnset verifies a normal item (ReplacesSubtree +// false) never triggers the subtree prefix query — the sweep is opt-in. +func TestIngestItem_NoSweepWhenFlagUnset(t *testing.T) { + repo := &sweepFakeRepo{} + ks := &sweepFakeKS{repo: repo} + s := &DataSourceService{knowledgeService: ks} + + ds := &types.DataSource{ID: "ds-1", Type: "feishu", TenantID: 7, KnowledgeBaseID: "kb-1"} + item := &types.FetchedItem{ + ExternalID: "nt-plain", + Content: []byte("data"), + FileName: "plain.md", + // ReplacesSubtree deliberately false + } + + if _, err := s.ingestItem(context.Background(), ds, item, nil); err != nil { + t.Fatalf("ingestItem error: %v", err) + } + if len(repo.prefixCalls) != 0 { + t.Fatalf("no subtree query expected when ReplacesSubtree is false, got %+v", repo.prefixCalls) + } + if len(ks.deleted) != 0 { + t.Fatalf("no deletes expected, got %+v", ks.deleted) + } +} + +// TestApplyFetchedItem_EmbeddedImageIngestFailureCountsAsSkip verifies that an +// embedded image extracted for OCR is best-effort: if the KB cannot ingest it +// (e.g. VLM/object-storage not configured for images), the failure is counted as +// Skipped, not Failed, so it never marks the whole document sync as failed. A +// non-image item with the same error must still count as Failed. +func TestApplyFetchedItem_EmbeddedImageIngestFailureCountsAsSkip(t *testing.T) { + ingestErr := errors.New("上传图片文件需要设置VLM模型") + ds := &types.DataSource{ID: "ds-1", Type: "feishu", TenantID: 7, KnowledgeBaseID: "kb-1"} + newItem := func(extID string, meta map[string]string) *types.FetchedItem { + return &types.FetchedItem{ + ExternalID: extID, + Title: "img", + Content: []byte("\x89PNG\r\n\x1a\nxxxx"), + ContentType: "image/png", + FileName: "image-x.png", + Metadata: meta, + } + } + + // Embedded image whose ingest fails → Skipped, not Failed. + ksImg := &sweepFakeKS{repo: &sweepFakeRepo{}, createErr: ingestErr} + sImg := &DataSourceService{knowledgeService: ksImg} + resImg := &types.SyncResult{} + sImg.applyFetchedItem(context.Background(), ds, + newItem("nt#image#x", map[string]string{"embedded_image": "true"}), nil, resImg) + if resImg.Skipped != 1 || resImg.Failed != 0 { + t.Fatalf("embedded image failure: Skipped=%d Failed=%d, want Skipped=1 Failed=0", + resImg.Skipped, resImg.Failed) + } + + // Control: a non-image item with the same error → Failed. + ksDoc := &sweepFakeKS{repo: &sweepFakeRepo{}, createErr: ingestErr} + sDoc := &DataSourceService{knowledgeService: ksDoc} + resDoc := &types.SyncResult{} + sDoc.applyFetchedItem(context.Background(), ds, newItem("nt-doc", nil), nil, resDoc) + if resDoc.Failed != 1 || resDoc.Skipped != 0 { + t.Fatalf("non-image failure: Failed=%d Skipped=%d, want Failed=1 Skipped=0", + resDoc.Failed, resDoc.Skipped) + } +} diff --git a/internal/datasource/connector/feishu/blocks.go b/internal/datasource/connector/feishu/blocks.go new file mode 100644 index 00000000..48cee78b --- /dev/null +++ b/internal/datasource/connector/feishu/blocks.go @@ -0,0 +1,429 @@ +package feishu + +import ( + "context" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// Feishu docx block_type integer enum (subset this connector handles). +// https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/docx-structure +const ( + blockTypePage = 1 + blockTypeText = 2 + blockTypeHeading1 = 3 + blockTypeHeading9 = 11 + blockTypeBullet = 12 + blockTypeOrdered = 13 + blockTypeCode = 14 + blockTypeQuote = 15 + blockTypeTodo = 17 + blockTypeBitable = 18 + blockTypeCallout = 19 + blockTypeDivider = 22 + blockTypeFile = 23 + blockTypeImage = 27 + blockTypeSheet = 30 + blockTypeTable = 31 + blockTypeTableCell = 32 +) + +// maxDocumentBlocks caps how many blocks a single document contributes, guarding +// against pathological/adversarial documents. Far above any real Feishu doc. +const maxDocumentBlocks = 50000 + +// textElement is one inline run inside a text-bearing block. +type textElement struct { + TextRun *struct { + Content string `json:"content"` + } `json:"text_run"` +} + +// blockText is the shared shape of text-bearing blocks (text, headingN, bullet…). +type blockText struct { + Elements []textElement `json:"elements"` +} + +// docxBlock is one node in the flat block array returned by the blocks API. +type docxBlock struct { + BlockID string `json:"block_id"` + ParentID string `json:"parent_id"` + BlockType int `json:"block_type"` + Children []string `json:"children"` + + Text *blockText `json:"text"` + Heading1 *blockText `json:"heading1"` + Heading2 *blockText `json:"heading2"` + Heading3 *blockText `json:"heading3"` + Heading4 *blockText `json:"heading4"` + Heading5 *blockText `json:"heading5"` + Heading6 *blockText `json:"heading6"` + Heading7 *blockText `json:"heading7"` + Heading8 *blockText `json:"heading8"` + Heading9 *blockText `json:"heading9"` + Bullet *blockText `json:"bullet"` + Ordered *blockText `json:"ordered"` + Code *blockText `json:"code"` + Quote *blockText `json:"quote"` + Todo *blockText `json:"todo"` + Callout *blockText `json:"callout"` + + Sheet *struct { + Token string `json:"token"` + } `json:"sheet"` + Bitable *struct { + Token string `json:"token"` + } `json:"bitable"` + File *struct { + Token string `json:"token"` + Name string `json:"name"` + } `json:"file"` + Image *struct { + Token string `json:"token"` + } `json:"image"` + + Table *struct { + Cells []string `json:"cells"` + Property *struct { + ColumnSize int `json:"column_size"` + } `json:"property"` + } `json:"table"` +} + +// docxBlocksResponse is the response for GET .../documents/:id/blocks. +type docxBlocksResponse struct { + apiResponse + Data struct { + Items []docxBlock `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + } `json:"data"` +} + +// ListDocumentBlocks returns every block of a docx document as a flat, +// pre-order array. Paginates at 500 blocks/page. documentID is the obj_token. +func (c *Client) ListDocumentBlocks(ctx context.Context, documentID string) ([]docxBlock, error) { + var all []docxBlock + pageToken := "" + for { + path := fmt.Sprintf("/open-apis/docx/v1/documents/%s/blocks?page_size=500&document_revision_id=-1", + url.PathEscape(documentID)) + if pageToken != "" { + path += "&page_token=" + url.QueryEscape(pageToken) + } + var resp docxBlocksResponse + if err := c.doRequest(ctx, http.MethodGet, path, nil, &resp); err != nil { + return nil, fmt.Errorf("list document blocks: %w", err) + } + if resp.Code != 0 { + return nil, fmt.Errorf("list document blocks error: code=%d msg=%s", resp.Code, resp.Msg) + } + all = append(all, resp.Data.Items...) + if len(resp.Data.Items) == 0 { + // Defensive: a malformed page (empty items but has_more=true and a + // non-empty page_token) would otherwise loop until the task deadline, + // burning API quota. There is nothing more to collect, so stop. + break + } + if len(all) >= maxDocumentBlocks { + logger.Warnf(ctx, "[Feishu] document %s exceeded %d blocks; truncating", documentID, maxDocumentBlocks) + break + } + if !resp.Data.HasMore || resp.Data.PageToken == "" { + break + } + pageToken = resp.Data.PageToken + } + return all, nil +} + +// maxTableRows caps how many rows of an embedded sheet/bitable are rendered, +// protecting chunking from pathologically large tables. Beyond this the table +// is truncated and the caller annotates the omission. +const maxTableRows = 500 + +// sheetValuesResponse is the response for sheets-v2 values read. +type sheetValuesResponse struct { + apiResponse + Data struct { + ValueRange struct { + Values [][]any `json:"values"` + } `json:"valueRange"` + } `json:"data"` +} + +// ReadSheetRange reads the cell values of an embedded spreadsheet block. +// embedToken is the block's sheet.token, formatted "spreadsheetToken_sheetId". +// Cells are stringified (display value) for RAG text retrieval. Rows are capped +// at maxTableRows; truncated is true when the source had more rows than that. +func (c *Client) ReadSheetRange(ctx context.Context, embedToken string) ([][]string, bool, error) { + idx := strings.LastIndex(embedToken, "_") + if idx < 0 { + return nil, false, fmt.Errorf("invalid sheet embed token: %q", embedToken) + } + spreadsheetToken, sheetID := embedToken[:idx], embedToken[idx+1:] + path := fmt.Sprintf("/open-apis/sheets/v2/spreadsheets/%s/values/%s?valueRenderOption=ToString", + url.PathEscape(spreadsheetToken), url.PathEscape(sheetID)) + var resp sheetValuesResponse + if err := c.doRequest(ctx, http.MethodGet, path, nil, &resp); err != nil { + return nil, false, fmt.Errorf("read sheet range: %w", err) + } + if resp.Code != 0 { + return nil, false, fmt.Errorf("read sheet range error: code=%d msg=%s", resp.Code, resp.Msg) + } + raw, truncated := capRows(resp.Data.ValueRange.Values) + return stringifyMatrix(raw), truncated, nil +} + +// capRows limits rows to maxTableRows, reporting whether truncation happened. It +// is generic so the sheet ([][]any) and bitable ([][]string) read paths share one +// truncation rule instead of each inlining their own. +func capRows[T any](rows []T) ([]T, bool) { + if len(rows) > maxTableRows { + return rows[:maxTableRows], true + } + return rows, false +} + +// stringifyMatrix renders arbitrary cell values to strings; nil → "". +func stringifyMatrix(in [][]any) [][]string { + out := make([][]string, len(in)) + for i, row := range in { + cells := make([]string, len(row)) + for j, v := range row { + cells[j] = cellToString(v) + } + out[i] = cells + } + return out +} + +// cellToString renders a single JSON cell value to a string; nil → "". +func cellToString(v any) string { + switch t := v.(type) { + case nil: + return "" + case string: + return t + case float64: + return strconv.FormatFloat(t, 'f', -1, 64) + case bool: + return strconv.FormatBool(t) + default: + return fmt.Sprintf("%v", t) + } +} + +// bitableFieldTypeDateTime is the Feishu bitable field type for a date/datetime +// column. Its cell value is a bare Unix-millisecond number, so without type-aware +// formatting it would render as a 13-digit integer instead of a readable date. +// https://open.feishu.cn/document/server-docs/docs/bitable-v1/app-table-field/guide +const bitableFieldTypeDateTime = 5 + +// bitableColumn describes one bitable field: its name, integer type, and (for a +// date column) its date_formatter, which distinguishes a date-only column +// ("yyyy/MM/dd") from a datetime one ("yyyy-MM-dd HH:mm"). +type bitableColumn struct { + name string + fieldType int + dateFormatter string +} + +// bitableFieldCell renders one bitable cell. Date columns carry a Unix-millisecond +// UTC instant; the calendar date a user sees is that instant in the table's +// timezone, so it is formatted in loc (rendering in UTC would shift the date, e.g. +// a GMT+8 "2024-04-01" would show as "2024-03-31 16:00:00"). A date-only formatter +// yields "2006-01-02"; a datetime formatter adds the "15:04" time. Every other +// type falls through to bitableCellToString. +func bitableFieldCell(v any, col bitableColumn, loc *time.Location) string { + if col.fieldType == bitableFieldTypeDateTime { + // Empty date cells arrive as nil (→ fall through to blank); ms==0 (epoch) is + // not a real Feishu date value either — render blank, not "1970-01-01" or "0". + if ms, ok := v.(float64); ok { + if ms == 0 { + return "" + } + t := time.UnixMilli(int64(ms)).In(loc) + if dateFormatterHasTime(col.dateFormatter) { + return t.Format("2006-01-02 15:04") + } + return t.Format("2006-01-02") + } + } + return bitableCellToString(v) +} + +// dateFormatterHasTime reports whether a Feishu date_formatter includes a time +// component. Feishu formatters are Java-style: 'H'/'h' hour, lowercase 'm' minute, +// uppercase 'M' month — so a time part is present iff the string carries an hour or +// a lowercase-'m' minute token (e.g. "yyyy-MM-dd HH:mm"). An empty formatter +// (Feishu's default "yyyy/MM/dd") is date-only. +func dateFormatterHasTime(f string) bool { + return strings.ContainsAny(f, "Hh") || strings.Contains(f, "m") +} + +// bitableCellToString renders a bitable field value — which may be text segments, +// a person/link object, or an attachment/multi-select array — to a readable +// string for RAG. Scalars delegate to cellToString. +func bitableCellToString(v any) string { + switch t := v.(type) { + case []any: + parts := make([]string, 0, len(t)) + for _, e := range t { + if s := bitableCellToString(e); s != "" { + parts = append(parts, s) + } + } + return strings.Join(parts, ", ") + case map[string]any: + for _, k := range []string{"text", "name", "en_name", "link"} { + if s, ok := t[k].(string); ok && s != "" { + return s + } + } + return "" + default: + return cellToString(v) + } +} + +type bitableFieldsResponse struct { + apiResponse + Data struct { + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + Items []struct { + FieldName string `json:"field_name"` + Type int `json:"type"` + Property *struct { + // DateFormatter distinguishes a date-only column from a datetime one. + DateFormatter string `json:"date_formatter"` + } `json:"property"` + } `json:"items"` + } `json:"data"` +} + +// maxBitableFieldPageSize is the documented per-page cap for the bitable +// list-fields endpoint (100). Unlike list-records (max 500), passing a larger +// page_size here is rejected, so fields must be fetched 100 at a time and paged. +const maxBitableFieldPageSize = 100 + +type bitableRecordsResponse struct { + apiResponse + Data struct { + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + Items []struct { + Fields map[string]any `json:"fields"` + } `json:"items"` + } `json:"data"` +} + +// ReadBitableRecords reads an embedded bitable block as a table: a header row of +// field names followed by one row per record. embedToken is the block's +// bitable.token, formatted "appToken_tableId". Record rows are capped at +// maxTableRows; truncated is true when the source had more records than that. +func (c *Client) ReadBitableRecords(ctx context.Context, embedToken string) ([][]string, bool, error) { + idx := strings.LastIndex(embedToken, "_") + if idx < 0 { + return nil, false, fmt.Errorf("invalid bitable embed token: %q", embedToken) + } + appToken, tableID := embedToken[:idx], embedToken[idx+1:] + + var cols []bitableColumn + baseFPath := fmt.Sprintf("/open-apis/bitable/v1/apps/%s/tables/%s/fields?page_size=%d", + url.PathEscape(appToken), url.PathEscape(tableID), maxBitableFieldPageSize) + fieldPageToken := "" + for { + fpath := baseFPath + if fieldPageToken != "" { + fpath += "&page_token=" + url.QueryEscape(fieldPageToken) + } + var fieldsResp bitableFieldsResponse + if err := c.doRequest(ctx, http.MethodGet, fpath, nil, &fieldsResp); err != nil { + return nil, false, fmt.Errorf("read bitable fields: %w", err) + } + if fieldsResp.Code != 0 { + return nil, false, fmt.Errorf("read bitable fields error: code=%d msg=%s", fieldsResp.Code, fieldsResp.Msg) + } + for _, f := range fieldsResp.Data.Items { + formatter := "" + if f.Property != nil { + formatter = f.Property.DateFormatter + } + cols = append(cols, bitableColumn{name: f.FieldName, fieldType: f.Type, dateFormatter: formatter}) + } + if len(fieldsResp.Data.Items) == 0 { + // Defensive: an empty page with has_more=true would loop forever (this + // loop has no size cap of its own). Nothing more to read, so stop. + break + } + if !fieldsResp.Data.HasMore || fieldsResp.Data.PageToken == "" { + break + } + fieldPageToken = fieldsResp.Data.PageToken + } + + header := make([]string, len(cols)) + for i, col := range cols { + header[i] = col.name + } + loc := c.tz() + + var dataRows [][]string + truncated := false + // Use the Search-records endpoint (POST .../records/search). The legacy + // GET .../records is officially deprecated ("已不推荐使用,可使用[查询记录]替代"). + // An empty body queries the table's default view, paginated via page_token + // (we page to the end below), so a default view with a filter would omit the + // filtered-out records — acceptable for RAG, but not literally "all records". + baseRPath := fmt.Sprintf("/open-apis/bitable/v1/apps/%s/tables/%s/records/search?page_size=500", + url.PathEscape(appToken), url.PathEscape(tableID)) + pageToken := "" + for { + rpath := baseRPath + if pageToken != "" { + rpath += "&page_token=" + url.QueryEscape(pageToken) + } + var rec bitableRecordsResponse + if err := c.doRequest(ctx, http.MethodPost, rpath, map[string]any{}, &rec); err != nil { + return nil, false, fmt.Errorf("search bitable records: %w", err) + } + if rec.Code != 0 { + return nil, false, fmt.Errorf("read bitable records error: code=%d msg=%s", rec.Code, rec.Msg) + } + for _, item := range rec.Data.Items { + row := make([]string, len(cols)) + for i, col := range cols { + row[i] = bitableFieldCell(item.Fields[col.name], col, loc) + } + dataRows = append(dataRows, row) + } + if len(rec.Data.Items) == 0 { + // Defensive: an empty page with has_more=true never advances dataRows, + // so the maxTableRows cap below would never trip — stop instead of + // looping until the task deadline. + break + } + if len(dataRows) >= maxTableRows { + if len(dataRows) > maxTableRows || rec.Data.HasMore { + truncated = true + } + break + } + if !rec.Data.HasMore || rec.Data.PageToken == "" { + break + } + pageToken = rec.Data.PageToken + } + dataRows, capped := capRows(dataRows) + truncated = truncated || capped + rows := append([][]string{header}, dataRows...) + return rows, truncated, nil +} diff --git a/internal/datasource/connector/feishu/blocks_test.go b/internal/datasource/connector/feishu/blocks_test.go new file mode 100644 index 00000000..d76e6f03 --- /dev/null +++ b/internal/datasource/connector/feishu/blocks_test.go @@ -0,0 +1,512 @@ +package feishu + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" +) + +func TestListDocumentBlocks_Paginates(t *testing.T) { + var gotTokens []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" { + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + return + } + gotTokens = append(gotTokens, r.URL.Query().Get("page_token")) + if r.URL.Query().Get("page_size") != "500" { + t.Errorf("page_size = %q, want 500", r.URL.Query().Get("page_size")) + } + if r.URL.Query().Get("page_token") == "" { + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "items": []map[string]any{{"block_id": "b1", "block_type": 2}, {"block_id": "b2", "block_type": 2}}, + "has_more": true, + "page_token": "p2", + }}) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "items": []map[string]any{{"block_id": "b3", "block_type": 2}}, + "has_more": false, + }}) + })) + defer srv.Close() + + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + blocks, err := c.ListDocumentBlocks(context.Background(), "doc123") + if err != nil { + t.Fatalf("ListDocumentBlocks: %v", err) + } + if len(blocks) != 3 { + t.Fatalf("got %d blocks, want 3", len(blocks)) + } + if blocks[0].BlockID != "b1" || blocks[2].BlockID != "b3" { + t.Errorf("order not preserved: %+v", blocks) + } + if len(gotTokens) != 2 || gotTokens[1] != "p2" { + t.Errorf("page tokens = %v, want ['', 'p2']", gotTokens) + } +} + +func TestReadSheetRange_SplitsTokenAndReadsValues(t *testing.T) { + var gotPath string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" { + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + return + } + gotPath = r.URL.Path + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "valueRange": map[string]any{"values": [][]any{{"名称", "数量"}, {"苹果", 3}, {"梨", nil}}}, + }}) + })) + defer srv.Close() + + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + rows, truncated, err := c.ReadSheetRange(context.Background(), "sht_abc_0") + if err != nil { + t.Fatalf("ReadSheetRange: %v", err) + } + if gotPath != "/open-apis/sheets/v2/spreadsheets/sht_abc/values/0" { + t.Errorf("path = %q", gotPath) + } + if truncated { + t.Errorf("did not expect truncation for 3 rows") + } + if len(rows) != 3 || rows[0][0] != "名称" || rows[1][1] != "3" || rows[2][1] != "" { + t.Errorf("rows = %+v", rows) + } +} + +func TestReadSheetRange_TruncatesLargeTable(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" { + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + return + } + values := make([][]any, 600) + for i := range values { + values[i] = []any{i} + } + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "valueRange": map[string]any{"values": values}, + }}) + })) + defer srv.Close() + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + rows, truncated, err := c.ReadSheetRange(context.Background(), "sht_x_0") + if err != nil { + t.Fatalf("err: %v", err) + } + if !truncated { + t.Errorf("expected truncated=true for 600 rows") + } + if len(rows) != 500 { + t.Errorf("rows capped to %d, want 500", len(rows)) + } +} + +func TestBitableCellToString(t *testing.T) { + // text-segment array: [{type:text, text:"你好"}] → "你好" + textSeg := []any{map[string]any{"type": "text", "text": "你好"}} + if got := bitableCellToString(textSeg); got != "你好" { + t.Errorf("text segment: got %q, want %q", got, "你好") + } + + // person array: [{id:u1, name:"张三"}] → "张三" + person := []any{map[string]any{"id": "u1", "name": "张三"}} + if got := bitableCellToString(person); got != "张三" { + t.Errorf("person: got %q, want %q", got, "张三") + } + + // plain number (float64) → "3" + if got := bitableCellToString(float64(3)); got != "3" { + t.Errorf("float64: got %q, want %q", got, "3") + } + + // plain string → passthrough + if got := bitableCellToString("abc"); got != "abc" { + t.Errorf("string: got %q, want %q", got, "abc") + } +} + +func TestBitableFieldCell_DateColumn(t *testing.T) { + gmt8 := resolveLocation("") // default GMT+8 + dateOnly := bitableColumn{fieldType: bitableFieldTypeDateTime, dateFormatter: "yyyy/MM/dd"} + dateTime := bitableColumn{fieldType: bitableFieldTypeDateTime, dateFormatter: "yyyy-MM-dd HH:mm"} + number := bitableColumn{fieldType: 2} + + // Feishu stores a date as a UTC instant at the table-timezone midnight. The + // official sample 1711900800000 is 2024-04-01 00:00:00 GMT+8 (== 2024-03-31 + // 16:00:00 UTC); a date-only column must render the GMT+8 calendar date, NOT + // the UTC-shifted "2024-03-31 16:00:00" the old code produced. + if got := bitableFieldCell(float64(1711900800000), dateOnly, gmt8); got != "2024-04-01" { + t.Errorf("date-only cell: got %q, want %q", got, "2024-04-01") + } + + // A datetime column keeps the time, rendered in the same timezone. + // 1719802800000 == 2024-07-01 03:00 UTC == 2024-07-01 11:00 GMT+8. + if got := bitableFieldCell(float64(1719802800000), dateTime, gmt8); got != "2024-07-01 11:00" { + t.Errorf("datetime cell: got %q, want %q", got, "2024-07-01 11:00") + } + + // A non-date numeric field is left as its plain value, not a date. + if got := bitableFieldCell(float64(42), number, gmt8); got != "42" { + t.Errorf("number cell: got %q, want %q", got, "42") + } + + // An empty date cell (nil, or epoch 0) renders blank, not "1970-01-01". + if got := bitableFieldCell(nil, dateOnly, gmt8); got != "" { + t.Errorf("empty date cell: got %q, want empty", got) + } + if got := bitableFieldCell(float64(0), dateOnly, gmt8); got != "" { + t.Errorf("epoch-0 date cell: got %q, want empty", got) + } +} + +func TestDateFormatterHasTime(t *testing.T) { + withTime := []string{"yyyy-MM-dd HH:mm", "HH:mm", "yyyy/MM/dd hh:mm", "MM-dd HH:mm"} + dateOnly := []string{"", "yyyy/MM/dd", "MM-dd", "MM/dd/yyyy", "dd/MM/yyyy"} + for _, f := range withTime { + if !dateFormatterHasTime(f) { + t.Errorf("dateFormatterHasTime(%q) = false, want true", f) + } + } + for _, f := range dateOnly { + if dateFormatterHasTime(f) { + t.Errorf("dateFormatterHasTime(%q) = true, want false", f) + } + } +} + +func TestResolveLocation(t *testing.T) { + // Empty and unknown names both fall back to a fixed GMT+8, with no dependency + // on system tzdata (minimal container images may omit it). + for _, name := range []string{"", "Not/AZone"} { + ref := time.Date(2024, 4, 1, 0, 0, 0, 0, resolveLocation(name)) + if _, off := ref.Zone(); off != defaultTimezoneOffsetSeconds { + t.Errorf("resolveLocation(%q) offset = %d, want %d", name, off, defaultTimezoneOffsetSeconds) + } + } +} + +// TestReadBitableRecords_DateColumnUsesFormatterAndTimezone proves the date fix +// end-to-end: property.date_formatter is parsed from the fields response, a type-5 +// column is detected, and the ms instant is rendered in the client timezone +// (GMT+8) — date-only vs datetime distinguished by the formatter. +func TestReadBitableRecords_DateColumnUsesFormatterAndTimezone(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + case strings.HasSuffix(r.URL.Path, "/fields"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "items": []map[string]any{ + {"field_name": "截止日期", "type": 5, "property": map[string]any{"date_formatter": "yyyy/MM/dd"}}, + {"field_name": "提醒时间", "type": 5, "property": map[string]any{"date_formatter": "yyyy-MM-dd HH:mm"}}, + }}}) + case strings.HasSuffix(r.URL.Path, "/records/search"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": false, "items": []map[string]any{ + {"fields": map[string]any{"截止日期": float64(1711900800000), "提醒时间": float64(1719802800000)}}, + }}}) + } + })) + defer srv.Close() + + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client(), location: resolveLocation("")} + rows, _, err := c.ReadBitableRecords(context.Background(), "bascabc_tblxyz") + if err != nil { + t.Fatalf("ReadBitableRecords: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %+v, want header + 1 record", rows) + } + if rows[1][0] != "2024-04-01" { + t.Errorf("date-only column = %q, want 2024-04-01 (GMT+8, not UTC-shifted)", rows[1][0]) + } + if rows[1][1] != "2024-07-01 11:00" { + t.Errorf("datetime column = %q, want 2024-07-01 11:00 (GMT+8)", rows[1][1]) + } +} + +func TestReadBitableRecords_SplitsTokenAndBuildsTable(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + case strings.HasSuffix(r.URL.Path, "/fields"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "items": []map[string]any{{"field_name": "任务"}, {"field_name": "状态"}}}}) + case strings.HasSuffix(r.URL.Path, "/records/search"): + // Must use the current Search-records endpoint (POST), not the + // deprecated GET .../records legacy interface. + if r.Method != http.MethodPost { + t.Errorf("records read method = %s, want POST (search endpoint)", r.Method) + } + if !strings.Contains(r.URL.Path, "/apps/bascabc/tables/tblxyz/") { + t.Errorf("bad path %q", r.URL.Path) + } + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": false, + "items": []map[string]any{ + {"fields": map[string]any{"任务": "写文档", "状态": "进行中"}}, + }}}) + } + })) + defer srv.Close() + + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + rows, truncated, err := c.ReadBitableRecords(context.Background(), "bascabc_tblxyz") + if err != nil { + t.Fatalf("ReadBitableRecords: %v", err) + } + if truncated { + t.Errorf("did not expect truncation") + } + if len(rows) != 2 || rows[0][0] != "任务" || rows[0][1] != "状态" || rows[1][0] != "写文档" || rows[1][1] != "进行中" { + t.Errorf("rows = %+v", rows) + } +} + +// TestReadBitableRecords_PaginatesFieldsAtMax100 guards the real-API constraint +// that the list-fields endpoint caps page_size at 100 (unlike list-records, which +// allows 500). The connector must request page_size=100 and page through fields, +// or a table with >100 columns would silently lose its header tail (or the whole +// bitable would degrade if Feishu rejects page_size=500). Verified against the +// official docs: bitable-v1/app-table-field/list "最大值:100". +func TestReadBitableRecords_PaginatesFieldsAtMax100(t *testing.T) { + const totalFields = 150 // spans two pages: 100 + 50 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + case strings.HasSuffix(r.URL.Path, "/fields"): + if ps := r.URL.Query().Get("page_size"); ps != "100" { + t.Errorf("fields page_size = %q, want 100 (endpoint max)", ps) + } + // Page 1 (no token): first 100 fields, has_more. Page 2 (token=f2): last 50. + var items []map[string]any + hasMore := false + nextTok := "" + if r.URL.Query().Get("page_token") == "" { + for i := 0; i < 100; i++ { + items = append(items, map[string]any{"field_name": fieldName(i)}) + } + hasMore, nextTok = true, "f2" + } else { + for i := 100; i < totalFields; i++ { + items = append(items, map[string]any{"field_name": fieldName(i)}) + } + } + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "items": items, "has_more": hasMore, "page_token": nextTok}}) + case strings.HasSuffix(r.URL.Path, "/records/search"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": false, "items": []map[string]any{}}}) + } + })) + defer srv.Close() + + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + rows, _, err := c.ReadBitableRecords(context.Background(), "bascabc_tblxyz") + if err != nil { + t.Fatalf("ReadBitableRecords: %v", err) + } + if len(rows) < 1 { + t.Fatal("expected at least a header row") + } + header := rows[0] + if len(header) != totalFields { + t.Fatalf("header has %d fields, want %d (fields pagination lost columns)", len(header), totalFields) + } + if header[0] != fieldName(0) || header[totalFields-1] != fieldName(totalFields-1) { + t.Errorf("header endpoints wrong: first=%q last=%q", header[0], header[totalFields-1]) + } +} + +func fieldName(i int) string { return "f" + strconv.Itoa(i) } + +// bitableRows builds n bitable record items each carrying a single "col" field. +func bitableRows(n int) []map[string]any { + items := make([]map[string]any, n) + for i := range items { + items[i] = map[string]any{"fields": map[string]any{"col": "v" + strconv.Itoa(i)}} + } + return items +} + +// TestReadBitableRecords_PaginatesAndTruncatesRecords exercises the record-side +// pagination advance and the >maxTableRows truncation — the boundary logic that +// no prior test reached (every other bitable test returns a single sub-cap page). +func TestReadBitableRecords_PaginatesAndTruncatesRecords(t *testing.T) { + var secondPageToken string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + case strings.HasSuffix(r.URL.Path, "/fields"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "items": []map[string]any{{"field_name": "col"}}}}) + case strings.HasSuffix(r.URL.Path, "/records/search"): + if tok := r.URL.Query().Get("page_token"); tok == "" { + // Page 1: 300 records, more to come. + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": true, "page_token": "r2", "items": bitableRows(300)}}) + } else { + secondPageToken = tok + // Page 2: 250 more → 550 total, capped to maxTableRows. + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": false, "items": bitableRows(250)}}) + } + } + })) + defer srv.Close() + + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + rows, truncated, err := c.ReadBitableRecords(context.Background(), "bascabc_tblxyz") + if err != nil { + t.Fatalf("ReadBitableRecords: %v", err) + } + if secondPageToken != "r2" { + t.Errorf("second records page must be fetched with page_token=r2, got %q", secondPageToken) + } + if len(rows) != maxTableRows+1 { // header + maxTableRows capped data rows + t.Errorf("rows = %d, want %d (header + %d capped)", len(rows), maxTableRows+1, maxTableRows) + } + if !truncated { + t.Error("a >maxTableRows bitable must report truncated=true") + } +} + +// TestReadBitableRecords_Exactly500NotTruncated guards the off-by-one at the cap: +// exactly maxTableRows records in a single page must NOT be flagged truncated. +func TestReadBitableRecords_Exactly500NotTruncated(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + case strings.HasSuffix(r.URL.Path, "/fields"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "items": []map[string]any{{"field_name": "col"}}}}) + case strings.HasSuffix(r.URL.Path, "/records/search"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": false, "items": bitableRows(maxTableRows)}}) + } + })) + defer srv.Close() + + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + rows, truncated, err := c.ReadBitableRecords(context.Background(), "bascabc_tblxyz") + if err != nil { + t.Fatalf("ReadBitableRecords: %v", err) + } + if truncated { + t.Error("exactly maxTableRows records must not be flagged truncated") + } + if len(rows) != maxTableRows+1 { + t.Errorf("rows = %d, want %d (header + %d)", len(rows), maxTableRows+1, maxTableRows) + } +} + +// TestReadBitableRecords_EmptyRecordPageTerminates guards the pagination +// zero-progress break: a malformed page (empty items but has_more=true and a +// non-empty page_token) must terminate instead of looping until the task +// deadline. A short context deadline is a safety net so a regression fails fast +// rather than hanging the suite. +func TestReadBitableRecords_EmptyRecordPageTerminates(t *testing.T) { + recordCalls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + case strings.HasSuffix(r.URL.Path, "/fields"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "items": []map[string]any{{"field_name": "col"}}}}) + case strings.HasSuffix(r.URL.Path, "/records/search"): + recordCalls++ + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": true, "page_token": "loop", "items": []map[string]any{}}}) + } + })) + defer srv.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + rows, _, err := c.ReadBitableRecords(ctx, "bascabc_tblxyz") + if err != nil { + t.Fatalf("empty-page pagination must terminate cleanly, got err: %v", err) + } + if recordCalls != 1 { + t.Errorf("records endpoint called %d times, want 1 (loop must break on the empty page)", recordCalls) + } + if len(rows) != 1 { // header only + t.Errorf("rows = %d, want 1 (header only, no records)", len(rows)) + } +} + +// TestReadBitableRecords_EmptyFieldsPageTerminates guards the fields loop, which +// has no size cap of its own — an empty page with has_more=true must still break. +func TestReadBitableRecords_EmptyFieldsPageTerminates(t *testing.T) { + fieldCalls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + case strings.HasSuffix(r.URL.Path, "/fields"): + fieldCalls++ + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": true, "page_token": "loop", "items": []map[string]any{}}}) + case strings.HasSuffix(r.URL.Path, "/records/search"): + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": false, "items": []map[string]any{}}}) + } + })) + defer srv.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + if _, _, err := c.ReadBitableRecords(ctx, "bascabc_tblxyz"); err != nil { + t.Fatalf("empty fields page must terminate cleanly, got err: %v", err) + } + if fieldCalls != 1 { + t.Errorf("fields endpoint called %d times, want 1 (loop must break on the empty page)", fieldCalls) + } +} + +// TestListDocumentBlocks_EmptyPageTerminates guards the blocks pagination loop. +func TestListDocumentBlocks_EmptyPageTerminates(t *testing.T) { + blockCalls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200}) + case strings.HasSuffix(r.URL.Path, "/blocks"): + blockCalls++ + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{ + "has_more": true, "page_token": "loop", "items": []map[string]any{}}}) + } + })) + defer srv.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()} + blocks, err := c.ListDocumentBlocks(ctx, "doc-1") + if err != nil { + t.Fatalf("empty blocks page must terminate cleanly, got err: %v", err) + } + if blockCalls != 1 { + t.Errorf("blocks endpoint called %d times, want 1 (loop must break on the empty page)", blockCalls) + } + if len(blocks) != 0 { + t.Errorf("blocks = %d, want 0", len(blocks)) + } +} diff --git a/internal/datasource/connector/feishu/client.go b/internal/datasource/connector/feishu/client.go index 262a888e..9c3da9bc 100644 --- a/internal/datasource/connector/feishu/client.go +++ b/internal/datasource/connector/feishu/client.go @@ -23,6 +23,9 @@ type Client struct { appID string appSecret string + // location renders bitable date cells in the table's timezone (default GMT+8). + location *time.Location + httpClient *http.Client // Token cache (thread-safe) @@ -51,12 +54,22 @@ func (e *partialWikiNodeListError) Error() string { return strings.Join(parts, "; ") } +// tz returns the client's date-rendering location, defaulting to GMT+8 when a +// Client was constructed without one (e.g. in tests that build Client directly). +func (c *Client) tz() *time.Location { + if c.location != nil { + return c.location + } + return time.FixedZone("GMT+8", defaultTimezoneOffsetSeconds) +} + // NewClient creates a new Feishu API client. func NewClient(config *Config) *Client { return &Client{ baseURL: config.GetBaseURL(), appID: config.AppID, appSecret: config.AppSecret, + location: resolveLocation(config.Timezone), httpClient: datasource.NewConnectorHTTPClient(30 * time.Second), } } @@ -126,6 +139,10 @@ const ( feishuRetry5xxDelay = 2 * time.Second ) +// maxFeishuDownloadBytes bounds a single file download to protect the sync +// worker from adversarial or pathological oversized responses. +const maxFeishuDownloadBytes = 512 * 1024 * 1024 // 512 MB + var feishuRetryBackoff = []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second} // doRequest executes an authenticated API request and decodes the JSON response, @@ -650,6 +667,15 @@ func (c *Client) DownloadDriveFile(ctx context.Context, fileToken string) ([]byt return c.downloadRawBytes(ctx, path) } +// DownloadMediaFile downloads embedded media (attachments/images referenced by +// document File/Image blocks) by its media token. Embedded block media live in a +// different token space than standalone Drive files and must use the /medias/ +// endpoint rather than /files/. +func (c *Client) DownloadMediaFile(ctx context.Context, fileToken string) ([]byte, error) { + path := fmt.Sprintf("/open-apis/drive/v1/medias/%s/download", url.PathEscape(fileToken)) + return c.downloadRawBytes(ctx, path) +} + // downloadRawBytes performs an authenticated GET and returns the raw response body. func (c *Client) downloadRawBytes(ctx context.Context, path string) ([]byte, error) { token, err := c.getTenantAccessToken(ctx) @@ -719,7 +745,11 @@ func (c *Client) downloadRawBytes(ctx context.Context, path string) ([]byte, err return nil, fmt.Errorf("download failed: status=%d body=%s", resp.StatusCode, string(body)) } - data, readErr := io.ReadAll(resp.Body) + data, readErr := io.ReadAll(io.LimitReader(resp.Body, maxFeishuDownloadBytes+1)) + if readErr == nil && int64(len(data)) > maxFeishuDownloadBytes { + resp.Body.Close() + return nil, fmt.Errorf("download exceeds max size (%d bytes): %s", maxFeishuDownloadBytes, path) + } resp.Body.Close() if readErr != nil { lastErr = fmt.Errorf("read download body: %w", readErr) diff --git a/internal/datasource/connector/feishu/connector.go b/internal/datasource/connector/feishu/connector.go index 1e0ad589..04dec5b5 100644 --- a/internal/datasource/connector/feishu/connector.go +++ b/internal/datasource/connector/feishu/connector.go @@ -5,6 +5,9 @@ import ( "encoding/json" "errors" "fmt" + "maps" + "net/http" + "path/filepath" "regexp" "strconv" "strings" @@ -238,7 +241,7 @@ func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig // summary line explains where every discovered node went. tally := newFetchTally(len(nodes)) for i, node := range nodes { - item, err := c.fetchNodeContent(ctx, client, node, spaceID, resourceID) + items, err := c.fetchNodeContent(ctx, client, node, spaceID, resourceID, config.MultimodalEnabled) if err != nil { tally.fail() // Log error but continue with other nodes @@ -250,9 +253,11 @@ func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig }) continue } - if item != nil { + if len(items) > 0 { tally.fetch() - allItems = append(allItems, *item) + for _, it := range items { + allItems = append(allItems, *it) + } } else { // Unsupported obj_type (mindnote/slides/…): skipped with no item. tally.skip(node.ObjType) @@ -346,7 +351,7 @@ func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSour } // Node is new or changed — fetch its content - item, err := c.fetchNodeContent(ctx, client, node, spaceID, resourceID) + fetchedItems, err := c.fetchNodeContent(ctx, client, node, spaceID, resourceID, config.MultimodalEnabled) if err != nil { // Record failed items changedItems = append(changedItems, types.FetchedItem{ @@ -357,8 +362,8 @@ func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSour }) continue } - if item != nil { - changedItems = append(changedItems, *item) + for _, it := range fetchedItems { + changedItems = append(changedItems, *it) } } @@ -481,7 +486,7 @@ func (c *Connector) FetchStream( continue } - item, ferr := c.fetchNodeContent(ctx, client, node, spaceID, resourceID) + items, ferr := c.fetchNodeContent(ctx, client, node, spaceID, resourceID, config.MultimodalEnabled) if ferr != nil { tally.fail() // Do NOT advance the cursor: the content was never fetched. @@ -503,10 +508,12 @@ func (c *Connector) FetchStream( // Fetched, or an unsupported obj_type (nothing to fetch): record // the current edit time so the node is not re-processed next run. newCursor.SpaceNodeTimes[resourceID][node.NodeToken] = editTimeStr - if item != nil { + if len(items) > 0 { tally.fetch() - if eerr := h.Emit(ctx, *item); eerr != nil { - return nil, eerr + for _, it := range items { + if eerr := h.Emit(ctx, *it); eerr != nil { + return nil, eerr + } } } else { // Unsupported obj_type (mindnote/slides/…): no item. @@ -654,15 +661,26 @@ func appendWikiNodeListFailureItems(items []types.FetchedItem, spaceID string, r return items } -// fetchNodeContent fetches the content of a single wiki node and converts it to FetchedItem. -// Dispatches to different retrieval strategies based on obj_type: -// - docx/doc → export API → .docx file -// - sheet → export API → .xlsx file -// - bitable → export API → .xlsx file +// parseableAttachmentExts are attachment extensions worth ingesting as their +// own knowledge entries; other files (icons, tiny decor) are skipped. +var parseableAttachmentExts = map[string]bool{ + ".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true, + ".ppt": true, ".pptx": true, ".txt": true, ".md": true, ".csv": true, +} + +// minAttachmentBytes filters out decorative micro-files. +const minAttachmentBytes = 2 * 1024 + +// fetchNodeContent fetches the content of a single wiki node and converts it to a +// slice of FetchedItems. For docx nodes it fans out into a main Markdown document +// plus optional attachment sub-items. Dispatches to different retrieval strategies +// based on obj_type: +// - docx → blocks API (Markdown) with export fallback; may return attachments +// - doc/sheet/bitable → export API → binary file // - file → drive download → original file (PDF/Word/image/etc.) // - mindnote → skip (no API) // - slides → skip (no API) -func (c *Connector) fetchNodeContent(ctx context.Context, client *Client, node wikiNode, spaceID string, resourceID string) (*types.FetchedItem, error) { +func (c *Connector) fetchNodeContent(ctx context.Context, client *Client, node wikiNode, spaceID string, resourceID string, multimodalEnabled bool) ([]*types.FetchedItem, error) { if !isSupportedDocType(node.ObjType) { return nil, nil } @@ -679,64 +697,302 @@ func (c *Connector) fetchNodeContent(ctx context.Context, client *Client, node w } switch node.ObjType { - case "docx", "doc", "sheet", "bitable": - // Export as a file via the async export API - data, fileName, err := client.ExportAndDownload(ctx, node.ObjToken, node.ObjType) + case "docx": + return c.fetchDocxWithBlocks(ctx, client, node, resourceID, editTime, baseMeta, multimodalEnabled) + case "doc", "sheet", "bitable": + item, err := c.fetchViaExport(ctx, client, node, resourceID, editTime, baseMeta) if err != nil { - return nil, fmt.Errorf("export %s (%s): %w", node.Title, node.ObjType, err) + return nil, err } - - // Ensure a reasonable file name with correct extension - ext := exportFileExtToSuffix[objTypeToExportFileExtension[node.ObjType]] - if fileName == "" { - fileName = sanitizeFileName(node.Title) + ext - } else if !strings.HasSuffix(strings.ToLower(fileName), ext) { - // Feishu often returns the doc title without extension — append it - fileName = sanitizeFileName(fileName) + ext - } - - return &types.FetchedItem{ - ExternalID: node.NodeToken, - Title: node.Title, - Content: data, - ContentType: "application/octet-stream", - FileName: fileName, - URL: c.region.wikiURL(node.NodeToken), - UpdatedAt: editTime, - SourceResourceID: resourceID, - Metadata: baseMeta, - }, nil - + return []*types.FetchedItem{item}, nil case "file": - // Download the original uploaded file from Drive - data, err := client.DownloadDriveFile(ctx, node.ObjToken) + item, err := c.fetchDriveFile(ctx, client, node, resourceID, editTime, baseMeta) if err != nil { - return nil, fmt.Errorf("download file %s (%s): %w", node.Title, node.ObjToken, err) + return nil, err } - - // Use the node title as file name; it usually preserves the original extension - fileName := node.Title - if fileName == "" { - fileName = node.ObjToken - } - - return &types.FetchedItem{ - ExternalID: node.NodeToken, - Title: node.Title, - Content: data, - ContentType: "application/octet-stream", - FileName: fileName, - URL: c.region.wikiURL(node.NodeToken), - UpdatedAt: editTime, - SourceResourceID: resourceID, - Metadata: baseMeta, - }, nil - + return []*types.FetchedItem{item}, nil default: return nil, nil } } +// fetchViaExport exports a doc/sheet/bitable node via the async export API and +// returns a single FetchedItem containing the exported binary. +func (c *Connector) fetchViaExport(ctx context.Context, client *Client, node wikiNode, resourceID string, editTime time.Time, baseMeta map[string]string) (*types.FetchedItem, error) { + // Export as a file via the async export API + data, fileName, err := client.ExportAndDownload(ctx, node.ObjToken, node.ObjType) + if err != nil { + return nil, fmt.Errorf("export %s (%s): %w", node.Title, node.ObjType, err) + } + + // Ensure a reasonable file name with correct extension + ext := exportFileExtToSuffix[objTypeToExportFileExtension[node.ObjType]] + if fileName == "" { + fileName = sanitizeFileName(node.Title) + ext + } else if !strings.HasSuffix(strings.ToLower(fileName), ext) { + // Feishu often returns the doc title without extension — append it + fileName = sanitizeFileName(fileName) + ext + } + + return &types.FetchedItem{ + ExternalID: node.NodeToken, + Title: node.Title, + Content: data, + ContentType: "application/octet-stream", + FileName: fileName, + URL: c.region.wikiURL(node.NodeToken), + UpdatedAt: editTime, + SourceResourceID: resourceID, + Metadata: baseMeta, + }, nil +} + +// fetchDriveFile downloads an original uploaded file from Drive and returns a +// single FetchedItem containing the raw bytes. +func (c *Connector) fetchDriveFile(ctx context.Context, client *Client, node wikiNode, resourceID string, editTime time.Time, baseMeta map[string]string) (*types.FetchedItem, error) { + // Download the original uploaded file from Drive + data, err := client.DownloadDriveFile(ctx, node.ObjToken) + if err != nil { + return nil, fmt.Errorf("download file %s (%s): %w", node.Title, node.ObjToken, err) + } + + // Use the node title as file name; it usually preserves the original extension + fileName := node.Title + if fileName == "" { + fileName = node.ObjToken + } + + return &types.FetchedItem{ + ExternalID: node.NodeToken, + Title: node.Title, + Content: data, + ContentType: "application/octet-stream", + FileName: fileName, + URL: c.region.wikiURL(node.NodeToken), + UpdatedAt: editTime, + SourceResourceID: resourceID, + Metadata: baseMeta, + }, nil +} + +// fetchDocxWithBlocks retrieves a docx node via the blocks API, converts it to +// Markdown, and returns a main item plus any parseable attachment sub-items. +// Falls back to the export API if the blocks API returns an error. +func (c *Connector) fetchDocxWithBlocks(ctx context.Context, client *Client, node wikiNode, + resourceID string, editTime time.Time, baseMeta map[string]string, multimodalEnabled bool) ([]*types.FetchedItem, error) { + + blocks, err := client.ListDocumentBlocks(ctx, node.ObjToken) + if err != nil { + logger.Warnf(ctx, "[Feishu] blocks API failed for %s (%s), falling back to export: %v", + node.Title, node.ObjToken, err) + item, ferr := c.fetchViaExport(ctx, client, node, resourceID, editTime, baseMeta) + if ferr != nil { + return nil, ferr + } + // Do NOT set ReplacesSubtree here. The export path cannot re-enumerate the + // doc's attachments, so it emits no sub-items. If the blocks API failed + // transiently (rate limit / 5xx), sweeping would delete the good attachment + // children from the prior blocks-path sync with nothing to replace them — + // silent data loss. Leaving stale children is the safe choice; they are + // reconciled on the next successful blocks-path sync. + return []*types.FetchedItem{item}, nil + } + + md, atts, err := blocksToMarkdown(ctx, client, blocks) + if err != nil { + return nil, fmt.Errorf("convert blocks %s: %w", node.Title, err) + } + + // A docx that renders to empty Markdown (a blank page, or only block types that + // produce no text) must NOT be emitted as a main item with empty Content plus a + // wiki URL: ingestItem would then take its URL branch and CreateKnowledgeFromURL + // against the login-gated Feishu page — a guaranteed failure that reports the + // node as Failed. Fall back to the export path, which always yields a valid (if + // minimal) .docx binary, preserving the invariant that a supported docx node + // ingests as content bytes. An empty render implies no File/Image blocks either + // (both write a placeholder into the Markdown), so no attachment/image sub-items + // are lost by skipping the downdrill here. + if len(strings.TrimSpace(string(md))) == 0 { + logger.Infof(ctx, "[Feishu] doc %s (%s): blocks rendered empty Markdown, falling back to export", + node.Title, node.ObjToken) + item, ferr := c.fetchViaExport(ctx, client, node, resourceID, editTime, baseMeta) + if ferr != nil { + return nil, ferr + } + return []*types.FetchedItem{item}, nil + } + + main := &types.FetchedItem{ + ExternalID: node.NodeToken, + Title: node.Title, + Content: md, + ContentType: "text/markdown", + FileName: sanitizeFileName(node.Title) + ".md", + URL: c.region.wikiURL(node.NodeToken), + UpdatedAt: editTime, + SourceResourceID: resourceID, + Metadata: baseMeta, + ReplacesSubtree: true, // sweep stale attachment sub-items on re-sync + } + items := []*types.FetchedItem{main} + + // keep collects the external_id of every attachment still present in the doc + // this sync — parseable or not, downloaded or not. The subtree sweep deletes + // only children NOT in this set, so an attachment that is still present but + // could not be re-ingested this cycle (unclassifiable filename, transient + // download failure) keeps its previously-synced good copy instead of being + // deleted with nothing to replace it. Only attachments genuinely removed from + // the doc fall out of keep and get swept — one bad attachment no longer + // freezes reconciliation of its siblings. + keep := make([]string, 0, len(atts)) + childMeta := func() map[string]string { + m := maps.Clone(baseMeta) + m["parent_node_token"] = node.NodeToken + m["attachment"] = "true" + return m + } + for _, a := range atts { + childID := types.SubtreeChildID(node.NodeToken, "file", a.FileToken) + keep = append(keep, childID) // present in the doc → never sweep as stale + ext := strings.ToLower(filepath.Ext(a.Name)) + if ext == "" { + // No filename extension to classify by: we can neither decide whether + // the file is parseable nor build a valid typed filename downstream, so + // it cannot be ingested as a standalone item this cycle. Log instead of + // dropping silently; its prior copy (if any) is preserved via keep. + logger.Warnf(ctx, "[Feishu] doc %s: skipping attachment with no usable filename (token=%s name=%q)", + node.ObjToken, a.FileToken, a.Name) + continue + } + if !parseableAttachmentExts[ext] { + continue // decorative/non-parseable → not a standalone knowledge item + } + data, derr := client.DownloadMediaFile(ctx, a.FileToken) + if derr != nil { + // Degrade gracefully: a single failed attachment (revoked token, + // permission gap, transient error) must NOT discard the already-built + // document body and its other attachments. Surface it as a per-item + // sync error (visible in the UI and counted, not just a server log); + // keep already preserves its prior copy so the sweep won't delete it. + logger.Warnf(ctx, "[Feishu] doc %s: attachment %q (token=%s) download failed: %v", + node.ObjToken, a.Name, a.FileToken, derr) + items = append(items, &types.FetchedItem{ + ExternalID: childID, + Title: a.Name, + SourceResourceID: resourceID, + Metadata: feishuErrorItemMeta(derr, childMeta()), + }) + continue + } + if len(data) < minAttachmentBytes { + // Below the decorative-micro-file floor. Log rather than drop silently + // (the sibling skip paths above also surface a note); its prior copy, if + // any, is preserved via keep. + logger.Infof(ctx, "[Feishu] doc %s: skipping tiny attachment %q (token=%s, %d bytes < %d)", + node.ObjToken, a.Name, a.FileToken, len(data), minAttachmentBytes) + continue + } + items = append(items, &types.FetchedItem{ + ExternalID: childID, + Title: a.Name, + Content: data, + ContentType: "application/octet-stream", + FileName: sanitizeFileName(a.Name), + URL: c.region.wikiURL(node.NodeToken), + UpdatedAt: editTime, + SourceResourceID: resourceID, + Metadata: childMeta(), + }) + } + + // Embedded images: the Markdown body only carries a token-free placeholder for + // each image, so image-borne text (screenshots/diagrams) would be unsearchable. + // Emit each image as a standalone sub-item whose bytes flow through WeKnora's + // VLM OCR+caption pipeline, recovering that text. The image's external_id is + // ALWAYS added to keep (so toggling VLM off later does not sweep previously + // OCR'd images), but the bytes are only downloaded and ingested when the KB has + // multimodal enabled — ingesting an image into a non-VLM KB is rejected, so + // doing so would turn every image into a failed sync item. + imgMeta := func() map[string]string { + m := maps.Clone(baseMeta) + m["parent_node_token"] = node.NodeToken + m["embedded_image"] = "true" + return m + } + for _, b := range blocks { + if b.BlockType != blockTypeImage || b.Image == nil || b.Image.Token == "" { + continue + } + childID := types.SubtreeChildID(node.NodeToken, "image", b.Image.Token) + keep = append(keep, childID) // present in the doc → never sweep as stale + if !multimodalEnabled { + continue // KB can't OCR images; the inline placeholder is all we keep + } + data, derr := client.DownloadMediaFile(ctx, b.Image.Token) + if derr != nil { + // A failed image download (revoked token, permission gap, transient + // error) is a genuine fetch failure, not the best-effort ingest + // rejection a non-VLM KB produces — surface it as a visible per-item + // sync error exactly like a failed attachment download, instead of + // dropping it to a server log only. keep already preserves any prior + // OCR'd copy so the sweep won't delete it. + logger.Warnf(ctx, "[Feishu] doc %s: image (token=%s) download failed: %v", + node.ObjToken, b.Image.Token, derr) + items = append(items, &types.FetchedItem{ + ExternalID: childID, + Title: fmt.Sprintf("%s(内嵌图片)", node.Title), + SourceResourceID: resourceID, + Metadata: feishuErrorItemMeta(derr, imgMeta()), + }) + continue + } + if len(data) < minAttachmentBytes { + continue // decorative micro-image (icon/spacer) + } + ext, contentType, ok := supportedImageExt(data) + if !ok { + logger.Warnf(ctx, "[Feishu] doc %s: skipping image (token=%s) of unsupported type %q", + node.ObjToken, b.Image.Token, contentType) + continue + } + items = append(items, &types.FetchedItem{ + ExternalID: childID, + Title: fmt.Sprintf("%s(内嵌图片)", node.Title), + Content: data, + ContentType: contentType, + FileName: "image-" + b.Image.Token + ext, + URL: c.region.wikiURL(node.NodeToken), + UpdatedAt: editTime, + SourceResourceID: resourceID, + Metadata: imgMeta(), + }) + } + + // Reconcile the subtree against the attachments still present in the doc: the + // sweep (in datasource_service) deletes only prior children absent from keep. + main.SubtreeKeep = keep + return items, nil +} + +// supportedImageExt sniffs image bytes and returns the filename extension and +// content type WeKnora accepts for a standalone image knowledge item (png/jpg/ +// gif — the image set isValidFileType admits). ok is false for non-image or +// unsupported formats (e.g. webp/bmp), which the caller skips rather than +// mislabel — a wrong extension would fail parsing. The detected content type is +// returned even when ok is false so the caller can log it without re-sniffing. +func supportedImageExt(data []byte) (ext, contentType string, ok bool) { + switch ct := http.DetectContentType(data); ct { + case "image/png": + return ".png", ct, true + case "image/jpeg": + return ".jpg", ct, true + case "image/gif": + return ".gif", ct, true + default: + return "", ct, false + } +} + // --- Helper functions --- func makeWikiNodeResourceID(spaceID, nodeToken string) string { @@ -810,6 +1066,14 @@ func parseFeishuConfig(config *types.DataSourceConfig, region Region) (*Config, feishuConfig.BaseURL = region.OpenBaseURL } + // Timezone is a display setting (bitable date rendering), not a credential, so + // it lives in Settings. Empty falls back to GMT+8 in resolveLocation. + if feishuConfig.Timezone == "" && config.Settings != nil { + if tz, ok := config.Settings["timezone"].(string); ok { + feishuConfig.Timezone = strings.TrimSpace(tz) + } + } + if err := datasource.ValidateConnectorBaseURL(feishuConfig.GetBaseURL()); err != nil { return nil, err } @@ -845,6 +1109,10 @@ func parseFeishuTimestamp(ts string) time.Time { // truncates at a UTF-8 rune boundary. Raw byte truncation would split a // multi-byte codepoint (Chinese chars are 3 bytes) and produce invalid UTF-8 // that downstream validation (utf8.ValidString) rejects. +// +// The extension is preserved across truncation: only the base name is trimmed, +// so a long attachment name like "很长的名字….pdf" keeps its ".pdf" suffix that +// downstream file-type classification depends on. func sanitizeFileName(name string) string { if name == "" { return "untitled" @@ -855,15 +1123,30 @@ func sanitizeFileName(name string) string { ) result := replacer.Replace(name) const maxBytes = 200 - if len(result) > maxBytes { - result = result[:maxBytes] - for len(result) > 0 { - r, size := utf8.DecodeLastRuneInString(result) - if r != utf8.RuneError || size != 1 { - break - } - result = result[:len(result)-1] - } + if len(result) <= maxBytes { + return result } - return result + ext := filepath.Ext(result) + if len(ext) >= maxBytes { + ext = "" // pathological: extension alone overflows the budget → drop it + } + base := truncateUTF8(result[:len(result)-len(ext)], maxBytes-len(ext)) + return base + ext +} + +// truncateUTF8 shortens s to at most maxBytes bytes without splitting a +// multi-byte rune: after a hard byte cut it trims any trailing partial codepoint. +func truncateUTF8(s string, maxBytes int) string { + if len(s) <= maxBytes { + return s + } + s = s[:maxBytes] + for len(s) > 0 { + r, size := utf8.DecodeLastRuneInString(s) + if r != utf8.RuneError || size != 1 { + break + } + s = s[:len(s)-1] + } + return s } diff --git a/internal/datasource/connector/feishu/connector_golden_test.go b/internal/datasource/connector/feishu/connector_golden_test.go new file mode 100644 index 00000000..f6717366 --- /dev/null +++ b/internal/datasource/connector/feishu/connector_golden_test.go @@ -0,0 +1,287 @@ +package feishu + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// ────────────────────────────────────────────────────────────────────── +// Golden end-to-end test: a single rich docx node exercising EVERY new +// capability at once, driven through the real Connector.FetchAll → real +// Client → Feishu-shaped fake endpoints (blocks / sheets-v2 / bitable-v1 / +// medias). This is the glue test the per-function unit tests can't be: +// it proves the whole pipeline produces correct, ordered Markdown plus the +// correctly filtered attachment sub-items. +// ────────────────────────────────────────────────────────────────────── + +// blk constructors kept local to this file to keep the fixture readable. +func sheetBlk(id, token string) docxBlock { + return docxBlock{BlockID: id, BlockType: blockTypeSheet, Sheet: &struct { + Token string `json:"token"` + }{Token: token}} +} +func bitableBlk(id, token string) docxBlock { + return docxBlock{BlockID: id, BlockType: blockTypeBitable, Bitable: &struct { + Token string `json:"token"` + }{Token: token}} +} +func imageBlk(id, token string) docxBlock { + return docxBlock{BlockID: id, BlockType: blockTypeImage, Image: &struct { + Token string `json:"token"` + }{Token: token}} +} +func fileBlk(id, token, name string) docxBlock { + return docxBlock{BlockID: id, BlockType: blockTypeFile, File: &struct { + Token string `json:"token"` + Name string `json:"name"` + }{Token: token, Name: name}} +} + +// cellBlk builds a table_cell container. A real Feishu table_cell holds no +// inline text of its own — its text lives in a child block, so the cell only +// references the child id (see cellTextBlk). +func cellBlk(id string) docxBlock { + return docxBlock{BlockID: id, BlockType: blockTypeTableCell, Children: []string{id + "_txt"}} +} + +// cellTextBlk builds the child text block a table cell points at. +func cellTextBlk(id, text string) docxBlock { + return docxBlock{BlockID: id + "_txt", BlockType: blockTypeText, Text: txt(text)} +} +func tableBlk(id string, cols int, cellIDs ...string) docxBlock { + b := docxBlock{BlockID: id, BlockType: blockTypeTable} + b.Table = &struct { + Cells []string `json:"cells"` + Property *struct { + ColumnSize int `json:"column_size"` + } `json:"property"` + }{Cells: cellIDs} + b.Table.Property = &struct { + ColumnSize int `json:"column_size"` + }{ColumnSize: cols} + return b +} + +// fakeFeishuGolden serves the full API surface a rich docx node needs. +func fakeFeishuGolden(nodes []wikiNode, docToken string, blocks []docxBlock, + mediaByToken map[string][]byte) (*httptest.Server, *Config) { + mux := http.NewServeMux() + + mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, tokenResponse{apiResponse: apiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200}) + }) + mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, wikiSpaceListResponse{apiResponse: apiResponse{Code: 0}, Data: struct { + Items []wikiSpace `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: []wikiSpace{{SpaceID: "space1", Name: "Test Space"}}}}) + }) + mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, wikiNodeListResponse{apiResponse: apiResponse{Code: 0}, Data: struct { + Items []wikiNode `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: nodes}}) + }) + + // docx blocks — paginated across two pages to exercise the paging glue. + mux.HandleFunc("/open-apis/docx/v1/documents/"+docToken+"/blocks", func(w http.ResponseWriter, r *http.Request) { + half := len(blocks) / 2 + page := blocks[:half] + hasMore := true + if r.URL.Query().Get("page_token") == "p2" { + page = blocks[half:] + hasMore = false + } + nextTok := "p2" + if !hasMore { + nextTok = "" + } + writeJSON(w, docxBlocksResponse{apiResponse: apiResponse{Code: 0}, Data: struct { + Items []docxBlock `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: page, HasMore: hasMore, PageToken: nextTok}}) + }) + + // sheets-v2 values: sht_spread_0 → spreadsheet "sht_spread", sheet "0". + // Raw JSON keeps the fake honest to the real wire shape without wrestling + // nested anonymous-struct literals. + mux.HandleFunc("/open-apis/sheets/v2/spreadsheets/sht_spread/values/0", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"code":0,"msg":"","data":{"valueRange":{"values":[["名称","数量"],["苹果",3]]}}}`)) + }) + + // bitable-v1 fields + records: bascApp_tblMain → app "bascApp", table "tblMain". + mux.HandleFunc("/open-apis/bitable/v1/apps/bascApp/tables/tblMain/fields", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"code":0,"msg":"","data":{"items":[{"field_name":"任务"},{"field_name":"状态"}]}}`)) + }) + mux.HandleFunc("/open-apis/bitable/v1/apps/bascApp/tables/tblMain/records/search", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"code":0,"msg":"","data":{"has_more":false,"page_token":"","items":[{"fields":{"任务":"写码","状态":"完成"}}]}}`)) + }) + + // medias download, routed by token embedded in the path. + mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/download") { + http.NotFound(w, r) + return + } + // path: /open-apis/drive/v1/medias//download + p := strings.TrimPrefix(r.URL.Path, "/open-apis/drive/v1/medias/") + tok := strings.TrimSuffix(p, "/download") + data, ok := mediaByToken[tok] + if !ok { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Write(data) + }) + + ts := httptest.NewServer(mux) + return ts, &Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL} +} + +func TestGolden_RichDocxAllCapabilities(t *testing.T) { + const docToken = "obj-golden" + bigPDF := bytes.Repeat([]byte("A"), minAttachmentBytes+512) // kept + tinyPDF := bytes.Repeat([]byte("B"), 100) // whitelisted but too small → dropped + + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + {BlockID: "h1", BlockType: blockTypeHeading1, Heading1: txt("季度报告")}, + {BlockID: "p1", BlockType: blockTypeText, Text: txt("本季度概览。")}, + {BlockID: "h2", BlockType: blockTypeHeading1 + 1, Heading2: txt("关键指标")}, + {BlockID: "b1", BlockType: blockTypeBullet, Bullet: txt("收入增长")}, + {BlockID: "o1", BlockType: blockTypeOrdered, Ordered: txt("第一步立项")}, + {BlockID: "code1", BlockType: blockTypeCode, Code: txt("SELECT 1")}, + {BlockID: "q1", BlockType: blockTypeQuote, Quote: txt("重要提示")}, + {BlockID: "todo1", BlockType: blockTypeTodo, Todo: txt("完成复盘")}, + {BlockID: "call1", BlockType: blockTypeCallout, Callout: txt("注意风险")}, + {BlockID: "div1", BlockType: blockTypeDivider}, + tableBlk("tbl1", 2, "c1", "c2", "c3", "c4"), + sheetBlk("sh1", "sht_spread_0"), + bitableBlk("bt1", "bascApp_tblMain"), + imageBlk("im1", "img-tok-SECRET"), + fileBlk("fbig", "tok-big", "手册.pdf"), + fileBlk("flogo", "tok-logo", "logo.png"), // non-whitelisted ext → no sub-item + fileBlk("fsmall", "tok-small", "small.pdf"), // whitelisted but too small → no sub-item + // table cells (containers) + their child text blocks — both are skipped by + // the main loop and read by the table renderer via the cells' Children. + cellBlk("c1"), cellBlk("c2"), cellBlk("c3"), cellBlk("c4"), + cellTextBlk("c1", "列A"), cellTextBlk("c2", "列B"), + cellTextBlk("c3", "1"), cellTextBlk("c4", "2"), + } + + nodes := []wikiNode{{ + NodeToken: "nt-golden", ObjToken: docToken, ObjType: "docx", + Title: "季度报告文档", NodeEditTime: "1711468800", + }} + media := map[string][]byte{"tok-big": bigPDF, "tok-small": tinyPDF} + + ts, cfg := fakeFeishuGolden(nodes, docToken, blocks, media) + defer ts.Close() + + c := NewConnector(RegionFeishu) + items, err := c.FetchAll(context.Background(), makeConfig(cfg, []string{"space1"}), []string{"space1"}) + if err != nil { + t.Fatalf("FetchAll error: %v", err) + } + + // ── main markdown item + exactly one attachment sub-item ── + if len(items) != 2 { + t.Fatalf("want 2 items (main + 1 kept attachment), got %d:\n%+v", len(items), items) + } + var main, att *types.FetchedItem + for i := range items { + if items[i].ExternalID == "nt-golden" { + main = &items[i] + } else { + att = &items[i] + } + } + if main == nil { + t.Fatal("main markdown item missing") + } + if main.ContentType != "text/markdown" { + t.Errorf("main ContentType = %q, want text/markdown", main.ContentType) + } + if !main.ReplacesSubtree { + t.Error("main item must set ReplacesSubtree for orphan sweeping") + } + if !strings.HasSuffix(main.FileName, ".md") { + t.Errorf("main FileName = %q, want .md", main.FileName) + } + md := string(main.Content) + + // ── every text construct rendered correctly ── + fragments := []string{ + "# 季度报告", + "本季度概览。", + "## 关键指标", + "- 收入增长", + "1. 第一步立项", + "```\nSELECT 1\n```", + "> 重要提示", + "- [ ] 完成复盘", + "> 注意风险", + "---", + "| 列A | 列B |", // native docx table header + "| 1 | 2 |", // native docx table row + "| 名称 | 数量 |", // embedded sheet header + "| 苹果 | 3 |", // embedded sheet row + "| 任务 | 状态 |", // embedded bitable header + "| 写码 | 完成 |", // embedded bitable row + "![图片]()", // token-free image placeholder + "📎 附件:手册.pdf", + "📎 附件:logo.png", + "📎 附件:small.pdf", + } + for _, f := range fragments { + if !strings.Contains(md, f) { + t.Errorf("markdown missing fragment %q\n--- full markdown ---\n%s", f, md) + } + } + + // ── document order preserved (heading before table before attachments) ── + order := []string{"# 季度报告", "## 关键指标", "| 列A | 列B |", "| 名称 | 数量 |", "| 任务 | 状态 |", "📎 附件:手册.pdf"} + last := -1 + for _, f := range order { + idx := strings.Index(md, f) + if idx <= last { + t.Errorf("fragment %q out of order (idx=%d, prev=%d)\n%s", f, idx, last, md) + } + last = idx + } + + // ── the internal image media token must NEVER leak into embeddings ── + if strings.Contains(md, "img-tok-SECRET") { + t.Errorf("internal image token leaked into markdown:\n%s", md) + } + + // ── attachment filtering: only the big whitelisted PDF becomes a sub-item ── + if att == nil { + t.Fatal("kept attachment sub-item missing") + } + if att.ExternalID != "nt-golden#file#tok-big" { + t.Errorf("attachment ExternalID = %q, want nt-golden#file#tok-big", att.ExternalID) + } + if att.Title != "手册.pdf" { + t.Errorf("attachment Title = %q", att.Title) + } + if !bytes.Equal(att.Content, bigPDF) { + t.Errorf("attachment content mismatch: got %d bytes want %d", len(att.Content), len(bigPDF)) + } + if att.Metadata["attachment"] != "true" || att.Metadata["parent_node_token"] != "nt-golden" { + t.Errorf("attachment metadata wrong: %+v", att.Metadata) + } +} diff --git a/internal/datasource/connector/feishu/connector_realapi_test.go b/internal/datasource/connector/feishu/connector_realapi_test.go index 944139d0..1bbae552 100644 --- a/internal/datasource/connector/feishu/connector_realapi_test.go +++ b/internal/datasource/connector/feishu/connector_realapi_test.go @@ -22,6 +22,7 @@ import ( "context" "encoding/json" "os" + "strings" "testing" "github.com/Tencent/WeKnora/internal/types" @@ -145,9 +146,18 @@ func TestRealAPI_FetchStreamResumeConverges(t *testing.T) { if n == 0 { t.Fatalf("pass 1 ingested 0 documents — create a few docs in the space, or check app scopes (wiki/docx/drive read)") } - // Every ingested node must be recorded in the cursor. + // Every ingested *node* must be recorded in the cursor. A multi-item node (a + // docx that fans out into a main document plus attachment/image sub-items) + // also ingests child items whose external_id is "#file#..." or + // "#image#...". Those are not wiki nodes: they ride their parent node's + // edit-time and intentionally carry no independent cursor entry (the parent's + // edit-time gates re-fetch of the whole subtree). Only node-level ids are + // required to be present. nt1 := nodeTimes(t, cur1)[spaceID] for _, id := range h1.ingested { + if strings.Contains(id, "#") { + continue // attachment/image sub-item, not a top-level cursor node + } if _, ok := nt1[id]; !ok { t.Errorf("pass 1 cursor missing edit time for ingested node %s", id) } diff --git a/internal/datasource/connector/feishu/connector_stream_test.go b/internal/datasource/connector/feishu/connector_stream_test.go index f786933c..5dcf8208 100644 --- a/internal/datasource/connector/feishu/connector_stream_test.go +++ b/internal/datasource/connector/feishu/connector_stream_test.go @@ -1,11 +1,13 @@ package feishu import ( + "bytes" "context" "encoding/json" "errors" "net/http" "net/http/httptest" + "strings" "testing" "github.com/Tencent/WeKnora/internal/types" @@ -253,7 +255,7 @@ func TestFetchStream_CheckpointsOnElapsedTime(t *testing.T) { prevN := feishuStreamCheckpointInterval prevT := feishuStreamCheckpointMaxInterval feishuStreamCheckpointInterval = 1 << 30 // never fires by count - feishuStreamCheckpointMaxInterval = 0 // fires by elapsed time every node + feishuStreamCheckpointMaxInterval = 0 // fires by elapsed time every node defer func() { feishuStreamCheckpointInterval = prevN feishuStreamCheckpointMaxInterval = prevT @@ -298,3 +300,220 @@ func TestFetchStream_EmitErrorAborts(t *testing.T) { t.Errorf("emitted %d items, want 0 (aborted on first emit)", len(h.emitted)) } } + +// ────────────────────────────────────────────────────────────────────── +// Stream integration: docx blocks fan-out (multi-item) through FetchStream +// ────────────────────────────────────────────────────────────────────── + +// TestFetchStream_DocxMultiItem is a stream-level integration test proving that a +// docx node fans out to a main Markdown item + an attachment item through the real +// FetchStream → fetchNodeContent → fetchDocxWithBlocks path. The fake server +// serves the blocks API (one text block + one file block) and the drive download; +// no export endpoint is registered, so any accidental fall-through to the export +// path would 404 and surface as a fetch error. +func TestFetchStream_DocxMultiItem(t *testing.T) { + const ( + nodeToken = "nt-blocks" + objToken = "obj-blocks" + attToken = "ft-stream-att" + attName = "slides.pdf" + ) + // Attachment content must exceed minAttachmentBytes (2 KiB). + attContent := bytes.Repeat([]byte("a"), minAttachmentBytes+1) + + nodes := []wikiNode{{ + NodeToken: nodeToken, + ObjToken: objToken, + ObjType: "docx", + Title: "Stream Blocks Doc", + ObjEditTime: "500", + }} + ts, cfg := fakeFeishuWithBlocks(nodes, objToken, attToken, attName, attContent) + defer ts.Close() + + c := NewConnector(RegionFeishu) + h := &recordingHandler{} + _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h) + if err != nil { + t.Fatalf("FetchStream() error: %v", err) + } + + if len(h.emitted) != 2 { + t.Fatalf("expected 2 emitted items (main doc + attachment), got %d: %+v", len(h.emitted), h.emitted) + } + + main := h.emitted[0] + if main.ExternalID != nodeToken { + t.Errorf("items[0].ExternalID = %q, want %q", main.ExternalID, nodeToken) + } + if main.ContentType != "text/markdown" { + t.Errorf("items[0].ContentType = %q, want text/markdown", main.ContentType) + } + if !main.ReplacesSubtree { + t.Errorf("items[0].ReplacesSubtree = false, want true") + } + + att := h.emitted[1] + wantAttID := nodeToken + "#file#" + attToken + if att.ExternalID != wantAttID { + t.Errorf("items[1].ExternalID = %q, want %q", att.ExternalID, wantAttID) + } + if att.Metadata["attachment"] != "true" { + t.Errorf("items[1].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"]) + } +} + +// fakeFeishuWithBlocksFallback returns a server where the blocks API returns HTTP 500 +// (simulating a permission/scope error) and the export task path returns success. +// This wires the fallback path: fetchDocxWithBlocks → blocks error → fetchViaExport. +func fakeFeishuWithBlocksFallback(nodes []wikiNode, docToken string) (*httptest.Server, *Config) { + mux := http.NewServeMux() + + mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, tokenResponse{ + apiResponse: apiResponse{Code: 0}, + TenantAccessToken: "fake-token", + Expire: 7200, + }) + }) + mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, wikiSpaceListResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []wikiSpace `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: []wikiSpace{{SpaceID: "space1", Name: "Test Space"}}}, + }) + }) + mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, wikiNodeListResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []wikiNode `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: nodes}, + }) + }) + + // Blocks API — always returns HTTP 500 (missing scope / permission denied). + blocksPath := "/open-apis/docx/v1/documents/" + docToken + "/blocks" + mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"code":99991400,"msg":"insufficient scope"}`)) + }) + + // Export task creation → returns ticket. + mux.HandleFunc("/open-apis/drive/v1/export_tasks", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + writeJSON(w, exportTaskCreateResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Ticket string `json:"ticket"` + }{Ticket: "ticket-fb"}, + }) + return + } + http.NotFound(w, r) + }) + // Export task status polling. + mux.HandleFunc("/open-apis/drive/v1/export_tasks/ticket-fb", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, exportTaskStatusResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Result struct { + FileToken string `json:"file_token"` + FileSize int64 `json:"file_size"` + JobStatus int `json:"job_status"` + JobErrorMsg string `json:"job_error_msg"` + FileName string `json:"file_name"` + } `json:"result"` + }{ + Result: struct { + FileToken string `json:"file_token"` + FileSize int64 `json:"file_size"` + JobStatus int `json:"job_status"` + JobErrorMsg string `json:"job_error_msg"` + FileName string `json:"file_name"` + }{ + FileToken: "ft-export-fallback", + FileSize: 512, + JobStatus: 0, // done + FileName: "fallback.docx", + }, + }, + }) + }) + // Export file download. + mux.HandleFunc("/open-apis/drive/v1/export_tasks/file/ft-export-fallback/download", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/octet-stream") + _, _ = w.Write([]byte("fake-exported-fallback-binary")) + }) + // Drive file download endpoint (not expected to be called in the fallback path, + // but registered to avoid 404 panic if the mux catches a stray request). + mux.HandleFunc("/open-apis/drive/v1/files/", func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/download") { + w.Header().Set("Content-Type", "application/octet-stream") + _, _ = w.Write([]byte("should-not-be-called")) + return + } + http.NotFound(w, r) + }) + + ts := httptest.NewServer(mux) + return ts, &Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL} +} + +// TestFetchStream_DocxBlocksFallback proves that when the blocks API returns HTTP 500 +// (e.g. missing docx:document:readonly scope), the connector automatically falls back +// to the export-API path and emits exactly one item with ContentType +// "application/octet-stream", not "text/markdown". No hard failure occurs — +// the sync completes successfully with the exported binary. +func TestFetchStream_DocxBlocksFallback(t *testing.T) { + const ( + nodeToken = "nt-fallback" + objToken = "obj-fallback" + ) + nodes := []wikiNode{{ + NodeToken: nodeToken, + ObjToken: objToken, + ObjType: "docx", + Title: "Fallback Doc", + ObjEditTime: "600", + }} + ts, cfg := fakeFeishuWithBlocksFallback(nodes, objToken) + defer ts.Close() + + c := NewConnector(RegionFeishu) + h := &recordingHandler{} + _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), nil, h) + if err != nil { + t.Fatalf("FetchStream() error: %v", err) + } + + // The fallback path must emit exactly one item (exported binary, not multi-item). + 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 != nodeToken { + t.Errorf("item.ExternalID = %q, want %q", item.ExternalID, nodeToken) + } + if item.ContentType == "text/markdown" { + t.Errorf("item.ContentType = %q; want application/octet-stream (export fallback, not blocks path)", item.ContentType) + } + if item.ContentType != "application/octet-stream" { + t.Errorf("item.ContentType = %q, want application/octet-stream", item.ContentType) + } + if item.Metadata["error"] != "" { + t.Errorf("fallback item should have no error metadata, got %q", item.Metadata["error"]) + } + // The export fallback cannot re-enumerate the doc's attachments, so it must + // NOT set ReplacesSubtree — otherwise a transient blocks-API failure would + // sweep and permanently delete the good attachment children from the prior + // blocks-path sync with nothing to replace them. + if item.ReplacesSubtree { + t.Error("export-fallback item must not set ReplacesSubtree (would delete good prior attachments on a transient failure)") + } +} diff --git a/internal/datasource/connector/feishu/connector_test.go b/internal/datasource/connector/feishu/connector_test.go index 84d46684..e7e67254 100644 --- a/internal/datasource/connector/feishu/connector_test.go +++ b/internal/datasource/connector/feishu/connector_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "os" + "slices" "strings" "testing" "time" @@ -361,6 +362,23 @@ func TestSanitizeFileName_TruncatesAtRuneBoundary(t *testing.T) { } } +func TestSanitizeFileName_PreservesExtensionOnTruncation(t *testing.T) { + // A pathologically long (>200-byte) CJK attachment name ending in ".pdf". + // Truncation must keep the ".pdf" suffix — downstream file-type validation + // classifies by extension, so a chopped extension would reject the file. + long := strings.Repeat("报告", 150) + ".pdf" // 150*6 bytes + ".pdf" + got := sanitizeFileName(long) + if !utf8.ValidString(got) { + t.Fatalf("produced invalid UTF-8: %q", got) + } + if len(got) > 200 { + t.Errorf("len = %d, want ≤ 200", len(got)) + } + if !strings.HasSuffix(got, ".pdf") { + t.Errorf("extension dropped by truncation: %q must end in .pdf", got) + } +} + func TestParseFeishuTimestamp(t *testing.T) { ts := parseFeishuTimestamp("1711468800") // 2024-03-27 00:00:00 UTC if ts.IsZero() { @@ -1247,6 +1265,592 @@ func TestExportFileExtToSuffix(t *testing.T) { } } +// ────────────────────────────────────────────────────────────────────── +// docx blocks path: multi-item fan-out + attachment sub-items +// ────────────────────────────────────────────────────────────────────── + +// fakeFeishuWithBlocks returns a test server that serves the auth/spaces/nodes +// endpoints plus: +// - a blocks endpoint for the given docx document (one text block + one file +// block whose attachment token is attToken and name is attName) +// - a drive file download for attToken returning attContent +// +// The export endpoint is intentionally absent; any call to it returns 404 so the +// test verifies the blocks-API path, not the export-fallback path. +func fakeFeishuWithBlocks(nodes []wikiNode, docToken, attToken, attName string, attContent []byte) (*httptest.Server, *Config) { + mux := http.NewServeMux() + + mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, tokenResponse{ + apiResponse: apiResponse{Code: 0}, + TenantAccessToken: "fake-token", + Expire: 7200, + }) + }) + mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, wikiSpaceListResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []wikiSpace `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: []wikiSpace{{SpaceID: "space1", Name: "Test Space"}}}, + }) + }) + mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, wikiNodeListResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []wikiNode `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: nodes}, + }) + }) + + // blocks API for the given docx document + blocksPath := "/open-apis/docx/v1/documents/" + docToken + "/blocks" + mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, docxBlocksResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []docxBlock `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{ + Items: []docxBlock{ + {BlockID: "b1", BlockType: blockTypePage}, + {BlockID: "b2", BlockType: blockTypeText, Text: &blockText{ + Elements: []textElement{{TextRun: &struct { + Content string `json:"content"` + }{Content: "Hello blocks"}}}, + }}, + {BlockID: "b3", BlockType: blockTypeFile, File: &struct { + Token string `json:"token"` + Name string `json:"name"` + }{Token: attToken, Name: attName}}, + }, + }, + }) + }) + + // media download for embedded attachment tokens (File/Image blocks use /medias/ endpoint) + 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(attContent) + return + } + http.NotFound(w, r) + }) + + ts := httptest.NewServer(mux) + return ts, &Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL} +} + +// TestFetchDocxWithBlocks_MultiItem verifies that a docx node returns a main +// Markdown item plus an attachment sub-item when the blocks API succeeds. +func TestFetchDocxWithBlocks_MultiItem(t *testing.T) { + const ( + nodeToken = "nt-docx" + objToken = "obj-docx" + attToken = "ft-att-1" + attName = "report.pdf" + ) + // Attachment content must exceed minAttachmentBytes (2 KiB) to not be filtered. + attContent := bytes.Repeat([]byte("x"), minAttachmentBytes+1) + + nodes := []wikiNode{{ + NodeToken: nodeToken, + ObjToken: objToken, + ObjType: "docx", + Title: "My Blocks Doc", + NodeEditTime: "1711468800", + }} + ts, cfg := fakeFeishuWithBlocks(nodes, objToken, attToken, attName, attContent) + defer ts.Close() + + conn := NewConnector(RegionFeishu) + items, err := conn.FetchAll(context.Background(), makeConfig(cfg, []string{"space1"}), []string{"space1"}) + if err != nil { + t.Fatalf("FetchAll() error: %v", err) + } + + if len(items) != 2 { + t.Fatalf("want 2 items (main doc + attachment), got %d: %+v", len(items), items) + } + + main := items[0] + if main.ExternalID != nodeToken { + t.Errorf("items[0].ExternalID = %q, want %q", main.ExternalID, nodeToken) + } + if main.ContentType != "text/markdown" { + t.Errorf("items[0].ContentType = %q, want text/markdown", main.ContentType) + } + if !main.ReplacesSubtree { + t.Errorf("items[0].ReplacesSubtree = false, want true") + } + if !strings.Contains(string(main.Content), "Hello blocks") { + t.Errorf("items[0].Content missing expected text; got %q", string(main.Content)) + } + + att := items[1] + wantAttID := nodeToken + "#file#" + attToken + if att.ExternalID != wantAttID { + t.Errorf("items[1].ExternalID = %q, want %q", att.ExternalID, wantAttID) + } + if att.Metadata["attachment"] != "true" { + t.Errorf("items[1].Metadata[attachment] = %q, want true", att.Metadata["attachment"]) + } + if att.Title != attName { + t.Errorf("items[1].Title = %q, want %q", att.Title, attName) + } +} + +// fakeFeishuWithBlocksAndDownloadStatus is like fakeFeishuWithBlocks but the +// drive download endpoint returns the given HTTP status code instead of 200. Use +// downloadStatus = http.StatusInternalServerError to exercise the +// attachment-download-failure path. +func fakeFeishuWithBlocksAndDownloadStatus(nodes []wikiNode, docToken, attToken, attName string, downloadStatus int) (*httptest.Server, *Config) { + mux := http.NewServeMux() + + mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, tokenResponse{ + apiResponse: apiResponse{Code: 0}, + TenantAccessToken: "fake-token", + Expire: 7200, + }) + }) + mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, wikiSpaceListResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []wikiSpace `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: []wikiSpace{{SpaceID: "space1", Name: "Test Space"}}}, + }) + }) + mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, wikiNodeListResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []wikiNode `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{Items: nodes}, + }) + }) + + // blocks API — one text block + one parseable .pdf file block + blocksPath := "/open-apis/docx/v1/documents/" + docToken + "/blocks" + mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, docxBlocksResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []docxBlock `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{ + Items: []docxBlock{ + {BlockID: "b1", BlockType: blockTypePage}, + {BlockID: "b2", BlockType: blockTypeText, Text: &blockText{ + Elements: []textElement{{TextRun: &struct { + Content string `json:"content"` + }{Content: "Hello"}}}, + }}, + {BlockID: "b3", BlockType: blockTypeFile, File: &struct { + Token string `json:"token"` + Name string `json:"name"` + }{Token: attToken, Name: attName}}, + }, + }, + }) + }) + + // media download endpoint returns the requested status (e.g. 500) + mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/download") { + w.WriteHeader(downloadStatus) + _, _ = w.Write([]byte(`{"code":99,"msg":"server error"}`)) + return + } + http.NotFound(w, r) + }) + + ts := httptest.NewServer(mux) + return ts, &Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL} +} + +// TestFetchDocxWithBlocks_AttachmentDownloadFailure verifies that when the blocks +// API succeeds but a single attachment download fails, the document body is still +// ingested (no error, so the node is not pinned into permanent retry), the failure +// is surfaced as a visible per-item error item (not just a server log), and the +// subtree sweep is suppressed so a transient failure never deletes the good prior +// copy of the attachment. One bad attachment must not block the whole document. +func TestFetchDocxWithBlocks_AttachmentDownloadFailure(t *testing.T) { + const ( + nodeToken = "nt-docx-fail" + objToken = "obj-docx-fail" + attToken = "ft-att-bad" + attName = "slides.pdf" + ) + nodes := []wikiNode{{ + NodeToken: nodeToken, + ObjToken: objToken, + ObjType: "docx", + Title: "Doc With Bad Attachment", + NodeEditTime: "1711468800", + }} + ts, cfg := fakeFeishuWithBlocksAndDownloadStatus(nodes, objToken, attToken, attName, http.StatusInternalServerError) + defer ts.Close() + + conn := NewConnector(RegionFeishu) + ctx := context.Background() + client := NewClient(cfg) + + baseMeta := map[string]string{ + "obj_token": objToken, + "obj_type": "docx", + "node_token": nodeToken, + "space_id": "space1", + "channel": types.ChannelFeishu, + } + items, err := conn.fetchDocxWithBlocks(ctx, client, nodes[0], "space1:nt-docx-fail", parseFeishuTimestamp("1711468800"), baseMeta, true) + if err != nil { + t.Fatalf("a failed attachment must not fail the whole node, got error: %v", err) + } + // Main Markdown item + a visible error sub-item for the failed attachment. + if len(items) != 2 { + t.Fatalf("want 2 items (main doc + attachment error item), got %d: %+v", len(items), items) + } + var main, errItem *types.FetchedItem + for _, it := range items { + if it.ExternalID == nodeToken { + main = it + } else { + errItem = it + } + } + if main == nil { + t.Fatal("main doc item missing") + } + if main.ContentType != "text/markdown" { + t.Errorf("main ContentType = %q, want text/markdown", main.ContentType) + } + // The subtree is still reconciled (ReplacesSubtree stays true), but the failed + // attachment must be listed in SubtreeKeep so the sweep preserves its good + // previously-synced copy instead of deleting it with nothing to replace it. + if !main.ReplacesSubtree { + t.Error("main.ReplacesSubtree must stay true; the failed child is preserved via SubtreeKeep, not by suppressing the whole sweep") + } + failedChildID := nodeToken + "#file#" + attToken + if !slices.Contains(main.SubtreeKeep, failedChildID) { + t.Errorf("SubtreeKeep must contain the failed attachment %q so its prior copy is preserved, got %+v", + failedChildID, main.SubtreeKeep) + } + if errItem == nil { + t.Fatal("attachment error item missing") + } + if len(errItem.Content) != 0 { + t.Errorf("attachment error item must carry no content, got %d bytes", len(errItem.Content)) + } + if errItem.Metadata["error"] == "" { + t.Error("attachment error item must carry error metadata for UI visibility") + } +} + +// TestFetchDocxWithBlocks_EmbeddedImage verifies that embedded images are emitted +// as standalone sub-items (whose bytes flow into the VLM OCR pipeline) only when +// the KB has multimodal enabled, but their external_id is ALWAYS kept in +// SubtreeKeep so toggling VLM off later does not sweep previously OCR'd images. +func TestFetchDocxWithBlocks_EmbeddedImage(t *testing.T) { + const ( + nodeToken = "nt-docx-img" + objToken = "obj-docx-img" + imgToken = "media-img-1" + ) + // A valid PNG signature + padding so http.DetectContentType returns image/png + // and the bytes exceed minAttachmentBytes. + pngBytes := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), minAttachmentBytes)...) + + mux := http.NewServeMux() + mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, tokenResponse{apiResponse: apiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200}) + }) + blocksPath := "/open-apis/docx/v1/documents/" + objToken + "/blocks" + mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, docxBlocksResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []docxBlock `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{ + Items: []docxBlock{ + {BlockID: "b1", BlockType: blockTypePage}, + {BlockID: "b2", BlockType: blockTypeText, Text: &blockText{ + Elements: []textElement{{TextRun: &struct { + Content string `json:"content"` + }{Content: "Hello"}}}, + }}, + {BlockID: "b3", BlockType: blockTypeImage, Image: &struct { + Token string `json:"token"` + }{Token: imgToken}}, + }, + }, + }) + }) + mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/download") { + _, _ = w.Write(pngBytes) + return + } + http.NotFound(w, r) + }) + ts := httptest.NewServer(mux) + defer ts.Close() + + cfg := &Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL} + conn := NewConnector(RegionFeishu) + ctx := context.Background() + client := NewClient(cfg) + node := wikiNode{NodeToken: nodeToken, ObjToken: objToken, ObjType: "docx", Title: "Doc With Image", NodeEditTime: "1711468800"} + baseMeta := map[string]string{"node_token": nodeToken, "channel": types.ChannelFeishu} + imgChildID := nodeToken + "#image#" + imgToken + + // multimodal ON → image emitted as a sub-item and kept. + items, err := conn.fetchDocxWithBlocks(ctx, client, node, "space1:"+nodeToken, parseFeishuTimestamp("1711468800"), baseMeta, true) + if err != nil { + t.Fatalf("fetchDocxWithBlocks (multimodal on): %v", err) + } + var main, img *types.FetchedItem + for _, it := range items { + switch it.ExternalID { + case nodeToken: + main = it + case imgChildID: + img = it + } + } + if main == nil { + t.Fatal("main doc item missing") + } + if img == nil { + t.Fatalf("embedded image sub-item missing; got %+v", items) + } + if !strings.HasSuffix(img.FileName, ".png") { + t.Errorf("image FileName = %q, want a .png extension", img.FileName) + } + if img.Metadata["embedded_image"] != "true" { + t.Errorf("image Metadata[embedded_image] = %q, want true", img.Metadata["embedded_image"]) + } + if img.Metadata["attachment"] == "true" { + t.Error("an embedded image must not be marked as a file attachment") + } + if len(img.Content) != len(pngBytes) { + t.Errorf("image Content = %d bytes, want %d", len(img.Content), len(pngBytes)) + } + if !slices.Contains(main.SubtreeKeep, imgChildID) { + t.Errorf("SubtreeKeep must contain image %q, got %+v", imgChildID, main.SubtreeKeep) + } + + // multimodal OFF → no image sub-item, but the id is still kept (not swept). + itemsOff, err := conn.fetchDocxWithBlocks(ctx, client, node, "space1:"+nodeToken, parseFeishuTimestamp("1711468800"), baseMeta, false) + if err != nil { + t.Fatalf("fetchDocxWithBlocks (multimodal off): %v", err) + } + var mainOff *types.FetchedItem + for _, it := range itemsOff { + if it.ExternalID == imgChildID { + t.Errorf("multimodal off must NOT emit an image sub-item, got %+v", it) + } + if it.ExternalID == nodeToken { + mainOff = it + } + } + if mainOff == nil { + t.Fatal("main doc item missing (multimodal off)") + } + if !slices.Contains(mainOff.SubtreeKeep, imgChildID) { + t.Errorf("SubtreeKeep must contain image %q even when multimodal off (so it isn't swept), got %+v", + imgChildID, mainOff.SubtreeKeep) + } +} + +// TestFetchDocxWithBlocks_ImageDownloadFailure verifies that a failed image +// download (a genuine fetch failure — revoked token, permission gap, transient +// error) surfaces a visible error sub-item exactly like a failed attachment +// download, rather than being silently dropped to a server log. The image is +// still kept in SubtreeKeep so any prior OCR'd copy is preserved. +func TestFetchDocxWithBlocks_ImageDownloadFailure(t *testing.T) { + const ( + nodeToken = "nt-docx-img-fail" + objToken = "obj-docx-img-fail" + imgToken = "media-img-bad" + ) + mux := http.NewServeMux() + mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, tokenResponse{apiResponse: apiResponse{Code: 0}, TenantAccessToken: "fake-token", Expire: 7200}) + }) + blocksPath := "/open-apis/docx/v1/documents/" + objToken + "/blocks" + mux.HandleFunc(blocksPath, func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, docxBlocksResponse{ + apiResponse: apiResponse{Code: 0}, + Data: struct { + Items []docxBlock `json:"items"` + HasMore bool `json:"has_more"` + PageToken string `json:"page_token"` + }{ + Items: []docxBlock{ + {BlockID: "b1", BlockType: blockTypePage}, + {BlockID: "b2", BlockType: blockTypeImage, Image: &struct { + Token string `json:"token"` + }{Token: imgToken}}, + }, + }, + }) + }) + // Media download always fails. + mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "boom", http.StatusInternalServerError) + }) + ts := httptest.NewServer(mux) + defer ts.Close() + + cfg := &Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL} + conn := NewConnector(RegionFeishu) + ctx := context.Background() + client := NewClient(cfg) + node := wikiNode{NodeToken: nodeToken, ObjToken: objToken, ObjType: "docx", Title: "Doc With Bad Image", NodeEditTime: "1711468800"} + baseMeta := map[string]string{"node_token": nodeToken, "channel": types.ChannelFeishu} + imgChildID := nodeToken + "#image#" + imgToken + + // multimodal ON → the download is attempted and fails → a visible error item. + items, err := conn.fetchDocxWithBlocks(ctx, client, node, "space1:"+nodeToken, parseFeishuTimestamp("1711468800"), baseMeta, true) + if err != nil { + t.Fatalf("a failed image download must not fail the whole node, got error: %v", err) + } + var main, errItem *types.FetchedItem + for _, it := range items { + switch it.ExternalID { + case nodeToken: + main = it + case imgChildID: + errItem = it + } + } + if main == nil { + t.Fatal("main doc item missing") + } + if errItem == nil { + t.Fatalf("failed image download must emit a visible error sub-item, got %+v", items) + } + if len(errItem.Content) != 0 { + t.Errorf("image error item must carry no content, got %d bytes", len(errItem.Content)) + } + if errItem.Metadata["error"] == "" { + t.Error("image error item must carry error metadata for UI visibility") + } + if errItem.Metadata["embedded_image"] != "true" { + t.Errorf("image error item must stay tagged embedded_image=true, got %q", errItem.Metadata["embedded_image"]) + } + if !slices.Contains(main.SubtreeKeep, imgChildID) { + t.Errorf("SubtreeKeep must contain the failed image %q so its prior copy is preserved, got %+v", + imgChildID, main.SubtreeKeep) + } + + // multimodal OFF → the download is never attempted, so no error item, but the + // id is still kept (not swept). + itemsOff, err := conn.fetchDocxWithBlocks(ctx, client, node, "space1:"+nodeToken, parseFeishuTimestamp("1711468800"), baseMeta, false) + if err != nil { + t.Fatalf("fetchDocxWithBlocks (multimodal off): %v", err) + } + for _, it := range itemsOff { + if it.ExternalID == imgChildID { + t.Errorf("multimodal off must NOT attempt the image download or emit an item, got %+v", it) + } + } +} + +// TestFetchDocxWithBlocks_NonWhitelistedExtNotPromoted verifies that a file block +// whose extension is not in the parseable-attachment whitelist (e.g. .png) is NOT +// promoted to a sub-item, but its inline reference IS present in the main document. +func TestFetchDocxWithBlocks_NonWhitelistedExtNotPromoted(t *testing.T) { + const ( + nodeToken = "nt-docx-png" + objToken = "obj-docx-png" + attToken = "ft-icon" + attName = "icon.png" + ) + // Content size well above minAttachmentBytes — the filter must be extension, not size. + attContent := bytes.Repeat([]byte("x"), minAttachmentBytes+100) + + nodes := []wikiNode{{ + NodeToken: nodeToken, + ObjToken: objToken, + ObjType: "docx", + Title: "Doc With PNG", + NodeEditTime: "1711468800", + }} + ts, cfg := fakeFeishuWithBlocks(nodes, objToken, attToken, attName, attContent) + defer ts.Close() + + conn := NewConnector(RegionFeishu) + items, err := conn.FetchAll(context.Background(), makeConfig(cfg, []string{"space1"}), []string{"space1"}) + if err != nil { + t.Fatalf("FetchAll() error: %v", err) + } + + // Only the main doc — no sub-item for a non-parseable extension. + if len(items) != 1 { + t.Fatalf("want 1 item (main doc only, .png not promoted), got %d: %+v", len(items), items) + } + mainContent := string(items[0].Content) + if !strings.Contains(mainContent, "📎 附件:icon.png") { + t.Errorf("main doc missing inline reference for icon.png; got:\n%s", mainContent) + } +} + +// TestFetchDocxWithBlocks_WhitelistedTinyAttachmentNotPromoted verifies that a +// whitelisted-extension file block whose download is smaller than minAttachmentBytes +// is NOT promoted to a sub-item, but its inline reference IS present in the main doc. +func TestFetchDocxWithBlocks_WhitelistedTinyAttachmentNotPromoted(t *testing.T) { + const ( + nodeToken = "nt-docx-tiny" + objToken = "obj-docx-tiny" + attToken = "ft-tiny-pdf" + attName = "tiny.pdf" + ) + // Content is well below minAttachmentBytes (100 bytes vs 2048 threshold). + attContent := bytes.Repeat([]byte("x"), 100) + + nodes := []wikiNode{{ + NodeToken: nodeToken, + ObjToken: objToken, + ObjType: "docx", + Title: "Doc With Tiny PDF", + NodeEditTime: "1711468800", + }} + ts, cfg := fakeFeishuWithBlocks(nodes, objToken, attToken, attName, attContent) + defer ts.Close() + + conn := NewConnector(RegionFeishu) + items, err := conn.FetchAll(context.Background(), makeConfig(cfg, []string{"space1"}), []string{"space1"}) + if err != nil { + t.Fatalf("FetchAll() error: %v", err) + } + + // Only the main doc — no sub-item for a file below the size threshold. + if len(items) != 1 { + t.Fatalf("want 1 item (main doc only, tiny .pdf not promoted), got %d: %+v", len(items), items) + } + mainContent := string(items[0].Content) + if !strings.Contains(mainContent, "📎 附件:tiny.pdf") { + t.Errorf("main doc missing inline reference for tiny.pdf; got:\n%s", mainContent) + } +} + // ────────────────────────────────────────────────────────────────────── // Feishu cursor serialization // ────────────────────────────────────────────────────────────────────── @@ -1287,3 +1891,37 @@ func TestFeishuCursorRoundTrip(t *testing.T) { t.Errorf("restored nt2 = %q, want 200", restored.SpaceNodeTimes["space1"]["nt2"]) } } + +// TestSupportedImageExt covers every arm of the sniff table: the png/jpg/gif +// formats WeKnora accepts (aligned with isValidFileType's image set), and the +// unsupported case which must return ok=false while still surfacing the detected +// content type so the caller can log it without re-sniffing. +func TestSupportedImageExt(t *testing.T) { + cases := []struct { + name string + data []byte + wantExt string + wantCT string + wantOK bool + }{ + {"png", []byte("\x89PNG\r\n\x1a\nrest"), ".png", "image/png", true}, + {"jpeg", []byte("\xFF\xD8\xFF\xE0\x00\x10JFIF"), ".jpg", "image/jpeg", true}, + {"gif", []byte("GIF89a\x01\x00\x01\x00"), ".gif", "image/gif", true}, + {"webp_unsupported", append([]byte("RIFF\x00\x00\x00\x00WEBPVP8 "), make([]byte, 8)...), "", "image/webp", false}, + {"text_unsupported", []byte("just some plain text, not an image at all"), "", "text/plain; charset=utf-8", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ext, ct, ok := supportedImageExt(tc.data) + if ok != tc.wantOK { + t.Fatalf("ok = %v, want %v", ok, tc.wantOK) + } + if ext != tc.wantExt { + t.Errorf("ext = %q, want %q", ext, tc.wantExt) + } + if ct != tc.wantCT { + t.Errorf("contentType = %q, want %q (must be returned even when !ok)", ct, tc.wantCT) + } + }) + } +} diff --git a/internal/datasource/connector/feishu/markdown.go b/internal/datasource/connector/feishu/markdown.go new file mode 100644 index 00000000..66964d5a --- /dev/null +++ b/internal/datasource/connector/feishu/markdown.go @@ -0,0 +1,320 @@ +package feishu + +import ( + "context" + "fmt" + "strings" +) + +// sheetReader is the subset of *Client that blocksToMarkdown needs, so the +// converter can be unit-tested with a fake or nil client. +type sheetReader interface { + ReadSheetRange(ctx context.Context, embedToken string) ([][]string, bool, error) + ReadBitableRecords(ctx context.Context, embedToken string) ([][]string, bool, error) +} + +// pendingAttachment is an embedded file block awaiting a download decision by +// the connector (whitelist/size filtering happens there, not here). +type pendingAttachment struct { + FileToken string + Name string +} + +// blocksToMarkdown renders a flat docx block array to Markdown, inlining +// embedded spreadsheet/bitable tables (Task 5) and collecting downloadable +// attachments. client may be nil when the block set has no downdrill blocks. +func blocksToMarkdown(ctx context.Context, client sheetReader, blocks []docxBlock) ([]byte, []pendingAttachment, error) { + byID := make(map[string]docxBlock, len(blocks)) + for _, b := range blocks { + byID[b.BlockID] = b + } + // Blocks nested inside a native table (its cells and their content blocks) + // are rendered by renderNativeTable. Mark them so the flat loop below does + // not also emit them as stray top-level paragraphs. + consumed := tableDescendants(blocks, byID) + + var sb strings.Builder + var atts []pendingAttachment + for _, b := range blocks { + if consumed[b.BlockID] { + continue + } + switch b.BlockType { + case blockTypePage: + continue // root container, no text of its own + case blockTypeText: + writePara(&sb, plainText(textBearingField(b))) + case blockTypeBullet: + writePara(&sb, "- "+plainText(textBearingField(b))) + case blockTypeOrdered: + writePara(&sb, "1. "+plainText(textBearingField(b))) + case blockTypeCode: + writePara(&sb, "```\n"+plainText(textBearingField(b))+"\n```") + case blockTypeQuote: + writePara(&sb, "> "+plainText(textBearingField(b))) + case blockTypeDivider: + writePara(&sb, "---") + case blockTypeTable: + writePara(&sb, renderNativeTable(b, byID)) + case blockTypeTableCell: + continue // rendered by its parent table (also covered by `consumed`) + case blockTypeSheet: + if b.Sheet != nil { + writePara(&sb, inlineTable(ctx, client, b.Sheet.Token, "sheet")) + } + case blockTypeBitable: + if b.Bitable != nil { + writePara(&sb, inlineTable(ctx, client, b.Bitable.Token, "bitable")) + } + case blockTypeImage: + // Emit a token-free placeholder: images carry no retrievable text, and + // leaking the internal media token would pollute embeddings. A neutral + // marker preserves surrounding context (e.g. "如下图所示"). + writePara(&sb, "![图片]()") + case blockTypeTodo: + if t := plainText(textBearingField(b)); t != "" { + writePara(&sb, "- [ ] "+t) + } + case blockTypeCallout: + // Callout is a container; its body is usually in child blocks (rendered + // separately). Emit its own text only if it carries direct inline text, + // so the container case is a safe no-op. + if t := plainText(textBearingField(b)); t != "" { + writePara(&sb, "> "+t) + } + case blockTypeFile: + if b.File != nil { + name := b.File.Name + if name == "" { + name = b.File.Token + } + writePara(&sb, "📎 附件:"+name) + atts = append(atts, pendingAttachment{FileToken: b.File.Token, Name: b.File.Name}) + } + default: + if b.BlockType >= blockTypeHeading1 && b.BlockType <= blockTypeHeading9 { + level := b.BlockType - blockTypeHeading1 + 1 + writePara(&sb, strings.Repeat("#", level)+" "+plainText(textBearingField(b))) + } + } + } + + out := strings.TrimRight(sb.String(), "\n") + if out != "" { + out += "\n" + } + return []byte(out), atts, nil +} + +// writePara appends a block of text followed by a blank line; empty text is skipped. +func writePara(sb *strings.Builder, s string) { + if s == "" { + return + } + sb.WriteString(s) + sb.WriteString("\n\n") +} + +// plainText concatenates the text runs of a text-bearing block. +func plainText(bt *blockText) string { + if bt == nil { + return "" + } + var sb strings.Builder + for _, e := range bt.Elements { + if e.TextRun != nil { + sb.WriteString(e.TextRun.Content) + } + } + return sb.String() +} + +// headingText returns the heading field for the block's level, or Text as fallback. +func headingText(b docxBlock) *blockText { + fields := []*blockText{ + b.Heading1, b.Heading2, b.Heading3, b.Heading4, b.Heading5, + b.Heading6, b.Heading7, b.Heading8, b.Heading9, + } + if idx := b.BlockType - blockTypeHeading1; idx >= 0 && idx < len(fields) && fields[idx] != nil { + return fields[idx] + } + return b.Text +} + +// tableDescendants returns the set of block IDs that belong to a native table — +// every cell listed in a table block plus everything reachable through those +// cells' Children. blocksToMarkdown skips these so table content is emitted only +// by the table renderer, never a second time as loose paragraphs. +func tableDescendants(blocks []docxBlock, byID map[string]docxBlock) map[string]bool { + consumed := make(map[string]bool) + var mark func(id string) + mark = func(id string) { + b, ok := byID[id] + if !ok || consumed[id] { + return + } + // Attachment/media blocks nested in a cell must still be collected (and + // their reference emitted) by the main loop — the table renderer only + // extracts text — so do not consume them, only their text structure. + if b.BlockType == blockTypeFile || b.BlockType == blockTypeImage { + return + } + consumed[id] = true + for _, c := range b.Children { + mark(c) + } + } + for _, b := range blocks { + // Only consume cells of tables we will actually render. A table that + // renderNativeTable would bail on (missing property / zero columns) must + // NOT have its cells consumed, or their text would be dropped entirely — + // leave them for the flat loop to emit as loose paragraphs instead. + if b.BlockType == blockTypeTable && tableRenderable(b) { + for _, cid := range b.Table.Cells { + mark(cid) + } + } + } + return consumed +} + +// tableRenderable reports whether a native table block carries enough structure +// (a column count) for renderNativeTable to produce a Markdown table. It is the +// single predicate shared by the consume pass and the render pass so the two +// never disagree about which tables are handled by the table renderer. +func tableRenderable(b docxBlock) bool { + return b.Table != nil && b.Table.Property != nil && b.Table.Property.ColumnSize > 0 +} + +// textBearingField returns the inline-text payload for whichever type-named +// field a block populates (docx stores a block's text in a field named after +// its type), so cell content of any text-like type can be extracted uniformly. +func textBearingField(b docxBlock) *blockText { + switch b.BlockType { + case blockTypeText: + return b.Text + case blockTypeBullet: + return b.Bullet + case blockTypeOrdered: + return b.Ordered + case blockTypeCode: + return b.Code + case blockTypeQuote: + return b.Quote + case blockTypeTodo: + return b.Todo + case blockTypeCallout: + return b.Callout + } + if b.BlockType >= blockTypeHeading1 && b.BlockType <= blockTypeHeading9 { + return headingText(b) + } + return b.Text +} + +// cellText renders a native table cell to a single string. A Feishu table_cell +// (block_type 32) is a container: its text lives in child blocks, not on the +// cell itself, so we concatenate the text of each child block. +func cellText(cell docxBlock, byID map[string]docxBlock) string { + var parts []string + for _, childID := range cell.Children { + if t := plainText(textBearingField(byID[childID])); t != "" { + parts = append(parts, t) + } + } + return strings.Join(parts, " ") +} + +// renderNativeTable renders a native docx table block into a Markdown table. +func renderNativeTable(b docxBlock, byID map[string]docxBlock) string { + if !tableRenderable(b) { + return "" + } + cols := b.Table.Property.ColumnSize + var cells []string + for _, cid := range b.Table.Cells { + cells = append(cells, cellText(byID[cid], byID)) + } + var rows [][]string + for i := 0; i < len(cells); i += cols { + end := i + cols + if end > len(cells) { + end = len(cells) + } + rows = append(rows, cells[i:end]) + } + return markdownTable(rows) +} + +// markdownTable renders a [][]string (first row = header) as a GFM table. +func markdownTable(rows [][]string) string { + // A zero-column header (an embedded sheet/bitable with no columns) would emit + // a header line of "| |" and a separator of just "|" — malformed GFM. Render + // nothing instead. + if len(rows) == 0 || len(rows[0]) == 0 { + return "" + } + var sb strings.Builder + cols := len(rows[0]) + sb.WriteString("| " + strings.Join(escapePipes(rows[0]), " | ") + " |\n") + sb.WriteString("|" + strings.Repeat(" --- |", cols) + "\n") + for _, r := range rows[1:] { + // Ragged data: a row wider than the header would emit more cells than the + // header/separator declare, producing a malformed GFM table. Clamp to the + // header width (truncate overflow, pad shortfall). + if len(r) > cols { + r = r[:cols] + } + for len(r) < cols { + r = append(r, "") + } + sb.WriteString("| " + strings.Join(escapePipes(r), " | ") + " |\n") + } + return strings.TrimRight(sb.String(), "\n") +} + +// escapePipes makes cell values safe for a single Markdown table row. +func escapePipes(row []string) []string { + out := make([]string, len(row)) + for i, c := range row { + out[i] = strings.ReplaceAll(strings.ReplaceAll(c, "\n", " "), "|", "\\|") + } + return out +} + +// inlineTable reads an embedded sheet/bitable and renders it as a Markdown +// table. Read/permission errors degrade to an inline note rather than failing +// the whole document (partial content beats no content). A reader-reported +// truncation appends a note. +func inlineTable(ctx context.Context, client sheetReader, token, kind string) string { + if client == nil { + return "" + } + var ( + rows [][]string + truncated bool + err error + noun string + ) + if kind == "sheet" { + rows, truncated, err = client.ReadSheetRange(ctx, token) + noun = "内嵌电子表格" + } else { + rows, truncated, err = client.ReadBitableRecords(ctx, token) + noun = "内嵌多维表格" + } + if err != nil { + return fmt.Sprintf("> [无法读取%s]", noun) + } + // markdownTable returns "" when there is nothing renderable (no rows, or a + // header with no columns). Skip the truncation note too in that case, since it + // would otherwise dangle without a table above it. + table := markdownTable(rows) + if table == "" { + return "" + } + if truncated { + table += fmt.Sprintf("\n\n> 表格已截断(仅显示前 %d 行)", maxTableRows) + } + return table +} diff --git a/internal/datasource/connector/feishu/markdown_test.go b/internal/datasource/connector/feishu/markdown_test.go new file mode 100644 index 00000000..ed29d406 --- /dev/null +++ b/internal/datasource/connector/feishu/markdown_test.go @@ -0,0 +1,317 @@ +package feishu + +import ( + "context" + "fmt" + "strings" + "testing" +) + +// txt builds a text-bearing blockText from plain content. +func txt(s string) *blockText { + return &blockText{Elements: []textElement{{TextRun: &struct { + Content string `json:"content"` + }{Content: s}}}} +} + +type fakeReader struct { + sheet [][]string + sheetTruncated bool + sheetErr error + bitable [][]string + bitableTruncated bool + bitableErr error +} + +func (f fakeReader) ReadSheetRange(_ context.Context, _ string) ([][]string, bool, error) { + return f.sheet, f.sheetTruncated, f.sheetErr +} +func (f fakeReader) ReadBitableRecords(_ context.Context, _ string) ([][]string, bool, error) { + return f.bitable, f.bitableTruncated, f.bitableErr +} + +func TestBlocksToMarkdown_EmbeddedSheetAndFile(t *testing.T) { + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + {BlockID: "s", BlockType: blockTypeSheet, Sheet: &struct { + Token string `json:"token"` + }{Token: "sht_a_0"}}, + {BlockID: "img", BlockType: blockTypeImage, Image: &struct { + Token string `json:"token"` + }{Token: "img_t"}}, + {BlockID: "f", BlockType: blockTypeFile, File: &struct { + Token string `json:"token"` + Name string `json:"name"` + }{Token: "file_t", Name: "报表.pdf"}}, + } + fr := fakeReader{sheet: [][]string{{"名称", "数量"}, {"苹果", "3"}}} + md, atts, err := blocksToMarkdown(context.Background(), fr, blocks) + if err != nil { + t.Fatalf("err: %v", err) + } + if !strings.Contains(string(md), "| 名称 | 数量 |") || !strings.Contains(string(md), "| 苹果 | 3 |") { + t.Errorf("sheet not inlined:\n%s", md) + } + if !strings.Contains(string(md), "![图片]()") { + t.Errorf("image placeholder missing:\n%s", md) + } + if strings.Contains(string(md), "feishu-media") { + t.Errorf("internal media token leaked into markdown:\n%s", md) + } + if len(atts) != 1 || atts[0].FileToken != "file_t" || atts[0].Name != "报表.pdf" { + t.Errorf("attachments = %+v", atts) + } + if !strings.Contains(string(md), "📎 附件:报表.pdf") { + t.Errorf("attachment inline reference missing:\n%s", md) + } +} + +func TestBlocksToMarkdown_SheetTruncatedNote(t *testing.T) { + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + {BlockID: "s", BlockType: blockTypeSheet, Sheet: &struct { + Token string `json:"token"` + }{Token: "sht_a_0"}}, + } + fr := fakeReader{sheet: [][]string{{"h"}, {"1"}}, sheetTruncated: true} + md, _, err := blocksToMarkdown(context.Background(), fr, blocks) + if err != nil { + t.Fatalf("err: %v", err) + } + if !strings.Contains(string(md), "表格已截断") { + t.Errorf("want truncation note, got:\n%s", md) + } +} + +func TestBlocksToMarkdown_SheetPermissionDegrades(t *testing.T) { + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + {BlockID: "s", BlockType: blockTypeSheet, Sheet: &struct { + Token string `json:"token"` + }{Token: "sht_a_0"}}, + } + fr := fakeReader{sheetErr: fmt.Errorf("code=99991672 permission denied")} + md, _, err := blocksToMarkdown(context.Background(), fr, blocks) + if err != nil { + t.Fatalf("should not fail on permission error, got %v", err) + } + if !strings.Contains(string(md), "无法读取内嵌电子表格") { + t.Errorf("want degraded placeholder, got:\n%s", md) + } +} + +func TestBlocksToMarkdown_BitableInlinedAndDegrades(t *testing.T) { + mk := func(fr fakeReader) string { + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + {BlockID: "bt", BlockType: blockTypeBitable, Bitable: &struct { + Token string `json:"token"` + }{Token: "bascabc_tblxyz"}}, + } + md, _, err := blocksToMarkdown(context.Background(), fr, blocks) + if err != nil { + t.Fatalf("err: %v", err) + } + return string(md) + } + + inlined := mk(fakeReader{bitable: [][]string{{"任务", "状态"}, {"写文档", "进行中"}}}) + if !strings.Contains(inlined, "| 任务 | 状态 |") || !strings.Contains(inlined, "| 写文档 | 进行中 |") { + t.Errorf("bitable not inlined:\n%s", inlined) + } + + degraded := mk(fakeReader{bitableErr: fmt.Errorf("code=99991672 permission denied")}) + if !strings.Contains(degraded, "无法读取内嵌多维表格") { + t.Errorf("want bitable degradation note, got:\n%s", degraded) + } +} + +func TestBlocksToMarkdown_NativeTableFromCellChildren(t *testing.T) { + // Real Feishu shape: a table_cell (block_type 32) is a container whose text + // lives in child text blocks, not on the cell. The renderer must read cell + // text from those children AND must not also emit them as loose paragraphs. + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + tableBlk("t", 2, "c1", "c2", "c3", "c4"), + cellBlk("c1"), cellBlk("c2"), cellBlk("c3"), cellBlk("c4"), + cellTextBlk("c1", "姓名"), cellTextBlk("c2", "分数"), + cellTextBlk("c3", "张三"), cellTextBlk("c4", "95"), + } + md, _, err := blocksToMarkdown(context.Background(), nil, blocks) + if err != nil { + t.Fatalf("err: %v", err) + } + s := string(md) + if !strings.Contains(s, "| 姓名 | 分数 |") || !strings.Contains(s, "| 张三 | 95 |") { + t.Errorf("native table not rendered from cell children:\n%s", s) + } + // Cell text must appear ONLY inside the table, never as a stray paragraph. + if n := strings.Count(s, "姓名"); n != 1 { + t.Errorf("cell text leaked outside the table (count=%d, want 1):\n%s", n, s) + } +} + +func TestBlocksToMarkdown_AttachmentInsideTableCellStillCollected(t *testing.T) { + // A file block nested inside a table cell must still be collected as an + // attachment — the table "consumed" set marks a cell's text structure but + // must NOT swallow attachment/media blocks, or embedded files silently vanish. + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + tableBlk("t", 1, "c1"), + {BlockID: "c1", BlockType: blockTypeTableCell, Children: []string{"f1"}}, + {BlockID: "f1", BlockType: blockTypeFile, File: &struct { + Token string `json:"token"` + Name string `json:"name"` + }{Token: "tok-in-cell", Name: "内嵌.pdf"}}, + } + _, atts, err := blocksToMarkdown(context.Background(), nil, blocks) + if err != nil { + t.Fatalf("err: %v", err) + } + if len(atts) != 1 || atts[0].FileToken != "tok-in-cell" { + t.Fatalf("attachment nested in a table cell was not collected: %+v", atts) + } +} + +func TestMarkdownTable_RaggedRowClampedToHeader(t *testing.T) { + // Header declares 2 columns; a data row with 4 cells (trailing populated + // cells beyond the header range) must be clamped to 2, or the emitted table + // has more body cells than header/separator columns → malformed GFM. + rows := [][]string{ + {"名称", "数量"}, + {"苹果", "3", "多余1", "多余2"}, + } + out := markdownTable(rows) + lines := strings.Split(out, "\n") + if len(lines) != 3 { + t.Fatalf("want 3 lines (header, separator, 1 row), got %d:\n%s", len(lines), out) + } + // Every row must have the same pipe count as the 2-column header. + want := strings.Count(lines[0], "|") + for i, ln := range lines { + if got := strings.Count(ln, "|"); got != want { + t.Errorf("line %d %q has %d pipes, want %d (ragged row not clamped)", i, ln, got, want) + } + } + if strings.Contains(out, "多余") { + t.Errorf("overflow cells must be dropped, got:\n%s", out) + } +} + +func TestMarkdownTable_ZeroColumnRendersNothing(t *testing.T) { + // An embedded sheet/bitable with a header row but no columns (e.g. a bitable + // whose fields were all deleted) yields rows == [][]string{{}}. len(rows)==1 + // passes a naive empty guard, but cols==0 would emit a malformed GFM table + // ("| |" header + a bare "|" separator). It must render nothing instead. + for _, rows := range [][][]string{ + {{}}, // one empty header row, no data + {{}, {}, {}}, // empty header + empty data rows + } { + out := markdownTable(rows) + if out != "" { + t.Errorf("zero-column table must render nothing, got %q for rows=%+v", out, rows) + } + } +} + +func TestBlocksToMarkdown_UnrenderableTablePreservesCellText(t *testing.T) { + // A native table block with no column property (Table!=nil, Property==nil) + // cannot be rendered as a Markdown table. Its cells must NOT be consumed, so + // their text still reaches the output as loose paragraphs rather than + // vanishing entirely. + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + // tableBlk sets Property (renderable); here we want an UNrenderable one. + {BlockID: "t", BlockType: blockTypeTable, Table: &struct { + Cells []string `json:"cells"` + Property *struct { + ColumnSize int `json:"column_size"` + } `json:"property"` + }{Cells: []string{"c1"}}}, + {BlockID: "c1", BlockType: blockTypeTableCell, Children: []string{"c1_txt"}}, + cellTextBlk("c1", "重要内容"), + } + md, _, err := blocksToMarkdown(context.Background(), nil, blocks) + if err != nil { + t.Fatalf("err: %v", err) + } + if !strings.Contains(string(md), "重要内容") { + t.Errorf("cell text of an unrenderable table was dropped:\n%s", md) + } +} + +func TestBlocksToMarkdown_TextConstructs(t *testing.T) { + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage, Children: []string{"h", "p", "b"}}, + {BlockID: "h", BlockType: blockTypeHeading1, Heading1: txt("标题")}, + {BlockID: "p", BlockType: blockTypeText, Text: txt("一段正文")}, + {BlockID: "b", BlockType: blockTypeBullet, Bullet: txt("要点")}, + } + md, atts, err := blocksToMarkdown(context.Background(), nil, blocks) + if err != nil { + t.Fatalf("blocksToMarkdown: %v", err) + } + if len(atts) != 0 { + t.Errorf("want 0 attachments, got %d", len(atts)) + } + want := "# 标题\n\n一段正文\n\n- 要点\n" + if string(md) != want { + t.Errorf("md =\n%q\nwant\n%q", md, want) + } +} + +func TestBlocksToMarkdown_BlankDocRendersEmpty(t *testing.T) { + // A page with no renderable children (or only empty-text/container blocks) + // must render to empty Markdown. fetchDocxWithBlocks relies on this: an empty + // render triggers the export fallback instead of emitting a content-less main + // item that would wrongly ingest the login-gated wiki URL. Any File/Image + // block writes a placeholder, so a truly empty render also implies no + // attachment/image downdrill is lost by that fallback. + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage, Children: []string{"p"}}, + {BlockID: "p", BlockType: blockTypeText, Text: txt("")}, + } + md, atts, err := blocksToMarkdown(context.Background(), nil, blocks) + if err != nil { + t.Fatalf("blocksToMarkdown: %v", err) + } + if strings.TrimSpace(string(md)) != "" { + t.Errorf("blank doc should render empty Markdown, got:\n%q", md) + } + if len(atts) != 0 { + t.Errorf("blank doc should collect no attachments, got %d", len(atts)) + } +} + +func TestBlocksToMarkdown_TodoAndCallout(t *testing.T) { + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + {BlockID: "t", BlockType: blockTypeTodo, Todo: txt("买牛奶")}, + {BlockID: "c", BlockType: blockTypeCallout, Callout: txt("注意事项")}, + } + md, _, err := blocksToMarkdown(context.Background(), nil, blocks) + if err != nil { + t.Fatalf("err: %v", err) + } + if !strings.Contains(string(md), "- [ ] 买牛奶") { + t.Errorf("todo not rendered:\n%s", md) + } + if !strings.Contains(string(md), "> 注意事项") { + t.Errorf("callout direct text not rendered:\n%s", md) + } +} + +func TestBlocksToMarkdown_CalloutContainerNoOp(t *testing.T) { + // A callout with no direct text (container form) must emit nothing itself. + blocks := []docxBlock{ + {BlockID: "root", BlockType: blockTypePage}, + {BlockID: "c", BlockType: blockTypeCallout}, + } + md, _, err := blocksToMarkdown(context.Background(), nil, blocks) + if err != nil { + t.Fatalf("err: %v", err) + } + if strings.TrimSpace(string(md)) != "" { + t.Errorf("empty callout should emit nothing, got:\n%q", md) + } +} diff --git a/internal/datasource/connector/feishu/types.go b/internal/datasource/connector/feishu/types.go index 72e1a089..f5782307 100644 --- a/internal/datasource/connector/feishu/types.go +++ b/internal/datasource/connector/feishu/types.go @@ -24,6 +24,30 @@ type Config struct { // Base URL for Feishu API (default: https://open.feishu.cn) // Use https://open.larksuite.com for Lark (international) deployments BaseURL string `json:"base_url,omitempty"` + + // Timezone is the IANA name (e.g. "Asia/Shanghai", "America/New_York") used to + // render bitable date cells. Feishu stores a date as a UTC instant, but the + // calendar date a user sees is that instant in the table's timezone, so + // rendering in UTC shifts the date. Empty defaults to GMT+8, which matches + // Feishu (mainland) tenants; set it for Lark tenants in other zones. + Timezone string `json:"timezone,omitempty"` +} + +// defaultTimezoneOffsetSeconds is GMT+8 (the Feishu mainland default), used when +// no timezone is configured. A fixed zone avoids any dependency on system tzdata, +// which minimal container images may omit. +const defaultTimezoneOffsetSeconds = 8 * 3600 + +// resolveLocation returns the *time.Location used to render bitable date cells. +// An empty name yields a fixed GMT+8 zone (no tzdata dependency); a named zone is +// loaded from the system tz database, falling back to GMT+8 if it is unavailable. +func resolveLocation(name string) *time.Location { + if name != "" { + if loc, err := time.LoadLocation(name); err == nil { + return loc + } + } + return time.FixedZone("GMT+8", defaultTimezoneOffsetSeconds) } // DefaultBaseURL is the default Feishu Open Platform API base URL. diff --git a/internal/types/datasource.go b/internal/types/datasource.go index 8b9f7ed2..242318aa 100644 --- a/internal/types/datasource.go +++ b/internal/types/datasource.go @@ -218,6 +218,14 @@ type DataSourceConfig struct { // Connector-specific configuration Settings map[string]interface{} `json:"settings"` + + // MultimodalEnabled mirrors the target knowledge base's VLM/multimodal + // setting for the current sync run. The service populates it before each fetch + // and it is never persisted (json:"-") — the KB owns the setting. Connectors + // use it to decide whether extracting embedded images for OCR is worthwhile: + // ingesting an image into a KB without VLM is rejected, so image extraction is + // skipped when this is false. + MultimodalEnabled bool `json:"-"` } // HasCredentials reports whether the credentials map carries any value at @@ -323,6 +331,62 @@ type FetchedItem struct { // Source resource ID (e.g., folder ID this document belongs to) SourceResourceID string `json:"source_resource_id"` + + // ReplacesSubtree, when true, tells ingestion to reconcile this item's + // sub-items: after the parent is (re)ingested, every existing knowledge item + // whose external_id starts with SubtreeChildPrefix(ExternalID) that is NOT + // listed in SubtreeKeep is deleted as stale. Used by connectors that fan one + // source node out into a parent document plus attachment/image sub-items + // (e.g. Feishu docx). + // + // PRECONDITIONS the sweep relies on — a connector setting this MUST honour: + // 1. Child external_ids are built with SubtreeChildID, so they share the + // '#' prefix the sweep matches. A child ID without that prefix is never + // swept (silently orphaned); an unrelated item that happens to start + // with the prefix would be wrongly swept. + // 2. The parent is emitted (streaming) / listed (batch) no later than its + // children, and SubtreeKeep already names every still-present child when + // the parent is ingested. The sweep runs at parent-ingest time against + // the PRIOR sync's children, so a child emitted after its parent's sweep + // but absent from SubtreeKeep could be deleted right after being added. + ReplacesSubtree bool `json:"replaces_subtree,omitempty"` + + // SubtreeKeep lists the external_ids of sub-items that still exist in the + // source this sync. Consulted only when ReplacesSubtree is true: the sweep + // preserves these children even if they could not be re-ingested this cycle + // (transient download/parse failure, or an unclassifiable filename), so a + // still-present attachment never loses its previously-synced good copy. Only + // children absent from this set — genuinely removed from the source — are + // swept. + // + // CONTRACT: an empty (or nil) SubtreeKeep with ReplacesSubtree=true means + // "keep nothing" and sweeps EVERY existing child under the prefix. That is + // correct for a node whose attachments all vanished, so a connector setting + // ReplacesSubtree MUST populate SubtreeKeep with every child still present. + // The field is consumed in-process (fetch → ingest, no serialization), so + // nil and empty are equivalent here; the omitempty tag is for API/debug + // exposure only and must not be relied on to distinguish "unset" from "empty". + SubtreeKeep []string `json:"subtree_keep,omitempty"` +} + +// SubtreeChildID builds the external_id of a sub-item fanned out from a parent +// source node — e.g. a docx node's attachment or embedded image. The shape is +// "##". The '#' separator is the contract the +// subtree sweep depends on (see SubtreeChildPrefix and FetchedItem.ReplacesSubtree): +// producers MUST build child IDs with this helper so the producer and the sweep +// consumer share one source of truth. kind is a short discriminator ("file", +// "image"); token is the source system's id for the child and is assumed to be +// '#'-free (Feishu/Notion/etc. tokens are). +func SubtreeChildID(parentExternalID, kind, token string) string { + return parentExternalID + "#" + kind + "#" + token +} + +// SubtreeChildPrefix is the external_id prefix that matches every child of a +// parent node built with SubtreeChildID. The sweep deletes prior children whose +// external_id starts with this prefix and are absent from SubtreeKeep. It must +// move in lockstep with SubtreeChildID: both encode the same '#' separator. +func SubtreeChildPrefix(parentExternalID string) string { + return parentExternalID + "#" } // SyncCursor represents the position/state for incremental sync diff --git a/internal/types/datasource_test.go b/internal/types/datasource_test.go index c703e0cd..65be745a 100644 --- a/internal/types/datasource_test.go +++ b/internal/types/datasource_test.go @@ -141,3 +141,28 @@ func TestDataSourceConfig_HasConfiguredCredentials_RSS(t *testing.T) { assert.False(t, cfg.HasCredentials()) }) } + +// TestSubtreeChildID_MatchesPrefix locks the producer/consumer contract: a child +// ID built by SubtreeChildID must start with the parent's SubtreeChildPrefix +// (what the sweep queries), and the prefix must not match a sibling node whose +// external_id merely shares a leading substring. +func TestSubtreeChildID_MatchesPrefix(t *testing.T) { + parent := "node123" + prefix := SubtreeChildPrefix(parent) + assert.Equal(t, "node123#", prefix) + + fileChild := SubtreeChildID(parent, "file", "tokABC") + imageChild := SubtreeChildID(parent, "image", "tokXYZ") + assert.Equal(t, "node123#file#tokABC", fileChild) + assert.Equal(t, "node123#image#tokXYZ", imageChild) + + // Every child of this node is swept by the prefix. + assert.True(t, strings.HasPrefix(fileChild, prefix)) + assert.True(t, strings.HasPrefix(imageChild, prefix)) + + // A sibling node "node1234" (shares the "node123" leading substring but is a + // different node) must NOT be caught by node123's prefix — the '#' guards it. + sibling := SubtreeChildID("node1234", "file", "tokABC") + assert.False(t, strings.HasPrefix(sibling, prefix), + "sibling node whose id shares a leading substring must not match the prefix") +} diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.go index 111b3603..d7b929a2 100644 --- a/internal/types/interfaces/knowledge.go +++ b/internal/types/interfaces/knowledge.go @@ -269,6 +269,9 @@ type KnowledgeRepository interface { // FindByMetadataKey finds a knowledge item by a key-value pair in the metadata JSON column. // Used by data source sync to locate existing items by external_id. FindByMetadataKey(ctx context.Context, tenantID uint64, kbID string, key string, value string) (*types.Knowledge, error) + // FindByMetadataKeyPrefix finds knowledge items whose metadata[key] starts + // with the given prefix. Used to sweep an external node's attachment sub-items. + FindByMetadataKeyPrefix(ctx context.Context, tenantID uint64, kbID string, key string, prefix string) ([]*types.Knowledge, error) // SearchKnowledgeInScopes searches knowledge items by keyword within the given (tenant_id, kb_id) scopes (own + shared). SearchKnowledgeInScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, int64, error) // ListIDsByTagIDs returns all knowledge IDs that have any of the specified tag IDs (OR semantics). diff --git a/migrations/versioned/000075_knowledge_metadata_external_id_index.down.sql b/migrations/versioned/000075_knowledge_metadata_external_id_index.down.sql new file mode 100644 index 00000000..5599466a --- /dev/null +++ b/migrations/versioned/000075_knowledge_metadata_external_id_index.down.sql @@ -0,0 +1,3 @@ +DO $$ BEGIN RAISE NOTICE '[Migration 000075] Dropping knowledge metadata external_id prefix index...'; END $$; + +DROP INDEX IF EXISTS idx_knowledges_kb_metadata_external_id; diff --git a/migrations/versioned/000075_knowledge_metadata_external_id_index.up.sql b/migrations/versioned/000075_knowledge_metadata_external_id_index.up.sql new file mode 100644 index 00000000..d47c00a3 --- /dev/null +++ b/migrations/versioned/000075_knowledge_metadata_external_id_index.up.sql @@ -0,0 +1,22 @@ +DO $$ BEGIN RAISE NOTICE '[Migration 000075] Adding knowledge metadata external_id prefix index...'; END $$; + +-- Speeds up the datasource subtree sweep (repository FindByMetadataKeyPrefix), +-- which runs on every re-sync of a multi-item source node: +-- WHERE knowledge_base_id = $1 AND deleted_at IS NULL +-- AND metadata->>'external_id' LIKE '#%' ESCAPE '\' +-- +-- The knowledge_base_id equality is already served by idx_knowledges_base_id, +-- but the metadata->>'external_id' LIKE-prefix is only a post-filter (Bitmap +-- Heap Scan recheck). This composite expression index lets the prefix match be +-- served by the index too. Two deliberate choices: +-- * text_pattern_ops — a plain btree opclass is NOT used for LIKE 'x%' in a +-- non-C collation; text_pattern_ops compares raw bytes, so it drives the +-- prefix match regardless of the database collation (this DB even carries a +-- collation-version mismatch, which text_pattern_ops sidesteps entirely). +-- * partial on deleted_at IS NULL — matches the query's own predicate and +-- keeps the index limited to live rows. +-- Non-destructive: index-only, no schema or data change. IF NOT EXISTS makes it +-- idempotent and safe to re-run. +CREATE INDEX IF NOT EXISTS idx_knowledges_kb_metadata_external_id + ON knowledges (knowledge_base_id, (metadata->>'external_id') text_pattern_ops) + WHERE deleted_at IS NULL;